#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
feat(billing): one payment screen for every edition (#7887)
ConnorYoh131489a8df29
diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.ymlindex 527dca9703..ff17f5947c 100644--- a/.github/workflows/dependency-review.yml+++ b/.github/workflows/dependency-review.yml@@ -24,3 +24,5 @@ jobs:uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0with:config-file: "./.github/config/dependency-review-config.yml"+ base-ref: ${{ github.event_name == 'workflow_dispatch' && 'main' || '' }}+ head-ref: ${{ github.event_name == 'workflow_dispatch' && github.sha || '' }}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.javaindex 3723a517eb..b225f04bde 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/GateDecision.java@@ -14,6 +14,8 @@ public record GateDecision(boolean allowed, Reason reason) {MANUAL_FREE,/** Linked + within entitlement — billable work allowed. */ENTITLED,+ /** Active local Enterprise licence includes processing without credit charges. */+ ENTERPRISE_LICENSE,FREE_TIER,/** Entitlement source unreachable — fail open, allow. */FAIL_OPEN,diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.javaindex eba5fada99..f0966049ec 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java@@ -7,6 +7,8 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.context.annotation.Profile;import org.springframework.stereotype.Service;+import stirling.software.common.service.LicenseServiceInterface;+/*** Decides whether a request may proceed under combined billing on a self-hosted instance.*@@ -15,6 +17,7 @@ import org.springframework.stereotype.Service;* <ol>* <li>Flag off → always allow (feature inert).* <li>Manual tool → always allow (manual tools are free, never metered).+ * <li>Active Enterprise licence → allow without consuming credits.* <li>Billable + not linked → {@code FREE_TIER} while units remain, else {@code* FREE_TIER_EXHAUSTED}. Linking buys a further grant, it does not activate the feature.* <li>Billable + linked + entitlement unknown (unreachable) → <b>fail open</b>, allow — unless@@ -39,6 +42,7 @@ import org.springframework.stereotype.Service;matchIfMissing = true)public class InstanceEntitlementGate {+ private final LicenseServiceInterface licenseService;private final AccountLinkProperties properties;private final DeviceCredentialStore credentialStore;private final EntitlementCache entitlementCache;@@ -52,7 +56,9 @@ public class InstanceEntitlementGate {EntitlementCache entitlementCache,AccountLinkSyncStateRepository syncStateRepository,LocalUsageService localUsageService,- FreeTierUsageService freeTierUsageService) {+ FreeTierUsageService freeTierUsageService,+ LicenseServiceInterface licenseService) {+ this.licenseService = licenseService;this.properties = properties;this.credentialStore = credentialStore;this.entitlementCache = entitlementCache;@@ -69,6 +75,9 @@ public class InstanceEntitlementGate {if (!billable) {return GateDecision.allow(GateDecision.Reason.MANUAL_FREE);}+ if (licenseService.isRunningEE()) {+ return GateDecision.allow(GateDecision.Reason.ENTERPRISE_LICENSE);+ }boolean linked = credentialStore.isLinked();long freeTierRemaining = linked ? 0L : freeTierUsageService.balance().remainingUnits();Optional<InstanceEntitlement> entitlement =diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.javaindex af8ff8999a..4a36228dc4 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptor.java@@ -172,6 +172,9 @@ public class InstanceEntitlementInterceptor implements HandlerInterceptor {HttpServletResponse response,Object handler,Exception ex) {+ if (request.getAttribute(ATTR_REASON) == GateDecision.Reason.ENTERPRISE_LICENSE) {+ return;+ }// Meter successful billable ops only.if (ex != null || response.getStatus() >= 400) {return;diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBiller.java b/app/proprietary/src/main/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBiller.javaindex b6aa6d8284..ef069f81d3 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBiller.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBiller.java@@ -9,6 +9,7 @@ import org.springframework.stereotype.Component;import lombok.extern.slf4j.Slf4j;+import stirling.software.common.service.LicenseServiceInterface;import stirling.software.proprietary.accountlink.EntitlementCache;import stirling.software.proprietary.accountlink.InstanceEntitlement;import stirling.software.proprietary.accountlink.UsageMeterService;@@ -33,18 +34,22 @@ import stirling.software.proprietary.billing.UnitCalcPolicy;@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")public class AccountLinkAutomationRunBiller implements AutomationRunBiller {+ private final LicenseServiceInterface licenseService;private final EntitlementCache entitlementCache;private final ObjectProvider<UsageMeterService> meterProvider;public AccountLinkAutomationRunBiller(- EntitlementCache entitlementCache, ObjectProvider<UsageMeterService> meterProvider) {+ EntitlementCache entitlementCache,+ ObjectProvider<UsageMeterService> meterProvider,+ LicenseServiceInterface licenseService) {+ this.licenseService = licenseService;this.entitlementCache = entitlementCache;this.meterProvider = meterProvider;}@Overridepublic void recordAutomationRun(List<FileSize> inputs) {- if (inputs.isEmpty()) {+ if (inputs.isEmpty() || licenseService.isRunningEE()) {return;}UsageMeterService meter = meterProvider.getIfAvailable();diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.javaindex bc6ec825fa..fa83432639 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java@@ -47,9 +47,8 @@ public class UserLicenseSettingsService {/*** Users an installation gets before it has to buy capacity. The one free-allowance number in- * Java: the saas seat reader floors on it, and {@code- * pricing_policy.server_free_user_allowance} is seeded to match so the two editions quote the- * same figure.+ * Java: the saas seat reader floors on it, the cloud wallet reports it, and {@code+ * pricing_policy.server_free_user_allowance} is seeded to match.*/public static final int DEFAULT_USER_LIMIT = 5;diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.javaindex c4b29619c9..016c308551 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java@@ -15,6 +15,7 @@ import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;+import stirling.software.common.service.LicenseServiceInterface;import stirling.software.proprietary.accountlink.GateDecision.Reason;/**@@ -24,6 +25,7 @@ import stirling.software.proprietary.accountlink.GateDecision.Reason;@ExtendWith(MockitoExtension.class)class InstanceEntitlementGateTest {+ @Mock private LicenseServiceInterface licenseService;@Mock private DeviceCredentialStore credentialStore;@Mock private EntitlementCache entitlementCache;@Mock private AccountLinkSyncStateRepository syncStateRepository;@@ -266,7 +268,8 @@ class InstanceEntitlementGateTest {entitlementCache,syncStateRepository,localUsageService,- freeTierUsageService);+ freeTierUsageService,+ licenseService);}private static AccountLinkProperties props(boolean meteringEnabled, int graceDays) {diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.javaindex 210ad277e4..ca55092dc1 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateWiringTest.java@@ -1,10 +1,12 @@package stirling.software.proprietary.accountlink;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;import java.time.LocalDateTime;@@ -13,6 +15,8 @@ import java.util.Optional;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import stirling.software.common.service.LicenseServiceInterface;+/** Verifies {@link InstanceEntitlementGate#evaluate} resolves live state from store + cache. */class InstanceEntitlementGateWiringTest {@@ -22,9 +26,11 @@ class InstanceEntitlementGateWiringTest {private LocalUsageService localUsage;private FreeTierUsageService freeTier;private InstanceEntitlementGate gate;+ private LicenseServiceInterface licenseService;@BeforeEachvoid setUp() {+ licenseService = mock(LicenseServiceInterface.class);properties = new AccountLinkProperties();properties.setEnabled(true);store = mock(DeviceCredentialStore.class);@@ -38,7 +44,8 @@ class InstanceEntitlementGateWiringTest {cache,mock(AccountLinkSyncStateRepository.class),localUsage,- freeTier);+ freeTier,+ licenseService);}private static FreeTierUsageService.FreeTierBalance grant(long remaining) {@@ -82,6 +89,26 @@ class InstanceEntitlementGateWiringTest {assertEquals(GateDecision.Reason.ENTITLED, d.reason());}+ @Test+ void enterpriseProcessingDoesNotConsultLinkStatusOrCreditBalances() {+ when(licenseService.isRunningEE()).thenReturn(true);+ GateDecision decision = gate.evaluate(true);+ assertTrue(decision.allowed());+ assertEquals(GateDecision.Reason.ENTERPRISE_LICENSE, decision.reason());+ verifyNoInteractions(store, cache, freeTier, localUsage);+ }++ @Test+ void removingEnterpriseLicenseRestoresCreditEnforcementWithoutRestart() {+ when(licenseService.isRunningEE()).thenReturn(true, false);+ assertTrue(gate.evaluate(true).allowed());+ when(store.isLinked()).thenReturn(false);+ when(freeTier.balance()).thenReturn(grant(0));+ GateDecision decision = gate.evaluate(true);+ assertFalse(decision.allowed());+ assertEquals(GateDecision.Reason.FREE_TIER_EXHAUSTED, decision.reason());+ }+@Testvoid flagOffShortCircuits() {properties.setEnabled(false);diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.javaindex 9d32b4a73d..2d36c8f75b 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java@@ -100,6 +100,19 @@ class InstanceEntitlementInterceptorTest {assertTrue(response.getContentAsString().contains("FREE_TIER_EXHAUSTED"));}+ @Test+ void enterpriseProcessingNeverReachesEitherCreditLedger() throws Exception {+ when(gate.evaluate(anyBoolean()))+ .thenReturn(GateDecision.allow(GateDecision.Reason.ENTERPRISE_LICENSE));+ InstanceEntitlementInterceptor interceptor = interceptor();+ MockHttpServletRequest request = new MockHttpServletRequest("POST", "/api/v1/ai/x");+ MockHttpServletResponse response = new MockHttpServletResponse();+ assertTrue(interceptor.preHandle(request, response, new Object()));+ interceptor.afterCompletion(request, response, new Object(), null);+ verifyNoInteractions(+ freeTierUsageService, entitlementCache, meterProvider, tempFileManager);+ }+@Testvoid metersTheFreeTierLedgerWhenUnlinked() throws Exception {// FREE_TIER is the gate saying "unlinked, inside the grant", so the op must land on thediff --git a/app/proprietary/src/test/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBillerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBillerTest.javaindex 148ba04bec..392b9bc6ff 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBillerTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/automation/AccountLinkAutomationRunBillerTest.java@@ -13,6 +13,7 @@ import org.junit.jupiter.api.Test;import org.mockito.ArgumentMatchers;import org.springframework.beans.factory.ObjectProvider;+import stirling.software.common.service.LicenseServiceInterface;import stirling.software.proprietary.accountlink.EntitlementCache;import stirling.software.proprietary.accountlink.EntitlementState;import stirling.software.proprietary.accountlink.InstanceEntitlement;@@ -26,6 +27,23 @@ class AccountLinkAutomationRunBillerTest {private static final UnitCalcPolicy POLICY = new UnitCalcPolicy(10, 1_000_000L, 1, 1000);private static final LocalDateTime PERIOD = LocalDateTime.of(2026, 9, 1, 0, 0);+ @Test+ void enterpriseLicenseSkipsAccrualUntilRemoved() {+ EntitlementCache cache = mock(EntitlementCache.class);+ when(cache.current()).thenReturn(Optional.of(entitlement(POLICY, PERIOD)));+ UsageMeterService meter = mock(UsageMeterService.class);+ LicenseServiceInterface license = mock(LicenseServiceInterface.class);+ when(license.isRunningEE()).thenReturn(true);+ AccountLinkAutomationRunBiller biller =+ new AccountLinkAutomationRunBiller(cache, providerOf(meter), license);+ List<FileSize> inputs = List.of(new FileSize(25, 5000L));+ biller.recordAutomationRun(inputs);+ org.mockito.Mockito.verifyNoInteractions(cache, meter);+ when(license.isRunningEE()).thenReturn(false);+ biller.recordAutomationRun(inputs);+ verify(meter).accrue(PERIOD, BillingCategory.AUTOMATION, 3L, null);+ }+@SuppressWarnings("unchecked")private static ObjectProvider<UsageMeterService> providerOf(UsageMeterService meter) {ObjectProvider<UsageMeterService> provider = mock(ObjectProvider.class);@@ -44,7 +62,8 @@ class AccountLinkAutomationRunBillerTest {when(cache.current()).thenReturn(Optional.of(entitlement(POLICY, PERIOD)));UsageMeterService meter = mock(UsageMeterService.class);AccountLinkAutomationRunBiller biller =- new AccountLinkAutomationRunBiller(cache, providerOf(meter));+ new AccountLinkAutomationRunBiller(+ cache, providerOf(meter), mock(LicenseServiceInterface.class));// 25 pages -> ceil(25/10)=3 page units; 5000 bytes -> 1 byte unit; max = 3.biller.recordAutomationRun(List.of(new FileSize(25, 5000L)));@@ -56,7 +75,8 @@ class AccountLinkAutomationRunBillerTest {void noAccrueWhenMeterAbsent() {EntitlementCache cache = mock(EntitlementCache.class);AccountLinkAutomationRunBiller biller =- new AccountLinkAutomationRunBiller(cache, providerOf(null));+ new AccountLinkAutomationRunBiller(+ cache, providerOf(null), mock(LicenseServiceInterface.class));biller.recordAutomationRun(List.of(new FileSize(1, 10L)));@@ -69,7 +89,8 @@ class AccountLinkAutomationRunBillerTest {when(cache.current()).thenReturn(Optional.empty());UsageMeterService meter = mock(UsageMeterService.class);AccountLinkAutomationRunBiller biller =- new AccountLinkAutomationRunBiller(cache, providerOf(meter));+ new AccountLinkAutomationRunBiller(+ cache, providerOf(meter), mock(LicenseServiceInterface.class));biller.recordAutomationRun(List.of(new FileSize(1, 10L)));@@ -89,7 +110,8 @@ class AccountLinkAutomationRunBillerTest {.thenReturn(Optional.of(entitlement(null, PERIOD)));UsageMeterService meter = mock(UsageMeterService.class);AccountLinkAutomationRunBiller biller =- new AccountLinkAutomationRunBiller(cache, providerOf(meter));+ new AccountLinkAutomationRunBiller(+ cache, providerOf(meter), mock(LicenseServiceInterface.class));biller.recordAutomationRun(List.of(new FileSize(1, 10L)));biller.recordAutomationRun(List.of(new FileSize(1, 10L)));@@ -107,7 +129,8 @@ class AccountLinkAutomationRunBillerTest {EntitlementCache cache = mock(EntitlementCache.class);UsageMeterService meter = mock(UsageMeterService.class);AccountLinkAutomationRunBiller biller =- new AccountLinkAutomationRunBiller(cache, providerOf(meter));+ new AccountLinkAutomationRunBiller(+ cache, providerOf(meter), mock(LicenseServiceInterface.class));biller.recordAutomationRun(List.of());diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygBillingDetailsController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygBillingDetailsController.javanew file mode 100644index 0000000000..1ca2a9ff81--- /dev/null+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygBillingDetailsController.java@@ -0,0 +1,99 @@+package stirling.software.saas.payg.api;++import java.util.Objects;+import java.util.Optional;++import org.springframework.context.annotation.Profile;+import org.springframework.http.HttpStatus;+import org.springframework.http.ResponseEntity;+import org.springframework.security.access.prepost.PreAuthorize;+import org.springframework.security.core.Authentication;+import org.springframework.transaction.annotation.Transactional;+import org.springframework.web.bind.annotation.GetMapping;+import org.springframework.web.bind.annotation.RequestMapping;+import org.springframework.web.bind.annotation.RestController;++import io.swagger.v3.oas.annotations.Hidden;++import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.proprietary.security.model.User;+import stirling.software.saas.payg.policy.PaygTeamExtensions;+import stirling.software.saas.payg.repository.PaygTeamExtensionsRepository;+import stirling.software.saas.payg.stripe.StripeCustomerDetailsDao;+import stirling.software.saas.security.UserTeamResolver;+import stirling.software.saas.util.AuthenticationUtils;++/**+ * {@code GET /api/v1/payg/billing-details}: who the team is billed to and where its invoices go.+ * The team is resolved from the authenticated principal, never from the request, as {@link+ * PaygPaymentMethodController} and {@link PaygInvoicesController} also do.+ *+ * <p>Read-only by design; Stripe's hosted portal is the one writer. Next-invoice timing is not+ * served here either, since the wallet already carries the period end.+ *+ * <p>No team, no {@code stripe_customer_id}, or a customer absent from the mirror all degrade to+ * {@code 200 present=false}, so the section loses rows rather than failing the page.+ */+@Slf4j+@Hidden+@RestController+@RequestMapping("/api/v1/payg")+@Profile("saas")+public class PaygBillingDetailsController {++ /** {@code present=false} carries no detail fields; either field may be null when present. */+ public record BillingDetailsResponse(boolean present, String companyName, String invoiceEmail) {+ static BillingDetailsResponse absent() {+ return new BillingDetailsResponse(false, null, null);+ }+ }++ private final StripeCustomerDetailsDao customerDetailsDao;+ private final PaygTeamExtensionsRepository extRepo;+ private final UserTeamResolver userTeamResolver;+ private final UserRepository userRepository;++ public PaygBillingDetailsController(+ StripeCustomerDetailsDao customerDetailsDao,+ PaygTeamExtensionsRepository extRepo,+ UserTeamResolver userTeamResolver,+ UserRepository userRepository) {+ this.customerDetailsDao = Objects.requireNonNull(customerDetailsDao, "customerDetailsDao");+ this.extRepo = Objects.requireNonNull(extRepo, "extRepo");+ this.userTeamResolver = Objects.requireNonNull(userTeamResolver, "userTeamResolver");+ this.userRepository = Objects.requireNonNull(userRepository, "userRepository");+ }++ @GetMapping("/billing-details")+ @PreAuthorize("isAuthenticated()")+ @Transactional(readOnly = true)+ public ResponseEntity<BillingDetailsResponse> get(Authentication auth) {+ User user;+ try {+ user = AuthenticationUtils.getCurrentUser(auth, userRepository);+ } catch (SecurityException e) {+ return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();+ }++ Optional<Long> resolvedTeam = userTeamResolver.teamId(user);+ if (resolvedTeam.isEmpty()) {+ return ResponseEntity.ok(BillingDetailsResponse.absent());+ }++ Optional<PaygTeamExtensions> ext = extRepo.findById(resolvedTeam.get());+ if (ext.isEmpty() || ext.get().getStripeCustomerId() == null) {+ return ResponseEntity.ok(BillingDetailsResponse.absent());+ }++ return ResponseEntity.ok(+ customerDetailsDao+ .findDetails(ext.get().getStripeCustomerId())+ .map(+ d ->+ new BillingDetailsResponse(+ true, d.companyName(), d.invoiceEmail()))+ .orElseGet(BillingDetailsResponse::absent));+ }+}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.javaindex abfd0ee405..08ab0fcf70 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java@@ -36,6 +36,7 @@ import stirling.software.proprietary.model.TeamMembership;import stirling.software.proprietary.security.database.repository.UserRepository;import stirling.software.proprietary.security.model.User;import stirling.software.proprietary.security.repository.TeamMembershipRepository;+import stirling.software.proprietary.service.UserLicenseSettingsService;import stirling.software.saas.model.SaasTeamExtensions;import stirling.software.saas.payg.api.WalletSnapshotResponse.ActivityRow;import stirling.software.saas.payg.api.WalletSnapshotResponse.CategoryBreakdown;@@ -232,6 +233,7 @@ public class PaygWalletController {limit,clampToInt(billing.freeGrantUnits()),clampToInt(billing.freeRemainingUnits()),+ UserLicenseSettingsService.DEFAULT_USER_LIMIT,billing.perDocMinor(),billing.currency(),estimatedBill,@@ -509,6 +511,7 @@ public class PaygWalletController {FREE_TIER_LIMIT_UNITS_FALLBACK,FREE_TIER_LIMIT_UNITS_FALLBACK,FREE_TIER_LIMIT_UNITS_FALLBACK,+ UserLicenseSettingsService.DEFAULT_USER_LIMIT,null,null,null,diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.java b/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.javaindex 344656fe6b..4c67f32255 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.java@@ -37,6 +37,8 @@ import java.util.List;* for capped subscribed teams; {@code null} when subscribed with no cap (uncapped).* @param freeAllowance the team's free document grant size per period (the "N" in "X of N free").* Resets each period. Applies to billable categories only.+ * @param freeUserAllowance users the team may have with no Team plan; the denominator the capacity+ * row shows until one is bought.* @param freeRemaining free documents still available to the team this period ({@code* payg_team_extensions.free_units_remaining}). 0 = this period's grant is exhausted.* @param pricePerDocMinor paid per-document rate in minor units of {@code currency} (may be@@ -77,6 +79,9 @@ public record WalletSnapshotResponse(Integer billableLimit,int freeAllowance,int freeRemaining,+ // Sent so both editions read one server-enforced number rather than restating it; the+ // admin-only endpoint that also carries it is not callable by a cloud team lead.+ int freeUserAllowance,BigDecimal pricePerDocMinor,String currency,Long estimatedBillMinor,diff --git a/app/saas/src/main/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDao.java b/app/saas/src/main/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDao.javanew file mode 100644index 0000000000..d604e89e59--- /dev/null+++ b/app/saas/src/main/java/stirling/software/saas/payg/stripe/StripeCustomerDetailsDao.java@@ -0,0 +1,67 @@+package stirling.software.saas.payg.stripe;++import java.util.List;+import java.util.Objects;+import java.util.Optional;++import org.springframework.context.annotation.Profile;+import org.springframework.dao.DataAccessException;+import org.springframework.jdbc.core.JdbcTemplate;+import org.springframework.stereotype.Repository;++import lombok.extern.slf4j.Slf4j;++/**+ * Who the customer is billed to and where invoices go, read from {@code stripe.customers} (Sync+ * Engine mirror).+ *+ * <p>The mirror is one-way, so there is no update path by design: a customer edits these in+ * Stripe's hosted portal and the change arrives on the next customer event, as {@link+ * StripePaymentMethodDao} already relies on for the card.+ */+@Slf4j+@Repository+@Profile("saas")+public class StripeCustomerDetailsDao {++ /** Either field may be null. */+ public record CustomerDetails(String companyName, String invoiceEmail) {}++ private static final String QUERY =+ "SELECT c.name AS name, c.email AS email FROM stripe.customers c WHERE c.id = ?";++ private final JdbcTemplate jdbcTemplate;++ public StripeCustomerDetailsDao(JdbcTemplate jdbcTemplate) {+ this.jdbcTemplate = Objects.requireNonNull(jdbcTemplate, "jdbcTemplate");+ }++ /** Empty on missing schema, unknown customer, or a connectivity blip. */+ public Optional<CustomerDetails> findDetails(String stripeCustomerId) {+ if (stripeCustomerId == null || stripeCustomerId.isBlank()) {+ return Optional.empty();+ }+ try {+ List<CustomerDetails> rows =+ jdbcTemplate.query(+ QUERY,+ (rs, i) ->+ new CustomerDetails(+ blankToNull(rs.getString("name")),+ blankToNull(rs.getString("email"))),+ stripeCustomerId);+ return rows.stream().filter(Objects::nonNull).findFirst();+ } catch (DataAccessException e) {+ log.warn(+ "stripe.customers lookup failed for customer {}: {}",+ stripeCustomerId,+ e.getMessage());+ return Optional.empty();+ }+ }++ /** Stripe stores an unset name or email as an empty string as readily as null. */+ private static String blankToNull(String raw) {+ return raw == null || raw.isBlank() ? null : raw.trim();+ }+}diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.javaindex 7a0c0e7866..5309eeebff 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.java@@ -28,6 +28,7 @@ class WalletSnapshotResponseTest {/* billableLimit= */ 100,/* freeAllowance= */ 500,/* freeRemaining= */ 488,+ /* freeUserAllowance= */ 5,new BigDecimal("1.5"),"usd",/* estimatedBillMinor= */ 1800L,@@ -62,6 +63,7 @@ class WalletSnapshotResponseTest {assertThat(r.billableLimit()).isEqualTo(100);assertThat(r.freeAllowance()).isEqualTo(500);assertThat(r.freeRemaining()).isEqualTo(488);+ assertThat(r.freeUserAllowance()).isEqualTo(5);assertThat(r.pricePerDocMinor()).isEqualByComparingTo("1.5");assertThat(r.currency()).isEqualTo("usd");assertThat(r.estimatedBillMinor()).isEqualTo(1800L);@@ -111,6 +113,7 @@ class WalletSnapshotResponseTest {null,500,500,+ 5,null,null,null,diff --git a/frontend/.storybook/billingSupabaseClient.ts b/frontend/.storybook/billingSupabaseClient.tsnew file mode 100644index 0000000000..6c2cfcb365--- /dev/null+++ b/frontend/.storybook/billingSupabaseClient.ts@@ -0,0 +1,15 @@+import { createClient } from "@supabase/supabase-js";++// Isolate legacy billing stories from the SaaS auth client configured in preview.+export const isSupabaseConfigured = true;+export const supabase = createClient(+ "http://billing.mock",+ "storybook-anon-key",+ {+ auth: {+ persistSession: false,+ autoRefreshToken: false,+ detectSessionInUrl: false,+ },+ },+);diff --git a/frontend/.storybook/main.ts b/frontend/.storybook/main.tsindex f7a772470a..4d0c4d9efa 100644--- a/frontend/.storybook/main.ts+++ b/frontend/.storybook/main.ts@@ -55,6 +55,10 @@ const config: StorybookConfig = {config.resolve = config.resolve ?? {};config.resolve.alias = {...(config.resolve.alias ?? {}),+ "@app/services/supabaseClient": resolve(+ __dirname,+ "billingSupabaseClient.ts",+ ),"@portal": resolve(__dirname, "../editor/src/portal"),// Direct layer aliases so .storybook config files (preview.tsx), which sit// outside src/ and so aren't covered by tsconfigPaths, can import layerdiff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex d530dd7bf8..6346d9b1c0 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -6506,6 +6506,7 @@ paymentCanceled = "Payment was canceled. No charges were made."perMonth = "/month"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."@@ -6516,6 +6517,10 @@ upgradeSuccess = "Payment successful! Your subscription has been upgraded. The lupgradeTitle = "Upgrade to {{planName}}"yearly = "Yearly"+[payment.addCapacity]+currently = "Currently up to {{users}} users"+title = "Add capacity"+[payment.capacityStage]continue = "Continue to payment"customHint = "Rounded up to the next block of {{users}}."@@ -6530,6 +6535,8 @@ perMonth = "/mo"perYear = "/yr"renewalNote = "Renews at {{total}}{{period}}. Cancel any time in Usage & Billing."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"@@ -6548,9 +6555,14 @@ billedYearly = "Billed yearly at {{currency}}{{amount}}"modalTitle = "Select Billing Period - {{planName}}"savePercent = "Save {{percent}}%"savingsAmount = "You save {{amount}}"+selectedMonthly = "Monthly"+selectedYearly = "Yearly"selectMonthly = "Select Monthly"selectYearly = "Select Yearly"+[payment.upgradeTeam]+title = "Upgrade to Team"+[pdfCommentAgent]submit = "Generate comments"@@ -7238,6 +7250,9 @@ going = "Taking you to stirling.com"reauthLede = "Your Stirling session expired. Signing in again keeps usage and billing visible. This server stays connected either way."title = "Connecting"+[portal.accountLink.gate]+retry = "Try again"+[portal.accountLink.instances]active = "Active"revoke = "Revoke"@@ -7367,66 +7382,83 @@ title = "Activating your Processor plan..."limit = "Monthly spend limit {{amount}}/mo. Processing pauses at the limit."limitNoCap = "No spend limit. Processing won't pause. Invoices post monthly."-[portal.billing.enterpriseUpsell]-cta = "Explore Enterprise"-description = "Committed volume discounts, air-gapped deployment, custom MSA and security reviews, and 3rd-party distributor partnerships."-eyebrow = "Volume discount · 1M+ PDFs"-title = "Stirling Enterprise"+[portal.billing.chip]+invoices = "Invoices"+nav = "Sections"+payment = "Payment"+plan = "Plan"+procurement = "Procurement"+usage = "Usage"++[portal.billing.cycle]+credits = "Credits"+creditsNote = "{{units}} used · includes free and prepaid credits"+day = "Day {{day}} of {{of}}"+editors = "Editors deployed"+estimated = "estimated · the meter settles at close"+estimatedPending = "estimated · includes {{pending}} not yet synced from your instances"+pdfs = "PDFs processed"+users = "Users"-[portal.billing.freeEditors]-activeThisMonth = "Active editors (30 days)"-cost = "Cost"-editorsDeployed = "Editors deployed"-inviteTeammates = "Invite teammates"-pdfsEdited = "Edit operations (30 days)"-subtitle = "Deploy anywhere, for your whole team."-title = "Free PDF Editors"+[portal.billing.enterprise]+cta = "Get an enterprise quote"+sub = "Air-gapped deployment, SCIM, data residency, uptime SLAs, and an agreement to match."+title = "Running Stirling in a regulated environment?"[portal.billing.freePlan]-anywhere = "Web, desktop & self-hosted"checkoutErrorTitle = "Couldn't start checkout"-currentPlan = "Current plan"-everyPdfTool = "Every PDF tool"-freeForever = "Free forever"noTeamResolved = "No team is resolved on your wallet yet — refresh and try again."-ownerOnly = "Only the team owner can switch on the Processor plan."payInvoice = "Pay invoice to complete"-planName = "Editor"-switchOnProcessor = "Switch on the Processor →"viewQuote = "View quote"-[portal.billing.invoices]-columnAmount = "Amount"-columnDate = "Date"-columnDescription = "Description"-columnPdfsProcessed = "PDFs processed"-columnStatus = "Status"-descriptionFallback = "Invoice"-downloadAriaLabel = "Download invoice {{number}} as PDF"-emptyDescription = "Once your team subscribes and the first cycle closes, your invoices appear here."-emptyTitle = "No invoices yet"-fetchLimitNote_one = "Showing your {{count}} most recent invoices. Older invoices are in the Stripe portal."-fetchLimitNote_other = "Showing your {{count}} most recent invoices. Older invoices are in the Stripe portal."-loadError = "Couldn't load invoices: {{error}}"-pdfLink = "PDF ↓"-showAll_one = "Show all {{count}}"-showAll_other = "Show all {{count}}"-showFewer_one = "Show fewer (top {{count}})"-showFewer_other = "Show fewer (top {{count}})"-showMostRecent_one = "Show {{count}} most recent"-showMostRecent_other = "Show {{count}} most recent"-title = "Invoice history"-viewAriaLabel = "View invoice {{number}} in Stripe"-viewLink = "View ↗"--[portal.billing.paymentMethod]-billedMonthly = "Billed monthly"-cardEnding = "{{brand}} ending {{last4}}"-cardFallback = "Card"-expiresBilledMonthly = "Expires {{expiry}} · billed monthly"-eyebrow = "Payment method"-managedSub = "Your card and billing details are kept securely in Stripe's customer portal."-managedTitle = "Managed in Stripe"+[portal.billing.identity.free]+chipAnywhere = "Web, desktop & self-hosted"+chipCredits = "{{allowance}} free credits monthly"+chipTools = "Every PDF tool"+name = "Free"+sub = "The full PDF Editor."++[portal.billing.identity.processor]+chipMetered = "Metered processing"+chipPipelines = "Pipelines & API"+name = "Processor"+sub = "Team base plus {{rate}} per credit"+subNoRate = "Team base plus metered processing"++[portal.billing.identity.team]+chipFleet = "Fleet control"+chipSso = "SSO"+name = "Team"+sub = "Up to {{users}} users"+subNoLimit = "No user limit"++[portal.billing.invoiceRow]+current = "Current"+failed = "Unpaid"+paid = "Paid"+undated = "Undated"+unknownAmount = "Unknown"+view = "View"++[portal.billing.license]+add = "Add"+addTitle = "Add license"+empty = "No license installed"+label = "License key"+update = "Update"+updateTitle = "Update license"+view = "View"++[portal.billing.payment]+billedTo = "Billed to"+card = "{{brand}} ending {{last4}}"+cardWithExpiry = "{{brand}} ending {{last4}} · expires {{month}} / {{year}}"+invoicesTo = "Invoices go to"+method = "Payment method"+nextInvoice = "Next invoice"+nextInvoiceNote = "from this cycle's pace"+nextInvoiceValue = "{{date}} · {{amount}}"+noCard = "No card on file"update = "Update"[portal.billing.pdfsProcessed]@@ -7441,7 +7473,6 @@ segmentApiDesc = "Direct API requests"segmentApiLabel = "API"segmentAutomationDesc = "Automations & pipelines"segmentAutomationLabel = "Automation"-sizeMultiplier = "{{formatted}} PDFs used a size multiplier"summary = "{{unique}} unique · {{units}} meter units · {{avg}} avg per PDF"summaryNoRate = "{{unique}} unique · {{units}} meter units"unit = "PDFs"@@ -7547,6 +7578,36 @@ exhausted = "Used up"healthy = "Plenty left"low = "Running low"+[portal.billing.processor]+activate = "Switch on the Processor"+capTooltip = "Pauses PDF processing at your spend limit."+factCapped = "{{pct}}% of {{cap}}"+factFree = "{{used}} of {{allowance}} used"+factNoCap = "no limit"+included = "Included in your license"+midFree = "{{rate}} per credit · {{allowance}} free every month"+midFreeNoRate = "{{allowance}} free every month"+midMetered = "{{spend}} metered this cycle"+midMeteredUnknown = "Metered this cycle"+raiseLimit = "Raise limit"+rowName = "Processor"++[portal.billing.section]+cycle = "This cycle"+invoices = "Invoices"+payment = "Payment"+plan = "Your plan"++[portal.billing.serverPlan]+active = "Active self-hosted license"+connectBody = "Connect to add cloud processing credits. Your server license stays active."+enterprise = "Enterprise"+enterpriseConnectBody = "Your Enterprise license includes processing on this server. Connecting an account is optional."+included = "Included with your license"+seats = "{{seats}} licensed seats"+server = "Server"+unlimited = "Unlimited users"+[portal.billing.spendLimit]adjustLimit = "Adjust limit"cancel = "Cancel"@@ -7572,14 +7633,8 @@ body_one = "At {{rate}}/day you reach the cap in ~{{count}} day (~{{monthEnd}} mbody_other = "At {{rate}}/day you reach the cap in ~{{count}} days (~{{monthEnd}} month-end). Suggested limit ~{{suggested}}."label = "Projected to exceed."-[portal.billing.spendThisMonth]-eyebrow = "Spend this month"-freeRemaining_one = "{{formatted}} free credit remaining"-freeRemaining_other = "{{formatted}} free credits remaining"-processed_one = "{{formattedCount}} PDF processed."-processed_other = "{{formattedCount}} PDFs processed."-processedWithRate_one = "{{formattedCount}} PDF processed, at {{rate}} each."-processedWithRate_other = "{{formattedCount}} PDFs processed, at {{rate}} each."+[portal.billing.spendLimitModal]+title = "Monthly spend limit"[portal.billing.subscribedPlan.capWarn]approachingBody = "Raise it now so automated processing never pauses."@@ -7591,18 +7646,15 @@ reachedTitle = "Monthly spend limit reached"[portal.billing.subscribedPlan.portalError]title = "Couldn't open Stripe portal"-[portal.billing.walletMeter]-barAria = "Free credits remaining"-capSuffix_one = "of {{allowance}} free credit left this month"-capSuffix_other = "of {{allowance}} free credits left this month"-eyebrow = "Processor trial"-statusLabel_one = "{{used}} used"-statusLabel_other = "{{used}} used"-sub = "Use the PDF Editor for free. Pay to process PDFs automatically."-title_one = "{{allowance}} free credit every month"-title_other = "{{allowance}} free credits every month"-titleWithRate_one = "{{allowance}} free credit every month, then {{rate}} per PDF"-titleWithRate_other = "{{allowance}} free credits every month, then {{rate}} per PDF"+[portal.billing.team]+addCapacity = "Add capacity"+fact = "{{users}} of {{licensed}} users"+factNoLimit = "{{users}} users"+midFree = "The Team plan covers 100 users"+midFreeSelfHosted = "The free tier covers your first users"+midIncluded = "Included with your Team base"+midPrice = "$99/mo per 100 users"+rowName = "Users"[portal.components.billingUnit]approval = "approval"@@ -9874,9 +9926,8 @@ type = "Type"close = "Close"[portal.usage]-managePayment = "Manage Payment"-subtitle = "Consumption, invoices, and plan management for every PDF Stirling has billed, in one console."-title = "Usage & billing"+subtitle = "Your plan, your usage, and every invoice."+title = "Usage & Billing"[portal.usage.error]loadWallet = "Couldn't load wallet"@@ -9885,18 +9936,11 @@ walletUnavailable = "Wallet unavailable: {{status}} {{statusText}}"[portal.usage.freeTier]adminOnly = "This server's monthly credits are shared by everyone on it, so only an administrator can see the figures. Everything you can run stays available."-barAria = "Free credits remaining"-capSuffix_one = "of {{allowance}} free credit left this month"-capSuffix_other = "of {{allowance}} free credits left this month"connect = "Connect a Stirling account"+connectBody = "Connecting adds a second monthly allowance, raises the users this server can have, and turns on the Processor."+connectTitle = "This server has no Stirling account"loadError = "Couldn't read this server's credit usage. Try again in a moment."loadErrorTitle = "Couldn't load credit usage"-resets = "Resets {{date}}"-statusLabel_one = "{{used}} used"-statusLabel_other = "{{used}} used"-subtitle = "What this server has processed against its monthly credits."-title_one = "{{allowance}} free credit every month"-title_other = "{{allowance}} free credits every month"[portal.usage.sessionExpired]action = "Sign in again"diff --git a/frontend/editor/src/core/tests/stubbed/pdf-text-editor.spec.ts b/frontend/editor/src/core/tests/stubbed/pdf-text-editor.spec.tsindex 655eb4cf20..8c5b16ddeb 100644--- a/frontend/editor/src/core/tests/stubbed/pdf-text-editor.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/pdf-text-editor.spec.ts@@ -4931,6 +4931,8 @@ test.describe("PDF text editor - stress: save+reopen multi-cycle", () => {test("save+reopen three times in a row (with one edit each) doesn't compound ghost objects", async ({page,}) => {+ // Three persistence round-trips can exceed the single-operation budget on CI runners.+ test.setTimeout(120_000);// Reach: a leak that adds one ghost text object per round-trip would grow// page 0's run count linearly with cycles.await loadFixture(page);diff --git a/frontend/editor/src/portal-saas/PortalProviders.tsx b/frontend/editor/src/portal-saas/PortalProviders.tsxindex 3c702921ea..8c806422f0 100644--- a/frontend/editor/src/portal-saas/PortalProviders.tsx+++ b/frontend/editor/src/portal-saas/PortalProviders.tsx@@ -1,6 +1,8 @@import { TierProvider } from "@portal/contexts/TierContext";import { UIProvider } from "@portal/contexts/UIContext";import { PortalChrome } from "@portal/components/PortalChrome";+import { LicenseProvider } from "@app/contexts/LicenseContext";+import { CheckoutProvider } from "@app/contexts/CheckoutContext";/*** SaaS provider stack. There is no account-link layer: the signed-in account IS@@ -8,12 +10,20 @@ import { PortalChrome } from "@portal/components/PortalChrome";* comes from the wallet (see portal-saas/contexts/usePlanTier). Dropping* LinkProvider / AccountLinkProvider / the login modal here keeps the link* machinery out of the SaaS bundle entirely.+ *+ * <p>Checkout is mounted so the buy doors on Usage & Billing are the same on both editions.+ * LicenseProvider comes with it rather than on its own account: CheckoutProvider calls+ * {@code useLicense}, which throws without one.*/export function PortalProviders() {return (<TierProvider><UIProvider>- <PortalChrome />+ <LicenseProvider>+ <CheckoutProvider>+ <PortalChrome />+ </CheckoutProvider>+ </LicenseProvider></UIProvider></TierProvider>);diff --git a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsxindex fa88c342c2..724bcc74b8 100644--- a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx+++ b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.test.tsx@@ -1,15 +1,33 @@import { describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter, useLocation } from "react-router-dom";vi.mock("@portal/views/Usage", () => ({- Usage: () => <div data-testid="usage" />,+ Usage: ({ onEnterpriseQuote }: { onEnterpriseQuote?: () => void }) => (+ <div data-testid="usage">+ <button onClick={onEnterpriseQuote}>Get enterprise quote</button>+ </div>+ ),}));-import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";+import { BillingSettingsSection } from "@portal/components/settings/BillingSettingsSection";++function Location() {+ return <output>{useLocation().pathname}</output>;+}describe("PortalBillingGate — SaaS", () => {it("renders the Usage page directly, with no link concept", () => {- render(<PortalBillingGate />);+ render(+ <MemoryRouter initialEntries={["/settings/billing"]}>+ <BillingSettingsSection />+ <Location />+ </MemoryRouter>,+ );expect(screen.getByTestId("usage")).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Get enterprise quote" }),+ );+ expect(screen.getByText("/processor/procurement")).toBeInTheDocument();});});diff --git a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsxindex 73c3eba8f3..efb35aaa5e 100644--- a/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx+++ b/frontend/editor/src/portal-saas/components/billing/PortalBillingGate.tsx@@ -1,4 +1,6 @@import { withBasePath } from "@app/constants/app";+import { useNavigate } from "react-router-dom";+import { toPortalPath } from "@portal/contexts/ViewContext";import { Usage } from "@portal/views/Usage";/**@@ -11,8 +13,10 @@ import { Usage } from "@portal/views/Usage";* without this a "Session expired" notice would dead-end until a manual reload.*/export function PortalBillingGate() {+ const navigate = useNavigate();return (<Usage+ onEnterpriseQuote={() => navigate(toPortalPath("/procurement"))}onReauth={() => {window.location.href = withBasePath("/login");}}diff --git a/frontend/editor/src/portal-saas/components/settings/PortalSettingsProviders.tsx b/frontend/editor/src/portal-saas/components/settings/PortalSettingsProviders.tsxnew file mode 100644index 0000000000..a3de04d1a2--- /dev/null+++ b/frontend/editor/src/portal-saas/components/settings/PortalSettingsProviders.tsx@@ -0,0 +1,12 @@+import type { ReactNode } from "react";+import { TierProvider } from "@portal/contexts/TierContext";+import { UIProvider } from "@portal/contexts/UIContext";++/** SaaS settings use the signed-in account, with no instance-link endpoints or dialog. */+export function PortalSettingsProviders({ children }: { children: ReactNode }) {+ return (+ <TierProvider>+ <UIProvider>{children}</UIProvider>+ </TierProvider>+ );+}diff --git a/frontend/editor/src/portal-saas/components/settings/PortalSettingsSectionHost.test.tsx b/frontend/editor/src/portal-saas/components/settings/PortalSettingsSectionHost.test.tsxnew file mode 100644index 0000000000..a85c501cf7--- /dev/null+++ b/frontend/editor/src/portal-saas/components/settings/PortalSettingsSectionHost.test.tsx@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { PortalSettingsSectionHost } from "@portal/components/settings/PortalSettingsSectionHost";+import { useLinkOptional } from "@portal/contexts/LinkContext";+import { useAccountLinkOptional } from "@portal/contexts/AccountLinkContext";+import { useUI } from "@portal/contexts/UIContext";++vi.mock("@portal/contexts/usePlanTier", () => ({ usePlanTier: () => "free" }));++function AccountState() {+ const link = useLinkOptional();+ const accountLink = useAccountLinkOptional();+ const ui = useUI();+ return (+ <output>+ {!link && !accountLink && !ui.linkModalOpen+ ? "cloud account"+ : "instance link"}+ </output>+ );+}++describe("SaaS settings providers", () => {+ it("supplies the billing UI without instance-link state or requests", () => {+ render(+ <PortalSettingsSectionHost>+ <AccountState />+ </PortalSettingsSectionHost>,+ );+ expect(screen.getByText("cloud account")).toBeInTheDocument();+ });+});diff --git a/frontend/editor/src/portal/PortalProviders.tsx b/frontend/editor/src/portal/PortalProviders.tsxindex 76b2655dd8..325e1cec22 100644--- a/frontend/editor/src/portal/PortalProviders.tsx+++ b/frontend/editor/src/portal/PortalProviders.tsx@@ -6,6 +6,9 @@ import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";import { ConnectCallbackHost } from "@portal/components/account-link/ConnectCallbackHost";import { PortalChrome } from "@portal/components/PortalChrome";import { useFreeTierExhaustedPrompt } from "@portal/hooks/useFreeTierExhaustedPrompt";+import { LicenseProvider } from "@app/contexts/LicenseContext";+import { AppConfigProvider } from "@app/contexts/AppConfigContext";+import { CheckoutProvider } from "@app/contexts/CheckoutContext";/** The one and only account-link modal, whichever step it is on. */function LinkModalHost() {@@ -15,8 +18,8 @@ function LinkModalHost() {// the server reporting the month's grant spent.useFreeTierExhaustedPrompt();- // Mounted only while open, so closing discards the flow. Kept mounted, an interrupted hand-off- // stays flagged and every later open resumes on the ghost step with no way forward.+ // Mounted only while open: kept mounted, an interrupted hand-off stays flagged and every+ // later open resumes on a ghost step with no way forward.if (!linkModalOpen) return null;return (<LinkAccountModal@@ -28,16 +31,27 @@ function LinkModalHost() {);}-/** Self-hosted provider stack. */+/**+ * Self-hosted provider stack. Checkout is mounted here rather than inherited: the portal is its+ * own route-set, outside the {@code AppProviders} where the editor keeps its copy.+ * License and checkout both need the local app config; without its provider, license loading+ * waits indefinitely for the admin and login settings.+ */export function PortalProviders() {return (<LinkProvider initialState="unlinked" statusKnown={false}><TierProvider><UIProvider><AccountLinkProvider>- <PortalChrome />- <LinkModalHost />- <ConnectCallbackHost />+ <AppConfigProvider>+ <LicenseProvider>+ <CheckoutProvider>+ <PortalChrome />+ <LinkModalHost />+ <ConnectCallbackHost />+ </CheckoutProvider>+ </LicenseProvider>+ </AppConfigProvider></AccountLinkProvider></UIProvider></TierProvider>diff --git a/frontend/editor/src/portal/api/billing.ts b/frontend/editor/src/portal/api/billing.tsindex 3e76ab2989..92eab21ee7 100644--- a/frontend/editor/src/portal/api/billing.ts+++ b/frontend/editor/src/portal/api/billing.ts@@ -15,6 +15,8 @@ export type {WalletMember,WalletCategoryBreakdown,WalletActivityRow,+ TeamHolding,+ ProcessorHolding,} from "@app/billing";export async function fetchWallet(): Promise<Wallet> {@@ -89,3 +91,16 @@ export interface PaymentMethod {export async function fetchPaymentMethod(): Promise<PaymentMethod> {return apiClient.saas.json<PaymentMethod>("/api/v1/payg/payment-method");}++// GET /api/v1/payg/billing-details. `present: false` when the Stripe mirror carries no+// customer. Read-only: the mirror is one-way, and Stripe's hosted portal is the writer.++export interface BillingDetails {+ present: boolean;+ companyName: string | null;+ invoiceEmail: string | null;+}++export async function fetchBillingDetails(): Promise<BillingDetails> {+ return apiClient.saas.json<BillingDetails>("/api/v1/payg/billing-details");+}diff --git a/frontend/editor/src/portal/api/fleetStats.ts b/frontend/editor/src/portal/api/fleetStats.tsindex 1ac3f822c0..e6fab76ed8 100644--- a/frontend/editor/src/portal/api/fleetStats.ts+++ b/frontend/editor/src/portal/api/fleetStats.ts@@ -1,7 +1,7 @@import { apiClient } from "@portal/api/http";/**- * Free-editor fleet usage for the {@link FreePdfEditorsCard}.+ * Free-editor fleet usage for the billing screen's editors-deployed row.** Self-hosted (this module) reads the local Stirling backend — the figures come* from this instance's audit trail, filtered to free UI tool runs. The SaaS builddiff --git a/frontend/editor/src/portal/components/billing/EnterpriseUpsell.stories.tsx b/frontend/editor/src/portal/components/billing/EnterpriseUpsell.stories.tsxdeleted file mode 100644index 1e2fb83045..0000000000--- a/frontend/editor/src/portal/components/billing/EnterpriseUpsell.stories.tsx+++ /dev/null@@ -1,17 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { EnterpriseUpsell } from "@portal/components/billing/EnterpriseUpsell";-import "@portal/components/billing/billing.css";--const meta: Meta<typeof EnterpriseUpsell> = {- title: "Portal/Billing/EnterpriseUpsell",- component: EnterpriseUpsell,- parameters: { layout: "padded" },-};-export default meta;-type Story = StoryObj<typeof EnterpriseUpsell>;--/** Standalone card — used on the free and subscribed billing views. */-export const Default: Story = {};--/** Bare variant — embeds in another card's column (no surface of its own). */-export const Bare: Story = { args: { bare: true } };diff --git a/frontend/editor/src/portal/components/billing/EnterpriseUpsell.tsx b/frontend/editor/src/portal/components/billing/EnterpriseUpsell.tsxdeleted file mode 100644index 55aaf89b5b..0000000000--- a/frontend/editor/src/portal/components/billing/EnterpriseUpsell.tsx+++ /dev/null@@ -1,58 +0,0 @@-import { useTranslation } from "react-i18next";-import { Button, Card } from "@app/ui";-import { useUI } from "@portal/contexts/UIContext";-import { useView } from "@portal/contexts/ViewContext";--interface Props {- /** Render without the Card wrapper, to embed inside another card's column. */- bare?: boolean;-}--/**- * Volume-discount / Enterprise upsell, shared by the free and subscribed billing- * views. The CTA lands the buyer on Home with the trial-setup step raised — the deal lives there,- * so there is nowhere else to send them.- */-export function EnterpriseUpsell({ bare = false }: Props) {- const { t } = useTranslation();- const { setActiveView } = useView();- const { requestTrialSetup } = useUI();- const body = (- <>- <span className="portal-billing__eyebrow">- {t(- "portal.billing.enterpriseUpsell.eyebrow",- "Volume discount · 1M+ PDFs",- )}- </span>- <div className="portal-billing__enterprise-head">- <div>- <h3 className="portal-billing__section-title">- {t("portal.billing.enterpriseUpsell.title", "Stirling Enterprise")}- </h3>- <p className="portal-billing__section-sub">- {t(- "portal.billing.enterpriseUpsell.description",- "Committed volume discounts, air-gapped deployment, custom MSA and security reviews, and 3rd-party distributor partnerships.",- )}- </p>- </div>- <Button- size="sm"- variant="secondary"- onClick={() => {- // The deal lives on Home; raise the request there rather than sending the buyer to a- // separate view that only mirrors it.- requestTrialSetup();- setActiveView("home");- }}- >- {t("portal.billing.enterpriseUpsell.cta", "Explore Enterprise")}- </Button>- </div>- </>- );- if (bare)- return <div className="portal-billing__enterprise-bare">{body}</div>;- return <Card padding="loose">{body}</Card>;-}diff --git a/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.stories.tsx b/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.stories.tsxdeleted file mode 100644index 1b1a0f1d47..0000000000--- a/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.stories.tsx+++ /dev/null@@ -1,18 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { FreePdfEditorsCard } from "@portal/components/billing/FreePdfEditorsCard";-import "@portal/components/billing/billing.css";--const meta: Meta<typeof FreePdfEditorsCard> = {- title: "Portal/Billing/FreePdfEditorsCard",- component: FreePdfEditorsCard,- parameters: { layout: "padded" },-};-export default meta;-type Story = StoryObj<typeof FreePdfEditorsCard>;--/**- * The team editor-fleet card. Metrics come from GET /api/v1/usage/fleet-stats- * (audit-derived, free UI runs only); with no backend behind Storybook the- * fetch fails and the figures fall back to "N/A". Cost is always $0.- */-export const Default: Story = {};diff --git a/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.tsx b/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.tsxdeleted file mode 100644index a0729d2bf1..0000000000--- a/frontend/editor/src/portal/components/billing/FreePdfEditorsCard.tsx+++ /dev/null@@ -1,83 +0,0 @@-import { useNavigate } from "react-router-dom";-import { useTranslation } from "react-i18next";-import { Button, Card, MetricCard, MetricStrip } from "@app/ui";-import GroupsIcon from "@mui/icons-material/GroupsRounded";-import PersonAddIcon from "@mui/icons-material/PersonAddAltRounded";-import { useFleetStats } from "@portal/queries/infrastructure";--/**- * "Free PDF Editors" team-fleet card. Editors-deployed / active-this-month /- * PDFs-edited come from the instance's usage endpoint- * ({@code GET /api/v1/usage/fleet-stats}), derived from the audit trail filtered- * to free UI tool runs. A figure the backend can't compute (e.g. document recording is- * off) arrives as null and renders "N/A". Activity covers the last 30 days of retained history.- */-function fmtMetric(value: number | null | undefined, loading: boolean): string {- if (loading) return "—";- if (value == null) return "N/A";- return value.toLocaleString();-}--export function FreePdfEditorsCard() {- const navigate = useNavigate();- const { t } = useTranslation();- const { data, loading } = useFleetStats();- return (- <Card padding="loose">- <div className="portal-billing__fleet-row">- <div className="portal-billing__editors-id">- <span className="portal-billing__editors-icon" aria-hidden>- <GroupsIcon sx={{ fontSize: 26 }} />- </span>- <div>- <h3 className="portal-billing__section-title">- {t("portal.billing.freeEditors.title", "Free PDF Editors")}- </h3>- <p className="portal-billing__section-sub">- {t(- "portal.billing.freeEditors.subtitle",- "Deploy anywhere, for your whole team.",- )}- </p>- </div>- </div>- <MetricStrip className="portal-billing__fleet-metrics">- <MetricCard- label={t(- "portal.billing.freeEditors.editorsDeployed",- "Editors deployed",- )}- value={fmtMetric(data?.editorsDeployed, loading)}- />- <MetricCard- label={t(- "portal.billing.freeEditors.activeThisMonth",- "Active editors (30 days)",- )}- value={fmtMetric(data?.activeThisMonth, loading)}- />- <MetricCard- label={t(- "portal.billing.freeEditors.pdfsEdited",- "Edit operations (30 days)",- )}- value={fmtMetric(data?.pdfsProcessed, loading)}- />- <MetricCard- label={t("portal.billing.freeEditors.cost", "Cost")}- value="$0"- />- </MetricStrip>- {/* Opens the Users tab with its invite-member modal (via the ?invite param). */}- <Button- variant="secondary"- size="sm"- leftSection={<PersonAddIcon sx={{ fontSize: 16 }} />}- onClick={() => navigate("/users?invite=1")}- >- {t("portal.billing.freeEditors.inviteTeammates", "Invite teammates")}- </Button>- </div>- </Card>- );-}diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsxindex d81a6e0254..7892ac4bfe 100644--- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx+++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx@@ -1,12 +1,8 @@import { useState } from "react";import { useTranslation } from "react-i18next";-import { Banner, Button, StatusBadge } from "@app/ui";+import { Banner, Button } from "@app/ui";import type { Wallet } from "@portal/api/billing";-import type { LocalUsage } from "@portal/api/link";import type { SaasCurrency } from "@portal/billing/stripe";-import { WalletMeter } from "@portal/components/billing/WalletMeter";-import { FreePdfEditorsCard } from "@portal/components/billing/FreePdfEditorsCard";-import { EnterpriseUpsell } from "@portal/components/billing/EnterpriseUpsell";import { StripeCheckoutModal } from "@portal/components/billing/StripeCheckoutModal";import { ActivationChoiceModal } from "@portal/components/billing/ActivationChoiceModal";import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";@@ -15,8 +11,13 @@ import { useBundleFlowState } from "@portal/hooks/useBundleFlowState";interface Props {wallet: Wallet;- /** Instance-local usage not yet synced to SaaS; folded into the trial meter. */- unsynced?: LocalUsage | null;+ /**+ * Which activation modal is open, when the host wants to drive it. Supplied so the Processor+ * row's own door can start this flow: the flow itself, its bundle state and its modals all stay+ * here, and only the step is lifted.+ */+ step?: "choose" | "payg" | "prepay" | null;+ onStepChange?: (step: "choose" | "payg" | "prepay" | null) => void;/*** Runs the post-checkout activation poll and resolves true once the wallet* reads subscribed (false if it's lagging past the poll window). The checkout@@ -34,11 +35,20 @@ function isSaasCurrency(c: string | null): c is SaasCurrency {* editor fleet, the Processor trial meter (with the inline "Switch on the* Processor" CTA → embedded Stripe Checkout), and the Enterprise upsell.*/-export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {+export function FreePlanView({+ wallet,+ step: controlledStep,+ onStepChange,+ onSubscribed,+}: 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 [step, setStep] = useState<"choose" | "payg" | "prepay" | null>(null);+ const [ownStep, setOwnStep] = useState<"choose" | "payg" | "prepay" | null>(+ null,+ );+ const step = onStepChange ? (controlledStep ?? null) : ownStep;+ const setStep = onStepChange ?? setOwnStep;const [missingTeam, setMissingTeam] = useState<string | null>(null);const isLeader = wallet.role === "leader";@@ -65,12 +75,8 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {return true;}- // No quote yet → open the pay-as-you-go vs prepay fork. A quote already in flight- // → skip the fork and reopen the bundle modal directly; its resume effect lands- // on the calculator (quote) or the payment step (invoice awaiting payment).- function openActivation() {- if (requireTeam()) setStep("choose");- }+ // Reopens the bundle modal directly; its resume effect lands on the calculator (quote) or the+ // payment step (invoice awaiting payment).function resumeBundle() {if (requireTeam()) setStep("prepay");}@@ -82,53 +88,25 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {flow.refresh();}- const switchOnAction = isLeader ? (- <Button- variant="primary"- onClick={flow.status === "none" ? openActivation : resumeBundle}- disabled={wallet.teamId == null}- >- {flow.status === "invoice"- ? t("portal.billing.freePlan.payInvoice", "Pay invoice to complete")- : flow.status === "quote"- ? t("portal.billing.freePlan.viewQuote", "View quote")- : t(- "portal.billing.freePlan.switchOnProcessor",- "Switch on the Processor →",- )}- </Button>- ) : null;+ // Starting the Processor is the row's own door. What survives here is the case that door+ // cannot express: a quote or invoice already raised, which resumes rather than starts.+ const resumeAction =+ isLeader && flow.status !== "none" ? (+ <Button+ variant="primary"+ onClick={resumeBundle}+ disabled={wallet.teamId == null}+ >+ {flow.status === "invoice"+ ? t("portal.billing.freePlan.payInvoice", "Pay invoice to complete")+ : t("portal.billing.freePlan.viewQuote", "View quote")}+ </Button>+ ) : null;return (<div className="portal-billing__stack">- {/* Current plan */}- <div className="portal-billing__current-plan">- <span className="portal-billing__eyebrow">- {t("portal.billing.freePlan.currentPlan", "Current plan")}- </span>- <div className="portal-billing__current-plan-row">- <h2 className="portal-billing__current-plan-name">- {t("portal.billing.freePlan.planName", "Editor")}- </h2>- <StatusBadge tone="success" size="sm" showDot={false}>- {t("portal.billing.freePlan.freeForever", "Free forever")}- </StatusBadge>- <StatusBadge tone="info" size="sm" showDot={false}>- {t("portal.billing.freePlan.everyPdfTool", "Every PDF tool")}- </StatusBadge>- <StatusBadge tone="purple" size="sm" showDot={false}>- {t(- "portal.billing.freePlan.anywhere",- "Web, desktop & self-hosted",- )}- </StatusBadge>- </div>- </div>-- <FreePdfEditorsCard />-- {/* Prepaid capacity is usable independent of a metered subscription, so surface it here on the- free plan too (not just the subscribed dashboard) whenever the team holds a live pool. */}+ {/* A live pool is usable without a metered subscription, so it surfaces on the free plan+ too. The no-pool upsell face never does. */}{wallet.prepaidUnitsRemaining > 0 && (<PrepaidCapacityCardwallet={wallet}@@ -136,12 +114,9 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {/>)}- {/* Processor trial — meter with the inline upgrade CTA */}- <WalletMeter- wallet={wallet}- unsynced={unsynced}- action={switchOnAction}- />+ {resumeAction && (+ <div className="portal-billing__prepaid-foot">{resumeAction}</div>+ )}{missingTeam && (<Banner@@ -154,18 +129,6 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {{missingTeam}</Banner>)}- {!isLeader && (- <p className="portal-billing__plan-readonly">- {t(- "portal.billing.freePlan.ownerOnly",- "Only the team owner can switch on the Processor plan.",- )}- </p>- )}-- {/* Volume discount / Enterprise */}- <EnterpriseUpsell />-<ActivationChoiceModalopen={step === "choose"}onClose={closeModals}diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.css b/frontend/editor/src/portal/components/billing/FreeTierPlanView.cssnew file mode 100644index 0000000000..edfa59a25c--- /dev/null+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.css@@ -0,0 +1,3 @@+.sui-banner.billing-connect {+ align-items: center;+}diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsxindex a2283ef660..27742d8a3e 100644--- a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx@@ -4,22 +4,26 @@ import { MemoryRouter } from "react-router-dom";import { PortalTestProviders } from "@portal/test/TestQueryProvider";/**- * The unlinked usage page reads the instance's own ledger and nothing else — no wallet, so no- * claim about linkage — and it has to survive the endpoint being admin-only, since a non-admin can- * hold a portal grant and reach this page.+ * The unlinked usage page renders the shared billing screen from the instance's own ledger and+ * nothing else — no wallet, so no claim about linkage — and it has to survive its endpoints being+ * admin-only, since a non-admin can hold a portal grant and reach this page.*/-const { fetchFreeTier, openLinkModal } = vi.hoisted(() => ({- fetchFreeTier: vi.fn(),- openLinkModal: vi.fn(),-}));+const { fetchFreeTier, fetchFleetStats, fetchUsers, openLinkModal } =+ vi.hoisted(() => ({+ fetchFreeTier: vi.fn(),+ fetchFleetStats: vi.fn(),+ fetchUsers: vi.fn(),+ openLinkModal: vi.fn(),+ }));vi.mock("@portal/api/link", () => ({ fetchFreeTier }));+vi.mock("@portal/queries/infrastructure", () => ({+ useFleetStats: () => ({ data: null, loading: false, error: null }),+}));+vi.mock("@app/portal/usersBackend", () => ({ usersBackend: { fetchUsers } }));vi.mock("@portal/contexts/UIContext", () => ({useUI: () => ({ openLinkModal }),}));-vi.mock("@portal/components/billing/FreePdfEditorsCard", () => ({- FreePdfEditorsCard: () => null,-}));vi.mock("react-i18next", () => ({useTranslation: () => ({// Interpolated so the figures themselves are what the assertions read.@@ -54,31 +58,50 @@ const renderView = () =>describe("FreeTierPlanView", () => {beforeEach(() => {fetchFreeTier.mockReset();+ fetchFleetStats.mockReset().mockRejectedValue(new Error("no stats"));+ fetchUsers.mockReset().mockRejectedValue(new Error("not admin"));openLinkModal.mockReset();});- it("renders the local meter: used, grant, remaining and when it resets", async () => {+ it("meters the local ledger on the shared screen", async () => {fetchFreeTier.mockResolvedValue(BALANCE);renderView();- expect(await screen.findByText("380")).toBeInTheDocument();- expect(- screen.getByText("of 500 free credits left this month"),- ).toBeInTheDocument();- expect(screen.getByText("120 used")).toBeInTheDocument();- expect(screen.getByText(/^Resets /)).toBeInTheDocument();++ expect(await screen.findByText("120 of 500 used")).toBeInTheDocument();+ // No rate is known locally, so the row quotes the allowance rather than a price.+ expect(screen.getByText("500 free every month")).toBeInTheDocument();});- it("reads only the instance's own ledger", async () => {+ it("reads only the instance's own ledger for the meter", async () => {fetchFreeTier.mockResolvedValue(BALANCE);renderView();- await screen.findByText("380");++ await screen.findByText("120 of 500 used");expect(fetchFreeTier).toHaveBeenCalledTimes(1);});+ it("shows the users this server may have when the admin endpoint answers", async () => {+ fetchFreeTier.mockResolvedValue(BALANCE);+ fetchUsers.mockResolvedValue({ summary: { seatsUsed: 3, seatLimit: 5 } });+ renderView();++ expect(await screen.findByText("3 of 5 users")).toBeInTheDocument();+ });++ it("drops the users row rather than claiming zero when it does not", async () => {+ fetchFreeTier.mockResolvedValue(BALANCE);+ renderView();++ await screen.findByText("120 of 500 used");+ expect(screen.queryByText(/of 0 users/)).toBeNull();+ expect(screen.queryByText("Users")).toBeNull();+ });+it("offers the account as more allowance, and asks for it only on request", async () => {fetchFreeTier.mockResolvedValue(BALANCE);renderView();- await screen.findByText("380");++ await screen.findByText("120 of 500 used");expect(openLinkModal).not.toHaveBeenCalled();expect(screen.getByText("Connect a Stirling account")).toBeInTheDocument();});@@ -86,6 +109,7 @@ describe("FreeTierPlanView", () => {it("tells a non-admin the figures are not theirs to see, rather than failing", async () => {fetchFreeTier.mockRejectedValue(new HttpError(403, "Forbidden", null));renderView();+expect(await screen.findByText(/only an administrator/),).toBeInTheDocument();@@ -95,6 +119,7 @@ describe("FreeTierPlanView", () => {it("reports a real failure as one", async () => {fetchFreeTier.mockRejectedValue(new HttpError(500, "Server Error", null));renderView();+expect(await screen.findByText("Couldn't load credit usage"),).toBeInTheDocument();diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsxindex 6007c47c94..71eb94c75e 100644--- a/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.tsx@@ -1,11 +1,16 @@+import type { ReactNode } from "react";+import type { ServerPlan } from "@app/billing/serverPlan";import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import { Banner, Button, Card, Skeleton } from "@app/ui";-import { formatPeriodDate, MeterBar, remainingMeter } from "@app/billing";+import { Banner, Button, Card } from "@app/ui";+import { BillingScreen } from "@app/billing";+import type { Wallet } from "@app/billing/types";import { fetchFreeTier, type FreeTierBalance } from "@portal/api/link";+import { useFleetStats } from "@portal/queries/infrastructure";+import { usersBackend } from "@app/portal/usersBackend";import { HttpError } from "@portal/api/http";import { useUI } from "@portal/contexts/UIContext";-import { FreePdfEditorsCard } from "@portal/components/billing/FreePdfEditorsCard";+import "@portal/components/billing/FreeTierPlanView.css";/** {@code forbidden} is an outcome, not a failure: the endpoint is admin-only. */type Load =@@ -14,16 +19,81 @@ type Load =| { state: "forbidden" }| { state: "failed" };+interface Seats {+ used: number;+ /** The ceiling the server enforces; null when it is unlimited or unreadable. */+ limit: number | null;+}++/**+ * The local ledger in the shape the shared screen reads.+ *+ * <p>Every field is either a fact this server knows or a deliberate zero: an unlinked instance has+ * bought nothing, so there is no rate, no invoice and no Stripe anything. {@code pricePerDocMinor}+ * stays null rather than guessing, which is what makes the Processor row quote an allowance+ * instead of a price.+ */+function localWallet(balance: FreeTierBalance, seats: Seats | null): Wallet {+ const none = { api: 0, ai: 0, automation: 0 };+ return {+ teamId: null,+ status: "free",+ team: { held: false, licensedUsers: null, usersInUse: seats?.used ?? 0 },+ processor: { active: false },+ role: "leader",+ billingPeriodStart: balance.periodStart,+ billingPeriodEnd: balance.periodEnd,+ billableUsed: balance.usedUnits,+ billableLimit: balance.grantUnits,+ freeAllowance: balance.grantUnits,+ freeUserAllowance: seats?.limit ?? 0,+ freeRemaining: balance.remainingUnits,+ pricePerDocMinor: null,+ bundleRatePerCreditMinor: null,+ currency: null,+ estimatedBillMinor: null,+ capUsd: null,+ noCap: false,+ stripeSubscriptionId: null,+ spendUnitsThisPeriod: balance.usedUnits,+ categoryBreakdown: none,+ categoryDocs: none,+ docsProcessedThisPeriod: 0,+ uniquePdfsThisPeriod: 0,+ sizeMultiplierPdfsThisPeriod: 0,+ billingMode: "payg",+ prepaidUnitsRemaining: 0,+ prepaidUnitsTotal: 0,+ prepaidExpiresAt: null,+ members: [],+ recent: [],+ };+}+/**- * Usage & billing for an instance with no Stirling account. Reads the local endpoint only: loading- * a wallet here would assert linkage the browser's SaaS session cannot vouch for.+ * Usage and billing for an instance with no Stirling account: the same screen a linked team sees,+ * fed from the local ledger, with connecting offered as the way to get more.+ *+ * <p>Reads local endpoints only. Loading a wallet here would assert a linkage the browser's SaaS+ * session cannot vouch for.*/-export function FreeTierPlanView() {+export function FreeTierPlanView({+ licenseSection,+ serverPlan,+ serverPlanAction,+}: {+ licenseSection?: ReactNode;+ serverPlan?: ServerPlan;+ serverPlanAction?: ReactNode;+}) {const { t } = useTranslation();const { openLinkModal } = useUI();// An outcome, not a rendered message: the effect must not depend on `t`, whose identity is// not stable across renders.const [load, setLoad] = useState<Load>({ state: "loading" });+ const [seats, setSeats] = useState<Seats | null>(null);+ const { data: fleetStats } = useFleetStats();+ const editorsDeployed = fleetStats?.editorsDeployed ?? null;useEffect(() => {let cancelled = false;@@ -37,58 +107,87 @@ export function FreeTierPlanView() {e instanceof HttpError && (e.status === 401 || e.status === 403);setLoad({ state: denied ? "forbidden" : "failed" });});+ // User counts are best-effort: this page is the credit meter, and a row is dropped rather than+ // guessed at when its source cannot answer.+ usersBackend+ .fetchUsers("free")+ .then((u) => {+ if (!cancelled) {+ setSeats({ used: u.summary.seatsUsed, limit: u.summary.seatLimit });+ }+ })+ .catch(() => {});return () => {cancelled = true;};}, []);- return (- <div className="portal-usage portal-billing">- <header className="portal-usage__header">- <div className="portal-usage__header-inner">- <div>- <h1 className="portal-usage__title">- {t("portal.usage.title", "Usage & billing")}- </h1>- <p className="portal-usage__subtitle">- {t(- "portal.usage.freeTier.subtitle",- "What this server has processed against its monthly credits.",- )}- </p>- </div>- <Button variant="secondary" fat onClick={() => openLinkModal()}>- {t("portal.usage.freeTier.connect", "Connect a Stirling account")}- </Button>- </div>- </header>-- <div className="portal-usage__body">- {load.state === "loading" && (- <div className="portal-billing__skeleton" aria-hidden>- <Skeleton height="10rem" />- <Skeleton height="14rem" />- </div>- )}+ const wallet =+ load.state === "ready" ? localWallet(load.balance, seats) : null;- {load.state === "failed" && (+ return (+ <BillingScreen+ wallet={wallet}+ loading={load.state === "loading"}+ selfHosted+ licenseSection={licenseSection}+ serverPlan={serverPlan}+ serverPlanAction={serverPlanAction}+ editorsDeployed={editorsDeployed}+ onAddCapacity={() => openLinkModal()}+ onActivateProcessor={() => openLinkModal()}+ notices={+ <><Banner- tone="danger"+ className="billing-connect"+ tone="info"title={t(- "portal.usage.freeTier.loadErrorTitle",- "Couldn't load credit usage",+ "portal.usage.freeTier.connectTitle",+ "This server has no Stirling account",)}+ action={+ <Button size="sm" onClick={() => openLinkModal()}>+ {t(+ "portal.usage.freeTier.connect",+ "Connect a Stirling account",+ )}+ </Button>+ }>- {t(- "portal.usage.freeTier.loadError",- "Couldn't read this server's credit usage. Try again in a moment.",- )}+ {serverPlan?.licenseType === "ENTERPRISE"+ ? t(+ "portal.billing.serverPlan.enterpriseConnectBody",+ "Your Enterprise license includes processing on this server. Connecting an account is optional.",+ )+ : serverPlan+ ? t(+ "portal.billing.serverPlan.connectBody",+ "Connect to add cloud processing credits. Your server license stays active.",+ )+ : t(+ "portal.usage.freeTier.connectBody",+ "Connecting adds a second monthly allowance, raises the users this server can have, and turns on the Processor.",+ )}</Banner>- )}-- {load.state !== "loading" && <FreePdfEditorsCard />}- {load.state === "forbidden" && (+ {load.state === "failed" && (+ <Banner+ tone="danger"+ title={t(+ "portal.usage.freeTier.loadErrorTitle",+ "Couldn't load credit usage",+ )}+ >+ {t(+ "portal.usage.freeTier.loadError",+ "Couldn't read this server's credit usage. Try again in a moment.",+ )}+ </Banner>+ )}+ </>+ }+ extras={+ load.state === "forbidden" ? (<Card padding="loose"><p className="portal-billing__section-sub">{t(@@ -97,68 +196,8 @@ export function FreeTierPlanView() {)}</p></Card>- )}-- {load.state === "ready" && <FreeTierMeter balance={load.balance} />}- </div>- </div>- );-}--function FreeTierMeter({ balance }: { balance: FreeTierBalance }) {- const { t } = useTranslation();- const { state, pct } = remainingMeter(- balance.remainingUnits,- balance.grantUnits,- );- const resets = formatPeriodDate(balance.periodEnd);-- return (- <Card padding="loose">- <div className="portal-billing__subscription-head">- <div>- <h2 className="portal-billing__meter-title">- {t(- "portal.usage.freeTier.title",- "{{allowance}} free credits every month",- {- count: balance.grantUnits,- allowance: balance.grantUnits.toLocaleString(),- },- )}- </h2>- </div>- </div>- <div className="portal-billing__trial-meter">- <MeterBar- state={state}- pct={pct}- barLabel={t(- "portal.usage.freeTier.barAria",- "Free credits remaining",- )}- figure={balance.remainingUnits.toLocaleString()}- capSuffix={t(- "portal.usage.freeTier.capSuffix",- "of {{allowance}} free credits left this month",- {- count: balance.grantUnits,- allowance: balance.grantUnits.toLocaleString(),- },- )}- statusLabel={t("portal.usage.freeTier.statusLabel", "{{used}} used", {- count: balance.usedUnits,- used: balance.usedUnits.toLocaleString(),- })}- meta={- resets- ? t("portal.usage.freeTier.resets", "Resets {{date}}", {- date: resets,- })- : null- }- />- </div>- </Card>+ ) : undefined+ }+ />);}diff --git a/frontend/editor/src/portal/components/billing/InvoicesList.stories.tsx b/frontend/editor/src/portal/components/billing/InvoicesList.stories.tsxdeleted file mode 100644index 90aba9a4fe..0000000000--- a/frontend/editor/src/portal/components/billing/InvoicesList.stories.tsx+++ /dev/null@@ -1,77 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse } from "msw";-import { InvoicesList } from "@portal/components/billing/InvoicesList";-import type { Invoice } from "@portal/api/billing";-import "@portal/components/billing/billing.css";--const meta: Meta<typeof InvoicesList> = {- title: "Portal/Billing/InvoicesList",- component: InvoicesList,- parameters: { layout: "padded" },-};-export default meta;-type Story = StoryObj<typeof InvoicesList>;--function invoice(overrides: Partial<Invoice> & { id: string }): Invoice {- return {- number: null,- status: "paid",- totalMinor: 4900,- currency: "usd",- createdAt: "2026-06-01T00:00:00Z",- periodStart: "2026-05-01T00:00:00Z",- periodEnd: "2026-06-01T00:00:00Z",- hostedInvoiceUrl: "https://invoice.stripe.com/i/mock",- invoicePdf: "https://invoice.stripe.com/i/mock/pdf",- description: "Stirling Processor Plan",- pdfsProcessed: 1204,- ...overrides,- };-}--const SEVEN_INVOICES: Invoice[] = Array.from({ length: 7 }, (_, i) =>- invoice({- id: `in_mock_${i}`,- number: `INV-${1000 + i}`,- status: i === 0 ? "open" : "paid",- createdAt: `2026-0${(i % 6) + 1}-01T00:00:00Z`,- }),-);--/** A handful of recent invoices — the common case. */-export const Default: Story = {- parameters: {- msw: {- handlers: [- http.get("*/api/v1/payg/invoices", () =>- HttpResponse.json(SEVEN_INVOICES),- ),- ],- },- },-};--/** No invoices yet — free team or a subscription with no closed cycle. */-export const Empty: Story = {- parameters: {- msw: {- handlers: [- http.get("*/api/v1/payg/invoices", () => HttpResponse.json([])),- ],- },- },-};--/** Fetch fails — the inline error message renders instead of the table. */-export const LoadError: Story = {- parameters: {- msw: {- handlers: [- http.get(- "*/api/v1/payg/invoices",- () => new HttpResponse(null, { status: 500 }),- ),- ],- },- },-};diff --git a/frontend/editor/src/portal/components/billing/InvoicesList.tsx b/frontend/editor/src/portal/components/billing/InvoicesList.tsxdeleted file mode 100644index 3ad8da9c2c..0000000000--- a/frontend/editor/src/portal/components/billing/InvoicesList.tsx+++ /dev/null@@ -1,243 +0,0 @@-import { useEffect, useState } from "react";-import { useTranslation } from "react-i18next";-import {- Button,- Card,- type CellLink,- column,- DataTable,- type DataTableColumn,- EmptyState,- Skeleton,-} from "@app/ui";-import { formatMinor, formatPeriodDate } from "@app/billing";-import { fetchInvoices, type Invoice } from "@portal/api/billing";--const DEFAULT_VISIBLE = 5;-/** Fetch a few more than DEFAULT_VISIBLE so "Show more" actually has something to show. */-const FETCH_LIMIT = 20;--function statusTone(- status: string,-): "success" | "warning" | "danger" | "neutral" {- switch (status) {- case "paid":- return "success";- case "open":- case "draft":- return "warning";- case "uncollectible":- case "void":- return "danger";- default:- return "neutral";- }-}--/**- * Recent Stripe invoices, sourced from GET /api/v1/payg/invoices (reads- * stripe.invoices via the Sync Engine). Backend orders newest first AND- * filters out drafts (matching Stripe's own customer portal behavior —- * drafts have no public hosted URL or PDF). We fetch FETCH_LIMIT rows and- * show DEFAULT_VISIBLE by default with a "Show all N" inline toggle. For- * history older than FETCH_LIMIT, the Stripe customer portal (button on the- * Subscription card above) is the authoritative archive.- *- * Each row links straight out to Stripe-hosted assets — the invoice page- * ({@code hostedInvoiceUrl}) and the PDF ({@code invoicePdf}). Rendered as- * actual {@code <a target="_blank">} anchors rather than {@code window.open}- * handlers so they're real user gestures (popup blockers don't trip).- */-export function InvoicesList() {- const { t } = useTranslation();- const [invoices, setInvoices] = useState<Invoice[] | null>(null);- const [error, setError] = useState<string | null>(null);- const [showAll, setShowAll] = useState(false);-- useEffect(() => {- let cancelled = false;- setError(null);- fetchInvoices(FETCH_LIMIT)- .then((rows) => {- if (!cancelled) setInvoices(rows);- })- .catch((e) => {- if (!cancelled) setError(e instanceof Error ? e.message : String(e));- });- return () => {- cancelled = true;- };- }, []);-- const total = invoices?.length ?? 0;- const visible = showAll ? total : Math.min(DEFAULT_VISIBLE, total);- const visibleRows = invoices?.slice(0, visible) ?? [];- const hasMore = total > DEFAULT_VISIBLE;- // We only fetched FETCH_LIMIT rows — at the cap there may be older invoices we- // didn't load, so don't claim "all".- const atFetchLimit = total >= FETCH_LIMIT;-- // Column layout mirrors Stripe's own customer-portal "Invoice history" rows:- // Date · Amount · Status · Description (product name) · Actions- // The monospace invoice id is dropped — users care about "what was it for",- // not the internal id.- const columns: DataTableColumn<Invoice>[] = [- column.text({- key: "date",- header: t("portal.billing.invoices.columnDate", "Date"),- sortable: true,- // Sort chronologically on the raw ISO timestamp, not the formatted label.- sortBy: (inv) => inv.createdAt ?? undefined,- get: (inv) =>- inv.createdAt ? formatPeriodDate(inv.createdAt, { year: true }) : "-",- }),- column.number({- key: "pdfs",- header: t(- "portal.billing.invoices.columnPdfsProcessed",- "PDFs processed",- ),- sortable: true,- // Billed units on the invoice's metered line item; blank when the- // line-item table isn't synced into the Stripe mirror.- get: (inv) => inv.pdfsProcessed,- format: (n) => n.toLocaleString(),- }),- column.number({- key: "amount",- header: t("portal.billing.invoices.columnAmount", "Amount"),- sortable: true,- get: (inv) => inv.totalMinor,- format: (n, inv) => formatMinor(n, inv.currency),- }),- column.badge({- key: "status",- header: t("portal.billing.invoices.columnStatus", "Status"),- sortable: true,- get: (inv) => ({ tone: statusTone(inv.status), label: inv.status }),- }),- column.text({- key: "description",- header: t("portal.billing.invoices.columnDescription", "Description"),- sortable: true,- get: (inv) =>- inv.description ??- t("portal.billing.invoices.descriptionFallback", "Invoice"),- }),- column.links({- key: "actions",- get: (inv) => {- const out: CellLink[] = [];- if (inv.hostedInvoiceUrl) {- out.push({- label: t("portal.billing.invoices.viewLink", "View ↗"),- href: inv.hostedInvoiceUrl,- ariaLabel: t(- "portal.billing.invoices.viewAriaLabel",- "View invoice {{number}} in Stripe",- { number: inv.number ?? inv.id },- ),- });- }- if (inv.invoicePdf) {- out.push({- label: t("portal.billing.invoices.pdfLink", "PDF ↓"),- href: inv.invoicePdf,- ariaLabel: t(- "portal.billing.invoices.downloadAriaLabel",- "Download invoice {{number}} as PDF",- { number: inv.number ?? inv.id },- ),- });- }- return out;- },- }),- ];-- return (- <Card padding="loose">- <h3 className="portal-billing__section-title">- {t("portal.billing.invoices.title", "Invoice history")}- </h3>-- {invoices === null && !error && (- <div className="portal-billing__skeleton" aria-hidden>- <Skeleton height="2.5rem" />- <Skeleton height="2.5rem" />- <Skeleton height="2.5rem" />- </div>- )}-- {error && (- <p className="portal-billing__error" role="alert">- {t(- "portal.billing.invoices.loadError",- "Couldn't load invoices: {{error}}",- { error },- )}- </p>- )}-- {invoices !== null && invoices.length === 0 && !error && (- <EmptyState- size="compact"- title={t("portal.billing.invoices.emptyTitle", "No invoices yet")}- description={t(- "portal.billing.invoices.emptyDescription",- "Once your team subscribes and the first cycle closes, your invoices appear here.",- )}- />- )}-- {invoices !== null && invoices.length > 0 && (- <>- <DataTable- columns={columns}- rows={visibleRows}- rowKey={(inv) => inv.id}- defaultSort={{ key: "date", direction: "desc" }}- />- {hasMore && (- <div className="portal-billing__invoice-footer">- <Button- variant="tertiary"- size="sm"- onClick={() => setShowAll((v) => !v)}- >- {showAll- ? t(- "portal.billing.invoices.showFewer",- "Show fewer (top {{count}})",- { count: DEFAULT_VISIBLE },- )- : atFetchLimit- ? t(- "portal.billing.invoices.showMostRecent",- "Show {{count}} most recent",- { count: total },- )- : t(- "portal.billing.invoices.showAll",- "Show all {{count}}",- {- count: total,- },- )}- </Button>- {showAll && atFetchLimit && (- <span className="portal-billing__invoice-note">- {t(- "portal.billing.invoices.fetchLimitNote",- "Showing your {{count}} most recent invoices. Older invoices are in the Stripe portal.",- { count: FETCH_LIMIT },- )}- </span>- )}- </div>- )}- </>- )}- </Card>- );-}diff --git a/frontend/editor/src/portal/components/billing/InvoicesSection.tsx b/frontend/editor/src/portal/components/billing/InvoicesSection.tsxnew file mode 100644index 0000000000..a1e73252c6--- /dev/null+++ b/frontend/editor/src/portal/components/billing/InvoicesSection.tsx@@ -0,0 +1,100 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ InvoiceRow,+ formatMinor,+ formatPeriodDate,+ type InvoiceRowState,+} from "@app/billing";+import { fetchInvoices, type Invoice } from "@portal/api/billing";++const LIMIT = 6;++/**+ * Stripe's invoice statuses, mapped to the four states a row can show. {@code open} is issued but+ * unpaid, not a draft: the backend filters drafts out, since a draft has no document to open.+ */+function rowState(status: string): InvoiceRowState {+ switch (status) {+ case "paid":+ return "paid";+ case "open":+ return "current";+ case "uncollectible":+ case "void":+ return "failed";+ default:+ return "other";+ }+}++/**+ * The Invoices section for the portal host, newest first. Renders nothing when there are none, so+ * the host can drop the section and its chip.+ */+export function InvoicesSection({+ onEmpty,+}: {+ /** Called once the fetch settles with no invoices, so the host can drop the section. */+ onEmpty?: () => void;+}) {+ const { t } = useTranslation();+ const [rows, setRows] = useState<Invoice[] | null>(null);++ useEffect(() => {+ let cancelled = false;+ fetchInvoices(LIMIT)+ .then((r) => {+ if (cancelled) return;+ setRows(r);+ if (r.length === 0) onEmpty?.();+ })+ .catch(() => {+ if (cancelled) return;+ setRows([]);+ onEmpty?.();+ });+ return () => {+ cancelled = true;+ };+ }, [onEmpty]);++ if (!rows || rows.length === 0) return null;++ const label = (s: InvoiceRowState, raw: string) =>+ s === "paid"+ ? t("portal.billing.invoiceRow.paid", "Paid")+ : s === "current"+ ? t("portal.billing.invoiceRow.current", "Current")+ : s === "failed"+ ? t("portal.billing.invoiceRow.failed", "Unpaid")+ : raw;++ return (+ <>+ {rows.map((inv) => {+ const state = rowState(inv.status);+ return (+ <InvoiceRow+ key={inv.id}+ date={+ inv.createdAt+ ? formatPeriodDate(inv.createdAt, { year: true })+ : t("portal.billing.invoiceRow.undated", "Undated")+ }+ description={inv.description}+ amount={+ inv.totalMinor != null+ ? formatMinor(inv.totalMinor, inv.currency)+ : t("portal.billing.invoiceRow.unknownAmount", "Unknown")+ }+ state={state}+ stateLabel={label(state, inv.status)}+ href={inv.hostedInvoiceUrl}+ viewLabel={t("portal.billing.invoiceRow.view", "View")}+ />+ );+ })}+ </>+ );+}diff --git a/frontend/editor/src/portal/components/billing/PaymentMethodCard.stories.tsx b/frontend/editor/src/portal/components/billing/PaymentMethodCard.stories.tsxdeleted file mode 100644index 63b492107e..0000000000--- a/frontend/editor/src/portal/components/billing/PaymentMethodCard.stories.tsx+++ /dev/null@@ -1,51 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse } from "msw";-import { PaymentMethodCard } from "@portal/components/billing/PaymentMethodCard";-import "@portal/components/billing/billing.css";--const meta: Meta<typeof PaymentMethodCard> = {- title: "Portal/Billing/PaymentMethodCard",- component: PaymentMethodCard,- args: { onManage: () => {} },- parameters: { layout: "padded" },-};-export default meta;-type Story = StoryObj<typeof PaymentMethodCard>;--/** Card present in the Stripe mirror. */-export const WithCard: Story = {- parameters: {- msw: {- handlers: [- http.get("*/api/v1/payg/payment-method", () =>- HttpResponse.json({- present: true,- brand: "visa",- last4: "4242",- expMonth: 8,- expYear: 2027,- }),- ),- ],- },- },-};--/** Mirror carries no card (table not synced / no card on file) — neutral fallback. */-export const ManagedInStripe: Story = {- parameters: {- msw: {- handlers: [- http.get("*/api/v1/payg/payment-method", () =>- HttpResponse.json({- present: false,- brand: null,- last4: null,- expMonth: null,- expYear: null,- }),- ),- ],- },- },-};diff --git a/frontend/editor/src/portal/components/billing/PaymentMethodCard.tsx b/frontend/editor/src/portal/components/billing/PaymentMethodCard.tsxdeleted file mode 100644index 4904e8364b..0000000000--- a/frontend/editor/src/portal/components/billing/PaymentMethodCard.tsx+++ /dev/null@@ -1,109 +0,0 @@-import { useEffect, useState } from "react";-import { useTranslation } from "react-i18next";-import { Button, Card } from "@app/ui";-import { fetchPaymentMethod, type PaymentMethod } from "@portal/api/billing";--interface Props {- /** Opens the Stripe customer portal (card changes live in Stripe, not here). */- onManage: () => void;- managing?: boolean;-}--function titleCase(s: string): string {- return s ? s.charAt(0).toUpperCase() + s.slice(1) : s;-}--/**- * The team's default card, read from the Stripe mirror via- * {@code GET /api/v1/payg/payment-method}. When the mirror doesn't carry the- * card (table not synced, or no card on file) we don't invent one — we show a- * neutral "managed in Stripe" state. Editing always happens in Stripe's portal;- * the Update button just deep-links there.- */-export function PaymentMethodCard({ onManage, managing }: Props) {- const { t } = useTranslation();- // undefined = loading, null = none/unavailable, object = real card.- const [pm, setPm] = useState<PaymentMethod | null | undefined>(undefined);-- useEffect(() => {- let cancelled = false;- fetchPaymentMethod()- .then((p) => {- if (!cancelled) setPm(p.present ? p : null);- })- .catch(() => {- if (!cancelled) setPm(null);- });- return () => {- cancelled = true;- };- }, []);-- const hasCard = pm != null && pm.last4 != null;-- return (- <Card padding="loose">- <div className="portal-billing__subscription-head">- <div>- <span className="portal-billing__eyebrow">- {t("portal.billing.paymentMethod.eyebrow", "Payment method")}- </span>- {hasCard ? (- <>- <h3 className="portal-billing__section-title">- {t(- "portal.billing.paymentMethod.cardEnding",- "{{brand}} ending {{last4}}",- {- brand: titleCase(- pm.brand ??- t("portal.billing.paymentMethod.cardFallback", "Card"),- ),- last4: pm.last4,- },- )}- </h3>- <p className="portal-billing__section-sub">- {pm.expMonth != null && pm.expYear != null- ? t(- "portal.billing.paymentMethod.expiresBilledMonthly",- "Expires {{expiry}} · billed monthly",- {- expiry: `${String(pm.expMonth).padStart(2, "0")}/${pm.expYear}`,- },- )- : t(- "portal.billing.paymentMethod.billedMonthly",- "Billed monthly",- )}- </p>- </>- ) : (- <>- <h3 className="portal-billing__section-title">- {t(- "portal.billing.paymentMethod.managedTitle",- "Managed in Stripe",- )}- </h3>- <p className="portal-billing__section-sub">- {t(- "portal.billing.paymentMethod.managedSub",- "Your card and billing details are kept securely in Stripe's customer portal.",- )}- </p>- </>- )}- </div>- <Button- variant="secondary"- size="sm"- loading={managing}- onClick={onManage}- >- {t("portal.billing.paymentMethod.update", "Update")}- </Button>- </div>- </Card>- );-}diff --git a/frontend/editor/src/portal/components/billing/PaymentSection.tsx b/frontend/editor/src/portal/components/billing/PaymentSection.tsxnew file mode 100644index 0000000000..3c2481ce18--- /dev/null+++ b/frontend/editor/src/portal/components/billing/PaymentSection.tsx@@ -0,0 +1,133 @@+import { estimatedBillWithPending } from "@app/billing/pendingUsage";+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { KvRow, formatMinor, formatPeriodDate } from "@app/billing";+import {+ fetchBillingDetails,+ fetchPaymentMethod,+ type BillingDetails,+ type PaymentMethod,+ type Wallet,+} from "@portal/api/billing";++/**+ * The Payment section for the portal host, read off the Stripe mirror.+ *+ * <p>{@code present: false} is indistinguishable from "not synced yet", so the row reports the+ * card as missing rather than inventing a brand.+ */+export function PaymentSection({+ wallet,+ pendingUnits = 0,+ onManage,+ managing = false,+}: {+ /** Supplies the next-invoice date and estimate. */+ wallet: Wallet;+ pendingUnits?: number;+ /** Opens the Stripe customer portal, which is where all of these are edited. */+ onManage?: () => void;+ managing?: boolean;+}) {+ const { t } = useTranslation();+ const estimatedMinor = estimatedBillWithPending(wallet, pendingUnits);+ const [pm, setPm] = useState<PaymentMethod | null>(null);+ const [details, setDetails] = useState<BillingDetails | null>(null);++ useEffect(() => {+ let cancelled = false;+ // Best-effort: a failed read leaves the "no card" copy rather than breaking the section.+ fetchPaymentMethod()+ .then((m) => {+ if (!cancelled) setPm(m);+ })+ .catch(() => {+ if (!cancelled) setPm(null);+ });+ fetchBillingDetails()+ .then((d) => {+ if (!cancelled) setDetails(d);+ })+ .catch(() => {+ if (!cancelled) setDetails(null);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const card =+ pm?.present && pm.brand && pm.last4+ ? pm.expMonth && pm.expYear+ ? t(+ "portal.billing.payment.cardWithExpiry",+ "{{brand}} ending {{last4}} · expires {{month}} / {{year}}",+ {+ brand: pm.brand,+ last4: pm.last4,+ month: String(pm.expMonth).padStart(2, "0"),+ year: pm.expYear,+ },+ )+ : t("portal.billing.payment.card", "{{brand}} ending {{last4}}", {+ brand: pm.brand,+ last4: pm.last4,+ })+ : t("portal.billing.payment.noCard", "No card on file");++ // The mirror cannot be written, so every row shares one door into Stripe's hosted portal.+ const update = onManage ? (+ <button type="button" onClick={onManage} disabled={managing}>+ {t("portal.billing.payment.update", "Update")}+ </button>+ ) : undefined;++ return (+ <>+ <KvRow+ label={t("portal.billing.payment.method", "Payment method")}+ value={card}+ door={update}+ />+ <KvRow+ label={t("portal.billing.payment.nextInvoice", "Next invoice")}+ note={+ wallet.processor.active+ ? t(+ "portal.billing.payment.nextInvoiceNote",+ "from this cycle's pace",+ )+ : undefined+ }+ value={+ estimatedMinor != null+ ? t(+ "portal.billing.payment.nextInvoiceValue",+ "{{date}} · {{amount}}",+ {+ date: formatPeriodDate(wallet.billingPeriodEnd, {+ year: true,+ }),+ amount: formatMinor(estimatedMinor, wallet.currency),+ },+ )+ : formatPeriodDate(wallet.billingPeriodEnd, { year: true })+ }+ />+ {details?.companyName && (+ <KvRow+ label={t("portal.billing.payment.billedTo", "Billed to")}+ value={details.companyName}+ door={update}+ />+ )}+ {details?.invoiceEmail && (+ <KvRow+ label={t("portal.billing.payment.invoicesTo", "Invoices go to")}+ value={details.invoiceEmail}+ door={update}+ />+ )}+ </>+ );+}diff --git a/frontend/editor/src/portal/components/billing/PdfsProcessedCard.tsx b/frontend/editor/src/portal/components/billing/PdfsProcessedCard.tsxindex d36da95dd3..10d047a460 100644--- a/frontend/editor/src/portal/components/billing/PdfsProcessedCard.tsx+++ b/frontend/editor/src/portal/components/billing/PdfsProcessedCard.tsx@@ -66,7 +66,6 @@ export function PdfsProcessedCard({const docs = wallet.docsProcessedThisPeriod;const uniquePdfs = wallet.uniquePdfsThisPeriod;const meterUnits = wallet.spendUnitsThisPeriod + pendingUnits;- const sizeMultiplierPdfs = wallet.sizeMultiplierPdfsThisPeriod;// Per-category PDF counts drive the split ("this many PDFs ran automation / AI /// API"); units are surfaced in the aggregate summary line, not per bucket.@@ -170,15 +169,6 @@ export function PdfsProcessedCard({</div></>) : null}- {sizeMultiplierPdfs > 0 ? (- <p className="portal-billing__section-sub">- {t(- "portal.billing.pdfsProcessed.sizeMultiplier",- "{{formatted}} PDFs used a size multiplier",- { formatted: sizeMultiplierPdfs.toLocaleString() },- )}- </p>- ) : null}</>) : pendingUnits > 0 ? (// docs == 0 but instance-local units have accrued that SaaS hasn't billed yetdiff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsxindex c21414ee0f..30dc8061dd 100644--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.test.tsx@@ -1,6 +1,13 @@+vi.mock("@portal/hooks/useServerPlan", () => ({+ useServerPlan: () => ({ serverPlan: undefined, loading: false }),+}));+vi.mock("@portal/components/billing/ServerLicenseSection", () => ({+ ServerLicenseSection: () => null,+}));+import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";-import { MemoryRouter } from "react-router-dom";+import { fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter, useLocation } from "react-router-dom";/*** Which usage page this instance has one of. The unlinked half must not go anywhere near the@@ -28,21 +35,36 @@ vi.mock("@portal/hooks/usePortalAdmin", () => ({usePortalAdmin: () => admin.is,}));vi.mock("@portal/views/Usage", () => ({- Usage: ({ onWalletLoaded }: { onWalletLoaded?: (w: unknown) => void }) => {+ Usage: ({+ onWalletLoaded,+ onEnterpriseQuote,+ }: {+ onWalletLoaded?: (w: unknown) => void;+ onEnterpriseQuote?: () => void;+ }) => {onWalletLoaded?.({ status: "free" });- return <div data-testid="usage" />;+ return (+ <div data-testid="usage">+ <button onClick={onEnterpriseQuote}>Get enterprise quote</button>+ </div>+ );},}));vi.mock("@portal/components/billing/FreeTierPlanView", () => ({FreeTierPlanView: () => <div data-testid="free-tier" />,}));-import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate";+import { BillingSettingsSection } from "@portal/components/settings/BillingSettingsSection";++function Location() {+ return <output>{useLocation().pathname}</output>;+}const renderGate = () =>render(- <MemoryRouter initialEntries={["/processor/usage"]}>- <PortalBillingGate />+ <MemoryRouter initialEntries={["/settings/billing"]}>+ <BillingSettingsSection />+ <Location /></MemoryRouter>,);@@ -63,6 +85,15 @@ describe("PortalBillingGate — self-hosted", () => {expect(screen.queryByTestId("usage")).toBeNull();});+ it("starts enterprise through the processor entry route across the settings provider boundary", () => {+ link.is = true;+ renderGate();+ fireEvent.click(+ screen.getByRole("button", { name: "Get enterprise quote" }),+ );+ expect(screen.getByText("/processor/procurement")).toBeInTheDocument();+ });+it("asks for nothing on the way in", () => {gate.gated = true;renderGate();diff --git a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsxindex 2e09894710..4d2f05d85a 100644--- a/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx+++ b/frontend/editor/src/portal/components/billing/PortalBillingGate.tsx@@ -1,4 +1,8 @@+import { ServerLicenseSection } from "@portal/components/billing/ServerLicenseSection";+import { useServerPlan } from "@portal/hooks/useServerPlan";+import { ManageBillingButton } from "@app/components/shared/ManageBillingButton";import { useCallback } from "react";+import { useNavigate } from "react-router-dom";import {useApplyLinkFacts,useLinkOptional,@@ -7,6 +11,7 @@ import { useUI } from "@portal/contexts/UIContext";import { useConnectGate } from "@portal/hooks/useConnectGate";import { usePortalAdmin } from "@portal/hooks/usePortalAdmin";import { FreeTierPlanView } from "@portal/components/billing/FreeTierPlanView";+import { toPortalPath } from "@portal/contexts/ViewContext";import { Usage } from "@portal/views/Usage";import type { Wallet } from "@portal/api/billing";@@ -22,22 +27,47 @@ export function PortalBillingGate() {const { openLinkModal } = useUI();const { loading } = useConnectGate();const isAdmin = usePortalAdmin();+ const { serverPlan, loading: licenseLoading } = useServerPlan(isAdmin);+ const serverPlanAction = serverPlan ? <ManageBillingButton /> : undefined;const link = useLinkOptional();+ const navigate = useNavigate();const onWalletLoaded = useCallback((w: Wallet) => applyLinkFacts(true, w.status === "subscribed"),[applyLinkFacts],);const onReauth = useCallback(() => openLinkModal("reauth"), [openLinkModal]);+ // The processor owns a separate UIProvider, so its entry route must raise the trial request.+ const onEnterpriseQuote = useCallback(() => {+ navigate(toPortalPath("/procurement"));+ }, [navigate]);// Administrators only: the figures are instance-wide and the endpoints ADMIN-gated. The nav// hides the entry to match, so this is the backstop for a typed URL.if (!isAdmin) return null;// Neither page while the answer is unknown: showing the local meter to a linked instance would// present a dormant ledger as its live one.- if (loading) return null;+ if (loading || licenseLoading) return null;// A positively known link, not merely "not gated": linking turned off and a failed status// check are neither, and must not reach a SaaS this instance has no address for.- if (!link?.isLinked) return <FreeTierPlanView />;- return <Usage onWalletLoaded={onWalletLoaded} onReauth={onReauth} />;+ if (!link?.isLinked)+ return (+ <FreeTierPlanView+ serverPlan={serverPlan}+ serverPlanAction={serverPlanAction}+ licenseSection={<ServerLicenseSection onSaved={() => {}} />}+ />+ );+ return (+ <Usage+ serverPlan={serverPlan}+ serverPlanAction={serverPlanAction}+ renderLicenseSection={(onSaved) => (+ <ServerLicenseSection onSaved={onSaved} />+ )}+ onWalletLoaded={onWalletLoaded}+ onReauth={onReauth}+ onEnterpriseQuote={onEnterpriseQuote}+ />+ );}diff --git a/frontend/editor/src/portal/components/billing/ServerLicenseSection.tsx b/frontend/editor/src/portal/components/billing/ServerLicenseSection.tsxnew file mode 100644index 0000000000..74d9a3ac84--- /dev/null+++ b/frontend/editor/src/portal/components/billing/ServerLicenseSection.tsx@@ -0,0 +1,128 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { useLicense } from "@app/contexts/LicenseContext";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import LicenseKeySection from "@app/components/shared/config/configSections/plan/LicenseKeySection";+import { KvRow } from "@app/billing/KvRow";+import { Banner, Button, Spinner } from "@app/ui";+import { Modal } from "@app/ui/Modal";++/** The caller must restrict this server-local license surface to administrators. */+export function ServerLicenseSection({ onSaved }: { onSaved: () => void }) {+ const { t } = useTranslation();+ const { licenseInfo, loading, error, refetchLicense } = useLicense();+ const { error: configError, refetch: refetchConfig } = useAppConfig();+ const [dialog, setDialog] = useState<"view" | "update" | null>(null);+ const storedKey = licenseInfo?.licenseKey?.trim();+ const licenseKey =+ storedKey === "00000000-0000-0000-0000-000000000000"+ ? undefined+ : storedKey;+ const certificate = licenseKey?.startsWith("file:")+ ? licenseKey.slice(5)+ : null;+ const label = t("portal.billing.license.label", "License key");+ const updateLabel = licenseKey+ ? t("portal.billing.license.update", "Update")+ : t("portal.billing.license.add", "Add");++ const loadError = configError ?? error;+ if (loadError)+ return (+ <Banner+ tone="danger"+ title={t("admin.error", "Error")}+ description={loadError}+ action={+ <Button+ onClick={() => {+ void (configError ? refetchConfig() : refetchLicense()).catch(+ () => {},+ );+ }}+ >+ {t("portal.accountLink.gate.retry", "Try again")}+ </Button>+ }+ />+ );+ if (loading && !licenseInfo)+ return <Spinner label={t("loading", "Loading...")} />;++ return (+ <>+ <KvRow+ label={label}+ value={+ licenseKey ? (+ certificate ? (+ <span className="billing-license__value">+ {certificate.split(/[\\/]/).pop()}+ </span>+ ) : (+ "••••••••••••••••"+ )+ ) : (+ t("portal.billing.license.empty", "No license installed")+ )+ }+ door={+ <span className="billing-license__actions">+ {licenseKey && (+ <button type="button" onClick={() => setDialog("view")}>+ {t("portal.billing.license.view", "View")}+ </button>+ )}+ <button type="button" onClick={() => setDialog("update")}>+ {updateLabel}+ </button>+ </span>+ }+ />+ <Modal+ open={dialog !== null}+ onClose={() => setDialog(null)}+ title={+ dialog === "view"+ ? label+ : licenseKey+ ? t("portal.billing.license.updateTitle", "Update license")+ : t("portal.billing.license.addTitle", "Add license")+ }+ width="lg"+ footer={+ dialog === "view" ? (+ <Button onClick={() => setDialog("update")}>{updateLabel}</Button>+ ) : undefined+ }+ >+ {dialog === "view" ? (+ <div>+ <p>+ {certificate+ ? t(+ "admin.settings.premium.inputMethod.file",+ "Certificate File",+ )+ : label}+ </p>+ <code className="billing-license__value">+ {certificate ?? licenseKey}+ </code>+ </div>+ ) : dialog === "update" ? (+ <LicenseKeySection+ presentation="form"+ currentLicenseInfo={+ licenseKey ? (licenseInfo ?? undefined) : undefined+ }+ onSaved={() => {+ setDialog(null);+ onSaved();+ }}+ />+ ) : null}+ </Modal>+ </>+ );+}diff --git a/frontend/editor/src/portal/components/billing/SpendLimitModal.tsx b/frontend/editor/src/portal/components/billing/SpendLimitModal.tsxnew file mode 100644index 0000000000..48059e77bc--- /dev/null+++ b/frontend/editor/src/portal/components/billing/SpendLimitModal.tsx@@ -0,0 +1,55 @@+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";++/**+ * 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.+ */+export function SpendLimitModal({+ open,+ onClose,+ wallet,+ onWalletChange,+ onBuyBundle,+}: {+ open: boolean;+ 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",+ );++ 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();+ }}+ />+ <PrepaidCapacityCard wallet={wallet} onBuy={onBuyBundle} />+ </div>+ </Modal>+ );+}diff --git a/frontend/editor/src/portal/components/billing/SpendThisMonthCard.stories.tsx b/frontend/editor/src/portal/components/billing/SpendThisMonthCard.stories.tsxdeleted file mode 100644index c2354e625a..0000000000--- a/frontend/editor/src/portal/components/billing/SpendThisMonthCard.stories.tsx+++ /dev/null@@ -1,20 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { SpendThisMonthCard } from "@portal/components/billing/SpendThisMonthCard";-import { subscribedWallet } from "@portal/components/billing/walletFixtures";-import "@portal/components/billing/billing.css";--const meta: Meta<typeof SpendThisMonthCard> = {- title: "Portal/Billing/SpendThisMonthCard",- component: SpendThisMonthCard,- parameters: { layout: "padded" },-};-export default meta;-type Story = StoryObj<typeof SpendThisMonthCard>;--/** Actual spend + the Enterprise upsell tacked onto the foot. */-export const Default: Story = { args: { wallet: subscribedWallet } };--/** Subscribed with this period's free grant part-spent — shows the free-remaining note. */-export const WithFreeRemaining: Story = {- args: { wallet: { ...subscribedWallet, freeRemaining: 380 } },-};diff --git a/frontend/editor/src/portal/components/billing/SpendThisMonthCard.tsx b/frontend/editor/src/portal/components/billing/SpendThisMonthCard.tsxdeleted file mode 100644index 10aebbe32f..0000000000--- a/frontend/editor/src/portal/components/billing/SpendThisMonthCard.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { useTranslation } from "react-i18next";-import { Card } from "@app/ui";-import { formatMinor } from "@app/billing";-import type { Wallet } from "@portal/api/billing";-import { EnterpriseUpsell } from "@portal/components/billing/EnterpriseUpsell";--/**- * Actual metered spend this period, with the Enterprise upsell tacked onto the- * foot (matching marketing — not a separate full-width row). Flex column so the- * upsell pins to the bottom and the card matches the spend-limit card's height.- */-export function SpendThisMonthCard({ wallet }: { wallet: Wallet }) {- const { t } = useTranslation();- const rateLabel =- wallet.pricePerDocMinor != null && wallet.pricePerDocMinor > 0- ? formatMinor(wallet.pricePerDocMinor, wallet.currency)- : null;-- return (- <Card padding="loose" className="portal-billing__spend-this-month">- <span className="portal-billing__eyebrow">- {t("portal.billing.spendThisMonth.eyebrow", "Spend this month")}- </span>- <div className="portal-billing__bignum-row">- <span className="portal-billing__bignum">- {formatMinor(wallet.estimatedBillMinor ?? 0, wallet.currency)}- </span>- </div>- <p className="portal-billing__section-sub">- {rateLabel- ? t(- "portal.billing.spendThisMonth.processedWithRate",- "{{formattedCount}} PDFs processed, at {{rate}} each.",- {- count: wallet.billableUsed,- formattedCount: wallet.billableUsed.toLocaleString(),- rate: rateLabel,- },- )- : t(- "portal.billing.spendThisMonth.processed",- "{{formattedCount}} PDFs processed.",- {- count: wallet.billableUsed,- formattedCount: wallet.billableUsed.toLocaleString(),- },- )}- </p>- {wallet.freeRemaining > 0 ? (- <p className="portal-billing__section-sub portal-billing__free-remaining">- {t(- "portal.billing.spendThisMonth.freeRemaining",- "{{formatted}} free PDFs remaining",- {- count: wallet.freeRemaining,- formatted: wallet.freeRemaining.toLocaleString(),- },- )}- </p>- ) : null}-- <div className="portal-billing__spend-foot">- <EnterpriseUpsell bare />- </div>- </Card>- );-}diff --git a/frontend/editor/src/portal/components/billing/SubscribedPlanView.tsx b/frontend/editor/src/portal/components/billing/SubscribedPlanView.tsxindex ba787a6ad6..6c3c9f7c40 100644--- a/frontend/editor/src/portal/components/billing/SubscribedPlanView.tsx+++ b/frontend/editor/src/portal/components/billing/SubscribedPlanView.tsx@@ -1,47 +1,46 @@+import { estimatedBillWithPending } from "@app/billing/pendingUsage";import { useState } from "react";import { useTranslation } from "react-i18next";import { Banner, Button } from "@app/ui";import { meterState } from "@app/billing";import type { Wallet } from "@portal/api/billing";-import type { LocalUsage } from "@portal/api/link";import { useStripePortal } from "@portal/hooks/useStripePortal";-import { FreePdfEditorsCard } from "@portal/components/billing/FreePdfEditorsCard";-import { PdfsProcessedCard } from "@portal/components/billing/PdfsProcessedCard";-import { PrepaidCapacityCard } from "@portal/components/billing/PrepaidCapacityCard";import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";-import { SpendThisMonthCard } from "@portal/components/billing/SpendThisMonthCard";-import { SpendLimitCard } from "@portal/components/billing/SpendLimitCard";-import { PaymentMethodCard } from "@portal/components/billing/PaymentMethodCard";-import { InvoicesList } from "@portal/components/billing/InvoicesList";+import { SpendLimitModal } from "@portal/components/billing/SpendLimitModal";interface Props {wallet: Wallet;- /** Instance-local usage not yet synced to SaaS; folded into the PDFs-processed card. */- unsynced?: LocalUsage | null;+ pendingUnits?: number;onWalletChange?: () => void;+ /**+ * Whether the spend-limit editor is open, when the host drives it. Lets the Processor row's+ * "Raise limit" door reach the control that already exists here.+ */+ adjusting?: boolean;+ onAdjustingChange?: (adjusting: boolean) => void;}/**- * Linked + subscribed — the full Processor-plan dashboard, matching the- * marketing layout and reusing the free view's building blocks:- * - team editor fleet ({@link FreePdfEditorsCard}, shared with the free view)- * - PDFs processed + category split ({@link PdfsProcessedCard})- * - spend-vs-cap meter, projection, and the leader-only cap editor- * ({@link SpendLimitCard} → shared {@code SpendCapControl})- * - Enterprise upsell ({@link EnterpriseUpsell}, shared with the free view)- * - per-member usage, Stripe invoices, and the default payment method+ * The flows a subscribed team needs that {@link BillingScreen} has no room for: the spend-limit+ * dialog its Processor row opens, and the bundle checkout.*- * Card / subscription management lives in Stripe's hosted portal — both the- * page-header "Manage Payment" action and the payment card's "Update" button- * deep-link there via {@link useStripePortal}.+ * <p>Nothing renders here at rest. Every card this view used to stack under the page either+ * restated the screen above it or was an upsell, and both now live inside a dialog or not at all.*/export function SubscribedPlanView({wallet,- unsynced,+ pendingUnits = 0,onWalletChange,+ adjusting: controlledAdjusting,+ onAdjustingChange,}: Props) {const { t } = useTranslation();- const [adjusting, setAdjusting] = useState(false);+ const estimatedMinor = estimatedBillWithPending(wallet, pendingUnits);+ const [ownAdjusting, setOwnAdjusting] = useState(false);+ const adjusting = onAdjustingChange+ ? (controlledAdjusting ?? false)+ : ownAdjusting;+ const setAdjusting = onAdjustingChange ?? setOwnAdjusting;const [bundleOpen, setBundleOpen] = useState(false);const portal = useStripePortal(wallet);@@ -49,17 +48,13 @@ export function SubscribedPlanView({// Buying/topping up prepaid capacity is a commercial action — leader-only, and// needs a resolved team to scope checkout.const canBuyBundle = isLeader && wallet.teamId != null;- const spent =- wallet.estimatedBillMinor != null ? wallet.estimatedBillMinor / 100 : 0;+ const spent = estimatedMinor != null ? estimatedMinor / 100 : 0;const capActive = !wallet.noCap && wallet.capUsd != null;const { state, pct } = meterState(spent, wallet.capUsd ?? 0);const showCapWarn = capActive && state !== "FULL";function raiseLimit() {setAdjusting(true);- document- .getElementById("portal-spend-limit")- ?.scrollIntoView({ behavior: "smooth", block: "start" });}return (@@ -104,29 +99,14 @@ export function SubscribedPlanView({</Banner>)}- <FreePdfEditorsCard />-- <PrepaidCapacityCard+ <SpendLimitModal+ open={adjusting}+ onClose={() => setAdjusting(false)}wallet={wallet}- onBuy={canBuyBundle ? () => setBundleOpen(true) : undefined}+ onWalletChange={onWalletChange}+ onBuyBundle={canBuyBundle ? () => setBundleOpen(true) : undefined}/>- <PdfsProcessedCard wallet={wallet} unsynced={unsynced} />-- <div className="portal-billing__spend-row">- <SpendThisMonthCard wallet={wallet} />- <SpendLimitCard- wallet={wallet}- onWalletChange={onWalletChange}- adjusting={adjusting}- onAdjustingChange={setAdjusting}- />- </div>-- <InvoicesList />-- <PaymentMethodCard onManage={portal.open} managing={portal.opening} />-{portal.error && (<Bannertone="danger"diff --git a/frontend/editor/src/portal/components/billing/WalletMeter.stories.tsx b/frontend/editor/src/portal/components/billing/WalletMeter.stories.tsxdeleted file mode 100644index b43bcf8a07..0000000000--- a/frontend/editor/src/portal/components/billing/WalletMeter.stories.tsx+++ /dev/null@@ -1,28 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { WalletMeter } from "@portal/components/billing/WalletMeter";-import { freeWallet } from "@portal/components/billing/walletFixtures";-import "@portal/components/billing/billing.css";--const meta: Meta<typeof WalletMeter> = {- title: "Portal/Billing/WalletMeter",- component: WalletMeter,- parameters: { layout: "padded" },-};-export default meta;-type Story = StoryObj<typeof WalletMeter>;--/** Free grant, plenty left (< 80% used) → FULL band. */-export const FreePlentyLeft: Story = {- // The band keys off used/allowance — 120/500 = 24% → FULL.- args: { wallet: { ...freeWallet, billableUsed: 120, freeRemaining: 380 } },-};--/** Free grant approaching the limit (≥ 80%) → WARNED band. */-export const FreeApproachingLimit: Story = {- args: { wallet: { ...freeWallet, billableUsed: 440, freeRemaining: 60 } },-};--/** Free grant exhausted → DEGRADED band. */-export const FreeLimitReached: Story = {- args: { wallet: { ...freeWallet, billableUsed: 500, freeRemaining: 0 } },-};diff --git a/frontend/editor/src/portal/components/billing/WalletMeter.tsx b/frontend/editor/src/portal/components/billing/WalletMeter.tsxdeleted file mode 100644index f9496b8b61..0000000000--- a/frontend/editor/src/portal/components/billing/WalletMeter.tsx+++ /dev/null@@ -1,103 +0,0 @@-import type { ReactNode } from "react";-import { useTranslation } from "react-i18next";-import { Card } from "@app/ui";-import { formatMinor, MeterBar, remainingMeter } from "@app/billing";-import type { Wallet } from "@portal/api/billing";-import type { LocalUsage } from "@portal/api/link";--interface Props {- /** A linked-free wallet. */- wallet: Wallet;- /** Instance-local usage not yet synced to SaaS; folded into "used" so the trial meter reflects work since the last sync. */- unsynced?: LocalUsage | null;- /** Optional top-right action (e.g. "Switch on the Processor"). */- action?: ReactNode;-}--/**- * The free Processor-trial meter — "X of N free PDFs left" against this period's- * grant, with what has been used alongside as the status badge. The bar shows what- * is left, so it drains towards empty as the grant is spent.- * Uses the shared {@link MeterBar} (same `paygf-meter` structure as the- * cloud plan page). The subscribed spend-vs-cap meter is a separate surface- * ({@code SpendLimitCard}); this card is only the free face.- *- * <p>Locally-accrued usage SaaS hasn't billed yet ({@code unsynced}) is folded- * into the used figure + remaining count so the trial depletes in step with the- * gate — which now also blocks against the pending local delta — instead of only- * moving after a daily sync.- */-export function WalletMeter({ wallet, unsynced, action }: Props) {- const { t } = useTranslation();- const pending = unsynced?.totalUnsyncedUnits ?? 0;- const used = wallet.billableUsed + pending;- const remaining = Math.max(0, wallet.freeRemaining - pending);- const { state, pct } = remainingMeter(remaining, wallet.freeAllowance);- const rate =- wallet.pricePerDocMinor != null && wallet.pricePerDocMinor > 0- ? wallet.pricePerDocMinor- : null;- const title =- rate != null- ? t(- "portal.billing.walletMeter.titleWithRate",- "{{allowance}} free credits every month, then {{rate}} per PDF",- {- count: wallet.freeAllowance,- allowance: wallet.freeAllowance.toLocaleString(),- rate: formatMinor(rate, wallet.currency),- },- )- : t(- "portal.billing.walletMeter.title",- "{{allowance}} free credits every month",- {- count: wallet.freeAllowance,- allowance: wallet.freeAllowance.toLocaleString(),- },- );-- return (- <Card padding="loose">- <div className="portal-billing__subscription-head">- <div>- <span className="portal-billing__eyebrow">- {t("portal.billing.walletMeter.eyebrow", "Processor trial")}- </span>- <h2 className="portal-billing__meter-title">{title}</h2>- <p className="portal-billing__section-sub">- {t(- "portal.billing.walletMeter.sub",- "Use the PDF Editor for free. Pay to process PDFs automatically.",- )}- </p>- </div>- {action}- </div>- <div className="portal-billing__trial-meter">- <MeterBar- state={state}- pct={pct}- barLabel={t(- "portal.billing.walletMeter.barAria",- "Free credits remaining",- )}- figure={remaining.toLocaleString()}- capSuffix={t(- "portal.billing.walletMeter.capSuffix",- "of {{allowance}} free credits left this month",- {- count: wallet.freeAllowance,- allowance: wallet.freeAllowance.toLocaleString(),- },- )}- statusLabel={t(- "portal.billing.walletMeter.statusLabel",- "{{used}} used",- { count: used, used: used.toLocaleString() },- )}- />- </div>- </Card>- );-}diff --git a/frontend/editor/src/portal/components/billing/billing.css b/frontend/editor/src/portal/components/billing/billing.cssindex c1b27720df..6511a1c93b 100644--- a/frontend/editor/src/portal/components/billing/billing.css+++ b/frontend/editor/src/portal/components/billing/billing.css@@ -6,34 +6,6 @@gap: 0.75rem;}-/* Spend this month | Spend limit — two separate cards, side by side. */-.portal-billing__spend-row {- display: grid;- grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr);- gap: 0.75rem;- align-items: stretch;-}-@media (max-width: 60rem) {- .portal-billing__spend-row {- grid-template-columns: 1fr;- }-}--/* Left card is a flex column so the Enterprise upsell pins to the foot and the- card matches the spend-limit card's height. */-.portal-billing__spend-this-month {- display: flex;- flex-direction: column;-}-.portal-billing__spend-foot {- margin-top: auto;- padding-top: 1rem;- border-top: 1px solid var(--c-border);-}-.portal-billing__spend-foot:not(:first-child) {- margin-top: 1.25rem;-}-/* Cap editor (in-place, replaces the spend-limit display). */.portal-billing__suggested {display: inline-flex;diff --git a/frontend/editor/src/portal/components/billing/walletFixtures.ts b/frontend/editor/src/portal/components/billing/walletFixtures.tsindex 81f630adae..55968e3870 100644--- a/frontend/editor/src/portal/components/billing/walletFixtures.ts+++ b/frontend/editor/src/portal/components/billing/walletFixtures.ts@@ -1,95 +1,6 @@-import type { Wallet } from "@portal/api/billing";--/** Linked, on the free monthly grant — leader view. Override per story. */-export const freeWallet: Wallet = {- teamId: 42,- status: "free",- team: { held: false, licensedUsers: null, usersInUse: 1 },- processor: { active: false },- role: "leader",- billingPeriodStart: "2026-06-01",- billingPeriodEnd: "2026-06-30",- billableUsed: 120,- billableLimit: 500,- freeAllowance: 500,- freeRemaining: 380,- pricePerDocMinor: 2,- bundleRatePerCreditMinor: 1,- currency: "usd",- estimatedBillMinor: null,- capUsd: null,- noCap: false,- stripeSubscriptionId: null,- spendUnitsThisPeriod: 120,- categoryBreakdown: { api: 40, ai: 30, automation: 50 },- categoryDocs: { api: 30, ai: 20, automation: 40 },- docsProcessedThisPeriod: 90,- uniquePdfsThisPeriod: 84,- sizeMultiplierPdfsThisPeriod: 12,- billingMode: "payg",- prepaidUnitsRemaining: 0,- prepaidUnitsTotal: 0,- prepaidExpiresAt: null,- members: [],- recent: [],-};--/** Linked + subscribed (Processor plan), capped, leader view with members. */-export const subscribedWallet: Wallet = {- teamId: 42,- status: "subscribed",- team: { held: false, licensedUsers: null, usersInUse: 4 },- processor: { active: true },- role: "leader",- billingPeriodStart: "2026-06-01",- billingPeriodEnd: "2026-06-30",- billableUsed: 2250,- billableLimit: 50000,- freeAllowance: 500,- freeRemaining: 0,- pricePerDocMinor: 2,- bundleRatePerCreditMinor: 1,- currency: "usd",- estimatedBillMinor: 4500,- capUsd: 1000,- noCap: false,- stripeSubscriptionId: "sub_123",- spendUnitsThisPeriod: 2250,- categoryBreakdown: { api: 900, ai: 600, automation: 750 },- categoryDocs: { api: 700, ai: 450, automation: 600 },- docsProcessedThisPeriod: 1750,- uniquePdfsThisPeriod: 1600,- sizeMultiplierPdfsThisPeriod: 320,- billingMode: "payg",- prepaidUnitsRemaining: 0,- prepaidUnitsTotal: 0,- prepaidExpiresAt: null,- members: [- {- userId: "u1",- name: "Ada Lovelace",- email: "[email protected]",- spendUnits: 1400,- },- {- userId: "u2",- name: "Alan Turing",- email: "[email protected]",- spendUnits: 850,- },- ],- recent: [],-};-/**- * Subscribed team currently drawing on a prepaid bundle — {@code billingMode:- * "prepaid"} with a mid-drawn pool (78k of 120k left) expiring in-term. Drives the- * prepaid-capacity card + the "Prepaid year" chip.+ * Moved to {@code @app/billing/walletFixtures} when the billing cards became shared across+ * editions, so the fixtures could not stay above them. Re-exported here because a dozen portal+ * stories and tests import this path and the move is not worth churning them for.*/-export const prepaidWallet: Wallet = {- ...subscribedWallet,- billingMode: "prepaid",- prepaidUnitsRemaining: 78000,- prepaidUnitsTotal: 120000,- prepaidExpiresAt: "2027-03-01",-};+export * from "@app/billing/walletFixtures";diff --git a/frontend/editor/src/portal/components/settings/BillingSettingsSection.css b/frontend/editor/src/portal/components/settings/BillingSettingsSection.cssdeleted file mode 100644index 1fe2d7f7cf..0000000000--- a/frontend/editor/src/portal/components/settings/BillingSettingsSection.css+++ /dev/null@@ -1,6 +0,0 @@-/* The ask sits where the wallet would, at the same measure as a settings section. */-.billing-settings__gate {- max-width: 60rem;- margin-inline: auto;- padding: 3rem 2rem;-}diff --git a/frontend/editor/src/portal/components/settings/BillingSettingsSection.tsx b/frontend/editor/src/portal/components/settings/BillingSettingsSection.tsxindex e69107907e..26a16f284a 100644--- a/frontend/editor/src/portal/components/settings/BillingSettingsSection.tsx+++ b/frontend/editor/src/portal/components/settings/BillingSettingsSection.tsx@@ -1,56 +1 @@-import { useCallback } from "react";-import { useTranslation } from "react-i18next";-import { Button, EmptyState } from "@app/ui";-import { LoadingFallback } from "@app/components/shared/LoadingFallback";-import { useApplyLinkFacts } from "@portal/contexts/LinkContext";-import { useUI } from "@portal/contexts/UIContext";-import { useConnectGate } from "@portal/hooks/useConnectGate";-import { Usage } from "@portal/views/Usage";-import type { Wallet } from "@portal/api/billing";-import "@portal/components/settings/BillingSettingsSection.css";--/**- * Usage & Billing as a settings section. The processor's route used- * ConnectGuardedRoute, which answers "not linked" by navigating to the- * processor home - inside settings that would throw the user out of the page- * they just opened. Here an unlinked instance gets the ask in place instead.- *- * Usage must not render while unlinked: its onWalletLoaded reports linked as a- * fact, and a browser can hold a SaaS session with no link to this server.- */-export function BillingSettingsSection() {- const { t } = useTranslation();- const { gated, loading, connect } = useConnectGate();- const applyLinkFacts = useApplyLinkFacts();- const { openLinkModal } = useUI();-- const onWalletLoaded = useCallback(- (w: Wallet) => applyLinkFacts(true, w.status === "subscribed"),- [applyLinkFacts],- );- const onReauth = useCallback(() => openLinkModal("reauth"), [openLinkModal]);-- // Unknown is not gated: showing the ask first would flash it at a linked admin.- if (loading) return <LoadingFallback />;-- if (gated) {- return (- <div className="billing-settings__gate">- <EmptyState- title={t("portal.nav.usage", "Usage & Billing")}- description={t(- "portal.accountLink.panel.sub",- "Link this self-hosted org to its Stirling account so unattended processing bills against your org wallet.",- )}- actions={- <Button variant="primary" onClick={connect}>- {t("portal.shell.sidebar.linkAccount", "Link Stirling account")}- </Button>- }- />- </div>- );- }-- return <Usage onWalletLoaded={onWalletLoaded} onReauth={onReauth} />;-}+export { PortalBillingGate as BillingSettingsSection } from "@portal/components/billing/PortalBillingGate";diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsxnew file mode 100644index 0000000000..a9316444da--- /dev/null+++ b/frontend/editor/src/portal/components/settings/PortalSettingsProviders.tsx@@ -0,0 +1,36 @@+import type { ReactNode } from "react";+import { LinkProvider } from "@portal/contexts/LinkContext";+import { TierProvider } from "@portal/contexts/TierContext";+import { UIProvider, useUI } from "@portal/contexts/UIContext";+import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";+import { LinkAccountModal } from "@portal/components/account-link/LinkAccountModal";++function LinkModalHost() {+ const { linkModalOpen, linkModalMode, closeLinkModal, connectOutcome } =+ useUI();+ if (!linkModalOpen) return null;+ return (+ <LinkAccountModal+ open+ mode={linkModalMode}+ onClose={closeLinkModal}+ outcome={connectOutcome}+ />+ );+}++/** The instance link starts unknown; checkout and license are inherited from AppProviders. */+export function PortalSettingsProviders({ children }: { children: ReactNode }) {+ return (+ <LinkProvider initialState="unlinked" statusKnown={false}>+ <TierProvider>+ <UIProvider>+ <AccountLinkProvider>+ {children}+ <LinkModalHost />+ </AccountLinkProvider>+ </UIProvider>+ </TierProvider>+ </LinkProvider>+ );+}diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsxnew file mode 100644index 0000000000..ec06b02bea--- /dev/null+++ b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.test.tsx@@ -0,0 +1,53 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { PortalSettingsSectionHost } from "@portal/components/settings/PortalSettingsSectionHost";+import { useLinkOptional } from "@portal/contexts/LinkContext";++const { fetchStatus } = vi.hoisted(() => ({ fetchStatus: vi.fn() }));+vi.mock("@portal/api/link", () => ({ fetchStatus }));+vi.mock("@portal/auth/saasSupabase", () => ({+ isSaasSupabaseConfigured: true,+}));+vi.mock("@portal/components/account-link/LinkAccountModal", () => ({+ LinkAccountModal: () => null,+}));++function LinkState() {+ const link = useLinkOptional();+ return (+ <output>+ {link?.statusKnown ? (link.isLinked ? "linked" : "unlinked") : "checking"}+ </output>+ );+}++describe("settings link status", () => {+ beforeEach(() => fetchStatus.mockReset());++ it("does not claim an unlinked server while its status is still loading", async () => {+ let resolve!: (value: { linked: boolean }) => void;+ fetchStatus.mockReturnValue(+ new Promise((done) => {+ resolve = done;+ }),+ );+ render(+ <PortalSettingsSectionHost>+ <LinkState />+ </PortalSettingsSectionHost>,+ );+ expect(screen.getByText("checking")).toBeInTheDocument();+ resolve({ linked: true });+ expect(await screen.findByText("linked")).toBeInTheDocument();+ });++ it("uses a confirmed unlinked status for local billing", async () => {+ fetchStatus.mockResolvedValue({ linked: false });+ render(+ <PortalSettingsSectionHost>+ <LinkState />+ </PortalSettingsSectionHost>,+ );+ expect(await screen.findByText("unlinked")).toBeInTheDocument();+ });+});diff --git a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsx b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsxindex 367e5054c1..49534e087e 100644--- a/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsx+++ b/frontend/editor/src/portal/components/settings/PortalSettingsSectionHost.tsx@@ -1,31 +1,11 @@import { type ReactNode } from "react";import { QueryClientProvider } from "@tanstack/react-query";import { getPortalQueryClient } from "@portal/queryClient";-import { LinkProvider } from "@portal/contexts/LinkContext";-import { TierProvider } from "@portal/contexts/TierContext";-import { UIProvider } from "@portal/contexts/UIContext";-import { AccountLinkProvider } from "@portal/contexts/AccountLinkContext";-import { LinkAccountModal } from "@portal/components/account-link/LinkAccountModal";+import { PortalSettingsProviders } from "@portal/components/settings/PortalSettingsProviders";import { ErrorBoundary } from "@portal/components/ErrorBoundary";-import { useUI } from "@portal/contexts/UIContext";import "@portal/theme/base.css";import "@portal/components/settings/PortalSettingsSectionHost.css";-/** The one account-link dialog for this subtree, mounted only while open. */-function LinkModalHost() {- const { linkModalOpen, linkModalMode, closeLinkModal, connectOutcome } =- useUI();- if (!linkModalOpen) return null;- return (- <LinkAccountModal- open- mode={linkModalMode}- onClose={closeLinkModal}- outcome={connectOutcome}- />- );-}-/*** Runs a portal-authored view inside the settings page. Those views are written* against the portal's own data and UI contexts and its scoped CSS reset, none@@ -42,16 +22,9 @@ export function PortalSettingsSectionHost({return (<QueryClientProvider client={getPortalQueryClient()}><div className="portal-settings-section portal-scope">- <LinkProvider initialState="unlinked">- <TierProvider>- <UIProvider>- <AccountLinkProvider>- <ErrorBoundary>{children}</ErrorBoundary>- <LinkModalHost />- </AccountLinkProvider>- </UIProvider>- </TierProvider>- </LinkProvider>+ <PortalSettingsProviders>+ <ErrorBoundary>{children}</ErrorBoundary>+ </PortalSettingsProviders></div></QueryClientProvider>);diff --git a/frontend/editor/src/portal/components/shared/StepModalHeader.tsx b/frontend/editor/src/portal/components/shared/StepModalHeader.tsxindex 9190893745..b1e83fe23a 100644--- a/frontend/editor/src/portal/components/shared/StepModalHeader.tsx+++ b/frontend/editor/src/portal/components/shared/StepModalHeader.tsx@@ -1,129 +1,6 @@-import type { ReactNode } from "react";-import { useTranslation } from "react-i18next";-import { Button } from "@app/ui";-// The trademarked Stirling wordmark — the font is baked into the SVG (no brand webfont is loaded),-// so we render the same asset the portal nav uses rather than styled text. Theme-switched in CSS.-import wordmarkLight from "@app/assets/brand/modern-logo/StirlingProcessorLogoBlackText.svg";-import wordmarkDark from "@app/assets/brand/modern-logo/StirlingProcessorLogoWhiteText.svg";-import "@portal/components/shared/StepModalHeader.css";-/**- * Header for any stepped flow modal: an identity row (brand wordmark or the flow's own title) with a- * "Step N of M" badge and close, an M-segment progress bar, and the current step's title.- *- * Shared so a flow's chrome is not re-implemented per flow — the prepay wizard, the metered- * checkout, and the procurement quote builder all wear this. The step label is passed already- * translated: each flow keeps its own copy key rather than this component inventing a shared one.+ * Moved to {@code @app/components/shared/StepModalHeader} when the editor's checkout flow needed+ * the same stepped-modal chrome the portal flows wear. Re-exported here because eight portal and+ * SaaS flows import this path and the move is not worth churning them for.*/-export function StepModalHeader({- title,- subtitle,- step,- total,- stepLabel,- aside,- brand = false,- className,- closeLabel,- onClose,-}: {- /** The current step's heading. Omit when the host modal already renders one. */- title?: string;- /** A line under the title, for a step whose heading needs qualifying (what the document covers). */- subtitle?: ReactNode;- /** Actions belonging to what is on screen (e.g. download this document), seated before the close. */- aside?: ReactNode;- /** 1-based current step. Omit to hide the badge and the progress bar (e.g. a terminal receipt). */- step?: number;- /** Segments to draw. Any length — a flow is not limited to three steps. */- total?: number;- /** Pre-translated "Step 2 of 3"; omitted renders no badge. */- stepLabel?: string;- /** Show the Stirling wordmark instead of a plain heading, for flows that stand alone. */- brand?: boolean;- /** Extra class on the root, so a host modal can still own its padding/layout. */- className?: string;- closeLabel?: string;- /** Omit when the host modal already owns a close control, so there is only ever one. */- onClose?: () => void;-}) {- const { t } = useTranslation();- const showSteps = step != null && total != null && total > 0;-- return (- <div className={`portal-stepmodal__head ${className ?? ""}`.trim()}>- <div className="portal-stepmodal__head-top">- {brand ? (- <div className="portal-stepmodal__brand">- {/* `wordmark`, not `wordmark-light-only`: theme.css hides the former in dark mode and- has no rule for the latter, so both used to render at once. */}- <img- src={wordmarkLight}- alt="Stirling"- className="portal-stepmodal__wordmark wordmark"- />- <img- src={wordmarkDark}- alt=""- aria-hidden- className="portal-stepmodal__wordmark wordmark-dark-only"- />- </div>- ) : title ? (- <div className="portal-stepmodal__ident">- <h3 className="portal-stepmodal__flow-title">{title}</h3>- {subtitle && (- <p className="portal-stepmodal__flow-sub">{subtitle}</p>- )}- </div>- ) : (- <span />- )}- <div className="portal-stepmodal__head-right">- {aside}- {stepLabel && (- <span className="portal-stepmodal__step">{stepLabel}</span>- )}- {onClose && (- <Button- variant="tertiary"- accent="neutral"- size="sm"- shape="circle"- onClick={onClose}- aria-label={closeLabel ?? t("portal.stepModal.close", "Close")}- leftSection={- <svg- viewBox="0 0 24 24"- width="16"- height="16"- fill="none"- stroke="currentColor"- strokeWidth={1.75}- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden- >- <line x1="18" y1="6" x2="6" y2="18" />- <line x1="6" y1="6" x2="18" y2="18" />- </svg>- }- />- )}- </div>- </div>-- {showSteps && (- <div className="portal-stepmodal__progress" aria-hidden>- {Array.from({ length: total }, (_, i) => (- <span key={i} className={i < step ? "is-filled" : ""} />- ))}- </div>- )}-- {/* With the wordmark up top the step title carries the heading; without it the flow title- already did, so repeating it here would say the same thing twice. */}- {brand && <div className="portal-stepmodal__title">{title}</div>}- </div>- );-}+export { StepModalHeader } from "@app/components/shared/StepModalHeader";diff --git a/frontend/editor/src/portal/hooks/useServerPlan.test.tsx b/frontend/editor/src/portal/hooks/useServerPlan.test.tsxnew file mode 100644index 0000000000..2a4a600677--- /dev/null+++ b/frontend/editor/src/portal/hooks/useServerPlan.test.tsx@@ -0,0 +1,59 @@+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { LicenseInfo } from "@app/types/license";+const state = vi.hoisted(() => ({+ licenseInfo: null as LicenseInfo | null,+ fetchUsers: vi.fn(),+}));+vi.mock("@app/contexts/LicenseContext", () => ({+ useLicense: () => ({ licenseInfo: state.licenseInfo, loading: false }),+}));+vi.mock("@app/portal/usersBackend", () => ({+ usersBackend: { fetchUsers: state.fetchUsers },+}));+import { useServerPlan } from "@portal/hooks/useServerPlan";++describe("local licence entitlements", () => {+ beforeEach(() => {+ state.licenseInfo = {+ licenseType: "ENTERPRISE",+ enabled: true,+ maxUsers: 250,+ hasKey: true,+ };+ state.fetchUsers+ .mockReset()+ .mockResolvedValue({ summary: { seatsUsed: 37 } });+ });+ it("uses the installed seats and local roster and refreshes after activation", async () => {+ const { result, rerender } = renderHook(() => useServerPlan(true));+ await waitFor(() => expect(result.current.serverPlan?.usersInUse).toBe(37));+ expect(result.current.serverPlan?.maxUsers).toBe(250);+ state.licenseInfo = { ...state.licenseInfo!, maxUsers: 500 };+ state.fetchUsers.mockResolvedValue({ summary: { seatsUsed: 45 } });+ rerender();+ await waitFor(() => expect(result.current.serverPlan?.usersInUse).toBe(45));+ expect(result.current.serverPlan?.maxUsers).toBe(500);+ });+ it("does not grant an inactive licence", () => {+ state.licenseInfo!.enabled = false;+ const { result } = renderHook(() => useServerPlan(true));+ expect(result.current.serverPlan).toBeUndefined();+ expect(state.fetchUsers).not.toHaveBeenCalled();+ });+ it("does not read licence seats for a non-admin", () => {+ const { result } = renderHook(() => useServerPlan(false));+ expect(result.current.serverPlan).toBeUndefined();+ expect(state.fetchUsers).not.toHaveBeenCalled();+ });+ it("keeps licensed capacity without inventing usage when the roster fails", async () => {+ state.fetchUsers.mockRejectedValue(new Error("unavailable"));+ const { result } = renderHook(() => useServerPlan(true));+ await waitFor(() => expect(state.fetchUsers).toHaveBeenCalled());+ expect(result.current.serverPlan).toEqual({+ licenseType: "ENTERPRISE",+ maxUsers: 250,+ usersInUse: null,+ });+ });+});diff --git a/frontend/editor/src/portal/hooks/useServerPlan.ts b/frontend/editor/src/portal/hooks/useServerPlan.tsnew file mode 100644index 0000000000..53aa698a8e--- /dev/null+++ b/frontend/editor/src/portal/hooks/useServerPlan.ts@@ -0,0 +1,34 @@+import { useEffect, useState } from "react";+import { useLicense } from "@app/contexts/LicenseContext";+import { usersBackend } from "@app/portal/usersBackend";+import type { ServerPlan } from "@app/billing/serverPlan";++/** Read local entitlements only in the self-hosted administrator's billing gate. */+export function useServerPlan(enabled: boolean) {+ const { licenseInfo, loading } = useLicense();+ const [usersInUse, setUsersInUse] = useState<number | null>(null);+ const licenseType =+ enabled && licenseInfo?.enabled && licenseInfo.licenseType !== "NORMAL"+ ? licenseInfo.licenseType+ : null;+ useEffect(() => {+ let cancelled = false;+ setUsersInUse(null);+ if (licenseType) {+ usersBackend+ .fetchUsers(licenseType === "ENTERPRISE" ? "enterprise" : "pro")+ .then(({ summary }) => {+ if (!cancelled) setUsersInUse(summary.seatsUsed);+ })+ .catch(() => {});+ }+ return () => {+ cancelled = true;+ };+ }, [licenseType, licenseInfo]);+ const serverPlan: ServerPlan | undefined =+ licenseType && licenseInfo+ ? { licenseType, maxUsers: licenseInfo.maxUsers, usersInUse }+ : undefined;+ return { serverPlan, loading: loading && !licenseInfo };+}diff --git a/frontend/editor/src/portal/views/Usage.test.tsx b/frontend/editor/src/portal/views/Usage.test.tsxindex 1df8b0525e..2eca3a5dfe 100644--- a/frontend/editor/src/portal/views/Usage.test.tsx+++ b/frontend/editor/src/portal/views/Usage.test.tsx@@ -1,3 +1,6 @@+vi.mock("@portal/queries/infrastructure", () => ({+ useFleetStats: () => ({ data: null, loading: false, error: null }),+}));import { beforeEach, describe, expect, it, vi } from "vitest";import { render, screen, waitFor } from "@testing-library/react";import { MantineProvider } from "@mantine/core";@@ -39,26 +42,44 @@ vi.mock("@portal/components/billing/SubscribedPlanView", () => ({import { Usage } from "@portal/views/Usage";describe("Usage — link-free wallet renderer", () => {+ // Enough of a wallet for BillingScreen to render; the bare {status} fixture predates it.+ const walletOf = (status: string) => ({+ status,+ role: "member",+ currency: "usd",+ freeAllowance: 500,+ freeRemaining: 500,+ spendUnitsThisPeriod: 0,+ docsProcessedThisPeriod: 0,+ sizeMultiplierPdfsThisPeriod: 0,+ estimatedBillMinor: 0,+ pricePerDocMinor: 1,+ billingPeriodStart: "2026-09-01T00:00:00",+ billingPeriodEnd: "2026-10-01T00:00:00",+ team: { held: false, licensedUsers: null, usersInUse: 1 },+ processor: { active: false },+ });+beforeEach(() => {fetchWallet.mockReset();refreshWalletCache.mockReset();});it("loads the wallet on mount and reports it via onWalletLoaded (no link gate)", async () => {- fetchWallet.mockResolvedValue({ status: "free" });+ fetchWallet.mockResolvedValue(walletOf("free"));const onWalletLoaded = vi.fn();renderUsage(<Usage onWalletLoaded={onWalletLoaded} />);// Renders immediately (no link prompt / login) and loads unconditionally.- expect(screen.getByText("Usage & billing")).toBeInTheDocument();+ expect(screen.getByText("Usage & Billing")).toBeInTheDocument();await waitFor(() =>- expect(onWalletLoaded).toHaveBeenCalledWith({ status: "free" }),+ expect(onWalletLoaded).toHaveBeenCalledWith(walletOf("free")),);});it("works with no callbacks (SaaS passes none)", async () => {- fetchWallet.mockResolvedValue({ status: "subscribed" });+ fetchWallet.mockResolvedValue(walletOf("subscribed"));renderUsage(<Usage />);diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsxindex b8970c4094..50e7e02e88 100644--- a/frontend/editor/src/portal/views/Usage.tsx+++ b/frontend/editor/src/portal/views/Usage.tsx@@ -1,6 +1,9 @@+import type { ReactNode } from "react";+import type { ServerPlan } from "@app/billing/serverPlan";import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { Banner, Button, Skeleton } from "@app/ui";+import { Banner, Button } from "@app/ui";+import { BillingScreen } from "@app/billing";import {fetchWallet,refreshWalletCache,@@ -13,6 +16,10 @@ import {} from "@portal/api/link";import { useStripePortal } from "@portal/hooks/useStripePortal";import { FreePlanView } from "@portal/components/billing/FreePlanView";+import { PaymentSection } from "@portal/components/billing/PaymentSection";+import { InvoicesSection } from "@portal/components/billing/InvoicesSection";+import { useFleetStats } from "@portal/queries/infrastructure";+import { useCheckoutOptional } from "@app/contexts/CheckoutContext";import { SubscribedPlanView } from "@portal/components/billing/SubscribedPlanView";import {HttpError,@@ -23,6 +30,9 @@ import "@portal/views/Usage.css";import "@portal/components/billing/billing.css";export interface UsageProps {+ serverPlan?: ServerPlan;+ serverPlanAction?: ReactNode;+ renderLicenseSection?: (onSaved: () => void) => ReactNode;/*** Called with the wallet whenever it loads (initial fetch + post-checkout* flip). A flavor-agnostic hook the composition uses for cross-cutting state —@@ -36,21 +46,28 @@ export interface UsageProps {* is owned by the app, so this path never triggers).*/onReauth?: () => void;+ /** A prop rather than a hook, as {@link onReauth} is: reaching for a router here would make+ * this view unrenderable wherever one is absent. */+ onEnterpriseQuote?: () => void;}/**- * Billing & usage page — a flavor-agnostic wallet renderer. Whether it should be- * shown at all (self-hosted only renders it once the instance is linked) is- * decided upstream by the billing gate; this component always loads the wallet- * and dispatches on {@code wallet.status}:+ * The portal's host for {@link BillingScreen}: it owns the data loading, session handling and+ * Stripe portal action, and passes its own detail sections through {@code extras}. Whether the+ * page is shown at all is the billing gate's decision, upstream.*- * free → FreePlanView (free meter + PAYG explainer)- * subscribed → SubscribedPlanView (period meter, cap, members, invoices)- *- * Wallet comes from {@code GET /api/v1/payg/wallet} (apiClient.saas). After a- * checkout / cancel, the refresh re-reads and the view re-dispatches on status.+ * <p>Wallet comes from {@code GET /api/v1/payg/wallet} (apiClient.saas); a checkout or cancel+ * re-reads it. Only the {@code extras} sections still branch on {@code wallet.status} — the two+ * products render from their own holdings, which that axis cannot express.*/-export function Usage({ onWalletLoaded, onReauth }: UsageProps = {}) {+export function Usage({+ serverPlan,+ serverPlanAction,+ renderLicenseSection,+ onWalletLoaded,+ onReauth,+ onEnterpriseQuote,+}: UsageProps = {}) {const { t } = useTranslation();const [wallet, setWallet] = useState<Wallet | null>(null);// Locally-accrued usage SaaS hasn't billed yet; added to the synced figure so@@ -61,6 +78,16 @@ export function Usage({ onWalletLoaded, onReauth }: UsageProps = {}) {// The SaaS session has lapsed and needs a re-sign-in (self-hosted only).const [sessionExpired, setSessionExpired] = useState(false);const [refreshKey, setRefreshKey] = useState(0);+ // From fleet-stats, not the wallet. Null when the backend cannot compute it, which omits the row.+ const { data: fleetStats } = useFleetStats();+ const editorsDeployed = fleetStats?.editorsDeployed ?? null;+ // A team never billed has none, and the section and its chip then drop out.+ const [hasInvoices, setHasInvoices] = useState(true);+ // Held here, not in the detail views that own the flows, so the product rows can start them.+ const [activationStep, setActivationStep] = useState<+ "choose" | "payg" | "prepay" | null+ >(null);+ const [adjustingLimit, setAdjustingLimit] = useState(false);// Stripe customer portal — the subscribed header's "Manage Payment" action.const portal = useStripePortal(wallet);// Guards the post-checkout poll loop from setState after unmount.@@ -123,6 +150,23 @@ export function Usage({ onWalletLoaded, onReauth }: UsageProps = {}) {}, [refreshKey, onWalletLoaded, t]);const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);+ const onInvoicesEmpty = useCallback(() => setHasInvoices(false), []);++ // The same flow the settings plan section uses, so there is one purchase implementation.+ // Optional on purpose: a build that mounts no provider must lose the door, not the page.+ const checkout = useCheckoutOptional();+ const heldLimit = wallet?.team?.held ? wallet.team.licensedUsers : null;+ const usersInUse = wallet?.team?.usersInUse;+ const addCapacity = useCallback(() => {+ // No email: the only one this instance holds is its local admin record, which is a Spring+ // username and not an address the buyer owns. The checkout asks for one instead.+ void checkout?.openCheckout("server", {+ combinedChoose: true,+ currentLimit: heldLimit,+ minimumSeats: usersInUse,+ onSuccess: () => setRefreshKey((k) => k + 1),+ });+ }, [checkout, heldLimit, usersInUse]);const confirmSubscription = useCallback(async (): Promise<boolean> => {// Stripe's onComplete fires before the subscription webhook lands, so poll the@@ -158,98 +202,116 @@ export function Usage({ onWalletLoaded, onReauth }: UsageProps = {}) {return false;}, [onWalletLoaded]);+ const enterpriseProcessor = serverPlan?.licenseType === "ENTERPRISE";+ const paying = Boolean(wallet?.processor?.active || wallet?.team?.held);+return (- <div className="portal-usage portal-billing">- <header className="portal-usage__header">- <div className="portal-usage__header-inner">- <div>- <h1 className="portal-usage__title">- {t("portal.usage.title", "Usage & billing")}- </h1>- <p className="portal-usage__subtitle">+ <BillingScreen+ wallet={wallet}+ serverPlan={serverPlan}+ serverPlanAction={serverPlanAction}+ licenseSection={renderLicenseSection?.(refresh)}+ loading={loading}+ pendingUnits={localUsage?.totalUnsyncedUnits ?? 0}+ notices={+ <>+ {sessionExpired && (+ <Banner+ tone="warning"+ title={t("portal.usage.sessionExpired.title", "Session expired")}+ action={+ onReauth ? (+ <Button size="sm" onClick={onReauth}>+ {t("portal.usage.sessionExpired.action", "Sign in again")}+ </Button>+ ) : undefined+ }+ >{t(- "portal.usage.subtitle",- "Consumption, invoices, and plan management for every PDF Stirling has billed, in one console.",+ "portal.usage.sessionExpired.body",+ "Your Stirling account session has expired. Sign in again to view billing — your instance stays linked.",)}- </p>- </div>- {wallet?.status === "subscribed" && (- <Button- variant="secondary"- fat- loading={portal.opening}- onClick={portal.open}- >- {t("portal.usage.managePayment", "Manage Payment")}- </Button>+ </Banner>)}- </div>- </header>-- <div className="portal-usage__body">- {loading && (- <div className="portal-billing__skeleton" aria-hidden>- <Skeleton height="10rem" />- <Skeleton height="14rem" />- </div>- )}- {sessionExpired && (- <Banner- tone="warning"- title={t("portal.usage.sessionExpired.title", "Session expired")}- action={- onReauth ? (- <Button size="sm" onClick={onReauth}>- {t("portal.usage.sessionExpired.action", "Sign in again")}- </Button>- ) : undefined- }- >- {t(- "portal.usage.sessionExpired.body",- "Your Stirling account session has expired. Sign in again to view billing — your instance stays linked.",- )}- </Banner>- )}-- {error && (- <Banner- tone="danger"- title={t("portal.usage.error.loadWallet", "Couldn't load wallet")}- >- {error}- </Banner>- )}-- {portal.error && (- <Banner- tone="danger"- title={t(- "portal.usage.error.openStripePortal",- "Couldn't open Stripe portal",- )}- >- {portal.error}- </Banner>- )}+ {error && (+ <Banner+ tone="danger"+ title={t("portal.usage.error.loadWallet", "Couldn't load wallet")}+ >+ {error}+ </Banner>+ )}- {wallet && wallet.status === "free" && (- <FreePlanView+ {portal.error && (+ <Banner+ tone="danger"+ title={t(+ "portal.usage.error.openStripePortal",+ "Couldn't open Stripe portal",+ )}+ >+ {portal.error}+ </Banner>+ )}+ </>+ }+ editorsDeployed={editorsDeployed}+ onAddCapacity={+ checkout && wallet?.role === "leader" ? addCapacity : undefined+ }+ onActivateProcessor={+ !enterpriseProcessor &&+ wallet?.role === "leader" &&+ !wallet?.processor?.active+ ? () => setActivationStep("choose")+ : undefined+ }+ onGovernSpend={+ !enterpriseProcessor &&+ wallet?.role === "leader" &&+ wallet?.processor?.active+ ? () => setAdjustingLimit(true)+ : undefined+ }+ onEnterpriseQuote={onEnterpriseQuote}+ paymentSection={+ paying && wallet ? (+ <PaymentSection+ pendingUnits={localUsage?.totalUnsyncedUnits ?? 0}wallet={wallet}- unsynced={localUsage}- onSubscribed={confirmSubscription}+ onManage={portal.open}+ managing={portal.opening}/>- )}+ ) : undefined+ }+ invoicesSection={+ paying && hasInvoices ? (+ <InvoicesSection onEmpty={onInvoicesEmpty} />+ ) : undefined+ }+ extras={+ <>+ {!enterpriseProcessor && wallet && wallet.status === "free" && (+ <FreePlanView+ wallet={wallet}+ step={activationStep}+ onStepChange={setActivationStep}+ onSubscribed={confirmSubscription}+ />+ )}- {wallet && wallet.status === "subscribed" && (- <SubscribedPlanView- wallet={wallet}- unsynced={localUsage}- onWalletChange={refresh}- />- )}- </div>- </div>+ {!enterpriseProcessor && wallet && wallet.status === "subscribed" && (+ <SubscribedPlanView+ pendingUnits={localUsage?.totalUnsyncedUnits ?? 0}+ wallet={wallet}+ onWalletChange={refresh}+ adjusting={adjustingLimit}+ onAdjustingChange={setAdjustingLimit}+ />+ )}+ </>+ }+ />);}diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsxnew file mode 100644index 0000000000..06bd264a69--- /dev/null+++ b/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx@@ -0,0 +1,214 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { BillingScreen } from "@app/billing/BillingScreen";+import { KvRow } from "@app/billing/KvRow";+import { InvoiceRow } from "@app/billing/InvoiceRow";+import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";++const meta: Meta<typeof BillingScreen> = {+ title: "Billing/BillingScreen",+ component: BillingScreen,+ parameters: { layout: "fullscreen" },+ args: { wallet: subscribedWallet },+};+export default meta;+type Story = StoryObj<typeof BillingScreen>;++/** Stand-ins for the host's sections, so the chip row and section rhythm can be reviewed. */+const payment = (+ <>+ <KvRow+ label="Payment method"+ value="Visa ending 4242 · expires 08 / 2027"+ door={<button type="button">Update</button>}+ />+ <KvRow+ label="Next invoice"+ note="from this cycle's pace"+ value="Oct 1 · $4,911.32"+ />+ <KvRow+ label="Billed to"+ value="Halcyon Legal"+ door={<button type="button">Update</button>}+ />+ <KvRow+ label="Invoices go to"+ value="[email protected]"+ door={<button type="button">Update</button>}+ />+ </>+);+const invoices = (+ <>+ <InvoiceRow+ date="Sep 1, 2026"+ description="Team · 100 users"+ amount="$99.00"+ state="current"+ stateLabel="Current"+ href="https://example.invalid/i/1"+ viewLabel="View"+ />+ <InvoiceRow+ date="Aug 1, 2026"+ description="Team · 100 users"+ amount="$99.00"+ state="paid"+ stateLabel="Paid"+ href="https://example.invalid/i/2"+ viewLabel="View"+ />+ <InvoiceRow+ date="Jul 1, 2026"+ description="Team · 100 users"+ amount="$99.00"+ state="paid"+ stateLabel="Paid"+ href="https://example.invalid/i/3"+ viewLabel="View"+ />+ </>+);++/** Nothing bought, so both rows sell. */+export const Free: Story = {+ args: {+ wallet: {+ ...freeWallet,+ team: { held: false, licensedUsers: null, usersInUse: 1 },+ processor: { active: false },+ freeUserAllowance: 5,+ },+ onAddCapacity: () => {},+ onActivateProcessor: () => {},+ onEnterpriseQuote: () => {},+ },+};++/** Team bought, the Processor not. The identity carries no price, so the Users row does. */+export const TeamOnly: Story = {+ args: {+ wallet: {+ ...freeWallet,+ team: { held: true, licensedUsers: 100, usersInUse: 6 },+ processor: { active: false },+ },+ onAddCapacity: () => {},+ onActivateProcessor: () => {},+ onEnterpriseQuote: () => {},+ editorsDeployed: 6,+ paymentSection: payment,+ invoicesSection: invoices,+ },+};++/** Both products: the identity carries the base, so Users says "included" and Processor governs. */+export const TeamAndProcessor: Story = {+ args: {+ wallet: {+ ...subscribedWallet,+ team: { held: true, licensedUsers: 100, usersInUse: 7 },+ processor: { active: true },+ estimatedBillMinor: 491_132,+ capUsd: 12_000,+ noCap: false,+ },+ onAddCapacity: () => {},+ onGovernSpend: () => {},+ onEnterpriseQuote: () => {},+ editorsDeployed: 6,+ paymentSection: payment,+ invoicesSection: invoices,+ },+};++/** Self-hosted and linked, carrying units the cloud has not billed yet. */+export const SelfHostedPendingSync: Story = {+ args: {+ selfHosted: true,+ wallet: {+ ...freeWallet,+ team: { held: true, licensedUsers: 100, usersInUse: 62 },+ processor: { active: false },+ },+ pendingUnits: 148,+ onAddCapacity: () => {},+ onActivateProcessor: () => {},+ onEnterpriseQuote: () => {},+ },+};++/** Over capacity, reachable by a downgrade, a cancellation or a lapsed card. */+export const OverCapacity: Story = {+ args: {+ wallet: {+ ...subscribedWallet,+ team: { held: true, licensedUsers: 100, usersInUse: 137 },+ processor: { active: true },+ },+ onAddCapacity: () => {},+ onGovernSpend: () => {},+ onEnterpriseQuote: () => {},+ paymentSection: payment,+ },+};++/** A member: identical facts, no doors, because no action callbacks are passed. */+export const MemberReadOnly: Story = {+ args: {+ wallet: {+ ...subscribedWallet,+ role: "member",+ team: { held: true, licensedUsers: 100, usersInUse: 7 },+ processor: { active: true },+ },+ },+};++/** Unlimited Team and no spend limit: two facts, neither with a denominator, so neither draws. */+export const NoLimits: Story = {+ args: {+ wallet: {+ ...subscribedWallet,+ team: { held: true, licensedUsers: null, usersInUse: 240 },+ processor: { active: true },+ noCap: true,+ capUsd: null,+ },+ onAddCapacity: () => {},+ onEnterpriseQuote: () => {},+ },+};++export const Loading: Story = {+ args: { wallet: null, loading: true },+};++export const ServerLicense: Story = {+ args: {+ wallet: freeWallet,+ selfHosted: true,+ serverPlan: { licenseType: "SERVER", maxUsers: 9999, usersInUse: 34 },+ serverPlanAction: (+ <button className="billing-ent__cta">Manage Billing</button>+ ),+ onActivateProcessor: () => {},+ licenseSection: (+ <KvRow+ label="License key"+ value="••••••••••••••••"+ door={<button>Update</button>}+ />+ ),+ },+};++export const EnterpriseLicense: Story = {+ args: {+ ...ServerLicense.args,+ wallet: subscribedWallet,+ serverPlan: { licenseType: "ENTERPRISE", maxUsers: 250, usersInUse: 37 },+ onGovernSpend: () => {},+ paymentSection: payment,+ },+};diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.test.tsxnew file mode 100644index 0000000000..2420bca7d9--- /dev/null+++ b/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx@@ -0,0 +1,181 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, def?: string, vars?: Record<string, unknown>) =>+ def && vars+ ? def.replace(/\{\{(\w+)\}\}/g, (_m, k) => String(vars[k] ?? ""))+ : (def ?? _key),+ i18n: { changeLanguage: vi.fn() },+ }),+}));++import { BillingScreen } from "@app/billing/BillingScreen";+import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";++/**+ * Units a linked instance has accrued that the cloud has not billed yet are real spend, and every+ * figure on this screen counts them. Two totals disagreeing by an undisclosed amount is the bug+ * these pin: a customer reconciling against an invoice has no way to explain the gap.+ */+describe("BillingScreen and units pending sync", () => {+ const wallet = {+ ...subscribedWallet,+ spendUnitsThisPeriod: 1000,+ estimatedBillMinor: 1000,+ pricePerDocMinor: 1,+ };++ it("counts them in both the estimate and the credit line, and says so once", () => {+ render(<BillingScreen wallet={wallet} pendingUnits={250} />);++ // 1000 synced + 250 pending, at 1 minor unit each. Twice on purpose: the cycle estimate and+ // the credit line are the two figures that used to disagree.+ expect(screen.getAllByText("$12.50")).toHaveLength(2);+ expect(+ screen.getByText("1,250 used · includes free and prepaid credits"),+ ).toBeInTheDocument();+ expect(+ screen.getByText(+ "estimated · includes 250 not yet synced from your instances",+ ),+ ).toBeInTheDocument();+ });++ it("says nothing about syncing when there is nothing waiting", () => {+ render(<BillingScreen wallet={wallet} pendingUnits={0} />);++ expect(screen.getAllByText("$10.00")).toHaveLength(2);+ expect(+ screen.getByText("1,000 used · includes free and prepaid credits"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("estimated · the meter settles at close"),+ ).toBeInTheDocument();+ });+});++describe("installed server licences", () => {+ it("keeps Server unlimited while allowing Processor activation", () => {+ const activate = vi.fn();+ render(+ <BillingScreen+ wallet={freeWallet}+ serverPlan={{ licenseType: "SERVER", maxUsers: 9999, usersInUse: 34 }}+ onActivateProcessor={activate}+ onAddCapacity={() => {}}+ serverPlanAction={<button>Manage Billing</button>}+ />,+ );+ expect(screen.getByText("Server")).toBeInTheDocument();+ expect(screen.getByText("Unlimited users")).toBeInTheDocument();+ expect(screen.queryByText("Free")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Add capacity" }),+ ).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Manage Billing" }),+ ).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Switch on the Processor" }),+ );+ expect(activate).toHaveBeenCalledOnce();+ });+ it("uses Enterprise seats and local users even with an active cloud Processor", () => {+ const govern = vi.fn();+ render(+ <BillingScreen+ wallet={subscribedWallet}+ serverPlan={{+ licenseType: "ENTERPRISE",+ maxUsers: 250,+ usersInUse: 37,+ }}+ onGovernSpend={govern}+ />,+ );+ expect(screen.getByText("Enterprise")).toBeInTheDocument();+ expect(screen.getByText("37 of 250 users")).toBeInTheDocument();+ expect(screen.getByText("37")).toBeInTheDocument();+ expect(screen.getByText("Included in your license")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Raise limit" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("Credits")).not.toBeInTheDocument();+ expect(govern).not.toHaveBeenCalled();+ });+ it("includes Enterprise processing even when the cloud Processor is off", () => {+ render(+ <BillingScreen+ wallet={freeWallet}+ serverPlan={{ licenseType: "ENTERPRISE", maxUsers: 100, usersInUse: 1 }}+ onActivateProcessor={() => {}}+ activateLabel="View quote"+ />,+ );+ expect(screen.getByText("Included in your license")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Switch on the Processor" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "View quote" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText(/of 500 used/)).not.toBeInTheDocument();+ });+ it("keeps the installed licence visible if the credit wallet is unavailable", () => {+ render(+ <BillingScreen+ wallet={null}+ serverPlan={{+ licenseType: "ENTERPRISE",+ maxUsers: 80,+ usersInUse: null,+ }}+ serverPlanAction={<button>Manage Billing</button>}+ />,+ );+ expect(screen.getByText("Enterprise")).toBeInTheDocument();+ expect(screen.getByText("80 licensed seats")).toBeInTheDocument();+ expect(screen.getByText("Included in your license")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Manage Billing" }),+ ).toBeInTheDocument();+ });+});++it("shows the net charge consistently when gross usage includes allowances", () => {+ render(+ <BillingScreen+ wallet={{+ ...subscribedWallet,+ spendUnitsThisPeriod: 2000,+ estimatedBillMinor: 4000,+ pricePerDocMinor: 2,+ freeRemaining: 100,+ prepaidUnitsRemaining: 150,+ }}+ pendingUnits={500}+ />,+ );+ expect(screen.getAllByText("$45.00")).toHaveLength(2);+ expect(+ screen.getByText("2,500 used · includes free and prepaid credits"),+ ).toBeInTheDocument();+ expect(screen.queryByText(/each/)).not.toBeInTheDocument();+});++it("does not price gross usage as paid usage", () => {+ render(+ <BillingScreen+ wallet={{+ ...subscribedWallet,+ spendUnitsThisPeriod: 2000,+ estimatedBillMinor: 3000,+ pricePerDocMinor: 2,+ }}+ />,+ );+ expect(screen.getAllByText("$30.00")).toHaveLength(2);+ expect(screen.queryByText("$40.00")).not.toBeInTheDocument();+});diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.tsxnew file mode 100644index 0000000000..ccdfbdc9fa--- /dev/null+++ b/frontend/editor/src/proprietary/billing/BillingScreen.tsx@@ -0,0 +1,489 @@+import type { ReactNode } from "react";+import { useCallback, useMemo } from "react";+import { useTranslation } from "react-i18next";+import { Skeleton } from "@app/ui";+import { formatMinor } from "@app/billing/format";+import { KvRow } from "@app/billing/KvRow";+import { TeamPlanRow } from "@app/billing/TeamPlanRow";+import { ProcessorPlanRow } from "@app/billing/ProcessorPlanRow";+import { estimatedBillWithPending } from "@app/billing/pendingUsage";+import type { ServerPlan } from "@app/billing/serverPlan";+import type { Wallet } from "@app/billing/types";+import "@app/billing/billing-screen.css";++export interface BillingScreenProps {+ /**+ * Null while loading, or when the host could not read one. A non-null wallet must be complete:+ * the sections dereference its fields without guards, so a hand-built partial object throws+ * rather than rendering a blank row.+ */+ wallet: Wallet | null;+ loading?: boolean;+ /** Self-hosted phrases its free tier differently. */+ selfHosted?: boolean;+ /** Local licence takes precedence over the cloud product names and user capacity. */+ serverPlan?: ServerPlan;+ /** Subscription management for the installed licence. */+ serverPlanAction?: ReactNode;+ /** Units a linked instance has accrued that the cloud has not billed yet. */+ pendingUnits?: number;+ /** Leader-only: sells Team capacity from the Users row. */+ onAddCapacity?: () => void;+ /** Leader-only: switches the Processor on from its row. */+ onActivateProcessor?: () => void;+ /** Overrides activation with a quote or invoice resume action. */+ activateLabel?: ReactNode;+ /** Leader-only: opens the spend limit from the Processor row once it is on. */+ onGovernSpend?: () => void;+ /** Overrides the governing door's label, e.g. "Top up" for a prepaid team. */+ governLabel?: ReactNode;+ /** Banners above the card: a lapsed session, a failed wallet read. Host-owned. */+ notices?: ReactNode;+ /** An existing deal stays above the plan, even when the wallet cannot be loaded. */+ procurementSection?: ReactNode;+ /** Local server license management, supplied only by self-hosted admin views. */+ licenseSection?: ReactNode;+ /** Omit where the edition has no payment surface; the chip drops out with the section. */+ paymentSection?: ReactNode;+ /** Omit where there are no invoices, for the same reason. */+ invoicesSection?: ReactNode;+ /** Null when the backend cannot compute it, which omits the row rather than showing a zero. */+ editorsDeployed?: number | null;+ /** The enterprise door. Omitted for a team already on an agreement. */+ onEnterpriseQuote?: () => void;+ /** Host-owned surfaces that are not sections of this card: modals, upsells, detail cards. */+ extras?: ReactNode;+}++/** Inclusive day index within the billing period, and the period's length, from real dates. */+function cycleDay(+ start: string,+ end: string,+): { day: number; of: number } | null {+ const s = Date.parse(start);+ const e = Date.parse(end);+ if (Number.isNaN(s) || Number.isNaN(e) || e <= s) return null;+ const day = 24 * 60 * 60 * 1000;+ const of = Math.round((e - s) / day);+ const elapsed = Math.floor((Date.now() - s) / day) + 1;+ return { day: Math.min(Math.max(1, elapsed), of), of };+}++/**+ * The billing screen, one view for every edition.+ *+ * <p>Nothing here reaches for a router, an API client or a modal stack: the wallet, the actions+ * and the payment and invoice sections all arrive as props and slots. That is what lets one+ * component serve the cloud, self-hosted and the desktop app, and it makes a member's read-only+ * screen a matter of passing no callbacks rather than a role check.+ *+ * <p>A chip exists only where its section does, so an omitted slot removes both.+ */+export function BillingScreen({+ wallet,+ loading = false,+ selfHosted = false,+ serverPlan,+ serverPlanAction,+ pendingUnits = 0,+ onAddCapacity,+ onActivateProcessor,+ activateLabel,+ onGovernSpend,+ governLabel,+ notices,+ procurementSection,+ licenseSection,+ editorsDeployed,+ paymentSection,+ invoicesSection,+ onEnterpriseQuote,+ extras,+}: BillingScreenProps) {+ const { t } = useTranslation();++ const jump = useCallback((id: string) => {+ document+ .getElementById(id)+ ?.scrollIntoView({ behavior: "smooth", block: "start" });+ }, []);++ const enterpriseProcessor = serverPlan?.licenseType === "ENTERPRISE";+ const paying = Boolean(wallet?.processor?.active) && !enterpriseProcessor;+ const teamHeld = Boolean(wallet?.team?.held);++ const chips = useMemo(() => {+ const out: Array<[string, string]> = [];+ if (procurementSection)+ out.push([+ "ub-procurement",+ t("portal.billing.chip.procurement", "Procurement"),+ ]);+ if (wallet || serverPlan)+ out.push(["ub-plan", t("portal.billing.chip.plan", "Plan")]);+ if (wallet) out.push(["ub-usage", t("portal.billing.chip.usage", "Usage")]);+ if (wallet && paymentSection)+ out.push(["ub-pay", t("portal.billing.chip.payment", "Payment")]);+ if (wallet && invoicesSection)+ out.push(["ub-inv", t("portal.billing.chip.invoices", "Invoices")]);+ if (licenseSection)+ out.push([+ "ub-license",+ t("admin.settings.premium.inputMethod.text", "License Key"),+ ]);+ return out;+ }, [+ wallet,+ serverPlan,+ procurementSection,+ licenseSection,+ paymentSection,+ invoicesSection,+ t,+ ]);++ const identity = useMemo(() => {+ if (serverPlan)+ return {+ name:+ serverPlan.licenseType === "SERVER"+ ? t("portal.billing.serverPlan.server", "Server")+ : t("portal.billing.serverPlan.enterprise", "Enterprise"),+ sub: t(+ "portal.billing.serverPlan.active",+ "Active self-hosted license",+ ),+ chips: [],+ };+ if (!wallet) return null;+ const rate = wallet.pricePerDocMinor;+ if (paying) {+ return {+ name: t("portal.billing.identity.processor.name", "Processor"),+ sub:+ rate != null+ ? t(+ "portal.billing.identity.processor.sub",+ "Team base plus {{rate}} per credit",+ {+ rate: formatMinor(rate, wallet.currency),+ },+ )+ : t(+ "portal.billing.identity.processor.subNoRate",+ "Team base plus metered processing",+ ),+ chips: [+ t(+ "portal.billing.identity.processor.chipMetered",+ "Metered processing",+ ),+ t(+ "portal.billing.identity.processor.chipPipelines",+ "Pipelines & API",+ ),+ ],+ };+ }+ if (teamHeld) {+ return {+ name: t("portal.billing.identity.team.name", "Team"),+ sub:+ wallet.team.licensedUsers != null+ ? t("portal.billing.identity.team.sub", "Up to {{users}} users", {+ users: wallet.team.licensedUsers.toLocaleString(),+ })+ : t("portal.billing.identity.team.subNoLimit", "No user limit"),+ chips: [+ t("portal.billing.identity.team.chipSso", "SSO"),+ t("portal.billing.identity.team.chipFleet", "Fleet control"),+ ],+ };+ }+ return {+ name: t("portal.billing.identity.free.name", "Free"),+ sub: t("portal.billing.identity.free.sub", "The full PDF Editor."),+ chips: [+ t("portal.billing.identity.free.chipTools", "Every PDF tool"),+ t(+ "portal.billing.identity.free.chipAnywhere",+ "Web, desktop & self-hosted",+ ),+ t(+ "portal.billing.identity.free.chipCredits",+ "{{allowance}} free credits monthly",+ {+ allowance: wallet.freeAllowance.toLocaleString(),+ },+ ),+ ],+ };+ }, [wallet, paying, teamHeld, serverPlan, t]);++ const creditUnits = (wallet?.spendUnitsThisPeriod ?? 0) + pendingUnits;+ const showTeam = Boolean(+ wallet &&+ (wallet.team.held ||+ wallet.team.usersInUse > 0 ||+ wallet.freeUserAllowance > 0),+ );+ const estimatedMinor = wallet+ ? estimatedBillWithPending(wallet, pendingUnits)+ : null;++ const cycle = wallet+ ? cycleDay(wallet.billingPeriodStart, wallet.billingPeriodEnd)+ : null;++ return (+ <div className="billing-page">+ <header className="billing-page__head">+ <h1 className="billing-page__title">+ {t("portal.usage.title", "Usage & Billing")}+ </h1>+ <p className="billing-page__subtitle">+ {t(+ "portal.usage.subtitle",+ "Your plan, your usage, and every invoice.",+ )}+ </p>+ </header>++ <div className="billing-page__body">+ <div className="billing-page__notices">{notices}</div>++ {loading && !wallet && (+ <div aria-hidden>+ <Skeleton height="12rem" />+ </div>+ )}++ {(procurementSection || licenseSection || identity) && (+ <div className="billing-card">+ <nav+ className="billing-card__chips"+ aria-label={t("portal.billing.chip.nav", "Sections")}+ >+ {chips.map(([id, label]) => (+ <button+ key={id}+ type="button"+ className="billing-card__chip"+ onClick={() => jump(id)}+ >+ {label}+ </button>+ ))}+ </nav>++ {procurementSection && (+ <section+ id="ub-procurement"+ className="billing-sec billing-sec--procurement"+ aria-label={t("portal.billing.chip.procurement", "Procurement")}+ >+ {procurementSection}+ </section>+ )}++ {identity && (+ <>+ <section id="ub-plan" className="billing-sec">+ <span className="billing-eyebrow">+ {t("portal.billing.section.plan", "Your plan")}+ </span>+ <div className="billing-id">+ <span className="billing-id__name">{identity.name}</span>+ <span className="billing-id__sub">{identity.sub}</span>+ {serverPlanAction && (+ <div className="billing-id__action">+ {serverPlanAction}+ </div>+ )}+ </div>+ <div className="billing-id__chips">+ {identity.chips.map((c) => (+ <span key={c} className="billing-id__chip">+ {c}+ </span>+ ))}+ </div>+ <div className="billing-meters">+ {(showTeam || serverPlan) && (+ <TeamPlanRow+ wallet={wallet}+ selfHosted={selfHosted}+ serverPlan={serverPlan}+ onAddCapacity={onAddCapacity}+ />+ )}+ {(wallet?.processor || enterpriseProcessor) && (+ <ProcessorPlanRow+ included={enterpriseProcessor}+ wallet={wallet}+ pendingUnits={pendingUnits}+ onActivate={onActivateProcessor}+ activateLabel={activateLabel}+ onGovern={onGovernSpend}+ governLabel={governLabel}+ />+ )}+ </div>+ </section>++ {wallet && (+ <>+ <section id="ub-usage" className="billing-sec">+ <div className="billing-eyebrow-row">+ <span className="billing-eyebrow">+ {t("portal.billing.section.cycle", "This cycle")}+ </span>+ {cycle && (+ <span className="billing-eyebrow-row__fact">+ {t(+ "portal.billing.cycle.day",+ "Day {{day}} of {{of}}",+ {+ day: cycle.day,+ of: cycle.of,+ },+ )}+ </span>+ )}+ </div>++ {/* The bill leads only once there is a bill. On the free tier the estimate is zero+ by definition, and a zero hero would read as a figure rather than as a state. */}+ {paying && estimatedMinor != null && (+ <div className="billing-bignum-row">+ <span className="billing-bignum">+ {formatMinor(estimatedMinor, wallet.currency)}+ </span>+ <span className="billing-bignum__note">+ {pendingUnits > 0+ ? t(+ "portal.billing.cycle.estimatedPending",+ "estimated · includes {{pending}} not yet synced from your instances",+ { pending: pendingUnits.toLocaleString() },+ )+ : t(+ "portal.billing.cycle.estimated",+ "estimated · the meter settles at close",+ )}+ </span>+ </div>+ )}++ <KvRow+ label={t("portal.billing.cycle.pdfs", "PDFs processed")}+ value={wallet.docsProcessedThisPeriod.toLocaleString()}+ />+ {(serverPlan+ ? serverPlan.usersInUse != null+ : showTeam) && (+ <KvRow+ label={t("portal.billing.cycle.users", "Users")}+ value={(+ serverPlan?.usersInUse ?? wallet.team.usersInUse+ ).toLocaleString()}+ />+ )}+ {editorsDeployed != null && (+ <KvRow+ label={t(+ "portal.billing.cycle.editors",+ "Editors deployed",+ )}+ value={editorsDeployed.toLocaleString()}+ />+ )}+ {paying && (+ <KvRow+ label={t("portal.billing.cycle.credits", "Credits")}+ note={+ wallet.pricePerDocMinor != null+ ? t(+ "portal.billing.cycle.creditsNote",+ "{{units}} used · includes free and prepaid credits",+ {+ units: creditUnits.toLocaleString(),+ },+ )+ : undefined+ }+ value={+ estimatedMinor != null+ ? formatMinor(estimatedMinor, wallet.currency)+ : creditUnits.toLocaleString()+ }+ />+ )}+ </section>++ {paymentSection && (+ <section id="ub-pay" className="billing-sec">+ <span className="billing-eyebrow">+ {t("portal.billing.section.payment", "Payment")}+ </span>+ {paymentSection}+ </section>+ )}++ {invoicesSection && (+ <section id="ub-inv" className="billing-sec">+ <span className="billing-eyebrow">+ {t("portal.billing.section.invoices", "Invoices")}+ </span>+ {invoicesSection}+ </section>+ )}+ </>+ )}+ </>+ )}+ {licenseSection && (+ <section+ id="ub-license"+ className="billing-sec billing-sec--license"+ aria-label={t(+ "admin.settings.premium.inputMethod.text",+ "License Key",+ )}+ >+ {licenseSection}+ </section>+ )}+ </div>+ )}++ {onEnterpriseQuote && serverPlan?.licenseType !== "ENTERPRISE" && (+ <div className="billing-ent">+ <div>+ <div className="billing-ent__title">+ {t(+ "portal.billing.enterprise.title",+ "Running Stirling in a regulated environment?",+ )}+ </div>+ <div className="billing-ent__sub">+ {t(+ "portal.billing.enterprise.sub",+ "Air-gapped deployment, SCIM, data residency, uptime SLAs, and an agreement to match.",+ )}+ </div>+ </div>+ <button+ type="button"+ className="billing-ent__cta"+ onClick={onEnterpriseQuote}+ >+ {t("portal.billing.enterprise.cta", "Get an enterprise quote")}+ </button>+ </div>+ )}++ {extras}+ </div>+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/billing/InvoiceRow.tsx b/frontend/editor/src/proprietary/billing/InvoiceRow.tsxnew file mode 100644index 0000000000..8376991bc5--- /dev/null+++ b/frontend/editor/src/proprietary/billing/InvoiceRow.tsx@@ -0,0 +1,61 @@+import { StatusBadge, type StatusTone } from "@app/ui";++export type InvoiceRowState = "paid" | "current" | "failed" | "other";++const TONE: Record<InvoiceRowState, StatusTone> = {+ paid: "success",+ current: "info",+ failed: "danger",+ other: "neutral",+};++/**+ * One invoice row. The door is a real anchor rather than a scripted open, so middle-click,+ * right-click and "open in new tab" all still work.+ */+export function InvoiceRow({+ date,+ description,+ amount,+ state,+ stateLabel,+ href,+ viewLabel,+}: {+ date: string;+ /** What the invoice was for, e.g. "Team · 100 users". */+ description?: string | null;+ amount: string;+ state: InvoiceRowState;+ stateLabel: string;+ /** Stripe's hosted invoice page. Omit when there is none and the door drops out. */+ href?: string | null;+ viewLabel: string;+}) {+ return (+ <div className="billing-inv">+ <span className="billing-inv__date">{date}</span>+ {description ? (+ <span className="billing-inv__desc">{description}</span>+ ) : (+ <span className="billing-inv__desc" />+ )}+ <span className="billing-inv__amount">{amount}</span>+ <StatusBadge tone={TONE[state]} size="sm" showDot={false}>+ {stateLabel}+ </StatusBadge>+ {href ? (+ <a+ className="billing-inv__door"+ href={href}+ target="_blank"+ rel="noreferrer noopener"+ >+ {viewLabel}+ </a>+ ) : (+ <span className="billing-inv__door" aria-hidden />+ )}+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/billing/KvRow.tsx b/frontend/editor/src/proprietary/billing/KvRow.tsxnew file mode 100644index 0000000000..c9c4b43eb2--- /dev/null+++ b/frontend/editor/src/proprietary/billing/KvRow.tsx@@ -0,0 +1,30 @@+import type { ReactNode } from "react";++/**+ * A cycle fact, as a key-value row. {@link note} is separated from the value by real whitespace+ * rather than margin, so screen readers do not run the two together as "100 users$99.00".+ */+export function KvRow({+ label,+ value,+ note,+ door,+}: {+ label: string;+ value: ReactNode;+ /** A muted qualifier before the value: "392,906 · 1c each", "flat · no meter running". */+ note?: string;+ /** A door at the row's right, e.g. "Update". */+ door?: ReactNode;+}) {+ return (+ <div className="billing-kv">+ <span className="billing-kv__label">{label}</span>+ <span className="billing-kv__value">+ {note ? <span className="billing-kv__note">{note} </span> : null}+ {value}+ {door ? <span className="billing-kv__door">{door}</span> : null}+ </span>+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/billing/MeterRow.tsx b/frontend/editor/src/proprietary/billing/MeterRow.tsxnew file mode 100644index 0000000000..8c228df357--- /dev/null+++ b/frontend/editor/src/proprietary/billing/MeterRow.tsx@@ -0,0 +1,80 @@+import type { ReactNode } from "react";++export type MeterRowTone = "free" | "paid" | "warn";++export interface MeterRowProps {+ /** The product's name on a measuring surface: "Users", "Processor". */+ name: string;+ /** The middle line. Never re-prices what the plan identity above already carries. */+ mid: ReactNode;+ /** The right-hand fact, e.g. "34 of 100 users". Tabular, so rows align down the column. */+ fact: ReactNode;+ /** 0-100. Ignored when {@link showTrack} is false. */+ pct?: number;+ tone?: MeterRowTone;+ /**+ * False when there is no denominator: a track would then draw full or empty, and both claim+ * headroom that an absent limit cannot support.+ */+ showTrack?: boolean;+ /** The door at the row's right. */+ door?: ReactNode;+ onDoor?: () => void;+ /** Tooltip on the middle line, for a fact that needs one qualifier and no more. */+ midTitle?: string;+}++/**+ * One product, as a row: a fact with its door at the right, which is how this screen sells.+ *+ * <p>The door is styled as a link but is a real {@code <button>}, so it keeps the keyboard and+ * screen-reader behaviour a styled span would lose.+ */+export function MeterRow({+ name,+ mid,+ fact,+ pct = 0,+ tone = "free",+ showTrack = true,+ door,+ onDoor,+ midTitle,+}: MeterRowProps) {+ const cls = `billing-meter${tone === "paid" ? " billing-meter--paid" : tone === "warn" ? " billing-meter--warn" : ""}`;+ return (+ <div className={cls}>+ <span className="billing-meter__dot" aria-hidden />+ <span className="billing-meter__name">{name}</span>+ <span className="billing-meter__mid" title={midTitle}>+ {mid}+ </span>+ {showTrack ? (+ <span+ className="billing-meter__track"+ role="img"+ aria-label={`${name}: ${typeof fact === "string" ? fact : ""}`}+ >+ <span+ className="billing-meter__fill"+ style={{ width: `${Math.min(100, Math.max(0, pct))}%` }}+ />+ </span>+ ) : (+ <span+ className="billing-meter__track"+ aria-hidden+ style={{ visibility: "hidden" }}+ />+ )}+ <span className="billing-meter__fact">{fact}</span>+ {door ? (+ <button type="button" className="billing-meter__door" onClick={onDoor}>+ {door}+ </button>+ ) : (+ <span className="billing-meter__door" aria-hidden />+ )}+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsxnew file mode 100644index 0000000000..8073e0b873--- /dev/null+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx@@ -0,0 +1,108 @@+import { describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, def?: string, vars?: Record<string, unknown>) =>+ def && vars+ ? def.replace(/\{\{(\w+)\}\}/g, (_m, k) => String(vars[k] ?? ""))+ : (def ?? _key),+ i18n: { changeLanguage: vi.fn() },+ }),+}));++import { ProcessorPlanRow } from "@app/billing/ProcessorPlanRow";+import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";+import type { Wallet } from "@app/billing/types";++const off = (over: Partial<Wallet> = {}): Wallet => ({+ ...freeWallet,+ processor: { active: false },+ ...over,+});+const on = (over: Partial<Wallet> = {}): Wallet => ({+ ...subscribedWallet,+ processor: { active: true },+ ...over,+});++describe("ProcessorPlanRow", () => {+ it("sells while off: the grant drains towards the activation door", () => {+ render(+ <ProcessorPlanRow+ wallet={off({ freeRemaining: 380, freeAllowance: 500 })}+ onActivate={() => {}}+ />,+ );++ expect(screen.getByText("120 of 500 used")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Switch on the Processor" }),+ ).toBeInTheDocument();+ });++ it("counts pending instance units as used rather than ignoring them", () => {+ render(+ <ProcessorPlanRow+ wallet={off({ freeRemaining: 380, freeAllowance: 500 })}+ pendingUnits={148}+ />,+ );++ // Blind to the unsynced units this would read 120 and overstate the headroom by exactly 148.+ expect(screen.getByText("268 of 500 used")).toBeInTheDocument();+ });++ it("never reports more used than the grant holds", () => {+ render(+ <ProcessorPlanRow+ wallet={off({ freeRemaining: 20, freeAllowance: 500 })}+ pendingUnits={9999}+ />,+ );++ expect(screen.getByText("500 of 500 used")).toBeInTheDocument();+ });++ it("governs while on, converting minor units to the limit's major scale", () => {+ render(+ <ProcessorPlanRow+ wallet={on({ estimatedBillMinor: 4500, capUsd: 1000, noCap: false })}+ onGovern={() => {}}+ />,+ );++ // 4500 minor is $45 against a $1,000 limit: 5%, not 450%.+ expect(screen.getByText("$45.00 metered this cycle")).toBeInTheDocument();+ expect(screen.getByText("5% of $1,000")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Raise limit" }),+ ).toBeInTheDocument();+ });++ it("says so rather than showing zero when the rate is unknown", () => {+ render(<ProcessorPlanRow wallet={on({ estimatedBillMinor: null })} />);+ expect(screen.getByText("Metered this cycle")).toBeInTheDocument();+ });++ it("drops the track when there is no spend limit", () => {+ const { container } = render(+ <ProcessorPlanRow wallet={on({ noCap: true, capUsd: null })} />,+ );++ expect(screen.getByText("no limit")).toBeInTheDocument();+ expect(container.querySelector(".billing-meter__fill")).toBeNull();+ });++ it("lets a prepaid team's door be relabelled without changing the row", () => {+ render(+ <ProcessorPlanRow+ wallet={on({ estimatedBillMinor: 4500, capUsd: 1000, noCap: false })}+ onGovern={() => {}}+ governLabel="Top up"+ />,+ );++ expect(screen.getByRole("button", { name: "Top up" })).toBeInTheDocument();+ });+});diff --git a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsxnew file mode 100644index 0000000000..bf6166fd58--- /dev/null+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx@@ -0,0 +1,161 @@+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { formatMinor, formatMoneyMajor } from "@app/billing/format";+import { MeterRow } from "@app/billing/MeterRow";+import { estimatedBillWithPending } from "@app/billing/pendingUsage";+import type { Wallet } from "@app/billing/types";++/**+ * The Processor product, as a row: the free grant draining towards activation while off, spend+ * against the limit while on.+ *+ * <p>Money arrives in two scales. The estimate is minor units and the limit is major, so the+ * comparison converts once here rather than leaving a factor of a hundred to a caller. An unknown+ * rate reports as unknown, never as zero.+ */+export function ProcessorPlanRow({+ wallet,+ included = false,+ pendingUnits = 0,+ onActivate,+ activateLabel,+ onGovern,+ governLabel,+}: {+ wallet: Wallet | null;+ /** A validated local Enterprise licence includes processing independently of the wallet. */+ included?: boolean;+ /**+ * Units accrued locally that the cloud has not billed yet. Subtracted rather than shown beside+ * the total, because the entitlement gate blocks against this same pending delta: reporting more+ * remaining than the gate will honour is what makes a wall arrive early.+ */+ pendingUnits?: number;+ /** Leader-only, while off: the activation door. Omit for members. */+ onActivate?: () => void;+ /** Overrides activation with the host's quote or invoice resume label. */+ activateLabel?: ReactNode;+ /** Leader-only, while on: the spend-limit door. Omit for members. */+ onGovern?: () => void;+ /** Overrides the governing door's label, e.g. "Top up" for a prepaid team. */+ governLabel?: ReactNode;+}) {+ const { t } = useTranslation();+ const name = t("portal.billing.processor.rowName", "Processor");+ if (included)+ return (+ <MeterRow+ name={name}+ mid={t("portal.billing.processor.included", "Included in your license")}+ fact=""+ tone="paid"+ showTrack={false}+ />+ );+ if (!wallet) return null;+ const rate = wallet.pricePerDocMinor;++ if (!wallet.processor.active) {+ const used = Math.min(+ wallet.freeAllowance,+ Math.max(0, wallet.freeAllowance - wallet.freeRemaining + pendingUnits),+ );+ const pct =+ wallet.freeAllowance > 0 ? (used / wallet.freeAllowance) * 100 : 0;+ const mid =+ rate != null+ ? t(+ "portal.billing.processor.midFree",+ "{{rate}} per credit · {{allowance}} free every month",+ {+ rate: formatMinor(rate, wallet.currency),+ allowance: wallet.freeAllowance.toLocaleString(),+ },+ )+ : t(+ "portal.billing.processor.midFreeNoRate",+ "{{allowance}} free every month",+ {+ allowance: wallet.freeAllowance.toLocaleString(),+ },+ );++ return (+ <MeterRow+ name={name}+ mid={mid}+ pct={pct}+ tone="free"+ fact={t(+ "portal.billing.processor.factFree",+ "{{used}} of {{allowance}} used",+ {+ used: used.toLocaleString(),+ allowance: wallet.freeAllowance.toLocaleString(),+ },+ )}+ door={+ onActivate+ ? (activateLabel ??+ t("portal.billing.processor.activate", "Switch on the Processor"))+ : undefined+ }+ onDoor={onActivate}+ />+ );+ }++ const spentMinor = estimatedBillWithPending(wallet, pendingUnits);+ const capped = !wallet.noCap && wallet.capUsd != null;+ // One conversion, in one place: the estimate is minor units, the limit is major.+ const spentMajor = spentMinor != null ? spentMinor / 100 : null;+ const pct =+ capped && spentMajor != null+ ? (spentMajor / (wallet.capUsd as number)) * 100+ : 0;++ const mid =+ spentMinor != null+ ? t(+ "portal.billing.processor.midMetered",+ "{{spend}} metered this cycle",+ {+ spend: formatMinor(spentMinor, wallet.currency),+ },+ )+ : t("portal.billing.processor.midMeteredUnknown", "Metered this cycle");++ const fact = capped+ ? t("portal.billing.processor.factCapped", "{{pct}}% of {{cap}}", {+ pct: Math.round(pct).toLocaleString(),+ cap: formatMoneyMajor(wallet.capUsd as number, wallet.currency),+ })+ : t("portal.billing.processor.factNoCap", "no limit");++ const door =+ governLabel ??+ (onGovern+ ? t("portal.billing.processor.raiseLimit", "Raise limit")+ : undefined);++ return (+ <MeterRow+ name={name}+ mid={mid}+ pct={pct}+ tone={capped && pct >= 90 ? "warn" : "paid"}+ showTrack={capped}+ fact={fact}+ door={onGovern ? door : undefined}+ onDoor={onGovern}+ midTitle={+ capped+ ? t(+ "portal.billing.processor.capTooltip",+ "Pauses PDF processing at your spend limit.",+ )+ : undefined+ }+ />+ );+}diff --git a/frontend/editor/src/proprietary/billing/TeamPlanRow.test.tsx b/frontend/editor/src/proprietary/billing/TeamPlanRow.test.tsxnew file mode 100644index 0000000000..35fec45131--- /dev/null+++ b/frontend/editor/src/proprietary/billing/TeamPlanRow.test.tsx@@ -0,0 +1,174 @@+import { describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, def?: string, vars?: Record<string, unknown>) =>+ def && vars+ ? def.replace(/\{\{(\w+)\}\}/g, (_m, k) => String(vars[k] ?? ""))+ : (def ?? _key),+ i18n: { changeLanguage: vi.fn() },+ }),+}));++import { TeamPlanRow } from "@app/billing/TeamPlanRow";+import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";+import type { TeamHolding, Wallet } from "@app/billing/types";++// The base wallet is spread FIRST so the explicit holding wins: passing freeWallet as the base+// would otherwise bring its own team along and silently override the one under test.+const w = (team: TeamHolding, over: Partial<Wallet> = {}): Wallet => ({+ ...subscribedWallet,+ ...over,+ team,+});++describe("TeamPlanRow", () => {+ it("names the row for what it measures and offers the capacity door", () => {+ const { container } = render(+ <TeamPlanRow+ wallet={w({ held: true, licensedUsers: 100, usersInUse: 34 })}+ onAddCapacity={() => {}}+ />,+ );++ expect(screen.getByText("Users")).toBeInTheDocument();+ expect(screen.getByText("34 of 100 users")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Add capacity" }),+ ).toBeInTheDocument();+ expect(container.querySelector(".billing-meter--paid")).not.toBeNull();+ });++ it("gives a member the same fact with no door", () => {+ render(+ <TeamPlanRow+ wallet={w({ held: true, licensedUsers: 100, usersInUse: 34 })}+ />,+ );++ expect(screen.getByText("34 of 100 users")).toBeInTheDocument();+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+ });++ it("turns amber only once the capacity is paid for", () => {+ const paid = render(+ <TeamPlanRow+ wallet={w({ held: true, licensedUsers: 100, usersInUse: 95 })}+ />,+ );+ expect(paid.container.querySelector(".billing-meter--warn")).not.toBeNull();+ paid.unmount();++ // A free tier filling up is the product working as intended, not a warning.+ const free = render(+ <TeamPlanRow+ wallet={w({ held: false, licensedUsers: 5, usersInUse: 5 }, freeWallet)}+ />,+ );+ expect(free.container.querySelector(".billing-meter--warn")).toBeNull();+ });++ it("prices Team only when the plan identity above does not", () => {+ // Team alone: the identity reads "Team, up to 100 users" and carries no price, so the row does.+ const alone = render(+ <TeamPlanRow+ wallet={w(+ { held: true, licensedUsers: 100, usersInUse: 4 },+ { processor: { active: false } },+ )}+ />,+ );+ expect(screen.getByText("$99/mo per 100 users")).toBeInTheDocument();+ alone.unmount();++ // With the Processor the identity already carries the base, so the row must not re-price it.+ render(+ <TeamPlanRow+ wallet={w(+ { held: true, licensedUsers: 100, usersInUse: 4 },+ { processor: { active: true } },+ )}+ />,+ );+ expect(+ screen.getByText("Included with your Team base"),+ ).toBeInTheDocument();+ expect(screen.queryByText("$99/mo per 100 users")).not.toBeInTheDocument();+ });++ it("phrases the free tier per edition", () => {+ const cloud = render(+ <TeamPlanRow+ wallet={w(+ { held: false, licensedUsers: null, usersInUse: 1 },+ freeWallet,+ )}+ />,+ );+ expect(+ screen.getByText("The Team plan covers 100 users"),+ ).toBeInTheDocument();+ cloud.unmount();++ render(+ <TeamPlanRow+ selfHosted+ wallet={w(+ { held: false, licensedUsers: null, usersInUse: 1 },+ freeWallet,+ )}+ />,+ );+ expect(+ screen.getByText("The free tier covers your first users"),+ ).toBeInTheDocument();+ });++ it("meters against the backend's free allowance while no plan is held", () => {+ const { container } = render(+ <TeamPlanRow+ wallet={w(+ { held: false, licensedUsers: null, usersInUse: 2 },+ {+ ...freeWallet,+ freeUserAllowance: 5,+ },+ )}+ />,+ );++ // The server already enforces this number, so the row states it rather than a constant.+ expect(screen.getByText("2 of 5 users")).toBeInTheDocument();+ expect(container.querySelector(".billing-meter__fill")).not.toBeNull();+ });++ it("lets the plan's own limit win once one is held", () => {+ render(+ <TeamPlanRow+ wallet={w(+ { held: true, licensedUsers: 100, usersInUse: 6 },+ {+ freeUserAllowance: 5,+ },+ )}+ />,+ );++ // One number governs at a time: a stale free allowance must not shrink a bought plan.+ expect(screen.getByText("6 of 100 users")).toBeInTheDocument();+ expect(screen.queryByText("6 of 5 users")).not.toBeInTheDocument();+ });++ it("drops the track when there is no limit to meter against", () => {+ const { container } = render(+ <TeamPlanRow+ wallet={w({ held: true, licensedUsers: null, usersInUse: 240 })}+ />,+ );++ expect(screen.getByText("240 users")).toBeInTheDocument();+ // A track with no denominator would claim headroom the absent limit cannot support.+ expect(container.querySelector(".billing-meter__fill")).toBeNull();+ });+});diff --git a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsxnew file mode 100644index 0000000000..e5d187d927--- /dev/null+++ b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx@@ -0,0 +1,130 @@+import { useTranslation } from "react-i18next";+import { MeterRow } from "@app/billing/MeterRow";+import type { ServerPlan } from "@app/billing/serverPlan";+import type { Wallet } from "@app/billing/types";++/**+ * The Team product, as a row: users against the capacity the plan covers.+ *+ * <p>Reads {@code wallet.team}, not {@code wallet.status}: that axis covers one product, so a team+ * holding Team without the Processor would be described wrongly by it.+ *+ * <p>{@code licensedUsers} is null for "no limit" and never a sentinel, so there is nothing to+ * divide by.+ */+export function TeamPlanRow({+ wallet,+ selfHosted = false,+ serverPlan,+ onAddCapacity,+}: {+ wallet: Wallet | null;+ serverPlan?: ServerPlan;+ /** Self-hosted phrases its free tier differently: that allowance is its own. */+ selfHosted?: boolean;+ /** Leader-only: the door that sells Team capacity. Omit for members. */+ onAddCapacity?: () => void;+}) {+ const { t } = useTranslation();+ if (serverPlan) {+ const unlimited = serverPlan.licenseType === "SERVER";+ const users = serverPlan.usersInUse;+ return (+ <MeterRow+ name={t("portal.billing.team.rowName", "Users")}+ mid={t(+ "portal.billing.serverPlan.included",+ "Included with your license",+ )}+ tone="paid"+ showTrack={!unlimited && users != null && serverPlan.maxUsers > 0}+ pct={+ users != null && serverPlan.maxUsers > 0+ ? (users / serverPlan.maxUsers) * 100+ : 0+ }+ fact={+ unlimited+ ? t("portal.billing.serverPlan.unlimited", "Unlimited users")+ : users == null+ ? t(+ "portal.billing.serverPlan.seats",+ "{{seats}} licensed seats",+ {+ seats: serverPlan.maxUsers.toLocaleString(),+ },+ )+ : t(+ "portal.billing.team.fact",+ "{{users}} of {{licensed}} users",+ {+ users: users.toLocaleString(),+ licensed: serverPlan.maxUsers.toLocaleString(),+ },+ )+ }+ />+ );+ }+ if (!wallet) return null;+ const { held, licensedUsers, usersInUse } = wallet.team;+ const processorActive = Boolean(wallet.processor?.active);++ const mid = !held+ ? selfHosted+ ? t(+ "portal.billing.team.midFreeSelfHosted",+ "The free tier covers your first users",+ )+ : t("portal.billing.team.midFree", "The Team plan covers 100 users")+ : processorActive+ ? t("portal.billing.team.midIncluded", "Included with your Team base")+ : t("portal.billing.team.midPrice", "$99/mo per 100 users");++ const door = onAddCapacity+ ? t("portal.billing.team.addCapacity", "Add capacity")+ : undefined;+ const name = t("portal.billing.team.rowName", "Users");++ // One number in charge at a time: the server's free allowance until a plan is held, the+ // plan's own limit after.+ const limit = held+ ? licensedUsers+ : (licensedUsers ?? wallet.freeUserAllowance ?? null);++ // A non-positive limit is an absent one, not a full meter: nothing to divide by either way.+ if (limit == null || limit <= 0) {+ return (+ <MeterRow+ name={name}+ mid={mid}+ showTrack={false}+ tone={held ? "paid" : "free"}+ fact={t("portal.billing.team.factNoLimit", "{{users}} users", {+ users: usersInUse.toLocaleString(),+ })}+ door={door}+ onDoor={onAddCapacity}+ />+ );+ }++ const pct = (usersInUse / limit) * 100;+ // A free tier filling up is the product working, not a warning, so amber is for paid capacity.+ const tone = held ? (pct >= 90 ? "warn" : "paid") : "free";++ return (+ <MeterRow+ name={name}+ mid={mid}+ pct={pct}+ tone={tone}+ fact={t("portal.billing.team.fact", "{{users}} of {{licensed}} users", {+ users: usersInUse.toLocaleString(),+ licensed: limit.toLocaleString(),+ })}+ door={door}+ onDoor={onAddCapacity}+ />+ );+}diff --git a/frontend/editor/src/proprietary/billing/billing-screen.css b/frontend/editor/src/proprietary/billing/billing-screen.cssnew file mode 100644index 0000000000..96992ebb66--- /dev/null+++ b/frontend/editor/src/proprietary/billing/billing-screen.css@@ -0,0 +1,471 @@+/*+ * The billing screen's own stylesheet, shared by every edition that renders it.+ *+ * Colours must go through the semantic tokens, never a literal: that is what makes both themes+ * come out right, and theme-lint blocks the alternative.+ */++.billing-page {+ display: flex;+ flex-direction: column;+ min-height: 100%;+}++.billing-page__head {+ flex-shrink: 0;+ padding: 1.75rem 2.5rem 0.75rem;+}++.billing-page__title {+ margin: 0;+ font-size: 1.75rem;+ font-weight: 700;+ letter-spacing: -0.01em;+ color: var(--c-text);+}++.billing-page__subtitle {+ margin: 0.125rem 0 0;+ font-size: 0.875rem;+ line-height: 1.4;+ color: var(--c-text-subtle);+}++.billing-page__body {+ flex: 1;+ padding: 1rem 2.5rem 1.5rem;+}++.billing-page__notices:not(:empty) {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ margin-bottom: 1rem;+}++.billing-card {+ overflow: hidden;+ background: var(--c-surface);+ border: 1px solid var(--c-border-subtle);+ border-radius: 0.75rem;+}++.billing-card__chips {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.375rem;+ padding: 0.625rem 1.125rem;+ border-bottom: 1px solid var(--c-border-subtle);+}++.billing-card__chip {+ padding: 0.3125rem 0.6875rem;+ font: inherit;+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--c-text-subtle);+ cursor: pointer;+ background: transparent;+ border: none;+ border-radius: 0.4375rem;+ transition:+ background-color 0.12s ease,+ color 0.12s ease;+}++.billing-card__chip:hover {+ color: var(--c-text);+ background: var(--c-hover);+}++.billing-sec {+ padding: 1.25rem 1.625rem 0.125rem;+ border-top: 1px solid var(--c-border-subtle);+ /* Chips scroll to these, so clear the sticky page head. */+ scroll-margin-top: 3.25rem;+}++.billing-sec:first-of-type {+ border-top: none;+}++.billing-sec--procurement {+ padding-bottom: 1.25rem;+}++.billing-sec:last-of-type {+ padding-bottom: 1.375rem;+}++.billing-sec.billing-sec--license {+ padding-block: 0.125rem;+}++.billing-eyebrow {+ display: block;+ margin: 0 0 0.625rem;+ font-size: 0.6875rem;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--c-text-subtle);+}++.billing-eyebrow-row {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+}++.billing-eyebrow-row__fact {+ font-size: 0.75rem;+ font-variant-numeric: tabular-nums;+ color: var(--c-text-subtle);+}++.billing-id {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 0.75rem;+}++.billing-id__name {+ font-size: 1.375rem;+ font-weight: 700;+ letter-spacing: -0.01em;+ color: var(--c-text);+}++.billing-id__sub {+ font-size: 0.78125rem;+ color: var(--c-text-subtle);+}++.billing-id__chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+ margin-top: 0.625rem;+}++.billing-id__chip {+ padding: 0.1875rem 0.625rem;+ font-size: 0.71875rem;+ font-weight: 600;+ color: var(--c-text-muted);+ border: 1px solid var(--c-border-subtle);+ border-radius: 1.25rem;+}++.billing-meters {+ margin-top: 0.875rem;+ border-top: 1px solid var(--c-border-subtle);+}++.billing-meter {+ display: flex;+ align-items: center;+ gap: 0.875rem;+ padding: 0.75rem 0;+ border-top: 1px solid var(--c-border-subtle);+}++.billing-meter:first-child {+ border-top: none;+}++.billing-meter__dot {+ flex-shrink: 0;+ width: 0.4375rem;+ height: 0.4375rem;+ border-radius: 50%;+ background: var(--c-primary);+}++.billing-meter--paid .billing-meter__dot,+.billing-meter--paid .billing-meter__fill {+ background: var(--c-success-solid);+}++.billing-meter--warn .billing-meter__dot,+.billing-meter--warn .billing-meter__fill {+ background: var(--c-warning-solid);+}++.billing-meter__name {+ flex-shrink: 0;+ width: 4.75rem;+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--c-text);+}++.billing-meter__mid {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ font-size: 0.75rem;+ color: var(--c-text-subtle);+ text-overflow: ellipsis;+ white-space: nowrap;+}++.billing-meter__track {+ flex-shrink: 0;+ width: 6.875rem;+ height: 0.3125rem;+ overflow: hidden;+ background: var(--c-surface-sunken);+ border-radius: 0.1875rem;+}++.billing-meter__fill {+ display: block;+ height: 100%;+ background: var(--c-primary);+ border-radius: 0.1875rem;+ transition: width 0.3s ease;+}++.billing-meter__fact {+ flex-shrink: 0;+ width: 7rem;+ font-size: 0.78125rem;+ font-variant-numeric: tabular-nums;+ color: var(--c-text-muted);+ text-align: right;+}++.billing-meter__door {+ flex-shrink: 0;+ width: 10.625rem;+ padding: 0;+ font: inherit;+ font-size: 0.78125rem;+ font-weight: 600;+ color: var(--c-accent-text);+ text-align: right;+ text-underline-offset: 2px;+ white-space: nowrap;+ cursor: pointer;+ background: none;+ border: none;+}++.billing-meter__door:hover,+.billing-meter__door:focus-visible {+ text-decoration: underline;+}++.billing-bignum-row {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 0.625rem;+ margin-bottom: 0.375rem;+}++.billing-bignum {+ font-size: 1.75rem;+ font-weight: 800;+ letter-spacing: -0.01em;+ font-variant-numeric: tabular-nums;+ color: var(--c-text);+}++.billing-bignum__note {+ font-size: 0.75rem;+ color: var(--c-text-subtle);+}++.billing-kv {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ padding: 0.5625rem 0;+ border-top: 1px solid var(--c-border-subtle);+}++.billing-kv:first-of-type {+ border-top: none;+}++.billing-kv__label {+ flex-shrink: 0;+ font-size: 0.75rem;+ font-weight: 500;+ color: var(--c-text-subtle);+}++.billing-kv__value {+ min-width: 0;+ font-size: 0.75rem;+ font-weight: 500;+ font-variant-numeric: tabular-nums;+ color: var(--c-text);+ text-align: right;+}++.billing-kv__note {+ margin-right: 0.25rem;+ font-weight: 400;+ color: var(--c-text-subtle);+}++.billing-ent {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ margin-top: 1rem;+ padding: 1.125rem 1.625rem;+ background: var(--c-surface);+ border: 1px solid var(--c-border-subtle);+ border-radius: 0.75rem;+}++.billing-ent__title {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--c-text);+}++.billing-ent__sub {+ margin-top: 0.1875rem;+ font-size: 0.75rem;+ line-height: 1.5;+ color: var(--c-text-subtle);+}++@media (max-width: 48rem) {+ .billing-page__head,+ .billing-page__body {+ padding-inline: 1rem;+ }++ /* The row collapses to two lines rather than crushing the meter: identity above, meter below. */+ .billing-meter {+ flex-wrap: wrap;+ }++ .billing-meter__mid {+ flex-basis: 100%;+ order: 3;+ white-space: normal;+ }++ .billing-meter__door {+ width: auto;+ }+}++.billing-ent__cta {+ flex-shrink: 0;+ padding: 0.5rem 1rem;+ font: inherit;+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--c-text);+ cursor: pointer;+ background: transparent;+ border: 1px solid var(--c-border);+ border-radius: 0.5625rem;+ transition: background-color 0.12s ease;+}++.billing-ent__cta:hover {+ background: var(--c-hover);+}++.billing-inv {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 0.5625rem 0;+ border-top: 1px solid var(--c-border-subtle);+}++.billing-inv:first-of-type {+ border-top: none;+}++.billing-inv__date {+ flex-shrink: 0;+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--c-text);+}++.billing-inv__desc {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ font-size: 0.75rem;+ color: var(--c-text-subtle);+ text-overflow: ellipsis;+ white-space: nowrap;+}++.billing-inv__amount {+ font-size: 0.8125rem;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ color: var(--c-text);+ text-align: right;+}++.billing-inv__door {+ flex-shrink: 0;+ min-width: 2.5rem;+ font-size: 0.78125rem;+ font-weight: 600;+ color: var(--c-accent-text);+ text-align: right;+ text-decoration: none;+ text-underline-offset: 2px;+}++.billing-inv__door:hover,+.billing-inv__door:focus-visible {+ text-decoration: underline;+}++.billing-kv__door {+ margin-left: 0.75rem;+ font-weight: 600;+ color: var(--c-accent-text);+}++.billing-kv__door button {+ padding: 0;+ font: inherit;+ font-weight: 600;+ color: var(--c-accent-text);+ cursor: pointer;+ background: none;+ border: none;+ text-underline-offset: 2px;+}++.billing-kv__door button:hover,+.billing-kv__door button:focus-visible {+ text-decoration: underline;+}++.billing-license__actions {+ display: inline-flex;+ gap: 0.75rem;+}++.billing-license__value {+ overflow-wrap: anywhere;+ user-select: all;+}++.billing-id__action {+ margin-left: auto;+}diff --git a/frontend/editor/src/proprietary/billing/index.ts b/frontend/editor/src/proprietary/billing/index.tsindex 2fe9dffd93..3a8ed957e3 100644--- a/frontend/editor/src/proprietary/billing/index.ts+++ b/frontend/editor/src/proprietary/billing/index.ts@@ -5,6 +5,8 @@ export type {WalletMember,WalletCategoryBreakdown,WalletActivityRow,+ TeamHolding,+ ProcessorHolding,} from "@app/billing/types";export {DEFAULT_CAP_PRESETS,@@ -33,6 +35,19 @@ export {type MeterState,} from "@app/billing/format";export { MeterBar } from "@app/billing/MeterBar";+export {+ BillingScreen,+ type BillingScreenProps,+} from "@app/billing/BillingScreen";+export { TeamPlanRow } from "@app/billing/TeamPlanRow";+export { ProcessorPlanRow } from "@app/billing/ProcessorPlanRow";+export {+ MeterRow,+ type MeterRowProps,+ type MeterRowTone,+} from "@app/billing/MeterRow";+export { KvRow } from "@app/billing/KvRow";+export { InvoiceRow, type InvoiceRowState } from "@app/billing/InvoiceRow";export {SpendCapControl,type SpendCapControlProps,diff --git a/frontend/editor/src/proprietary/billing/pendingUsage.test.ts b/frontend/editor/src/proprietary/billing/pendingUsage.test.tsnew file mode 100644index 0000000000..bba05eadb5--- /dev/null+++ b/frontend/editor/src/proprietary/billing/pendingUsage.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";+import { estimatedBillWithPending } from "@app/billing/pendingUsage";+import { subscribedWallet } from "@app/billing/walletFixtures";++describe("pending credit charges", () => {+ it.each([+ [100, 300, 0, 0],+ [400, 300, 200, 0],+ [600, 300, 200, 100],+ [250, 0, 0, 250],+ ])(+ "accounts for free and prepaid credits (%i pending, %i free, %i prepaid)",+ (pending, free, prepaid, paid) => {+ expect(+ estimatedBillWithPending(+ {+ ...subscribedWallet,+ estimatedBillMinor: 1000,+ pricePerDocMinor: 1,+ freeRemaining: free,+ prepaidUnitsRemaining: prepaid,+ },+ pending,+ ),+ ).toBe(1000 + paid);+ },+ );+ it("does not price overflow without an active meter", () => {+ expect(+ estimatedBillWithPending(+ {+ ...subscribedWallet,+ processor: { active: false },+ estimatedBillMinor: 0,+ },+ 500,+ ),+ ).toBe(0);+ });+ it("preserves an unknown estimate", () => {+ expect(+ estimatedBillWithPending(+ { ...subscribedWallet, estimatedBillMinor: null },+ 500,+ ),+ ).toBeNull();+ });+});diff --git a/frontend/editor/src/proprietary/billing/pendingUsage.ts b/frontend/editor/src/proprietary/billing/pendingUsage.tsnew file mode 100644index 0000000000..643a59e2bc--- /dev/null+++ b/frontend/editor/src/proprietary/billing/pendingUsage.ts@@ -0,0 +1,25 @@+import type { Wallet } from "@app/billing/types";++/** Pending usage consumes the remaining free grant and prepaid pool before the meter. */+export function pendingMeteredUnits(+ wallet: Wallet,+ pendingUnits: number,+): number {+ if (!wallet.processor.active) return 0;+ return Math.max(+ 0,+ pendingUnits - wallet.freeRemaining - wallet.prepaidUnitsRemaining,+ );+}++/** Estimated metered charges including unsynced usage; null preserves an unknown rate. */+export function estimatedBillWithPending(+ wallet: Wallet,+ pendingUnits: number,+): number | null {+ if (wallet.estimatedBillMinor == null) return null;+ return (+ wallet.estimatedBillMinor ++ pendingMeteredUnits(wallet, pendingUnits) * (wallet.pricePerDocMinor ?? 0)+ );+}diff --git a/frontend/editor/src/proprietary/billing/serverPlan.ts b/frontend/editor/src/proprietary/billing/serverPlan.tsnew file mode 100644index 0000000000..6464278ef0--- /dev/null+++ b/frontend/editor/src/proprietary/billing/serverPlan.ts@@ -0,0 +1,6 @@+/** Validated local entitlement; cloud wallet membership must not supply the server's seats. */+export interface ServerPlan {+ licenseType: "SERVER" | "ENTERPRISE";+ maxUsers: number;+ usersInUse: number | null;+}diff --git a/frontend/editor/src/proprietary/billing/types.ts b/frontend/editor/src/proprietary/billing/types.tsindex 47f33a60b7..5e9df435b6 100644--- a/frontend/editor/src/proprietary/billing/types.ts+++ b/frontend/editor/src/proprietary/billing/types.ts@@ -76,6 +76,11 @@ export interface Wallet {billableLimit: number | null;/** Free grant size per billing period; unused units don't carry over. */freeAllowance: number;+ /**+ * Users the team may have with no Team plan. The server enforces this, so the capacity row shows+ * it as the denominator rather than any surface restating the number.+ */+ freeUserAllowance: number;/** Free grant left in this period; 0 = exhausted. */freeRemaining: number;/** Paid per-document rate in minor units (may be fractional); null = unknown (render "unknown", never substitute). */diff --git a/frontend/editor/src/proprietary/billing/walletFixtures.ts b/frontend/editor/src/proprietary/billing/walletFixtures.tsnew file mode 100644index 0000000000..71ed8e8179--- /dev/null+++ b/frontend/editor/src/proprietary/billing/walletFixtures.ts@@ -0,0 +1,93 @@+import type { Wallet } from "@app/billing/types";++/** Free monthly grant, leader view. Override per story. */+export const freeWallet: Wallet = {+ teamId: 42,+ status: "free",+ team: { held: false, licensedUsers: null, usersInUse: 1 },+ processor: { active: false },+ role: "leader",+ billingPeriodStart: "2026-06-01",+ billingPeriodEnd: "2026-06-30",+ billableUsed: 120,+ billableLimit: 500,+ freeUserAllowance: 5,+ freeAllowance: 500,+ freeRemaining: 380,+ pricePerDocMinor: 2,+ bundleRatePerCreditMinor: 1,+ currency: "usd",+ estimatedBillMinor: null,+ capUsd: null,+ noCap: false,+ stripeSubscriptionId: null,+ spendUnitsThisPeriod: 120,+ categoryBreakdown: { api: 40, ai: 30, automation: 50 },+ categoryDocs: { api: 30, ai: 20, automation: 40 },+ docsProcessedThisPeriod: 90,+ uniquePdfsThisPeriod: 84,+ sizeMultiplierPdfsThisPeriod: 12,+ billingMode: "payg",+ prepaidUnitsRemaining: 0,+ prepaidUnitsTotal: 0,+ prepaidExpiresAt: null,+ members: [],+ recent: [],+};++/** Subscribed and capped, leader view with members. */+export const subscribedWallet: Wallet = {+ teamId: 42,+ status: "subscribed",+ team: { held: false, licensedUsers: null, usersInUse: 4 },+ processor: { active: true },+ role: "leader",+ billingPeriodStart: "2026-06-01",+ billingPeriodEnd: "2026-06-30",+ billableUsed: 2250,+ billableLimit: 50000,+ freeUserAllowance: 5,+ freeAllowance: 500,+ freeRemaining: 0,+ pricePerDocMinor: 2,+ bundleRatePerCreditMinor: 1,+ currency: "usd",+ estimatedBillMinor: 4500,+ capUsd: 1000,+ noCap: false,+ stripeSubscriptionId: "sub_123",+ spendUnitsThisPeriod: 2250,+ categoryBreakdown: { api: 900, ai: 600, automation: 750 },+ categoryDocs: { api: 700, ai: 450, automation: 600 },+ docsProcessedThisPeriod: 1750,+ uniquePdfsThisPeriod: 1600,+ sizeMultiplierPdfsThisPeriod: 320,+ billingMode: "payg",+ prepaidUnitsRemaining: 0,+ prepaidUnitsTotal: 0,+ prepaidExpiresAt: null,+ members: [+ {+ userId: "u1",+ name: "Ada Lovelace",+ email: "[email protected]",+ spendUnits: 1400,+ },+ {+ userId: "u2",+ name: "Alan Turing",+ email: "[email protected]",+ spendUnits: 850,+ },+ ],+ recent: [],+};++/** Mid-drawn prepaid pool expiring in-term, for the prepaid-capacity card. */+export const prepaidWallet: Wallet = {+ ...subscribedWallet,+ billingMode: "prepaid",+ prepaidUnitsRemaining: 78000,+ prepaidUnitsTotal: 120000,+ prepaidExpiresAt: "2027-03-01",+};diff --git a/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx b/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsxindex 04c0420de1..5b7fedc63a 100644--- a/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx+++ b/frontend/editor/src/proprietary/components/settings/portalSettingsNav.tsx@@ -192,6 +192,8 @@ export const PORTAL_SUPERSEDED_SECTION_KEYS: readonly NavKey[] = [// the superset, so it replaces rather than duplicates it."users","api-keys",+ "plan",+ "adminPlan",];/** Where a superseded section's bookmarks and search results now land. */@@ -199,6 +201,8 @@ export const PORTAL_SECTION_ALIASES: Partial<Record<string, NavKey>> = {people: "users",teams: "users",infrastructure: "api-keys",+ plan: "billing",+ adminPlan: "billing",// The processor links to a build-neutral "audit"; self-hosted's is the admin one.audit: "adminAudit",};diff --git a/frontend/editor/src/proprietary/components/shared/ManageBillingButton.stories.tsx b/frontend/editor/src/proprietary/components/shared/ManageBillingButton.stories.tsxindex f860767b43..56ff59a30e 100644--- a/frontend/editor/src/proprietary/components/shared/ManageBillingButton.stories.tsx+++ b/frontend/editor/src/proprietary/components/shared/ManageBillingButton.stories.tsx@@ -1,5 +1,9 @@import type { Meta, StoryObj } from "@storybook/react-vite";+import { expect, within } from "storybook/test";+import { http, HttpResponse } from "msw";import { ManageBillingButton } from "@app/components/shared/ManageBillingButton";+import { AppConfigProvider } from "@app/contexts/AppConfigContext";+import { LicenseProvider } from "@app/contexts/LicenseContext";/*** Button that opens the Stripe billing portal for the current license.@@ -7,7 +11,41 @@ import { ManageBillingButton } from "@app/components/shared/ManageBillingButton"const meta = {title: "Shared/ManageBillingButton",component: ManageBillingButton,- parameters: { layout: "centered" },+ parameters: {+ layout: "centered",+ msw: {+ handlers: [+ http.get("*/api/v1/admin/license-info", () =>+ HttpResponse.json({+ licenseType: "SERVER",+ enabled: true,+ maxUsers: 0,+ hasKey: true,+ licenseKey: "storybook-server-license",+ }),+ ),+ http.post("http://billing.mock/functions/v1/manage-billing", () =>+ HttpResponse.json({ url: "https://example.com/billing" }),+ ),+ ],+ },+ },+ decorators: [+ (Story) => (+ <AppConfigProvider autoFetch={false} initialConfig={{ isAdmin: true }}>+ <LicenseProvider>+ <Story />+ </LicenseProvider>+ </AppConfigProvider>+ ),+ ],+ play: async ({ canvasElement }) => {+ await expect(+ await within(canvasElement).findByRole("button", {+ name: "Manage Billing",+ }),+ ).toBeVisible();+ },} satisfies Meta<typeof ManageBillingButton>;export default meta;diff --git a/frontend/editor/src/proprietary/components/shared/ManageBillingButton.test.tsx b/frontend/editor/src/proprietary/components/shared/ManageBillingButton.test.tsxnew file mode 100644index 0000000000..cafd4acb04--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/ManageBillingButton.test.tsx@@ -0,0 +1,83 @@+vi.mock("@app/contexts/LicenseContext", () => ({+ useLicense: () => ({ licenseInfo: service.license }),+}));+vi.mock("@app/services/supabaseClient", () => ({+ get isSupabaseConfigured() {+ return service.configured;+ },+ supabase: {},+}));+import { MantineProvider } from "@mantine/core";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+const service = vi.hoisted(() => ({+ getLicenseInfo: vi.fn(),+ configured: true,+ license: { enabled: true, licenseKey: "test-installed-license" },+ createBillingPortalSession: vi.fn(),+}));+vi.mock("@app/services/licenseService", () => ({ default: service }));+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));+import { ManageBillingButton } from "@app/components/shared/ManageBillingButton";+it("opens the legacy subscription using the installed licence identity", async () => {+ service.getLicenseInfo.mockResolvedValue({+ licenseKey: "test-installed-license",+ });+ service.createBillingPortalSession.mockResolvedValue({+ url: "https://billing.stripe.com/test",+ });+ const open = vi.spyOn(window, "open").mockImplementation(() => null);+ render(+ <MantineProvider>+ <ManageBillingButton returnUrl="https://server.example/settings/billing" />+ </MantineProvider>,+ );+ fireEvent.click(screen.getByRole("button", { name: "Manage Billing" }));+ await waitFor(() =>+ expect(service.createBillingPortalSession).toHaveBeenCalledWith(+ "https://server.example/settings/billing",+ "test-installed-license",+ ),+ );+ expect(open).toHaveBeenCalledWith(+ "https://billing.stripe.com/test",+ "_blank",+ );+ open.mockRestore();+});++beforeEach(() => {+ service.configured = true;+ service.license = { enabled: true, licenseKey: "test-installed-license" };+ service.createBillingPortalSession.mockClear();+});+it.each([+ "file:/licenses/enterprise.lic",+ "",+ "00000000-0000-0000-0000-000000000000",+])("hides billing for a non-billing key: %s", (licenseKey) => {+ service.license.licenseKey = licenseKey;+ render(+ <MantineProvider>+ <ManageBillingButton />+ </MantineProvider>,+ );+ expect(+ screen.queryByRole("button", { name: "Manage Billing" }),+ ).not.toBeInTheDocument();+ expect(service.createBillingPortalSession).not.toHaveBeenCalled();+});+it("hides billing when the portal service is unconfigured", () => {+ service.configured = false;+ render(+ <MantineProvider>+ <ManageBillingButton />+ </MantineProvider>,+ );+ expect(+ screen.queryByRole("button", { name: "Manage Billing" }),+ ).not.toBeInTheDocument();+});diff --git a/frontend/editor/src/proprietary/components/shared/ManageBillingButton.tsx b/frontend/editor/src/proprietary/components/shared/ManageBillingButton.tsxindex 22450f441e..5583f9c9ff 100644--- a/frontend/editor/src/proprietary/components/shared/ManageBillingButton.tsx+++ b/frontend/editor/src/proprietary/components/shared/ManageBillingButton.tsx@@ -2,6 +2,8 @@ import React, { useState } from "react";import { Button } from "@app/ui/Button";import { useTranslation } from "react-i18next";import licenseService from "@app/services/licenseService";+import { useLicense } from "@app/contexts/LicenseContext";+import { isSupabaseConfigured, supabase } from "@app/services/supabaseClient";import { alert } from "@app/components/toast";interface ManageBillingButtonProps {@@ -13,24 +15,25 @@ export const ManageBillingButton: React.FC<ManageBillingButtonProps> = ({}) => {const { t } = useTranslation();const [loading, setLoading] = useState(false);+ const { licenseInfo } = useLicense();+ const licenseKey = licenseInfo?.licenseKey?.trim();+ if (+ !isSupabaseConfigured ||+ !supabase ||+ !licenseInfo?.enabled ||+ !licenseKey ||+ licenseKey.startsWith("file:") ||+ licenseKey === "00000000-0000-0000-0000-000000000000"+ )+ return null;const handleClick = async () => {try {setLoading(true);- // Get current license key for authentication- const licenseInfo = await licenseService.getLicenseInfo();-- if (!licenseInfo.licenseKey) {- throw new Error(- "No license key found. Please activate a license first.",- );- }-- // Create billing portal session with license keyconst response = await licenseService.createBillingPortalSession(returnUrl,- licenseInfo.licenseKey,+ licenseKey,);// Open billing portal in new tabdiff --git a/frontend/editor/src/portal/components/shared/StepModalHeader.css b/frontend/editor/src/proprietary/components/shared/StepModalHeader.csssimilarity index 100%rename from frontend/editor/src/portal/components/shared/StepModalHeader.cssrename to frontend/editor/src/proprietary/components/shared/StepModalHeader.cssdiff --git a/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsx b/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsxnew file mode 100644index 0000000000..6436c76143--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/StepModalHeader.tsx@@ -0,0 +1,126 @@+import type { ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@app/ui";+// No brand webfont is loaded, so the wordmark must be this SVG rather than styled text.+import wordmarkLight from "@app/assets/brand/modern-logo/StirlingProcessorLogoBlackText.svg";+import wordmarkDark from "@app/assets/brand/modern-logo/StirlingProcessorLogoWhiteText.svg";+import "@app/components/shared/StepModalHeader.css";++/**+ * Header for any stepped flow modal: identity row, step badge, progress bar, step title. Worn by+ * the prepay wizard, the metered checkout and the procurement quote builder.+ *+ * <p>The step label arrives already translated, so each flow keeps its own copy key.+ */+export function StepModalHeader({+ title,+ subtitle,+ step,+ total,+ stepLabel,+ aside,+ brand = false,+ className,+ closeLabel,+ onClose,+}: {+ /** The current step's heading. Omit when the host modal already renders one. */+ title?: string;+ /** A line under the title, for a heading that needs qualifying. */+ subtitle?: ReactNode;+ /** Actions belonging to what is on screen, seated before the close. */+ aside?: ReactNode;+ /** 1-based current step. Omit to hide the badge and the progress bar (e.g. a terminal receipt). */+ step?: number;+ /** Segments to draw; any length. */+ total?: number;+ /** Pre-translated "Step 2 of 3"; omitted renders no badge. */+ stepLabel?: string;+ /** Show the Stirling wordmark instead of a plain heading, for flows that stand alone. */+ brand?: boolean;+ /** Extra class on the root, so a host modal can own its own padding. */+ className?: string;+ closeLabel?: string;+ /** Omit when the host modal already owns a close control, so there is only ever one. */+ onClose?: () => void;+}) {+ const { t } = useTranslation();+ const showSteps = step != null && total != null && total > 0;++ return (+ <div className={`portal-stepmodal__head ${className ?? ""}`.trim()}>+ <div className="portal-stepmodal__head-top">+ {brand ? (+ <div className="portal-stepmodal__brand">+ {/* `wordmark`, not `wordmark-light-only`: theme.css hides the former in dark mode and+ has no rule for the latter, so both used to render at once. */}+ <img+ src={wordmarkLight}+ alt="Stirling"+ className="portal-stepmodal__wordmark wordmark"+ />+ <img+ src={wordmarkDark}+ alt=""+ aria-hidden+ className="portal-stepmodal__wordmark wordmark-dark-only"+ />+ </div>+ ) : title ? (+ <div className="portal-stepmodal__ident">+ <h3 className="portal-stepmodal__flow-title">{title}</h3>+ {subtitle && (+ <p className="portal-stepmodal__flow-sub">{subtitle}</p>+ )}+ </div>+ ) : (+ <span />+ )}+ <div className="portal-stepmodal__head-right">+ {aside}+ {stepLabel && (+ <span className="portal-stepmodal__step">{stepLabel}</span>+ )}+ {onClose && (+ <Button+ variant="tertiary"+ accent="neutral"+ size="sm"+ shape="circle"+ onClick={onClose}+ aria-label={closeLabel ?? t("portal.stepModal.close", "Close")}+ leftSection={+ <svg+ viewBox="0 0 24 24"+ width="16"+ height="16"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.75}+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ >+ <line x1="18" y1="6" x2="6" y2="18" />+ <line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ }+ />+ )}+ </div>+ </div>++ {showSteps && (+ <div className="portal-stepmodal__progress" aria-hidden>+ {Array.from({ length: total }, (_, i) => (+ <span key={i} className={i < step ? "is-filled" : ""} />+ ))}+ </div>+ )}++ {/* With the wordmark up top the step title carries the heading; without it the flow title+ already did, so repeating it here would say the same thing twice. */}+ {brand && <div className="portal-stepmodal__title">{title}</div>}+ </div>+ );+}diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/plan/LicenseKeySection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/plan/LicenseKeySection.tsxindex 0b88820d9d..7798d0df0f 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/plan/LicenseKeySection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/plan/LicenseKeySection.tsx@@ -23,10 +23,16 @@ import { useLoginRequired } from "@app/hooks/useLoginRequired";interface LicenseKeySectionProps {currentLicenseInfo?: LicenseInfo;+ /** Form-only presentation for hosts that supply their own dialog. */+ presentation?: "disclosure" | "form";+ /** Refresh any host-owned entitlement views after the license context has updated. */+ onSaved?: () => void;}const LicenseKeySection: React.FC<LicenseKeySectionProps> = ({currentLicenseInfo,+ presentation = "disclosure",+ onSaved,}) => {const { t } = useTranslation();const { refetchLicense } = useLicense();@@ -69,6 +75,7 @@ const LicenseKeySection: React.FC<LicenseKeySectionProps> = ({if (response.success) {// Refresh license context to update all componentsawait refetchLicense();+ onSaved?.();const successMessage =inputMethod === "file"@@ -112,6 +119,221 @@ const LicenseKeySection: React.FC<LicenseKeySectionProps> = ({}};+ const form = (+ <Stack gap="md">+ <Alert+ variant="light"+ color="blue"+ icon={<LocalIcon icon="info-rounded" width="1rem" height="1rem" />}+ >+ <Text size="sm">+ {t(+ "admin.settings.premium.licenseKey.info",+ "If you have a license key or certificate file from a direct purchase, you can enter it here to activate premium or enterprise features.",+ )}+ </Text>+ </Alert>++ {/* Severe warning if license already exists */}+ {currentLicenseInfo?.licenseKey && (+ <Alert+ variant="light"+ color="red"+ icon={<LocalIcon icon="warning-rounded" width="1rem" height="1rem" />}+ title={t(+ "admin.settings.premium.key.overwriteWarning.title",+ "⚠️ Warning: Existing License Detected",+ )}+ >+ <Stack gap="xs">+ <Text size="sm" fw={600}>+ {t(+ "admin.settings.premium.key.overwriteWarning.line1",+ "Overwriting your current license key cannot be undone.",+ )}+ </Text>+ <Text size="sm">+ {t(+ "admin.settings.premium.key.overwriteWarning.line2",+ "Your previous license will be permanently lost unless you have backed it up elsewhere.",+ )}+ </Text>+ <Text size="sm" fw={500}>+ {t(+ "admin.settings.premium.key.overwriteWarning.line3",+ "Important: Keep license keys private and secure. Never share them publicly.",+ )}+ </Text>+ </Stack>+ </Alert>+ )}++ {/* Show current license source */}+ {currentLicenseInfo?.licenseKey && (+ <Alert+ variant="light"+ color="green"+ icon={+ <LocalIcon icon="check-circle-rounded" width="1rem" height="1rem" />+ }+ >+ <Stack gap="xs">+ <Text size="sm" fw={500}>+ {t(+ "admin.settings.premium.currentLicense.title",+ "Active License",+ )}+ </Text>+ <Text size="xs">+ {currentLicenseInfo.licenseKey.startsWith("file:")+ ? t(+ "admin.settings.premium.currentLicense.file",+ "Source: License file ({{path}})",+ {+ path: currentLicenseInfo.licenseKey.substring(5),+ },+ )+ : t(+ "admin.settings.premium.currentLicense.key",+ "Source: License key",+ )}+ </Text>+ <Text size="xs">+ {t(+ "admin.settings.premium.currentLicense.type",+ "Type: {{type}}",+ {+ type: currentLicenseInfo.licenseType,+ },+ )}+ </Text>+ </Stack>+ </Alert>+ )}++ {/* Input method selector */}+ <SegmentedControl+ value={inputMethod}+ onChange={(value) => {+ setInputMethod(value);+ // Clear opposite input when switching+ if (value === "text") setLicenseFile(null);+ if (value === "file") setLicenseKeyInput("");+ }}+ options={[+ {+ label: t("admin.settings.premium.inputMethod.text", "License Key"),+ value: "text",+ disabled: !loginEnabled || savingLicense,+ },+ {+ label: t(+ "admin.settings.premium.inputMethod.file",+ "Certificate File",+ ),+ value: "file",+ disabled: !loginEnabled || savingLicense,+ },+ ]}+ />++ {/* Input area */}+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ {inputMethod === "text" ? (+ /* Text input */+ <TextInput+ label={+ <SettingsFieldLabel+ info={t(+ "admin.settings.premium.key.description",+ "Enter your premium or enterprise license key. Premium features will be automatically enabled when a key is provided.",+ )}+ >+ {t("admin.settings.premium.key.label", "License Key")}+ </SettingsFieldLabel>+ }+ value={licenseKeyInput}+ onChange={(e) => setLicenseKeyInput(e.target.value)}+ placeholder={+ (presentation === "disclosure"+ ? currentLicenseInfo?.licenseKey+ : undefined) || "00000000-0000-0000-0000-000000000000"+ }+ type="password"+ disabled={!loginEnabled || savingLicense}+ />+ ) : (+ /* File upload */+ <div>+ <Text size="sm" fw={500} mb="xs">+ {t(+ "admin.settings.premium.file.label",+ "License Certificate File",+ )}{" "}+ <InfoTooltip+ label={t(+ "admin.settings.premium.file.description",+ "Upload your .lic or .cert license file",+ )}+ />+ </Text>+ <FilePicker+ onChange={setLicenseFile}+ accept=".lic,.cert"+ disabled={!loginEnabled || savingLicense}+ variant="secondary"+ leftSection={+ <LocalIcon+ icon="upload-file-rounded"+ width="1rem"+ height="1rem"+ />+ }+ >+ {licenseFile+ ? licenseFile.name+ : t(+ "admin.settings.premium.file.choose",+ "Choose License File",+ )}+ </FilePicker>+ {licenseFile && (+ <Text size="xs" c="dimmed" mt="xs">+ {t(+ "admin.settings.premium.file.selected",+ "Selected: {{filename}} ({{size}})",+ {+ filename: licenseFile.name,+ size: (licenseFile.size / 1024).toFixed(2) + " KB",+ },+ )}+ </Text>+ )}+ </div>+ )}++ <Group justify="flex-end">+ <Button+ onClick={handleSaveLicense}+ loading={savingLicense}+ size="sm"+ disabled={+ !loginEnabled ||+ (inputMethod === "text" && !licenseKeyInput.trim()) ||+ (inputMethod === "file" && !licenseFile)+ }+ >+ {t("admin.settings.save", "Save Changes")}+ </Button>+ </Group>+ </Stack>+ </Paper>+ </Stack>+ );++ if (presentation === "form") return form;+return (<div><Button@@ -134,224 +356,7 @@ const LicenseKeySection: React.FC<LicenseKeySectionProps> = ({</Button><Collapse in={showLicenseKey} mt="md">- <Stack gap="md">- <Alert- variant="light"- color="blue"- icon={<LocalIcon icon="info-rounded" width="1rem" height="1rem" />}- >- <Text size="sm">- {t(- "admin.settings.premium.licenseKey.info",- "If you have a license key or certificate file from a direct purchase, you can enter it here to activate premium or enterprise features.",- )}- </Text>- </Alert>-- {/* Severe warning if license already exists */}- {currentLicenseInfo?.licenseKey && (- <Alert- variant="light"- color="red"- icon={- <LocalIcon icon="warning-rounded" width="1rem" height="1rem" />- }- title={t(- "admin.settings.premium.key.overwriteWarning.title",- "⚠️ Warning: Existing License Detected",- )}- >- <Stack gap="xs">- <Text size="sm" fw={600}>- {t(- "admin.settings.premium.key.overwriteWarning.line1",- "Overwriting your current license key cannot be undone.",- )}- </Text>- <Text size="sm">- {t(- "admin.settings.premium.key.overwriteWarning.line2",- "Your previous license will be permanently lost unless you have backed it up elsewhere.",- )}- </Text>- <Text size="sm" fw={500}>- {t(- "admin.settings.premium.key.overwriteWarning.line3",- "Important: Keep license keys private and secure. Never share them publicly.",- )}- </Text>- </Stack>- </Alert>- )}-- {/* Show current license source */}- {currentLicenseInfo?.licenseKey && (- <Alert- variant="light"- color="green"- icon={- <LocalIcon- icon="check-circle-rounded"- width="1rem"- height="1rem"- />- }- >- <Stack gap="xs">- <Text size="sm" fw={500}>- {t(- "admin.settings.premium.currentLicense.title",- "Active License",- )}- </Text>- <Text size="xs">- {currentLicenseInfo.licenseKey.startsWith("file:")- ? t(- "admin.settings.premium.currentLicense.file",- "Source: License file ({{path}})",- {- path: currentLicenseInfo.licenseKey.substring(5),- },- )- : t(- "admin.settings.premium.currentLicense.key",- "Source: License key",- )}- </Text>- <Text size="xs">- {t(- "admin.settings.premium.currentLicense.type",- "Type: {{type}}",- {- type: currentLicenseInfo.licenseType,- },- )}- </Text>- </Stack>- </Alert>- )}-- {/* Input method selector */}- <SegmentedControl- value={inputMethod}- onChange={(value) => {- setInputMethod(value);- // Clear opposite input when switching- if (value === "text") setLicenseFile(null);- if (value === "file") setLicenseKeyInput("");- }}- options={[- {- label: t(- "admin.settings.premium.inputMethod.text",- "License Key",- ),- value: "text",- disabled: !loginEnabled || savingLicense,- },- {- label: t(- "admin.settings.premium.inputMethod.file",- "Certificate File",- ),- value: "file",- disabled: !loginEnabled || savingLicense,- },- ]}- />-- {/* Input area */}- <Paper withBorder p="md" radius="md">- <Stack gap="md">- {inputMethod === "text" ? (- /* Text input */- <TextInput- label={- <SettingsFieldLabel- info={t(- "admin.settings.premium.key.description",- "Enter your premium or enterprise license key. Premium features will be automatically enabled when a key is provided.",- )}- >- {t("admin.settings.premium.key.label", "License Key")}- </SettingsFieldLabel>- }- value={licenseKeyInput}- onChange={(e) => setLicenseKeyInput(e.target.value)}- placeholder={- currentLicenseInfo?.licenseKey ||- "00000000-0000-0000-0000-000000000000"- }- type="password"- disabled={!loginEnabled || savingLicense}- />- ) : (- /* File upload */- <div>- <Text size="sm" fw={500} mb="xs">- {t(- "admin.settings.premium.file.label",- "License Certificate File",- )}{" "}- <InfoTooltip- label={t(- "admin.settings.premium.file.description",- "Upload your .lic or .cert license file",- )}- />- </Text>- <FilePicker- onChange={setLicenseFile}- accept=".lic,.cert"- disabled={!loginEnabled || savingLicense}- variant="secondary"- leftSection={- <LocalIcon- icon="upload-file-rounded"- width="1rem"- height="1rem"- />- }- >- {licenseFile- ? licenseFile.name- : t(- "admin.settings.premium.file.choose",- "Choose License File",- )}- </FilePicker>- {licenseFile && (- <Text size="xs" c="dimmed" mt="xs">- {t(- "admin.settings.premium.file.selected",- "Selected: {{filename}} ({{size}})",- {- filename: licenseFile.name,- size: (licenseFile.size / 1024).toFixed(2) + " KB",- },- )}- </Text>- )}- </div>- )}-- <Group justify="flex-end">- <Button- onClick={handleSaveLicense}- loading={savingLicense}- size="sm"- disabled={- !loginEnabled ||- (inputMethod === "text" && !licenseKeyInput.trim()) ||- (inputMethod === "file" && !licenseFile)- }- >- {t("admin.settings.save", "Save Changes")}- </Button>- </Group>- </Stack>- </Paper>- </Stack>+ {form}</Collapse></div>);diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsxnew file mode 100644index 0000000000..ae230ed43b--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.test.tsx@@ -0,0 +1,239 @@+vi.mock("@app/ui/ActionIcon", () => ({+ ActionIcon: ({+ children,+ onClick,+ "aria-label": label,+ }: {+ children: ReactNode;+ onClick: () => void;+ "aria-label": string;+ }) => (+ <button onClick={onClick} aria-label={label}>+ {children}+ </button>+ ),+}));+import { fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import type { PlanTierGroup } from "@app/services/licenseService";+const service = vi.hoisted(() => ({+ getLicenseInfo: vi.fn(),+ createCheckoutSession: vi.fn(),+}));+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>,+ Text: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Group: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}));+vi.mock(+ "@app/components/shared/stripeCheckout/hooks/useLicensePolling",+ () => ({ useLicensePolling: () => ({}) }),+);+vi.mock(+ "@app/components/shared/stripeCheckout/hooks/useCheckoutSession",+ () => ({+ useCheckoutSession: () => ({+ createCheckoutSession: service.createCheckoutSession,+ }),+ }),+);+vi.mock("@app/components/shared/stripeCheckout/stages/PaymentStage", () => ({+ PaymentStage: () => <div>Payment details</div>,+}));+vi.mock("@app/components/shared/stripeCheckout/stages/SuccessStage", () => ({+ SuccessStage: () => null,+}));+vi.mock("@app/components/shared/stripeCheckout/stages/ErrorStage", () => ({+ ErrorStage: () => null,+}));+vi.mock("@app/components/shared/stripeCheckout/stages/EmailStage", () => ({+ EmailStage: ({+ emailInput,+ setEmailInput,+ onSubmit,+ }: {+ emailInput: string;+ setEmailInput: (email: string) => void;+ onSubmit: () => void;+ }) => (+ <div>+ Buyer email+ <input+ aria-label="Email"+ value={emailInput}+ onChange={(event) => setEmailInput(event.target.value)}+ />+ <button onClick={onSubmit}>Continue</button>+ </div>+ ),+}));+vi.mock(+ "@app/components/shared/stripeCheckout/stages/PlanSelectionStage",+ () => ({+ PlanSelectionStage: ({+ onSelectPlan,+ }: {+ onSelectPlan: (period: "monthly" | "yearly") => void;+ }) => (+ <div>+ Billing period+ <button onClick={() => onSelectPlan("monthly")}>Monthly</button>+ </div>+ ),+ }),+);+vi.mock("@app/components/shared/stripeCheckout/stages/CapacityStage", () => ({+ CapacityStage: ({+ serverQuantity,+ currentLimit,+ onContinue,+ }: {+ serverQuantity: number;+ currentLimit: number;+ onContinue: () => void;+ }) => (+ <div>+ Capacity: {serverQuantity} blocks; current: {currentLimit}+ <button onClick={onContinue}>Continue to payment</button>+ </div>+ ),+}));+vi.mock("@app/components/shared/StepModalHeader", () => ({+ StepModalHeader: ({ aside }: { aside?: ReactNode }) => <div>{aside}</div>,+}));+import StripeCheckout from "@app/components/shared/stripeCheckout/StripeCheckout";+const planGroup: PlanTierGroup = {+ tier: "server",+ name: "Team",+ features: [],+ highlights: [],+ yearly: null,+ monthly: {+ id: "team",+ name: "Team",+ price: 99,+ currency: "usd",+ period: "month",+ features: [],+ highlights: [],+ lookupKey: "test:team:monthly",+ },+};+describe("capacity checkout entry", () => {+ beforeEach(() => {+ service.getLicenseInfo.mockReset();+ });+ it.each(["SERVER", "ENTERPRISE"])(+ "keeps combined choices for an existing %s licence",+ async (licenseType) => {+ service.getLicenseInfo.mockResolvedValue({+ licenseType,+ licenseKey: "test-license",+ });+ render(+ <StripeCheckout+ opened+ onClose={() => {}}+ planGroup={planGroup}+ combinedChoose+ minimumSeats={250}+ currentLimit={300}+ />,+ );+ expect(+ await screen.findByText("Capacity: 3 blocks; current: 300"),+ ).toBeInTheDocument();+ expect(screen.getByText("Billing period")).toBeInTheDocument();+ expect(screen.queryByText("Buyer email")).not.toBeInTheDocument();+ },+ );+ it("still asks a free user for their billing email", async () => {+ service.getLicenseInfo.mockResolvedValue({ licenseType: "NORMAL" });+ render(+ <StripeCheckout+ opened+ onClose={() => {}}+ planGroup={planGroup}+ combinedChoose+ />,+ );+ expect(await screen.findByText("Buyer email")).toBeInTheDocument();+ });+ it("seeds required capacity when the caller supplies an email", async () => {+ render(+ <StripeCheckout+ opened+ onClose={() => {}}+ planGroup={planGroup}+ combinedChoose+ initialEmail="[email protected]"+ minimumSeats={250}+ currentLimit={300}+ />,+ );+ expect(+ await screen.findByText("Capacity: 3 blocks; current: 300"),+ ).toBeInTheDocument();+ expect(service.getLicenseInfo).not.toHaveBeenCalled();+ });+});++describe("combined checkout for plans without capacity", () => {+ it.each(["supplied email", "existing license", "email entry"])(+ "reaches payment from %s",+ async (entry) => {+ service.getLicenseInfo.mockResolvedValue(+ entry === "existing license"+ ? { licenseType: "ENTERPRISE", licenseKey: "test-license" }+ : { licenseType: "NORMAL" },+ );+ render(+ <StripeCheckout+ opened+ onClose={() => {}}+ planGroup={{ ...planGroup, tier: "enterprise" }}+ combinedChoose+ initialEmail={+ entry === "supplied email" ? "[email protected]" : undefined+ }+ />,+ );+ if (entry === "email entry") {+ await screen.findByText("Buyer email");+ fireEvent.change(screen.getByLabelText("Email"), {+ target: { value: "[email protected]" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));+ }+ fireEvent.click(await screen.findByRole("button", { name: "Monthly" }));+ expect(await screen.findByText("Payment details")).toBeInTheDocument();+ expect(screen.queryByText(/Capacity:/)).not.toBeInTheDocument();+ },+ );+});++it("starts at held capacity and lets payment return to those choices", async () => {+ render(+ <StripeCheckout+ opened+ onClose={() => {}}+ planGroup={planGroup}+ combinedChoose+ initialEmail="[email protected]"+ minimumSeats={40}+ currentLimit={300}+ />,+ );+ expect(+ await screen.findByText("Capacity: 3 blocks; current: 300"),+ ).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Continue to payment" }));+ expect(await screen.findByText("Payment details")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "common.back" }));+ expect(+ await screen.findByText("Capacity: 3 blocks; current: 300"),+ ).toBeInTheDocument();+});diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsxindex 47589389e8..857b0258f9 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/StripeCheckout.tsx@@ -6,7 +6,11 @@ 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 { StripeCheckoutProps } from "@app/components/shared/stripeCheckout/types/checkout";+import {+ CheckoutStage,+ StripeCheckoutProps,+} from "@app/components/shared/stripeCheckout/types/checkout";+import { StepModalHeader } from "@app/components/shared/StepModalHeader";import {validateEmail,getModalTitle,@@ -47,6 +51,9 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({onClose,planGroup,minimumSeats = 1,+ initialEmail,+ combinedChoose: requestedCombinedChoose = false,+ currentLimit = null,onSuccess,onError,onLicenseActivated,@@ -54,6 +61,9 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({}) => {const { t } = useTranslation();const isMobile = useIsMobile();+ const sellsCapacity = planGroup.tier === "server";+ const combinedChoose = requestedCombinedChoose && sellsCapacity;+ const minimumCapacity = Math.max(minimumSeats, currentLimit ?? 0);// Initialize all state via custom hookconst checkoutState = useCheckoutState(planGroup);@@ -103,22 +113,27 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({...prev,email: checkoutState.emailInput,}));- navigation.goToStage("plan-selection");+ if (combinedChoose) {+ // Arrive on the capacity an installation already needs rather than on a blocked minimum,+ // the same seeding the separate walk does when a period is picked.+ if (sellsCapacity) {+ checkoutState.setServerQuantity(blocksForUsers(minimumCapacity));+ }+ navigation.goToStage("choose");+ } else {+ navigation.goToStage("plan-selection");+ }} else {checkoutState.setEmailError(validation.error);}};- // Only the Team tier is sold by capacity. Enterprise is priced per seat and free has nothing to- // size, so both go straight to payment.- const sellsCapacity = planGroup.tier === "server";-// Plan selection handlerconst handlePlanSelect = (period: "monthly" | "yearly") => {checkoutState.setSelectedPeriod(period);if (sellsCapacity) {// Arrive on the capacity an installation already needs rather than on a blocked minimum.- checkoutState.setServerQuantity(blocksForUsers(minimumSeats));+ checkoutState.setServerQuantity(blocksForUsers(minimumCapacity));navigation.goToStage("capacity");return;}@@ -175,6 +190,21 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({// Check for existing license to skip email stageconst checkExistingLicense = async () => {try {+ // A caller that already holds the email (a linked instance does, from the account link)+ // never needs to be asked for it, whatever the licence says.+ if (combinedChoose && sellsCapacity)+ checkoutState.setServerQuantity(blocksForUsers(minimumCapacity));+ if (initialEmail) {+ checkoutState.setEmailInput(initialEmail);+ checkoutState.setState((prev) => ({+ ...prev,+ email: initialEmail,+ currentStage: combinedChoose ? "choose" : "plan-selection",+ loading: false,+ }));+ return;+ }+const licenseInfo = await licenseService.getLicenseInfo();// Only skip email if license is PRO or ENTERPRISE (not NORMAL/free tier)if (licenseInfo?.licenseType && licenseInfo.licenseType !== "NORMAL") {@@ -182,7 +212,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({console.log("Valid premium license detected - skipping email stage");checkoutState.setCurrentLicenseKey(licenseInfo.licenseKey || null);checkoutState.setState({- currentStage: "plan-selection",+ currentStage: combinedChoose ? "choose" : "plan-selection",loading: false,});} else {@@ -200,6 +230,12 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({}, [opened,hostedCheckoutSuccess,+ initialEmail,+ combinedChoose,+ sellsCapacity,+ minimumCapacity,+ checkoutState.setServerQuantity,+ checkoutState.setEmailInput,checkoutState.setCurrentLicenseKey,checkoutState.setPollingStatus,checkoutState.setLicenseKey,@@ -237,6 +273,41 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({/>);+ // Page 1 of 2: both choices at once, which is how the design puts them in front of a buyer.+ // 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")}+ />+ )}+ </>+ );+case "plan-selection":return (<PlanSelectionStage@@ -254,6 +325,7 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({serverQuantity={checkoutState.serverQuantity}setServerQuantity={checkoutState.setServerQuantity}currentUsers={minimumSeats}+ currentLimit={currentLimit}onContinue={() => navigation.goToStage("payment")}/>);@@ -291,32 +363,55 @@ 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 email+ // page only when the caller supplied no address. 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+ ? [+ ...(initialEmail || checkoutState.currentLicenseKey+ ? []+ : (["email"] as CheckoutStage[])),+ "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={- <Group gap="sm" wrap="nowrap">- {canGoBack && (- <ActionIcon- variant="tertiary"- size="lg"- 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>+ 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>+ )}size={isMobile ? "100%" : 980}centeredradius="lg"- withCloseButton={true}+ withCloseButton={!steppedStep}closeOnEscape={true}closeOnClickOutside={false}fullScreen={isMobile}@@ -328,6 +423,44 @@ const StripeCheckout: React.FC<StripeCheckoutProps> = ({},}}>+ {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.tsxnew file mode 100644index 0000000000..bcec8e3ab9--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.test.tsx@@ -0,0 +1,25 @@+import { MantineProvider } from "@mantine/core";+import { render, screen } from "@testing-library/react";+import { expect, it, vi } from "vitest";+import { CapacityStage } from "@app/components/shared/stripeCheckout/stages/CapacityStage";+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));+it("blocks purchasing less than the existing allowance even when usage is lower", () => {+ render(+ <MantineProvider>+ <CapacityStage+ selectedPlan={null}+ serverQuantity={1}+ setServerQuantity={() => {}}+ currentUsers={40}+ currentLimit={300}+ onContinue={() => {}}+ />+ </MantineProvider>,+ );+ expect(screen.getByRole("button", { name: "100" })).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Continue to payment" }),+ ).toBeDisabled();+});diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsxindex 4cd131b3f9..8de942229e 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/CapacityStage.tsx@@ -24,6 +24,12 @@ interface CapacityStageProps {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.+ */+ currentLimit?: number | null;onContinue: () => void;onContactSales?: () => void;}@@ -40,6 +46,7 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({serverQuantity,setServerQuantity,currentUsers = 0,+ currentLimit = null,onContinue,onContactSales,}) => {@@ -51,12 +58,11 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({const covered = usersForBlocks(serverQuantity);const total = blockPrice * serverQuantity;- // Never sell less capacity than is already in use; reducing capacity happens at renewal rather- // than by stranding accounts that already exist. The stage is entered pre-seeded to this minimum.- const minBlocks = blocksForUsers(currentUsers);+ // Adding capacity cannot reduce the purchased allowance or strand existing users.+ const minBlocks = blocksForUsers(Math.max(currentUsers, currentLimit ?? 0));const minUsers = usersForBlocks(minBlocks);const maxUsers = usersForBlocks(SELF_SERVE_MAX_BLOCKS);- const belowCurrentUsage = serverQuantity < minBlocks;+ const belowMinimumCapacity = serverQuantity < minBlocks;const offerEnterprise = shouldOfferEnterprise(serverQuantity);const presets = USER_PRESETS.filter((users) => users <= maxUsers);@@ -74,11 +80,17 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({return (<Stack gap="lg" style={{ padding: "1.5rem 2rem" }}><Text size="sm" c="dimmed">- {t(- "payment.capacityStage.subheading",- "Covers everyone you invite, in blocks of {{users}} users.",- { users: USERS_PER_BLOCK },- )}+ {currentLimit != null+ ? t(+ "payment.capacityStage.subheadingAdd",+ "Your plan covers {{current}} users today. Choose the new total.",+ { current: currentLimit },+ )+ : t(+ "payment.capacityStage.subheading",+ "Covers everyone you invite, in blocks of {{users}} users.",+ { users: USERS_PER_BLOCK },+ )}</Text><Group gap="sm" wrap="wrap" align="center">@@ -126,7 +138,7 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({/>)}- {belowCurrentUsage && (+ {belowMinimumCapacity && (<Alert color="yellow" variant="light">{t("payment.capacityStage.minimumForCurrentUsers",@@ -152,9 +164,13 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({)}</Text><Text size="sm" fw={500}>- {t("payment.capacityStage.userTotal", "{{users}} users", {- users: covered,- })}+ {currentLimit != null+ ? t("payment.capacityStage.userDelta", "+{{users}} users", {+ users: Math.max(0, covered - currentLimit),+ })+ : t("payment.capacityStage.userTotal", "{{users}} users", {+ users: covered,+ })}</Text></Group><Group justify="space-between" align="baseline">@@ -175,7 +191,7 @@ export const CapacityStage: React.FC<CapacityStageProps> = ({</Stack><Stack gap="sm">- <Button onClick={onContinue} disabled={belowCurrentUsage} fullWidth>+ <Button onClick={onContinue} disabled={belowMinimumCapacity} fullWidth>{t("payment.capacityStage.continue", "Continue to payment")}</Button>diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsxindex d74afc4d99..e14e90e6ee 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/stages/PlanSelectionStage.tsx@@ -18,6 +18,12 @@ interface PlanSelectionStageProps {minimumSeats: number;savings: SavingsCalculation | null;onSelectPlan: (period: "monthly" | "yearly") => void;+ /**+ * The period currently chosen. Supplied when these cards share a page with another control, so+ * picking one is a selection the buyer can see rather than a step that navigates away. Absent,+ * neither card claims to be chosen: both buttons stay secondary.+ */+ selectedPeriod?: "monthly" | "yearly";}export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({@@ -25,6 +31,7 @@ export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({minimumSeats,savings,onSelectPlan,+ selectedPeriod,}) => {const { t } = useTranslation();const isEnterprise = planGroup.tier === "enterprise";@@ -40,7 +47,7 @@ export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({withBorderp="xl"radius="md"- style={getClickablePaperStyle()}+ style={getClickablePaperStyle(selectedPeriod === "monthly")}onClick={() => onSelectPlan("monthly")}><Stack@@ -80,8 +87,15 @@ export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({)}<div style={{ marginTop: "auto", paddingTop: "1rem" }}>- <Button variant="secondary" fullWidth>- {t("payment.planStage.selectMonthly", "Select Monthly")}+ <Button+ variant={+ selectedPeriod === "monthly" ? "primary" : "secondary"+ }+ fullWidth+ >+ {selectedPeriod === "monthly"+ ? t("payment.planStage.selectedMonthly", "Monthly")+ : t("payment.planStage.selectMonthly", "Select Monthly")}</Button></div></Stack>@@ -96,7 +110,9 @@ export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({withBorderp="xl"radius="md"- style={getClickablePaperStyle(!!savings)}+ style={getClickablePaperStyle(+ selectedPeriod ? selectedPeriod === "yearly" : !!savings,+ )}onClick={() => onSelectPlan("yearly")}>{savings && (@@ -193,8 +209,15 @@ export const PlanSelectionStage: React.FC<PlanSelectionStageProps> = ({)}<div style={{ marginTop: "auto", paddingTop: "1rem" }}>- <Button fullWidth>- {t("payment.planStage.selectYearly", "Select Yearly")}+ <Button+ variant={+ selectedPeriod === "yearly" ? "primary" : "secondary"+ }+ fullWidth+ >+ {selectedPeriod === "yearly"+ ? t("payment.planStage.selectedYearly", "Yearly")+ : t("payment.planStage.selectYearly", "Select Yearly")}</Button></div></Stack>diff --git a/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts b/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.tsindex 5120b7da10..f6bd2ec480 100644--- a/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts+++ b/frontend/editor/src/proprietary/components/shared/stripeCheckout/types/checkout.ts@@ -1,6 +1,16 @@import { PlanTierGroup } from "@app/services/licenseService";export interface StripeCheckoutProps {+ /** Supplying it skips the email step. */+ initialEmail?: string;+ /**+ * Put the period and capacity choices on one page instead of walking them separately. Independent+ * of {@link initialEmail}: a buyer who still has to type an address gets the email page in front+ * of the combined one rather than the long walk behind it. Ignored for tiers that do not sell capacity.+ */+ combinedChoose?: boolean;+ /** Users the current plan covers, or null when there is none. Drives the add-capacity face. */+ currentLimit?: number | null;opened: boolean;onClose: () => void;planGroup: PlanTierGroup;@@ -21,6 +31,11 @@ export interface StripeCheckoutProps {export type CheckoutStage =| "email"+ /**+ * Billing period and capacity on one page. The separate {@code plan-selection} and {@code+ * capacity} stages remain for the flows that still walk them one at a time.+ */+ | "choose"| "plan-selection"| "capacity"| "payment"diff --git a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsxindex e050114bee..d489d48797 100644--- a/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx+++ b/frontend/editor/src/proprietary/contexts/CheckoutContext.tsx@@ -41,6 +41,17 @@ export interface CheckoutOptions {currency?: string; // Optional currency override (auto-detected from locale)onSuccess?: (sessionId: string) => void; // Callback after successful paymentonError?: (error: string) => void; // Callback on error+ /**+ * Supplying it skips the email step. No caller does today: the only address a self-hosted+ * instance holds is its Spring username. #7945 removes the step instead, by buying as the+ * signed-in account.+ */+ email?: string;+ /** Put the period and capacity choices on one page rather than walking them separately. */+ combinedChoose?: boolean;+ /** 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;}interface CheckoutContextValue {@@ -446,6 +457,9 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({onClose={closeCheckout}planGroup={selectedPlanGroup}minimumSeats={minimumSeats}+ initialEmail={currentOptions.email}+ combinedChoose={currentOptions.combinedChoose}+ currentLimit={currentOptions.currentLimit ?? null}onSuccess={handlePaymentSuccess}onError={handlePaymentError}onLicenseActivated={handleLicenseActivated}@@ -457,6 +471,14 @@ export const CheckoutProvider: React.FC<CheckoutProviderProps> = ({);};+/**+ * The checkout, or null where no provider is mounted. A build may mount none, and a hard {@link+ * useCheckout} would turn that into a blank page instead of a missing door.+ */+export const useCheckoutOptional = (): CheckoutContextValue | null => {+ return useContext(CheckoutContext) ?? null;+};+export const useCheckout = (): CheckoutContextValue => {const context = useContext(CheckoutContext);if (!context) {diff --git a/frontend/editor/src/saas/components/shared/FreeLimitReachedModal.test.tsx b/frontend/editor/src/saas/components/shared/FreeLimitReachedModal.test.tsxindex b30d4aefbb..eeb51468cd 100644--- a/frontend/editor/src/saas/components/shared/FreeLimitReachedModal.test.tsx+++ b/frontend/editor/src/saas/components/shared/FreeLimitReachedModal.test.tsx@@ -19,6 +19,7 @@ const wallet: Wallet = {billingPeriodEnd: "2026-06-30",billableUsed: 500,billableLimit: 500,+ freeUserAllowance: 5,freeAllowance: 500,freeRemaining: 0,pricePerDocMinor: 2,diff --git a/frontend/editor/src/saas/hooks/walletDevPreview.ts b/frontend/editor/src/saas/hooks/walletDevPreview.tsindex 98e0ce0aa3..1104d6b36c 100644--- a/frontend/editor/src/saas/hooks/walletDevPreview.ts+++ b/frontend/editor/src/saas/hooks/walletDevPreview.ts@@ -54,6 +54,7 @@ function buildDevPreviewWallet(role: WalletRole): Wallet {billingPeriodEnd: isoDay(periodEnd),billableUsed: 62,billableLimit: subscribed ? 1250 : 500,+ freeUserAllowance: 5,freeAllowance: 500,// One-time grant: a free team has used 62 of 500 (438 left); the dev// subscribed team is shown with its grant fully spent (kept across the