#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Read prepaid credits on the Processor row, not a card beside it (#8145)
ConnorYoh81db97ef0b39
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex ad0b456e49..a38246a5f0 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -7672,13 +7672,6 @@ unit = "PDFs"unitsPending_one = "{{units}} meter unit pending sync from linked instances"unitsPending_other = "{{units}} meter units pending sync from linked instances"-[portal.billing.prepaid]-capSuffix = "of {{total}} prepaid credits"-expires = "Expires {{date}}"-eyebrow = "Prepaid capacity"-note = "Used before metered billing and outside your spend limit."-topUp = "Top up"-[portal.billing.prepaid.buy]back = "Back"cancel = "Cancel"@@ -7701,8 +7694,6 @@ label = "I understand that when my prepaid capacity is used up or expires after[portal.billing.prepaid.deploy][portal.billing.prepaid.offer]-cta = "Review offer"-subtitle = "Prepay a year of PDF processing and get two months free, used before metered billing, outside your spend limit."title = "Get 12 months for the price of 10"[portal.billing.prepaid.pay]@@ -7725,15 +7716,11 @@ downloading = "Preparing…"[portal.billing.prepaid.size]-[portal.billing.prepaid.state]-exhausted = "Used up"-healthy = "Plenty left"-low = "Running low"-[portal.billing.processor]activate = "Switch on the Processor"factFree = "{{used}} of {{allowance}} used"factNoCap = "no limit"+factPrepaid = "{{remaining}} left"freeRemaining = "Free credits remaining"included = "Included in your license"includedRenewal = "{{summary}} · Renews {{date}}"@@ -7742,9 +7729,15 @@ midIncluded = "{{rate}} per credit · {{allowance}} included every month"midIncludedNoRate = "{{allowance}} included every month"midMetered = "{{spend}} metered this cycle"midMeteredUnknown = "Metered this cycle"+midPrepaid = "Prepaid credits, drawn before metered billing"+midPrepaidExpiry = "{{summary}} · Expires {{date}}"noSpendLimit = "No spend limit"paidUsed = "Paid metered usage"percentUsed = "{{pct}}%"+prepaidExhausted = "Used up, metered billing has resumed"+prepaidExpires = "Expires {{date}}"+prepaidRemaining = "Prepaid credits remaining"+prepaidTooltip = "Drawn before metered billing, and outside your spend limit."raiseLimit = "Raise limit"remainingOf = "{{remaining}} of {{total}}"rowName = "Processor"diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.stories.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.stories.tsxindex f14ced89a4..58ef4a4332 100644--- a/frontend/editor/src/portal/components/billing/FreePlanView.stories.tsx+++ b/frontend/editor/src/portal/components/billing/FreePlanView.stories.tsx@@ -4,6 +4,7 @@ import { http, HttpResponse } from "msw";import { BillingScreen } from "@app/billing";import { FreePlanView } from "@portal/components/billing/FreePlanView";import { freeWallet } from "@app/billing/walletFixtures";+import type { Wallet } from "@app/billing/types";import "@portal/components/billing/billing.css";const meta: Meta<typeof FreePlanView> = {@@ -39,23 +40,41 @@ const meta: Meta<typeof FreePlanView> = {export default meta;type Story = StoryObj<typeof FreePlanView>;-function ActivationPreview({ resume = false }: { resume?: boolean }) {+function ActivationPreview({+ resume = false,+ wallet = freeWallet,+}: {+ resume?: boolean;+ wallet?: Wallet;+}) {const [step, setStep] = useState<"choose" | "prepay" | "payg" | null>(resume ? "prepay" : null,);return (<BillingScreen- wallet={freeWallet}+ wallet={wallet}onActivateProcessor={() => setStep(resume ? "prepay" : "choose")}activateLabel={resume ? "View quote" : undefined}extras={- <FreePlanView wallet={freeWallet} step={step} onStepChange={setStep} />+ <FreePlanView wallet={wallet} step={step} onStepChange={setStep} />}/>);}+/** A free team holding a live pool: it reads on the Processor row, not a card below. */+const freeWithPool: Wallet = {+ ...freeWallet,+ billingMode: "prepaid",+ prepaidUnitsRemaining: 78_000,+ prepaidUnitsTotal: 120_000,+ prepaidExpiresAt: "2027-03-01",+};+export const Leader: Story = { render: () => <ActivationPreview /> };+export const PrepaidPool: Story = {+ render: () => <ActivationPreview wallet={freeWithPool} />,+};export const Member: Story = {args: { wallet: { ...freeWallet, role: "member" } },};diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsxindex e50ce5e382..787f447630 100644--- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx+++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx@@ -5,7 +5,6 @@ import type { Wallet } from "@portal/api/billing";import type { SaasCurrency } from "@portal/billing/stripe";import { StripeCheckoutModal } from "@portal/components/billing/StripeCheckoutModal";import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";-import { PrepaidCapacityCard } from "@portal/components/billing/PrepaidCapacityCard";interface Props {wallet: Wallet;@@ -30,7 +29,10 @@ function isSaasCurrency(c: string | null): c is SaasCurrency {return c === "usd" || c === "eur" || c === "gbp";}-/** Owns activation dialogs and prepaid capacity; the host supplies the Processor row action. */+/**+ * Owns the activation dialogs; the host supplies the Processor row action that opens them.+ * Nothing renders here at rest — a held prepaid pool reads on the Processor row itself.+ */export function FreePlanView({wallet,step: controlledStep,@@ -44,32 +46,13 @@ export function FreePlanView({);const step = onStepChange ? (controlledStep ?? null) : ownStep;const setStep = onStepChange ?? setOwnStep;- const [missingTeam, setMissingTeam] = useState<string | null>(null);- const isLeader = wallet.role === "leader";const currency: SaasCurrency = isSaasCurrency(wallet.currency)? wallet.currency: "usd";-- function requireTeam(): boolean {- if (wallet.teamId == null) {- setMissingTeam(- t(- "portal.billing.freePlan.noTeamResolved",- "No team is resolved on your wallet yet — refresh and try again.",- ),- );- return false;- }- setMissingTeam(null);- return true;- }-- // Reopens the bundle modal directly; its resume effect lands on the calculator (quote) or the- // payment step (invoice awaiting payment).- function resumeBundle() {- if (requireTeam()) setStep("prepay");- }+ // Every dialog below needs a team to scope checkout, so an unresolved one would open nothing+ // at all. Saying so beats a door that silently does nothing.+ const missingTeam = step != null && wallet.teamId == null;// Closing any activation modal re-reads the flow state so the CTA reflects a// freshly-minted quote / invoice without a full page reload.@@ -80,15 +63,6 @@ export function FreePlanView({return (<div className="portal-billing__stack">- {/* A live pool is usable without a metered subscription, so it surfaces on the free plan- too. The no-pool upsell face never does. */}- {wallet.prepaidUnitsRemaining > 0 && (- <PrepaidCapacityCard- wallet={wallet}- onBuy={isLeader ? resumeBundle : undefined}- />- )}-{missingTeam && (<Bannertone="warning"@@ -97,7 +71,10 @@ export function FreePlanView({"Couldn't start checkout",)}>- {missingTeam}+ {t(+ "portal.billing.freePlan.noTeamResolved",+ "No team is resolved on your wallet yet — refresh and try again.",+ )}</Banner>)}{wallet.teamId != null && (diff --git a/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.stories.tsx b/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.stories.tsxdeleted file mode 100644index a8a3d64d0d..0000000000--- a/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.stories.tsx+++ /dev/null@@ -1,43 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { PrepaidCapacityCard } from "@portal/components/billing/PrepaidCapacityCard";-import {- subscribedWallet,- prepaidWallet,-} from "@portal/components/billing/walletFixtures";-import "@portal/components/billing/billing.css";--const meta: Meta<typeof PrepaidCapacityCard> = {- title: "Portal/Billing/PrepaidCapacityCard",- component: PrepaidCapacityCard,- parameters: { layout: "padded" },- args: {- wallet: subscribedWallet,- onBuy: () => {},- },-};-export default meta;-type Story = StoryObj<typeof PrepaidCapacityCard>;--/** No bundle yet — the "12 months for the price of 10" offer nudge (leader view). */-export const OfferNudge: Story = {- args: {- wallet: subscribedWallet,- },-};--/** Bundle held, plenty of capacity left — meter + "Top up" action (leader view). */-export const BundleHealthy: Story = {- args: {- wallet: prepaidWallet,- },-};--/** Bundle nearly drawn down — meter crosses into the "Running low" band. */-export const BundleLow: Story = {- args: {- wallet: {- ...prepaidWallet,- prepaidUnitsRemaining: 10_000,- },- },-};diff --git a/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.tsx b/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.tsxdeleted file mode 100644index 6ea4d8d336..0000000000--- a/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.tsx+++ /dev/null@@ -1,109 +0,0 @@-import { useTranslation } from "react-i18next";-import { Button, Card } from "@app/ui";-import { formatPeriodDate, MeterBar, remainingMeter } from "@app/billing";-import type { Wallet } from "@portal/api/billing";--/**- * Prepaid-bundle capacity for the subscribed Processor dashboard, and the entry- * point for buying it. Two faces, driven by whether the team holds a bundle:- *- * - No bundle → a slim "Get 12 months for the price of 10" offer nudge with a- * "Review offer" CTA (the demo's commit-nudge card), shown only when a buyer- * ({@code onBuy}, leader) is present.- * - Bundle held → the capacity meter (drains towards empty as the pool is drawn- * down, so it warns as capacity runs low) plus a "Top up" action for the leader.- *- * Prepaid is consumed before metered billing and sits outside the spend limit, so- * it reads as its own dimension. Buying/topping up opens {@code BundleCheckoutModal}- * via {@code onBuy}; members (no {@code onBuy}) get the display-only meter.- */-export function PrepaidCapacityCard({- wallet,- onBuy,-}: {- wallet: Wallet;- /** Leader-only: opens the purchase/top-up modal. Omit for members. */- onBuy?: () => void;-}) {- const { t } = useTranslation();-- // No bundle yet — show the buy nudge (leader only), else nothing.- if (wallet.prepaidUnitsTotal <= 0) {- if (!onBuy) return null;- return (- <Card padding="loose" className="portal-billing__prepaid-offer">- <div>- <div className="portal-billing__section-title">- {t(- "portal.billing.prepaid.offer.title",- "Get 12 months for the price of 10",- )}- </div>- <p className="portal-billing__prepaid-offer-sub">- {t(- "portal.billing.prepaid.offer.subtitle",- "Prepay a year of PDF processing and get two months free — used before metered billing, outside your spend limit.",- )}- </p>- </div>- <Button variant="secondary" onClick={onBuy}>- {t("portal.billing.prepaid.offer.cta", "Review offer")}- </Button>- </Card>- );- }-- const remaining = wallet.prepaidUnitsRemaining;- const total = wallet.prepaidUnitsTotal;- const { state, pct } = remainingMeter(remaining, total);- const stateLabel =- state === "DEGRADED"- ? t("portal.billing.prepaid.state.exhausted", "Used up")- : state === "WARNED"- ? t("portal.billing.prepaid.state.low", "Running low")- : t("portal.billing.prepaid.state.healthy", "Plenty left");-- return (- <Card padding="loose">- <span className="portal-billing__eyebrow">- {t("portal.billing.prepaid.eyebrow", "Prepaid capacity")}- </span>- <MeterBar- state={state}- pct={pct}- barLabel={t("portal.billing.prepaid.eyebrow", "Prepaid capacity")}- figure={remaining.toLocaleString()}- capSuffix={t(- "portal.billing.prepaid.capSuffix",- "of {{total}} prepaid credits",- {- total: total.toLocaleString(),- },- )}- statusLabel={stateLabel}- meta={- wallet.prepaidExpiresAt ? (- <span>- {t("portal.billing.prepaid.expires", "Expires {{date}}", {- date: formatPeriodDate(wallet.prepaidExpiresAt, { year: true }),- })}- </span>- ) : undefined- }- />- <div className="portal-billing__prepaid-foot">- <p className="portal-billing__section-sub">- {t(- "portal.billing.prepaid.note",- "Used before metered billing and outside your spend limit.",- )}- </p>- {onBuy && (- <Button variant="secondary" size="sm" onClick={onBuy}>- {t("portal.billing.prepaid.topUp", "Top up")}- </Button>- )}- </div>- </Card>- );-}diff --git a/frontend/editor/src/portal/components/billing/SubscribedPlanView.stories.tsx b/frontend/editor/src/portal/components/billing/SubscribedPlanView.stories.tsxindex 1b9c5cc2f8..c2e6e3ba3e 100644--- a/frontend/editor/src/portal/components/billing/SubscribedPlanView.stories.tsx+++ b/frontend/editor/src/portal/components/billing/SubscribedPlanView.stories.tsx@@ -1,10 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { http, HttpResponse } from "msw";import { SubscribedPlanView } from "@portal/components/billing/SubscribedPlanView";-import {- prepaidWallet,- subscribedWallet,-} from "@portal/components/billing/walletFixtures";+import { subscribedWallet } from "@portal/components/billing/walletFixtures";import "@portal/components/billing/billing.css";const card = http.get("*/api/v1/payg/payment-method", () =>@@ -75,10 +72,7 @@ const meta: Meta<typeof SubscribedPlanView> = {export default meta;type Story = StoryObj<typeof SubscribedPlanView>;-/**- * The full Processor-plan dashboard — leader, within cap, no prepaid bundle yet.- * Surfaces the "Get 12 months for the price of 10" prepay nudge ("Review offer").- */+/** Leader, within cap: the view holds only dialogs, so it renders nothing at rest. */export const Leader: Story = { args: { wallet: subscribedWallet } };/** Approaching the cap — surfaces the over-cap warning banner + projection. */@@ -92,6 +86,3 @@ export const ApproachingCap: Story = {},},};--/** Drawing on a prepaid bundle — surfaces the capacity meter + a "Top up" action. */-export const WithPrepaid: Story = { args: { wallet: prepaidWallet } };diff --git a/frontend/editor/src/portal/components/billing/billing.css b/frontend/editor/src/portal/components/billing/billing.cssindex 93bd5268d8..38f2f62e7b 100644--- a/frontend/editor/src/portal/components/billing/billing.css+++ b/frontend/editor/src/portal/components/billing/billing.css@@ -1149,36 +1149,7 @@color: var(--c-text-subtle);}-/* ── Prepaid bundle: buy nudge + top-up + purchase modal ───────────────────── */--/* Slim commit-nudge card shown when the team holds no bundle: title/subtitle- left, "Review offer" CTA right. Mirrors the demo's prepay nudge. */-.portal-billing__prepaid-offer {- display: flex;- align-items: center;- justify-content: space-between;- gap: 1rem;- flex-wrap: wrap;-}-.portal-billing__prepaid-offer-sub {- margin: 0.25rem 0 0;- font-size: 0.875rem;- line-height: 1.5;- color: var(--c-text-subtle);- max-width: 46ch;-}--/* Meter card foot: the "used before metered billing" note + a leader Top-up. */-.portal-billing__prepaid-foot {- display: flex;- align-items: center;- justify-content: space-between;- gap: 1rem;- margin-top: 0.75rem;-}-.portal-billing__prepaid-foot .portal-billing__section-sub {- margin: 0;-}+/* ── Prepaid bundle: purchase modal ────────────────────────────────────────── *//* Purchase modal — calculator step. */.portal-billing__bundle-calc {diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsxindex f9ac2d9edc..c860f40488 100644--- a/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx+++ b/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx@@ -3,7 +3,11 @@ import type { Meta, StoryObj } from "@storybook/react-vite";import { BillingScreen } from "@app/billing/BillingScreen";import { KvRow } from "@app/billing/KvRow";import { InvoiceRow } from "@app/billing/InvoiceRow";-import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";+import {+ freeWallet,+ prepaidWallet,+ subscribedWallet,+} from "@app/billing/walletFixtures";import { AppConfigProvider } from "@app/contexts/AppConfigContext";import { LicenseProvider } from "@app/contexts/LicenseContext";import { ServerLicenseSection } from "@portal/components/billing/ServerLicenseSection";@@ -251,6 +255,36 @@ export const TeamAndProcessor: Story = {},};+/** A live prepaid pool leads the Processor row; the meter it is spent ahead of sits in the hover. */+export const PrepaidPool: Story = {+ args: {+ wallet: prepaidWallet,+ onAddCapacity: () => {},+ onGovernSpend: () => {},+ onEnterpriseQuote: () => {},+ paymentSection: payment,+ invoicesSection: invoices,+ },+};++/** Prepay bought without metering switched on: the pool still governs, activation is still the door. */+export const PrepaidPoolNotActivated: Story = {+ args: {+ wallet: {+ ...prepaidWallet,+ status: "free",+ processor: { active: false },+ estimatedBillMinor: null,+ capUsd: null,+ stripeSubscriptionId: null,+ prepaidUnitsRemaining: 9_400,+ prepaidUnitsTotal: 120_000,+ },+ onActivateProcessor: () => {},+ onEnterpriseQuote: () => {},+ },+};+/** Self-hosted and linked, carrying units the cloud has not billed yet. */export const SelfHostedPendingSync: Story = {args: {diff --git a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsxindex b70a751bae..db8252f4dc 100644--- a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx@@ -26,6 +26,12 @@ const on = (over: Partial<Wallet> = {}): Wallet => ({...over,});+/**+ * Group a count the way the row does. The component leaves counts on the runtime locale (only+ * money is pinned to en-US), so a literal "78,000" would fail wherever the separator differs.+ */+const n = (value: number) => value.toLocaleString();+describe("ProcessorPlanRow", () => {it("shows remaining free credits and paid spend separately on focus", () => {render(@@ -48,7 +54,7 @@ describe("ProcessorPlanRow", () => {expect(tooltip.getByRole("progressbar", { name: "Paid metered usage" }),).toHaveAttribute("aria-valuenow", "25");- expect(tooltip.getByText("500 of 1,000")).toBeInTheDocument();+ expect(tooltip.getByText(`${n(500)} of ${n(1000)}`)).toBeInTheDocument();expect(tooltip.getByText("$25.00 / $100")).toBeInTheDocument();});it("hides an absent included pool while retaining metered billing", () => {@@ -88,7 +94,9 @@ describe("ProcessorPlanRow", () => {expect(screen.getByText("$0.00 of $0 metered this cycle"),).toBeInTheDocument();- expect(screen.queryByText("300 of 2,500 used")).not.toBeInTheDocument();+ expect(+ screen.queryByText(`${n(300)} of ${n(2500)} used`),+ ).not.toBeInTheDocument();expect(screen.getAllByText("Processor")).toHaveLength(1);});it("does not add a separate included-credit row while metering is on", () => {@@ -103,7 +111,9 @@ describe("ProcessorPlanRow", () => {/>,);expect(screen.queryByText("Included credits")).not.toBeInTheDocument();- expect(screen.queryByText("425 of 2,700 used")).not.toBeInTheDocument();+ expect(+ screen.queryByText(`${n(425)} of ${n(2700)} used`),+ ).not.toBeInTheDocument();expect(screen.getAllByText("Processor")).toHaveLength(1);});@@ -176,6 +186,129 @@ describe("ProcessorPlanRow", () => {expect(container.querySelectorAll(".billing-meter__fill")).toHaveLength(0);});+ it("leads with a live prepaid pool, because the meter cannot move until it empties", () => {+ render(+ <ProcessorPlanRow+ wallet={on({+ prepaidUnitsRemaining: 78_000,+ prepaidUnitsTotal: 120_000,+ prepaidExpiresAt: "2027-03-01",+ estimatedBillMinor: 0,+ capUsd: 1000,+ noCap: false,+ })}+ onGovern={() => {}}+ />,+ );++ expect(screen.getByText(`${n(78_000)} left`)).toBeInTheDocument();+ expect(+ screen.getByText(/Prepaid credits, drawn before metered billing/),+ ).toBeInTheDocument();+ // The metered headline would read "$0.00 of $1,000", which says nothing while the pool lasts.+ expect(screen.queryByText(/metered this cycle/)).not.toBeInTheDocument();+ });++ it("carries the free grant and the meter behind the prepaid headline", () => {+ render(+ <ProcessorPlanRow+ wallet={on({+ freeAllowance: 500,+ freeRemaining: 500,+ prepaidUnitsRemaining: 60_000,+ prepaidUnitsTotal: 120_000,+ estimatedBillMinor: 0,+ capUsd: 1000,+ noCap: false,+ })}+ />,+ );+ fireEvent.focus(screen.getByRole("group", { name: "Processor" }));+ const tooltip = within(screen.getByRole("tooltip"));+ expect(+ tooltip.getByRole("progressbar", { name: "Free credits remaining" }),+ ).toHaveAttribute("aria-valuenow", "100");+ expect(+ tooltip.getByRole("progressbar", { name: "Prepaid credits remaining" }),+ ).toHaveAttribute("aria-valuenow", "50");+ expect(+ tooltip.getByRole("progressbar", { name: "Paid metered usage" }),+ ).toHaveAttribute("aria-valuenow", "0");+ });++ it("draws pending units through the free grant before the prepaid pool", () => {+ render(+ <ProcessorPlanRow+ wallet={on({+ freeAllowance: 500,+ freeRemaining: 500,+ prepaidUnitsRemaining: 1000,+ prepaidUnitsTotal: 1000,+ })}+ pendingUnits={700}+ />,+ );++ // 500 clears the grant, so only the remaining 200 touch the pool.+ expect(screen.getByText("800 left")).toBeInTheDocument();+ });++ it("hands the row back to the meter once the pool is spent, and says why", () => {+ render(+ <ProcessorPlanRow+ wallet={on({+ prepaidUnitsRemaining: 0,+ prepaidUnitsTotal: 120_000,+ estimatedBillMinor: 4500,+ capUsd: 1000,+ noCap: false,+ })}+ onGovern={() => {}}+ />,+ );++ expect(+ screen.getByText("$45.00 of $1,000 metered this cycle"),+ ).toBeInTheDocument();+ fireEvent.focus(screen.getByRole("group", { name: "Processor" }));+ const tooltip = within(screen.getByRole("tooltip"));+ expect(tooltip.getByText(`${n(0)} of ${n(120_000)}`)).toBeInTheDocument();+ expect(+ tooltip.getByText("Used up, metered billing has resumed"),+ ).toBeInTheDocument();+ });++ it("keeps the activation door while a pool runs without a subscription", () => {+ render(+ <ProcessorPlanRow+ wallet={off({+ prepaidUnitsRemaining: 40_000,+ prepaidUnitsTotal: 120_000,+ })}+ onActivate={() => {}}+ />,+ );++ expect(screen.getByText(`${n(40_000)} left`)).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Switch on the Processor" }),+ ).toBeInTheDocument();+ });++ it("shows no prepaid tranche for a team that never bought one", () => {+ render(+ <ProcessorPlanRow+ wallet={on({ freeAllowance: 500, freeRemaining: 200 })}+ />,+ );+ fireEvent.focus(screen.getByRole("group", { name: "Processor" }));+ expect(+ within(screen.getByRole("tooltip")).queryByRole("progressbar", {+ name: "Prepaid credits remaining",+ }),+ ).not.toBeInTheDocument();+ });+it("lets a prepaid team's door be relabelled without changing the row", () => {render(<ProcessorPlanRowdiff --git a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsxindex 172ebdfa40..e786b32daf 100644--- a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx@@ -4,14 +4,62 @@ import {formatMinor,formatMoneyMajor,formatPeriodDate,+ remainingMeter,} from "@app/billing/format";import { MeterRow } from "@app/billing/MeterRow";import { estimatedBillWithPending } from "@app/billing/pendingUsage";import type { Wallet } from "@app/billing/types";+/** One tranche of the row's breakdown: a labelled figure over its own small bar. */+function Tranche({+ label,+ value,+ pct,+ note,+ showBar = true,+}: {+ label: string;+ value: ReactNode;+ /** Null draws the track empty and reports no value — an unknown, not a zero. */+ pct: number | null;+ note?: ReactNode;+ showBar?: boolean;+}) {+ const width = pct == null ? 0 : Math.min(100, Math.max(0, pct));+ return (+ <div>+ <div className="billing-breakdown__row">+ <span>{label}</span>+ <strong>{value}</strong>+ </div>+ {showBar && (+ <span+ className="billing-breakdown__bar"+ role="progressbar"+ aria-label={label}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={pct == null ? undefined : Math.round(width)}+ >+ <span+ className="billing-breakdown__fill"+ style={{ width: `${width}%` }}+ />+ </span>+ )}+ {note && <small>{note}</small>}+ </div>+ );+}+/**- * The Processor product, as a row: the free grant draining towards activation while off, spend- * against the limit while on.+ * The Processor product, as a row: the free grant draining towards activation while off, a live+ * prepaid pool while one is held, and spend against the limit once the meter is what is left.+ *+ * <p>All three are tranches of one product, so they share one row rather than stacking cards.+ * The headline is whichever governs the team right now and the hover breakdown carries the rest.+ * A live prepaid pool leads: it is what the team draws on, and the metered figure cannot move+ * until it empties.** <p>Money arrives in two scales. The estimate is minor units and the limit is major, so the* comparison converts once here rather than leaving a factor of a hundred to a caller. An unknown@@ -58,16 +106,182 @@ export function ProcessorPlanRow({);if (!wallet) return null;const rate = wallet.pricePerDocMinor;+ const active = wallet.processor.active;- const includedCredits = (() => {- if (wallet.processor.active || wallet.freeAllowance <= 0) return null;- const used = Math.min(- wallet.freeAllowance,- Math.max(0, wallet.freeAllowance - wallet.freeRemaining + pendingUnits),+ // One door per row, and both of them already reach a purchase: the activation fork sells+ // prepay, the spend-limit dialog sells credits. Prepaid therefore adds no third door.+ const door = active+ ? onGovern+ ? (governLabel ?? t("portal.billing.processor.raiseLimit", "Raise limit"))+ : undefined+ : onActivate+ ? (activateLabel ??+ t("portal.billing.processor.activate", "Switch on the Processor"))+ : undefined;+ const onDoor = active ? onGovern : onActivate;++ // Drawdown order mirrors pendingMeteredUnits: the free grant, then the prepaid pool, then the+ // meter. Unsynced units consume them in that same order, so no tranche reports headroom the+ // entitlement gate will refuse.+ const freeLeft = Math.min(+ wallet.freeAllowance,+ Math.max(0, wallet.freeRemaining - pendingUnits),+ );+ const prepaidTotal = wallet.prepaidUnitsTotal;+ const prepaidLeft = Math.max(+ 0,+ wallet.prepaidUnitsRemaining -+ Math.max(0, pendingUnits - wallet.freeRemaining),+ );+ const heldPrepaid = prepaidTotal > 0;+ const prepaidMeter = heldPrepaid+ ? remainingMeter(prepaidLeft, prepaidTotal)+ : null;++ const spentMinor = active+ ? estimatedBillWithPending(wallet, pendingUnits)+ : null;+ const capped = active && !wallet.noCap && wallet.capUsd != null;+ // One conversion, in one place: the estimate is minor units, the limit is major.+ const spentMajor = spentMinor != null ? spentMinor / 100 : null;+ const spendPct =+ capped && spentMajor != null+ ? wallet.capUsd === 0+ ? 100+ : (spentMajor / (wallet.capUsd as number)) * 100+ : 0;++ const remainingOf = (remaining: number, total: number) =>+ t("portal.billing.processor.remainingOf", "{{remaining}} of {{total}}", {+ remaining: remaining.toLocaleString(),+ total: total.toLocaleString(),+ });++ const tranches: ReactNode[] = [];+ if (wallet.freeAllowance > 0)+ tranches.push(+ <Tranche+ key="free"+ label={t(+ "portal.billing.processor.freeRemaining",+ "Free credits remaining",+ )}+ value={remainingOf(freeLeft, wallet.freeAllowance)}+ pct={(freeLeft / wallet.freeAllowance) * 100}+ />,+ );+ if (heldPrepaid)+ tranches.push(+ <Tranche+ key="prepaid"+ label={t(+ "portal.billing.processor.prepaidRemaining",+ "Prepaid credits remaining",+ )}+ value={remainingOf(prepaidLeft, prepaidTotal)}+ pct={prepaidMeter?.pct ?? 0}+ note={+ prepaidLeft === 0+ ? t(+ "portal.billing.processor.prepaidExhausted",+ "Used up, metered billing has resumed",+ )+ : wallet.prepaidExpiresAt+ ? t(+ "portal.billing.processor.prepaidExpires",+ "Expires {{date}}",+ {+ date: formatPeriodDate(wallet.prepaidExpiresAt, {+ year: true,+ }),+ },+ )+ : undefined+ }+ />,+ );+ if (active)+ tranches.push(+ <Tranche+ key="paid"+ label={t("portal.billing.processor.paidUsed", "Paid metered usage")}+ value={+ <>+ {spentMinor == null+ ? "—"+ : formatMinor(spentMinor, wallet.currency)}+ {capped+ ? ` / ${formatMoneyMajor(wallet.capUsd as number, wallet.currency)}`+ : ""}+ </>+ }+ pct={spentMinor == null ? null : spendPct}+ showBar={capped}+ note={+ capped+ ? undefined+ : t("portal.billing.processor.noSpendLimit", "No spend limit")+ }+ />,+ );+ // A lone tranche is what the headline already says, and a tooltip would only repeat it.+ const details =+ tranches.length > 1 ? (+ <div className="billing-breakdown">{tranches}</div>+ ) : undefined;++ if (heldPrepaid && prepaidLeft > 0) {+ const summary = t(+ "portal.billing.processor.midPrepaid",+ "Prepaid credits, drawn before metered billing",+ );+ return (+ <MeterRow+ name={name}+ mid={+ wallet.prepaidExpiresAt+ ? t(+ "portal.billing.processor.midPrepaidExpiry",+ "{{summary}} · Expires {{date}}",+ {+ summary,+ date: formatPeriodDate(wallet.prepaidExpiresAt, {+ year: true,+ }),+ },+ )+ : summary+ }+ midTitle={t(+ "portal.billing.processor.prepaidTooltip",+ "Drawn before metered billing, and outside your spend limit.",+ )}+ details={details}+ pct={prepaidMeter?.pct ?? 0}+ tone={prepaidMeter?.state === "FULL" ? "paid" : "warn"}+ fact={t("portal.billing.processor.factPrepaid", "{{remaining}} left", {+ remaining: prepaidLeft.toLocaleString(),+ })}+ door={door}+ onDoor={onDoor}+ />);- const pct =- wallet.freeAllowance > 0 ? (used / wallet.freeAllowance) * 100 : 0;- const mid =+ }++ if (!active) {+ if (wallet.freeAllowance <= 0)+ return (+ <MeterRow+ name={name}+ mid=""+ fact=""+ showTrack={false}+ door={door}+ onDoor={onDoor}+ />+ );+ const used = wallet.freeAllowance - freeLeft;+ const freeMid =rate != null? t("portal.billing.processor.midIncluded",@@ -84,7 +298,6 @@ export function ProcessorPlanRow({allowance: wallet.freeAllowance.toLocaleString(),},);-return (<MeterRowname={name}@@ -94,13 +307,14 @@ export function ProcessorPlanRow({"portal.billing.processor.includedRenewal","{{summary}} · Renews {{date}}",{- summary: mid,+ summary: freeMid,date: formatPeriodDate(wallet.includedPeriodEnd),},)- : mid+ : freeMid}- pct={pct}+ details={details}+ pct={(used / wallet.freeAllowance) * 100}tone="free"fact={t("portal.billing.processor.factFree",@@ -110,48 +324,11 @@ export function ProcessorPlanRow({allowance: wallet.freeAllowance.toLocaleString(),},)}- door={- !wallet.processor.active && onActivate- ? (activateLabel ??- t("portal.billing.processor.activate", "Switch on the Processor"))- : undefined- }- onDoor={!wallet.processor.active ? onActivate : undefined}+ door={door}+ onDoor={onDoor}/>);- })();- if (!wallet.processor.active)- return (- includedCredits ?? (- <MeterRow- name={name}- mid=""- fact=""- showTrack={false}- door={- onActivate- ? (activateLabel ??- t(- "portal.billing.processor.activate",- "Switch on the Processor",- ))- : undefined- }- onDoor={onActivate}- />- )- );-- const spentMinor = estimatedBillWithPending(wallet, pendingUnits);- const capped = !wallet.noCap && wallet.capUsd != null;- // One conversion, in one place: the estimate is minor units, the limit is major.- const spentMajor = spentMinor != null ? spentMinor / 100 : null;- const pct =- capped && spentMajor != null- ? wallet.capUsd === 0- ? 100- : (spentMajor / (wallet.capUsd as number)) * 100- : 0;+ }const mid =spentMinor != null@@ -177,109 +354,21 @@ export function ProcessorPlanRow({? spentMinor == null? "—": t("portal.billing.processor.percentUsed", "{{pct}}%", {- pct: Math.round(pct).toLocaleString(),+ pct: Math.round(spendPct).toLocaleString(),}): t("portal.billing.processor.factNoCap", "no limit");- const door =- governLabel ??- (onGovern- ? t("portal.billing.processor.raiseLimit", "Raise limit")- : undefined);- const freeRemaining = Math.min(- wallet.freeAllowance,- Math.max(0, wallet.freeRemaining - pendingUnits),- );- const freePct =- wallet.freeAllowance > 0 ? (freeRemaining / wallet.freeAllowance) * 100 : 0;- const freeLabel = t(- "portal.billing.processor.freeRemaining",- "Free credits remaining",- );- const paidLabel = t(- "portal.billing.processor.paidUsed",- "Paid metered usage",- );- const details = (- <div className="billing-breakdown">- <div>- <div className="billing-breakdown__row">- <span>{freeLabel}</span>- <strong>- {t(- "portal.billing.processor.remainingOf",- "{{remaining}} of {{total}}",- {- remaining: freeRemaining.toLocaleString(),- total: wallet.freeAllowance.toLocaleString(),- },- )}- </strong>- </div>- <span- className="billing-breakdown__bar"- role="progressbar"- aria-label={freeLabel}- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={Math.round(freePct)}- >- <span- className="billing-breakdown__fill"- style={{ width: `${freePct}%` }}- />- </span>- </div>- <div>- <div className="billing-breakdown__row">- <span>{paidLabel}</span>- <strong>- {spentMinor == null- ? "—"- : formatMinor(spentMinor, wallet.currency)}- {capped- ? ` / ${formatMoneyMajor(wallet.capUsd as number, wallet.currency)}`- : ""}- </strong>- </div>- {capped ? (- <span- className="billing-breakdown__bar"- role="progressbar"- aria-label={paidLabel}- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={- spentMinor == null- ? undefined- : Math.round(Math.min(100, Math.max(0, pct)))- }- >- <span- className="billing-breakdown__fill"- style={{ width: `${Math.min(100, Math.max(0, pct))}%` }}- />- </span>- ) : (- <small>- {t("portal.billing.processor.noSpendLimit", "No spend limit")}- </small>- )}- </div>- </div>- );-return (<MeterRowname={name}mid={mid}details={details}- pct={pct}- tone={capped && pct >= 90 ? "warn" : "paid"}+ pct={spendPct}+ tone={capped && spendPct >= 90 ? "warn" : "paid"}showTrack={capped}fact={fact}- door={onGovern ? door : undefined}- onDoor={onGovern}+ door={door}+ onDoor={onDoor}midTitle={capped? t(diff --git a/frontend/editor/src/proprietary/billing/billing-screen.css b/frontend/editor/src/proprietary/billing/billing-screen.cssindex 6c42bafb89..4734dbb0e6 100644--- a/frontend/editor/src/proprietary/billing/billing-screen.css+++ b/frontend/editor/src/proprietary/billing/billing-screen.css@@ -260,6 +260,8 @@}.billing-breakdown small {+ display: block;+ margin-top: 0.25rem;color: var(--c-text-muted);}