#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
Simplify Team and Processor purchase dialogs (#8049)
ConnorYoheac9799c6496
diff --git a/app/saas/src/main/java/stirling/software/saas/service/SaasTeamService.java b/app/saas/src/main/java/stirling/software/saas/service/SaasTeamService.javaindex 840cf77b5a..764c78332c 100644--- a/app/saas/src/main/java/stirling/software/saas/service/SaasTeamService.java+++ b/app/saas/src/main/java/stirling/software/saas/service/SaasTeamService.java@@ -764,87 +764,7 @@ public class SaasTeamService {.findById(teamId).orElseThrow(() -> new IllegalArgumentException("Team not found"));- // Handle seat reduction: automatically remove excess members if reducing below current- // usage- int currentSeatsUsed = saasTeamExtensionService.getSeatsUsed(team);- int currentMaxSeats = saasTeamExtensionService.getMaxSeats(team);- if (maxSeats < currentSeatsUsed) {- int excessMembers = currentSeatsUsed - maxSeats;- log.warn(- "Team {} reducing seats from {} to {} with {} current members. Removing {} excess members.",- teamId,- currentMaxSeats,- maxSeats,- currentSeatsUsed,- excessMembers);-- // Get all team members, sorted by priority (non-leaders first, most recently joined- // first)- List<TeamMembership> allMembers = membershipRepository.findByTeamId(teamId);-- // Sort: MEMBER role first (non-leaders), then by accepted date descending (most recent- // first)- List<TeamMembership> membersToRemove =- allMembers.stream()- .sorted(- (m1, m2) -> {- // Leaders (LEADER role) come last (lower priority for- // removal)- if (m1.getRole() != m2.getRole()) {- return m1.getRole() == TeamRole.LEADER ? 1 : -1;- }- // Among same role, remove most recently joined first- // (descending accepted date)- LocalDateTime date1 =- m1.getAcceptedAt() != null- ? m1.getAcceptedAt()- : m1.getInvitedAt();- LocalDateTime date2 =- m2.getAcceptedAt() != null- ? m2.getAcceptedAt()- : m2.getInvitedAt();- if (date1 == null && date2 == null) return 0;- if (date1 == null) return 1;- if (date2 == null) return -1;- return date2.compareTo(- date1); // Descending (most recent first)- })- .limit(excessMembers)- .collect(java.util.stream.Collectors.toList());-- // Remove excess members- for (TeamMembership membership : membersToRemove) {- User userToRemove = membership.getUser();- log.info(- "Removing user {} ({}) from team {} due to seat reduction",- userToRemove.getId(),- userToRemove.getUsername(),- teamId);-- // Delete membership- membershipRepository.delete(membership);-- // Atomically decrement seats_used count (prevents race condition)- saasTeamExtensionsRepository.decrementSeatsUsed(teamId);-- // Return the evicted user to their durable home team.- returnUserToHome(userToRemove);-- // Downgrade user to FREE tier- downgradeUserToFree(userToRemove);-- log.info(- "User {} removed from team {} and migrated to personal team due to seat reduction",- userToRemove.getId(),- teamId);- }-- log.info(- "Completed seat reduction for team {}: removed {} members",- teamId,- excessMembers);- }-+ // A reduction blocks future admissions; existing memberships remain intact.saasTeamExtensionService.setSeats(team, maxSeats, maxSeats);// Personal team with maxSeats > 1 is really a standard team.@@ -857,7 +777,9 @@ public class SaasTeamService {maxSeats);}// Revert to personal when downgrading to 1 seat- else if (!wasPersonal && maxSeats == 1) {+ else if (!wasPersonal+ && maxSeats == 1+ && saasTeamExtensionService.getSeatsUsed(team) <= 1) {saasTeamExtensionService.setPersonal(team, true);log.info("Team {} converted from STANDARD to PERSONAL (maxSeats reduced to 1)", teamId);}diff --git a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.java b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.javaindex 2da28f1111..f2c2019ccc 100644--- a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamServiceTest.java@@ -1313,7 +1313,6 @@ class SaasTeamServiceTest {Team t = team(teamId, "My Team");when(teamRepository.findById(teamId)).thenReturn(Optional.of(t));when(saasTeamExtensionService.getSeatsUsed(t)).thenReturn(1);- when(saasTeamExtensionService.getMaxSeats(t)).thenReturn(1);// First isPersonal call (after setSeats) returns true -> convert to standard.when(saasTeamExtensionService.isPersonal(t)).thenReturn(true, false);@@ -1330,7 +1329,6 @@ class SaasTeamServiceTest {Team t = team(teamId, "Acme");when(teamRepository.findById(teamId)).thenReturn(Optional.of(t));when(saasTeamExtensionService.getSeatsUsed(t)).thenReturn(1);- when(saasTeamExtensionService.getMaxSeats(t)).thenReturn(5);// Was standard (false) so reducing to 1 flips back to personal.when(saasTeamExtensionService.isPersonal(t)).thenReturn(false);@@ -1340,39 +1338,19 @@ class SaasTeamServiceTest {}@Test- @DisplayName("removes excess members (members before leaders) when reducing below usage")- void reduceBelowUsage_removesExcessMembers() {+ @DisplayName("reductions retain existing members and the standard team")+ void reduceBelowUsage_retainsMembers() {Team t = team(teamId, "Acme");- User leader = user(1L, "[email protected]", "alice");- User member = user(2L, "[email protected]", "bob");- // Distinct membership ids so delete() verification can tell the two rows apart- // (TeamMembership equals is by membershipId).- TeamMembership leaderM = membership(t, leader, TeamRole.LEADER);- leaderM.setMembershipId(1L);- TeamMembership memberM = membership(t, member, TeamRole.MEMBER);- memberM.setMembershipId(2L);- memberM.setAcceptedAt(LocalDateTime.now());- leaderM.setAcceptedAt(LocalDateTime.now().minusDays(10));-when(teamRepository.findById(teamId)).thenReturn(Optional.of(t));when(saasTeamExtensionService.getSeatsUsed(t)).thenReturn(2);- when(saasTeamExtensionService.getMaxSeats(t)).thenReturn(2);- when(membershipRepository.findByTeamId(teamId)).thenReturn(List.of(leaderM, memberM));- // Reduce to 1: must remove 1 excess; the MEMBER goes first.- stubCreatePersonalTeam(member, 500L);when(saasTeamExtensionService.isPersonal(t)).thenReturn(false);service.updateTeamSeats(teamId, 1);- // The MEMBER is removed, the LEADER kept (removal prioritises non-leaders).- verify(membershipRepository).delete(memberM);- verify(membershipRepository, never()).delete(leaderM);- // One decrement for the removed member, then a second seat update is applied via- // setSeats(t, 1, 1). Reducing to 1 seat also flips a standard team back to personal:- // setPersonal(true) is invoked for both the removed member's new personal team and t.- verify(saasTeamExtensionsRepository).decrementSeatsUsed(teamId);- verify(saasTeamExtensionService, org.mockito.Mockito.times(2))- .setPersonal(any(), eq(true));+ verify(saasTeamExtensionService).setSeats(t, 1, 1);+ verify(membershipRepository, never()).delete(any(TeamMembership.class));+ verify(saasTeamExtensionService, never()).decrementSeatsUsed(any());+ verify(saasTeamExtensionService, never()).setPersonal(t, true);}@Test@@ -1381,7 +1359,6 @@ class SaasTeamServiceTest {Team t = team(teamId, "Acme");when(teamRepository.findById(teamId)).thenReturn(Optional.of(t));when(saasTeamExtensionService.getSeatsUsed(t)).thenReturn(2);- when(saasTeamExtensionService.getMaxSeats(t)).thenReturn(5);// Already standard, raising to 10: neither conversion branch fires.when(saasTeamExtensionService.isPersonal(t)).thenReturn(false);diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 65a321e2f7..e814dded7a 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -3491,6 +3491,7 @@ title = "Choose color"actions = "Actions"back = "Back"cancel = "Cancel"+change = "Change"clearFilters = "Clear filters"close = "Close"codeSample = "Code sample"@@ -6604,6 +6605,8 @@ resetsTomorrow = "Resets tomorrow"thisPeriod = "This billing period"[payment]+billingPeriod = "Billing period"+cancelTeamChange = "Keep current plan"canCloseWindow = "You can now close this window."error = "Payment Error"generatingLicense = "Generating your license key..."@@ -6619,17 +6622,22 @@ manageSubscription = "Manage subscription"monthly = "Monthly"paymentCanceled = "Payment was canceled. No charges were made."perMonth = "/month"+perUserBlock = "per 100 users"preparing = "Preparing your checkout..."redirecting = "Redirecting to secure checkout..."-stepOf = "Step {{n}} of {{total}}"success = "Payment Successful!"successMessage = "Your subscription has been activated successfully. You will receive a confirmation email shortly."syncError = "Payment successful but license sync failed. Your license will be updated shortly. Please contact support if issues persist."syncingLicense = "Syncing your upgraded license..."teamActivated = "Your Team capacity is active"teamActivating = "Confirming your Team capacity..."+teamChangeCurrent = "Your current allowance remains available until then. Keep your current plan to cancel this change before making another adjustment."+teamChangePending = "{{users}} users · {{period}} from {{date}}"+teamChangeSupport = "Your Team subscription has a scheduled change that needs billing support to adjust."+teamChangeUnavailable = "Scheduled Team changes could not be loaded. Refresh to try again."teamPending = "Your Team purchase is still processing. Refresh this page shortly."teamProcessing = "Team purchase processing"+teamScheduled = "Your Team change is scheduled for {{date}}. Your current capacity stays active until then."upgradeComplete = "Upgrade Complete"upgradeCompleteMessage = "Your subscription has been upgraded successfully. Your existing license key has been updated."upgradeSuccess = "Payment successful! Your subscription has been upgraded. The license has been updated on your server. You will receive a confirmation email shortly."@@ -6637,13 +6645,13 @@ upgradeTitle = "Upgrade to {{planName}}"yearly = "Yearly"[payment.addCapacity]-currently = "Currently up to {{users}} users"-title = "Add capacity"++[payment.adjustTeam]+title = "Adjust Team plan"[payment.capacityStage]adjustmentNote = "Stripe will show the exact charge, any prorations and your next billing date before you confirm. Your saved payment method will be used if available."continue = "Continue to payment"-customHint = "Rounded up to the next block of {{users}}."customLabel = "Number of users"dueToday = "Due today"enterpriseQuote = "Get an enterprise quote"@@ -6652,13 +6660,17 @@ minimumForCurrentUsers = "You have {{users}} users, so the plan must cover at lemodalTitle = "Upgrade to {{planName}}"newPlanTotal = "New plan total"other = "Other"+overCapacityBody = "{{users}} users are on this server; your current allowance is {{limit}}. Choose a Team plan below to cover everyone."+overCapacityConsequence = "Existing accounts stay in place. Adding or inviting users is blocked until you add capacity or free up seats."+overCapacityTitle = "Your server has more users than your plan covers"perMonth = "/mo"perYear = "/yr"+reductionNote = "The lower capacity starts at your next renewal. Until then, you can use your current allowance. Existing users stay; new users are blocked if you are over capacity when the change takes effect."renewalNote = "Renews at {{total}}{{period}}. Cancel any time in Usage & Billing."reviewChange = "Review change in Stripe"+roundsTo = "rounds to {{users}}"subheading = "Covers everyone you invite, in blocks of {{users}} users."subheadingAdd = "Your plan covers {{current}} users today. Choose the new total."-userDelta = "+{{users}} users"usersLabel = "Users"userTotal = "{{users}} users"@@ -7521,13 +7533,8 @@ title = "Almost there"[portal.billing.checkout.cap]amountAria = "Monthly spend limit"-back = "Back"continue = "Continue to payment"error = "Couldn't set your spend limit"-finePrint = "Invoices post monthly. Cancel anytime."-noLimit = "No limit"-note = "You're never billed past your limit. Processing just pauses."-perMonth = "/ mo"title = "Set your spend limit"[portal.billing.checkout.card]@@ -7653,11 +7660,11 @@ topUp = "Top up"[portal.billing.prepaid.buy]back = "Back"-calcTitle = "Calculate your annual payment"cancel = "Cancel"cancelPurchase = "Cancel purchase"close = "Close"continueToPayment = "Continue to payment"+creditTitle = "Prepay the year"finalise = "Finalise"invoiceErrorTitle = "Couldn't generate the invoice"loadingTitle = "Loading your quote"@@ -7665,34 +7672,12 @@ payTitle = "Pay for your year"step = "Step {{current}} of {{total}}"[portal.billing.prepaid.calc]-change = "Change"-deployRow = "Deployment"-done = "Done"-enterpriseHint = "This is enterprise scale. At this volume, enterprise rates beat any self-serve discount. Rate lock, terms, and a quote in minutes."-governanceRow = "Governance"-governanceValue = "{{label}} · {{count}} policies"-handlesLabel = "Your Processor"-handlesValue = "handles {{volume}} credits / mo"-pipelinesLabel = "Pipelines"-policiesMeta = "{{count}} policies"-poolCaption = "One pool of {{credits}} credits for the year. Heavy months borrow from light ones."-priceLabel = "Your year · 12 months for the price of 10"rateUnknown = "We'll show the exact price at checkout."-savings = "You save {{amount}} · 2 months free."-sizingRow = "Sizing"-sizingValue = "{{label}} · {{desc}}"-usersLabel = "Total users"[portal.billing.prepaid.consent]label = "I understand that when my prepaid capacity is used up or expires after 12 months, processing automatically continues at the standard metered pay-as-you-go rate (up to my spend limit) unless I cancel, and that I can cancel anytime from the billing portal."[portal.billing.prepaid.deploy]-cloud = "Stirling Cloud"-cloudDesc = "Managed by Stirling. Live in minutes."-cloudValue = "Stirling Cloud · Managed"-selfhost = "Self-hosted"-selfhostDesc = "Runs on private infrastructure. Same rate."-selfhostValue = "Self-hosted · Private infrastructure"[portal.billing.prepaid.offer]cta = "Review offer"@@ -7710,33 +7695,14 @@ poNumber = "PO number (optional)"poNumberPlaceholder = "e.g. PO-2026-0142"[portal.billing.prepaid.pipelines]-advanced = "Advanced"-advancedDesc = "Pipelines drive most of your processing."-none = "None"-noneDesc = "Not running pipelines yet. Turn them on any time."-standard = "Standard"-standardDesc = "A few pipelines re-process arriving PDFs."[portal.billing.prepaid.posture]-essentials = "Essentials"-essentialsDesc = "Classification, the default, plus Sharing"-governed = "Governed"-governedDesc = "Adds Security and Routing"-regulated = "Regulated"-regulatedDesc = "Every category, incl. Compliance, Retention, Ingestion"[portal.billing.prepaid.review]download = "Download quote (PDF)"downloading = "Preparing…"-share = "share for approval"[portal.billing.prepaid.size]-compact = "Compact"-compactDesc = "Files under 25 MB, no data charges"-heavy = "Heavy"-heavyDesc = "Scanned or image-heavy, routinely 50 MB+"-standard = "Standard"-standardDesc = "Mostly small, some scans past 25 MB"[portal.billing.prepaid.state]exhausted = "Used up"@@ -7775,18 +7741,34 @@ seats = "{{seats}} licensed seats"server = "Server"unlimited = "Unlimited users"+[portal.billing.simple]+afterYear = "After the year"+afterYearNote = "No automatic renewal. Further processing needs an active metered plan and stays within its spend limit."+billingNote = "No standing fee. Credits bill monthly as used. Cancel any time in Usage & Billing."+creditEstimate = "≈ {{credits}} credits"+credits = "Credits"+limit = "Spend limit · processing pauses here"+limitIntro = "Cap what the Processor can bill each month."+monthlyAmount = "{{amount}}/mo"+prepayDiscount = "Prepay discount · 12 for 10"+prepayIntro = "A year of processing at a discount."+rate = "{{rate}} each · billed as used"+ratePending = "Rate shown at checkout"+setLimit = "Set a spend limit"+yearSize = "Year size"+yearValue = "A year of processing"+[portal.billing.spendLimit]adjustLimit = "Adjust limit"+buyCredits = "Buy credits"cancel = "Cancel"capControlNote = "Changes apply immediately — raise or lower the ceiling any time."capSuffix = "/ month"-capSuffixWithDocs = "/ month · ≈ {{documents}} documents"displaySub = "You're only billed for what you process automatically — never past the ceiling."editTitle = "Set your monthly ceiling"eyebrow = "Spend limit"-guardrailBody = "a hard ceiling; you're never billed past it. At the cap, metered processing pauses (unlimited PDF editing keeps working) until you raise it or the cycle resets. Nothing is lost."-guardrailLabel = "Your guardrail:"noCap = "no cap"+pauseNote = "Metered processing pauses at your limit. PDF editing remains available."pctUsed = "{{pct}}% used"remaining = "{{amount}} remaining"save = "Save limit"@@ -7801,7 +7783,6 @@ body_other = "At {{rate}}/day you reach the cap in ~{{count}} days (~{{monthEnd}label = "Projected to exceed."[portal.billing.spendLimitModal]-title = "Monthly spend limit"[portal.billing.subscribedPlan.capWarn]approachingBody = "Raise it now so automated processing never pauses."diff --git a/frontend/editor/src/core/components/onboarding/Onboarding.tsx b/frontend/editor/src/core/components/onboarding/Onboarding.tsxindex 8ffde7ccae..3e68ff92a9 100644--- a/frontend/editor/src/core/components/onboarding/Onboarding.tsx+++ b/frontend/editor/src/core/components/onboarding/Onboarding.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useCallback, useState } from "react";+import { useEffect, useMemo, useCallback, useState, useRef } from "react";import { type StepType } from "@reactour/tour";import { useTranslation } from "react-i18next";import { useNavigate, useLocation } from "react-router-dom";@@ -11,7 +11,6 @@ import OnboardingTour, {type CloseArgs,} from "@app/components/onboarding/OnboardingTour";import OnboardingModalSlide from "@app/components/onboarding/OnboardingModalSlide";-import StaticOnboardingSlide from "@app/components/onboarding/StaticOnboardingSlide";import {useServerLicenseRequest,useTourRequest,@@ -42,11 +41,7 @@ export default function Onboarding() {const { osInfo, osOptions, setSelectedDownloadUrl, handleDownloadSelected } =useOnboardingDownload();- const {- showLicenseSlide,- licenseNotice: externalLicenseNotice,- closeLicenseSlide,- } = useServerLicenseRequest();+ const { showLicenseSlide, closeLicenseSlide } = useServerLicenseRequest();const {tourRequested: externalTourRequested,requestedTourType,@@ -115,7 +110,7 @@ export default function Onboarding() {break;case "see-plans":actions.complete();- navigate("/settings/adminPlan");+ navigate("/settings/billing");break;}},@@ -258,6 +253,40 @@ export default function Onboarding() {return modalSlides.findIndex((step) => step.id === currentStep.id);}, [activeFlow, currentStep]);+ const onboardingLicenseRequested =+ isActive && currentStep?.id === "server-license";+ const handledLicenseRequest = useRef(false);+ useEffect(() => {+ const requested = showLicenseSlide || onboardingLicenseRequested;+ if (!requested) {+ handledLicenseRequest.current = false;+ return;+ }+ if (bypassOnboarding || onAuthRoute || handledLicenseRequest.current)+ return;+ handledLicenseRequest.current = true;+ if (showLicenseSlide) closeLicenseSlide();+ else actions.complete();+ if (+ serverExperience.effectiveIsAdmin &&+ !serverExperience.hasPaidLicense &&+ serverExperience.overFreeTierLimit === true+ ) {+ navigate("/settings/billing?upgrade=team");+ }+ }, [+ showLicenseSlide,+ onboardingLicenseRequested,+ bypassOnboarding,+ onAuthRoute,+ closeLicenseSlide,+ actions,+ navigate,+ serverExperience.effectiveIsAdmin,+ serverExperience.hasPaidLicense,+ serverExperience.overFreeTierLimit,+ ]);+if (bypassOnboarding) {return null;}@@ -266,39 +295,7 @@ export default function Onboarding() {return null;}- if (showLicenseSlide) {- const effectiveLicenseNotice =- externalLicenseNotice || runtimeState.licenseNotice;- return (- <StaticOnboardingSlide- key="server-license"- slideId="server-license"- // Remove back button for the external license notice.- transformButtons={(buttons) =>- buttons.filter((btn) => btn.key !== "license-back")- }- runtimeState={{- ...runtimeState,- licenseNotice: effectiveLicenseNotice,- }}- params={{- osOptions: [],- onDownloadUrlChange: () => {},- licenseNotice: effectiveLicenseNotice,- loginEnabled: serverExperience.loginEnabled,- }}- onSkip={closeLicenseSlide}- onAction={(action) => {- if (action === "see-plans") {- closeLicenseSlide();- navigate("/settings/adminPlan");- } else {- closeLicenseSlide();- }- }}- />- );- }+ if (showLicenseSlide || onboardingLicenseRequested) return null;// Always render the tour component (it controls its own visibility with isOpen)const tourComponent = (diff --git a/frontend/editor/src/core/components/onboarding/orchestrator/useOnboardingOrchestrator.ts b/frontend/editor/src/core/components/onboarding/orchestrator/useOnboardingOrchestrator.tsindex 38432ebcd3..c90616e01e 100644--- a/frontend/editor/src/core/components/onboarding/orchestrator/useOnboardingOrchestrator.ts+++ b/frontend/editor/src/core/components/onboarding/orchestrator/useOnboardingOrchestrator.ts@@ -188,9 +188,7 @@ export function useOnboardingOrchestrator(isOverLimit: serverExperience.overFreeTierLimit ?? false,requiresLicense:!serverExperience.hasPaidLicense &&- (serverExperience.overFreeTierLimit === true ||- (serverExperience.effectiveIsAdmin &&- serverExperience.userCountResolved)),+ serverExperience.overFreeTierLimit === true,},}));}, [diff --git a/frontend/editor/src/portal/billing/stripe.ts b/frontend/editor/src/portal/billing/stripe.tsindex 598db229d9..39bbd0ed74 100644--- a/frontend/editor/src/portal/billing/stripe.ts+++ b/frontend/editor/src/portal/billing/stripe.ts@@ -122,7 +122,7 @@ async function rpc<T>(/** Inputs to {@link upsertBundleQuote} — the sized config + computed figures. */export interface BundleQuoteInput {teamId: number;- users: number;+ users: number | null;posturePolicies: number;sizeMult: number;pipelineMult: number;diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.test.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.test.tsxnew file mode 100644index 0000000000..69a78c8dd5--- /dev/null+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.test.tsx@@ -0,0 +1,182 @@+import { MantineProvider } from "@mantine/core";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ cleanup,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";+import { subscribedWallet } from "@app/billing/walletFixtures";+import type { LatestBundleQuote } from "@portal/billing/stripe";++const api = vi.hoisted(() => ({+ getLatestBundleQuote: vi.fn(),+ fetchBundlePricing: vi.fn(),+ upsertBundleQuote: vi.fn(),+ createBundleStripeQuote: vi.fn(),+ acceptBundleStripeQuote: vi.fn(),+ finalizeBundleInvoice: vi.fn(),+}));+vi.mock("@portal/billing/stripe", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@portal/billing/stripe")>()),+ ...api,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, fallback: string, values?: Record<string, unknown>) =>+ fallback.replace(/{{(.*?)}}/g, (_, key: string) =>+ String(values?.[key] ?? ""),+ ),+ }),+}));++function showCheckout() {+ return render(+ <MantineProvider>+ <BundleCheckoutModal open wallet={subscribedWallet} onClose={() => {}} />+ </MantineProvider>,+ );+}++describe("annual credit purchases", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ sessionStorage.clear();+ api.getLatestBundleQuote.mockResolvedValue(null);+ api.fetchBundlePricing.mockResolvedValue({+ currency: "usd",+ unitAmountMinor: 1,+ });+ api.finalizeBundleInvoice.mockResolvedValue({+ invoiceId: "in_test",+ status: "open",+ hostedInvoiceUrl: null,+ invoicePdf: null,+ });+ api.upsertBundleQuote.mockResolvedValue({+ quoteId: 7,+ status: "draft",+ validUntil: "2027-01-01",+ });+ api.createBundleStripeQuote.mockResolvedValue({+ stripeQuoteId: "qt_test",+ stripeQuoteNumber: "Q-7",+ });+ });+ afterEach(cleanup);++ it("quotes the chosen credit pool independently of Team seats, without accepting it", async () => {+ showCheckout();+ fireEvent.click(await screen.findByRole("button", { name: "$24,000" }));+ expect(screen.queryByText("Total users")).not.toBeInTheDocument();+ expect(screen.getByText("$20,000.00")).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await screen.findByText("Pay for your year");+ expect(api.upsertBundleQuote).toHaveBeenCalledWith(+ expect.objectContaining({+ users: null,+ poolCredits: 2_400_000,+ priceMinor: 2_000_000,+ posturePolicies: 1,+ sizeMult: 1,+ pipelineMult: 1,+ consented: false,+ }),+ );+ expect(api.acceptBundleStripeQuote).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.getByRole("button", { name: "$24,000" })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await screen.findByText("Pay for your year");+ expect(api.createBundleStripeQuote).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ fireEvent.click(screen.getByRole("button", { name: "$12,000" }));+ fireEvent.click(screen.getByRole("button", { name: "$24,000" }));+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await screen.findByText("Pay for your year");+ expect(api.createBundleStripeQuote).toHaveBeenCalledTimes(2);+ });++ it("resumes an old quote's exact pool, amount and currency even if the wallet rate changed", async () => {+ const latest: LatestBundleQuote = {+ quoteId: 7,+ users: 25,+ posturePolicies: 4,+ sizeMult: 1.2,+ pipelineMult: 1,+ poolCredits: 576_000,+ priceMinor: 480_000,+ currency: "gbp",+ consentedAt: null,+ stripeQuoteId: "qt_existing",+ stripeQuoteNumber: "Q-7",+ stripeRef: null,+ validUntil: "2027-01-01",+ };+ api.getLatestBundleQuote.mockResolvedValue(latest);+ api.fetchBundlePricing.mockResolvedValue({+ currency: "gbp",+ unitAmountMinor: 2,+ });+ showCheckout();+ expect(await screen.findByText("≈ 576,000 credits")).toBeInTheDocument();+ expect(screen.getByText("£4,800.00")).toBeInTheDocument();+ expect(screen.queryByText(/You save/)).not.toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Continue to payment" }),+ );+ await screen.findByText("Pay for your year");+ expect(api.upsertBundleQuote).not.toHaveBeenCalled();+ expect(api.createBundleStripeQuote).not.toHaveBeenCalled();++ fireEvent.change(screen.getByPlaceholderText("e.g. Jane Smith"), {+ target: { value: "Test Buyer" },+ });+ fireEvent.click(screen.getByRole("checkbox"));+ fireEvent.click(screen.getByRole("button", { name: "Finalise" }));+ await waitFor(() =>+ expect(api.upsertBundleQuote).toHaveBeenCalledWith(+ expect.objectContaining({+ quoteId: 7,+ poolCredits: 576_000,+ priceMinor: 480_000,+ currency: "gbp",+ consented: true,+ }),+ ),+ );+ });++ it("keeps a custom credit pool after reopening and blocks an empty quantity", async () => {+ const view = showCheckout();+ fireEvent.click(await screen.findByRole("button", { name: "Other" }));+ const input = screen.getByRole("textbox", { name: "Year size" });+ fireEvent.change(input, { target: { value: "7654.32" } });+ await waitFor(() =>+ expect(+ JSON.parse(sessionStorage.getItem("payg-bundle-calc:42") ?? "{}")+ .poolCredits,+ ).toBe(765432),+ );+ view.unmount();+ showCheckout();+ expect(await screen.findByText("≈ 765,432 credits")).toBeInTheDocument();+ fireEvent.change(screen.getByRole("textbox", { name: "Year size" }), {+ target: { value: "" },+ });+ expect(+ screen.getByRole("button", { name: "Continue to payment" }),+ ).toBeDisabled();+ });+});diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsxindex 459c884dca..9eaca9d0d4 100644--- a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx@@ -16,7 +16,11 @@ import {BUNDLE_SIZE_TIERS,type BundleQuoteBreakdown,computeBundleQuote,+ bundleListMinor,+ bundlePriceMinor,formatMinor,+ formatMoneyMajor,+ currencySymbol,} from "@app/billing";import type { Wallet } from "@portal/api/billing";import {@@ -33,32 +37,9 @@ import {type BundleStripeQuote,type LatestBundleQuote,} from "@portal/billing/stripe";-import { PrepayModalHeader } from "@portal/components/billing/PrepayModalHeader";import "@portal/theme/surface.css";-/**- * Prepaid-bundle purchase modal for the Processor billing page — "12 months for- * the price of 10". Three steps inside the shared portal {@link Modal}:- *- * 1. Size your year — buyers size the purchase in PEOPLE. Team size drives an- * estimated volume (≈80 PDFs/user/mo), provisioned ~3× above expected; the- * finer settings (governance posture, file size, pipelines) scale it up. All- * local, via the shared {@code computeBundleQuote} brain.- * The calculator is the quote page: it also carries a "Download quote (PDF)"- * link, which (like Accept) mints the Stripe QUOTE lazily via- * create-payg-bundle-quote — nothing is minted just by sizing.- * 2. Review + pay — the same quote receipt card (with "Download quote (PDF)") plus recipient details- * + consent. "Finalise" accepts the quote and generates the net-terms invoice, then the step flips- * to the finalized state (Download invoice / Pay online). Paying opens Stripe's hosted invoice;- * capacity lands via the webhook on invoice.paid, never here. No separate confirmation screen.- *- * The pool is denominated in size-folded RUNS — the same currency the meter charges- * on consumption — so a flat per-run rate reproduces the marketing calculator's- * total. The run-based brain (policy-count posture, pipelines, 1¢/run, 10/12) lives- * in {@code @app/billing}, shared with the backend.- */--/** Default team size the calculator opens on. */+const DEFAULT_POOL_CREDITS = 1_200_000;const DEFAULT_USERS = 25;/**@@ -124,7 +105,8 @@ function buildStripeQuoteSig(* only the "still sizing, nothing minted yet" fallback.*/interface CalcSettings {- users: number;+ poolCredits: number;+ users: number | null;postureId: string;sizeId: string;pipelineId: string;@@ -145,8 +127,31 @@ function readCalcSettings(teamId: number): CalcSettings | null {// laundered by the ...IdFor() lookups downstream, but we default them here too).const p = JSON.parse(raw) as Partial<Record<keyof CalcSettings, unknown>>;const users = Number(p.users);- return {+ const legacy = computeBundleQuote({users: Number.isFinite(users) && users > 0 ? users : DEFAULT_USERS,+ posturePolicies: policiesFor(+ typeof p.postureId === "string" ? p.postureId : "governed",+ ),+ sizeMult: sizeMultFor(+ typeof p.sizeId === "string" ? p.sizeId : "standard",+ ),+ pipelineMult: pipelineMultFor(+ typeof p.pipelineId === "string" ? p.pipelineId : "none",+ ),+ ratePerRunMinor: null,+ });+ const poolCredits = Number(p.poolCredits);+ return {+ poolCredits:+ Number.isSafeInteger(poolCredits) && poolCredits > 0+ ? poolCredits+ : legacy.poolCredits,+ users:+ p.users == null+ ? null+ : Number.isFinite(users) && users > 0+ ? users+ : DEFAULT_USERS,postureId: typeof p.postureId === "string" ? p.postureId : "governed",sizeId: typeof p.sizeId === "string" ? p.sizeId : "standard",pipelineId: typeof p.pipelineId === "string" ? p.pipelineId : "none",@@ -209,13 +214,14 @@ export function BundleCheckoutModal({}: Props) {const { t } = useTranslation();const teamId = wallet.teamId;- const currency = wallet.currency ?? "usd";+ const walletCurrency = wallet.currency ?? "usd";// The pool is priced per size-scaled RUN at the prepaid-bundle rate (bundle:processor), NOT the// metered per-document rate — so the estimate matches the amount the checkout edge fn charges.const ratePerRunMinor = wallet.bundleRatePerCreditMinor;const [phase, setPhase] = useState<Phase>("calc");- const [users, setUsers] = useState(DEFAULT_USERS);+ const [poolCredits, setPoolCredits] = useState(DEFAULT_POOL_CREDITS);+ const [users, setUsers] = useState<number | null>(null);const [postureId, setPostureId] = useState<string>("governed");const [sizeId, setSizeId] = useState<string>("standard");const [pipelineId, setPipelineId] = useState<string>("none");@@ -250,6 +256,9 @@ export function BundleCheckoutModal({const [persistedPriceMinor, setPersistedPriceMinor] = useState<number | null>(null,);+ const [persistedCurrency, setPersistedCurrency] = useState<string | null>(+ null,+ );const [persistedPoolCredits, setPersistedPoolCredits] = useState<number | null>(null);@@ -273,7 +282,8 @@ export function BundleCheckoutModal({if (!open) {hydratedRef.current = false;setPhase("calc");- setUsers(DEFAULT_USERS);+ setPoolCredits(DEFAULT_POOL_CREDITS);+ setUsers(null);setPostureId("governed");setSizeId("standard");setPipelineId("none");@@ -287,6 +297,7 @@ export function BundleCheckoutModal({setInvoice(null);setPersistedPriceMinor(null);setPersistedPoolCredits(null);+ setPersistedCurrency(null);setBusy(false);setPdfBusy(false);setActionError(null);@@ -309,13 +320,15 @@ export function BundleCheckoutModal({if (latest) {// Resume the existing quote: restore its sizing + consent + id (landing on the calculator), and// relink any already-minted Stripe quote so Download/Accept reuse it rather than minting anew.- setUsers(latest.users ?? DEFAULT_USERS);+ setPoolCredits(latest.poolCredits);+ setUsers(latest.users);setPostureId(postureIdFor(latest.posturePolicies));setSizeId(sizeIdFor(latest.sizeMult));setPipelineId(pipelineIdFor(latest.pipelineMult));setConsented(latest.consentedAt != null);setQuoteId(latest.quoteId);setPersistedPriceMinor(latest.priceMinor);+ setPersistedCurrency(latest.currency);setPersistedPoolCredits(latest.poolCredits);if (saved?.poNumber) setPoNumber(saved.poNumber);if (saved?.companyName) setCompanyName(saved.companyName);@@ -354,6 +367,7 @@ export function BundleCheckoutModal({}}} else if (saved) {+ setPoolCredits(saved.poolCredits);setUsers(saved.users);setPostureId(saved.postureId);setSizeId(saved.sizeId);@@ -376,6 +390,7 @@ export function BundleCheckoutModal({useEffect(() => {if (!open || teamId == null || !hydratedRef.current) return;writeCalcSettings(teamId, {+ poolCredits,users,postureId,sizeId,@@ -388,6 +403,7 @@ export function BundleCheckoutModal({}, [open,teamId,+ poolCredits,users,postureId,sizeId,@@ -398,22 +414,41 @@ export function BundleCheckoutModal({consented,]);- const quote = useMemo(- () =>- computeBundleQuote({- users,- posturePolicies: policiesFor(postureId),- sizeMult: sizeMultFor(sizeId),- pipelineMult: pipelineMultFor(pipelineId),- ratePerRunMinor,- }),- [users, postureId, sizeId, pipelineId, ratePerRunMinor],- );+ const quote = useMemo<BundleQuoteBreakdown>(() => {+ const listMinor = bundleListMinor(poolCredits, ratePerRunMinor);+ const priceMinor = bundlePriceMinor(poolCredits, ratePerRunMinor);+ return {+ expectedMonthlyVolume: Math.round(poolCredits / 12),+ provisionedMonthlyVolume: Math.round(poolCredits / 12),+ poolCredits,+ listMinor,+ priceMinor,+ savingsMinor:+ listMinor != null && priceMinor != null ? listMinor - priceMinor : null,+ overEnterprise: false,+ };+ }, [poolCredits, ratePerRunMinor]);- // The receipt shows the persisted (server) total on resume so it matches the quote the buyer- // created, not a figure recomputed from a since-changed rate — but only while the sizing is- // unchanged (same pool). Editing the calculator changes the pool and reverts to the live estimate.- // savings tracks whichever total is shown so the receipt stays internally consistent.+ const currency =+ persistedPoolCredits === poolCredits+ ? (persistedCurrency ?? walletCurrency)+ : walletCurrency;++ function changePool(credits: number) {+ const next = Number.isSafeInteger(credits) && credits > 0 ? credits : 0;+ if (next === poolCredits) return;+ setStripeQuoteSig(null);+ setPersistedPriceMinor(null);+ setPersistedPoolCredits(null);+ setPersistedCurrency(null);+ setPoolCredits(next);+ setUsers(null);+ setPostureId("essentials");+ setSizeId("compact");+ setPipelineId("none");+ }++ // A resumed quote keeps its agreed total; its original undiscounted rate is not persisted.const receiptQuote = useMemo(() => {if (persistedPriceMinor == null ||@@ -424,10 +459,8 @@ export function BundleCheckoutModal({return {...quote,priceMinor: persistedPriceMinor,- savingsMinor:- quote.listMinor != null- ? quote.listMinor - persistedPriceMinor- : quote.savingsMinor,+ listMinor: null,+ savingsMinor: null,};}, [quote, persistedPriceMinor, persistedPoolCredits]);@@ -460,12 +493,12 @@ export function BundleCheckoutModal({const q = await upsertBundleQuote({teamId,users,- posturePolicies: policiesFor(postureId),- sizeMult: sizeMultFor(sizeId),- pipelineMult: pipelineMultFor(pipelineId),+ posturePolicies: users == null ? 1 : policiesFor(postureId),+ sizeMult: users == null ? 1 : sizeMultFor(sizeId),+ pipelineMult: users == null ? 1 : pipelineMultFor(pipelineId),provisionedMonthlyVolume: quote.provisionedMonthlyVolume,poolCredits: quote.poolCredits,- priceMinor: quote.priceMinor,+ priceMinor: receiptQuote.priceMinor,currency,consented,eulaVersion: CONSENT_EULA_VERSION,@@ -723,27 +756,28 @@ export function BundleCheckoutModal({open={open}onClose={onClose}width="md"- className="portal-billing__bundle-modal portal-billing__checkout-modal--framed"+ className="portal-billing__bundle-modal portal-billing__checkout-modal--framed processor-prepay"ariaLabel={t("portal.billing.prepaid.offer.title","Get 12 months for the price of 10",)}+ title={+ resolving+ ? t("portal.billing.prepaid.buy.loadingTitle", "Loading your quote")+ : phase === "pay"+ ? t("portal.billing.prepaid.buy.payTitle", "Pay for your year")+ : t("portal.billing.prepaid.buy.creditTitle", "Prepay the year")+ }+ subtitle={+ !resolving && phase === "calc"+ ? t(+ "portal.billing.simple.prepayIntro",+ "A year of processing at a discount.",+ )+ : undefined+ }footer={resolving ? undefined : footer}>- <PrepayModalHeader- step={resolving ? undefined : phase === "pay" ? 3 : 2}- title={- resolving- ? t("portal.billing.prepaid.buy.loadingTitle", "Loading your quote")- : phase === "pay"- ? t("portal.billing.prepaid.buy.payTitle", "Pay for your year")- : t(- "portal.billing.prepaid.buy.calcTitle",- "Calculate your annual payment",- )- }- onClose={onClose}- /><div className="portal-billing__checkout-scroll">{resolving && (<div className="portal-billing__bundle-pay" aria-busy="true">@@ -754,14 +788,10 @@ export function BundleCheckoutModal({)}{!resolving && phase === "calc" && (<CalculatorStep- users={users}- setUsers={setUsers}- postureId={postureId}- setPostureId={setPostureId}- sizeId={sizeId}- setSizeId={setSizeId}- pipelineId={pipelineId}- setPipelineId={setPipelineId}+ credits={poolCredits}+ rate={ratePerRunMinor}+ selectionCurrency={walletCurrency}+ onCreditsChange={changePool}quote={receiptQuote}currency={currency}onDownload={downloadPdf}@@ -793,11 +823,6 @@ export function BundleCheckoutModal({);}-// ─── Shared: the quote receipt card ──────────────────────────────────────────-// The sized plan, its price + savings, the credit pool, and a shareable proforma download. Shown on both-// the calculator step and the payment step (so the buyer can review + download the quote before/after-// finalizing it).-function QuoteReceipt({quote,currency,@@ -812,337 +837,92 @@ function QuoteReceipt({}) {const { t } = useTranslation();return (- <div className="portal-billing__bundle-receipt">- <div className="portal-billing__bundle-receipt-row portal-billing__bundle-receipt-row--head">- <span>- {t("portal.billing.prepaid.calc.handlesLabel", "Your Processor")}- </span>- <strong>- {t(- "portal.billing.prepaid.calc.handlesValue",- "handles {{volume}} credits / mo",- { volume: quote.provisionedMonthlyVolume.toLocaleString() },- )}- </strong>- </div>- {quote.priceMinor != null ? (- <>+ <>+ <div className="portal-billing__bundle-receipt processor-prepay__receipt">+ {quote.listMinor != null && (<div className="portal-billing__bundle-receipt-row"><span>- {t(- "portal.billing.prepaid.calc.priceLabel",- "Your year · 12 months for the price of 10",- )}+ {t("portal.billing.simple.yearValue", "A year of processing")}</span>- <strong className="portal-billing__bundle-receipt-price">- {formatMinor(quote.priceMinor, currency)}- </strong>+ <strong>{formatMinor(quote.listMinor, currency)}</strong></div>- {quote.savingsMinor != null && quote.savingsMinor > 0 && (- <p className="portal-billing__bundle-savings">+ )}+ {quote.savingsMinor != null && quote.savingsMinor > 0 && (+ <div className="portal-billing__bundle-receipt-row">+ <span>{t(- "portal.billing.prepaid.calc.savings",- "You save {{amount}} · 2 months free.",- { amount: formatMinor(quote.savingsMinor, currency) },+ "portal.billing.simple.prepayDiscount",+ "Prepay discount · 12 for 10",)}- </p>- )}- </>- ) : (- <p className="portal-billing__bundle-savings">- {t(- "portal.billing.prepaid.calc.rateUnknown",- "We'll show the exact price at checkout.",- )}- </p>- )}- {quote.poolCredits > 0 && (- <p className="portal-billing__bundle-pool">- {t(- "portal.billing.prepaid.calc.poolCaption",- "One pool of {{credits}} credits for the year. Heavy months borrow from light ones.",- { credits: quote.poolCredits.toLocaleString() },- )}- </p>- )}- {quote.poolCredits > 0 && (- <div- role="button"- tabIndex={0}- aria-disabled={downloading}- className="portal-billing__bundle-download"- onClick={onDownload}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- onDownload();- }- }}- >- <svg- width="13"- height="13"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden- >- <path d="M12 3v12m0 0l-4-4m4 4l4-4M4 21h16" />- </svg>- {downloading- ? t("portal.billing.prepaid.review.downloading", "Preparing…")- : t(- "portal.billing.prepaid.review.download",- "Download quote (PDF)",- )}- {!downloading && (- <span className="portal-billing__bundle-download-share">- · {t("portal.billing.prepaid.review.share", "share for approval")}</span>- )}+ <strong className="processor-prepay__saving">+ −{formatMinor(quote.savingsMinor, currency)}+ </strong>+ </div>+ )}+ <div className="portal-billing__bundle-receipt-row">+ <strong>{t("payment.capacityStage.dueToday", "Due today")}</strong>+ <strong>+ {quote.priceMinor == null+ ? t(+ "portal.billing.prepaid.calc.rateUnknown",+ "We'll show the exact price at checkout.",+ )+ : formatMinor(quote.priceMinor, currency)}+ </strong></div>- )}- </div>+ </div>+ <Button+ variant="quiet"+ size="sm"+ disabled={downloading || quote.poolCredits <= 0}+ onClick={onDownload}+ >+ {downloading+ ? t("portal.billing.prepaid.review.downloading", "Preparing…")+ : t("portal.billing.prepaid.review.download", "Download quote (PDF)")}+ </Button>+ </>);}-// ─── Step 1: users-first calculator ──────────────────────────────────────────--interface CalcProps {- users: number;- setUsers: (v: number) => void;- postureId: string;- setPostureId: (v: string) => void;- sizeId: string;- setSizeId: (v: string) => void;- pipelineId: string;- setPipelineId: (v: string) => void;- quote: BundleQuoteBreakdown;- currency: string;- /** Mint-if-needed + stream the Stripe quote PDF. */- onDownload: () => void;- /** PDF download in flight. */- downloading: boolean;- /** Last Download error, surfaced inline. */- actionError: string | null;-}--interface PickerCard {- id: string;- title: string;- meta?: string;- desc: string;-}-function CalculatorStep({- users,- setUsers,- postureId,- setPostureId,- sizeId,- setSizeId,- pipelineId,- setPipelineId,+ credits,+ rate,+ selectionCurrency,+ onCreditsChange,quote,currency,onDownload,downloading,actionError,-}: CalcProps) {+}: {+ credits: number;+ rate: number | null;+ selectionCurrency: string;+ onCreditsChange: (credits: number) => void;+ quote: BundleQuoteBreakdown;+ currency: string;+ onDownload: () => void;+ downloading: boolean;+ actionError: string | null;+}) {const { t } = useTranslation();- // Deployment is a display-only finer setting (same rate self-serve); expanded- // tracks which row's card picker is bloomed (demo: one open at a time).- const [deployId, setDeployId] = useState<string>("cloud");- const [expanded, setExpanded] = useState<string | null>(null);-- const deployCards: PickerCard[] = [- {- id: "cloud",- title: t("portal.billing.prepaid.deploy.cloud", "Stirling Cloud"),- desc: t(- "portal.billing.prepaid.deploy.cloudDesc",- "Managed by Stirling. Live in minutes.",- ),- },- {- id: "selfhost",- title: t("portal.billing.prepaid.deploy.selfhost", "Self-hosted"),- desc: t(- "portal.billing.prepaid.deploy.selfhostDesc",- "Runs on private infrastructure. Same rate.",- ),- },- ];- const sizeCards: PickerCard[] = [- {- id: "compact",- title: t("portal.billing.prepaid.size.compact", "Compact"),- meta: "×1",- desc: t(- "portal.billing.prepaid.size.compactDesc",- "Files under 25 MB, no data charges",- ),- },- {- id: "standard",- title: t("portal.billing.prepaid.size.standard", "Standard"),- meta: "×1.2",- desc: t(- "portal.billing.prepaid.size.standardDesc",- "Mostly small, some scans past 25 MB",- ),- },- {- id: "heavy",- title: t("portal.billing.prepaid.size.heavy", "Heavy"),- meta: "×2",- desc: t(- "portal.billing.prepaid.size.heavyDesc",- "Scanned or image-heavy, routinely 50 MB+",- ),- },- ];- const postureCards: PickerCard[] = [- {- id: "essentials",- title: t("portal.billing.prepaid.posture.essentials", "Essentials"),- meta: t(- "portal.billing.prepaid.calc.policiesMeta",- "{{count}} policies",- {- count: 2,- },- ),- desc: t(- "portal.billing.prepaid.posture.essentialsDesc",- "Classification, the default, plus Sharing",- ),- },- {- id: "governed",- title: t("portal.billing.prepaid.posture.governed", "Governed"),- meta: t(- "portal.billing.prepaid.calc.policiesMeta",- "{{count}} policies",- {- count: 4,- },- ),- desc: t(- "portal.billing.prepaid.posture.governedDesc",- "Adds Security and Routing",- ),- },- {- id: "regulated",- title: t("portal.billing.prepaid.posture.regulated", "Regulated"),- meta: t(- "portal.billing.prepaid.calc.policiesMeta",- "{{count}} policies",- {- count: 7,- },- ),- desc: t(- "portal.billing.prepaid.posture.regulatedDesc",- "Every category, incl. Compliance, Retention, Ingestion",- ),- },- ];- const pipelineCards: PickerCard[] = [- {- id: "none",- title: t("portal.billing.prepaid.pipelines.none", "None"),- desc: t(- "portal.billing.prepaid.pipelines.noneDesc",- "Not running pipelines yet. Turn them on any time.",- ),- },- {- id: "standard",- title: t("portal.billing.prepaid.pipelines.standard", "Standard"),- desc: t(- "portal.billing.prepaid.pipelines.standardDesc",- "A few pipelines re-process arriving PDFs.",- ),- },- {- id: "advanced",- title: t("portal.billing.prepaid.pipelines.advanced", "Advanced"),- desc: t(- "portal.billing.prepaid.pipelines.advancedDesc",- "Pipelines drive most of your processing.",- ),- },- ];-- const find = (cards: PickerCard[], id: string) =>- cards.find((c) => c.id === id) ?? cards[0];- const size = find(sizeCards, sizeId);- const posture = find(postureCards, postureId);- const pipeline = find(pipelineCards, pipelineId);- const policies =- BUNDLE_POLICY_POSTURES.find((p) => p.id === postureId)?.policies ?? 0;-- const deployValue =- deployId === "cloud"- ? t(- "portal.billing.prepaid.deploy.cloudValue",- "Stirling Cloud · Managed",- )- : t(- "portal.billing.prepaid.deploy.selfhostValue",- "Self-hosted · Private infrastructure",- );- const sizeValue = t(- "portal.billing.prepaid.calc.sizingValue",- "{{label}} · {{desc}}",- { label: size.title, desc: size.desc },+ const presets = [12_000, 24_000, 48_000];+ const yearValue = rate && rate > 0 ? Math.round(credits * rate) / 100 : null;+ const [custom, setCustom] = useState(+ yearValue == null || !presets.includes(yearValue),);- const postureValue = t(- "portal.billing.prepaid.calc.governanceValue",- "{{label}} · {{count}} policies",- { label: posture.title, count: policies },- );-- const rows = [- {- id: "deploy",- label: t("portal.billing.prepaid.calc.deployRow", "Deployment"),- value: deployValue,- cards: deployCards,- activeId: deployId,- onPick: setDeployId,- },- {- id: "size",- label: t("portal.billing.prepaid.calc.sizingRow", "Sizing"),- value: sizeValue,- cards: sizeCards,- activeId: sizeId,- onPick: setSizeId,- },- {- id: "posture",- label: t("portal.billing.prepaid.calc.governanceRow", "Governance"),- value: postureValue,- cards: postureCards,- activeId: postureId,- onPick: setPostureId,- },- {- id: "pipes",- label: t("portal.billing.prepaid.calc.pipelinesLabel", "Pipelines"),- value: pipeline.title,- cards: pipelineCards,- activeId: pipelineId,- onPick: setPipelineId,- },- ];-+ const [draft, setDraft] = useState<number | string>(yearValue ?? "");+ const changeAmount = (value: number | string) => {+ setDraft(value);+ const amount = Number(value);+ onCreditsChange(+ rate && rate > 0 && Number.isFinite(amount) && amount > 0+ ? Math.round((amount * 100) / rate)+ : 0,+ );+ };return (<div className="portal-billing__bundle-calc">{actionError && (@@ -1156,131 +936,80 @@ function CalculatorStep({{actionError}</Banner>)}- <div className="portal-billing__bundle-field">- <div className="portal-billing__bundle-field-label">- {t("portal.billing.prepaid.calc.usersLabel", "Total users")}- </div>- <div className="portal-billing__bundle-users">- <NumberInput- value={users}- onChange={(v) => setUsers(typeof v === "number" ? v : 0)}- min={0}- step={1}- allowNegative={false}- aria-label={t(- "portal.billing.prepaid.calc.usersLabel",- "Total users",- )}- />+ <div className="processor-prepay__picker">+ <div+ className="processor-prepay__choices"+ role="group"+ aria-label={t("portal.billing.simple.yearSize", "Year size")}+ >+ <span>{t("portal.billing.simple.yearSize", "Year size")}</span>+ {presets.map((value) => (+ <Button+ key={value}+ variant="secondary"+ disabled={!rate || rate <= 0}+ aria-pressed={!custom && yearValue === value}+ onClick={() => {+ setCustom(false);+ changeAmount(value);+ }}+ >+ {formatMoneyMajor(value, selectionCurrency)}+ </Button>+ ))}+ <Button+ variant="secondary"+ aria-pressed={custom}+ disabled={!rate || rate <= 0}+ onClick={() => {+ setDraft(yearValue ?? "");+ setCustom(true);+ }}+ >+ {t("payment.capacityStage.other", "Other")}+ </Button></div>+ {custom && rate != null && rate > 0 && (+ <div className="processor-prepay__custom">+ <NumberInput+ value={draft}+ onChange={changeAmount}+ hideControls+ clampBehavior="none"+ prefix={currencySymbol(selectionCurrency)}+ decimalScale={2}+ allowNegative={false}+ aria-label={t("portal.billing.simple.yearSize", "Year size")}+ />+ </div>+ )}</div>-- {/* Finer settings as progressive-disclosure rows — a "Change" blooms the card picker. */}- <div className="portal-surface portal-billing__bundle-rows">- {rows.map((row) => {- const open = expanded === row.id;- return (- <div key={row.id} className="portal-billing__bundle-row">- <div- role="button"- tabIndex={0}- className="portal-billing__bundle-row-head"- aria-expanded={open}- onClick={() => setExpanded(open ? null : row.id)}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- setExpanded(open ? null : row.id);- }- }}- >- <span className="portal-billing__bundle-row-label">- {row.label}- </span>- <span className="portal-billing__bundle-row-value">- {row.value}- <span className="portal-billing__bundle-row-change">- {open- ? t("portal.billing.prepaid.calc.done", "Done")- : t("portal.billing.prepaid.calc.change", "Change")}- </span>- </span>- </div>- {open && (- <div className="portal-billing__bundle-row-body">- <div className="portal-billing__bundle-cards">- {row.cards.map((card) => {- const active = card.id === row.activeId;- const pick = () => {- row.onPick(card.id);- setExpanded(null);- };- return (- <div- key={card.id}- role="button"- tabIndex={0}- aria-pressed={active}- className={- "portal-billing__bundle-card" +- (active- ? " portal-billing__bundle-card--active"- : "")- }- onClick={pick}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- pick();- }- }}- >- <span className="portal-billing__bundle-card-head">- <span className="portal-billing__bundle-card-title">- {card.title}- </span>- {card.meta && (- <span className="portal-billing__bundle-card-meta">- {card.meta}- </span>- )}- </span>- <span className="portal-billing__bundle-card-desc">- {card.desc}- </span>- </div>- );- })}- </div>- </div>- )}- </div>- );+ <p className="processor-prepay__credits">+ {t("portal.billing.simple.creditEstimate", "≈ {{credits}} credits", {+ credits: quote.poolCredits.toLocaleString(),})}- </div>-- {/* Receipt — the sized plan, its price, the credit pool, and a shareable proforma. */}+ </p><QuoteReceiptquote={quote}currency={currency}onDownload={onDownload}downloading={downloading}/>-- {quote.overEnterprise && (- <p className="portal-billing__bundle-savings">+ <div className="processor-prepay__after">+ <strong>+ {t("portal.billing.simple.afterYear", "After the year")}+ </strong>+ <p>{t(- "portal.billing.prepaid.calc.enterpriseHint",- "This is enterprise scale. At this volume, enterprise rates beat any self-serve discount. Rate lock, terms, and a quote in minutes.",+ "portal.billing.simple.afterYearNote",+ "No automatic renewal. Further processing needs an active metered plan and stays within its spend limit.",)}</p>- )}+ </div></div>);}-// ─── Step 2: pay for your year (quote already accepted → PO · download · pay) ──-function PaymentStep({quote,currency,diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.test.tsxindex 80ab4bd27f..7bcc11cb16 100644--- a/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx+++ b/frontend/editor/src/portal/components/billing/FreePlanView.test.tsx@@ -65,10 +65,10 @@ describe("Processor activation navigation", () => {</MantineProvider>,);fireEvent.click(await screen.findByRole("button", { name: "Back" }));- fireEvent.click(screen.getByRole("button", { name: "Pay as you go" }));+ fireEvent.click(screen.getByRole("button", { name: "Change" }));const limit = screen.getByRole("textbox", { name: "Monthly spend limit" });fireEvent.change(limit, { target: { value: "250" } });- expect(limit).toHaveValue("250");+ expect(limit).toHaveValue("$250");expect(api.cancelBundleQuote).not.toHaveBeenCalled();expect(api.acceptBundleStripeQuote).not.toHaveBeenCalled();expect(api.createCheckoutSession).not.toHaveBeenCalled();@@ -81,12 +81,8 @@ describe("Processor activation navigation", () => {</MantineProvider>,);fireEvent.click(await screen.findByRole("button", { name: "Back" }));- fireEvent.click(screen.getByRole("button", { name: "Pay as you go" }));- fireEvent.click(screen.getByRole("button", { name: "Back" }));- fireEvent.click(screen.getByRole("button", { name: "Prepay a year" }));- expect(- await screen.findByText("Calculate your annual payment"),- ).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Buy credits" }));+ expect(await screen.findByText("Prepay the year")).toBeInTheDocument();expect(api.getLatestBundleQuote).toHaveBeenCalledTimes(2);expect(api.cancelBundleQuote).not.toHaveBeenCalled();expect(api.createBundleStripeQuote).not.toHaveBeenCalled();diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsxindex d4c074790d..e50ce5e382 100644--- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx+++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx@@ -4,7 +4,6 @@ import { Banner } from "@app/ui";import type { Wallet } from "@portal/api/billing";import type { SaasCurrency } from "@portal/billing/stripe";import { StripeCheckoutModal } from "@portal/components/billing/StripeCheckoutModal";-import { ActivationChoiceModal } from "@portal/components/billing/ActivationChoiceModal";import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";import { PrepaidCapacityCard } from "@portal/components/billing/PrepaidCapacityCard";@@ -40,8 +39,6 @@ export function FreePlanView({onActivationClosed,}: Props) {const { t } = useTranslation();- // Activation fork (demo D97): choose → the metered checkout (payg) or the- // discounted bundle (prepay). Exactly one is open at a time.const [ownStep, setOwnStep] = useState<"choose" | "payg" | "prepay" | null>(null,);@@ -103,18 +100,11 @@ export function FreePlanView({{missingTeam}</Banner>)}- <ActivationChoiceModal- open={step === "choose"}- onClose={closeModals}- onChoosePayg={() => setStep("payg")}- onChoosePrepay={() => setStep("prepay")}- />-{wallet.teamId != null && (<StripeCheckoutModal- open={step === "payg"}+ open={step === "payg" || step === "choose"}onClose={closeModals}- onBack={() => setStep("choose")}+ onPrepay={() => setStep("prepay")}teamId={wallet.teamId}currency={currency}pricePerDocMinor={wallet.pricePerDocMinor}@@ -133,7 +123,7 @@ export function FreePlanView({<BundleCheckoutModalopen={step === "prepay"}onClose={closeModals}- onBack={() => setStep("choose")}+ onBack={() => setStep("payg")}wallet={wallet}onComplete={() => {closeModals();diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsxindex 95a9cff169..97eec5c0b1 100644--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx@@ -346,20 +346,20 @@ describe("PortalBillingGate — self-hosted", () => {expect(applyLinkFacts).not.toHaveBeenCalled();});- it("prompts once for a procurement link and preserves it when linking completes", () => {- gate.gated = true;- const view = render(- <GateTree entry="/settings/billing?procurement=start" />,- );- expect(connect).toHaveBeenCalledTimes(1);- view.rerender(<GateTree entry="/settings/billing?procurement=start" />);- expect(connect).toHaveBeenCalledTimes(1);- link.is = true;- gate.gated = false;- view.rerender(<GateTree entry="/settings/billing?procurement=start" />);- expect(screen.getByTestId("usage")).toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent(- "/settings/billing?procurement=start",- );- });+ it.each(["procurement=start", "upgrade=team"])(+ "prompts once for %s and preserves it when linking completes",+ (intent) => {+ gate.gated = true;+ const entry = `/settings/billing?${intent}`;+ const view = render(<GateTree entry={entry} />);+ expect(connect).toHaveBeenCalledTimes(1);+ view.rerender(<GateTree entry={entry} />);+ expect(connect).toHaveBeenCalledTimes(1);+ link.is = true;+ gate.gated = false;+ view.rerender(<GateTree entry={entry} />);+ expect(screen.getByTestId("usage")).toBeInTheDocument();+ expect(screen.getByTestId("location")).toHaveTextContent(entry);+ },+ );});diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsxindex 077cbd97f4..9d49a4bf25 100644--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx@@ -31,22 +31,25 @@ export function PortalBillingGate() {const {serverPlan,usersInUse,+ userLimit,loading: licenseLoading,} = useServerPlan(isOwner);const serverPlanAction = serverPlan ? <ManageBillingButton /> : undefined;const link = useLinkOptional();const [searchParams] = useSearchParams();const prompted = useRef(false);- const procurementRequested =- trialSetupRequested || searchParams.get("procurement") === "start";+ const accountLinkRequested =+ trialSetupRequested ||+ searchParams.get("procurement") === "start" ||+ searchParams.get("upgrade") === "team";useEffect(() => {- if (!procurementRequested || link?.isLinked) prompted.current = false;+ if (!accountLinkRequested || link?.isLinked) prompted.current = false;else if (isOwner && !loading && gated && !prompted.current) {prompted.current = true;connect();}- }, [procurementRequested, link?.isLinked, isOwner, loading, gated, connect]);+ }, [accountLinkRequested, link?.isLinked, isOwner, loading, gated, connect]);const onWalletLoaded = useCallback((w: Wallet) => applyLinkFacts(true, w.status === "subscribed"),@@ -72,6 +75,7 @@ export function PortalBillingGate() {return (<UsagelocalUsersInUse={usersInUse}+ localUserLimit={userLimit}serverPlan={serverPlan}serverPlanAction={serverPlanAction}onWalletLoaded={onWalletLoaded}diff --git a/frontend/editor/src/portal/components/billing/ProcessorSpendFields.tsx b/frontend/editor/src/portal/components/billing/ProcessorSpendFields.tsxnew file mode 100644index 0000000000..f21f4d0fae--- /dev/null+++ b/frontend/editor/src/portal/components/billing/ProcessorSpendFields.tsx@@ -0,0 +1,101 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Button, NumberInput } from "@app/ui";+import {+ currencySymbol,+ formatMinor,+ formatMoneyMajor,+} from "@app/billing/format";++/** The monthly ceiling is separate from the per-credit rate; null is explicitly uncapped. */+export function ProcessorSpendFields({+ value,+ onChange,+ currency,+ rate,+ disabled = false,+}: {+ value: number | null;+ onChange: (value: number | null) => void;+ currency: string;+ rate: number | null;+ disabled?: boolean;+}) {+ const { t } = useTranslation();+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState<number | string>(value ?? "");+ return (+ <div className="processor-spend-fields">+ <div className="processor-spend-fields__row">+ <span>{t("portal.billing.simple.credits", "Credits")}</span>+ <strong>+ {rate == null+ ? t("portal.billing.simple.ratePending", "Rate shown at checkout")+ : t(+ "portal.billing.simple.rate",+ "{{rate}} each · billed as used",+ { rate: formatMinor(rate, currency) },+ )}+ </strong>+ </div>+ <div className="processor-spend-fields__row">+ <span>+ {t(+ "portal.billing.simple.limit",+ "Spend limit · processing pauses here",+ )}+ </span>+ <div className="processor-spend-fields__value">+ <strong>+ {value == null+ ? t("payg.cap.noCapLabel", "No cap")+ : t("portal.billing.simple.monthlyAmount", "{{amount}}/mo", {+ amount: formatMoneyMajor(value, currency),+ })}+ </strong>+ <Button+ variant="quiet"+ disabled={disabled}+ onClick={() => {+ setDraft(value ?? "");+ setEditing(!editing);+ }}+ >+ {t("common.change", "Change")}+ </Button>+ </div>+ </div>+ {editing && (+ <div className="processor-spend-fields__edit">+ <NumberInput+ aria-label={t(+ "portal.billing.checkout.cap.amountAria",+ "Monthly spend limit",+ )}+ value={draft}+ prefix={currencySymbol(currency)}+ hideControls+ clampBehavior="none"+ allowNegative={false}+ decimalScale={2}+ disabled={disabled}+ onChange={(next) => {+ setDraft(next);+ onChange(next === "" ? 0 : Number(next));+ }}+ />+ <Button+ variant="quiet"+ disabled={disabled}+ onClick={() => {+ onChange(null);+ setEditing(false);+ }}+ >+ {t("payg.cap.noCapLabel", "No cap")}+ </Button>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/editor/src/portal/components/billing/SpendLimitCard.tsx b/frontend/editor/src/portal/components/billing/SpendLimitCard.tsxindex 671cb46aa7..7fb32a303a 100644--- a/frontend/editor/src/portal/components/billing/SpendLimitCard.tsx+++ b/frontend/editor/src/portal/components/billing/SpendLimitCard.tsx@@ -3,7 +3,6 @@ import { useTranslation } from "react-i18next";import { Banner, Button, Card } from "@app/ui";import {currencySymbol,- docCapForMoney,formatMinor,formatMoneyMajor,MeterBar,@@ -136,7 +135,7 @@ export function SpendLimitCard({<SharedSpendCapControlcapUsd={draftCap}onChange={setDraftCap}- pricePerDocMinor={wallet.pricePerDocMinor}+ disabled={saving}currency={wallet.currency}note={t("portal.billing.spendLimit.capControlNote",@@ -161,15 +160,12 @@ export function SpendLimitCard({</Button>)}- <div className="portal-billing__guardrail">- <strong>- {t("portal.billing.spendLimit.guardrailLabel", "Your guardrail:")}- </strong>{" "}+ <p className="portal-billing__section-sub">{t(- "portal.billing.spendLimit.guardrailBody",- "a hard ceiling — you're never billed past it. At the cap, metered processing pauses (unlimited PDF editing keeps working) until you raise it or the cycle resets. Nothing is lost.",+ "portal.billing.spendLimit.pauseNote",+ "Metered processing pauses at your limit. PDF editing remains available.",)}- </div>+ </p>{error && (<Banner@@ -187,6 +183,7 @@ export function SpendLimitCard({<Buttonvariant="secondary"size="sm"+ disabled={saving}onClick={() => onAdjustingChange(false)}>{t("portal.billing.spendLimit.cancel", "Cancel")}@@ -205,7 +202,6 @@ export function SpendLimitCard({const capActive = !wallet.noCap && wallet.capUsd != null;const { state, pct } = meterState(spentMinor / 100, cap);const remainingMinor = Math.max(0, Math.round(cap * 100) - spentMinor);- const docEstimate = docCapForMoney(wallet.capUsd, wallet.pricePerDocMinor);const spentLabel = formatMinor(spentMinor, wallet.currency);return (@@ -243,15 +239,7 @@ export function SpendLimitCard({}capSuffix={capActive- ? docEstimate != null- ? t(- "portal.billing.spendLimit.capSuffixWithDocs",- "/ month · ≈ {{documents}} documents",- {- documents: docEstimate.toLocaleString(),- },- )- : t("portal.billing.spendLimit.capSuffix", "/ month")+ ? t("portal.billing.spendLimit.capSuffix", "/ month"): t("portal.billing.spendLimit.noCap", "no cap")}statusLabel={diff --git a/frontend/editor/src/portal/components/billing/SpendLimitModal.test.tsx b/frontend/editor/src/portal/components/billing/SpendLimitModal.test.tsxnew file mode 100644index 0000000000..06c06bf6b9--- /dev/null+++ b/frontend/editor/src/portal/components/billing/SpendLimitModal.test.tsx@@ -0,0 +1,94 @@+import { MantineProvider } from "@mantine/core";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { SpendLimitModal } from "@portal/components/billing/SpendLimitModal";+import { StripeCheckoutModal } from "@portal/components/billing/StripeCheckoutModal";+import { subscribedWallet } from "@app/billing/walletFixtures";++const updateCap = vi.hoisted(() => vi.fn());+vi.mock("@portal/api/billing", () => ({ updateCap }));+vi.mock("@portal/billing/stripe", () => ({+ getStripePublishableKey: () => null,+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, fallback: string, values?: Record<string, unknown>) =>+ fallback.replace(/{{(.*?)}}/g, (_, key: string) =>+ String(values?.[key] ?? ""),+ ),+ }),+}));++describe("Processor spend limit", () => {+ beforeEach(() => {+ updateCap.mockReset().mockResolvedValue(undefined);+ });++ it("keeps custom decimals editable, blocks an empty value and saves the chosen limit", async () => {+ const onClose = vi.fn();+ const onWalletChange = vi.fn();+ render(+ <MantineProvider>+ <SpendLimitModal+ open+ wallet={subscribedWallet}+ onClose={onClose}+ onWalletChange={onWalletChange}+ />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Change" }));+ const input = screen.getByRole("textbox", { name: "Monthly spend limit" });+ fireEvent.change(input, { target: { value: "" } });+ expect(screen.getByRole("button", { name: "Save limit" })).toBeDisabled();+ expect(updateCap).not.toHaveBeenCalled();+ fireEvent.change(input, { target: { value: "125.50" } });+ expect(input).toHaveValue("$125.50");+ fireEvent.click(screen.getByRole("button", { name: "Save limit" }));+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ expect(updateCap).toHaveBeenCalledWith(125.5);+ expect(onWalletChange).toHaveBeenCalledOnce();+ });++ it("only saves an uncapped limit after explicitly selecting it", async () => {+ render(+ <MantineProvider>+ <SpendLimitModal open wallet={subscribedWallet} onClose={() => {}} />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Change" }));+ fireEvent.click(screen.getByRole("button", { name: "No cap" }));+ fireEvent.click(screen.getByRole("button", { name: "Save limit" }));+ await waitFor(() => expect(updateCap).toHaveBeenCalledWith(null));+ });++ it("retains the dialog and chosen amount when saving fails", async () => {+ updateCap.mockRejectedValue(new Error("Unavailable"));+ const onClose = vi.fn();+ render(+ <MantineProvider>+ <SpendLimitModal open wallet={subscribedWallet} onClose={onClose} />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Save limit" }));+ expect(await screen.findByText("Couldn't save limit")).toBeInTheDocument();+ expect(onClose).not.toHaveBeenCalled();+ });++ it("keeps an explicitly uncapped value when opening Processor signup", () => {+ render(+ <MantineProvider>+ <StripeCheckoutModal+ open+ teamId={42}+ currency="usd"+ initialCapUsd={null}+ onClose={() => {}}+ onComplete={async () => false}+ />+ </MantineProvider>,+ );+ expect(screen.getByText("No cap")).toBeInTheDocument();+ expect(updateCap).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/portal/components/billing/SpendLimitModal.tsx b/frontend/editor/src/portal/components/billing/SpendLimitModal.tsxindex 48059e77bc..1ddcacddba 100644--- a/frontend/editor/src/portal/components/billing/SpendLimitModal.tsx+++ b/frontend/editor/src/portal/components/billing/SpendLimitModal.tsx@@ -1,20 +1,10 @@+import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import { Modal } from "@app/ui";-import type { Wallet } from "@portal/api/billing";-import { SpendLimitCard } from "@portal/components/billing/SpendLimitCard";-import { PrepaidCapacityCard } from "@portal/components/billing/PrepaidCapacityCard";+import { Banner, Button, Modal } from "@app/ui";+import { updateCap, type Wallet } from "@portal/api/billing";+import { ProcessorSpendFields } from "@portal/components/billing/ProcessorSpendFields";-/**- * The spend limit, as a dialog opened from the Processor row's own door.- *- * <p>A dialog rather than a panel below the page because the row states the limit already: an- * editor sitting under the enterprise band is both a second copy of that fact and a control a- * long way from the thing it edits.- *- * <p>Prepaid capacity rides along because it is the other answer to the same question. A buyer- * who came here to raise a ceiling is the buyer for whom paying up front is cheaper, and the- * offer has nowhere else to live now that the page carries no cards.- */+/** Changes the existing ceiling without opening another checkout. */export function SpendLimitModal({open,onClose,@@ -26,29 +16,82 @@ export function SpendLimitModal({onClose: () => void;wallet: Wallet;onWalletChange?: () => void;- /** Leader-only: opens the bundle checkout. Omit for members, who see no offer. */onBuyBundle?: () => void;}) {const { t } = useTranslation();- const title = t(- "portal.billing.spendLimitModal.title",- "Monthly spend limit",+ const [draft, setDraft] = useState<number | null>(+ wallet.noCap ? null : wallet.capUsd,);-+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState(false);+ useEffect(() => {+ if (open) {+ setDraft(wallet.noCap ? null : wallet.capUsd);+ setError(false);+ }+ }, [open, wallet.noCap, wallet.capUsd]);+ async function save() {+ setSaving(true);+ setError(false);+ try {+ await updateCap(draft);+ onWalletChange?.();+ onClose();+ } catch {+ setError(true);+ } finally {+ setSaving(false);+ }+ }return (- <Modal open={open} onClose={onClose} width="md" ariaLabel={title}>- <div className="portal-billing__stack">- <SpendLimitCard- wallet={wallet}- onWalletChange={onWalletChange}- adjusting- // The card's own cancel and save both settle to "not adjusting", which is this- // dialog's close.- onAdjustingChange={(adjusting) => {- if (!adjusting) onClose();- }}+ <Modal+ open={open}+ onClose={onClose}+ width="md"+ className="processor-checkout--simple processor-spend-modal"+ title={t("portal.billing.simple.setLimit", "Set a spend limit")}+ subtitle={t(+ "portal.billing.simple.limitIntro",+ "Cap what the Processor can bill each month.",+ )}+ >+ <ProcessorSpendFields+ value={draft}+ onChange={setDraft}+ currency={wallet.currency ?? "usd"}+ rate={wallet.pricePerDocMinor}+ disabled={saving}+ />+ <p className="portal-billing__checkout-finePrint">+ {t(+ "portal.billing.simple.billingNote",+ "No standing fee. Credits bill monthly as used. Cancel any time in Usage & Billing.",+ )}+ </p>+ {error && (+ <Banner+ tone="danger"+ title={t(+ "portal.billing.spendLimit.saveError",+ "Couldn't save limit",+ )}/>- <PrepaidCapacityCard wallet={wallet} onBuy={onBuyBundle} />+ )}+ <div className="portal-billing__checkout-cap-actions">+ {onBuyBundle ? (+ <Button variant="secondary" onClick={onBuyBundle} disabled={saving}>+ {t("portal.billing.spendLimit.buyCredits", "Buy credits")}+ </Button>+ ) : (+ <span />+ )}+ <Button+ onClick={save}+ loading={saving}+ disabled={draft !== null && (!Number.isFinite(draft) || draft <= 0)}+ >+ {t("portal.billing.spendLimit.save", "Save limit")}+ </Button></div></Modal>);diff --git a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsxindex faaf8664cb..ee896f28f4 100644--- a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx+++ b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx@@ -1,11 +1,6 @@import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { Banner, Button, Modal, Skeleton, Spinner } from "@app/ui";-import {- currencySymbol,- docCapForMoney,- formatMinor,-} from "@app/billing/format";import {EmbeddedCheckout,EmbeddedCheckoutProvider,@@ -18,18 +13,18 @@ import {type SaasCurrency,} from "@portal/billing/stripe";import { CardPlaceholder } from "@portal/components/billing/CardPlaceholder";+import { ProcessorSpendFields } from "@portal/components/billing/ProcessorSpendFields";import { PrepayModalHeader } from "@portal/components/billing/PrepayModalHeader";interface Props {open: boolean;onClose: () => void;- /** Return from the spend limit to the host's payment choices. */- onBack?: () => void;+ onPrepay?: () => void;/** Caller's resolved team id. The edge function needs it to scope checkout. */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. */+ /** Per-credit rate in minor currency units. */pricePerDocMinor?: number | null;/** Cap to seed the spend-limit step with; defaults to $100/mo. */initialCapUsd?: number | null;@@ -44,8 +39,7 @@ interface Props {onComplete: () => Promise<boolean>;}-/** Preset monthly caps offered on the spend-limit step (major currency units). */-const CAP_PRESETS = [50, 100, 250, 1000] as const;+/** Default monthly cap in major currency units. */const DEFAULT_CAP_USD = 100;/**@@ -108,125 +102,10 @@ function CheckoutActivationSlow({ onClose }: { onClose: () => void }) {);}-/**- * Spend-limit picker for step 1: a primary editable amount ({@code $ 100 / mo}) with quick-pick chips- * below. The amount field is the main entry — always visible, defaulted, and typeable — and clicking a- * chip (or "No cap") just writes into it. Controlled via {@code capUsd}/{@code onChange}- * (null = no cap, a number = a monthly ceiling).- */-function SpendLimitPicker({- capUsd,- onChange,- currency,- pricePerDocMinor,- presets,- disabled,-}: {- capUsd: number | null;- onChange: (v: number | null) => void;- currency: SaasCurrency;- pricePerDocMinor?: number | null;- presets: readonly number[];- disabled?: boolean;-}) {- const { t } = useTranslation();- const sym = currencySymbol(currency);- const isNoCap = capUsd === null;- // Local mirror so partial typing isn't clobbered by the controlled value; resync when not focused- // (e.g. a chip sets the amount, or an initial cap loads in).- const [text, setText] = useState(capUsd != null ? String(capUsd) : "");- const [focused, setFocused] = useState(false);- useEffect(() => {- if (!focused) setText(capUsd != null ? String(capUsd) : "");- }, [capUsd, focused]);-- const docs = docCapForMoney(capUsd, pricePerDocMinor);-- const onInput = (raw: string) => {- const cleaned = raw.replace(/[^0-9]/g, "");- setText(cleaned);- // Empty maps to 0 — the "nothing entered yet" sentinel (distinct from the explicit null "No limit").- // The parent treats 0 as incomplete and blocks Continue, so a cleared field can't become a $0 cap.- onChange(cleaned === "" ? 0 : parseInt(cleaned, 10));- };-- return (- <div className="portal-billing__caplimit">- <div- className="portal-billing__caplimit-field"- data-nocap={isNoCap ? "true" : "false"}- >- <span className="portal-billing__caplimit-sym">{sym}</span>- <input- className="portal-billing__caplimit-input"- inputMode="numeric"- value={isNoCap ? "" : text}- placeholder={- isNoCap ? t("portal.billing.checkout.cap.noLimit", "No limit") : ""- }- aria-label={t(- "portal.billing.checkout.cap.amountAria",- "Monthly spend limit",- )}- onChange={(e) => onInput(e.target.value)}- onFocus={() => setFocused(true)}- onBlur={() => setFocused(false)}- disabled={disabled}- />- <span className="portal-billing__caplimit-suffix">- {t("portal.billing.checkout.cap.perMonth", "/ mo")}- </span>- </div>-- <div className="portal-billing__caplimit-chips">- {presets.map((p) => (- <Button- key={p}- type="button"- variant="quiet"- className="portal-billing__caplimit-chip"- data-selected={capUsd === p ? "true" : "false"}- onClick={() => onChange(p)}- disabled={disabled}- >- {sym}- {p.toLocaleString()}- </Button>- ))}- <Button- type="button"- variant="quiet"- className="portal-billing__caplimit-chip"- data-selected={isNoCap ? "true" : "false"}- onClick={() => onChange(null)}- disabled={disabled}- >- {t("payg.cap.noCapLabel", "No cap")}- </Button>- </div>-- {docs != null && (- <div className="portal-billing__caplimit-estimate">- <span className="portal-billing__caplimit-estimate-main">- {t("payg.cap.docsEstimate", "≈ {{docs}} credits / month", {- docs: docs.toLocaleString(),- })}- </span>- <span className="portal-billing__caplimit-estimate-sub">- {t("payg.cap.docsRate", "at {{rate}} / credit", {- rate: formatMinor(pricePerDocMinor ?? 0, currency),- })}- </span>- </div>- )}- </div>- );-}-export function StripeCheckoutModal({open,onClose,- onBack,+ onPrepay,teamId,currency,pricePerDocMinor,@@ -245,7 +124,7 @@ export function StripeCheckoutModal({"cap" | "checkout" | "finalizing" | "activationSlow">("cap");const [capUsd, setCapUsd] = useState<number | null>(- initialCapUsd ?? DEFAULT_CAP_USD,+ initialCapUsd === undefined ? DEFAULT_CAP_USD : initialCapUsd,);const [capBusy, setCapBusy] = useState(false);const [capError, setCapError] = useState<string | null>(null);@@ -266,7 +145,6 @@ export function StripeCheckoutModal({setClientSecret(null);setError(null);setLoading(true);- setCapUsd(initialCapUsd ?? DEFAULT_CAP_USD);setCapBusy(false);setCapError(null);}@@ -368,7 +246,7 @@ export function StripeCheckoutModal({// Valid to continue when a positive cap is set OR "No limit" (null) was explicitly picked. A cleared// field maps to 0 (incomplete) — block Continue rather than let it become an accidental $0 ceiling.- const capValid = capUsd === null || capUsd > 0;+ const capValid = capUsd === null || (Number.isFinite(capUsd) && capUsd > 0);// The chosen cap, formatted for the payment-step recap (null = "No cap" was picked on step 1).const capLabel =@@ -384,6 +262,19 @@ export function StripeCheckoutModal({<Modalopen={open}onClose={handleClose}+ title={+ phase === "cap"+ ? t("portal.billing.simple.setLimit", "Set a spend limit")+ : undefined+ }+ subtitle={+ phase === "cap"+ ? t(+ "portal.billing.simple.limitIntro",+ "Cap what the Processor can bill each month.",+ )+ : undefined+ }/* Only the Stripe checkout step needs the room; every other step stays narrow. The checkoutstep also gets a wider-than-xl cap so the embedded Stripe iframe clears its ~1000pxtwo-column threshold (below it, Stripe falls back to the single-column "portrait" layout). */@@ -393,7 +284,9 @@ export function StripeCheckoutModal({phase === "cap" || phase === "checkout"? "portal-billing__checkout-modal--framed": "",- phase === "checkout" ? "portal-billing__checkout-modal--wide" : "",+ phase === "checkout"+ ? "portal-billing__checkout-modal--wide"+ : "processor-checkout--simple",].filter(Boolean).join(" ")}@@ -408,34 +301,18 @@ export function StripeCheckoutModal({{phase === "cap" && (<div className="portal-billing__checkout-cap">- <PrepayModalHeader- step={2}- total={3}- title={t(- "portal.billing.checkout.cap.title",- "Set your spend limit",- )}- onClose={handleClose}- /><div className="portal-billing__checkout-scroll">- <SpendLimitPicker- capUsd={capUsd}+ <ProcessorSpendFields+ value={capUsd}onChange={setCapUsd}- pricePerDocMinor={pricePerDocMinor}currency={currency}- presets={CAP_PRESETS}+ rate={pricePerDocMinor ?? null}disabled={capBusy}/><p className="portal-billing__checkout-finePrint">{t(- "portal.billing.checkout.cap.note",- "You're never billed past your limit. Processing just pauses.",- )}- </p>- <p className="portal-billing__checkout-finePrint">- {t(- "portal.billing.checkout.cap.finePrint",- "Invoices post monthly. Cancel anytime.",+ "portal.billing.simple.billingNote",+ "No standing fee. Credits bill monthly as used. Cancel any time in Usage & Billing.",)}</p>{capError && (@@ -451,11 +328,11 @@ export function StripeCheckoutModal({)}<div className="portal-billing__checkout-cap-actions"><Button- variant="quiet"- onClick={onBack ?? onClose}+ variant="secondary"+ onClick={onPrepay ?? onClose}disabled={capBusy}>- {t("portal.billing.checkout.cap.back", "Back")}+ {t("portal.billing.spendLimit.buyCredits", "Buy credits")}</Button><Buttonloading={capBusy}@@ -476,8 +353,8 @@ export function StripeCheckoutModal({{phase === "checkout" && (<div className="portal-billing__checkout-pay"><PrepayModalHeader- step={3}- total={3}+ step={2}+ total={2}title={t("portal.billing.checkout.title", "Add a payment method")}onClose={handleClose}/>diff --git a/frontend/editor/src/portal/components/billing/billing.css b/frontend/editor/src/portal/components/billing/billing.cssindex 6511a1c93b..e33f8953e1 100644--- a/frontend/editor/src/portal/components/billing/billing.css+++ b/frontend/editor/src/portal/components/billing/billing.css@@ -1532,3 +1532,133 @@line-height: 1.5;color: var(--c-text-subtle);}++.processor-spend-fields__row {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 1rem;+ padding: 1rem 0;+ border-bottom: 1px solid var(--c-border-subtle);+ font-size: 0.875rem;+}+.processor-spend-fields__row > span {+ color: var(--c-text-muted);+}+.processor-spend-fields__value {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}+.processor-spend-fields__edit {+ display: flex;+ gap: 0.5rem;+ padding: 0.75rem 0;+}+.processor-checkout--simple .portal-billing__checkout-scroll {+ padding: 0 1.25rem 1.25rem;+}+.processor-checkout--simple .portal-billing__checkout-finePrint {+ margin: 0.875rem 0;+}+.processor-spend-modal .sui-modal__body {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ padding: 0 1.25rem 1.25rem;+}+.processor-spend-modal .portal-billing__checkout-finePrint {+ margin: 0;+}+.processor-spend-modal .portal-billing__checkout-cap-actions {+ gap: 1rem;+ margin-top: 0.25rem;+}+.processor-prepay__picker {+ border: 1px solid var(--c-border);+ border-radius: 0.75rem;+ padding: 0.875rem;+}+.processor-prepay__choices {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ flex-wrap: wrap;+}+.processor-prepay__choices > span,+.processor-prepay__credits {+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}+.processor-prepay__choices button {+ border-radius: 999px;+ font-weight: 500;+}+.processor-prepay__choices button[aria-pressed="true"] {+ border-color: var(--c-primary);+ background: var(--c-primary-subtle);+ color: var(--c-accent-text);+}+.processor-prepay__custom {+ display: flex;+ gap: 0.5rem;+ align-items: center;+ margin-top: 0.625rem;+}+.processor-prepay__credits {+ margin: -0.375rem 0 0;+}+.processor-prepay__receipt {+ background: transparent;+ padding: 0 0.875rem;+ gap: 0;+}+.processor-prepay__receipt .portal-billing__bundle-receipt-row {+ padding: 0.875rem 0;+}+.processor-prepay__receipt+ .portal-billing__bundle-receipt-row+ + .portal-billing__bundle-receipt-row {+ border-top: 1px solid var(--c-border-subtle);+}+.processor-prepay__receipt .processor-prepay__saving {+ color: color-mix(in srgb, var(--c-success) 65%, var(--c-text));+}+.processor-prepay__after {+ border: 1px solid var(--c-border);+ border-radius: 0.75rem;+ padding: 0.875rem;+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}+.processor-prepay__after p {+ margin: 0.25rem 0 0;+}++.processor-prepay .portal-billing__bundle-calc {+ gap: 0.75rem;+}+.processor-prepay .portal-billing__bundle-calc > button {+ align-self: flex-start;+}+.processor-prepay .sui-modal__title,+.processor-checkout--simple .sui-modal__title {+ font-size: 1.125rem;+ font-weight: 600;+}+.processor-prepay .sui-modal__header,+.processor-checkout--simple .sui-modal__header {+ border-bottom: 0;+ padding: 1.25rem 1.25rem 0.75rem;+}+.processor-prepay .sui-modal__footer {+ border-top: 0;+ padding-top: 0.25rem;+}+@media (max-width: 30rem) {+ .processor-spend-fields__row {+ align-items: flex-start;+ flex-wrap: wrap;+ gap: 0.5rem;+ }+}diff --git a/frontend/editor/src/portal/hooks/useServerPlan.ts b/frontend/editor/src/portal/hooks/useServerPlan.tsindex 807c2a95dd..6c50090e3e 100644--- a/frontend/editor/src/portal/hooks/useServerPlan.ts+++ b/frontend/editor/src/portal/hooks/useServerPlan.ts@@ -7,6 +7,7 @@ import type { ServerPlan } from "@app/billing/serverPlan";export function useServerPlan(enabled: boolean) {const { licenseInfo, loading } = useLicense();const [usersInUse, setUsersInUse] = useState<number | null>(null);+ const [userLimit, setUserLimit] = useState<number | null>(null);const installedKey = licenseInfo?.licenseKey?.trim();const licenseType =enabled &&@@ -20,15 +21,22 @@ export function useServerPlan(enabled: boolean) {useEffect(() => {let cancelled = false;setUsersInUse(null);+ setUserLimit(null);const refreshUsers = () => {if (!enabled) return;usersBackend.fetchUsers(licenseType === "ENTERPRISE" ? "enterprise" : "pro").then(({ summary }) => {- if (!cancelled) setUsersInUse(summary.seatsUsed);+ if (!cancelled) {+ setUsersInUse(summary.seatsUsed);+ setUserLimit(summary.seatLimit);+ }}).catch(() => {- if (!cancelled) setUsersInUse(null);+ if (!cancelled) {+ setUsersInUse(null);+ setUserLimit(null);+ }});};refreshUsers();@@ -42,5 +50,10 @@ export function useServerPlan(enabled: boolean) {licenseType && licenseInfo? { licenseType, maxUsers: licenseInfo.maxUsers, usersInUse }: undefined;- return { serverPlan, usersInUse, loading: loading && !licenseInfo };+ return {+ serverPlan,+ usersInUse,+ userLimit,+ loading: loading && !licenseInfo,+ };}diff --git a/frontend/editor/src/portal/views/Usage.test.tsx b/frontend/editor/src/portal/views/Usage.test.tsxindex 86d4b84d19..8dfbc141f9 100644--- a/frontend/editor/src/portal/views/Usage.test.tsx+++ b/frontend/editor/src/portal/views/Usage.test.tsx@@ -89,12 +89,17 @@ vi.mock("@app/portal/api/fleetStats", () => ({vi.mock("@app/portal/api/users", () => ({fetchAdminEmail: () => Promise.resolve(null),}));+const checkout = { openCheckout: vi.fn() };+let checkoutEnabled = false;vi.mock("@app/contexts/CheckoutContext", () => ({- useCheckoutOptional: () => null,+ useCheckoutOptional: () => (checkoutEnabled ? checkout : null),}));vi.mock("@app/portal/api/billing", () => ({fetchWallet: () => fetchWallet(),refreshWalletCache: () => refreshWalletCache(),+ fetchPaymentMethod: () => Promise.resolve(null),+ fetchBillingDetails: () => Promise.resolve(null),+ fetchInvoices: () => Promise.resolve([]),}));const fetchLocalUsage = vi.fn().mockResolvedValue(null);vi.mock("@app/portal/api/link", () => ({@@ -161,6 +166,8 @@ describe("Usage — link-free wallet renderer", () => {});beforeEach(() => {+ checkoutEnabled = false;+ checkout.openCheckout.mockReset();resetPortalSaasSessionState();bundleFlow.status = "none";bundleFlow.refresh.mockReset();@@ -175,6 +182,75 @@ describe("Usage — link-free wallet renderer", () => {procurement.setOpen.mockReset();});+ it("opens Team once for an over-capacity server and includes the actual allowance", async () => {+ checkoutEnabled = true;+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });+ renderUsage(+ <Usage localUsersInUse={7} localUserLimit={5} />,+ "/settings/billing?upgrade=team",+ );+ await waitFor(() => expect(checkout.openCheckout).toHaveBeenCalledTimes(1));+ expect(checkout.openCheckout).toHaveBeenCalledWith(+ "server",+ expect.objectContaining({+ combinedChoose: true,+ minimumSeats: 7,+ capacityNotice: { users: 7, limit: 5 },+ }),+ );+ expect(screen.getByTestId("location")).toHaveTextContent(+ "/settings/billing",+ );+ await waitFor(() =>+ expect(screen.getByTestId("location")).not.toHaveTextContent("upgrade="),+ );+ });++ it.each([+ ["within allowance", 4, 5, false, "leader"],+ ["grandfathered allowance", 7, 10, false, "leader"],+ ["unknown or uncapped limit", 7, null, false, "leader"],+ ["active Team", 7, 5, true, "leader"],+ ["member", 7, 5, false, "member"],+ ] as const)(+ "does not prompt a server with %s",+ async (_label, users, limit, held, role) => {+ checkoutEnabled = true;+ fetchWallet.mockResolvedValue({+ ...walletOf("free"),+ role,+ team: { held, licensedUsers: 100 },+ });+ renderUsage(+ <Usage localUsersInUse={users} localUserLimit={limit} />,+ "/settings/billing?upgrade=team",+ );+ await waitFor(() =>+ expect(screen.getByTestId("location")).not.toHaveTextContent(+ "upgrade=",+ ),+ );+ expect(checkout.openCheckout).not.toHaveBeenCalled();+ },+ );++ it("does not prompt holders of an installed Server license", async () => {+ checkoutEnabled = true;+ fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });+ renderUsage(+ <Usage+ localUsersInUse={7}+ localUserLimit={5}+ serverPlan={{ licenseType: "SERVER", maxUsers: 0, usersInUse: 7 }}+ />,+ "/settings/billing?upgrade=team",+ );+ await waitFor(() =>+ expect(screen.getByTestId("location")).not.toHaveTextContent("upgrade="),+ );+ expect(checkout.openCheckout).not.toHaveBeenCalled();+ });+it("loads the wallet on mount and reports it via onWalletLoaded (no link gate)", async () => {fetchWallet.mockResolvedValue(walletOf("free"));const onWalletLoaded = vi.fn();diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsxindex 38b25f3988..e3ffcc5bb1 100644--- a/frontend/editor/src/portal/views/Usage.tsx+++ b/frontend/editor/src/portal/views/Usage.tsx@@ -1,3 +1,4 @@+import { TeamSubscriptionChange } from "@app/billing/TeamSubscriptionChange";import type { ServerPlan } from "@app/billing/serverPlan";import {useCallback,@@ -44,6 +45,7 @@ import "@app/portal/components/billing/billing.css";export interface UsageProps {/** Local occupied seats for self-hosted; undefined keeps the SaaS membership count. */localUsersInUse?: number | null;+ localUserLimit?: number | null;serverPlan?: ServerPlan;serverPlanAction?: ReactNode;/**@@ -69,6 +71,7 @@ export interface UsageProps {*/export function Usage({localUsersInUse,+ localUserLimit,serverPlan,serverPlanAction,onWalletLoaded,@@ -265,9 +268,63 @@ export function Usage({combinedChoose: true,currentLimit: heldLimit,minimumSeats: usersInUse ?? undefined,+ capacityNotice:+ !serverPlan &&+ !wallet?.team?.held &&+ localUsersInUse != null &&+ localUserLimit != null &&+ localUsersInUse > localUserLimit+ ? { users: localUsersInUse, limit: localUserLimit }+ : undefined,onSuccess: () => setRefreshKey((k) => k + 1),});- }, [checkout, heldLimit, usersInUse]);+ }, [+ checkout,+ heldLimit,+ usersInUse,+ serverPlan,+ wallet?.team?.held,+ localUsersInUse,+ localUserLimit,+ ]);++ const handledTeamRequest = useRef(false);+ useEffect(() => {+ if (searchParams.get("upgrade") !== "team") {+ handledTeamRequest.current = false;+ return;+ }+ if (+ handledTeamRequest.current ||+ !wallet ||+ !checkout ||+ (hasLocalInstance && localUsersInUse == null)+ )+ return;+ handledTeamRequest.current = true;+ const next = new URLSearchParams(searchParams);+ next.delete("upgrade");+ setSearchParams(next, { replace: true });+ if (+ wallet.role === "leader" &&+ !wallet.team?.held &&+ !serverPlan &&+ localUsersInUse != null &&+ localUserLimit != null &&+ localUsersInUse > localUserLimit+ )+ addCapacity();+ }, [+ searchParams,+ setSearchParams,+ wallet,+ checkout,+ localUsersInUse,+ localUserLimit,+ serverPlan,+ addCapacity,+ hasLocalInstance,+ ]);const confirmSubscription = useCallback(async (): Promise<boolean> => {// Stripe's onComplete fires before the subscription webhook lands, so poll the@@ -336,6 +393,9 @@ export function Usage({pendingUnits={localUsage?.totalUnsyncedUnits ?? 0}notices={<>+ {wallet?.team?.held && wallet.role === "leader" && (+ <TeamSubscriptionChange refreshKey={refreshKey} />+ )}{procurement.loadError && (<Bannertone="danger"diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.tsxindex 4ff28183c3..fddac322d8 100644--- a/frontend/editor/src/proprietary/billing/BillingScreen.tsx+++ b/frontend/editor/src/proprietary/billing/BillingScreen.tsx@@ -265,7 +265,7 @@ export function BillingScreen({return (<div className="billing-page">- <header className="billing-page__head">+ <div className="billing-page__head"><div><h1 className="billing-page__title">{t("portal.usage.title", "Usage & Billing")}@@ -278,7 +278,7 @@ export function BillingScreen({</p></div>{headerAction}- </header>+ </div><div className="billing-page__body"><div className="billing-page__notices">{notices}</div>diff --git a/frontend/editor/src/proprietary/billing/TeamSubscriptionChange.test.tsx b/frontend/editor/src/proprietary/billing/TeamSubscriptionChange.test.tsxnew file mode 100644index 0000000000..23924326d0--- /dev/null+++ b/frontend/editor/src/proprietary/billing/TeamSubscriptionChange.test.tsx@@ -0,0 +1,83 @@+import { beforeEach, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { TeamSubscriptionChange } from "@app/billing/TeamSubscriptionChange";+import { teamSubscriptionChange } from "@app/services/serverPlanCheckout";++vi.mock("@app/services/serverPlanCheckout", () => ({+ teamSubscriptionChange: vi.fn(),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, fallback: string, values: Record<string, unknown> = {}) =>+ fallback.replace(/{{(\w+)}}/g, (_, key: string) =>+ String(values[key] ?? key),+ ),+ }),+}));+vi.mock("@app/ui", () => ({+ Banner: ({+ title,+ action,+ children,+ }: {+ title: string;+ action?: React.ReactNode;+ children?: React.ReactNode;+ }) => (+ <section>+ {title}+ {children}+ {action}+ </section>+ ),+ Button: ({+ variant: _variant,+ ...props+ }: React.ButtonHTMLAttributes<HTMLButtonElement> & { variant: string }) => (+ <button {...props} />+ ),+}));+const pending = {+ scheduleId: "sched_team",+ quantity: 1,+ effectiveAt: 1800000000,+ interval: "month",+};+beforeEach(() => vi.clearAllMocks());++it("shows future capacity and lets the leader keep the current plan", async () => {+ vi.mocked(teamSubscriptionChange)+ .mockResolvedValueOnce({ pending })+ .mockResolvedValueOnce({ pending: null });+ render(<TeamSubscriptionChange refreshKey={0} />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Keep current plan" }),+ );+ await waitFor(() =>+ expect(teamSubscriptionChange).toHaveBeenCalledWith("cancel", "sched_team"),+ );+ await waitFor(() =>+ expect(screen.queryByRole("button")).not.toBeInTheDocument(),+ );+});++it("does not claim a failed cancellation succeeded", async () => {+ vi.mocked(teamSubscriptionChange)+ .mockResolvedValueOnce({ pending })+ .mockRejectedValueOnce(new Error("offline"));+ render(<TeamSubscriptionChange refreshKey={0} />);+ fireEvent.click(+ await screen.findByRole("button", { name: "Keep current plan" }),+ );+ expect(await screen.findByText(/could not be loaded/)).toBeInTheDocument();+});++it("does not offer cancellation for an unsupported schedule", async () => {+ vi.mocked(teamSubscriptionChange).mockResolvedValue({+ pending: null,+ unsupportedSchedule: true,+ });+ render(<TeamSubscriptionChange refreshKey={0} />);+ expect(await screen.findByText(/billing support/)).toBeInTheDocument();+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+});diff --git a/frontend/editor/src/proprietary/billing/TeamSubscriptionChange.tsx b/frontend/editor/src/proprietary/billing/TeamSubscriptionChange.tsxnew file mode 100644index 0000000000..a0296856fe--- /dev/null+++ b/frontend/editor/src/proprietary/billing/TeamSubscriptionChange.tsx@@ -0,0 +1,96 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { Banner, Button } from "@app/ui";+import {+ teamSubscriptionChange,+ type PendingTeamChange,+} from "@app/services/serverPlanCheckout";+import { USERS_PER_BLOCK } from "@app/components/shared/stripeCheckout/utils/capacity";++/** Keeps the current allowance separate from Stripe's scheduled renewal change. */+export function TeamSubscriptionChange({ refreshKey }: { refreshKey: number }) {+ const { t } = useTranslation();+ const [pending, setPending] = useState<PendingTeamChange | null>(null);+ const [error, setError] = useState(false);+ const [unsupported, setUnsupported] = useState(false);+ const [busy, setBusy] = useState(false);+ useEffect(() => {+ let cancelled = false;+ void teamSubscriptionChange("status")+ .then((result) => {+ if (cancelled) return;+ setPending(result.pending);+ setUnsupported(Boolean(result.unsupportedSchedule));+ setError(false);+ })+ .catch(() => {+ if (!cancelled) setError(true);+ });+ return () => {+ cancelled = true;+ };+ }, [refreshKey]);++ const cancel = async () => {+ if (!pending) return;+ setBusy(true);+ try {+ await teamSubscriptionChange("cancel", pending.scheduleId);+ setPending(null);+ setError(false);+ window.dispatchEvent(new Event("stirling:billing-updated"));+ } catch {+ setError(true);+ } finally {+ setBusy(false);+ }+ };+ if (error)+ return (+ <Banner+ tone="warning"+ title={t(+ "payment.teamChangeUnavailable",+ "Scheduled Team changes could not be loaded. Refresh to try again.",+ )}+ />+ );+ if (unsupported)+ return (+ <Banner+ tone="warning"+ title={t(+ "payment.teamChangeSupport",+ "Your Team subscription has a scheduled change that needs billing support to adjust.",+ )}+ />+ );+ if (!pending) return null;+ return (+ <Banner+ tone="info"+ title={t(+ "payment.teamChangePending",+ "{{users}} users · {{period}} from {{date}}",+ {+ period:+ pending.interval === "year"+ ? t("payment.yearly", "Yearly")+ : t("payment.monthly", "Monthly"),+ users: pending.quantity * USERS_PER_BLOCK,+ date: new Date(pending.effectiveAt * 1000).toLocaleDateString(),+ },+ )}+ action={+ <Button variant="secondary" disabled={busy} onClick={cancel}>+ {t("payment.cancelTeamChange", "Keep current plan")}+ </Button>+ }+ >+ {t(+ "payment.teamChangeCurrent",+ "Your current allowance remains available until then. Keep your current plan to cancel this change before making another adjustment.",+ )}+ </Banner>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.stories.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.stories.tsxindex 8d25b6b33e..3d4066e52c 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.stories.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.stories.tsx@@ -8,8 +8,8 @@ const PLAN_GROUP: PlanTierGroup = {monthly: {id: "server-monthly",name: "Server Monthly",- price: 29,- currency: "usd",+ price: 99,+ currency: "$",period: "monthly",features: [],highlights: ["Unlimited documents", "Priority support"],@@ -18,8 +18,8 @@ const PLAN_GROUP: PlanTierGroup = {yearly: {id: "server-yearly",name: "Server Yearly",- price: 290,- currency: "usd",+ price: 990,+ currency: "$",period: "yearly",features: [],highlights: ["Unlimited documents", "Priority support", "2 months free"],@@ -56,3 +56,11 @@ export const HostedCheckoutSuccess: Story = {},},};++export const TeamPurchase: Story = {+ args: { combinedChoose: true },+};++export const TeamAdjustment: Story = {+ args: { combinedChoose: true, currentLimit: 300, minimumSeats: 40 },+};diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsxindex abe8337064..826da07c6d 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsx@@ -24,7 +24,12 @@ const service = vi.hoisted(() => ({vi.mock("@app/services/licenseService", () => ({ default: service }));vi.mock("@app/hooks/useIsMobile", () => ({ useIsMobile: () => false }));vi.mock("@mantine/core", () => ({- Modal: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Modal: ({ children, title }: { children: ReactNode; title?: ReactNode }) => (+ <div>+ {title}+ {children}+ </div>+ ),Text: ({ children }: { children: ReactNode }) => <div>{children}</div>,Group: ({ children }: { children: ReactNode }) => <div>{children}</div>,}));@@ -88,14 +93,17 @@ vi.mock(vi.mock("@app/components/shared/stripeCheckout/stages/CapacityStage", () => ({CapacityStage: ({serverQuantity,+ periodPicker,currentLimit,onContinue,}: {serverQuantity: number;+ periodPicker?: ReactNode;currentLimit: number;onContinue: () => void;}) => (<div>+ {periodPicker}Capacity: {serverQuantity} blocks; current: {currentLimit}<button onClick={onContinue}>Continue to payment</button></div>diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsxindex f45ed2e734..48242c5fcf 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx@@ -6,11 +6,7 @@ import LocalIcon from "@app/components/shared/LocalIcon";import licenseService from "@app/services/licenseService";import { useIsMobile } from "@app/hooks/useIsMobile";import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";-import {- CheckoutStage,- StripeCheckoutProps,-} from "@app/components/shared/stripeCheckout/types/checkout";-import { StepModalHeader } from "@app/components/shared/StepModalHeader";+import { StripeCheckoutProps } from "@app/components/shared/stripeCheckout/types/checkout";import { getModalTitle } from "@app/components/shared/stripeCheckout/utils/checkoutUtils";import { calculateSavings } from "@app/components/shared/stripeCheckout/utils/savingsCalculator";import { useCheckoutState } from "@app/components/shared/stripeCheckout/hooks/useCheckoutState";@@ -49,6 +45,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({minimumSeats = 1,combinedChoose: requestedCombinedChoose = false,currentLimit = null,+ capacityNotice,onSuccess,onError,onLicenseActivated,@@ -222,35 +219,25 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({// The period cards select rather than navigate, and capacity supplies the single continue.case "choose":return (- <>- <PlanSelectionStage- planGroup={planGroup}- minimumSeats={minimumSeats}- savings={savings}- selectedPeriod={checkoutState.selectedPeriod}- onSelectPlan={(period) => {- checkoutState.setSelectedPeriod(period);- if (sellsCapacity) {- checkoutState.setServerQuantity(- Math.max(- blocksForUsers(minimumCapacity),- checkoutState.serverQuantity || 1,- ),- );- }- }}- />- {sellsCapacity && (- <CapacityStage- selectedPlan={checkoutState.selectedPlan}- serverQuantity={checkoutState.serverQuantity}- setServerQuantity={checkoutState.setServerQuantity}- currentUsers={minimumSeats}- currentLimit={currentLimit}- onContinue={() => navigation.goToStage("payment")}+ <CapacityStage+ selectedPlan={checkoutState.selectedPlan}+ serverQuantity={checkoutState.serverQuantity}+ setServerQuantity={checkoutState.setServerQuantity}+ currentUsers={minimumSeats}+ currentLimit={currentLimit}+ capacityNotice={capacityNotice}+ periodPicker={+ <PlanSelectionStage+ compact+ planGroup={planGroup}+ minimumSeats={minimumSeats}+ savings={savings}+ selectedPeriod={checkoutState.selectedPeriod}+ onSelectPlan={checkoutState.setSelectedPeriod}/>- )}- </>+ }+ onContinue={() => navigation.goToStage("payment")}+ />);case "plan-selection":@@ -271,6 +258,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({setServerQuantity={checkoutState.setServerQuantity}currentUsers={minimumSeats}currentLimit={currentLimit}+ capacityNotice={capacityNotice}onContinue={() => navigation.goToStage("payment")}/>);@@ -309,97 +297,56 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({};const canGoBack = checkoutState.stageHistory.length > 0;- // The combined flow wears the stepped chrome, counting the pages it actually walks. The separate- // walk keeps its own title, because a step count would be a lie about how many pages it has.- const steppedPath: CheckoutStage[] | null = combinedChoose- ? ["choose", "payment"]- : null;- const steppedIndex = steppedPath- ? steppedPath.indexOf(checkoutState.state.currentStage)- : -1;- const steppedStep = steppedIndex >= 0 ? steppedIndex + 1 : null;return (<Modalopened={opened}onClose={handleClose}title={- steppedStep ? undefined : (- <Group gap="sm" wrap="nowrap">- {canGoBack && (- <ActionIcon- variant="tertiary"- size="lg"- disabled={checkoutState.state.loading}- onClick={navigation.goBack}- aria-label={t("common.back", "Back")}- >- <LocalIcon icon="arrow-back" width={20} height={20} />- </ActionIcon>- )}- <Text fw={600} size="lg">- {getModalTitle(- checkoutState.state.currentStage,- planGroup.name,- t,- )}- </Text>- </Group>- )+ <Group gap="sm" wrap="nowrap">+ {canGoBack && (+ <ActionIcon+ variant="tertiary"+ size="lg"+ disabled={checkoutState.state.loading}+ onClick={navigation.goBack}+ aria-label={t("common.back", "Back")}+ >+ <LocalIcon icon="arrow-back" width={20} height={20} />+ </ActionIcon>+ )}+ <Text fw={600} size="lg">+ {combinedChoose+ ? currentLimit != null+ ? t("payment.adjustTeam.title", "Adjust Team plan")+ : t("payment.upgradeTeam.title", "Upgrade to Team")+ : getModalTitle(+ checkoutState.state.currentStage,+ planGroup.name,+ t,+ )}+ </Text>+ </Group>}- size={isMobile ? "100%" : 980}+ size={isMobile ? "100%" : combinedChoose ? 500 : 980}centeredradius="lg"- withCloseButton={!steppedStep}+ withCloseButtoncloseOnEscape={true}closeOnClickOutside={false}fullScreen={isMobile}zIndex={Z_INDEX_OVER_CONFIG_MODAL}styles={{- body: {},+ header: combinedChoose+ ? { borderBottom: 0, padding: "1.25rem 1.25rem 0.25rem" }+ : undefined,+ body: combinedChoose ? { padding: "0 1.25rem 1.25rem" } : undefined,+ close: combinedChoose ? { borderRadius: "50%" } : undefined,content: {maxHeight: "95vh",},}}>- {steppedStep && (- <StepModalHeader- title={- currentLimit != null- ? t("payment.addCapacity.title", "Add capacity")- : t("payment.upgradeTeam.title", "Upgrade to Team")- }- subtitle={- currentLimit != null- ? t(- "payment.addCapacity.currently",- "Currently up to {{users}} users",- { users: currentLimit },- )- : undefined- }- step={steppedStep}- total={steppedPath?.length ?? 0}- stepLabel={t("payment.stepOf", "Step {{n}} of {{total}}", {- n: steppedStep,- total: steppedPath?.length ?? 0,- })}- aside={- canGoBack ? (- <ActionIcon- variant="tertiary"- size="lg"- disabled={checkoutState.state.loading}- onClick={navigation.goBack}- aria-label={t("common.back", "Back")}- >- <LocalIcon icon="arrow-back" width={20} height={20} />- </ActionIcon>- ) : undefined- }- onClose={handleClose}- />- )}{renderContent()}</Modal>);diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsxindex 1207768541..1cc9d9742d 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx@@ -1,3 +1,5 @@+import { useState } from "react";+import userEvent from "@testing-library/user-event";import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import { expect, it, vi } from "vitest";@@ -5,23 +7,23 @@ import { CapacityStage } from "@app/components/shared/stripeCheckout/stages/Capavi.mock("react-i18next", () => ({useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),}));-it("blocks purchasing less than the existing allowance even when usage is lower", () => {+it("allows a reduction at renewal even when current usage exceeds the future allowance", () => {render(<MantineProvider><CapacityStageselectedPlan={null}serverQuantity={1}setServerQuantity={() => {}}- currentUsers={40}+ currentUsers={240}currentLimit={300}onContinue={() => {}}/></MantineProvider>,);- expect(screen.getByRole("button", { name: "100" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "100" })).toBeEnabled();expect(screen.getByRole("button", { name: "Review change in Stripe" }),- ).toBeDisabled();+ ).toBeEnabled();});it("shows the new recurring total without inventing the adjustment charge", () => {@@ -62,3 +64,60 @@ it("keeps payment language for a first purchase", () => {screen.getByRole("button", { name: "Continue to payment" }),).toBeEnabled();});++it("lets a custom user count be typed without replacing it with rounded blocks", async () => {+ const user = userEvent.setup();+ function Picker() {+ const [quantity, setQuantity] = useState(1);+ return (+ <CapacityStage+ selectedPlan={null}+ serverQuantity={quantity}+ setServerQuantity={setQuantity}+ currentUsers={240}+ onContinue={() => {}}+ />+ );+ }+ render(+ <MantineProvider>+ <Picker />+ </MantineProvider>,+ );+ await user.click(screen.getByRole("button", { name: "Other" }));+ const input = screen.getByRole("textbox", { name: "Number of users" });+ await user.clear(input);+ expect(+ screen.getByRole("button", { name: "Continue to payment" }),+ ).toBeDisabled();+ await user.type(input, "245");+ expect(input).toHaveValue("245");+ expect(+ screen.getByRole("button", { name: "Continue to payment" }),+ ).toBeEnabled();+});++it.each([+ [undefined, false],+ [{ users: 5, limit: 5 }, false],+ [{ users: 7, limit: 5 }, true],+])(+ "only explains blocked admissions above the supplied allowance",+ (capacityNotice, shown) => {+ render(+ <MantineProvider>+ <CapacityStage+ selectedPlan={null}+ serverQuantity={1}+ setServerQuantity={() => {}}+ onContinue={() => {}}+ capacityNotice={capacityNotice}+ />+ </MantineProvider>,+ );+ expect(+ !!screen.queryByText("Your server has more users than your plan covers"),+ ).toBe(shown);+ expect(!!screen.queryByText(/Existing accounts stay in place/)).toBe(shown);+ },+);diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsxindex 01b55f1eaf..bdc405685e 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx@@ -1,5 +1,14 @@import React, { useState } from "react";-import { Stack, Text, Group, Divider, Alert, NumberInput } from "@mantine/core";+import {+ Stack,+ Text,+ Group,+ Divider,+ Alert,+ NumberInput,+ Box,+} from "@mantine/core";+import "@app/components/shared/stripeCheckout/team-checkout.css";import { Button } from "@app/ui/Button";import { useTranslation } from "react-i18next";import { PlanTier } from "@app/services/licenseService";@@ -16,24 +25,32 @@ import {interface CapacityStageProps {/** The plan the buyer picked a billing period for; supplies block price and currency. */selectedPlan: PlanTier | null;- /**- * Blocks of users being bought. Held in blocks because that is what the Stripe line item counts,- * but nothing shown to the buyer says so.- */+ /** Stripe quantity counts blocks of users. */serverQuantity: number;setServerQuantity: (quantity: number) => void;/** Users already on this installation, so capacity cannot be set below what is in use. */currentUsers?: number;- /**- * Users the current plan already covers, when there is one. Its presence switches this from- * "upgrade to Team" to "add capacity": the buyer is choosing a new total, so the line item states- * what is being ADDED rather than what is covered, which is the number they are deciding about.- */+ /** Existing purchased capacity; an adjustment selects the new total. */currentLimit?: number | null;+ periodPicker?: React.ReactNode;+ capacityNotice?: { users: number; limit: number };onContinue: () => void;onContactSales?: () => void;}+function showCustomValueInvalid(+ value: number | string,+ minimum: number,+ maximum: number,+) {+ return (+ value === "" ||+ !Number.isSafeInteger(Number(value)) ||+ Number(value) < minimum ||+ Number(value) > maximum+ );+}+/*** Choose how many users the Team plan should cover.*@@ -47,6 +64,8 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({setServerQuantity,currentUsers = 0,currentLimit = null,+ periodPicker,+ capacityNotice,onContinue,onContactSales,}) => {@@ -57,13 +76,15 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({const isYearly = selectedPlan?.period?.includes("year") ?? false;const covered = usersForBlocks(serverQuantity);const total = blockPrice * serverQuantity;+ const [draftUsers, setDraftUsers] = useState<number | string>(covered);- // Adding capacity cannot reduce the purchased allowance or strand existing users.- const minBlocks = blocksForUsers(Math.max(currentUsers, currentLimit ?? 0));+ const minBlocks = currentLimit == null ? blocksForUsers(currentUsers) : 1;+ const reducing = currentLimit != null && covered < currentLimit;const minUsers = usersForBlocks(minBlocks);const maxUsers = usersForBlocks(SELF_SERVE_MAX_BLOCKS);const belowMinimumCapacity = serverQuantity < minBlocks;const offerEnterprise = shouldOfferEnterprise(serverQuantity);+ const invalidDraft = showCustomValueInvalid(draftUsers, 1, maxUsers);const presets = USER_PRESETS.filter((users) => users <= maxUsers);const [showCustom, setShowCustom] = useState(@@ -78,65 +99,115 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({setServerQuantity(blocksForUsers(users));return (- <Stack gap="lg" style={{ padding: "1.5rem 2rem" }}>+ <Stack gap="sm" className="team-capacity">+ {capacityNotice && capacityNotice.users > capacityNotice.limit && (+ <Box className="team-capacity__notice">+ <Text size="sm" fw={500}>+ {t(+ "payment.capacityStage.overCapacityTitle",+ "Your server has more users than your plan covers",+ )}+ </Text>+ <Text size="sm" mt={4}>+ {t(+ "payment.capacityStage.overCapacityBody",+ "{{users}} users are on this server; your current allowance is {{limit}}. Choose a Team plan below to cover everyone.",+ { users: capacityNotice.users, limit: capacityNotice.limit },+ )}+ </Text>+ <Text size="xs" c="dimmed" mt={6}>+ {t(+ "payment.capacityStage.overCapacityConsequence",+ "Existing accounts stay in place. Adding or inviting users is blocked until you add capacity or free up seats.",+ )}+ </Text>+ </Box>+ )}<Text size="sm" c="dimmed">{currentLimit != null? t("payment.capacityStage.subheadingAdd","Your plan covers {{current}} users today. Choose the new total.",- { current: currentLimit },+ {+ current: currentLimit,+ },): t("payment.capacityStage.subheading","Covers everyone you invite, in blocks of {{users}} users.",- { users: USERS_PER_BLOCK },+ {+ users: USERS_PER_BLOCK,+ },)}</Text>- <Group gap="sm" wrap="wrap" align="center">- <Text size="sm" fw={500}>- {t("payment.capacityStage.usersLabel", "Users")}- </Text>- {presets.map((users) => (+ <Box className="team-capacity__selection">+ <Group gap="xs" wrap="wrap" align="center">+ <Text size="sm" fw={500}>+ {t("payment.capacityStage.usersLabel", "Users")}+ </Text>+ {presets.map((users) => (+ <Button+ key={users}+ variant="secondary"+ className="team-capacity__pill"+ aria-pressed={!showCustom && covered === users}+ disabled={users < minUsers}+ onClick={() => {+ setShowCustom(false);+ setDraftUsers(users);+ selectUsers(users);+ }}+ >+ {users}+ </Button>+ ))}<Button- key={users}- variant={!showCustom && covered === users ? "primary" : "secondary"}- disabled={users < minUsers}+ variant="secondary"+ className="team-capacity__pill"+ aria-pressed={showCustom}onClick={() => {- setShowCustom(false);- selectUsers(users);+ setDraftUsers(covered);+ setShowCustom(true);}}>- {users}+ {t("payment.capacityStage.other", "Other")}</Button>- ))}- <Button- variant={showCustom ? "primary" : "secondary"}- onClick={() => setShowCustom(true)}- >- {t("payment.capacityStage.other", "Other")}- </Button>- </Group>+ </Group>- {showCustom && (- <NumberInput- label={t("payment.capacityStage.customLabel", "Number of users")}- description={t(- "payment.capacityStage.customHint",- "Rounded up to the next block of {{users}}.",- { users: USERS_PER_BLOCK },- )}- value={covered}- onChange={(value) => selectUsers(Number(value) || minUsers)}- min={minUsers}- max={maxUsers}- step={USERS_PER_BLOCK}- clampBehavior="strict"- allowDecimal={false}- allowNegative={false}- style={{ width: 220 }}- />- )}+ {showCustom && (+ <Group gap="xs" mt="xs">+ <NumberInput+ aria-label={t(+ "payment.capacityStage.customLabel",+ "Number of users",+ )}+ value={draftUsers}+ onChange={(value) => {+ setDraftUsers(value);+ if (+ value !== "" &&+ Number.isSafeInteger(Number(value)) &&+ Number(value) > 0+ )+ selectUsers(Number(value));+ }}+ min={minUsers}+ max={maxUsers}+ clampBehavior="none"+ hideControls+ allowDecimal={false}+ allowNegative={false}+ style={{ width: 80 }}+ />+ <Text size="xs" c="dimmed">+ {t("payment.capacityStage.roundsTo", "rounds to {{users}}", {+ users: covered,+ })}+ </Text>+ </Group>+ )}+ </Box>{belowMinimumCapacity && (<Alert color="yellow" variant="light">@@ -148,9 +219,17 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({</Alert>)}- <Divider />+ {periodPicker}+ {reducing && (+ <Text size="sm" c="dimmed">+ {t(+ "payment.capacityStage.reductionNote",+ "The lower capacity starts at your next renewal. Until then, you can use your current allowance. Existing users stay; new users are blocked if you are over capacity when the change takes effect.",+ )}+ </Text>+ )}- <Stack gap="xs">+ <Stack gap="sm" className="team-capacity__receipt"><Group justify="space-between"><Text size="sm" c="dimmed">{t(@@ -164,41 +243,44 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({)}</Text><Text size="sm" fw={500}>- {currentLimit != null- ? t("payment.capacityStage.userDelta", "+{{users}} users", {- users: Math.max(0, covered - currentLimit),- })- : t("payment.capacityStage.userTotal", "{{users}} users", {- users: covered,- })}+ {t("payment.capacityStage.userTotal", "{{users}} users", {+ users: covered,+ })}</Text></Group>+ <Divider /><Group justify="space-between" align="baseline"><Text fw={600}>{currentLimit != null? t("payment.capacityStage.newPlanTotal", "New plan total"): t("payment.capacityStage.dueToday", "Due today")}</Text>- <Text size="xl" fw={700}>+ <Text size="md" fw={600}>{formatPrice(total, currency)}</Text></Group>- <Text size="xs" c="dimmed">- {currentLimit != null- ? t(- "payment.capacityStage.adjustmentNote",- "Stripe will show the exact charge, any prorations and your next billing date before you confirm. Your saved payment method will be used if available.",- )- : t(- "payment.capacityStage.renewalNote",- "Renews at {{total}}{{period}}. Cancel any time in Usage & Billing.",- { total: formatPrice(total, currency, 0), period },- )}- </Text></Stack>+ <Text size="xs" c="dimmed">+ {currentLimit != null+ ? t(+ "payment.capacityStage.adjustmentNote",+ "Stripe will show the exact charge, any prorations and your next billing date before you confirm. Your saved payment method will be used if available.",+ )+ : t(+ "payment.capacityStage.renewalNote",+ "Renews at {{total}}{{period}}. Cancel any time in Usage & Billing.",+ {+ total: formatPrice(total, currency, 0),+ period,+ },+ )}+ </Text>- <Stack gap="sm">- <Button onClick={onContinue} disabled={belowMinimumCapacity} fullWidth>+ <Group justify="flex-end" mt="sm">+ <Button+ onClick={onContinue}+ disabled={belowMinimumCapacity || (showCustom && invalidDraft)}+ >{currentLimit != null? t("payment.capacityStage.reviewChange", "Review change in Stripe"): t("payment.capacityStage.continue", "Continue to payment")}@@ -212,7 +294,7 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({)}</Button>)}- </Stack>+ </Group></Stack>);};diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsxindex e14e90e6ee..3608f25ebd 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx@@ -24,6 +24,7 @@ interface PlanSelectionStageProps {* neither card claims to be chosen: both buttons stay secondary.*/selectedPeriod?: "monthly" | "yearly";+ compact?: boolean;}export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({@@ -32,11 +33,69 @@ export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({savings,onSelectPlan,selectedPeriod,+ compact = false,}) => {const { t } = useTranslation();const isEnterprise = planGroup.tier === "enterprise";const seatCount = minimumSeats || 1;+ if (compact) {+ return (+ <div+ role="group"+ aria-label={t("payment.billingPeriod", "Billing period")}+ style={{+ display: "grid",+ gridTemplateColumns: "repeat(2, minmax(0, 1fr))",+ gap: "0.75rem",+ }}+ >+ {(["monthly", "yearly"] as const).map((period) => {+ const plan = planGroup[period];+ if (!plan) return null;+ const selected = selectedPeriod === period;+ return (+ <button+ key={period}+ type="button"+ aria-pressed={selected}+ onClick={() => onSelectPlan(period)}+ style={{+ textAlign: "left",+ padding: "0.75rem",+ borderRadius: "0.75rem",+ cursor: "pointer",+ color: "var(--c-text)",+ border: `1px solid ${selected ? "var(--c-primary)" : "var(--c-border)"}`,+ background: selected+ ? "var(--c-primary-subtle)"+ : "transparent",+ }}+ >+ <Text component="span" display="block" fw={600}>+ {period === "monthly"+ ? t("payment.monthly", "Monthly")+ : t("payment.yearly", "Yearly")}+ </Text>+ <Text component="span" display="block" size="sm" c="dimmed">+ {formatPrice(plan.price, plan.currency, 0)}+ {period === "monthly"+ ? t("payment.capacityStage.perMonth", "/mo")+ : t("payment.capacityStage.perYear", "/yr")}+ {" · "}+ {period === "yearly" && savings+ ? t("payment.planStage.savePercent", "Save {{percent}}%", {+ percent: savings.percent,+ })+ : t("payment.perUserBlock", "per 100 users")}+ </Text>+ </button>+ );+ })}+ </div>+ );+ }+return (<Stack gap="lg" style={{ padding: "1rem 2rem" }}><Grid gutter="xl" style={{ marginTop: "1rem" }}>diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/team-checkout.css b/frontend/editor/src/proprietary/components/shared/stripeCheckout/team-checkout.cssnew file mode 100644index 0000000000..d633fb3e34--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/team-checkout.css@@ -0,0 +1,27 @@+.team-capacity {+ padding: 0;+}+.team-capacity__selection,+.team-capacity__receipt {+ border: 1px solid var(--c-border);+ border-radius: 0.75rem;+ padding: 0.875rem;+}+.team-capacity__pill {+ border-radius: 999px;+ font-weight: 500;+ min-width: 3rem;+}+.team-capacity__pill[aria-pressed="true"] {+ border-color: var(--c-primary);+ color: var(--c-accent-text);+ background: var(--c-primary-subtle);+}++.team-capacity__notice {+ padding: 14px 16px;+ border-radius: 12px;+ border: 1px solid var(--c-border);+ background: var(--c-primary-subtle);+ color: var(--c-text);+}diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts b/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.tsindex cf4f5fae6e..3bf9ca700b 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts@@ -9,6 +9,8 @@ export interface StripeCheckoutProps {combinedChoose?: boolean;/** Users the current plan covers, or null when there is none. Drives the add-capacity face. */currentLimit?: number | null;+ /** Present only for a self-hosted server above its actual allowance. */+ capacityNotice?: { users: number; limit: number };opened: boolean;onClose: () => void;planGroup: PlanTierGroup;diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsxindex e070c9fed4..e7c452d869 100644--- a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx@@ -48,6 +48,8 @@ export interface CheckoutOptions {/** Users the current plan covers. Its presence is what makes this "add capacity", not a first* upgrade, so the capacity step states the delta. */currentLimit?: number | null;+ /** Present only for a self-hosted server above its actual allowance. */+ capacityNotice?: { users: number; limit: number };}interface CheckoutContextValue {@@ -146,12 +148,22 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({window.dispatchEvent(new Event("stirling:billing-updated"));alert({alertType: result.success ? "success" : "warning",- title: result.success- ? t("payment.teamActivated", "Your Team capacity is active")- : t(- "payment.teamPending",- "Your Team purchase is still processing. Refresh this page shortly.",- ),+ title: result.scheduledAt+ ? t(+ "payment.teamScheduled",+ "Your Team change is scheduled for {{date}}. Your current capacity stays active until then.",+ {+ date: new Date(+ result.scheduledAt * 1000,+ ).toLocaleDateString(),+ },+ )+ : result.success+ ? t("payment.teamActivated", "Your Team capacity is active")+ : t(+ "payment.teamPending",+ "Your Team purchase is still processing. Refresh this page shortly.",+ ),});return;}@@ -482,6 +494,7 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({minimumSeats={minimumSeats}combinedChoose={currentOptions.combinedChoose}currentLimit={currentOptions.currentLimit ?? null}+ capacityNotice={currentOptions.capacityNotice}onSuccess={handlePaymentSuccess}onError={handlePaymentError}onLicenseActivated={handleLicenseActivated}diff --git a/frontend/editor/src/proprietary/services/serverPlanCheckout.ts b/frontend/editor/src/proprietary/services/serverPlanCheckout.tsindex 255e973b01..ec3a488be5 100644--- a/frontend/editor/src/proprietary/services/serverPlanCheckout.ts+++ b/frontend/editor/src/proprietary/services/serverPlanCheckout.ts@@ -107,22 +107,53 @@ export async function createServerPlanCheckoutSession(return { clientSecret, url, sessionId: data?.sessionId ?? null };}-/** Returns confirmed purchased seats, or null while fulfilment is pending. */+export interface PendingTeamChange {+ scheduleId: string;+ quantity: number;+ effectiveAt: number;+ interval: string | null;+}++/** Reads or cancels a future Team change; the Edge function verifies the billing leader. */+export async function teamSubscriptionChange(+ action: "status" | "cancel",+ scheduleId?: string,+): Promise<{+ pending: PendingTeamChange | null;+ unsupportedSchedule?: boolean;+}> {+ if (!supabase) throw new Error("Checkout is not configured");+ const token = await getAccessToken();+ if (!token) throw new Error("Sign in to manage your Team plan");+ const { data, error } = await supabase.functions.invoke(+ "team-subscription-change",+ {+ headers: { Authorization: `Bearer ${token}` },+ body: { action, scheduleId },+ },+ );+ if (error || data?.error) throw new Error(data?.error || error?.message);+ return data;+}++/** Returns confirmed purchased seats, a future change, or null while fulfilment is pending. */export async function verifyTeamCheckout(sessionId: string,quantity: number,-): Promise<number | null> {+): Promise<number | PendingTeamChange | null> {if (!supabase) throw new Error("Checkout is not configured");const token = await getAccessToken();if (!token) throw new Error("Sign in to verify the Team purchase");const { data, error } = await supabase.functions.invoke<{ready: boolean;licensedUsers?: number;+ scheduled?: PendingTeamChange;}>("complete-team-checkout", {headers: { Authorization: `Bearer ${token}` },body: { session_id: sessionId, quantity },});if (error) throw error;+ if (data?.scheduled) return data.scheduled;const users = data?.licensedUsers;return data?.ready &&typeof users === "number" &&diff --git a/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.test.ts b/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.test.tsnew file mode 100644index 0000000000..87f9b25202--- /dev/null+++ b/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.test.ts@@ -0,0 +1,30 @@+import { expect, it, vi } from "vitest";+import { pollTeamCheckout } from "@app/utils/licenseCheckoutUtils";+import { verifyTeamCheckout } from "@app/services/serverPlanCheckout";+import { requiresLocalTeamActivation } from "@app/services/teamPlanActivation";++vi.mock("@app/services/serverPlanCheckout", () => ({+ verifyTeamCheckout: vi.fn(),+}));+vi.mock("@app/services/teamPlanActivation", () => ({+ requiresLocalTeamActivation: vi.fn(),+}));+vi.mock("@app/services/licenseService", () => ({ default: {} }));++it("reports a scheduled reduction without activating the lower allowance early", async () => {+ vi.mocked(verifyTeamCheckout).mockResolvedValue({+ scheduleId: "sched_team",+ quantity: 1,+ effectiveAt: 1800000000,+ interval: "month",+ });+ const onActivated = vi.fn();+ expect(+ await pollTeamCheckout("sub_team", 1, { backoffMs: [0], onActivated }),+ ).toEqual({+ success: true,+ scheduledAt: 1800000000,+ });+ expect(requiresLocalTeamActivation).not.toHaveBeenCalled();+ expect(onActivated).not.toHaveBeenCalled();+});diff --git a/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.ts b/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.tsindex 3be63d5828..0af7f8ac7b 100644--- a/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.ts+++ b/frontend/editor/src/proprietary/utils/licenseCheckoutUtils.ts@@ -20,6 +20,10 @@ export async function pollTeamCheckout(if (config.isMounted && !config.isMounted()) return { success: false };try {const purchasedUsers = await verifyTeamCheckout(sessionId, quantity);+ if (purchasedUsers != null && typeof purchasedUsers === "object") {+ config.onStatusChange?.("ready");+ return { success: true, scheduledAt: purchasedUsers.effectiveAt };+ }if (purchasedUsers != null) {if (!(await requiresLocalTeamActivation())) {config.onStatusChange?.("ready");@@ -172,6 +176,7 @@ export async function pollLicenseKeyWithBackoff(*/export interface LicenseActivationResult {success: boolean;+ scheduledAt?: number;licenseType?: string;licenseInfo?: LicenseInfo;error?: string;