#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
Enterprise procurement page (#8771)
Reece Browne0318fd358bc6
diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalController.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalController.javaindex 88b37da5ea..e53b3cc49e 100644--- a/app/saas/src/main/java/stirling/software/saas/legal/LegalController.java+++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalController.java@@ -1,6 +1,7 @@package stirling.software.saas.legal;import java.util.Optional;+import java.util.Set;import org.springframework.context.annotation.Profile;import org.springframework.http.ResponseEntity;@@ -55,10 +56,23 @@ public class LegalController {public record ConsentRequest(String documentId, String context) {}- /** Fetch a legal document's current version as markdown. 404 for an unknown document. */+ /**+ * The documents a visitor may read before signing in. The enterprise agreement is not one: it+ * is served with its deal through the procurement controller.+ */+ private static final Set<String> PUBLIC_DOCUMENT_IDS = Set.of("eula", "sla", "subprocessors");++ /**+ * Fetch a legal document's current version as markdown. 404 for an unknown document. Public:+ * visitors are asked to agree to these before they have an account, so they must be able to+ * read them first.+ */@GetMapping("/{docId}")- @PreAuthorize("isAuthenticated()")+ @PreAuthorize("permitAll()")public ResponseEntity<LegalDocumentResponse> document(@PathVariable String docId) {+ if (!PUBLIC_DOCUMENT_IDS.contains(docId)) {+ return ResponseEntity.notFound().build();+ }return registry.meta(docId).<ResponseEntity<LegalDocumentResponse>>map(meta ->diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java b/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.javaindex ae35e53d39..5fc7d5c787 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java@@ -1,6 +1,7 @@package stirling.software.saas.procurement.api;import java.util.List;+import java.util.Map;import java.util.Objects;import java.util.Optional;@@ -32,9 +33,11 @@ import stirling.software.saas.procurement.model.ProcurementAgreementSignature;import stirling.software.saas.procurement.model.ProcurementDeal;import stirling.software.saas.procurement.model.ProcurementQuote;import stirling.software.saas.procurement.model.QuoteDetails;+import stirling.software.saas.procurement.pricing.PricingRates;import stirling.software.saas.procurement.pricing.ProcurementPricingService;import stirling.software.saas.procurement.pricing.QuoteConfig;import stirling.software.saas.procurement.pricing.QuoteLineItem;+import stirling.software.saas.procurement.service.BelowMinimumDealException;import stirling.software.saas.procurement.service.ProcurementService;import stirling.software.saas.procurement.service.ProcurementService.ContractPeriod;import stirling.software.saas.security.UserTeamResolver;@@ -60,6 +63,9 @@ public class ProcurementController {// ObjectMapper bean.private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();+ /** Error code for a quote under the minimum deal size; the builder keys on it. */+ static final String QUOTE_BELOW_MINIMUM = "quote_below_minimum";+private final ProcurementService procurement;private final ProcurementPricingService pricing;private final UserTeamResolver userTeamResolver;@@ -154,8 +160,7 @@ public class ProcurementController {/*** The inputs the quote was priced from, echoed back so the builder can seed itself when the- * buyer re-edits an existing quote. {@code users} is not persisted (only the resulting volume- * is), so it is always 0 here; the builder treats the seeded volume as manually set.+ * buyer re-edits an existing quote. {@code users} is the licensed seat count, 0 when unset.*/public record QuoteConfigEcho(long volume,@@ -209,7 +214,42 @@ public class ProcurementController {String businessName,String contactName,String contactEmail,- QuoteResponse latestQuote) {}+ QuoteResponse latestQuote,+ // Smallest annual fee a quote may come to (minor units), so the builder can say so+ // before the buyer prices one; 0 when there is no floor.+ long minAnnualNetMinor,+ // The deployment the licence is issued for: the current quote's once one exists, else+ // the trial's. Setup steps and the offline licence follow this, not {@code deployment}.+ String entitledDeployment,+ // The rates quotes are priced from, so the builder's live estimate uses the same ones.+ PricingRates rateCard,+ // How many times the trial may be extended, so the page can say when it can't be.+ int maxTrialExtensions) {++ /** The snapshot of a team with no deal yet. */+ static SnapshotResponse empty(+ long minAnnualNetMinor, PricingRates rateCard, int maxTrialExtensions) {+ return new SnapshotResponse(+ null,+ null,+ null,+ 0,+ null,+ null,+ 0,+ false,+ null,+ null,+ null,+ null,+ null,+ null,+ minAnnualNetMinor,+ null,+ rateCard,+ maxTrialExtensions);+ }+ }/** The filled agreement for review: registry metadata + the rendered markdown body. */public record AgreementDocumentResponse(@@ -248,12 +288,16 @@ public class ProcurementController {// journey (stage, trial, quote) but the key is withheld; the .lic file is likewise gated.boolean leader = userTeamResolver.isLeader(caller.get());return ResponseEntity.ok(- procurement.getDeal(teamId).map(d -> toSnapshot(d, leader)).orElse(EMPTY_SNAPSHOT));+ procurement+ .getDeal(teamId)+ .map(d -> toSnapshot(d, leader))+ .orElseGet(this::emptySnapshot));}- private static final SnapshotResponse EMPTY_SNAPSHOT =- new SnapshotResponse(- null, null, null, 0, null, null, 0, false, null, null, null, null, null, null);+ private SnapshotResponse emptySnapshot() {+ return SnapshotResponse.empty(+ config.getMinAnnualNetMinor(), pricing.rates(), config.getMaxTrialExtensions());+ }/*** Download the offline / air-gapped licence file (.lic) for the team — available for an@@ -359,8 +403,7 @@ public class ProcurementController {@PostMapping("/quote")@PreAuthorize("isAuthenticated()")- public ResponseEntity<QuoteResponse> buildQuote(- @RequestBody QuoteRequest request, Authentication auth) {+ public ResponseEntity<?> buildQuote(@RequestBody QuoteRequest request, Authentication auth) {Long teamId = requireLeader(auth);if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();try {@@ -368,8 +411,14 @@ public class ProcurementController {toQuote(procurement.buildQuote(teamId, request.toConfig(), request.toDetails())));+ } catch (BelowMinimumDealException e) {+ // Named in the body so the builder can say the quote is too small, as opposed to the+ // deal having moved on (below).+ log.warn("[procurement] quote below minimum team={}: {}", teamId, e.getMessage());+ return ResponseEntity.status(HttpStatus.CONFLICT)+ .body(Map.of("error", QUOTE_BELOW_MINIMUM));} catch (IllegalStateException e) {- // Below the minimum deal size, or the deal is already live. A client error, not a+ // The deal is already past quoting (e.g. accepted elsewhere). A client error, not a// fault.log.warn("[procurement] quote rejected team={}: {}", teamId, e.getMessage());return ResponseEntity.status(HttpStatus.CONFLICT).build();@@ -567,7 +616,7 @@ public class ProcurementController {Long teamId = requireLeader(auth);if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build();procurement.resetDeal(teamId);- return ResponseEntity.ok(EMPTY_SNAPSHOT);+ return ResponseEntity.ok(emptySnapshot());}// ---- helpers ------------------------------------------------------------@@ -610,11 +659,8 @@ public class ProcurementController {* endpoints are leader-gated, so they always pass true.*/private SnapshotResponse toSnapshot(ProcurementDeal deal, boolean includeLicenseKey) {- QuoteResponse latest =- procurement.quotesForDeal(deal.getDealId()).stream()- .findFirst()- .map(this::toQuote)- .orElse(null);+ List<ProcurementQuote> quotes = procurement.quotesForDeal(deal.getDealId());+ QuoteResponse latest = quotes.stream().findFirst().map(this::toQuote).orElse(null);return new SnapshotResponse(deal.getDealId(),deal.getStage(),@@ -629,7 +675,11 @@ public class ProcurementController {deal.getBusinessName(),deal.getContactName(),deal.getContactEmail(),- latest);+ latest,+ config.getMinAnnualNetMinor(),+ procurement.entitledDeployment(deal, quotes),+ pricing.rates(),+ config.getMaxTrialExtensions());}private QuoteResponse toQuote(ProcurementQuote q) {diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/pricing/PricingRates.java b/app/saas/src/main/java/stirling/software/saas/procurement/pricing/PricingRates.javaindex 61dc5f499a..70214b4b0b 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/pricing/PricingRates.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/pricing/PricingRates.java@@ -14,7 +14,9 @@ package stirling.software.saas.procurement.pricing;public record PricingRates(double listRatePerRun, // $0.01 list per rundouble floorRatePerRun, // $0.005 asymptotic floor (cost + margin)- double discountPerDoubling, // 0.06 = 6% off the per-run rate per doubling past 1M runs/yr+ long runCurveKnee, // committed runs/yr past which the per-run rate starts to fall+ double discountPerDoubling, // 0.06 = 6% off the per-run rate per doubling past the knee+ double maxVolumeDiscount, // the most the curve takes off the list ratedouble[] termDiscountByYear, // meter-only discount; index 0 = 1yr … index 4 = 5yrdouble indemnificationRate, // fraction of the net meter (legal exposure scales with usage)long dedicatedSupportMinor, // flat: dedicated SE/CSM (standard + priority are included)@@ -28,7 +30,9 @@ public record PricingRates(return new PricingRates(0.01, // $0.01 / run list0.005, // $0.005 / run floor- 0.06, // 6% off per doubling of committed runs past 1M/yr+ 1_000_000L, // the curve starts past 1M committed runs/yr+ 0.06, // 6% off per doubling of committed runs past the knee+ 0.5, // never more than half off the list ratenew double[] {0.0, 0.03, 0.05, 0.06, 0.07}, // 1–5 year term, meter only0.05, // IP indemnification = 5% of the net meter3_000_000, // dedicated SE/CSM $30,000 / yrdiff --git a/app/saas/src/main/java/stirling/software/saas/procurement/pricing/ProcurementPricingService.java b/app/saas/src/main/java/stirling/software/saas/procurement/pricing/ProcurementPricingService.javaindex 073e84ccc7..db1d2958ca 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/pricing/ProcurementPricingService.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/pricing/ProcurementPricingService.java@@ -29,7 +29,6 @@ import org.springframework.stereotype.Service;public class ProcurementPricingService {private static final double LOG2 = Math.log(2.0);- private static final long RUN_CURVE_KNEE = 1_000_000L; // discount starts past 1M committed runs/*** Estimated annual PDF volume from seat count (~2,012.5 PDFs/user/yr = 5 docs/day x 230 working@@ -40,8 +39,16 @@ public class ProcurementPricingService {return Math.round(Math.max(0, users) * 5.0 * 230.0 * 1.75);}+ /**+ * The rate card quotes are priced from. Also sent to the quote builder, which runs the same+ * formula over it for its live estimate, so its figures can't drift from these rates.+ */+ public PricingRates rates() {+ return PricingRates.defaults();+ }+public QuoteBreakdown price(QuoteConfig cfg) {- return price(cfg, PricingRates.defaults());+ return price(cfg, rates());}public QuoteBreakdown price(QuoteConfig cfg, PricingRates rates) {@@ -52,14 +59,6 @@ public class ProcurementPricingService {int intensity = Math.max(1, cfg.intensity());long runVol = volume * (long) intensity;- // Committed-volume curve: continuous, no cliffs. Floors at the per-run cost + margin.- double volDisc =- runVol > RUN_CURVE_KNEE- ? Math.min(- 0.5,- rates.discountPerDoubling()- * (Math.log(runVol / (double) RUN_CURVE_KNEE) / LOG2))- : 0.0;double rate = perRunRate(cfg, rates);double termDisc = rates.termDiscount(cfg.termYears());@@ -165,12 +164,14 @@ public class ProcurementPricingService {*/private static double perRunRate(QuoteConfig cfg, PricingRates rates) {long runVol = Math.max(0, cfg.volume()) * (long) Math.max(1, cfg.intensity());+ // Committed-volume curve: continuous, no cliffs. Floors at the per-run cost + margin.+ long knee = rates.runCurveKnee();double volDisc =- runVol > RUN_CURVE_KNEE+ runVol > knee? Math.min(- 0.5,+ rates.maxVolumeDiscount(),rates.discountPerDoubling()- * (Math.log(runVol / (double) RUN_CURVE_KNEE) / LOG2))+ * (Math.log(runVol / (double) knee) / LOG2)): 0.0;return Math.max(rates.floorRatePerRun(), rates.listRatePerRun() * (1.0 - volDisc))* cfg.sizeMult();diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/service/BelowMinimumDealException.java b/app/saas/src/main/java/stirling/software/saas/procurement/service/BelowMinimumDealException.javanew file mode 100644index 0000000000..1d144ade87--- /dev/null+++ b/app/saas/src/main/java/stirling/software/saas/procurement/service/BelowMinimumDealException.java@@ -0,0 +1,12 @@+package stirling.software.saas.procurement.service;++/**+ * A quote priced under the minimum enterprise deal size. A distinct type so the API can tell the+ * buyer their quote is too small, rather than reporting it like any other conflicting state.+ */+public class BelowMinimumDealException extends IllegalStateException {++ public BelowMinimumDealException(String message) {+ super(message);+ }+}diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.javaindex 93df3c8e7e..31d9a67099 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java@@ -355,7 +355,7 @@ public class ProcurementService {// price a $0 enterprise quote, accept it, and be provisioned a committed licence.long floor = config.getMinAnnualNetMinor();if (floor > 0 && breakdown.annualNetMinor() < floor) {- throw new IllegalStateException(+ throw new BelowMinimumDealException("Quoted annual fee "+ breakdown.annualNetMinor()+ " is below the minimum enterprise deal size "@@ -781,7 +781,19 @@ public class ProcurementService {* otherwise the trial's self-selected target. Paid entitlements must follow what was quoted.*/private String entitledDeployment(ProcurementDeal deal) {- ProcurementQuote quote = currentQuote(deal.getTeamId()).orElse(null);+ return entitledDeployment(deal, quotesForDeal(deal.getDealId()));+ }++ /**+ * {@link #entitledDeployment(ProcurementDeal)} from the deal's quotes, newest first, for a+ * caller that already has them loaded.+ */+ public String entitledDeployment(ProcurementDeal deal, List<ProcurementQuote> quotes) {+ ProcurementQuote quote =+ quotes.stream()+ .filter(q -> q.getQuoteId().equals(deal.getAcceptedQuoteId()))+ .findFirst()+ .orElse(quotes.isEmpty() ? null : quotes.get(0));if (quote != null && quote.getDeployment() != null && !quote.getDeployment().isBlank()) {return quote.getDeployment();}diff --git a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.javaindex 9338b824c8..ce0064135a 100644--- a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java+++ b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java@@ -127,6 +127,10 @@ public class SupabaseSecurityConfig {"/api/v1/account-link/connect/request","/api/v1/account-link/connect/claim").permitAll()+ // Static legal documents, read before agreeing to them,+ // which can be before the reader has an account.+ .requestMatchers(HttpMethod.GET, "/api/v1/legal/*")+ .permitAll().requestMatchers(req ->RequestUriUtils.isStaticResource(diff --git a/app/saas/src/test/java/stirling/software/saas/legal/LegalControllerTest.java b/app/saas/src/test/java/stirling/software/saas/legal/LegalControllerTest.javanew file mode 100644index 0000000000..bb9a69d03e--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/legal/LegalControllerTest.java@@ -0,0 +1,43 @@+package stirling.software.saas.legal;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.Mockito.mock;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.springframework.http.HttpStatus;++import stirling.software.proprietary.security.database.repository.UserRepository;+import stirling.software.saas.security.UserTeamResolver;++class LegalControllerTest {++ private LegalController controller;++ @BeforeEach+ void setUp() throws Exception {+ LegalDocumentRegistry registry = new LegalDocumentRegistry();+ registry.load();+ controller =+ new LegalController(+ registry,+ mock(LegalConsentService.class),+ mock(UserTeamResolver.class),+ mock(UserRepository.class));+ }++ @Test+ void servesThePublicDocuments() {+ for (String id : new String[] {"eula", "sla", "subprocessors"}) {+ var response = controller.document(id);+ assertThat(response.getStatusCode()).as(id).isEqualTo(HttpStatus.OK);+ assertThat(response.getBody().markdown()).as(id).isNotBlank();+ }+ }++ @Test+ void doesNotServeTheEnterpriseAgreement() {+ assertThat(controller.document("enterprise-agreement").getStatusCode())+ .isEqualTo(HttpStatus.NOT_FOUND);+ }+}diff --git a/app/saas/src/test/java/stirling/software/saas/procurement/pricing/ProcurementPricingServiceTest.java b/app/saas/src/test/java/stirling/software/saas/procurement/pricing/ProcurementPricingServiceTest.javaindex e62c6ff00b..7b5f08510e 100644--- a/app/saas/src/test/java/stirling/software/saas/procurement/pricing/ProcurementPricingServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/procurement/pricing/ProcurementPricingServiceTest.java@@ -6,6 +6,9 @@ import org.junit.jupiter.api.Test;import stirling.software.saas.procurement.pricing.QuoteLineItem.Kind;+import tools.jackson.databind.JsonNode;+import tools.jackson.databind.ObjectMapper;+/*** Locks the D71 pricing engine to the numbers marketing publishes. The two anchor fixtures are the* ones the demo memo foots against: acme (90M PDFs · Governed · self-hosted · dedicated · 3-yr =@@ -191,4 +194,25 @@ class ProcurementPricingServiceTest {.findFirst().orElseThrow();}++ /**+ * The quote builder reads the rate card by these names (RateCard in the portal's procurement+ * API) and runs the same formula over it, so a rename here would break its live estimate.+ */+ @Test+ void rateCardSerializesUnderTheNamesTheBuilderReads() {+ JsonNode json = new ObjectMapper().valueToTree(pricing.rates());+ assertThat(json.get("listRatePerRun").asDouble()).isEqualTo(0.01);+ assertThat(json.get("floorRatePerRun").asDouble()).isEqualTo(0.005);+ assertThat(json.get("runCurveKnee").asLong()).isEqualTo(1_000_000L);+ assertThat(json.get("discountPerDoubling").asDouble()).isEqualTo(0.06);+ assertThat(json.get("maxVolumeDiscount").asDouble()).isEqualTo(0.5);+ assertThat(json.get("termDiscountByYear").size()).isEqualTo(5);+ assertThat(json.get("indemnificationRate").asDouble()).isEqualTo(0.05);+ assertThat(json.get("dedicatedSupportMinor").asLong()).isEqualTo(3_000_000L);+ assertThat(json.get("selfHostDeployMinor").asLong()).isEqualTo(1_200_000L);+ assertThat(json.get("airgapDeployMinor").asLong()).isEqualTo(3_600_000L);+ assertThat(json.get("qbrAnnualMinor").asLong()).isEqualTo(800_000L);+ assertThat(json.get("trainingOneTimeMinor").asLong()).isEqualTo(750_000L);+ }}diff --git a/frontend/.storybook/preview.tsx b/frontend/.storybook/preview.tsxindex daec5f121f..f42ce059ff 100644--- a/frontend/.storybook/preview.tsx+++ b/frontend/.storybook/preview.tsx@@ -16,8 +16,9 @@ void React;import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { TierProvider, type Tier } from "@processor/contexts/TierContext";import { LinkProvider, type LinkState } from "@processor/contexts/LinkContext";-import { ThemeProvider, useTheme } from "@processor/contexts/ThemeContext";+import { ThemeProvider } from "@processor/contexts/ThemeContext";import { UIProvider } from "@processor/contexts/UIContext";+import { AppConfigProvider } from "@editor-core/contexts/AppConfigContext";import { SuiProvider } from "@processor/theme/SuiProvider";import { MantineProvider } from "@mantine/core";import {@@ -160,23 +161,6 @@ function TierKey({);}-/**- * Makes the Storybook toolbar the SINGLE source of truth for the theme.- */-function ThemeBridge({- theme,- children,-}: {- theme: "light" | "dark";- children: React.ReactNode;-}) {- const { setTheme } = useTheme();- useEffect(() => {- setTheme(theme);- }, [theme, setTheme]);- return <>{children}</>;-}-/*** Sets the theme attributes colors.css needs — always `data-app-theme="custom"`* with the fixed default accent (data-accent="default"), matching the editor.@@ -261,10 +245,17 @@ const withProviders: Decorator = (Story, context) => {return (<MemoryRouter initialEntries={["/"]}><QueryClientProvider client={queryClient}>- <ThemeProvider>+ {/* Forced, not saved: the toolbar owns the theme, and one tab saving it would flip the others. */}+ <ThemeProvider forcedTheme={colorScheme}><SchemeSetup scheme={colorScheme} />- <ThemeBridge theme={colorScheme}>- <StoryTheme isPortalStory={isPortalStory} colorScheme={colorScheme}>+ <StoryTheme isPortalStory={isPortalStory} colorScheme={colorScheme}>+ {/* The app mounts this with the platform providers; without it the config never+ loads and anything waiting on it (the portal's connect gate) never settles.+ Seeded rather than fetched; a story can mount its own to vary it. */}+ <AppConfigProvider+ initialConfig={STORY_APP_CONFIG}+ autoFetch={false}+ >{/* LinkProvider must wrap TierProvider: TierContext derives its tierfrom useLink() (matches App.tsx's nesting). */}<LinkProvider key={linkState} initialState={linkState}>@@ -282,14 +273,17 @@ const withProviders: Decorator = (Story, context) => {</UIProvider></TierKey></LinkProvider>- </StoryTheme>- </ThemeBridge>+ </AppConfigProvider>+ </StoryTheme></ThemeProvider></QueryClientProvider></MemoryRouter>);};+/** Matches the mocked /api/v1/config/app-config, which the portal's views were written against. */+const STORY_APP_CONFIG = { aiEngineEnabled: true };+const preview: Preview = {loaders: [mswLoader],// The scan runs once per theme (SCAN_THEME=light|dark, forwarded bydiff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex e299821b4e..b839c740ea 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -90,6 +90,7 @@"web-vitals": "^5.1.0"},"devDependencies": {+ "@mswjs/interceptors": "^0.41.9","@playwright/test": "^1.55.0","@storybook/addon-a11y": "^9.1.20","@storybook/addon-docs": "^9.1.20",diff --git a/frontend/package.json b/frontend/package.jsonindex d41bfcf2b7..3fffc9325a 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -112,6 +112,7 @@]},"devDependencies": {+ "@mswjs/interceptors": "^0.41.9","@playwright/test": "^1.55.0","@storybook/addon-a11y": "^9.1.20","@storybook/addon-docs": "^9.1.20",diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.tomlindex b44ab16c0a..c044ee6aa9 100644--- a/frontend/public/locales/en-US/translation.toml+++ b/frontend/public/locales/en-US/translation.toml@@ -9200,6 +9200,139 @@ status = "Status"time = "Time"user = "User"+[portal.enterprise]+backTo = "Back to {{stage}}"+brandTag = "Enterprise"+callInfo = "A 15-minute call. Bring your questions on pricing, deployment or security, or plan your rollout together."+callTitle = "Talk to a solutions engineer"+deployment = "Deployment"+footer = "Questions about Stirling Enterprise?"+home = "Go to Stirling"+member = "Your team leader runs the Enterprise deal. Once it starts, you can follow its progress here."+memberDeal = "Your team leader runs this deal. You can follow its progress here."+quotePanel = "Your quote"+signIn = "Sign in"+signInToStart = "Sign in to start your trial"+stage = "Stage {{current}} of {{total}}"+stagesLabel = "Progress"++[portal.enterprise.connect]+ownerOnly = "Only this server’s owner can connect it. Ask them to open this page."+unavailable = "Connecting to a Stirling account is turned off on this server. Book a call and we’ll set up your trial with you."++[portal.enterprise.landing]+lede = "Try it free for 14 days, then build your quote and sign your agreement here. No card required."+tickAgreement = "One agreement covering the MSA, order form, EULA and DPA"+tickCompliance = "SCIM, data residency and uptime SLAs"+tickDeploy = "Run it on Stirling Cloud, your own servers, or fully air-gapped"+title = "Stirling Enterprise"++[portal.enterprise.options]+label = "Ways to run it"+next = "Next"+previous = "Previous"+slideOf = "{{n}} of {{total}}"++[portal.enterprise.options.airgap]+more = "Offline licence docs"+point1 = "Activated with a licence file that works offline, not a key checked online"+point2 = "Installs like self-hosted, from an image you bring across"+point3 = "Sign-in stays inside your network"+tagline = "Self-hosted on a network with no internet access."+title = "Air-gapped"++[portal.enterprise.options.cloud]+more = "Stirling Cloud docs"+point1 = "Your team signs in at stirling.com/app"+point2 = "Runs on AWS, with stored files encrypted at rest"+point3 = "Single sign-on through your own identity provider needs self-hosting"+tagline = "Hosted for you, with nothing to install."+title = "Stirling Cloud"++[portal.enterprise.options.selfhost]+more = "Self-hosting docs"+point1 = "Install with Docker, or the Helm chart on Kubernetes"+point2 = "Documents are processed on your own infrastructure"+point3 = "OAuth2, OIDC or SAML single sign-on"+tagline = "On your own servers, on-premises or in your own cloud."+title = "Self-hosted"++[portal.enterprise.review]+back = "Return to {{stage}}"+company = "Company"+completed = "Completed"+extensions = "Extensions used"+paid = "Paid. Your invoice stays available here."+people = "People"+started = "Started"+trialEnds = "Trial end date"+trialTitle = "Your trial"+version = "Version"+viewInvoice = "View invoice"++[portal.enterprise.setup]+copied = "Copied"+copy = "Copy"+markDone = "Mark “{{step}}” done"+progress = "{{done}} of {{total}} done"+subtitle = "Make the most of your trial by trying it the way you'll run it."+subtitleLive = "The steps to finish before you roll out to everyone."+title = "Get set up"+titleLive = "Go-live checklist"++[portal.enterprise.setup.firstDocument]+body = "Upload a PDF your team works with and try the tools you'd use day to day, such as redact, compress or OCR."+title = "Run your first document"++[portal.enterprise.setup.getApp]+body = "Install the desktop app for Windows, Mac or Linux and sign in with the account you just made, or use it straight from your browser."+title = "Get Stirling"++[portal.enterprise.setup.install]+body = "Run this on your server. It starts Stirling with your licence applied, and the image includes OCR and office conversion. For larger teams, use Kubernetes."+title = "Install and start Stirling"++[portal.enterprise.setup.invite]+body = "Bring in the people who'll use it, so the trial reflects real work."+title = "Invite your team"++[portal.enterprise.setup.licence]+body = "Open http://your-server:8080/settings/adminPlan, where your Enterprise licence should show as active. Installed another way? Add the key under premium.key in settings.yml and restart."+title = "Check your licence is active"++[portal.enterprise.setup.links]+browser = "Use it in your browser"+docker = "Docker guide"+download = "Download the app"+downloadForTeam = "Get the app for your team"+downloading = "Downloading..."+downloadLicence = "Download licence file"+invite = "Invite teammates"+kubernetes = "Kubernetes guide"+licence = "Licence activation"+ocr = "OCR languages"+openApp = "Open Stirling"+samlGuide = "SAML guide"+ssoGuide = "SSO guide"++[portal.enterprise.setup.offlineInstall]+body = "Pull the full image on a connected machine, carry it and the licence file across, then load and start it. The full image adds the fonts an offline server can't download."+title = "Bring Stirling across and start it"++[portal.enterprise.setup.offlineLicence]+body = "An air-gapped server can't reach our licence service, so it checks this signed file instead. Keep it with the image you carry across."+title = "Download your offline licence"++[portal.enterprise.setup.people]+bodyAirgap = "Create accounts at /settings/people, or point Stirling at your internal identity provider so sign-in never leaves your network."+bodySelfHosted = "Create accounts at /settings/people, or connect your identity provider so your team signs in with their work accounts. They use Stirling in the browser at your server's address, or in the desktop app pointed at it."+title = "Add your people"++[portal.enterprise.setup.signIn]+body = "Open http://your-server:8080 and sign in with admin / stirling. You'll be asked to choose a new password straight away."+bodyAirgap = "Open http://your-server:8080 and sign in with admin / stirling, choose a new password, then check /settings/adminPlan shows your licence as active."+title = "Sign in as the admin"+[portal.errorBoundary]description = "This view hit an unexpected error. Try again, or pick another section from the sidebar."retry = "Try again"@@ -9351,6 +9484,7 @@ title = "Nothing to review"[portal.home.download]back = "Back"body = "Download the desktop app or self-host the server."+bodyDesktop = "Download the desktop app, then sign in with your Stirling account."done = "Done"guide = "Open the {{name}} guide"openInBrowser = "Open in browser instead"@@ -10500,7 +10634,6 @@ cloud = "Drive · Box · S3"email = "Email intake"[portal.procurement]-subtitle = "Get your team evaluated, contracted, and onboarded. Every document in one place."title = "Procurement"[portal.procurement.agreement]@@ -10518,7 +10651,6 @@ loadError = "Could not load the agreement. Please try again."loading = "Loading the agreement..."ref = "Ref {{ref}} · {{version}}"requestChanges = "Request changes"-scrollHint = "Scroll to review"signatory = "Signatory name"signatoryPlaceholder = "Full name"signatoryTitle = "Signatory title"@@ -10526,32 +10658,42 @@ signatoryTitlePlaceholder = "e.g. General Counsel"signError = "Could not record your signature. Please try again."[portal.procurement.builder]+addonOneTime = "{{amount}} one-time"+addonPerYear = "+{{amount}}/yr"addons = "Add-ons"addressLine1 = "Address line 1"addressLine1Placeholder = "500 Howard St"addressLine2 = "Address line 2"addressLine2Placeholder = "Suite, floor, building"back = "Back"+belowMinimum = "This quote is below the minimum size for an Enterprise deal."businessName = "Business name"businessNamePlaceholder = "Your company"city = "City"cityPlaceholder = "San Francisco"completeRequired = "Please complete the required fields (marked *) with a valid email before generating the quote."+conflict = "This deal has changed since you opened it. Close the builder and reload the page to see where it stands."contactEmail = "Contact email"contactEmailPlaceholder = "[email protected]"contactName = "Contact name"contactNamePlaceholder = "Jane Doe"continue = "Continue"done = "Done"+editUsage = "Edit usage"eula = "I have read and agree to the Stirling Enterprise EULA. It governs the agreement generated from this quote."generate = "Generate quote"indemnification = "Enhanced IP Protection"indemnificationSub = "Extends our IP defense to patent claims. Baseline copyright, trademark and trade-secret indemnification is included free."+minimum = "Enterprise requires a minimum yearly spend of {{min}}."+minimumBelow = "This quote comes to {{annual}} a year. If you expect to use more, raise your estimated usage; otherwise the Team plan is likely a better fit."+minimumNear = "Enterprise requires a minimum yearly spend of {{min}}. Raise your estimated usage to reach it, or talk it through with us."+minimumNearTitle = "You're {{gap}} a year short of Enterprise."+paperBrand = "Stirling PDF"paperEyebrow = "Enterprise quote"paperFor = "Prepared for"pdfSize = "PDF size"poNumber = "PO number"-poNumberPlaceholder = "Optional"+poNumberPlaceholder = "e.g. PO-10042"postalCode = "Postal code"postalCodePlaceholder = "94105"posture = "Governance"@@ -10564,9 +10706,13 @@ posture_regulated = "Regulated"posture_regulatedSub = "Every category — Compliance, Retention, Ingestion"qbr = "Quarterly business reviews"qbrSub = "Your SE reviews usage and roadmap each quarter"+raiseUsage = "Raise estimated usage"region = "State / region"regionPlaceholder = "California"-running = "{{annual}} / yr · {{years}}-yr {{tcv}}"+runningLabel = "Estimated price"+runningLabelIssued = "Quoted price"+runningOneYear = "{{annual}} a year"+runningTotal = "{{tcv}} total over {{years}} years"s1Sub = "Your team, and the PDFs you expect to run each year."s1Title = "How much will you process?"s2Sub = "Longer terms discount the rate; your service level sets support."@@ -10588,7 +10734,7 @@ slStandard = "Standard"slStandardSub = "Next business day · shared CSM · included"stepOf = "Step {{n}} of {{total}}"taxId = "VAT / Tax ID"-taxIdPlaceholder = "Optional"+taxIdPlaceholder = "e.g. GB123456789"term = "Term"termDiscount = "{{pct}}% multi-year commitment discount applied"title = "Build your quote"@@ -10605,6 +10751,19 @@ volumePlaceholder = "e.g. 1,000,000"years_one = "{{count}} year"years_other = "{{count}} years"+[portal.procurement.builder.line]+deployment = "{{deployment}} deployment"+indemnification = "IP indemnification"+multiYear_one = "{{count}}-year commitment"+multiYear_other = "{{count}}-year commitment"+qbr = "Quarterly business reviews"+seats_one = "{{users}} agreed user + SSO / RBAC / audit"+seats_other = "{{users}} agreed users + SSO / RBAC / audit"+seatsUnset = "Users + SSO / RBAC / audit"+support = "Dedicated SE / CSM"+training = "Onboarding & training"+usage = "PDF processing — {{volume}} PDFs/yr at {{rate}}/PDF ({{posture}} posture)"+[portal.procurement.documents]agreement = "Enterprise Agreement"agreementSub = "MSA, Order Form and DPA in one signature."@@ -10615,6 +10774,8 @@ invoice = "Invoice"invoiceSub = "Your first subscription invoice."laterInvoice = "Available after you accept"laterQuote = "Available once your quote is issued"+laterSigning = "Available once the agreement is signed"+laterTitle = "Later in your deal"quote = "Quote"quoteSub = "Your itemised enterprise quote."sla = "SLA Exhibit"@@ -10631,19 +10792,16 @@ title = "Something went wrong"[portal.procurement.hero]barAria = "Stage {{current}} of {{total}}"ctaAgreement = "Review & sign agreement"-ctaExploring = "Set up your trial"ctaQuote = "Review your quote"ctaReviewQuote = "Review quote"ctaTrial = "Build your quote"-documents = "Documents"eyebrow = "Enterprise"eyebrowCompany = "{{company}} Enterprise"inviteTeammates = "Invite teammates"-licenseKey = "Licence key"liveSub = "Your organization is provisioned and your licence is active."liveTitle = "You are live on Stirling Enterprise"next = "Next: {{stage}}"-open = "Open procurement"+open = "Open Enterprise"scheduleCall = "Schedule a call"sentenceAgreement = "review and sign the agreement"sentenceLive = "provisioning and rollout"@@ -10688,19 +10846,15 @@ downloadError = "Could not generate the offline licence file just yet — pleasedownloadOffline = "Download offline licence (.lic)"hint = "Paste this key into a self-hosted instance to activate it, or keep it for your records. Keep it safe."label = "Your licence key"-subtitle = "Activate a self-hosted instance with this key, or keep it for your records."-title = "Your licence key"trialFileHint = "This is your trial licence file. Once your agreement is in place, come back and download it again — unlike the online licence key, the .lic file won't update on its own."[portal.procurement.link]cta = "Link account"description = "Procurement runs on your linked Stirling account: it's how we provision the trial, price your quote, and start billing. Link an account to start."-eyebrow = "Enterprise"title = "Link your account to begin"[portal.procurement.live]description = "Your subscription is active and your licence is issued. Your team is provisioned and billing has started."-eyebrow = "Live"title = "You're live on Stirling Enterprise"[portal.procurement.milestone]@@ -10708,16 +10862,14 @@ downloadError = "Could not download the quote PDF just yet — please try again[portal.procurement.payment]description = "Your quote is accepted and your licence is already active — your team can start right away. Pay the first invoice when you're ready; you can pay or download it here, no email needed."-downloadAgreement = "Download signed agreement"downloadInvoice = "Download invoice"-eyebrow = "Payment"-title = "Subscription created"viewInvoice = "View & pay invoice"[portal.procurement.review]acceptCta = "Accept quote"annual = "Annual fee (year 1)"downloadCta = "Download quote"+oneTime = "one-time"poNumber = "Purchase order: {{po}}"renewal = "Renews at {{amount}}/year after the term (+{{pct}}% CPI)"tcv = "{{years}}-year term, paid in full up front: {{tcv}}"@@ -10743,10 +10895,10 @@ deployment = "Where should it deploy?"eula = "I agree to the Stirling EULA & Commercial Terms."fullName = "Full name"fullNamePlaceholder = "Your name"-invites = "Invite teammates · optional"+invites = "Invite teammates"invitesPlaceholder = "[email protected], [email protected]"scheduleCall = "Schedule a call"-seats = "People testing"+seats = "How many people will trial it?"seatsPlaceholder = "e.g. 15"selfhost = "Self-hosted"selfhostSub = "Docker or Kubernetes"@@ -10763,12 +10915,19 @@ workEmailPlaceholder = "[email protected]"[portal.procurement.trial]body = "Extending adds 7 days and notifies your solutions engineer."bodyMaxed = "You have used all your extensions — talk to your solutions engineer if you need more time."-cancel = "Cancel trial"extend = "Extend 7 days"maxed = "Maxed out"subtitle = "Your free trial runs through {{date}}. No card required."title = "Enterprise trial"+[portal.procurement.validation]+confirm = "Confirm you're authorized to sign for the organization."+email = "Enter a valid email address."+eula = "Agree to the EULA to continue."+required = "This field is required."+seats = "Enter how many people will trial it."+volume = "Enter how many PDFs you expect to process a year."+[portal.review]subtitle = "Anything from your policy runs and your team's editors that needs your attention."title = "Review"diff --git a/frontend/src/editor/core/components/shared/StepModalHeader.tsx b/frontend/src/editor/core/components/shared/StepModalHeader.tsxindex b9c1c869f7..0fa9da8bd3 100644--- a/frontend/src/editor/core/components/shared/StepModalHeader.tsx+++ b/frontend/src/editor/core/components/shared/StepModalHeader.tsx@@ -53,7 +53,7 @@ export function StepModalHeader({<div className="portal-stepmodal__head-top">{typeof brand === "string" ? (<div className="portal-stepmodal__ident">- <h3 className="portal-stepmodal__flow-title">{brand}</h3>+ <h2 className="portal-stepmodal__flow-title">{brand}</h2></div>) : brand ? (<div className="portal-stepmodal__brand">@@ -71,7 +71,7 @@ export function StepModalHeader({</div>) : title ? (<div className="portal-stepmodal__ident">- <h3 className="portal-stepmodal__flow-title">{title}</h3>+ <h2 className="portal-stepmodal__flow-title">{title}</h2>{subtitle && (<p className="portal-stepmodal__flow-sub">{subtitle}</p>)}diff --git a/frontend/src/editor/core/constants/selfHosting.ts b/frontend/src/editor/core/constants/selfHosting.tsindex 9017fe7ca2..1e596a118b 100644--- a/frontend/src/editor/core/constants/selfHosting.ts+++ b/frontend/src/editor/core/constants/selfHosting.ts@@ -2,7 +2,7 @@ import { DOWNLOAD_URLS } from "@editor/constants/downloads";export type DockerImageTag = "latest" | "latest-fat" | "latest-ultra-lite";-const DOCKER_IMAGE = "docker.stirlingpdf.com/stirlingtools/stirling-pdf";+export const DOCKER_IMAGE = "docker.stirlingpdf.com/stirlingtools/stirling-pdf";export const dockerRunCommand = (tag: DockerImageTag = "latest") =>`docker run -d --name stirling-pdf -p 8080:8080 \\\n -v ./stirling-data:/configs \\\n ${DOCKER_IMAGE}:${tag}`;diff --git a/frontend/src/editor/core/tests/stubbed/account-link-dialogs.spec.ts b/frontend/src/editor/core/tests/stubbed/account-link-dialogs.spec.tsindex 44fa8c3b6b..49672c0d9d 100644--- a/frontend/src/editor/core/tests/stubbed/account-link-dialogs.spec.ts+++ b/frontend/src/editor/core/tests/stubbed/account-link-dialogs.spec.ts@@ -106,20 +106,24 @@ for (const path of ["/settings/account-link", "/settings/billing"]) {});}-test("dismissing the trial connection prerequisite does not reopen it", async ({+test("the Enterprise page asks an unlinked server to connect first, and only on request", async ({page,}) => {- await page.goto("/settings/billing?procurement=start");+ await page.goto("/enterprise");+ const connect = page.getByRole("button", {+ name: "Link account",+ exact: true,+ });+ await expect(connect).toBeVisible();+ await expect(page.getByRole("dialog")).toHaveCount(0);+ await connect.click();await expect(page.getByRole("dialog")).toHaveCount(1);await page.getByRole("dialog").getByRole("button", { name: "Not now", exact: true }).click();await expect(page.getByRole("dialog")).toHaveCount(0);- await page- .getByRole("button", { name: "Connect a Stirling account", exact: true })- .click();- await expect(page.getByRole("dialog")).toHaveCount(1);+ await expect(connect).toBeVisible();});test("late exhausted-credit responses do not reopen a dismissed dialog", async ({diff --git a/frontend/src/editor/proprietary/billing/BillingScreen.test.tsx b/frontend/src/editor/proprietary/billing/BillingScreen.test.tsxindex 242def5a96..5b8c22dd58 100644--- a/frontend/src/editor/proprietary/billing/BillingScreen.test.tsx+++ b/frontend/src/editor/proprietary/billing/BillingScreen.test.tsx@@ -1,5 +1,6 @@import { describe, expect, it, vi } from "vitest";import { fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";vi.mock("react-i18next", () => ({useTranslation: () => ({@@ -11,7 +12,10 @@ vi.mock("react-i18next", () => ({}),}));-import { BillingScreen } from "@editor/billing/BillingScreen";+import {+ BillingScreen,+ COMPARE_PLANS_ANCHOR,+} from "@editor/billing/BillingScreen";import { freeWallet, subscribedWallet } from "@editor/billing/walletFixtures";it.each(["free", "team", "processor", "SERVER", "ENTERPRISE"] as const)(@@ -337,3 +341,17 @@ it("retains Plan and Usage while data is unavailable without inventing figures oexpect(screen.queryByText("The full PDF Editor.")).toBeNull();expect(screen.queryByRole("button", { name: "Add capacity" })).toBeNull();});++it("opens the plan comparison when linked straight to it", () => {+ window.location.hash = `#${COMPARE_PLANS_ANCHOR}`;+ try {+ render(+ <MantineProvider>+ <BillingScreen wallet={freeWallet} />+ </MantineProvider>,+ );+ expect(screen.getByRole("dialog")).toBeInTheDocument();+ } finally {+ window.location.hash = "";+ }+});diff --git a/frontend/src/editor/proprietary/billing/BillingScreen.tsx b/frontend/src/editor/proprietary/billing/BillingScreen.tsxindex d79a7d8e90..fb9315a074 100644--- a/frontend/src/editor/proprietary/billing/BillingScreen.tsx+++ b/frontend/src/editor/proprietary/billing/BillingScreen.tsx@@ -15,8 +15,12 @@ import { fleetUsersInUse } from "@editor/billing/fleetSeats";import type { ServerPlan } from "@editor/billing/serverPlan";import type { Wallet } from "@editor/billing/types";import type { LegacyTeamAllowance } from "@editor/types/legacyBilling";+import { COMPARE_PLANS_ANCHOR } from "@editor/billing/compareAnchor";import "@editor/billing/billing-screen.css";+// Kept in its own module so callers that only link here need not load this screen.+export { COMPARE_PLANS_ANCHOR };+export interface BillingScreenProps {/** Host-specific occupied seats; null means unavailable, undefined uses the wallet. */usersInUse?: number | null;@@ -129,7 +133,10 @@ export function BillingScreen({extras,}: BillingScreenProps) {const { t } = useTranslation();- const [comparing, setComparing] = useState(false);+ // Opened straight away when linked to it, e.g. from a quote too small for Enterprise.+ const [comparing, setComparing] = useState(+ () => window.location.hash === `#${COMPARE_PLANS_ANCHOR}`,+ );const enterpriseProcessor =Boolean(wallet?.enterprise) || serverPlan?.licenseType === "ENTERPRISE";diff --git a/frontend/src/editor/proprietary/billing/compareAnchor.ts b/frontend/src/editor/proprietary/billing/compareAnchor.tsnew file mode 100644index 0000000000..2bfc1335dc--- /dev/null+++ b/frontend/src/editor/proprietary/billing/compareAnchor.ts@@ -0,0 +1,2 @@+/** Settings anchor that opens billing with the plan comparison showing. */+export const COMPARE_PLANS_ANCHOR = "compare-plans";diff --git a/frontend/src/editor/proprietary/routes/adminRouteExtensions.tsx b/frontend/src/editor/proprietary/routes/adminRouteExtensions.tsxindex 2fbb164c4f..32cafa864e 100644--- a/frontend/src/editor/proprietary/routes/adminRouteExtensions.tsx+++ b/frontend/src/editor/proprietary/routes/adminRouteExtensions.tsx@@ -1,8 +1,13 @@import { lazy } from "react";import type { ReactElement } from "react";-import { Route } from "react-router-dom";+import { Navigate, Route, useLocation } from "react-router-dom";import { PORTAL_BASENAME } from "@editor/routes/portalBasename";import { HAS_PORTAL } from "@editor/routes/hasPortal";+import { NoAppChrome } from "@editor/components/layout/NoAppChrome";+import {+ ENTERPRISE_PATH,+ LEGACY_ENTERPRISE_PATH,+} from "@editor/portal/components/procurement/enterprisePath";const PortalApp = HAS_PORTAL? lazy(async () => {@@ -11,11 +16,11 @@ const PortalApp = HAS_PORTAL}): null;-const ProcurementRedirect = HAS_PORTAL+/** The Enterprise page reads like a website, so it carries none of the app's chrome. */+const EnterpriseApp = HAS_PORTAL? lazy(async () => {- const m =- await import("@processor/components/procurement/ProcurementRedirect");- return { default: m.ProcurementRedirect };+ const m = await import("@processor/EnterpriseApp");+ return { default: m.EnterpriseApp };}): null;@@ -29,14 +34,23 @@ const ConnectCallback = HAS_PORTAL}): null;+/** Old Enterprise links, kept working with whatever they carry (?source=sales). */+function LegacyEnterpriseRedirect() {+ const { search, hash } = useLocation();+ return <Navigate to={`${ENTERPRISE_PATH}${search}${hash}`} replace />;+}+/** The portal mounts as an admin-only route-set at PORTAL_BASENAME (/processor/*). */export function getAdminRouteExtensions(): ReactElement[] {- if (!PortalApp || !ConnectCallback || !ProcurementRedirect) return [];+ if (!PortalApp || !ConnectCallback || !EnterpriseApp) return [];return [+ <Route key="enterprise" element={<NoAppChrome />}>+ <Route path={ENTERPRISE_PATH} element={<EnterpriseApp />} />+ </Route>,<Route- key="procurement"- path="/procurement"- element={<ProcurementRedirect />}+ key="enterprise-legacy"+ path={LEGACY_ENTERPRISE_PATH}+ element={<LegacyEnterpriseRedirect />}/>,<Routekey="portal"diff --git a/frontend/src/editor/proprietary/routes/login/LoggedInState.test.tsx b/frontend/src/editor/proprietary/routes/login/LoggedInState.test.tsxindex 9e20011565..74b908c883 100644--- a/frontend/src/editor/proprietary/routes/login/LoggedInState.test.tsx+++ b/frontend/src/editor/proprietary/routes/login/LoggedInState.test.tsx@@ -3,6 +3,10 @@ import { render, waitFor } from "@testing-library/react";import { MemoryRouter } from "react-router-dom";import LoggedInState from "@editor/routes/login/LoggedInState";import { resolveLandingPath } from "@editor/utils/loginLanding";+import {+ rememberPendingDestination,+ resetPendingDestinationForTests,+} from "@editor/services/pendingDestination";vi.mock("@editor/utils/loginLanding", () => ({resolveLandingPath: vi.fn(),@@ -21,6 +25,24 @@ vi.mock("react-router-dom", async () => {describe("LoggedInState", () => {beforeEach(() => {mockNavigate.mockClear();+ window.localStorage.clear();+ resetPendingDestinationForTests();+ });++ it("returns to the destination remembered before an auth detour", async () => {+ rememberPendingDestination("/enterprise");+ render(+ <MemoryRouter>+ <LoggedInState />+ </MemoryRouter>,+ );++ await waitFor(() => {+ expect(mockNavigate).toHaveBeenCalledWith("/enterprise", {+ replace: true,+ });+ });+ expect(resolveLandingPath).not.toHaveBeenCalled();});it("navigates to the resolved landing path", async () => {diff --git a/frontend/src/editor/proprietary/routes/login/LoggedInState.tsx b/frontend/src/editor/proprietary/routes/login/LoggedInState.tsxindex e89cd0cd9e..3b90085800 100644--- a/frontend/src/editor/proprietary/routes/login/LoggedInState.tsx+++ b/frontend/src/editor/proprietary/routes/login/LoggedInState.tsx@@ -1,6 +1,7 @@import { useEffect } from "react";import { useNavigate } from "react-router-dom";import { LoadingFallback } from "@editor/components/shared/LoadingFallback";+import { takePendingDestination } from "@editor/services/pendingDestination";import { resolveLandingPath } from "@editor/utils/loginLanding";export default function LoggedInState() {@@ -8,7 +9,10 @@ export default function LoggedInState() {useEffect(() => {let active = true;- void resolveLandingPath().then(+ // A signed-in visitor on the login page has just finished an auth detour, so the place they+ // set out for (the Enterprise page's trial, say) comes before the default landing.+ const remembered = takePendingDestination();+ void (remembered ? Promise.resolve(remembered) : resolveLandingPath()).then((path) => {if (active) navigate(path, { replace: true });},diff --git a/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx b/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsxindex a386e0f192..7c11d8be79 100644--- a/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx+++ b/frontend/src/editor/saas/components/runLocation/RunLocationGate.test.tsx@@ -74,6 +74,25 @@ describe("RunLocationGate", () => {expect(screen.getByText("The app")).toBeInTheDocument();});+ it.each(["/enterprise", "/procurement"])(+ "lets the Enterprise landing link %s through without recording a choice",+ (path) => {+ renderAt(path);+ expect(screen.getByText("The app")).toBeInTheDocument();+ expect(window.localStorage.getItem(SEEN_KEY)).toBeNull();+ },+ );++ it("lets sign-in through on the way back to the Enterprise page", () => {+ renderAt("/login?next=%2Fenterprise%3Fsource%3Dsales");+ expect(screen.getByText("The app")).toBeInTheDocument();+ });++ it("still asks on sign-in headed anywhere else", () => {+ renderAt("/login");+ expect(screen.queryByText("The app")).not.toBeInTheDocument();+ });+it("lets flow links through without recording a choice", () => {renderAt("/auth/callback");expect(screen.getByText("The app")).toBeInTheDocument();diff --git a/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx b/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsxindex d8e11ba22b..e603072784 100644--- a/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx+++ b/frontend/src/editor/saas/components/runLocation/RunLocationGate.tsx@@ -4,21 +4,38 @@ import { normalizePath } from "@editor/utils/pathUtils";import { PublicRouteProviders } from "@editor/components/PublicRouteProviders";import { RunLocationChooser } from "@editor/components/runLocation/RunLocationChooser";import { hasChosenRunLocation } from "@editor/components/runLocation/runLocationChosen";+import {+ ENTERPRISE_PATH,+ LEGACY_ENTERPRISE_PATH,+} from "@editor/portal/components/procurement/enterprisePath";// Links that finish a flow already in progress (an emailed sign-in, an OAuth// redirect, a shared file). Interrupting them with the chooser in a fresh// browser would strand the visitor mid-flow, or lose the token in the URL.+// The Enterprise page is a landing link from campaigns and sales replies, and+// asks where Stirling will be deployed itself.const FLOW_PATHS = ["/auth/callback","/auth/reset","/oauth/consent","/link","/account-link/callback",+ ENTERPRISE_PATH,+ LEGACY_ENTERPRISE_PATH,];-export function bypassesRunLocation(pathname: string): boolean {+// Signing in from the Enterprise page detours through these, naming it as `next`.+const AUTH_PATHS = ["/login", "/signup"];++export function bypassesRunLocation(pathname: string, search = ""): boolean {const path = normalizePath(pathname);- return FLOW_PATHS.includes(path) || path.startsWith("/share/");+ if (FLOW_PATHS.includes(path) || path.startsWith("/share/")) return true;+ const next = new URLSearchParams(search).get("next");+ const nextPath = next?.split(/[?#]/)[0];+ return (+ AUTH_PATHS.includes(path) &&+ (nextPath === ENTERPRISE_PATH || nextPath === LEGACY_ENTERPRISE_PATH)+ );}/**@@ -26,10 +43,10 @@ export function bypassesRunLocation(pathname: string): boolean {* auth included, until this browser has confirmed a choice once.*/export function RunLocationGate() {- const { pathname } = useLocation();+ const { pathname, search } = useLocation();const [showChooser, setShowChooser] = useState(() => !hasChosenRunLocation());- if (!showChooser || bypassesRunLocation(pathname)) {+ if (!showChooser || bypassesRunLocation(pathname, search)) {return <Outlet />;}diff --git a/frontend/src/editor/saas/routes/Login.guest.test.tsx b/frontend/src/editor/saas/routes/Login.guest.test.tsxnew file mode 100644index 0000000000..06b01f95b8--- /dev/null+++ b/frontend/src/editor/saas/routes/Login.guest.test.tsx@@ -0,0 +1,88 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { MemoryRouter, Route, Routes } from "react-router-dom";+import { MantineProvider } from "@mantine/core";+import { TestQueryProvider } from "@editor/tests/utils/TestQueryProvider";+import Login from "@editor/routes/Login";++const auth = vi.hoisted(() => ({+ session: {} as object | null,+ isAnonymous: true,+}));++vi.mock("@editor/auth/UseSession", () => ({+ useAuth: () => ({+ session: auth.session,+ isAnonymous: auth.isAnonymous,+ loading: false,+ refreshSession: vi.fn(),+ }),+}));+const { signInAnonymously } = vi.hoisted(() => ({+ signInAnonymously: vi.fn(),+}));+vi.mock("@editor/auth/supabase", () => ({+ supabase: {+ auth: {+ getSession: async () => ({ data: { session: null }, error: null }),+ },+ },+ signInAnonymously,+}));+vi.mock("@editor/hooks/useDocumentMeta", () => ({ useDocumentMeta: vi.fn() }));+const destination = vi.hoisted(() => ({+ rememberPendingDestination: vi.fn(),+ clearPendingDestination: vi.fn(),+ takePendingDestination: vi.fn(() => null),+}));+vi.mock("@editor/services/pendingDestination", () => destination);++function mount(entry: string) {+ window.history.replaceState(null, "", entry);+ render(+ <MantineProvider>+ <TestQueryProvider>+ <MemoryRouter initialEntries={[entry]}>+ <Routes>+ <Route path="/login" element={<Login />} />+ <Route path="/enterprise" element={<div>Enterprise page</div>} />+ </Routes>+ </MemoryRouter>+ </TestQueryProvider>+ </MantineProvider>,+ );+}++describe("SaaS login with a guest session", () => {+ beforeEach(() => {+ auth.session = {};+ auth.isAnonymous = true;+ vi.clearAllMocks();+ });++ it("shows a guest the sign-in form instead of sending them back to `next`", () => {+ mount("/login?next=%2Fenterprise");+ expect(screen.queryByText("Enterprise page")).not.toBeInTheDocument();+ expect(screen.getAllByRole("textbox").length).toBeGreaterThan(0);+ });++ it("sends a signed-in account straight on to `next`", () => {+ auth.isAnonymous = false;+ mount("/login?next=%2Fenterprise");+ expect(screen.getByText("Enterprise page")).toBeInTheDocument();+ });++ it("lets a guest skip on to `next` as the same guest, without a new guest session", () => {+ mount("/login?next=%2Fenterprise");+ fireEvent.click(screen.getByRole("button", { name: /skip/i }));+ expect(signInAnonymously).not.toHaveBeenCalled();+ expect(screen.getByText("Enterprise page")).toBeInTheDocument();+ });++ it("leaves no remembered destination behind once it has sent them on", () => {+ auth.isAnonymous = false;+ mount("/login?next=%2Fenterprise");+ expect(destination.clearPendingDestination).toHaveBeenCalled();+ expect(destination.rememberPendingDestination).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/editor/saas/routes/Login.tsx b/frontend/src/editor/saas/routes/Login.tsxindex df3a90164d..fa415a8c7b 100644--- a/frontend/src/editor/saas/routes/Login.tsx+++ b/frontend/src/editor/saas/routes/Login.tsx@@ -16,6 +16,7 @@ import {} from "@editor/constants/app";import { isSafePostLoginRedirect } from "@editor/services/postLoginRedirect";import {+ clearPendingDestination,rememberPendingDestination,takePendingDestination,} from "@editor/services/pendingDestination";@@ -33,7 +34,9 @@ import { privateContentClassName } from "@editor/components/shared/privateContenexport default function Login() {const navigate = useNavigate();- const { session, loading, refreshSession } = useAuth();+ const { session, isAnonymous, loading, refreshSession } = useAuth();+ // A guest session is not a sign-in: guests come here to sign in, so they get the form.+ const signedIn = !!session && !isAnonymous;const { t } = useTranslation();const [isSigningIn, setIsSigningIn] = useState(false);const [error, setError] = useState<string | null>(null);@@ -69,17 +72,21 @@ export default function Login() {}}, []);+ /** On to where the visitor was heading, which is then no longer remembered. */+ const continueToNext = () => {+ clearPendingDestination();+ navigate(nextPath ?? "/", { replace: true });+ };+useEffect(() => {- if (session && !loading && nextPath) {- navigate(nextPath, { replace: true });- }- }, [session, loading, nextPath, navigate]);+ if (signedIn && !loading && nextPath) continueToNext();+ }, [signedIn, loading, nextPath, navigate]);// Stashed as well as held in the URL: leaving to create an account loses the// query string, and the confirmation link cannot carry a `next`.useEffect(() => {- if (nextPath) rememberPendingDestination(nextPath);- }, [nextPath]);+ if (nextPath && !signedIn) rememberPendingDestination(nextPath);+ }, [nextPath, signedIn]);const baseUrl = getBaseUrl();@@ -104,7 +111,7 @@ export default function Login() {}// Show logged in state if authenticated (unless bouncing back to `next`)- if (session && !loading) {+ if (signedIn && !loading) {if (nextPath) {return null;}@@ -245,6 +252,12 @@ export default function Login() {};const handleAnonymousSignIn = async () => {+ // Already a guest: carry on as that guest. Signing in anonymously again would swap their+ // session for a brand-new guest account.+ if (session && isAnonymous) {+ continueToNext();+ return;+ }try {setIsSigningIn(true);setError(null);@@ -260,10 +273,8 @@ export default function Login() {// Refresh session to ensure backend endpoints are properly synchronizedawait refreshSession();- console.log(- "[Login] Session refreshed, user will be redirected by auth state change",- );- // User will be redirected by the auth state change after session refresh+ // A guest session does not count as signed in here, so nothing else moves them on.+ continueToNext();}} catch (err) {console.error("[Login] Unexpected error:", err);@@ -420,7 +431,12 @@ export default function Login() {><Buttonvariant="tertiary"- onClick={() => navigate("/signup")}+ onClick={() =>+ navigate(+ "/signup" ++ (nextPath ? `?next=${encodeURIComponent(nextPath)}` : ""),+ )+ }style={{background: "none",border: "none",diff --git a/frontend/src/editor/saas/routes/Signup.tsx b/frontend/src/editor/saas/routes/Signup.tsxindex d99f7b34d6..678b804211 100644--- a/frontend/src/editor/saas/routes/Signup.tsx+++ b/frontend/src/editor/saas/routes/Signup.tsx@@ -262,7 +262,7 @@ export default function Signup() {><Buttonvariant="tertiary"- onClick={() => navigate("/login")}+ onClick={() => navigate(`/login${location.search}`)}style={{background: "none",border: "none",diff --git a/frontend/src/processor/proprietary/EnterpriseApp.tsx b/frontend/src/processor/proprietary/EnterpriseApp.tsxnew file mode 100644index 0000000000..e7db03afca--- /dev/null+++ b/frontend/src/processor/proprietary/EnterpriseApp.tsx@@ -0,0 +1,37 @@+import { type ReactNode } from "react";+import { useAuth } from "@editor/auth";+import { EnterpriseAuthBoundary } from "@processor/auth/EnterpriseAuthBoundary";+import { PortalFrame } from "@processor/PortalFrame";+import { PortalSettingsProviders } from "@processor/components/settings/PortalSettingsProviders";+import { ErrorBoundary } from "@processor/components/ErrorBoundary";+import { Enterprise } from "@processor/views/Enterprise";++/** The portal's providers load account data as they mount, so a visitor without one gets none. */+function AccountProviders({ children }: { children: ReactNode }) {+ const { session, isAnonymous } = useAuth();+ return session && !isAnonymous ? (+ <PortalSettingsProviders>{children}</PortalSettingsProviders>+ ) : (+ children+ );+}++/**+ * The Enterprise page as its own route, served like a website separate from the app: none of the+ * portal's chrome, but the same query cache, sign-in and account link as billing, so a deal started+ * on either side shows on the other. EnterpriseAuthBoundary decides per build whether sign-in+ * comes first.+ */+export function EnterpriseApp() {+ return (+ <PortalFrame>+ <EnterpriseAuthBoundary>+ <AccountProviders>+ <ErrorBoundary>+ <Enterprise />+ </ErrorBoundary>+ </AccountProviders>+ </EnterpriseAuthBoundary>+ </PortalFrame>+ );+}diff --git a/frontend/src/processor/proprietary/PortalApp.tsx b/frontend/src/processor/proprietary/PortalApp.tsxindex 5c1e29f9e2..6af4a33f38 100644--- a/frontend/src/processor/proprietary/PortalApp.tsx+++ b/frontend/src/processor/proprietary/PortalApp.tsx@@ -1,22 +1,6 @@-import { type ReactNode } from "react";-import { QueryClientProvider } from "@tanstack/react-query";import { PortalAuthBoundary } from "@processor/auth/PortalAuthBoundary";-import { ThemeProvider, useTheme } from "@processor/contexts/ThemeContext";-import { SuiProvider } from "@processor/theme/SuiProvider";+import { PortalFrame } from "@processor/PortalFrame";import { PortalProviders } from "@processor/PortalProviders";-import { getPortalQueryClient } from "@processor/queryClient";-// Reset + typography, scoped to .portal-scope below.-import "@processor/theme/base.css";--/**- * Binds the SUI design system to the portal's own ThemeProvider so the SUI- * components follow the same light/dark switch as the CSS tokens. Must sit- * inside <ThemeProvider> to read useTheme().- */-function ThemedSuiProvider({ children }: { children: ReactNode }) {- const { theme } = useTheme();- return <SuiProvider colorScheme={theme}>{children}</SuiProvider>;-}/*** The portal, mounted as a route-set under /processor/* inside the editor app@@ -30,19 +14,11 @@ function ThemedSuiProvider({ children }: { children: ReactNode }) {* self-hosted mounts the account-link layer, SaaS does not.*/export function PortalApp() {- const queryClient = getPortalQueryClient();return (- <QueryClientProvider client={queryClient}>- <ThemeProvider>- <ThemedSuiProvider>- {/* Scopes base.css to the portal so it doesn't restyle the host editor. */}- <div className="portal-scope">- <PortalAuthBoundary>- <PortalProviders />- </PortalAuthBoundary>- </div>- </ThemedSuiProvider>- </ThemeProvider>- </QueryClientProvider>+ <PortalFrame>+ <PortalAuthBoundary>+ <PortalProviders />+ </PortalAuthBoundary>+ </PortalFrame>);}diff --git a/frontend/src/processor/proprietary/PortalFrame.tsx b/frontend/src/processor/proprietary/PortalFrame.tsxnew file mode 100644index 0000000000..6f88af4556--- /dev/null+++ b/frontend/src/processor/proprietary/PortalFrame.tsx@@ -0,0 +1,34 @@+import { type ReactNode } from "react";+import { QueryClientProvider } from "@tanstack/react-query";+import { ThemeProvider, useTheme } from "@processor/contexts/ThemeContext";+import { SuiProvider } from "@processor/theme/SuiProvider";+import { getPortalQueryClient } from "@processor/queryClient";+// Reset + typography, scoped to .portal-scope below.+import "@processor/theme/base.css";++/**+ * Binds the SUI design system to the portal's own ThemeProvider so the SUI+ * components follow the same light/dark switch as the CSS tokens. Must sit+ * inside <ThemeProvider> to read useTheme().+ */+function ThemedSuiProvider({ children }: { children: ReactNode }) {+ const { theme } = useTheme();+ return <SuiProvider colorScheme={theme}>{children}</SuiProvider>;+}++/**+ * What every page the portal mounts inside the editor needs: the portal's query cache (shared, so+ * state loaded on one page shows on another), its theme and design system, and its base styles.+ */+export function PortalFrame({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={getPortalQueryClient()}>+ <ThemeProvider>+ <ThemedSuiProvider>+ {/* Scopes base.css to the portal so it doesn't restyle the host editor. */}+ <div className="portal-scope">{children}</div>+ </ThemedSuiProvider>+ </ThemeProvider>+ </QueryClientProvider>+ );+}diff --git a/frontend/src/processor/proprietary/ViewRouter.test.tsx b/frontend/src/processor/proprietary/ViewRouter.test.tsxindex 3e5623ed98..bc923e5f5c 100644--- a/frontend/src/processor/proprietary/ViewRouter.test.tsx+++ b/frontend/src/processor/proprietary/ViewRouter.test.tsx@@ -7,6 +7,9 @@ import { getAdminRouteExtensions } from "@editor/routes/adminRouteExtensions";vi.mock("@editor/routes/hasPortal", () => ({ HAS_PORTAL: true }));vi.mock("@processor/PortalApp", () => ({ PortalApp: () => <ViewRouter /> }));+vi.mock("@processor/EnterpriseApp", () => ({+ EnterpriseApp: () => <BillingLocation />,+}));vi.mock("@processor/views/Home", () => ({ Home: () => <div>Home</div> }));vi.mock("@processor/views/Users", () => ({ Users: () => null }));@@ -32,7 +35,7 @@ function BillingLocation() {describe("procurement sales links", () => {it.each(["/", "/app"])(- "accepts the short link under basename %s without duplicating the prefix",+ "sends the old /procurement link to the Enterprise page under basename %s",async (basename) => {render(<MemoryRouter@@ -50,15 +53,13 @@ describe("procurement sales links", () => {</MemoryRouter>,);expect(- await screen.findByText(- "/settings/billing?source=sales&procurement=start",- ),+ await screen.findByText("/enterprise?source=sales"),).toBeInTheDocument();},);it.each(["/", "/app"])(- "keeps the old usage bookmark's query and section under %s",+ "sends an old usage bookmark that started the trial to the Enterprise page under %s",async (basename) => {render(<MemoryRouter@@ -75,11 +76,7 @@ describe("procurement sales links", () => {</Suspense></MemoryRouter>,);- expect(- await screen.findByText(- "/settings/billing?procurement=start#ub-license",- ),- ).toBeInTheDocument();+ expect(await screen.findByText("/enterprise")).toBeInTheDocument();},);});diff --git a/frontend/src/processor/proprietary/ViewRouter.tsx b/frontend/src/processor/proprietary/ViewRouter.tsxindex bf8fb3f1f6..3ae0a6be94 100644--- a/frontend/src/processor/proprietary/ViewRouter.tsx+++ b/frontend/src/processor/proprietary/ViewRouter.tsx@@ -8,6 +8,7 @@ import { Sources } from "@processor/views/Sources";import { Integrations } from "@processor/views/Integrations";import { VIEW_PATHS, toPortalPath } from "@processor/contexts/ViewContext";import { DOCS_PATH } from "@editor/routes/docsRoute";+import { legacyProcurementTarget } from "@processor/components/procurement/enterprisePath";/** Keeps the query and hash a moved tab's deep links carry (?tab=, #doc-id). */function MovedTo({ to }: { to: string }) {@@ -15,6 +16,16 @@ function MovedTo({ to }: { to: string }) {return <Navigate to={`${to}${search}${hash}`} replace />;}+/** Old usage bookmarks; one that set out to start the Enterprise trial goes to the Enterprise page. */+function UsageRedirect() {+ const target = legacyProcurementTarget(useLocation().search);+ return target ? (+ <Navigate to={target} replace />+ ) : (+ <MovedTo to="/settings/billing" />+ );+}+// The portal mounts as a route-set under /processor/* in the editor app, so these// child routes are relative to that base: strip the leading slash from the// logical VIEW_PATHS, and home is the index route. Redirects use toPortalPath@@ -73,10 +84,7 @@ export function ViewRouter() {path={rel(VIEW_PATHS.infrastructure)}element={<MovedTo to="/settings/api-keys" />}/>- <Route- path={rel(VIEW_PATHS.usage)}- element={<MovedTo to="/settings/billing" />}- />+ <Route path={rel(VIEW_PATHS.usage)} element={<UsageRedirect />} /><Route path={rel(VIEW_PATHS.docs)} element={<MovedTo to={DOCS_PATH} />} />{/* Account-link is a settings section now. */}<Routediff --git a/frontend/src/processor/proprietary/api/http.ts b/frontend/src/processor/proprietary/api/http.tsindex a1f5048748..aecac67c9f 100644--- a/frontend/src/processor/proprietary/api/http.ts+++ b/frontend/src/processor/proprietary/api/http.ts@@ -71,6 +71,8 @@ export interface HttpRequestOptions {/** Extra headers; Content-Type and Accept are set automatically. */headers?: Record<string, string>;signal?: AbortSignal;+ /** Sent without the session (SaaS only): the endpoint is public and the caller may have none. */+ anonymous?: boolean;}/** Thrown by any apiClient call on non-2xx response, with the parsed body. */@@ -252,25 +254,28 @@ async function saasJson<T>(const base = saasBaseUrl();// null = unset (self-hosted, no VITE_SAAS_API_URL). "" is same-origin (SaaS) — valid.if (base === null) throw new SaasUnconfiguredError();- const res = await withPortalSaasSession(- (token) =>- fetch(`${base}${path}`, {- method: options.method ?? "GET",- headers: {- Accept: "application/json",- ...(options.body !== undefined- ? { "Content-Type": "application/json" }- : {}),- ...options.headers,- Authorization: `Bearer ${token}`,- },- body:- options.body !== undefined ? JSON.stringify(options.body) : undefined,- signal: options.signal,- }),- (response) => response.status === 401,- !options.method || options.method === "GET",- );+ const send = (token: string | null) =>+ fetch(`${base}${path}`, {+ method: options.method ?? "GET",+ headers: {+ Accept: "application/json",+ ...(options.body !== undefined+ ? { "Content-Type": "application/json" }+ : {}),+ ...options.headers,+ ...(token ? { Authorization: `Bearer ${token}` } : {}),+ },+ body:+ options.body !== undefined ? JSON.stringify(options.body) : undefined,+ signal: options.signal,+ });+ const res = options.anonymous+ ? await send(null)+ : await withPortalSaasSession(+ send,+ (response) => response.status === 401,+ !options.method || options.method === "GET",+ );return unwrap<T>(res);}diff --git a/frontend/src/processor/proprietary/api/procurement.ts b/frontend/src/processor/proprietary/api/procurement.tsindex 6ac313fb9f..9a62c68cb7 100644--- a/frontend/src/processor/proprietary/api/procurement.ts+++ b/frontend/src/processor/proprietary/api/procurement.ts@@ -5,7 +5,7 @@ import { invokeSaasFunction } from "@editor/portal/auth/saasFunctions";/** Procurement models the enterprise commercial journey: trial → quote → agreement → payment →- * implementation. Usage & Billing hosts the deal summary and its flow dialogs.+ * implementation. The Enterprise page hosts it; billing shows where the deal stands.*//* ──────────────────────────────────────────────────────────────────────── */@@ -128,6 +128,37 @@ export interface AcceptResult {invoicePdf: string | null;}+/** Where a buyer can run Stirling Enterprise. */+export const DEPLOYMENTS = ["cloud", "selfhost", "airgap"] as const;+export type Deployment = (typeof DEPLOYMENTS)[number];++/** The error code the server answers a quote under the minimum deal size with (a 409). */+export const QUOTE_BELOW_MINIMUM = "quote_below_minimum";++/**+ * The rates the server prices quotes from (its PricingRates), sent so the quote builder's live+ * estimate uses the same ones. Per-run rates are in dollars; flat fees in minor units (cents).+ */+export interface RateCard {+ listRatePerRun: number;+ floorRatePerRun: number;+ /** Committed runs a year past which the per-run rate starts to fall. */+ runCurveKnee: number;+ /** Share taken off the per-run rate for each doubling of committed runs past the knee. */+ discountPerDoubling: number;+ /** The most the committed-volume curve takes off the list rate. */+ maxVolumeDiscount: number;+ /** Meter-only discount by term; index 0 is a one-year term. */+ termDiscountByYear: number[];+ /** Share of the net meter charged for indemnification. */+ indemnificationRate: number;+ dedicatedSupportMinor: number;+ selfHostDeployMinor: number;+ airgapDeployMinor: number;+ qbrAnnualMinor: number;+ trainingOneTimeMinor: number;+}+/** One shape for every state; an unstarted procurement has {@link ProcurementSnapshot.dealId} null. */export interface ProcurementSnapshot {dealId: number | null;@@ -149,6 +180,17 @@ export interface ProcurementSnapshot {contactName: string | null;contactEmail: string | null;latestQuote: QuoteResult | null;+ /** Smallest annual fee a quote may come to (minor units); 0 when there is no floor. */+ minAnnualNetMinor: number;+ /**+ * The deployment the licence is issued for: the current quote's once there is one, else the+ * trial's. Setup steps and the offline licence follow this; null on an unstarted deal.+ */+ entitledDeployment: string | null;+ /** What quotes are priced from; the builder's live estimate runs the same formula over it. */+ rateCard: RateCard;+ /** How many times the trial may be extended. */+ maxTrialExtensions: number;}export interface QuoteConfigInput {@@ -306,9 +348,14 @@ export function recordAgreementSignature();}-/** Fetch a static legal document (eula, sla, subprocessors) by id for in-product viewing. */+/**+ * Fetch a static legal document (eula, sla, subprocessors) by id for in-product viewing. Public, so a+ * visitor can read the terms they are asked to agree to before they have an account.+ */export function fetchLegalDocument(docId: string): Promise<AgreementDocument> {- return apiClient.saas.json<AgreementDocument>(`/api/v1/legal/${docId}`);+ return apiClient.saas.json<AgreementDocument>(`/api/v1/legal/${docId}`, {+ anonymous: true,+ });}/** Download the stored, signed enterprise-agreement PDF for the team (post-signing). */@@ -410,10 +457,3 @@ export function goLive(): Promise<ProcurementSnapshot> {{ method: "POST" },);}--/** Reset the team's procurement (delete the deal) and get the fresh empty snapshot. */-export function resetProcurement(): Promise<ProcurementSnapshot> {- return apiClient.saas.json<ProcurementSnapshot>("/api/v1/procurement/reset", {- method: "POST",- });-}diff --git a/frontend/src/processor/proprietary/auth/EnterpriseAuthBoundary.tsx b/frontend/src/processor/proprietary/auth/EnterpriseAuthBoundary.tsxnew file mode 100644index 0000000000..298f860789--- /dev/null+++ b/frontend/src/processor/proprietary/auth/EnterpriseAuthBoundary.tsx@@ -0,0 +1,11 @@+import { type ReactNode } from "react";+import { PortalAuthBoundary } from "@processor/auth/PortalAuthBoundary";++/**+ * Self-hosted: the Enterprise page is reached from the server's own billing, by an operator who is+ * already signed in, so it keeps the portal's sign-in gate. The SaaS build shadows this to let+ * visitors from the website see the page before they have an account.+ */+export function EnterpriseAuthBoundary({ children }: { children: ReactNode }) {+ return <PortalAuthBoundary>{children}</PortalAuthBoundary>;+}diff --git a/frontend/src/processor/proprietary/components/DownloadEditorModal.tsx b/frontend/src/processor/proprietary/components/DownloadEditorModal.tsxindex 49e2fe6f5c..c297e5ebf0 100644--- a/frontend/src/processor/proprietary/components/DownloadEditorModal.tsx+++ b/frontend/src/processor/proprietary/components/DownloadEditorModal.tsx@@ -46,6 +46,8 @@ const ICONS: Record<OptionId, IconName> = {interface Props {open: boolean;onClose: () => void;+ /** Leaves out self-hosting, for people whose server is already chosen (Stirling Cloud). */+ desktopOnly?: boolean;}function openUrl(url: string) {@@ -59,7 +61,11 @@ function openUrl(url: string) {* — marks the getting-started "Download the editor" step complete (via* {@link markEditorInstalled}); nothing else is persisted.*/-export function DownloadEditorModal({ open, onClose }: Props) {+export function DownloadEditorModal({+ open,+ onClose,+ desktopOnly = false,+}: Props) {const { t } = useTranslation();const [selected, setSelected] = useState<OptionId | null>(null);const [dockerVariant, setDockerVariant] = useState<DockerVariant>("latest");@@ -246,7 +252,9 @@ export function DownloadEditorModal({ open, onClose }: Props) {subtitle={detail? t(`portal.home.download.${selected}.detailBody`)- : t("portal.home.download.body")+ : desktopOnly+ ? t("portal.home.download.bodyDesktop")+ : t("portal.home.download.body")}footer={detail ? (@@ -279,10 +287,14 @@ export function DownloadEditorModal({ open, onClose }: Props) {{t("portal.home.download.sectionDesktop")}</p>{DESKTOP.map(renderRow)}- <p className="portal-install__section">- {t("portal.home.download.sectionSelfHosted")}- </p>- {SELF_HOSTED.map(renderRow)}+ {!desktopOnly && (+ <>+ <p className="portal-install__section">+ {t("portal.home.download.sectionSelfHosted")}+ </p>+ {SELF_HOSTED.map(renderRow)}+ </>+ )}</div>)}</Modal>diff --git a/frontend/src/processor/proprietary/components/Sidebar.tsx b/frontend/src/processor/proprietary/components/Sidebar.tsxindex 5905ef1dfc..f9e013599c 100644--- a/frontend/src/processor/proprietary/components/Sidebar.tsx+++ b/frontend/src/processor/proprietary/components/Sidebar.tsx@@ -52,9 +52,6 @@ export function Sidebar() {// off-canvas drawer, so the icon-rail state never applies there.const collapsed = sidebarCollapsed && !isMobile;- // Procurement is no longer a nav tab — it lives on Home as the deal-status hero and expands into- // a takeover modal (matching the marketing prototype).-function renderGroup(entries: NavEntry[]) {return entries.filter((entry) => adminNavVisible || !entry.requiresAdmin)diff --git a/frontend/src/processor/proprietary/components/billing/FreeTierPlanView.test.tsx b/frontend/src/processor/proprietary/components/billing/FreeTierPlanView.test.tsxindex 80c96ebbce..072470d184 100644--- a/frontend/src/processor/proprietary/components/billing/FreeTierPlanView.test.tsx+++ b/frontend/src/processor/proprietary/components/billing/FreeTierPlanView.test.tsx@@ -178,7 +178,7 @@ describe("FreeTierPlanView", () => {});it.each(["Get an enterprise quote", "Explore Enterprise"])(- "retains the Enterprise request across linking from %s",+ "opens the Enterprise page from %s, which handles connecting",async (button) => {fetchFreeTier.mockResolvedValue(BALANCE);renderView(undefined, undefined, "/settings/billing?source=sales");@@ -189,11 +189,8 @@ describe("FreeTierPlanView", () => {fireEvent.click(screen.getByRole("button", { name: button }));- expect(openLinkModal).toHaveBeenCalledWith("link");- expect(screen.getByTestId("location")).toHaveTextContent(- "/settings/billing?source=sales&procurement=start",- );- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(openLinkModal).not.toHaveBeenCalled();+ expect(screen.getByTestId("location")).toHaveTextContent("/enterprise");},);diff --git a/frontend/src/processor/proprietary/components/billing/FreeTierPlanView.tsx b/frontend/src/processor/proprietary/components/billing/FreeTierPlanView.tsxindex 69540a9fa2..4985442e45 100644--- a/frontend/src/processor/proprietary/components/billing/FreeTierPlanView.tsx+++ b/frontend/src/processor/proprietary/components/billing/FreeTierPlanView.tsx@@ -1,7 +1,6 @@import type { ReactNode } from "react";import type { ServerPlan } from "@editor/billing/serverPlan";import { useEffect, useState } from "react";-import { useSearchParams } from "react-router-dom";import { useQuery } from "@tanstack/react-query";import { useAuth } from "@editor/auth";import { qk } from "@processor/queries/keys";@@ -15,6 +14,7 @@ import { usersBackend } from "@editor/portal/usersBackend";import { HttpError } from "@processor/api/http";import { useUI } from "@processor/contexts/UIContext";import "@processor/components/billing/FreeTierPlanView.css";+import { useOpenEnterprise } from "@processor/components/procurement/enterprisePath";/** {@code forbidden} is an outcome, not a failure: the endpoint is admin-only. */type Load =@@ -93,7 +93,7 @@ export function FreeTierPlanView({const { t } = useTranslation();const { isAdmin } = useAuth();const { openLinkModal } = useUI();- const [searchParams, setSearchParams] = useSearchParams();+ const openEnterprise = useOpenEnterprise();const query = useQuery({queryKey: qk.freeTier(),queryFn: fetchFreeTier,@@ -142,14 +142,6 @@ export function FreeTierPlanView({? () => openLinkModal(exhausted ? "exhausted" : "link"): undefined;- function requestEnterpriseQuote() {- // The link handoff retains the URL across sign-in; Usage consumes this request once linked.- const next = new URLSearchParams(searchParams);- next.set("procurement", "start");- setSearchParams(next, { replace: true });- openLinkModal("link");- }-return (<BillingScreenwallet={wallet}@@ -162,7 +154,7 @@ export function FreeTierPlanView({pdfsProcessed={fleetStats?.pdfsProcessed ?? null}onAddCapacity={onLink}onActivateProcessor={onLink}- onEnterpriseQuote={isAdmin ? requestEnterpriseQuote : undefined}+ onEnterpriseQuote={isAdmin ? openEnterprise : undefined}notices={<><Bannerdiff --git a/frontend/src/processor/proprietary/components/billing/PortalBillingGate.test.tsx b/frontend/src/processor/proprietary/components/billing/PortalBillingGate.test.tsxindex 38f259bf8e..dc62c6bb9f 100644--- a/frontend/src/processor/proprietary/components/billing/PortalBillingGate.test.tsx+++ b/frontend/src/processor/proprietary/components/billing/PortalBillingGate.test.tsx@@ -390,20 +390,17 @@ describe("PortalBillingGate — self-hosted", () => {expect(applyLinkFacts).not.toHaveBeenCalled();});- it.each(["procurement=start", "upgrade=team"])(- "prompts once for %s and preserves it when linking completes",- (intent) => {- gate.gated = true;- const entry = `/settings/billing?${intent}`;- const view = render(<GateTree entry={entry} />);- expect(connect).toHaveBeenCalledTimes(1);- view.rerender(<GateTree entry={entry} />);- expect(connect).toHaveBeenCalledTimes(1);- link.is = true;- gate.gated = false;- view.rerender(<GateTree entry={entry} />);- expect(screen.getByTestId("usage")).toBeInTheDocument();- expect(screen.getByTestId("location")).toHaveTextContent(entry);- },- );+ it("prompts once for upgrade=team and preserves it when linking completes", () => {+ gate.gated = true;+ const entry = "/settings/billing?upgrade=team";+ const view = render(<GateTree entry={entry} />);+ expect(connect).toHaveBeenCalledTimes(1);+ view.rerender(<GateTree entry={entry} />);+ expect(connect).toHaveBeenCalledTimes(1);+ link.is = true;+ gate.gated = false;+ view.rerender(<GateTree entry={entry} />);+ expect(screen.getByTestId("usage")).toBeInTheDocument();+ expect(screen.getByTestId("location")).toHaveTextContent(entry);+ });});diff --git a/frontend/src/processor/proprietary/components/billing/PortalBillingGate.tsx b/frontend/src/processor/proprietary/components/billing/PortalBillingGate.tsxindex 07d7f20357..66937daf2d 100644--- a/frontend/src/processor/proprietary/components/billing/PortalBillingGate.tsx+++ b/frontend/src/processor/proprietary/components/billing/PortalBillingGate.tsx@@ -1,13 +1,12 @@import { useServerPlan } from "@editor/portal/hooks/useServerPlan";import { ManageBillingButton } from "@editor/components/shared/ManageBillingButton";import { useCallback, useEffect, useRef } from "react";-import { useSearchParams } from "react-router-dom";+import { Navigate, useSearchParams } from "react-router-dom";import { ServerLicenseSection } from "@editor/portal/components/billing/ServerLicenseSection";import {useApplyLinkFacts,useLinkOptional,} from "@editor/portal/contexts/LinkContext";-import { useUI } from "@editor/portal/contexts/UIContext";import { useConnectGate } from "@editor/portal/hooks/useConnectGate";import { useAccountLinkOwner } from "@editor/portal/hooks/useAccountLinkOwner";import { AccountConnectionNotice } from "@editor/portal/components/account-link/AccountConnectionNotice";@@ -15,6 +14,7 @@ import { SaasSessionBanner } from "@editor/portal/components/account-link/SaasSeimport { FreeTierPlanView } from "@editor/portal/components/billing/FreeTierPlanView";import { Usage } from "@editor/portal/views/Usage";import type { Wallet } from "@editor/portal/api/billing";+import { legacyProcurementTarget } from "@processor/components/procurement/enterprisePath";/*** The seam the SaaS build shadows: picks which usage page this instance has one of.@@ -25,7 +25,6 @@ import type { Wallet } from "@editor/portal/api/billing";*/export function PortalBillingGate() {const applyLinkFacts = useApplyLinkFacts();- const { trialSetupRequested } = useUI();const { loading, gated, connect } = useConnectGate();const isOwner = useAccountLinkOwner();const {@@ -38,10 +37,7 @@ export function PortalBillingGate() {const link = useLinkOptional();const [searchParams] = useSearchParams();const prompted = useRef(false);- const accountLinkRequested =- trialSetupRequested ||- searchParams.get("procurement") === "start" ||- searchParams.get("upgrade") === "team";+ const accountLinkRequested = searchParams.get("upgrade") === "team";useEffect(() => {if (!accountLinkRequested || link?.isLinked) prompted.current = false;@@ -56,6 +52,8 @@ export function PortalBillingGate() {[applyLinkFacts],);+ const procurementTarget = legacyProcurementTarget(searchParams.toString());+ if (procurementTarget) return <Navigate to={procurementTarget} replace />;// Only the organization owner manages the server's account and billing.// The nav hides these sections too; this guards a directly entered URL.if (!isOwner) return null;diff --git a/frontend/src/processor/proprietary/components/procurement/CalendlyInline.tsx b/frontend/src/processor/proprietary/components/procurement/CalendlyInline.tsxindex 0620f24fc9..acc1fdcfaf 100644--- a/frontend/src/processor/proprietary/components/procurement/CalendlyInline.tsx+++ b/frontend/src/processor/proprietary/components/procurement/CalendlyInline.tsx@@ -44,36 +44,6 @@ function buildUrl(base: string): string {return `${base}${sep}hide_event_type_details=1&background_color=${WIDGET_COLORS.background}&text_color=${WIDGET_COLORS.text}&primary_color=${WIDGET_COLORS.primary}`;}-// Origins the embed fetches from: the widget script, then the scheduler iframe.-const CALENDLY_ORIGINS = [- "https://assets.calendly.com",- "https://calendly.com",-];--function preconnect(origin: string): void {- if (typeof document === "undefined") return;- if (document.querySelector(`link[rel="preconnect"][href="${origin}"]`))- return;- const link = document.createElement("link");- link.rel = "preconnect";- link.href = origin;- link.crossOrigin = "anonymous";- document.head.appendChild(link);-}--/**- * Warm the Calendly embed ahead of use: open connections to its origins and start fetching- * widget.js, so opening the scheduler initialises near-instantly instead of paying a cold- * script + iframe fetch on click. Idempotent and safe to call repeatedly; failures are left- * for the modal's own load to surface as the fallback link.- */-export function warmCalendly(): void {- CALENDLY_ORIGINS.forEach(preconnect);- void loadScript({ src: CALENDLY_SCRIPT, id: "calendly-widget-script" }).catch(- () => {},- );-}-export function CalendlyInline({url = CALENDLY_URL,height = 760,diff --git a/frontend/src/processor/proprietary/components/procurement/DealStatusHero.stories.tsx b/frontend/src/processor/proprietary/components/procurement/DealStatusHero.stories.tsxindex b41e2a3f65..4e765fad73 100644--- a/frontend/src/processor/proprietary/components/procurement/DealStatusHero.stories.tsx+++ b/frontend/src/processor/proprietary/components/procurement/DealStatusHero.stories.tsx@@ -1,6 +1,7 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { DealStatusHero } from "@processor/components/procurement/DealStatusHero";import type { ProcurementSnapshot } from "@processor/api/procurement";+import { RATE_CARD } from "@processor/mocks/handlers/procurementSaas";import { BillingScreen } from "@editor/billing/BillingScreen";import { freeWallet } from "@editor/billing/walletFixtures";@@ -19,23 +20,18 @@ const base: ProcurementSnapshot = {contactEmail: null,agreementSignedVersion: null,latestQuote: null,+ rateCard: RATE_CARD,+ maxTrialExtensions: 2,+ minAnnualNetMinor: 0,+ entitledDeployment: null,};-/** The CTA opens the existing flow; the billing stories exercise its section and jump link. */+/** Billing's view of a deal underway; its one action opens the Enterprise page. */const meta: Meta<typeof DealStatusHero> = {title: "Portal/Procurement/DealStatusHero",component: DealStatusHero,parameters: { layout: "padded" },- args: {- canSchedule: true,- onExpand: () => {},- onAcceptQuote: () => {},- onLicense: () => {},- onInvite: () => {},- onSchedule: () => {},- onManageTrial: () => {},- onDocuments: () => {},- },+ args: { onOpen: () => {} },};export default meta;@@ -64,6 +60,11 @@ export const Live: Story = {},};+/** Members follow the deal from billing without a way into it. */+export const Member: Story = {+ args: { ...Trial.args, onOpen: undefined },+};+export const BillingTrial: Story = {parameters: { layout: "fullscreen" },args: Trial.args,diff --git a/frontend/src/processor/proprietary/components/procurement/DealStatusHero.test.tsx b/frontend/src/processor/proprietary/components/procurement/DealStatusHero.test.tsxindex 8bd21ec84b..4ef5704aab 100644--- a/frontend/src/processor/proprietary/components/procurement/DealStatusHero.test.tsx+++ b/frontend/src/processor/proprietary/components/procurement/DealStatusHero.test.tsx@@ -3,6 +3,7 @@ import { fireEvent, render, screen } from "@testing-library/react";import { MantineProvider } from "@mantine/core";import { DealStatusHero } from "@processor/components/procurement/DealStatusHero";import type { ProcurementSnapshot } from "@processor/api/procurement";+import { RATE_CARD } from "@processor/mocks/handlers/procurementSaas";vi.mock("react-i18next", () => ({useTranslation: () => ({@@ -14,9 +15,6 @@ vi.mock("react-i18next", () => ({},}),}));-vi.mock("@processor/components/procurement/CalendlyInline", () => ({- warmCalendly: vi.fn(),-}));const snapshot: ProcurementSnapshot = {dealId: 1,@@ -33,43 +31,37 @@ const snapshot: ProcurementSnapshot = {contactName: null,contactEmail: null,latestQuote: null,+ rateCard: RATE_CARD,+ maxTrialExtensions: 2,+ minAnnualNetMinor: 0,+ entitledDeployment: null,};-function mount(overrides: Partial<ProcurementSnapshot> = {}, readOnly = false) {+function mount(overrides: Partial<ProcurementSnapshot> = {}, member = false) {+ const onOpen = vi.fn();vi.useFakeTimers({ toFake: ["Date"] });vi.setSystemTime(new Date("2026-09-11T00:00:00Z"));- const onManageTrial = vi.fn();- const onDocuments = vi.fn();render(<MantineProvider><DealStatusHerosnapshot={{ ...snapshot, ...overrides }}- readOnly={readOnly}- canSchedule={false}- onExpand={vi.fn()}- onAcceptQuote={vi.fn()}- onLicense={vi.fn()}- onInvite={vi.fn()}- onSchedule={vi.fn()}- onManageTrial={onManageTrial}- onDocuments={onDocuments}+ onOpen={member ? undefined : onOpen}/></MantineProvider>,);- return { onManageTrial, onDocuments };+ return { onOpen };}afterEach(() => vi.useRealTimers());-describe("DealStatusHero trial status", () => {- it("preserves the trial-management action and document icon", () => {- const { onManageTrial, onDocuments } = mount();- fireEvent.click(screen.getByRole("button", { name: "7 days left" }));- expect(onManageTrial).toHaveBeenCalledOnce();+describe("DealStatusHero", () => {+ it("opens the Enterprise page from its one action", () => {+ const { onOpen } = mount();fireEvent.click(- screen.getByRole("button", { name: "portal.procurement.hero.documents" }),+ screen.getByRole("button", { name: "portal.procurement.hero.open" }),);- expect(onDocuments).toHaveBeenCalledOnce();+ expect(onOpen).toHaveBeenCalledOnce();+ expect(screen.getAllByRole("button")).toHaveLength(1);});it.each(["trial", "quote", "security"] as const)(@@ -80,14 +72,6 @@ describe("DealStatusHero trial status", () => {},);- it("does not offer trial extensions after the deal advances to quote", () => {- mount({ stage: "quote" });- expect(screen.getByText("7 days left")).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "7 days left" }),- ).not.toBeInTheDocument();- });-it.each(["exploring", "procurement", "active"] as const)("does not label %s using a historical trial date",(stage) => {@@ -96,7 +80,7 @@ describe("DealStatusHero trial status", () => {},);- it("shows the member's trial status without mutation actions", () => {+ it("shows a member the trial status with no way into the deal", () => {mount({}, true);expect(screen.getByText("7 days left")).toBeInTheDocument();expect(screen.queryAllByRole("button")).toHaveLength(0);diff --git a/frontend/src/processor/proprietary/components/procurement/DealStatusHero.tsx b/frontend/src/processor/proprietary/components/procurement/DealStatusHero.tsxindex 33ffbe7a3e..f868096d8e 100644--- a/frontend/src/processor/proprietary/components/procurement/DealStatusHero.tsx+++ b/frontend/src/processor/proprietary/components/procurement/DealStatusHero.tsx@@ -1,4 +1,3 @@-import { useEffect, type ReactNode } from "react";import { Icon } from "@editor/ui/Icon";import { useTranslation } from "react-i18next";import { Button } from "@editor/ui";@@ -7,8 +6,10 @@ import {type DealStage,type ProcurementSnapshot,} from "@processor/api/procurement";-import { warmCalendly } from "@processor/components/procurement/CalendlyInline";-import { openApiUrl } from "@processor/api/externalUrl";+import {+ daysLeft,+ trialLeftLabel,+} from "@processor/components/procurement/format";import "@processor/theme/surface.css";import "@processor/views/Procurement.css";@@ -23,94 +24,32 @@ const STAGE_SENTENCE: Record<DealStage, string> = {active: "portal.procurement.hero.sentenceLive",};-/** The primary action for each stage; expanding the flow runs it. */-const STAGE_CTA: Record<DealStage, string> = {- exploring: "portal.procurement.hero.ctaExploring",- trial: "portal.procurement.hero.ctaTrial",- quote: "portal.procurement.hero.ctaQuote",- security: "portal.procurement.hero.ctaAgreement",- // Same label whether it links straight to Stripe or, lacking an invoice URL, opens the stage dialog- // where the invoice actions live — the buyer is being sent to the invoice either way.- procurement: "portal.procurement.payment.viewInvoice",- active: "portal.procurement.hero.open",-};-/**- * The enterprise deal summary carries the journey as a segmented progress band plus a stage- * sentence, and one primary action with quiet icon buttons beside it; the flow itself opens in the- * takeover modal. Rollout setup lives in the non-procurement setup checklist, not here.+ * Where a deal stands, as a progress band and a stage sentence, with one way into the Enterprise+ * page where every step of it is taken. Shown wherever billing is, so a deal underway is never+ * more than a click from its next action.*/export function DealStatusHero({snapshot,- readOnly = false,- busy = false,- canSchedule,- onExpand,- onAcceptQuote,- onLicense,- onInvite,- onSchedule,- onManageTrial,- onDocuments,+ onOpen,}: {snapshot: ProcurementSnapshot;- /** Members can follow the deal without access to the leader's procurement actions. */- readOnly?: boolean;- busy?: boolean;- /** Booking a call runs through the linked account (its email prefills Calendly), so the- * "Schedule a call" action only appears when the org has linked its account. */- canSchedule: boolean;- onExpand: () => void;- /**- * Accept the issued quote, which advances the deal to the agreement. Offered here rather than- * inside the quote review so the buyer can circulate the quote and come back to decide.- */- onAcceptQuote: () => void;- onLicense: () => void;- onInvite: () => void;- onSchedule: () => void;- onManageTrial: () => void;- /** Open the Documents reference (agreement, quote, invoice, EULA, SLA, subprocessors). */- onDocuments: () => void;+ /** Omitted for members, who follow the deal here but do not run it. */+ onOpen?: () => void;}) {const { t } = useTranslation();-- // Warm Calendly's connections + widget script as soon as the "Schedule a call" action is- // available, so opening the scheduler initialises quickly instead of paying a cold fetch.- useEffect(() => {- if (canSchedule) warmCalendly();- }, [canSchedule]);-const stage = snapshot.stage ?? "trial";- const inTrial = stage === "trial";- const trialDaysLeft =+ const trialEndsAt =snapshot.trialEndsAt && ["trial", "quote", "security"].includes(stage)- ? daysLeft(snapshot.trialEndsAt)+ ? snapshot.trialEndsAt: null;- const trialLabel =- trialDaysLeft === 0- ? t("portal.procurement.journey.expired", "Trial expired")- : t("portal.procurement.journey.daysLeft", { count: trialDaysLeft ?? 0 });const isLive = stage === "active";- // A live quote is sitting with the buyer. A draft (or an expired/cancelled one) is not something to- // accept — that stage still means "finish building it".- const quoteAwaitingDecision =- stage === "quote" &&- (snapshot.latestQuote?.status === "sent" ||- snapshot.latestQuote?.status === "open");- // Paying happens on Stripe, so the card links straight there rather than opening a dialog whose only- // real action was the same link. Without an invoice URL there is nothing to link to, so the stage- // falls back to its dialog, where the signed agreement is still reachable.- const invoiceUrl =- stage === "procurement" ? snapshot.latestQuote?.invoiceUrl : null;// Known from trial setup onward. The quote's own copy wins when present, since the buyer may have// corrected it there; before either exists the eyebrow stands alone rather than inventing a name.const company =snapshot.latestQuote?.config.businessName?.trim() ||snapshot.businessName?.trim();- // Exploring is presented as the Trial rung — same position, sentence and next step — because the- // buyer has entered the journey; only the ask differs, since no trial has actually started.const journeyStage = stage === "exploring" ? "trial" : stage;const currentIdx = Math.max(0,@@ -153,19 +92,11 @@ export function DealStatusHero({)}</p>- {trialDaysLeft != null && Number.isFinite(trialDaysLeft) && (+ {trialEndsAt && Number.isFinite(daysLeft(trialEndsAt)) && (<div className="portal-hero__chips">- {inTrial && !readOnly ? (- <button- type="button"- className="portal-hero__chip portal-hero__chip--action"- onClick={onManageTrial}- >- {trialLabel}- </button>- ) : (- <span className="portal-hero__chip">{trialLabel}</span>- )}+ <span className="portal-hero__chip">+ {trialLeftLabel(t, trialEndsAt)}+ </span></div>)}</div>@@ -187,90 +118,13 @@ export function DealStatusHero({</div>)}- {!readOnly && (+ {onOpen && (<div className="portal-hero__cta">- {/* An issued quote is a decision point, so the card carries both halves of it: accept it, or- open it again to read and circulate first. Every other stage has one next step. */}- {quoteAwaitingDecision ? (- <>- <Button variant="primary" loading={busy} onClick={onAcceptQuote}>- {t("portal.procurement.review.acceptCta")}- </Button>- <Button variant="secondary" onClick={onExpand}>- {t("portal.procurement.hero.ctaReviewQuote")}- </Button>- </>- ) : invoiceUrl ? (- <Button variant="primary" onClick={() => openApiUrl(invoiceUrl)}>- {t("portal.procurement.payment.viewInvoice")}- </Button>- ) : (- <Button variant="primary" loading={busy} onClick={onExpand}>- {t(STAGE_CTA[stage])}- </Button>- )}- <div className="portal-hero__icons">- {snapshot.licenseKey && (- <IconAction- label={t("portal.procurement.hero.licenseKey")}- onClick={onLicense}- >- <Icon name="key" size={15} />- </IconAction>- )}- <IconAction- label={t("portal.procurement.hero.documents")}- onClick={onDocuments}- >- <Icon name="file-text" size={15} />- </IconAction>- {!isLive && (- <IconAction- label={t("portal.procurement.hero.inviteTeammates")}- onClick={onInvite}- >- <Icon name="user-plus" size={15} />- </IconAction>- )}- {canSchedule && (- <IconAction- label={t("portal.procurement.hero.scheduleCall")}- onClick={onSchedule}- >- <Icon name="calendar" size={15} />- </IconAction>- )}- </div>+ <Button variant="primary" onClick={onOpen}>+ {t("portal.procurement.hero.open")}+ </Button></div>)}</div>);}--/** A quiet icon-only secondary action; its label carries in the tooltip and to screen readers. */-function IconAction({- label,- onClick,- children,-}: {- label: string;- onClick: () => void;- children: ReactNode;-}) {- return (- <button- type="button"- className="portal-hero__iconbtn"- title={label}- aria-label={label}- onClick={onClick}- >- {children}- </button>- );-}--function daysLeft(iso: string): number {- const end = new Date(iso).getTime();- return Math.max(0, Math.ceil((end - Date.now()) / 86_400_000));-}diff --git a/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.css b/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.cssnew file mode 100644index 0000000000..88f3e3b95c--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.css@@ -0,0 +1,114 @@+/* The ways to run it, one slide at a time beside the trial panel. */+.ent__options {+ margin-top: 2rem;+ padding: 1.125rem 1.25rem 1rem;+ border: 1px solid var(--c-border-subtle);+ border-radius: var(--radius-lg, 12px);+ background: var(--c-surface);+}++.ent__options-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 0.75rem;+}++.ent__options-eyebrow {+ font-size: 0.75rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--c-text-subtle);+}++.ent__options-nav {+ display: flex;+ gap: 0.25rem;+}++/* Stacked in one cell, so the card holds the tallest slide's height. */+.ent__options-slides {+ display: grid;+}++.ent__options-slide {+ grid-area: 1 / 1;+ visibility: hidden;+ opacity: 0;+ transition:+ opacity 160ms ease,+ visibility 0s linear 160ms;+}++.ent__options-slide[data-active] {+ visibility: visible;+ opacity: 1;+ transition: opacity 160ms ease;+}++@media (prefers-reduced-motion: reduce) {+ .ent__options-slide,+ .ent__options-slide[data-active] {+ transition: none;+ }+}++.ent__options-title {+ display: flex;+ align-items: flex-start;+ gap: 0.75rem;+}++.ent__options-title strong {+ display: block;+ font-size: 1rem;+}++.ent__options-title span:not(.ent__options-icon) {+ display: block;+ margin-top: 0.125rem;+ font-size: 0.875rem;+ color: var(--c-text-muted);+}++.ent__options-icon {+ display: grid;+ flex: none;+ place-items: center;+ width: 2.25rem;+ height: 2.25rem;+ border-radius: var(--radius-md, 8px);+ background: var(--c-primary-subtle);+ color: var(--c-accent-text);+}++.ent__options-points {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+ margin: 0.875rem 0 0;+ padding-left: 1.125rem;+ font-size: 0.875rem;+ color: var(--c-text-muted);+}++.ent__options-more {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ margin-top: 0.875rem;+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--c-accent-text);+ text-decoration: none;+}++.ent__options-more:hover {+ text-decoration: underline;+ text-underline-offset: 0.2em;+}++.ent__options-dots {+ margin-top: 1rem;+}diff --git a/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.stories.tsx b/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.stories.tsxnew file mode 100644index 0000000000..4bd64dd5c1--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.stories.tsx@@ -0,0 +1,34 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { expect, userEvent, waitFor, within } from "storybook/test";+import { DeploymentOptions } from "@processor/components/procurement/DeploymentOptions";++/** The ways to run Enterprise, a slide each, as shown beside the trial panel on the landing page. */+const meta: Meta<typeof DeploymentOptions> = {+ title: "Portal/Procurement/Deployment options",+ component: DeploymentOptions,+ parameters: { layout: "padded" },+ decorators: [+ (Story) => (+ <div className="ent" style={{ height: "auto", maxWidth: "32rem" }}>+ <Story />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DeploymentOptions>;++export const StirlingCloud: Story = {};++export const AirGapped: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await userEvent.click(canvas.getByRole("button", { name: "Previous" }));+ // The slide fades in, so it is only visible once the transition ends.+ await waitFor(() =>+ expect(+ canvas.getByRole("link", { name: /Offline licence docs/ }),+ ).toBeVisible(),+ );+ },+};diff --git a/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.tsx b/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.tsxnew file mode 100644index 0000000000..5d1ae3fe60--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/DeploymentOptions.tsx@@ -0,0 +1,189 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { ActionIcon, CarouselDots } from "@editor/ui";+import { Icon, type IconName } from "@editor/ui/Icon";+import type { Deployment } from "@processor/api/procurement";+import { ENTERPRISE_DOCS } from "@processor/components/procurement/enterpriseDocs";+import "@processor/components/procurement/DeploymentOptions.css";++interface Option {+ id: Deployment;+ icon: IconName;+ docs: string;+}++const OPTIONS: Option[] = [+ { id: "cloud", icon: "cloud", docs: ENTERPRISE_DOCS.cloud },+ { id: "selfhost", icon: "server", docs: ENTERPRISE_DOCS.server },+ { id: "airgap", icon: "shield-check", docs: ENTERPRISE_DOCS.offlineLicence },+];++/**+ * The ways to run Enterprise, one slide each with a link to its docs, for buyers who meet the+ * deployment question at the start of the trial without a technical background.+ *+ * Every slide shares one grid cell, so the card holds the tallest one's height and the page does+ * not jump between slides.+ */+export function DeploymentOptions() {+ const { t } = useTranslation();+ const [index, setIndex] = useState(0);+ const step = (by: number) =>+ setIndex((i) => (i + by + OPTIONS.length) % OPTIONS.length);++ const copy = {+ cloud: {+ title: t("portal.enterprise.options.cloud.title", "Stirling Cloud"),+ tagline: t(+ "portal.enterprise.options.cloud.tagline",+ "Hosted for you, with nothing to install.",+ ),+ points: [+ t(+ "portal.enterprise.options.cloud.point1",+ "Your team signs in at stirling.com/app",+ ),+ t(+ "portal.enterprise.options.cloud.point2",+ "Runs on AWS, with stored files encrypted at rest",+ ),+ t(+ "portal.enterprise.options.cloud.point3",+ "Single sign-on through your own identity provider needs self-hosting",+ ),+ ],+ more: t("portal.enterprise.options.cloud.more", "Stirling Cloud docs"),+ },+ selfhost: {+ title: t("portal.enterprise.options.selfhost.title", "Self-hosted"),+ tagline: t(+ "portal.enterprise.options.selfhost.tagline",+ "On your own servers, on-premises or in your own cloud.",+ ),+ points: [+ t(+ "portal.enterprise.options.selfhost.point1",+ "Install with Docker, or the Helm chart on Kubernetes",+ ),+ t(+ "portal.enterprise.options.selfhost.point2",+ "Documents are processed on your own infrastructure",+ ),+ t(+ "portal.enterprise.options.selfhost.point3",+ "OAuth2, OIDC or SAML single sign-on",+ ),+ ],+ more: t("portal.enterprise.options.selfhost.more", "Self-hosting docs"),+ },+ airgap: {+ title: t("portal.enterprise.options.airgap.title", "Air-gapped"),+ tagline: t(+ "portal.enterprise.options.airgap.tagline",+ "Self-hosted on a network with no internet access.",+ ),+ points: [+ t(+ "portal.enterprise.options.airgap.point1",+ "Activated with a licence file that works offline, not a key checked online",+ ),+ t(+ "portal.enterprise.options.airgap.point2",+ "Installs like self-hosted, from an image you bring across",+ ),+ t(+ "portal.enterprise.options.airgap.point3",+ "Sign-in stays inside your network",+ ),+ ],+ more: t("portal.enterprise.options.airgap.more", "Offline licence docs"),+ },+ };++ return (+ <section+ className="ent__options"+ aria-roledescription="carousel"+ aria-label={t("portal.enterprise.options.label", "Ways to run it")}+ >+ <div className="ent__options-head">+ <span className="ent__options-eyebrow">+ {t("portal.enterprise.options.label", "Ways to run it")}+ </span>+ <div className="ent__options-nav">+ <ActionIcon+ variant="quiet"+ size="sm"+ aria-label={t("portal.enterprise.options.previous", "Previous")}+ onClick={() => step(-1)}+ >+ <Icon name="chevron-left" size={16} />+ </ActionIcon>+ <ActionIcon+ variant="quiet"+ size="sm"+ aria-label={t("portal.enterprise.options.next", "Next")}+ onClick={() => step(1)}+ >+ <Icon name="chevron-right" size={16} />+ </ActionIcon>+ </div>+ </div>++ <div className="ent__options-slides" aria-live="polite">+ {OPTIONS.map((option, i) => {+ const c = copy[option.id];+ const active = i === index;+ return (+ <div+ key={option.id}+ className="ent__options-slide"+ data-active={active || undefined}+ aria-hidden={!active}+ inert={!active}+ aria-roledescription="slide"+ aria-label={t("portal.enterprise.options.slideOf", {+ defaultValue: "{{n}} of {{total}}",+ n: i + 1,+ total: OPTIONS.length,+ })}+ >+ <div className="ent__options-title">+ <span className="ent__options-icon">+ <Icon name={option.icon} size={18} />+ </span>+ <div>+ <strong>{c.title}</strong>+ <span>{c.tagline}</span>+ </div>+ </div>+ <ul className="ent__options-points">+ {c.points.map((point) => (+ <li key={point}>{point}</li>+ ))}+ </ul>+ <a+ className="ent__options-more"+ href={option.docs}+ target="_blank"+ rel="noopener noreferrer"+ >+ {c.more}+ <Icon name="external-link" size={14} />+ </a>+ </div>+ );+ })}+ </div>++ <CarouselDots+ count={OPTIONS.length}+ activeIndex={index}+ onSelect={setIndex}+ label={t("portal.enterprise.options.label", "Ways to run it")}+ dotLabel={(i) => copy[OPTIONS[i].id].title}+ className="ent__options-dots"+ />+ </section>+ );+}diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementAgreement.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementAgreement.tsxindex 7ccb532e84..8b773a4fd8 100644--- a/frontend/src/processor/proprietary/components/procurement/ProcurementAgreement.tsx+++ b/frontend/src/processor/proprietary/components/procurement/ProcurementAgreement.tsx@@ -1,4 +1,4 @@-import { useRef, useState } from "react";+import { useState } from "react";import { useTranslation } from "react-i18next";import Markdown from "react-markdown";import remarkGfm from "remark-gfm";@@ -13,6 +13,12 @@ import { Icon } from "@editor/ui/Icon";import { StepModalHeader } from "@processor/components/shared/StepModalHeader";import { useAsync } from "@processor/hooks/useAsync";import "@processor/theme/surface.css";+import {+ ConsentCheckbox,+ Field,+ focusFirstInvalid,+ isFilled,+} from "@processor/components/procurement/formField";import "@processor/views/Procurement.css";import { privateContentClassName } from "@editor/components/shared/privateContentClassName";@@ -20,13 +26,10 @@ import { privateContentClassName } from "@editor/components/shared/privateConten* The agreement (security) step: the buyer reviews the full Stirling Enterprise Agreement — Master* Services Agreement + Order Form (from the quote) + Data Processing Addendum, one signature — then* signs it. The document body is served by the backend from the versioned legal registry (static- * legal copy, English only); this component renders it, gates signing behind a scroll-through, and- * captures the typed legal name, signatory, title, and authority. On sign it records the signature+ * legal copy, English only); this component renders it in full and captures the typed legal name,+ * signatory, title, and authority. On sign it records the signature* (pinned to the exact document version + a hash) and then accepts the quote into a subscription.- *- * Presented as the document itself rather than a card about it: this step names the agreement in the- * dialog's own header and carries its download there, so the terms are read on paper-like stock- * instead of in app chrome. That is why it draws its own header — see ProcurementFlow.+ * It draws its own header, which names the agreement and carries its download.*/export function ProcurementAgreement({quote,@@ -41,7 +44,7 @@ export function ProcurementAgreement({onAgree: () => void;/** Hand the buyer to their SE to negotiate terms: closes this and opens scheduling. */onRequestChanges: () => void;- /** This step draws the dialog's header, so it carries the close too. */+ /** This step draws its own header, so it carries the close too. */onClose?: () => void;}) {const { t } = useTranslation();@@ -51,12 +54,10 @@ export function ProcurementAgreement({const [signatory, setSignatory] = useState(quote.config.contactName ?? "");const [title, setTitle] = useState("");const [confirmed, setConfirmed] = useState(false);- const [scrolledToEnd, setScrolledToEnd] = useState(false);const [signing, setSigning] = useState(false);const [downloadingMsa, setDownloadingMsa] = useState(false);const [error, setError] = useState(false);const [downloadError, setDownloadError] = useState(false);- const docRef = useRef<HTMLDivElement>(null);const downloadMsa = async () => {setDownloadingMsa(true);@@ -80,20 +81,25 @@ export function ProcurementAgreement({}};- const onScroll = () => {- const el = docRef.current;- if (!el) return;- if (el.scrollTop + el.clientHeight >= el.scrollHeight - 24) {- setScrolledToEnd(true);+ // A signature is pinned to the document's version, so there is nothing to sign until it shows.+ const valid = {+ legalName: isFilled(legalName),+ signatory: isFilled(signatory),+ confirmed,+ };+ const ready = doc != null && Object.values(valid).every(Boolean);+ // Signing stays clickable once the document is in; a blocked click marks what is missing.+ const [tried, setTried] = useState(false);+ const required = t("portal.procurement.validation.required");+ const attemptSign = () => {+ if (!ready) {+ setTried(true);+ focusFirstInvalid();+ return;}+ void sign();};- const ready =- scrolledToEnd &&- confirmed &&- legalName.trim().length > 0 &&- signatory.trim().length > 0;-const sign = async () => {setError(false);setSigning(true);@@ -104,13 +110,12 @@ export function ProcurementAgreement({signatoryTitle: title.trim(),authorityConfirmed: confirmed,});- onAgree(); // proceed into the committed subscription+ onAgree();} catch {setError(true);} finally {// In `finally`, not only on failure: accepting can fail after the signature is recorded, and- // the controller deliberately keeps this dialog open on failure so the error is readable. With- // the flag left set, the button span the rest of the session and there was no way to retry.+ // the dialog stays open on failure, so the button must reset for a retry.setSigning(false);}};@@ -143,19 +148,7 @@ export function ProcurementAgreement({}/>- {/* The tray scrolls, not the paper. The paper is its natural height inside it, so mid-document it- runs flush to the footer with no grey beneath, and the tray's bottom padding only comes into- view once the buyer reaches the end — the page ending is what shows they got there. */}- {/* Focusable and named: signing is gated on scrolling to the end, so the- tray has to be scrollable by keyboard as well as pointer. */}- <div- className="portal-agreement__tray portal-agreement__scroll"- ref={docRef}- onScroll={onScroll}- tabIndex={0}- role="group"- aria-label={t("portal.procurement.agreement.docName")}- >+ <div className="portal-agreement__tray"><div className="portal-surface portal-agreement__doc">{loading && <p>{t("portal.procurement.agreement.loading")}</p>}{!loading && !doc && (@@ -196,17 +189,17 @@ export function ProcurementAgreement({</p>)}- {/* The signature block: who is bound, who signs, and the act of signing, on one line — the- shape of a paper signature block rather than a form above a button. The consent sits- directly under the fields it qualifies, with no rule between them: it is part of signing,- not a separate section, and boxing it cost the document a quarter of its height. */}+ {/* The signature block: who is bound, who signs, and the act of signing, on one line like a+ paper signature block. The consent sits directly under the fields it qualifies. */}<div className="portal-qb__foot portal-agreement__signbar"><div className="portal-agreement__signrow"><div className="portal-qb__row portal-agreement__signfields">- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.agreement.legalName")}- </span>+ <Field+ label={t("portal.procurement.agreement.legalName")}+ required+ invalid={tried && !valid.legalName}+ error={required}+ ><inputvalue={legalName}className={privateContentClassName}@@ -215,11 +208,13 @@ export function ProcurementAgreement({)}onChange={(e) => setLegalName(e.target.value)}/>- </label>- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.agreement.signatory")}- </span>+ </Field>+ <Field+ label={t("portal.procurement.agreement.signatory")}+ required+ invalid={tried && !valid.signatory}+ error={required}+ ><inputvalue={signatory}className={privateContentClassName}@@ -228,11 +223,8 @@ export function ProcurementAgreement({)}onChange={(e) => setSignatory(e.target.value)}/>- </label>- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.agreement.signatoryTitle")}- </span>+ </Field>+ <Field label={t("portal.procurement.agreement.signatoryTitle")}><inputvalue={title}className={privateContentClassName}@@ -241,35 +233,28 @@ export function ProcurementAgreement({)}onChange={(e) => setTitle(e.target.value)}/>- </label>+ </Field></div><Buttonvariant="primary"loading={busy || signing}- disabled={!ready}- onClick={sign}+ disabled={doc == null}+ onClick={attemptSign}>{t("portal.procurement.agreement.agreeCta")}</Button></div>- {/* Consent under the fields it qualifies; the gate's state under the button it gates, so the- reason signing is unavailable sits beside the unavailable thing. */}<div className="portal-agreement__signfoot">- <label className="portal-agreement__accept">- <input- type="checkbox"- checked={confirmed}- disabled={!scrolledToEnd}- onChange={(e) => setConfirmed(e.target.checked)}- />- <span>{t("portal.procurement.agreement.confirm")}</span>- </label>- {doc && !scrolledToEnd && (- <span className="portal-agreement__gate">- {t("portal.procurement.agreement.scrollHint")}- </span>- )}+ <ConsentCheckbox+ className="portal-agreement__accept"+ checked={confirmed}+ onChange={setConfirmed}+ invalid={tried && !confirmed}+ error={t("portal.procurement.validation.confirm")}+ >+ {t("portal.procurement.agreement.confirm")}+ </ConsentCheckbox></div></div></div>diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementBanner.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementBanner.tsxdeleted file mode 100644index 40dc57082f..0000000000--- a/frontend/src/processor/proprietary/components/procurement/ProcurementBanner.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { useUI } from "@processor/contexts/UIContext";-import { DealStatusHero } from "@processor/components/procurement/DealStatusHero";-import type { ProcurementController } from "@processor/components/procurement/useProcurement";--/**- * The deal-status hero and the dialogs must share the same controller instance.- */-export function ControlledDealStatusHero({- controller,- readOnly = false,-}: {- controller: ProcurementController;- readOnly?: boolean;-}) {- const { openSettings } = useUI();- if (!controller.data) return null;- return (- <DealStatusHero- snapshot={controller.data}- readOnly={readOnly}- busy={controller.busy}- canSchedule={controller.isLinked}- onExpand={() =>- // Exploring has no journey to expand into yet — its ask is to set the trial up.- controller.stage === "exploring"- ? controller.onStartTrial()- : controller.setOpen(true)- }- onAcceptQuote={() => void controller.onAcceptQuote()}- onLicense={() => controller.setExtra("license")}- onInvite={() => openSettings("users")}- onSchedule={() => controller.setExtra("schedule")}- onManageTrial={() => controller.setExtra("trial")}- onDocuments={() => controller.setExtra("documents")}- />- );-}diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementExtras.stories.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementExtras.stories.tsxindex 713bcc7559..06c32fc9a2 100644--- a/frontend/src/processor/proprietary/components/procurement/ProcurementExtras.stories.tsx+++ b/frontend/src/processor/proprietary/components/procurement/ProcurementExtras.stories.tsx@@ -1,76 +1,27 @@import type { Meta, StoryObj } from "@storybook/react-vite";-import type { ProcurementSnapshot } from "@processor/api/procurement";import {- LicenseModal,+ DocumentsList,ScheduleCallModal,- TrialSetupModal,- TrialManageModal,+ TrialSetupForm,} from "@processor/components/procurement/ProcurementExtras";import "@processor/views/Procurement.css";/**- * The small centred dialogs that hang off the deal-status hero's quick actions: the licence key,- * schedule-a-call, trial setup, and trial management. Grouped in one story file since none is- * substantial enough to warrant its own.+ * The Enterprise page's pieces outside the journey's stages: the trial setup form, the documents+ * list and booking a call. One file, since none is big enough for its own.*/const meta: Meta = {title: "Portal/Procurement/ProcurementExtras",- parameters: { layout: "fullscreen" },+ parameters: { layout: "padded" },};export default meta;type Story = StoryObj;-const SNAPSHOT: ProcurementSnapshot = {- dealId: 42,- stage: "trial",- deployment: "cloud",- seats: 12,- trialStartedAt: "2026-06-15T00:00:00Z",- trialEndsAt: "2026-07-29T00:00:00Z",- trialExtensionsUsed: 0,- licensed: false,- licenseKey: null,- agreementSignedVersion: null,- businessName: null,- contactName: null,- contactEmail: null,- latestQuote: null,-};--// Licence key with the offline add-on available.-export const License: Story = {- render: () => (- <LicenseModal- open- onClose={() => {}}- licenseKey="MOCK-ENTERPRISE-KEY-0001"- offlineAvailable- downloadingLicense={false}- onDownloadOffline={() => {}}- />- ),-};--// Still on the trial licence: warns that the offline file must be re-downloaded once the-// agreement is in place.-export const LicenseTrial: Story = {- render: () => (- <LicenseModal- open- onClose={() => {}}- licenseKey="MOCK-TRIAL-KEY-0001"- offlineAvailable- downloadingLicense={false}- onDownloadOffline={() => {}}- trial- />- ),-};-// Calendly's widget.js can't reach the network in Storybook, so this renders the// "unable to load" fallback link rather than the live embed.export const ScheduleCall: Story = {+ parameters: { layout: "fullscreen" },render: () => (<ScheduleCallModal open onClose={() => {}} email="[email protected]" />),@@ -79,40 +30,22 @@ export const ScheduleCall: Story = {// Two steps before the trial starts: how they'll run it, then who is buying.export const TrialSetup: Story = {render: () => (- <TrialSetupModal- open- onClose={() => {}}+ <TrialSetupFormbusy={false}+ email="[email protected]"onScheduleCall={() => {}}onConfirm={() => {}}/>),};-// Trial in progress with extensions still available.-export const TrialManage: Story = {- render: () => (- <TrialManageModal- open- onClose={() => {}}- snapshot={SNAPSHOT}- busy={false}- onExtend={() => {}}- onCancel={() => {}}- />- ),-};--// Both extensions used: the extend action is disabled in favour of a "contact us" message.-export const TrialManageMaxed: Story = {+// Before a quote is issued: only the reference documents are available.+export const Documents: Story = {render: () => (- <TrialManageModal- open- onClose={() => {}}- snapshot={{ ...SNAPSHOT, trialExtensionsUsed: 2 }}- busy={false}- onExtend={() => {}}- onCancel={() => {}}+ <DocumentsList+ onDownloadAgreement={() => {}}+ quoteAvailable={false}+ onDownloadQuote={() => {}}/>),};diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementExtras.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementExtras.tsxindex aadcca2fa1..df0832219e 100644--- a/frontend/src/processor/proprietary/components/procurement/ProcurementExtras.tsx+++ b/frontend/src/processor/proprietary/components/procurement/ProcurementExtras.tsx@@ -4,28 +4,35 @@ import Markdown from "react-markdown";import remarkGfm from "remark-gfm";import { Button } from "@editor/ui";import {+ DEPLOYMENTS,fetchLegalDocument,- recordLegalConsent,- type ProcurementSnapshot,type TrialSetupDetails,} from "@processor/api/procurement";import { StepModalHeader } from "@processor/components/shared/StepModalHeader";import { CalendlyInline } from "@processor/components/procurement/CalendlyInline";-import { LicensePanel } from "@processor/components/procurement/ProcurementStages";import { FlowModal } from "@processor/components/shared/FlowModal";import { useAsync } from "@processor/hooks/useAsync";+import type { TrialDraft } from "@processor/components/procurement/trialDraft";+import { useProcurementPrefill } from "@processor/components/procurement/prefill";import { openApiUrl } from "@processor/api/externalUrl";import "@processor/views/Procurement.css";import { privateContentClassName } from "@editor/components/shared/privateContentClassName";+import {+ ConsentCheckbox,+ emailFieldError,+ Field,+ FieldGroup,+ focusFirstInvalid,+ isEmail,+ isFilled,+ OptionCard,+} from "@processor/components/procurement/formField";/**- * Small centred dialogs that hang off the deal-status hero's quick actions — the licence key,- * schedule a call, trial management, and trial setup. Schedule a call embeds the live Calendly- * scheduler. The shells and wiring are real so the hero behaves like the marketing prototype.+ * Pieces of the Enterprise page that stand apart from the journey's stages: the trial setup form,+ * the deal's documents, booking a call, and the legal-document reader.*/-const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;-function SideModal({open,onClose,@@ -118,12 +125,9 @@ export function LegalDocumentModal({* The deal's paperwork in one place, reachable throughout the journey (not tied to the current* stage): the enterprise agreement, the quote, the invoice, and the reference documents (EULA, SLA* exhibit, subprocessors). Each row downloads or views the real artifact when it's available, and- * reads as "available later" until then. The per-stage download buttons remain the primary path;- * this is the secondary, always-on reference.+ * reads as "available later" until then.*/-export function DocumentsModal({- open,- onClose,+export function DocumentsList({agreementVersion,downloadingAgreement,onDownloadAgreement,@@ -134,13 +138,11 @@ export function DocumentsModal({invoiceUrl,invoicePdf,}: {- open: boolean;- onClose: () => void;agreementVersion?: string | null;downloadingAgreement?: boolean;onDownloadAgreement: () => void;- /** Jump to the agreement/sign stage in the flow (used before it's signed). */- onViewAgreement: () => void;+ /** Open the agreement to read and sign; omitted where the viewer cannot act on it. */+ onViewAgreement?: () => void;quoteAvailable: boolean;downloadingQuote?: boolean;onDownloadQuote: () => void;@@ -151,107 +153,113 @@ export function DocumentsModal({const [legalDoc, setLegalDoc] = useState<string | null>(null);const invoice = invoiceUrl || invoicePdf || null;+ const docs: DocEntry[] = [+ {+ name: t("portal.procurement.documents.agreement"),+ sub: agreementVersion ?? t("portal.procurement.documents.agreementSub"),+ action: agreementVersion+ ? {+ label: t("portal.procurement.documents.download"),+ onClick: onDownloadAgreement,+ loading: downloadingAgreement,+ }+ : quoteAvailable && onViewAgreement+ ? {+ label: t("portal.procurement.documents.view"),+ onClick: onViewAgreement,+ }+ : {+ // With a quote issued, the agreement waits on accepting it, not on the quote.+ unavailable: quoteAvailable+ ? t("portal.procurement.documents.laterInvoice")+ : t("portal.procurement.documents.laterQuote"),+ },+ },+ {+ name: t("portal.procurement.documents.quote"),+ sub: t("portal.procurement.documents.quoteSub"),+ action: quoteAvailable+ ? {+ label: t("portal.procurement.documents.download"),+ onClick: onDownloadQuote,+ loading: downloadingQuote,+ }+ : { unavailable: t("portal.procurement.documents.laterQuote") },+ },+ {+ name: t("portal.procurement.documents.invoice"),+ sub: t("portal.procurement.documents.invoiceSub"),+ action: invoice+ ? {+ label: t("portal.procurement.documents.view"),+ onClick: () => openApiUrl(invoice),+ }+ : // Issued on signing, which comes after accepting the quote.+ { unavailable: t("portal.procurement.documents.laterSigning") },+ },+ {+ name: t("portal.procurement.documents.eula"),+ sub: t("portal.procurement.documents.eulaSub"),+ action: {+ label: t("portal.procurement.documents.view"),+ onClick: () => setLegalDoc("eula"),+ },+ },+ {+ name: t("portal.procurement.documents.sla"),+ sub: t("portal.procurement.documents.slaSub"),+ action: {+ label: t("portal.procurement.documents.view"),+ onClick: () => setLegalDoc("sla"),+ },+ },+ {+ name: t("portal.procurement.documents.subprocessors"),+ sub: t("portal.procurement.documents.subprocessorsSub"),+ action: {+ label: t("portal.procurement.documents.view"),+ onClick: () => setLegalDoc("subprocessors"),+ },+ },+ ];+ // What can be opened now leads; what the deal has yet to produce follows, quieter.+ const ready = docs.filter((d) => !("unavailable" in d.action));+ const later = docs.filter((d) => "unavailable" in d.action);+return (<>- <SideModal- open={open}- onClose={onClose}- title={t("portal.procurement.documents.title")}- subtitle={t("portal.procurement.documents.subtitle")}- >- <ul className="portal-docmodal">- <DocItem- name={t("portal.procurement.documents.agreement")}- sub={- agreementVersion ?? t("portal.procurement.documents.agreementSub")- }- action={- agreementVersion- ? {- label: t("portal.procurement.documents.download"),- onClick: onDownloadAgreement,- loading: downloadingAgreement,- }- : quoteAvailable- ? {- label: t("portal.procurement.documents.view"),- onClick: onViewAgreement,- }- : {- unavailable: t("portal.procurement.documents.laterQuote"),- }- }- />- <DocItem- name={t("portal.procurement.documents.quote")}- sub={t("portal.procurement.documents.quoteSub")}- action={- quoteAvailable- ? {- label: t("portal.procurement.documents.download"),- onClick: onDownloadQuote,- loading: downloadingQuote,- }- : { unavailable: t("portal.procurement.documents.laterQuote") }- }- />- <DocItem- name={t("portal.procurement.documents.invoice")}- sub={t("portal.procurement.documents.invoiceSub")}- action={- invoice- ? {- label: t("portal.procurement.documents.view"),- onClick: () => openApiUrl(invoice),- }- : {- unavailable: t("portal.procurement.documents.laterInvoice"),- }- }- />- <DocItem- name={t("portal.procurement.documents.eula")}- sub={t("portal.procurement.documents.eulaSub")}- action={{- label: t("portal.procurement.documents.view"),- onClick: () => setLegalDoc("eula"),- }}- />- <DocItem- name={t("portal.procurement.documents.sla")}- sub={t("portal.procurement.documents.slaSub")}- action={{- label: t("portal.procurement.documents.view"),- onClick: () => setLegalDoc("sla"),- }}- />- <DocItem- name={t("portal.procurement.documents.subprocessors")}- sub={t("portal.procurement.documents.subprocessorsSub")}- action={{- label: t("portal.procurement.documents.view"),- onClick: () => setLegalDoc("subprocessors"),- }}- />- </ul>- </SideModal>+ <ul className="portal-docmodal">+ {ready.map((d) => (+ <DocItem key={d.name} {...d} />+ ))}+ </ul>+ {later.length > 0 && (+ <>+ <h3 className="portal-docmodal__group">+ {t("portal.procurement.documents.laterTitle", "Later in your deal")}+ </h3>+ <ul className="portal-docmodal portal-docmodal--later">+ {later.map((d) => (+ <DocItem key={d.name} {...d} />+ ))}+ </ul>+ </>+ )}<LegalDocumentModal docId={legalDoc} onClose={() => setLegalDoc(null)} /></>);}-/** One row in the Documents list: name + sub on the left, an action button or a muted note. */-function DocItem({- name,- sub,- action,-}: {+interface DocEntry {name: string;sub: string;action:| { label: string; onClick: () => void; loading?: boolean }| { unavailable: string };-}) {+}++/** One row in the Documents list: name + sub on the left, an action button or a muted note. */+function DocItem({ name, sub, action }: DocEntry) {return (<li className="portal-docmodal__row"><div className="portal-docmodal__text">@@ -273,49 +281,6 @@ function DocItem({);}-// ── Licence key ──────────────────────────────────────────────────────────────-export function LicenseModal({- open,- onClose,- licenseKey,- offlineAvailable,- downloadingLicense,- onDownloadOffline,- trial = false,-}: {- open: boolean;- onClose: () => void;- licenseKey: string;- offlineAvailable: boolean;- downloadingLicense: boolean;- onDownloadOffline: () => void;- /** Licence is still the trial one (not yet upgraded on accept) — the downloadable .lic is a- * snapshot, so warn that it must be re-downloaded once the agreement is in place. */- trial?: boolean;-}) {- const { t } = useTranslation();- return (- <SideModal- open={open}- onClose={onClose}- title={t("portal.procurement.license.title")}- subtitle={t("portal.procurement.license.subtitle")}- >- <LicensePanel- licenseKey={licenseKey}- offlineAvailable={offlineAvailable}- downloadingLicense={downloadingLicense}- onDownloadOffline={onDownloadOffline}- />- {offlineAvailable && trial && (- <p className="portal-proc__license-hint">- {t("portal.procurement.license.trialFileHint")}- </p>- )}- </SideModal>- );-}-// ── Schedule a call ──────────────────────────────────────────────────────────export function ScheduleCallModal({open,@@ -342,27 +307,28 @@ export function ScheduleCallModal({}// ── Trial setup ────────────────────────────────────────────────────────────-const DEPLOYMENTS = ["cloud", "selfhost", "airgap"] as const;/*** Captured before the trial starts: where the buyer will run Stirling (which drives the deployment* fee and, for air-gapped, the offline licence) and their team size. Both seed the quote builder so* it opens on their real environment; the trial only begins once this is confirmed.*/-export function TrialSetupModal({- open,- onClose,+export function TrialSetupForm({busy,email,+ initial,+ startLabel,onScheduleCall,onConfirm,}: {- open: boolean;- onClose: () => void;busy: boolean;+ /** Answers given before a sign-in detour; the form reopens on its last step with them. */+ initial?: TrialDraft | null;+ /** Replaces "Start trial" where confirming leads somewhere else first, such as sign-in. */+ startLabel?: string;/** Linked-account email, prefilled as the work email on the details step. */- email?: string;- /** Open the scheduler — the step-1 escape hatch for buyers who want to talk first. */+ email?: string | null;+ /** The step-1 escape hatch for buyers who want to talk first. */onScheduleCall: () => void;onConfirm: (deployment: string,@@ -371,39 +337,55 @@ export function TrialSetupModal({) => void;}) {const { t } = useTranslation();- const [step, setStep] = useState(0);- const [deployment, setDeployment] = useState<string>("cloud");- const [seats, setSeats] = useState("");- const [contactName, setContactName] = useState("");- const [businessName, setBusinessName] = useState("");- const [contactEmail, setContactEmail] = useState("");- const [inviteEmails, setInviteEmails] = useState("");+ const prefill = useProcurementPrefill();+ const [step, setStep] = useState(initial ? 1 : 0);+ const [deployment, setDeployment] = useState<string>(+ initial?.deployment ?? "cloud",+ );+ const [seats, setSeats] = useState(+ initial ? String(initial.seats) : String(prefill?.seats ?? ""),+ );+ const [contactName, setContactName] = useState(+ initial?.details.contactName ?? prefill?.contactName ?? "",+ );+ const [businessName, setBusinessName] = useState(+ initial?.details.businessName ?? prefill?.businessName ?? "",+ );+ const [contactEmail, setContactEmail] = useState(+ initial?.details.contactEmail || email || prefill?.contactEmail || "",+ );+ const [inviteEmails, setInviteEmails] = useState(+ initial?.details.inviteEmails ?? "",+ );const [eula, setEula] = useState(false);const [legalDoc, setLegalDoc] = useState<string | null>(null);- // Reset to defaults each time the dialog opens, so a cancelled setup doesn't linger.+ // The linked email can arrive after the form mounts; fill it in unless the buyer typed their own.useEffect(() => {- if (open) {- setStep(0);- setDeployment("cloud");- setSeats("");- setContactName("");- setBusinessName("");- setContactEmail(email ?? "");- setInviteEmails("");- setEula(false);- }- }, [open, email]);+ if (email) setContactEmail((current) => current || email);+ }, [email]);// The buying entity is what the quote and agreement are drawn against, so it is required here// rather than deferred to the quote; invites are genuinely optional.- const detailsValid =- contactName.trim().length > 0 &&- businessName.trim().length > 0 &&- EMAIL_RE.test(contactEmail.trim());+ const seatsValid = Number(seats) > 0;+ const valid = {+ contactName: isFilled(contactName),+ businessName: isFilled(businessName),+ contactEmail: isEmail(contactEmail),+ };+ const detailsValid = Object.values(valid).every(Boolean);+ // Errors wait for an attempt to move on, except a mistyped email, which shows on leaving the field.+ const [triedSeats, setTriedSeats] = useState(false);+ const [triedStart, setTriedStart] = useState(false);+ const [emailTouched, setEmailTouched] = useState(false);+ const required = t("portal.procurement.validation.required");+ const emailError = emailFieldError(+ contactEmail,+ { tried: triedStart, touched: emailTouched },+ { required, invalid: t("portal.procurement.validation.email") },+ );const confirm = () => {- void recordLegalConsent("eula", "trial"); // clickwrap consent, best-effortonConfirm(deployment, Math.max(0, Number(seats) || 0), {businessName: businessName.trim(),contactName: contactName.trim(),@@ -412,244 +394,176 @@ export function TrialSetupModal({});};+ const continueToDetails = () => {+ if (!seatsValid) {+ setTriedSeats(true);+ focusFirstInvalid();+ return;+ }+ setStep(1);+ };+ const start = () => {+ if (!detailsValid || !eula) {+ setTriedStart(true);+ focusFirstInvalid();+ return;+ }+ confirm();+ };+return (- <>- <SideModal- open={open}- onClose={onClose}+ <div className="portal-setup">+ <StepModalHeadertitle={t("portal.procurement.setup.title")}subtitle={t(step === 0? "portal.procurement.setup.subtitle": "portal.procurement.setup.subtitleDetails",)}- headerAside={- <span className="portal-stepmodal__step">- {t("portal.procurement.setup.stepOf", { n: step + 1, total: 2 })}- </span>- }- footer={- step === 0 ? (- <>- <span className="portal-sidemodal__foot-hint">- {t("portal.procurement.setup.talkFirst")}{" "}- <button- type="button"- className="portal-legal__link"- onClick={onScheduleCall}- >- {t("portal.procurement.setup.scheduleCall")}- </button>- </span>- <Button- variant="primary"- disabled={Number(seats) <= 0}- onClick={() => setStep(1)}- >- {t("portal.procurement.setup.continue")}- </Button>- </>- ) : (- <>- <Button variant="secondary" onClick={() => setStep(0)}>- {t("portal.procurement.setup.back")}- </Button>- <Button- variant="primary"- loading={busy}- disabled={!eula || !detailsValid}- onClick={confirm}- >- {t("portal.procurement.setup.start")}- </Button>- </>- )- }- >- <StepModalHeader step={step + 1} total={2} />-- {step === 0 && (- <>- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.setup.seats")}- </span>- <input- type="number"- min={0}- placeholder={t("portal.procurement.setup.seatsPlaceholder")}- value={seats}- onChange={(e) => setSeats(e.target.value)}- />- </label>- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.setup.deployment")}- </span>- <div className="portal-qb__opts portal-qb__opts--across">- {DEPLOYMENTS.map((d) => (- <button- key={d}- type="button"- className="portal-qb__opt"- data-on={deployment === d || undefined}- onClick={() => setDeployment(d)}- >- <span className="portal-qb__opt-title">- {t(`portal.procurement.setup.${d}`)}- </span>- <span className="portal-qb__opt-sub">- {t(`portal.procurement.setup.${d}Sub`)}- </span>- </button>- ))}- </div>- </label>- </>- )}+ step={step + 1}+ total={2}+ stepLabel={t("portal.procurement.setup.stepOf", {+ n: step + 1,+ total: 2,+ })}+ />- {step === 1 && (- <>- <div className="portal-qb__row">- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.setup.fullName")}- </span>- <input- value={contactName}- className={privateContentClassName}- placeholder={t(- "portal.procurement.setup.fullNamePlaceholder",- )}- onChange={(e) => setContactName(e.target.value)}- />- </label>- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.setup.businessName")}- </span>- <input- value={businessName}- className={privateContentClassName}- placeholder={t(- "portal.procurement.setup.businessNamePlaceholder",- )}- onChange={(e) => setBusinessName(e.target.value)}+ {step === 0 && (+ <>+ <Field+ label={t("portal.procurement.setup.seats")}+ required+ invalid={triedSeats && !seatsValid}+ error={t("portal.procurement.validation.seats")}+ >+ <input+ type="number"+ min={0}+ required+ placeholder={t("portal.procurement.setup.seatsPlaceholder")}+ value={seats}+ onChange={(e) => setSeats(e.target.value)}+ />+ </Field>+ <FieldGroup label={t("portal.procurement.setup.deployment")}>+ <div className="portal-qb__opts portal-qb__opts--across">+ {DEPLOYMENTS.map((d) => (+ <OptionCard+ key={d}+ on={deployment === d}+ title={t(`portal.procurement.setup.${d}`)}+ sub={t(`portal.procurement.setup.${d}Sub`)}+ onClick={() => setDeployment(d)}/>- </label>+ ))}</div>- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.setup.workEmail")}- </span>+ </FieldGroup>+ </>+ )}++ {step === 1 && (+ <>+ <div className="portal-qb__row">+ <Field+ label={t("portal.procurement.setup.fullName")}+ required+ invalid={triedStart && !valid.contactName}+ error={required}+ ><input- type="email"- value={contactEmail}+ value={contactName}className={privateContentClassName}- placeholder={t("portal.procurement.setup.workEmailPlaceholder")}- onChange={(e) => setContactEmail(e.target.value)}+ placeholder={t("portal.procurement.setup.fullNamePlaceholder")}+ onChange={(e) => setContactName(e.target.value)}/>- </label>- <label className="portal-qb__field">- <span className="portal-qb__field-label">- {t("portal.procurement.setup.invites")}- </span>+ </Field>+ <Field+ label={t("portal.procurement.setup.businessName")}+ required+ invalid={triedStart && !valid.businessName}+ error={required}+ ><input- value={inviteEmails}+ value={businessName}className={privateContentClassName}- placeholder={t("portal.procurement.setup.invitesPlaceholder")}- onChange={(e) => setInviteEmails(e.target.value)}+ placeholder={t(+ "portal.procurement.setup.businessNamePlaceholder",+ )}+ onChange={(e) => setBusinessName(e.target.value)}/>- </label>+ </Field>+ </div>+ <Field+ label={t("portal.procurement.setup.workEmail")}+ required+ invalid={emailError != null}+ error={emailError ?? undefined}+ >+ <input+ type="email"+ value={contactEmail}+ className={privateContentClassName}+ placeholder={t("portal.procurement.setup.workEmailPlaceholder")}+ onChange={(e) => setContactEmail(e.target.value)}+ onBlur={() => setEmailTouched(true)}+ />+ </Field>+ <Field label={t("portal.procurement.setup.invites")}>+ <input+ value={inviteEmails}+ className={privateContentClassName}+ placeholder={t("portal.procurement.setup.invitesPlaceholder")}+ onChange={(e) => setInviteEmails(e.target.value)}+ />+ </Field>- <label className="portal-qb__eula">- <input- type="checkbox"- checked={eula}- onChange={(e) => setEula(e.target.checked)}- />- <span>- {t("portal.procurement.setup.eula")}{" "}- <button- type="button"- className="portal-legal__link"- onClick={() => setLegalDoc("eula")}- >- {t("portal.procurement.setup.viewEula")}- </button>- </span>- </label>+ <ConsentCheckbox+ checked={eula}+ onChange={setEula}+ invalid={triedStart && !eula}+ error={t("portal.procurement.validation.eula")}+ >+ {t("portal.procurement.setup.eula")}{" "}+ <button+ type="button"+ className="portal-legal__link"+ onClick={() => setLegalDoc("eula")}+ >+ {t("portal.procurement.setup.viewEula")}+ </button>+ </ConsentCheckbox>+ </>+ )}++ <div className="portal-setup__foot">+ {step === 0 ? (+ <>+ <span className="portal-sidemodal__foot-hint">+ {t("portal.procurement.setup.talkFirst")}{" "}+ <button+ type="button"+ className="portal-legal__link"+ onClick={onScheduleCall}+ >+ {t("portal.procurement.setup.scheduleCall")}+ </button>+ </span>+ <Button variant="primary" onClick={continueToDetails}>+ {t("portal.procurement.setup.continue")}+ </Button>+ </>+ ) : (+ <>+ <Button variant="secondary" onClick={() => setStep(0)}>+ {t("portal.procurement.setup.back")}+ </Button>+ <Button variant="primary" loading={busy} onClick={start}>+ {startLabel ?? t("portal.procurement.setup.start")}+ </Button></>)}- </SideModal>+ </div><LegalDocumentModal docId={legalDoc} onClose={() => setLegalDoc(null)} />- </>- );-}--// ── Trial management ─────────────────────────────────────────────────────────-export function TrialManageModal({- open,- onClose,- snapshot,- busy,- onExtend,- onCancel,-}: {- open: boolean;- onClose: () => void;- snapshot: ProcurementSnapshot;- busy: boolean;- onExtend: () => void;- onCancel: () => void;-}) {- const { t } = useTranslation();- const ends = snapshot.trialEndsAt- ? new Date(snapshot.trialEndsAt).toLocaleDateString(undefined, {- month: "long",- day: "numeric",- year: "numeric",- })- : "";- const maxed = snapshot.trialExtensionsUsed >= 2;- return (- <SideModal- open={open}- onClose={onClose}- title={t("portal.procurement.trial.title")}- subtitle={- ends- ? t("portal.procurement.trial.subtitle", { date: ends })- : undefined- }- footer={- <>- <button- type="button"- className="portal-sidemodal__ghost"- onClick={onCancel}- disabled={busy}- >- {t("portal.procurement.trial.cancel")}- </button>- <Button- variant="primary"- loading={busy}- disabled={maxed}- onClick={onExtend}- >- {maxed- ? t("portal.procurement.trial.maxed")- : t("portal.procurement.trial.extend")}- </Button>- </>- }- >- <p className="portal-sidemodal__text">- {maxed- ? t("portal.procurement.trial.bodyMaxed")- : t("portal.procurement.trial.body")}- </p>- </SideModal>+ </div>);}diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.stories.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.stories.tsxindex 5159149e7b..413f9dd182 100644--- a/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.stories.tsx+++ b/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.stories.tsx@@ -6,6 +6,7 @@ import type {QuoteResult,} from "@processor/api/procurement";import "@processor/views/Procurement.css";+import { RATE_CARD } from "@processor/mocks/handlers/procurementSaas";const quote: QuoteResult = {quoteId: 488,@@ -64,6 +65,10 @@ const snapshot: ProcurementSnapshot = {contactName: null,contactEmail: null,latestQuote: quote,+ rateCard: RATE_CARD,+ maxTrialExtensions: 2,+ minAnnualNetMinor: 0,+ entitledDeployment: null,};/** Builds a fully-populated controller so callers only need to override the fields a story cares about. */@@ -93,10 +98,8 @@ function makeController(extra: null,setExtra: () => {},invoicePdf: null,- onStartTrial: () => {},onConfirmSetup: () => {},onExtendTrial: () => {},- onReset: () => {},onGenerate: async () => {},onAgree: () => {},onDownloadPdf: async () => {},@@ -110,8 +113,8 @@ function makeController(}/**- * The procurement takeover flow: quote & agreement, payment, and live stages, driven by a- * plain ProcurementController object (no live backend needed to render each stage).+ * The Enterprise page's takeover: the quote builder and the agreement, driven by a plain+ * ProcurementController object (no live backend needed to render each step).*/const meta: Meta<typeof ProcurementFlow> = {title: "Portal/Procurement/ProcurementFlow",@@ -127,30 +130,12 @@ export const Default: Story = {args: { controller: makeController() },};-// No linked account yet: the modal shows the "link your account" empty state.-export const Unlinked: Story = {+// Quote accepted: the agreement to read and sign.+export const Agreement: Story = {args: {controller: makeController({- isLinked: false,- data: null,- started: false,- stage: undefined,- latest: null,- isIssued: false,- isDraft: true,- }),- },-};--// Snapshot still loading: the skeleton placeholder shows instead of a stage.-export const Loading: Story = {- args: {- controller: makeController({- loading: true,- data: null,- started: false,- stage: undefined,- latest: null,+ data: { ...snapshot, stage: "security" },+ stage: "security",}),},};diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.test.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.test.tsxdeleted file mode 100644index 05bd447d14..0000000000--- a/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.test.tsx+++ /dev/null@@ -1,71 +0,0 @@-import { useState } from "react";-import { MemoryRouter } from "react-router-dom";-import { render, screen, fireEvent, waitFor } from "@testing-library/react";-import { it, expect, vi } from "vitest";-import { MantineProvider } from "@mantine/core";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { UIProvider, useUI } from "@editor/portal/contexts/UIContext";-import { LinkProvider } from "@editor/portal/contexts/LinkContext";-import { ProcurementFlow } from "@editor/portal/components/procurement/ProcurementFlow";-import { useProcurement } from "@editor/portal/components/procurement/useProcurement";-import { LinkAccountModal } from "@editor/portal/components/account-link/LinkAccountModal";-vi.mock("react-i18next", () => ({- useTranslation: () => ({- t: (key: string, fallback?: string) => fallback ?? key,- i18n: { language: "en-US" },- }),-}));-vi.mock("@editor/portal/hooks/useLinkedAccountEmail", () => ({- useLinkedAccountEmail: () => null,-}));-vi.mock("@editor/portal/hooks/useConnectHandoff", () => ({- useConnectHandoff: () => ({ busy: false, error: null, begin: vi.fn() }),-}));-function Flow() {- const controller = useProcurement();- const [open, setOpen] = useState(true);- const ui = useUI();- return (- <>- <ProcurementFlow controller={{ ...controller, open, setOpen }} />- {ui.linkModalOpen && (- <LinkAccountModal- open- mode={ui.linkModalMode}- onClose={ui.closeLinkModal}- />- )}- </>- );-}-it("suspends procurement while connecting and returns to its next action on dismissal", async () => {- render(- <MantineProvider>- <QueryClientProvider- client={- new QueryClient({ defaultOptions: { queries: { retry: false } } })- }- >- <LinkProvider initialState="unlinked">- <UIProvider>- <MemoryRouter>- <Flow />- </MemoryRouter>- </UIProvider>- </LinkProvider>- </QueryClientProvider>- </MantineProvider>,- );- fireEvent.click(- screen.getByRole("button", { name: "portal.procurement.link.cta" }),- );- await waitFor(() => expect(screen.getAllByRole("dialog")).toHaveLength(1));- expect(- screen.getByRole("dialog", { name: "Connect your Stirling account" }),- ).toBeVisible();- fireEvent.click(screen.getByRole("button", { name: "Not now" }));- await waitFor(() => expect(screen.getAllByRole("dialog")).toHaveLength(1));- expect(- screen.getByRole("button", { name: "portal.procurement.link.cta" }),- ).toBeVisible();-});diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.tsxindex db7006e4dc..7c42518f0b 100644--- a/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.tsx+++ b/frontend/src/processor/proprietary/components/procurement/ProcurementFlow.tsx@@ -1,28 +1,30 @@import { useTranslation } from "react-i18next";-import { Banner, Button, EmptyState, Skeleton } from "@editor/ui";-import { useUI } from "@editor/portal/contexts/UIContext";-import { useLinkedAccountEmail } from "@editor/portal/hooks/useLinkedAccountEmail";-import { ProcurementAgreement } from "@editor/portal/components/procurement/ProcurementAgreement";-import {- DocumentsModal,- LicenseModal,- ScheduleCallModal,- TrialManageModal,- TrialSetupModal,-} from "@editor/portal/components/procurement/ProcurementExtras";-import { ProcurementModal } from "@editor/portal/components/procurement/ProcurementModal";-import {- LiveStageCard,- PaymentStageCard,-} from "@editor/portal/components/procurement/ProcurementStages";-import { QuoteBuilder } from "@editor/portal/components/procurement/QuoteBuilder";-import type { ProcurementController } from "@editor/portal/components/procurement/useProcurement";+import { Banner } from "@editor/ui";+import { COMPARE_PLANS_ANCHOR } from "@editor/billing/compareAnchor";+import { useUI } from "@processor/contexts/UIContext";+import { useLinkedAccountEmail } from "@processor/hooks/useLinkedAccountEmail";+import { ProcurementAgreement } from "@processor/components/procurement/ProcurementAgreement";+import { ScheduleCallModal } from "@processor/components/procurement/ProcurementExtras";+import { QuoteBuilder } from "@processor/components/procurement/QuoteBuilder";+import type { ProcurementController } from "@processor/components/procurement/useProcurement";++/** Which long step, if any, the deal is on: building its quote or signing its agreement. */+export function procurementFlowStep(+ controller: ProcurementController,+): "builder" | "agreement" | null {+ const { started, stage, editing, latest } = controller;+ // The builder spans the whole quote stage, not just the draft part of it: issuing turns its last+ // step into the review of the issued paper rather than handing off to a separate card.+ if (started && (editing || stage === "trial" || stage === "quote"))+ return "builder";+ if (started && !editing && stage === "security" && latest != null)+ return "agreement";+ return null;+}/**- * The procurement takeover flow: the full-screen journey modal (quote builder →- * quote & agreement → payment → live) plus the licence-key, schedule-call, trial-setup,- * and trial-management modals. Driven entirely by a shared ProcurementController- * so it can sit alongside the deal-status section in Usage & Billing.+ * The journey's two long steps, building a quote and signing the agreement, shown within the deal+ * at their stage. Booking a call opens here too: the agreement's "request changes" leads to it.*/export function ProcurementFlow({controller,@@ -30,206 +32,95 @@ export function ProcurementFlow({controller: ProcurementController;}) {const { t } = useTranslation();- const { openLinkModal, linkModalOpen } = useUI();const scheduleEmail = useLinkedAccountEmail();+ const { openSettings } = useUI();const {- isLinked,- loading,data,- started,- stage,latest,isIssued,busy,downloading,- downloadingLicense,error,setError,open,setOpen,editing,- setEditing,extra,setExtra,- invoicePdf,- onConfirmSetup,- onExtendTrial,- onReset,onGenerate,onAgree,onDownloadPdf,- onDownloadOfflineLicense,- downloadingAgreement,- onDownloadSignedAgreement,} = controller;- // The builder owns the dialog's chrome while it is the visible step. It spans the whole quote- // stage now, not just the draft part of it: issuing turns its last step into the review of the- // issued paper rather than handing off to a separate card.- const builderShowing =- isLinked && started && (editing || stage === "trial" || stage === "quote");- const agreementShowing =- isLinked && started && !editing && stage === "security" && latest != null;- // Both of these name their own document in the header and carry its download there, so the shell- // must not stack a second header (nor a second close) above them.- const ownsHeader = builderShowing || agreementShowing;+ const step = procurementFlowStep(controller);+ const builderShowing = step === "builder";+ const agreementShowing = step === "agreement";return (<>- <ProcurementModal- open={open && !linkModalOpen}- onClose={() => setOpen(false)}- title={t("portal.procurement.title")}- subtitle={t("portal.procurement.subtitle")}- // The builder and the agreement render their own heading and close; the payment and live- // steps have none, so they keep the shell's header.- headerless={ownsHeader}- >- {error && (- <Banner- tone="danger"- title={t("portal.procurement.error.title")}- onDismiss={() => setError(null)}- >- {error}- </Banner>- )}-- {!isLinked && (- <EmptyState- eyebrow={t("portal.procurement.link.eyebrow")}- title={t("portal.procurement.link.title")}- description={t("portal.procurement.link.description")}- actions={- <Button variant="primary" onClick={() => openLinkModal()}>- {t("portal.procurement.link.cta")}- </Button>- }- />- )}-- {isLinked && (loading || !started) && <Skeleton height="10rem" />}-- {isLinked && started && (- <>- {builderShowing && (- <QuoteBuilder- deployment={data?.deployment ?? "cloud"}- seats={data?.seats ?? 0}- email={scheduleEmail}- dealDetails={- data- ? {- businessName: data.businessName,- contactName: data.contactName,- contactEmail: data.contactEmail,- }- : undefined- }- initial={latest?.config}- eulaAlreadyAgreed={data?.trialStartedAt != null}- onClose={() => setOpen(false)}- onGenerate={onGenerate}- // Null while re-editing: the buyer asked for the form, not the paper they just left.- issued={!editing && isIssued ? latest : null}- downloading={downloading}- onDownload={onDownloadPdf}- />- )}-- {/* Agreement step: review and sign the enterprise agreement. Signing accepts the quote- into a committed subscription (Stripe). */}- {agreementShowing && latest && (- <ProcurementAgreement- quote={latest}- busy={busy}- onAgree={onAgree}- onRequestChanges={() => {- setOpen(false);- setExtra("schedule");- }}- onClose={() => setOpen(false)}- />- )}-- {!editing && stage === "procurement" && latest && (- <PaymentStageCard- invoiceUrl={latest.invoiceUrl}- invoicePdf={latest.invoicePdf ?? invoicePdf}- signedAgreementVersion={data?.agreementSignedVersion}- downloadingAgreement={downloadingAgreement}- onDownloadSignedAgreement={onDownloadSignedAgreement}- />- )}+ {open && step && (+ <section+ className="portal-procflow"+ aria-label={t("portal.procurement.title")}+ >+ {error && (+ <Banner+ tone="danger"+ title={t("portal.procurement.error.title")}+ onDismiss={() => setError(null)}+ >+ {error}+ </Banner>+ )}- {!editing && stage === "active" && (- <LiveStageCard- signedAgreementVersion={data?.agreementSignedVersion}- downloadingAgreement={downloadingAgreement}- onDownloadSignedAgreement={onDownloadSignedAgreement}- />- )}- </>- )}- </ProcurementModal>+ {builderShowing && data && (+ <QuoteBuilder+ deployment={data.deployment ?? "cloud"}+ seats={data.seats}+ email={scheduleEmail}+ dealDetails={{+ businessName: data.businessName,+ contactName: data.contactName,+ contactEmail: data.contactEmail,+ }}+ initial={latest?.config}+ eulaAlreadyAgreed={data.trialStartedAt != null}+ minAnnualMinor={data.minAnnualNetMinor}+ rates={data.rateCard}+ onScheduleCall={() => setExtra("schedule")}+ onComparePlans={() =>+ openSettings("billing", COMPARE_PLANS_ANCHOR)+ }+ onClose={() => setOpen(false)}+ onGenerate={onGenerate}+ // Null while re-editing: the buyer asked for the form, not the paper they just left.+ issued={!editing && isIssued ? latest : null}+ downloading={downloading}+ onDownload={onDownloadPdf}+ />+ )}- <TrialSetupModal- open={extra === "setup" && !linkModalOpen}- onClose={() => setExtra(null)}- busy={busy}- email={scheduleEmail ?? undefined}- onScheduleCall={() => setExtra("schedule")}- onConfirm={onConfirmSetup}- />- {data?.licenseKey && (- <LicenseModal- open={extra === "license" && !linkModalOpen}- onClose={() => setExtra(null)}- licenseKey={data.licenseKey}- offlineAvailable={data.deployment === "airgap"}- downloadingLicense={downloadingLicense}- onDownloadOffline={onDownloadOfflineLicense}- trial={data.stage !== "procurement" && data.stage !== "active"}- />+ {/* Signing accepts the quote into a committed subscription (Stripe). */}+ {agreementShowing && latest && (+ <ProcurementAgreement+ quote={latest}+ busy={busy}+ onAgree={onAgree}+ onRequestChanges={() => {+ setOpen(false);+ setExtra("schedule");+ }}+ onClose={() => setOpen(false)}+ />+ )}+ </section>)}+<ScheduleCallModal- open={extra === "schedule" && !linkModalOpen}+ open={extra === "schedule"}onClose={() => setExtra(null)}email={scheduleEmail}/>- {data && (- <TrialManageModal- open={extra === "trial" && !linkModalOpen}- onClose={() => setExtra(null)}- snapshot={data}- busy={busy}- onExtend={async () => {- await onExtendTrial();- setExtra(null);- }}- onCancel={async () => {- await onReset();- setExtra(null);- }}- />- )}- <DocumentsModal- open={extra === "documents" && !linkModalOpen}- onClose={() => setExtra(null)}- agreementVersion={data?.agreementSignedVersion}- downloadingAgreement={downloadingAgreement}- onDownloadAgreement={onDownloadSignedAgreement}- onViewAgreement={() => {- setExtra(null);- setEditing(false);- setOpen(true);- }}- quoteAvailable={!!latest?.stripeQuoteId}- downloadingQuote={downloading}- onDownloadQuote={onDownloadPdf}- invoiceUrl={latest?.invoiceUrl}- invoicePdf={latest?.invoicePdf ?? invoicePdf}- /></>);}diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementModal.stories.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementModal.stories.tsxdeleted file mode 100644index 6e7769d4df..0000000000--- a/frontend/src/processor/proprietary/components/procurement/ProcurementModal.stories.tsx+++ /dev/null@@ -1,40 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { Button, Card } from "@editor/ui";-import { ProcurementModal } from "@processor/components/procurement/ProcurementModal";--/**- * The full-screen takeover modal shell. Rendered always-open here to verify the panel has a solid- * (not see-through) surface over the dimmed, blurred backdrop.- */-const meta: Meta<typeof ProcurementModal> = {- title: "Portal/Procurement/ProcurementModal",- component: ProcurementModal,- parameters: { layout: "fullscreen" },- args: {- open: true,- onClose: () => {},- title: "Enterprise procurement",- subtitle: "Get your team evaluated, contracted, and onboarded.",- },-};-export default meta;--type Story = StoryObj<typeof ProcurementModal>;--export const Open: Story = {- args: {- children: (- <Card padding="loose">- <h3 style={{ margin: 0 }}>Ready for payment</h3>- <p style={{ color: "var(--c-text-subtle)" }}>- Your quote is accepted. Continue to checkout to pay your committed- contract and go live.- </p>- <div style={{ display: "flex", gap: "0.6rem" }}>- <Button variant="primary">Continue to checkout</Button>- <Button variant="secondary">Edit quote</Button>- </div>- </Card>- ),- },-};diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementModal.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementModal.tsxdeleted file mode 100644index f3dd5db73d..0000000000--- a/frontend/src/processor/proprietary/components/procurement/ProcurementModal.tsx+++ /dev/null@@ -1,49 +0,0 @@-import type { ReactNode } from "react";-import { FlowModal } from "@processor/components/shared/FlowModal";-import "@processor/views/Procurement.css";--/**- * The procurement takeover: the shared {@link FlowModal} at takeover width. Chrome and copy only —- * the shell (portal, focus trap, Escape, close, header/body bands) is shared, so this dialog cannot- * drift from the trial and licence dialogs the way two hand-rolled shells did.- */-export function ProcurementModal({- open,- onClose,- title,- subtitle,- headerless = false,- children,-}: {- open: boolean;- onClose: () => void;- /** Dialog label. Omit `subtitle` (and pass `headerless`) when the step renders its own heading. */- title: string;- subtitle?: string;- /**- * Skip the title block, which takes the shell's close with it: the step inside supplies the- * heading, step badge and its own close (see StepModalHeader), so the shell would otherwise stack- * a second header and leave a stray close above it. Escape and the backdrop still dismiss.- */- headerless?: boolean;- children: ReactNode;-}) {- return (- <FlowModal- open={open}- onClose={onClose}- label={title}- size="lg"- header={- headerless ? undefined : (- <>- <h2 className="portal-procmodal__title">{title}</h2>- {subtitle && <p className="portal-procmodal__sub">{subtitle}</p>}- </>- )- }- >- {children}- </FlowModal>- );-}diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementRedirect.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementRedirect.tsxdeleted file mode 100644index 256a689385..0000000000--- a/frontend/src/processor/proprietary/components/procurement/ProcurementRedirect.tsx+++ /dev/null@@ -1,9 +0,0 @@-import { Navigate, useLocation } from "react-router-dom";--/** Keep sales links resumable across sign-in, account linking and page reloads. */-export function ProcurementRedirect() {- const { search } = useLocation();- const params = new URLSearchParams(search);- params.set("procurement", "start");- return <Navigate to={`/settings/billing?${params}`} replace />;-}diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementStages.stories.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementStages.stories.tsxindex 8a1a852371..ba1884c1a6 100644--- a/frontend/src/processor/proprietary/components/procurement/ProcurementStages.stories.tsx+++ b/frontend/src/processor/proprietary/components/procurement/ProcurementStages.stories.tsx@@ -1,17 +1,8 @@import type { Meta, StoryObj } from "@storybook/react-vite";-import {- PaymentStageCard,- LiveStageCard,- LicensePanel,-} from "@processor/components/procurement/ProcurementStages";+import { LicensePanel } from "@processor/components/procurement/ProcurementStages";import "@processor/views/Procurement.css";-/**- * The three small presentational pieces used inside the procurement takeover- * modal once a quote exists: the payment step, the live confirmation, and the- * licence panel shown alongside them. Grouped in one story file since none is- * substantial enough to warrant its own.- */+/** The licence key panel on the Enterprise page, with and without the offline licence file. */const meta: Meta = {title: "Portal/Procurement/ProcurementStages",parameters: { layout: "padded" },@@ -20,26 +11,6 @@ export default meta;type Story = StoryObj;-// Subscription created: both invoice link and PDF download are offered.-export const Payment: Story = {- render: () => (- <PaymentStageCard- invoiceUrl="https://billing.example.com/invoices/inv_123"- invoicePdf="https://billing.example.com/invoices/inv_123.pdf"- />- ),-};--// Invoice not yet issued: no action row renders.-export const PaymentPending: Story = {- render: () => <PaymentStageCard invoiceUrl={null} invoicePdf={null} />,-};--// Deal is active: terminal confirmation card.-export const Live: Story = {- render: () => <LiveStageCard />,-};-// Licence key with the offline add-on available.export const License: Story = {render: () => (diff --git a/frontend/src/processor/proprietary/components/procurement/ProcurementStages.tsx b/frontend/src/processor/proprietary/components/procurement/ProcurementStages.tsxindex e947b628b1..611621aeaf 100644--- a/frontend/src/processor/proprietary/components/procurement/ProcurementStages.tsx+++ b/frontend/src/processor/proprietary/components/procurement/ProcurementStages.tsx@@ -1,118 +1,8 @@-import { useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "@editor/ui";-import { openApiUrl } from "@processor/api/externalUrl";+import { useCopyFeedback } from "@processor/hooks/useCopyFeedback";import "@processor/views/Procurement.css";-/**- * The stage-specific views shown inside the procurement takeover modal once the agreement is signed:- * the subscription-created payment step and the live confirmation. Each is a pure presentational view- * driven by props; the controller owns the state and the actions.- *- * Neither is wrapped in a Card: the dialog is already the surface, and a card inside it drew a second- * border around content that filled it. Both wear the same eyebrow/title/description stack and put- * their actions in the flow's footer bar, so the last two steps of the journey read like the ones- * before them rather than like panels that wandered in.- */--/** The subscription-created step: pay or download the first invoice, and the signed agreement. */-export function PaymentStageCard({- invoiceUrl,- invoicePdf,- signedAgreementVersion,- downloadingAgreement,- onDownloadSignedAgreement,-}: {- invoiceUrl?: string | null;- invoicePdf?: string | null;- /** Version label of the signed agreement PDF, if one is available to download. */- signedAgreementVersion?: string | null;- downloadingAgreement?: boolean;- onDownloadSignedAgreement?: () => void;-}) {- const { t } = useTranslation();- return (- <div className="portal-procstage">- <span className="portal-proc__eyebrow">- {t("portal.procurement.payment.eyebrow")}- </span>- <h3 className="portal-proc__builder-title">- {t("portal.procurement.payment.title")}- </h3>- <p className="portal-proc__subtitle">- {t("portal.procurement.payment.description")}- </p>- {(invoiceUrl || invoicePdf || signedAgreementVersion) && (- <div className="portal-qb__foot portal-procstage__foot">- <div className="portal-qb__foot-btns">- {signedAgreementVersion && onDownloadSignedAgreement && (- <Button- variant="secondary"- loading={downloadingAgreement}- onClick={onDownloadSignedAgreement}- >- {t("portal.procurement.payment.downloadAgreement")}- </Button>- )}- {invoicePdf && (- <Button- variant="secondary"- onClick={() => openApiUrl(invoicePdf)}- >- {t("portal.procurement.payment.downloadInvoice")}- </Button>- )}- {invoiceUrl && (- <Button variant="primary" onClick={() => openApiUrl(invoiceUrl)}>- {t("portal.procurement.payment.viewInvoice")}- </Button>- )}- </div>- </div>- )}- </div>- );-}--/** The live confirmation once the deal is active. */-export function LiveStageCard({- signedAgreementVersion,- downloadingAgreement,- onDownloadSignedAgreement,-}: {- signedAgreementVersion?: string | null;- downloadingAgreement?: boolean;- onDownloadSignedAgreement?: () => void;-} = {}) {- const { t } = useTranslation();- return (- <div className="portal-procstage">- <span className="portal-proc__eyebrow">- {t("portal.procurement.live.eyebrow")}- </span>- <h3 className="portal-proc__builder-title">- {t("portal.procurement.live.title")}- </h3>- <p className="portal-proc__subtitle">- {t("portal.procurement.live.description")}- </p>- {signedAgreementVersion && onDownloadSignedAgreement && (- <div className="portal-qb__foot portal-procstage__foot">- <div className="portal-qb__foot-btns">- <Button- variant="secondary"- loading={downloadingAgreement}- onClick={onDownloadSignedAgreement}- >- {t("portal.procurement.payment.downloadAgreement")}- </Button>- </div>- </div>- )}- </div>- );-}-/*** The team's licence key with Copy — and, when the paid offline add-on was taken, a download for* the air-gapped licence file. Shown from the trial step onward (the key exists from the trial and@@ -130,13 +20,8 @@ export function LicensePanel({onDownloadOffline: () => void;}) {const { t } = useTranslation();- const [copied, setCopied] = useState(false);-- const copyKey = () => {- void navigator.clipboard?.writeText(licenseKey);- setCopied(true);- setTimeout(() => setCopied(false), 1500);- };+ const { copied, copy } = useCopyFeedback();+ const copyKey = () => void copy(licenseKey);return (<div className="portal-proc__license">diff --git a/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.stories.tsx b/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.stories.tsxindex 36410b5e25..e05c867c9b 100644--- a/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.stories.tsx+++ b/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.stories.tsx@@ -1,5 +1,6 @@import type { Meta, StoryObj } from "@storybook/react-vite";import { QuoteBuilder } from "@processor/components/procurement/QuoteBuilder";+import { RATE_CARD } from "@processor/mocks/handlers/procurementSaas";import "@processor/views/Procurement.css";/**@@ -11,10 +12,56 @@ const meta: Meta<typeof QuoteBuilder> = {title: "Portal/Procurement/QuoteBuilder",component: QuoteBuilder,parameters: { layout: "padded" },- args: { deployment: "cloud", onGenerate: () => {} },+ args: { deployment: "cloud", rates: RATE_CARD, onGenerate: () => {} },};export default meta;type Story = StoryObj<typeof QuoteBuilder>;export const Default: Story = {};++/**+ * A team small enough to price under the Enterprise minimum, details filled: generating explains+ * the minimum and leads to the self-serve plans.+ */+export const BelowMinimum: Story = {+ args: {+ minAnnualMinor: 1_200_000,+ onComparePlans: () => {},+ eulaAlreadyAgreed: true,+ initial: {+ volume: 10_000,+ users: 5,+ intensity: 4,+ sizeMult: 1.4,+ deployment: "cloud",+ termYears: 3,+ serviceLevel: "standard",+ indemnification: false,+ training: false,+ qbr: false,+ businessName: "Northwind",+ contactName: "Dana Lee",+ contactEmail: "[email protected]",+ addressLine1: "1 Main St",+ city: "Springfield",+ region: "IL",+ postalCode: "62701",+ },+ },+};++/** Sizing a small team from scratch: Continue moves on and raises the minimum as it goes. */+export const SmallTeam: Story = {+ args: { seats: 5, minAnnualMinor: 1_200_000, onComparePlans: () => {} },+};++/** Just short of the minimum: Continue offers to top the usage up, or to talk it through. */+export const NearMinimum: Story = {+ args: {+ seats: 95,+ minAnnualMinor: 1_200_000,+ onComparePlans: () => {},+ onScheduleCall: () => {},+ },+};diff --git a/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.test.tsx b/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.test.tsxnew file mode 100644index 0000000000..54cbdac3fa--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.test.tsx@@ -0,0 +1,305 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import type { QuoteConfigInput, QuoteResult } from "@processor/api/procurement";+import { QuoteBuilder } from "@processor/components/procurement/QuoteBuilder";+import { RATE_CARD } from "@processor/mocks/handlers/procurementSaas";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, value?: unknown, options?: Record<string, unknown>) => {+ const vars =+ typeof value === "object" && value !== null+ ? (value as Record<string, unknown>)+ : (options ?? {});+ const text = typeof value === "string" ? value : key;+ return text.replace(/\{\{(\w+)\}\}/g, (_, name) => String(vars[name]));+ },+ i18n: { language: "en-US" },+ }),+}));++const { buildQuote } = vi.hoisted(() => ({ buildQuote: vi.fn() }));+vi.mock("@processor/api/procurement", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@processor/api/procurement")>()),+ buildQuote,+}));++/** A cloud quote for a handful of users, with every detail filled so it can be generated. */+const smallQuote: QuoteConfigInput = {+ volume: 10_000,+ users: 5,+ intensity: 4,+ sizeMult: 1.4,+ deployment: "cloud",+ termYears: 3,+ serviceLevel: "standard",+ indemnification: false,+ training: false,+ qbr: false,+ businessName: "Northwind",+ contactName: "Dana Lee",+ contactEmail: "[email protected]",+ addressLine1: "1 Main St",+ city: "Springfield",+ region: "IL",+ postalCode: "62701",+};++function mount(+ onComparePlans = vi.fn(),+ initial: QuoteConfigInput | null = smallQuote,+ onScheduleCall = vi.fn(),+) {+ render(+ <MantineProvider>+ <QuoteBuilder+ deployment="cloud"+ seats={5}+ initial={initial ?? undefined}+ eulaAlreadyAgreed+ minAnnualMinor={1_200_000}+ rates={RATE_CARD}+ onComparePlans={onComparePlans}+ onScheduleCall={onScheduleCall}+ onGenerate={vi.fn()}+ />+ </MantineProvider>,+ );+}++const field = (name: string) =>+ screen.getByLabelText(+ new RegExp(`^portal\\.procurement\\.builder\\.${name}( \\*)?$`),+ );++const generate = () =>+ screen.getByRole("button", { name: "portal.procurement.builder.generate" });++describe("QuoteBuilder chrome", () => {+ it("has no close: a quote in progress is left through the page, not dismissed", () => {+ mount();+ expect(+ screen.queryByRole("button", { name: "Close" }),+ ).not.toBeInTheDocument();+ });++ it("words the issued quote's lines through translations, keeping unknown ones as sent", () => {+ const issued: QuoteResult = {+ quoteId: 1,+ quoteNumber: "QT-1",+ status: "sent",+ currency: "usd",+ annualNetMinor: 1_600_000,+ tcvMinor: 4_800_000,+ renewalAnnualNetMinor: 1_650_000,+ cpiRatePct: 3,+ lineItems: [+ {+ key: "usage",+ label: "server usage",+ kind: "RECURRING",+ amountMinor: 1,+ },+ {+ key: "seats",+ label: "server seats",+ kind: "INCLUDED",+ amountMinor: 0,+ },+ {+ key: "deployment",+ label: "server deploy",+ kind: "RECURRING",+ amountMinor: 1,+ },+ {+ key: "new-thing",+ label: "Something new",+ kind: "RECURRING",+ amountMinor: 1,+ },+ ],+ validUntil: null,+ stripeQuoteId: "qt_1",+ invoiceUrl: null,+ invoicePdf: null,+ config: { ...smallQuote, deployment: "selfhost" },+ };+ render(+ <MantineProvider>+ <QuoteBuilder+ deployment="selfhost"+ seats={5}+ initial={issued.config}+ eulaAlreadyAgreed+ minAnnualMinor={0}+ rates={RATE_CARD}+ issued={issued}+ onGenerate={vi.fn()}+ />+ </MantineProvider>,+ );+ expect(screen.queryByText("server usage")).not.toBeInTheDocument();+ expect(+ screen.getByText("portal.procurement.builder.line.usage"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("portal.procurement.builder.line.seats"),+ ).toBeInTheDocument();+ expect(+ screen.getByText("portal.procurement.builder.line.deployment"),+ ).toBeInTheDocument();+ expect(screen.getByText("Something new")).toBeInTheDocument();+ });+});++describe("QuoteBuilder minimum deal size", () => {+ it("only notes where Enterprise starts while the buyer is still sizing the quote", () => {+ mount();+ expect(+ screen.getByText(+ /^Enterprise requires a minimum yearly spend of \D*12,000\.$/,+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Compare plans" }),+ ).not.toBeInTheDocument();+ });++ it("explains the minimum and leads to the self-serve plans when a too-small quote is generated", () => {+ const onComparePlans = vi.fn();+ mount(onComparePlans);+ fireEvent.click(generate());++ expect(buildQuote).not.toHaveBeenCalled();+ expect(screen.getByText(/^This quote comes to /)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Compare plans" }));+ expect(onComparePlans).toHaveBeenCalledOnce();+ });++ it("lets the buyer continue past a too-small quote, warning them as they go", () => {+ mount(vi.fn(), null);+ expect(screen.queryByText(/^This quote comes to /)).not.toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", {+ name: "portal.procurement.builder.continue",+ }),+ );+ expect(screen.getByText(/^This quote comes to /)).toBeInTheDocument();+ expect(+ screen.getByRole("button", {+ name: "portal.procurement.builder.continue",+ }),+ ).toBeEnabled();+ });++ it("helps a quote just short of the minimum over it, or into a call", () => {+ const onScheduleCall = vi.fn();+ // About $10,100 a year: inside the near band.+ mount(vi.fn(), { ...smallQuote, volume: 190_000 }, onScheduleCall);+ fireEvent.click(generate());++ expect(+ screen.getByText(/a year short of Enterprise\.$/),+ ).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", {+ name: "portal.procurement.hero.scheduleCall",+ }),+ );+ expect(onScheduleCall).toHaveBeenCalledOnce();++ fireEvent.click(+ screen.getByRole("button", { name: "Raise estimated usage" }),+ );+ expect(+ screen.queryByText(/a year short of Enterprise/),+ ).not.toBeInTheDocument();+ expect(screen.queryByText(/^Enterprise requires/)).not.toBeInTheDocument();+ });+});++describe("QuoteBuilder contact email", () => {+ it("says the email is invalid, not just marks it, when generating", () => {+ mount(vi.fn(), { ...smallQuote, contactEmail: "dana@northwind" });+ fireEvent.click(generate());+ expect(+ screen.getByText("portal.procurement.validation.email"),+ ).toBeInTheDocument();+ });+});++describe("QuoteBuilder blocked steps", () => {+ it("keeps sizing's Continue clickable and asks for a volume instead of moving on", () => {+ mount(vi.fn(), null);+ fireEvent.change(field("volume"), { target: { value: "0" } });+ const next = screen.getByRole("button", {+ name: "portal.procurement.builder.continue",+ });+ expect(next).toBeEnabled();+ fireEvent.click(next);+ expect(+ screen.getByText("portal.procurement.validation.volume"),+ ).toBeInTheDocument();+ });++ it("names each missing required detail when generating", () => {+ mount(vi.fn(), { ...smallQuote, city: "", postalCode: "" });+ fireEvent.click(generate());+ expect(+ screen.getAllByText("portal.procurement.validation.required"),+ ).toHaveLength(2);+ });+});++describe("QuoteBuilder generate errors", () => {+ it("offers the self-serve plans only when the server refuses the deal for its size", async () => {+ buildQuote.mockRejectedValueOnce(new Error("Network down"));+ mount(vi.fn(), { ...smallQuote, volume: 900_000 });+ fireEvent.click(generate());+ expect(await screen.findByText("Network down")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Compare plans" }),+ ).not.toBeInTheDocument();+ });+});++describe("QuoteBuilder option groups", () => {+ it("leaves the choice alone when the group's heading is clicked", () => {+ mount(vi.fn(), null);+ fireEvent.click(screen.getByText("portal.procurement.builder.posture"));+ expect(+ screen.getByRole("group", { name: "portal.procurement.builder.posture" }),+ ).toBeInTheDocument();+ const pressed = screen+ .getAllByRole("button", { pressed: true })+ .map((b) => b.textContent);+ expect(pressed).toEqual([+ expect.stringContaining("posture_governed"),+ expect.stringContaining("size_standard"),+ ]);+ });+});++describe("QuoteBuilder sizing", () => {+ it("re-estimates volume from the team size even after a manual figure", () => {+ mount(vi.fn(), null);+ fireEvent.change(field("volume"), { target: { value: "999999" } });+ fireEvent.change(field("users"), { target: { value: "50" } });+ expect(field("volume")).not.toHaveValue(999_999);+ });++ it("shows one-time onboarding beside a one-year total", () => {+ mount(vi.fn(), null);+ fireEvent.click(+ screen.getByRole("button", {+ name: "portal.procurement.builder.continue",+ }),+ );+ const oneTime = "portal.procurement.builder.addonOneTime";+ expect(screen.queryByText(oneTime)).not.toBeInTheDocument();+ fireEvent.click(screen.getByText("portal.procurement.builder.training"));+ expect(screen.getByText(oneTime)).toBeInTheDocument();+ });+});diff --git a/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.tsx b/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.tsxindex 6dce3cf26d..5fa54ea41a 100644--- a/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.tsx+++ b/frontend/src/processor/proprietary/components/procurement/QuoteBuilder.tsx@@ -1,35 +1,46 @@-import { useEffect, useState, type ReactNode } from "react";+import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import { Button } from "@editor/ui";+import { Banner, Button } from "@editor/ui";import { Icon } from "@editor/ui/Icon";+import { errorMessage, HttpError } from "@processor/api/http";import { money } from "@processor/components/procurement/format";import {buildQuote,+ QUOTE_BELOW_MINIMUM,recordLegalConsent,type QuoteConfigInput,+ type RateCard,type QuoteResult,} from "@processor/api/procurement";+import {+ DetailsStep,+ PlanStep,+ SizingStep,+} from "@processor/components/procurement/QuoteBuilderSteps";+import { QuotePaper } from "@processor/components/procurement/QuotePaper";+import {+ estimateVolume,+ DEFAULT_POSTURE,+ DEFAULT_SIZE_TIER,+ previewAnnualMinor,+} from "@processor/components/procurement/quotePricing";import { LegalDocumentModal } from "@processor/components/procurement/ProcurementExtras";import { StepModalHeader } from "@processor/components/shared/StepModalHeader";+import { useProcurementPrefill } from "@processor/components/procurement/prefill";+import {+ focusFirstInvalid,+ isEmail,+ isFilled,+} from "@processor/components/procurement/formField";import "@processor/theme/surface.css";import "@processor/views/Procurement.css";-const STEPS = ["volume", "plan", "details", "review"] as const;-const DETAILS_STEP = 2;-const REVIEW_STEP = 3;-const TERM_DISCOUNT = [0, 0.03, 0.05, 0.06, 0.07]; // 1..5 years — meter-only discount (D71)-// Governance posture: the intensity (runs per PDF) fed to the committed-volume curve.-const POSTURES = [- { intensity: 2, key: "essentials" },- { intensity: 4, key: "governed" },- { intensity: 7, key: "regulated" },-] as const;-// PDF-size tiers (D93): a multiplier on the rate. Default Standard (×1.4). Mirrors the server.-const SIZE_TIERS = [- { mult: 1.0, key: "compact" },- { mult: 1.4, key: "standard" },- { mult: 2.4, key: "heavy" },-] as const;+const STEP = { sizing: 0, plan: 1, details: 2, review: 3 } as const;+const STEP_COUNT = Object.keys(STEP).length;+/** Share of the minimum from which a quote counts as nearly there, so the nudge is to top up. */+const NEAR_MINIMUM_RATIO = 0.75;+/** Upper bound for the volume search, far past any real estimate. */+const MAX_VOLUME = 1_000_000_000_000;/*** The enterprise quote builder — volume → commitment & service → details → review. A client-side@@ -46,6 +57,10 @@ export function QuoteBuilder({dealDetails,initial,eulaAlreadyAgreed = false,+ minAnnualMinor = 0,+ rates,+ onComparePlans,+ onScheduleCall,onGenerate,issued,downloading = false,@@ -56,7 +71,7 @@ export function QuoteBuilder({seats?: number;/** Linked-account email; prefills the contact email on a fresh quote's details step. */email?: string | null;- /** Dismiss the dialog. The builder draws its own header, so it carries the close too. */+ /** Leave the builder, from the review step's Done. It has no close: a quote in progress is left through the page. */onClose?: () => void;/*** The buying entity captured at trial setup. Seeds a fresh quote's details step so it confirms@@ -68,6 +83,14 @@ export function QuoteBuilder({contactName?: string | null;contactEmail?: string | null;};+ /** Smallest annual fee the server will quote; 0 when there is no floor. */+ minAnnualMinor?: number;+ /** The server's rate card, which the live estimate is priced from. */+ rates: RateCard;+ /** Where a buyer too small for Enterprise goes instead: the self-serve plans. */+ onComparePlans?: () => void;+ /** Talk it through with us, offered when a quote falls just short of the minimum. */+ onScheduleCall?: () => void;/** Seed the builder from an existing quote's config (re-editing a quote). */initial?: QuoteConfigInput;/**@@ -87,17 +110,24 @@ export function QuoteBuilder({onGenerate: (quote: QuoteResult) => void;}) {const { t } = useTranslation();- const [step, setStep] = useState(0);+ // Re-editing a quote opens on its details, everything seeded: one click re-generates, or Back+ // changes a field.+ const [step, setStep] = useState<number>(+ initial ? STEP.details : STEP.sizing,+ );+ const prefill = useProcurementPrefill();const [cfg, setCfg] = useState<QuoteConfigInput>(initial ?? {// Users-first: with no seats from the trial, leave volume empty so entering the team size// auto-fills it (rather than pre-seeding a figure that hides the users → volume estimate).volume: seats > 0 ? estimateVolume(seats) : 0,users: Math.max(0, seats),- intensity: 4, // Governed — the default governance posture per the pricing alignment- sizeMult: 1.4, // Standard — the default PDF-size tier (D93)+ intensity: DEFAULT_POSTURE.intensity,+ sizeMult: DEFAULT_SIZE_TIER.mult,deployment,- termYears: 3,+ // One year: the sizing step prices the base rate, and longer terms' discounts belong to the+ // commitment step where the term is chosen.+ termYears: 1,serviceLevel: "priority",indemnification: false,training: false,@@ -105,66 +135,72 @@ export function QuoteBuilder({businessName: dealDetails?.businessName ?? "",contactName: dealDetails?.contactName ?? "",contactEmail: dealDetails?.contactEmail ?? email ?? "",- addressLine1: "",+ addressLine1: prefill?.addressLine1 ?? "",addressLine2: "",- city: "",- region: "",- postalCode: "",+ city: prefill?.city ?? "",+ region: prefill?.region ?? "",+ postalCode: prefill?.postalCode ?? "",poNumber: "",taxId: "",},);- // A seeded quote carries a volume but no user count, so treat it as manually set.+ // A seeded quote's volume may have been typed rather than estimated, so keep it as is.const [manualVolume, setManualVolume] = useState(initial != null);// Never pre-ticked, even when re-editing a quote: a consent the buyer did not tick in this session// is not a consent, and recordLegalConsent would have logged one as though they had.const [eula, setEula] = useState(false);const [legalDoc, setLegalDoc] = useState<string | null>(null);const [busy, setBusy] = useState(false);+ const [generateError, setGenerateError] = useState<{+ message: string;+ /** The server declined the deal for its size, so the self-serve plans are the way on. */+ tooSmall: boolean;+ } | null>(null);+ // Set by moving on (or generating) under the floor, so the warning answers that step rather than+ // nagging while the buyer is still sizing the quote.+ const [triedBelowMinimum, setTriedBelowMinimum] = useState(false);// Only surface field errors once the buyer tries to generate — no red fields on first sight.const [showErrors, setShowErrors] = useState(false);+ const [emailTouched, setEmailTouched] = useState(false);+ // Same for the sizing step: Continue stays clickable and says what is missing.+ const [triedSizing, setTriedSizing] = useState(false);function set<K extends keyof QuoteConfigInput>(k: K, v: QuoteConfigInput[K]) {setCfg((c) => ({ ...c, [k]: v }));}// Required buyer details before a quote can be generated (Order Form / invoice need these).- const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(- (cfg.contactEmail ?? "").trim(),- );const valid = {- businessName: cfg.businessName.trim().length > 0,- contactName: (cfg.contactName ?? "").trim().length > 0,- contactEmail: emailOk,- addressLine1: (cfg.addressLine1 ?? "").trim().length > 0,- city: (cfg.city ?? "").trim().length > 0,- region: (cfg.region ?? "").trim().length > 0,- postalCode: (cfg.postalCode ?? "").trim().length > 0,+ businessName: isFilled(cfg.businessName),+ contactName: isFilled(cfg.contactName),+ contactEmail: isEmail(cfg.contactEmail),+ addressLine1: isFilled(cfg.addressLine1),+ city: isFilled(cfg.city),+ region: isFilled(cfg.region),+ postalCode: isFilled(cfg.postalCode),};const detailsValid = Object.values(valid).every(Boolean);const eulaOk = eulaAlreadyAgreed || eula;const canGenerate = detailsValid && eulaOk;- // Re-editing an existing quote: everything is seeded, so jump to the details step with the- // agreement pre-accepted — one click re-generates, or Back to change a field. No walking from step 1.- // Mount-only: seed the step from `initial` once (deliberately no deps).- useEffect(() => {- if (initial) setStep(DETAILS_STEP);- }, []);-// Issuing lands by snapshot refresh rather than as a return value, so the arrival of the issued// quote is what opens the review step. Keyed on the quote's id, not the object: React Query hands// back a fresh object on every refetch, which would yank a buyer who had walked Back to the form.useEffect(() => {- if (issued) setStep(REVIEW_STEP);+ if (issued) setStep(STEP.review);}, [issued?.quoteId]);- const preview = previewAnnualMinor(cfg);- const tcvPreview = preview * cfg.termYears + (cfg.training ? 750_000 : 0);+ const preview = previewAnnualMinor(cfg, rates);+ const tcvPreview =+ preview * cfg.termYears + (cfg.training ? rates.trainingOneTimeMinor : 0);+ // Priced off the usage fee, so its figure moves with the rest of the quote.+ const indemnityPreview =+ previewAnnualMinor({ ...cfg, indemnification: true }, rates) -+ previewAnnualMinor({ ...cfg, indemnification: false }, rates);// On the review step the footer quotes the issued figures rather than the client-side preview, so// the running total never disagrees with the paper directly above it.- const onPaper = issued != null && step === REVIEW_STEP;+ const onPaper = issued != null && step === STEP.review;const running = onPaper? {annual: money(issued.annualNetMinor, issued.currency),@@ -176,21 +212,95 @@ export function QuoteBuilder({years: cfg.termYears,tcv: money(tcvPreview),};+ // Onboarding is one-time, so over a single year it shows beside the yearly price; on paper as+ // the issued quote charged it, in its currency.+ const trainingLine = onPaper+ ? issued.lineItems.find((li) => li.key === "training")+ : undefined;+ const oneTime = onPaper+ ? trainingLine+ ? money(trainingLine.amountMinor, issued.currency)+ : null+ : cfg.training+ ? money(rates.trainingOneTimeMinor)+ : null;++ // The preview uses the server's rates, so a draft under the floor is caught here rather than by+ // the server refusing to price it.+ const belowMinimum =+ !onPaper && minAnnualMinor > 0 && preview < minAnnualMinor;+ const showMinimum = belowMinimum && triedBelowMinimum;+ // Close enough that a little more usage clears it: help them over rather than away.+ const nearMinimum =+ belowMinimum && preview >= minAnnualMinor * NEAR_MINIMUM_RATIO;++ /** Lift the estimated volume just far enough for the quote to clear the minimum. */+ function raiseToMinimum() {+ let low = cfg.volume;+ let high = Math.max(cfg.volume, 1) * 2;+ while (+ previewAnnualMinor({ ...cfg, volume: high }, rates) < minAnnualMinor &&+ high < MAX_VOLUME+ ) {+ low = high;+ high *= 2;+ }+ while (high - low > 1) {+ const mid = Math.floor((low + high) / 2);+ if (previewAnnualMinor({ ...cfg, volume: mid }, rates) >= minAnnualMinor)+ high = mid;+ else low = mid;+ }+ setManualVolume(true);+ set("volume", high);+ }++ // Moving on never waits on the minimum; it only raises the warning, which stays until the+ // quote clears it.+ function advance(next: number) {+ if (belowMinimum) setTriedBelowMinimum(true);+ setStep(next);+ }- // Fully filled → price + hand the draft to the parent to issue as a Stripe Quote (which then shows- // as the milestone). No separate in-builder preview step.async function generate() {if (!canGenerate) {setShowErrors(true);+ focusFirstInvalid();+ return;+ }+ if (belowMinimum) {+ setTriedBelowMinimum(true);return;}setBusy(true);+ setGenerateError(null);try {const quote = await buildQuote(cfg);// Record the EULA clickwrap only when it's collected here — i.e. the buyer didn't already// accept it at trial start. Best-effort.if (!eulaAlreadyAgreed) void recordLegalConsent("eula", "quote");onGenerate(quote);+ } catch (e) {+ // The server names a quote under the minimum Enterprise size; any other conflict is the deal+ // having moved on elsewhere (accepted in another tab, say).+ const conflict = e instanceof HttpError && e.status === 409;+ const tooSmall =+ conflict &&+ (e.body as { error?: string } | null)?.error === QUOTE_BELOW_MINIMUM;+ setGenerateError({+ tooSmall,+ message: tooSmall+ ? t(+ "portal.procurement.builder.belowMinimum",+ "This quote is below the minimum size for an Enterprise deal.",+ )+ : conflict+ ? t(+ "portal.procurement.builder.conflict",+ "This deal has changed since you opened it. Close the builder and reload the page to see where it stands.",+ )+ : errorMessage(e),+ });} finally {setBusy(false);}@@ -201,451 +311,167 @@ export function QuoteBuilder({<StepModalHeadertitle={t("portal.procurement.builder.title")}step={step + 1}- total={STEPS.length}+ total={STEP_COUNT}stepLabel={t("portal.procurement.builder.stepOf", {n: step + 1,- total: STEPS.length,+ total: STEP_COUNT,})}- onClose={onClose}/><div className="portal-qb__body">- {step === 0 && (- <Step- icon={<Icon name="file-text" size={22} />}- title={t("portal.procurement.builder.s1Title")}- sub={t("portal.procurement.builder.s1Sub")}- >- <div className="portal-qb__row">- <Field label={t("portal.procurement.builder.users")}>- <input- type="number"- min={0}- placeholder={t("portal.procurement.builder.usersPlaceholder")}- value={cfg.users || ""}- onChange={(e) => {- const users = Number(e.target.value);- set("users", users);- if (!manualVolume) set("volume", estimateVolume(users));- }}- />- </Field>- <Field label={t("portal.procurement.builder.volume")}>- <input- type="number"- min={0}- placeholder={t(- "portal.procurement.builder.volumePlaceholder",- )}- value={cfg.volume || ""}- onChange={(e) => {- setManualVolume(true);- set("volume", Number(e.target.value));- }}- />- </Field>- </div>- <p className="portal-qb__hint">- {cfg.users > 0 && !manualVolume- ? t("portal.procurement.builder.volEstimated", {- count: cfg.users,- })- : cfg.users > 0- ? t("portal.procurement.builder.volManual")- : t("portal.procurement.builder.volNoUsers")}- </p>- <Field label={t("portal.procurement.builder.posture")}>- <div className="portal-qb__opts">- {POSTURES.map((p) => (- <OptCard- key={p.key}- on={cfg.intensity === p.intensity}- title={t(`portal.procurement.builder.posture_${p.key}`)}- sub={`${t("portal.procurement.builder.posture_count", {- count: p.intensity,- })} · ${t(`portal.procurement.builder.posture_${p.key}Sub`)}`}- onClick={() => set("intensity", p.intensity)}- />- ))}- </div>- </Field>-- <Field label={t("portal.procurement.builder.pdfSize")}>- <div className="portal-qb__opts">- {SIZE_TIERS.map((s) => (- <OptCard- key={s.key}- on={cfg.sizeMult === s.mult}- title={t(`portal.procurement.builder.size_${s.key}`)}- sub={`×${s.mult} · ${t(`portal.procurement.builder.size_${s.key}Sub`)}`}- onClick={() => set("sizeMult", s.mult)}- />- ))}- </div>- </Field>- </Step>+ {step === STEP.sizing && (+ <SizingStep+ cfg={cfg}+ set={set}+ manualVolume={manualVolume}+ setManualVolume={setManualVolume}+ volumeInvalid={triedSizing && cfg.volume <= 0}+ />)}-- {step === 1 && (- <Step- icon={<Icon name="shield-check" size={22} />}- title={t("portal.procurement.builder.s2Title")}- sub={t("portal.procurement.builder.s2Sub")}- >- <Field label={t("portal.procurement.builder.term")}>- <div className="portal-qb__pills">- {[1, 2, 3, 4, 5].map((y) => (- <button- key={y}- type="button"- data-on={cfg.termYears === y || undefined}- onClick={() => set("termYears", y)}- >- {t("portal.procurement.builder.years", { count: y })}- </button>- ))}- </div>- {TERM_DISCOUNT[cfg.termYears - 1] > 0 && (- <p className="portal-qb__discount">- {t("portal.procurement.builder.termDiscount", {- pct: Math.round(TERM_DISCOUNT[cfg.termYears - 1] * 100),- })}- </p>- )}- </Field>-- <Field label={t("portal.procurement.builder.serviceLevel")}>- <div className="portal-qb__opts">- <OptCard- on={cfg.serviceLevel === "standard"}- title={t("portal.procurement.builder.slStandard")}- sub={t("portal.procurement.builder.slStandardSub")}- onClick={() => set("serviceLevel", "standard")}- />- <OptCard- on={cfg.serviceLevel === "priority"}- title={t("portal.procurement.builder.slPriority")}- sub={t("portal.procurement.builder.slPrioritySub")}- onClick={() => set("serviceLevel", "priority")}- />- <OptCard- on={cfg.serviceLevel === "dedicated"}- title={t("portal.procurement.builder.slDedicated")}- sub={t("portal.procurement.builder.slDedicatedSub")}- onClick={() => set("serviceLevel", "dedicated")}- />- </div>- </Field>-- <Field label={t("portal.procurement.builder.addons")}>- <div className="portal-qb__addons">- <AddOn- on={cfg.indemnification}- title={t("portal.procurement.builder.indemnification")}- sub={t("portal.procurement.builder.indemnificationSub")}- onClick={() => set("indemnification", !cfg.indemnification)}- />- <AddOn- on={cfg.training}- title={t("portal.procurement.builder.training")}- sub={t("portal.procurement.builder.trainingSub")}- onClick={() => set("training", !cfg.training)}- />- <AddOn- on={cfg.qbr}- title={t("portal.procurement.builder.qbr")}- sub={t("portal.procurement.builder.qbrSub")}- onClick={() => set("qbr", !cfg.qbr)}- />- </div>- </Field>- </Step>+ {step === STEP.plan && (+ <PlanStep+ cfg={cfg}+ set={set}+ rates={rates}+ indemnityPreview={indemnityPreview}+ />)}-- {step === 2 && (- <Step- icon={<Icon name="users" size={22} />}- title={t("portal.procurement.builder.s3Title")}- sub={t("portal.procurement.builder.s3Sub")}- >- <div className="portal-qb__row">- <Field- label={t("portal.procurement.builder.businessName")}- required- invalid={showErrors && !valid.businessName}- >- <input- placeholder={t(- "portal.procurement.builder.businessNamePlaceholder",- )}- value={cfg.businessName}- onChange={(e) => set("businessName", e.target.value)}- />- </Field>- <Field- label={t("portal.procurement.builder.contactName")}- required- invalid={showErrors && !valid.contactName}- >- <input- placeholder={t(- "portal.procurement.builder.contactNamePlaceholder",- )}- value={cfg.contactName ?? ""}- onChange={(e) => set("contactName", e.target.value)}- />- </Field>- </div>- <Field- label={t("portal.procurement.builder.contactEmail")}- required- invalid={showErrors && !valid.contactEmail}- >- <input- type="email"- placeholder={t(- "portal.procurement.builder.contactEmailPlaceholder",- )}- value={cfg.contactEmail ?? ""}- onChange={(e) => set("contactEmail", e.target.value)}- />- </Field>- <Field- label={t("portal.procurement.builder.addressLine1")}- required- invalid={showErrors && !valid.addressLine1}- >- <input- placeholder={t(- "portal.procurement.builder.addressLine1Placeholder",- )}- value={cfg.addressLine1 ?? ""}- onChange={(e) => set("addressLine1", e.target.value)}- />- </Field>- <Field label={t("portal.procurement.builder.addressLine2")}>- <input- placeholder={t(- "portal.procurement.builder.addressLine2Placeholder",- )}- value={cfg.addressLine2 ?? ""}- onChange={(e) => set("addressLine2", e.target.value)}- />- </Field>- <div className="portal-qb__row">- <Field- label={t("portal.procurement.builder.city")}- required- invalid={showErrors && !valid.city}- >- <input- placeholder={t("portal.procurement.builder.cityPlaceholder")}- value={cfg.city ?? ""}- onChange={(e) => set("city", e.target.value)}- />- </Field>- <Field- label={t("portal.procurement.builder.region")}- required- invalid={showErrors && !valid.region}- >- <input- placeholder={t(- "portal.procurement.builder.regionPlaceholder",- )}- value={cfg.region ?? ""}- onChange={(e) => set("region", e.target.value)}- />- </Field>- <Field- label={t("portal.procurement.builder.postalCode")}- required- invalid={showErrors && !valid.postalCode}- >- <input- placeholder={t(- "portal.procurement.builder.postalCodePlaceholder",- )}- value={cfg.postalCode ?? ""}- onChange={(e) => set("postalCode", e.target.value)}- />- </Field>- </div>- <div className="portal-qb__row">- <Field label={t("portal.procurement.builder.poNumber")}>- <input- placeholder={t(- "portal.procurement.builder.poNumberPlaceholder",- )}- value={cfg.poNumber ?? ""}- onChange={(e) => set("poNumber", e.target.value)}- />- </Field>- <Field label={t("portal.procurement.builder.taxId")}>- <input- placeholder={t("portal.procurement.builder.taxIdPlaceholder")}- value={cfg.taxId ?? ""}- onChange={(e) => set("taxId", e.target.value)}- />- </Field>- </div>- {!eulaAlreadyAgreed && (- <label className="portal-qb__eula">- <input- type="checkbox"- checked={eula}- onChange={(e) => setEula(e.target.checked)}- />- <span>- {t("portal.procurement.builder.eula")}{" "}- <button- type="button"- className="portal-legal__link"- onClick={() => setLegalDoc("eula")}- >- {t("portal.procurement.builder.viewEula")}- </button>- </span>- </label>- )}- {showErrors && !canGenerate && (- <p className="portal-qb__error">- {t("portal.procurement.builder.completeRequired")}- </p>- )}- </Step>+ {step === STEP.details && (+ <DetailsStep+ cfg={cfg}+ set={set}+ valid={valid}+ showErrors={showErrors}+ emailTouched={emailTouched}+ onEmailBlur={() => setEmailTouched(true)}+ eula={+ eulaAlreadyAgreed+ ? null+ : {+ checked: eula,+ onChange: setEula,+ onView: () => setLegalDoc("eula"),+ }+ }+ />)}- {/* No step heading here, unlike the form steps: the quote is the content, and a heading over- it only repeats what the paper already says. The real issued figures, not the footer's- client-side preview — this is the document the buyer circulates, so it has to match the- PDF and the Stripe quote exactly. */}- {step === REVIEW_STEP && issued && (- <div className="portal-qb__papertray">- <div className="portal-surface portal-qb__paper">- <div className="portal-qb__paper-head">- <div>- <div className="portal-qb__paper-brand">Stirling PDF</div>- <div className="portal-qb__paper-eyebrow">- {t("portal.procurement.builder.paperEyebrow")}- </div>- </div>- <div className="portal-qb__paper-meta">- <div className="portal-qb__quote-number">- {issued.quoteNumber}- </div>- {issued.validUntil && (- <div>- {t("portal.procurement.review.validUntil", {- date: new Date(issued.validUntil).toLocaleDateString(),- })}- </div>- )}- {/* On the document rather than in the footer: it downloads this paper, so it- belongs to it, and the footer stays the flow's own Back/Done. */}- <Button- variant="tertiary"- size="sm"- className="portal-qb__paper-download"- leftSection={<Icon name="download" size={14} />}- loading={downloading}- onClick={onDownload}- >- {t("portal.procurement.review.downloadCta")}- </Button>- </div>- </div>-- {issued.config.businessName?.trim() && (- <div className="portal-qb__paper-for">- <div className="portal-qb__paper-eyebrow">- {t("portal.procurement.builder.paperFor")}- </div>- <div className="portal-qb__paper-company">- {issued.config.businessName}- </div>- </div>- )}-- <ul className="portal-qb__lines">- {issued.lineItems.map((li) => (- <li key={li.key} data-kind={li.kind}>- <span>{li.label}</span>- <span>{money(li.amountMinor, issued.currency)}</span>- </li>- ))}- </ul>-- <div className="portal-qb__total">- <div>- <div className="portal-qb__total-label">- {t("portal.procurement.review.annual")}- </div>- <div className="portal-qb__total-tcv">- {t("portal.procurement.review.tcv", {- years: issued.config.termYears,- tcv: money(issued.tcvMinor, issued.currency),- })}- </div>- <div className="portal-qb__total-tcv">- {t("portal.procurement.review.renewal", {- amount: money(- issued.renewalAnnualNetMinor,- issued.currency,- ),- pct: issued.cpiRatePct,- })}- </div>- {issued.config.poNumber?.trim() && (- <div className="portal-qb__total-tcv">- {t("portal.procurement.review.poNumber", {- po: issued.config.poNumber.trim(),- })}- </div>- )}- </div>- <div className="portal-qb__total-num">- {money(issued.annualNetMinor, issued.currency)}- </div>- </div>- </div>- </div>+ {/* No step heading, unlike the form steps: a heading over the quote repeats the paper. */}+ {step === STEP.review && issued && (+ <QuotePaper+ issued={issued}+ rates={rates}+ downloading={downloading}+ onDownload={onDownload}+ />)}</div>+ {showMinimum && (+ <MinimumNotice+ near={nearMinimum}+ minMinor={minAnnualMinor}+ previewMinor={preview}+ onScheduleCall={onScheduleCall}+ onRaise={raiseToMinimum}+ onEditUsage={() => setStep(STEP.sizing)}+ onComparePlans={onComparePlans}+ />+ )}++ {generateError && (+ <Banner+ tone="danger"+ title={t("portal.procurement.error.title")}+ onDismiss={() => setGenerateError(null)}+ action={+ generateError.tooSmall &&+ onComparePlans && (+ <Button size="sm" onClick={onComparePlans}>+ {t("portal.billing.compare.open", "Compare plans")}+ </Button>+ )+ }+ >+ {generateError.message}+ </Banner>+ )}+<div className="portal-qb__foot">- <span className="portal-qb__running">- {t("portal.procurement.builder.running", running)}- </span>+ <div className="portal-qb__totals">+ <span className="portal-qb__running-label">+ {onPaper+ ? t("portal.procurement.builder.runningLabelIssued")+ : t("portal.procurement.builder.runningLabel")}+ </span>+ <span className="portal-qb__running">+ {t("portal.procurement.builder.runningOneYear", {+ annual: running.annual,+ })}+ </span>+ {/* A one-year term's total is its yearly price; repeating it says nothing. */}+ {running.years > 1 && (+ <span className="portal-qb__running-total">+ {t("portal.procurement.builder.runningTotal", running)}+ </span>+ )}+ {/* Over one year there is no term total to fold onboarding into, so it shows on its own. */}+ {running.years === 1 && oneTime && (+ <span className="portal-qb__running-total">+ {t("portal.procurement.builder.addonOneTime", {+ amount: oneTime,+ })}+ </span>+ )}+ {belowMinimum && !showMinimum && (+ <span className="portal-qb__minimum">+ {t(+ "portal.procurement.builder.minimum",+ "Enterprise requires a minimum yearly spend of {{min}}.",+ { min: money(minAnnualMinor) },+ )}+ </span>+ )}+ </div><div className="portal-qb__foot-btns">{step > 0 && (<Button variant="secondary" onClick={() => setStep(step - 1)}>{t("portal.procurement.builder.back")}</Button>)}- {step === 0 && (+ {step === STEP.sizing && (<Buttonvariant="primary"- disabled={cfg.volume <= 0}- onClick={() => setStep(1)}+ onClick={() => {+ if (cfg.volume <= 0) {+ setTriedSizing(true);+ focusFirstInvalid();+ return;+ }+ advance(STEP.plan);+ }}>{t("portal.procurement.builder.continue")}</Button>)}- {step === 1 && (- <Button variant="primary" onClick={() => setStep(2)}>+ {step === STEP.plan && (+ <Button variant="primary" onClick={() => advance(STEP.details)}>{t("portal.procurement.builder.continue")}</Button>)}- {step === DETAILS_STEP && (- <Button variant="primary" loading={busy} onClick={generate}>+ {step === STEP.details && (+ <Button+ variant={showMinimum ? "secondary" : "primary"}+ loading={busy}+ onClick={generate}+ >{t("portal.procurement.builder.generate")}</Button>)}{/* No Accept here: the review step ends on the deal card, where accepting is one of twodeliberate choices rather than the only way out of a modal. Download lives on thedocument itself. */}- {step === REVIEW_STEP && (+ {step === STEP.review && (<Button variant="primary" onClick={onClose}>{t("portal.procurement.builder.done")}</Button>@@ -657,143 +483,89 @@ export function QuoteBuilder({);}-function Step({- icon,- title,- sub,- children,+/** Why a quote under the Enterprise minimum can't go ahead, and the ways on from there. */+function MinimumNotice({+ near,+ minMinor,+ previewMinor,+ onScheduleCall,+ onRaise,+ onEditUsage,+ onComparePlans,}: {- icon: ReactNode;- title: string;- sub: string;- children: React.ReactNode;+ /** Close enough that a little more usage clears it. */+ near: boolean;+ minMinor: number;+ previewMinor: number;+ onScheduleCall?: () => void;+ onRaise: () => void;+ onEditUsage: () => void;+ onComparePlans?: () => void;}) {+ const { t } = useTranslation();return (- <>- <div className="portal-qb__intro">- <span className="portal-qb__intro-icon" aria-hidden>- {icon}- </span>- <div>- <div className="portal-qb__intro-title">{title}</div>- <div className="portal-qb__intro-sub">{sub}</div>+ <Banner+ tone="warning"+ className="portal-qb__minimum-callout"+ title={+ near+ ? t(+ "portal.procurement.builder.minimumNearTitle",+ "You're {{gap}} a year short of Enterprise.",+ { gap: money(minMinor - previewMinor) },+ )+ : t(+ "portal.procurement.builder.minimum",+ "Enterprise requires a minimum yearly spend of {{min}}.",+ { min: money(minMinor) },+ )+ }+ action={+ <div className="portal-qb__minimum-actions">+ {near ? (+ <>+ {onScheduleCall && (+ <Button variant="secondary" onClick={onScheduleCall}>+ {t("portal.procurement.hero.scheduleCall")}+ </Button>+ )}+ <Button variant="primary" onClick={onRaise}>+ {t(+ "portal.procurement.builder.raiseUsage",+ "Raise estimated usage",+ )}+ </Button>+ </>+ ) : (+ <>+ <Button variant="secondary" onClick={onEditUsage}>+ {t("portal.procurement.builder.editUsage", "Edit usage")}+ </Button>+ {onComparePlans && (+ <Button+ variant="primary"+ rightSection={<Icon name="arrow-right" size={16} />}+ onClick={onComparePlans}+ >+ {t("portal.billing.compare.open", "Compare plans")}+ </Button>+ )}+ </>+ )}</div>- </div>- {children}- </>- );-}--function Field({- label,- required,- invalid,- children,-}: {- label: string;- required?: boolean;- invalid?: boolean;- children: React.ReactNode;-}) {- return (- <label className="portal-qb__field" data-invalid={invalid || undefined}>- <span className="portal-qb__field-label">- {label}- {required && (- <span className="portal-qb__req" aria-hidden>- {" *"}- </span>- )}- </span>- {children}- </label>- );-}--function OptCard({- on,- title,- sub,- onClick,-}: {- on: boolean;- title: string;- sub: string;- onClick: () => void;-}) {- return (- <button- type="button"- className="portal-qb__opt"- data-on={on || undefined}- onClick={onClick}- >- <span className="portal-qb__opt-title">{title}</span>- <span className="portal-qb__opt-sub">{sub}</span>- </button>- );-}--function AddOn({- on,- title,- sub,- onClick,-}: {- on: boolean;- title: string;- sub: string;- onClick: () => void;-}) {- return (- <button- type="button"- className="portal-qb__addon"- data-on={on || undefined}- onClick={onClick}+ }>- <span className="portal-qb__addon-box" aria-hidden>- {on ? "✓" : ""}- </span>- <span>- <span className="portal-qb__addon-title">{title}</span>- <span className="portal-qb__addon-sub">{sub}</span>- </span>- </button>+ {near+ ? t(+ "portal.procurement.builder.minimumNear",+ "Enterprise requires a minimum yearly spend of {{min}}. Raise your estimated usage to reach it, or talk it through with us.",+ { min: money(minMinor) },+ )+ : t(+ "portal.procurement.builder.minimumBelow",+ "This quote comes to {{annual}} a year. If you expect to use more, raise your estimated usage; otherwise the Team plan is likely a better fit.",+ { annual: money(previewMinor) },+ )}+ </Banner>);}--function estimateVolume(users: number): number {- const raw = Math.max(0, users) * 5 * 230 * 1.75;- const stepSize = raw >= 1_000_000 ? 50_000 : raw >= 100_000 ? 25_000 : 5_000;- return Math.round(raw / stepSize) * stepSize;-}--// Client mirror of the server pricing curve (ProcurementPricingService / quotePricing). The server-// is authoritative; this only drives the live footer estimate. Minor units (cents); the meter-// rounds to whole dollars, exactly like the backend, so the preview matches the issued quote.-// Exported for the pricing-parity test, which pins this client estimate to the mock and the-// server's published fixtures so a rate-card change can't silently desync the footer from the-// issued quote. This copy stays non-authoritative — the backend prices the real quote.-export function previewAnnualMinor(cfg: QuoteConfigInput): number {- const LIST = 0.01;- const FLOOR = 0.005;- const runVol = Math.max(0, cfg.volume) * Math.max(1, cfg.intensity);- const volDisc =- runVol > 1_000_000- ? Math.min(0.5, 0.06 * Math.log2(runVol / 1_000_000))- : 0;- const rate = Math.max(FLOOR, LIST * (1 - volDisc)) * (cfg.sizeMult || 1);- const termDisc = TERM_DISCOUNT[Math.min(Math.max(cfg.termYears, 1), 5) - 1];- const meterNet = Math.round(runVol * rate * (1 - termDisc)) * 100; // whole $ → minor units- const support = cfg.serviceLevel === "dedicated" ? 3_000_000 : 0; // std + priority included- const deploy =- cfg.deployment === "airgap"- ? 3_600_000- : cfg.deployment === "selfhost"- ? 1_200_000- : 0;- const indemnity = cfg.indemnification ? Math.round(meterNet * 0.05) : 0;- const qbr = cfg.qbr ? 800_000 : 0;- return meterNet + support + deploy + indemnity + qbr;-}diff --git a/frontend/src/processor/proprietary/components/procurement/QuoteBuilderSteps.tsx b/frontend/src/processor/proprietary/components/procurement/QuoteBuilderSteps.tsxnew file mode 100644index 0000000000..3a89fd59b6--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/QuoteBuilderSteps.tsx@@ -0,0 +1,420 @@+import { type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Icon } from "@editor/ui/Icon";+import type { QuoteConfigInput, RateCard } from "@processor/api/procurement";+import { money } from "@processor/components/procurement/format";+import { privateContentClassName } from "@editor/components/shared/privateContentClassName";+import {+ ConsentCheckbox,+ emailFieldError,+ Field,+ FieldGroup,+ OptionCard,+} from "@processor/components/procurement/formField";+import {+ estimateVolume,+ POSTURES,+ SIZE_TIERS,+ termDiscount,+} from "@processor/components/procurement/quotePricing";++/** Sets one field of the quote being built. */+export type SetQuoteField = <K extends keyof QuoteConfigInput>(+ k: K,+ v: QuoteConfigInput[K],+) => void;++/** Which of the buyer's required details are filled in validly. */+export type QuoteDetailsValidity = Record<+ | "businessName"+ | "contactName"+ | "contactEmail"+ | "addressLine1"+ | "city"+ | "region"+ | "postalCode",+ boolean+>;++/** How much the buyer will process, which sets the usage fee. */+export function SizingStep({+ cfg,+ set,+ manualVolume,+ setManualVolume,+ volumeInvalid,+}: {+ cfg: QuoteConfigInput;+ set: SetQuoteField;+ /** The volume was typed rather than estimated from the team size. */+ manualVolume: boolean;+ setManualVolume: (manual: boolean) => void;+ volumeInvalid: boolean;+}) {+ const { t } = useTranslation();+ return (+ <Step+ icon={<Icon name="file-text" size={22} />}+ title={t("portal.procurement.builder.s1Title")}+ sub={t("portal.procurement.builder.s1Sub")}+ >+ <div className="portal-qb__row">+ <Field label={t("portal.procurement.builder.users")}>+ <input+ type="number"+ min={0}+ placeholder={t("portal.procurement.builder.usersPlaceholder")}+ value={cfg.users || ""}+ onChange={(e) => {+ const users = Number(e.target.value);+ set("users", users);+ // A manual figure gives way here, as the hint under the fields promises.+ setManualVolume(false);+ set("volume", estimateVolume(users));+ }}+ />+ </Field>+ <Field+ label={t("portal.procurement.builder.volume")}+ required+ invalid={volumeInvalid}+ error={t("portal.procurement.validation.volume")}+ >+ <input+ type="number"+ min={0}+ placeholder={t("portal.procurement.builder.volumePlaceholder")}+ value={cfg.volume || ""}+ onChange={(e) => {+ setManualVolume(true);+ set("volume", Number(e.target.value));+ }}+ />+ </Field>+ </div>+ <p className="portal-qb__hint">+ {cfg.users > 0 && !manualVolume+ ? t("portal.procurement.builder.volEstimated", {+ count: cfg.users,+ })+ : cfg.users > 0+ ? t("portal.procurement.builder.volManual")+ : t("portal.procurement.builder.volNoUsers")}+ </p>+ <FieldGroup label={t("portal.procurement.builder.posture")}>+ <div className="portal-qb__opts">+ {POSTURES.map((p) => (+ <OptionCard+ key={p.key}+ on={cfg.intensity === p.intensity}+ title={t(`portal.procurement.builder.posture_${p.key}`)}+ sub={`${t("portal.procurement.builder.posture_count", {+ count: p.intensity,+ })} · ${t(`portal.procurement.builder.posture_${p.key}Sub`)}`}+ onClick={() => set("intensity", p.intensity)}+ />+ ))}+ </div>+ </FieldGroup>++ <FieldGroup label={t("portal.procurement.builder.pdfSize")}>+ <div className="portal-qb__opts">+ {SIZE_TIERS.map((s) => (+ <OptionCard+ key={s.key}+ on={cfg.sizeMult === s.mult}+ title={t(`portal.procurement.builder.size_${s.key}`)}+ // The multiplier stays in the price, not on the card: it is rate detail buyers+ // need not weigh, and the running estimate already shows its effect.+ sub={t(`portal.procurement.builder.size_${s.key}Sub`)}+ onClick={() => set("sizeMult", s.mult)}+ />+ ))}+ </div>+ </FieldGroup>+ </Step>+ );+}++/** Term, service level and add-ons. */+export function PlanStep({+ cfg,+ set,+ rates,+ indemnityPreview,+}: {+ cfg: QuoteConfigInput;+ set: SetQuoteField;+ rates: RateCard;+ /** What indemnification adds a year at the current usage, in cents. */+ indemnityPreview: number;+}) {+ const { t } = useTranslation();+ return (+ <Step+ icon={<Icon name="shield-check" size={22} />}+ title={t("portal.procurement.builder.s2Title")}+ sub={t("portal.procurement.builder.s2Sub")}+ >+ <FieldGroup label={t("portal.procurement.builder.term")}>+ <div className="portal-qb__pills">+ {rates.termDiscountByYear+ .map((_, i) => i + 1)+ .map((y) => (+ <button+ key={y}+ type="button"+ aria-pressed={cfg.termYears === y}+ data-on={cfg.termYears === y || undefined}+ onClick={() => set("termYears", y)}+ >+ {t("portal.procurement.builder.years", { count: y })}+ </button>+ ))}+ </div>+ {termDiscount(rates, cfg.termYears) > 0 && (+ <p className="portal-qb__discount">+ {t("portal.procurement.builder.termDiscount", {+ pct: Math.round(termDiscount(rates, cfg.termYears) * 100),+ })}+ </p>+ )}+ </FieldGroup>++ <FieldGroup label={t("portal.procurement.builder.serviceLevel")}>+ <div className="portal-qb__opts">+ <OptionCard+ on={cfg.serviceLevel === "standard"}+ title={t("portal.procurement.builder.slStandard")}+ sub={t("portal.procurement.builder.slStandardSub")}+ onClick={() => set("serviceLevel", "standard")}+ />+ <OptionCard+ on={cfg.serviceLevel === "priority"}+ title={t("portal.procurement.builder.slPriority")}+ sub={t("portal.procurement.builder.slPrioritySub")}+ onClick={() => set("serviceLevel", "priority")}+ />+ <OptionCard+ on={cfg.serviceLevel === "dedicated"}+ title={t("portal.procurement.builder.slDedicated")}+ sub={t("portal.procurement.builder.slDedicatedSub")}+ onClick={() => set("serviceLevel", "dedicated")}+ />+ </div>+ </FieldGroup>++ <FieldGroup label={t("portal.procurement.builder.addons")}>+ <div className="portal-qb__addons">+ <AddOn+ on={cfg.indemnification}+ title={t("portal.procurement.builder.indemnification")}+ sub={`${t("portal.procurement.builder.indemnificationSub")} · ${t(+ "portal.procurement.builder.addonPerYear",+ { amount: money(indemnityPreview) },+ )}`}+ onClick={() => set("indemnification", !cfg.indemnification)}+ />+ <AddOn+ on={cfg.training}+ title={t("portal.procurement.builder.training")}+ sub={`${t("portal.procurement.builder.trainingSub")} · ${t(+ "portal.procurement.builder.addonOneTime",+ { amount: money(rates.trainingOneTimeMinor) },+ )}`}+ onClick={() => set("training", !cfg.training)}+ />+ <AddOn+ on={cfg.qbr}+ title={t("portal.procurement.builder.qbr")}+ sub={`${t("portal.procurement.builder.qbrSub")} · ${t(+ "portal.procurement.builder.addonPerYear",+ { amount: money(rates.qbrAnnualMinor) },+ )}`}+ onClick={() => set("qbr", !cfg.qbr)}+ />+ </div>+ </FieldGroup>+ </Step>+ );+}++/** The buying entity's details, which the order form and invoice need. */+export function DetailsStep({+ cfg,+ set,+ valid,+ showErrors,+ emailTouched,+ onEmailBlur,+ eula,+}: {+ cfg: QuoteConfigInput;+ set: SetQuoteField;+ valid: QuoteDetailsValidity;+ /** The buyer has tried to generate, so every invalid field says why. */+ showErrors: boolean;+ emailTouched: boolean;+ onEmailBlur: () => void;+ /** The EULA clickwrap, or null when the buyer already accepted it. */+ eula: {+ checked: boolean;+ onChange: (agreed: boolean) => void;+ onView: () => void;+ } | null;+}) {+ const { t } = useTranslation();+ const required = t("portal.procurement.validation.required");+ /** One of the buyer's text details; its label and placeholder keys follow its name. */+ const text = (+ name:+ | Exclude<keyof QuoteDetailsValidity, "contactEmail">+ | "addressLine2"+ | "poNumber"+ | "taxId",+ ) => {+ const isRequired = name in valid;+ return (+ <Field+ label={t(`portal.procurement.builder.${name}`)}+ required={isRequired}+ invalid={+ isRequired && showErrors && !valid[name as keyof QuoteDetailsValidity]+ }+ error={required}+ >+ <input+ className={privateContentClassName}+ placeholder={t(`portal.procurement.builder.${name}Placeholder`)}+ value={cfg[name] ?? ""}+ onChange={(e) => set(name, e.target.value)}+ />+ </Field>+ );+ };+ const emailError = emailFieldError(+ cfg.contactEmail,+ { tried: showErrors, touched: emailTouched },+ { required, invalid: t("portal.procurement.validation.email") },+ );+ const eulaInvalid = eula != null && showErrors && !eula.checked;+ const incomplete =+ !Object.values(valid).every(Boolean) || (eula != null && !eula.checked);+ return (+ <Step+ icon={<Icon name="users" size={22} />}+ title={t("portal.procurement.builder.s3Title")}+ sub={t("portal.procurement.builder.s3Sub")}+ >+ <div className="portal-qb__row">+ {text("businessName")}+ {text("contactName")}+ </div>+ <Field+ label={t("portal.procurement.builder.contactEmail")}+ required+ invalid={emailError != null}+ error={emailError ?? undefined}+ >+ <input+ type="email"+ className={privateContentClassName}+ placeholder={t("portal.procurement.builder.contactEmailPlaceholder")}+ value={cfg.contactEmail ?? ""}+ onChange={(e) => set("contactEmail", e.target.value)}+ onBlur={onEmailBlur}+ />+ </Field>+ {text("addressLine1")}+ {text("addressLine2")}+ <div className="portal-qb__row">+ {text("city")}+ {text("region")}+ {text("postalCode")}+ </div>+ <div className="portal-qb__row">+ {text("poNumber")}+ {text("taxId")}+ </div>+ {eula && (+ <ConsentCheckbox+ checked={eula.checked}+ onChange={eula.onChange}+ invalid={eulaInvalid}+ error={t("portal.procurement.validation.eula")}+ >+ {t("portal.procurement.builder.eula")}{" "}+ <button+ type="button"+ className="portal-legal__link"+ onClick={eula.onView}+ >+ {t("portal.procurement.builder.viewEula")}+ </button>+ </ConsentCheckbox>+ )}+ {showErrors && incomplete && (+ <p className="portal-qb__error" role="alert">+ {t("portal.procurement.builder.completeRequired")}+ </p>+ )}+ </Step>+ );+}++function Step({+ icon,+ title,+ sub,+ children,+}: {+ icon: ReactNode;+ title: string;+ sub: string;+ children: ReactNode;+}) {+ return (+ <>+ <div className="portal-qb__intro">+ <span className="portal-qb__intro-icon" aria-hidden>+ {icon}+ </span>+ <div>+ <div className="portal-qb__intro-title">{title}</div>+ <div className="portal-qb__intro-sub">{sub}</div>+ </div>+ </div>+ {children}+ </>+ );+}++function AddOn({+ on,+ title,+ sub,+ onClick,+}: {+ on: boolean;+ title: string;+ sub: string;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ className="portal-qb__addon"+ aria-pressed={on}+ data-on={on || undefined}+ onClick={onClick}+ >+ <span className="portal-qb__addon-box" aria-hidden>+ {on ? "✓" : ""}+ </span>+ <span>+ <span className="portal-qb__addon-title">{title}</span>+ <span className="portal-qb__addon-sub">{sub}</span>+ </span>+ </button>+ );+}diff --git a/frontend/src/processor/proprietary/components/procurement/QuotePaper.tsx b/frontend/src/processor/proprietary/components/procurement/QuotePaper.tsxnew file mode 100644index 0000000000..2eccf1183a--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/QuotePaper.tsx@@ -0,0 +1,187 @@+import type { TFunction } from "i18next";+import { useTranslation } from "react-i18next";+import { Button } from "@editor/ui";+import { Icon } from "@editor/ui/Icon";+import type {+ QuoteLineItem,+ QuoteResult,+ RateCard,+} from "@processor/api/procurement";+import { money, unitRate } from "@processor/components/procurement/format";+import {+ perRunRate,+ POSTURES,+} from "@processor/components/procurement/quotePricing";++/**+ * The issued quote as the buyer circulates it. Shows the real issued figures, not the builder's+ * client-side preview, so it matches the PDF and the Stripe quote exactly.+ */+export function QuotePaper({+ issued,+ rates,+ downloading,+ onDownload,+}: {+ issued: QuoteResult;+ rates: RateCard;+ downloading: boolean;+ onDownload?: () => void;+}) {+ const { t } = useTranslation();+ return (+ <div className="portal-qb__papertray">+ <div className="portal-surface portal-qb__paper">+ <div className="portal-qb__paper-head">+ <div>+ <div className="portal-qb__paper-brand">+ {t("portal.procurement.builder.paperBrand", "Stirling PDF")}+ </div>+ <div className="portal-qb__paper-eyebrow">+ {t("portal.procurement.builder.paperEyebrow")}+ </div>+ </div>+ <div className="portal-qb__paper-meta">+ <div className="portal-qb__quote-number">{issued.quoteNumber}</div>+ {issued.validUntil && (+ <div>+ {t("portal.procurement.review.validUntil", {+ date: new Date(issued.validUntil).toLocaleDateString(+ undefined,+ {+ timeZone: "UTC",+ },+ ),+ })}+ </div>+ )}+ {/* On the document rather than in the footer: it downloads this paper, so it+ belongs to it, and the footer stays the flow's own Back/Done. */}+ <Button+ variant="tertiary"+ size="sm"+ className="portal-qb__paper-download"+ leftSection={<Icon name="download" size={14} />}+ loading={downloading}+ onClick={onDownload}+ >+ {t("portal.procurement.review.downloadCta")}+ </Button>+ </div>+ </div>++ {issued.config.businessName?.trim() && (+ <div className="portal-qb__paper-for">+ <div className="portal-qb__paper-eyebrow">+ {t("portal.procurement.builder.paperFor")}+ </div>+ <div className="portal-qb__paper-company">+ {issued.config.businessName}+ </div>+ </div>+ )}++ <ul className="portal-qb__lines">+ {issued.lineItems.map((li) => (+ <li key={li.key} data-kind={li.kind}>+ <span>{lineLabel(li, issued, rates, t)}</span>+ <span>+ {/* Marked, since one-off charges sit outside the yearly fee totalled below. */}+ {li.kind === "ONE_TIME" && (+ <span className="portal-qb__line-note">+ {t("portal.procurement.review.oneTime")}+ </span>+ )}+ {money(li.amountMinor, issued.currency)}+ </span>+ </li>+ ))}+ </ul>++ <div className="portal-qb__total">+ <div>+ <div className="portal-qb__total-label">+ {t("portal.procurement.review.annual")}+ </div>+ <div className="portal-qb__total-tcv">+ {t("portal.procurement.review.tcv", {+ years: issued.config.termYears,+ tcv: money(issued.tcvMinor, issued.currency),+ })}+ </div>+ <div className="portal-qb__total-tcv">+ {t("portal.procurement.review.renewal", {+ amount: money(issued.renewalAnnualNetMinor, issued.currency),+ pct: issued.cpiRatePct,+ })}+ </div>+ {issued.config.poNumber?.trim() && (+ <div className="portal-qb__total-tcv">+ {t("portal.procurement.review.poNumber", {+ po: issued.config.poNumber.trim(),+ })}+ </div>+ )}+ </div>+ <div className="portal-qb__total-num">+ <strong>{money(issued.annualNetMinor, issued.currency)}</strong>+ </div>+ </div>+ </div>+ </div>+ );+}++/**+ * An issued quote's line in the viewer's language. The server words its lines in English for the+ * PDF and Stripe, so each known line is rebuilt from its key and the quote's own inputs; a line+ * this page does not know keeps the server's wording.+ */+function lineLabel(+ li: QuoteLineItem,+ quote: QuoteResult,+ rates: RateCard,+ t: TFunction,+): string {+ const cfg = quote.config;+ switch (li.key) {+ case "usage": {+ const posture = POSTURES.find((p) => p.intensity === cfg.intensity);+ if (!posture) return li.label;+ return t("portal.procurement.builder.line.usage", {+ volume: cfg.volume.toLocaleString(),+ // From the current rate card: the line carries its amount but not the rate it was issued at.+ rate: unitRate(+ perRunRate(cfg, rates) * Math.max(1, cfg.intensity),+ quote.currency,+ ),+ posture: t(`portal.procurement.builder.posture_${posture.key}`),+ });+ }+ case "seats":+ return cfg.users > 0+ ? t("portal.procurement.builder.line.seats", {+ count: cfg.users,+ users: cfg.users.toLocaleString(),+ })+ : t("portal.procurement.builder.line.seatsUnset");+ case "multi-year":+ return t("portal.procurement.builder.line.multiYear", {+ count: cfg.termYears,+ });+ case "support":+ return t("portal.procurement.builder.line.support");+ case "deployment":+ return t("portal.procurement.builder.line.deployment", {+ deployment: t(`portal.procurement.setup.${cfg.deployment}`),+ });+ case "indemnification":+ return t("portal.procurement.builder.line.indemnification");+ case "qbr":+ return t("portal.procurement.builder.line.qbr");+ case "training":+ return t("portal.procurement.builder.line.training");+ default:+ return li.label;+ }+}diff --git a/frontend/src/processor/proprietary/components/procurement/SetupChecklist.css b/frontend/src/processor/proprietary/components/procurement/SetupChecklist.cssnew file mode 100644index 0000000000..ab05c29ff0--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/SetupChecklist.css@@ -0,0 +1,113 @@+/* Headings use the Enterprise page's own (.ent__h2, .ent__h3), which this only adjusts. */+.ent-setup__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.ent-setup__steps {+ display: flex;+ flex-direction: column;+ margin: 1.25rem 0 0;+ padding: 0;+ list-style: none;+}++.ent-setup__step {+ display: flex;+ gap: 1rem;+ padding: 1rem 0;+ border-top: 1px solid var(--c-border-subtle);+}++.ent-setup__tick {+ display: grid;+ flex: none;+ place-items: center;+ width: 1.75rem;+ height: 1.75rem;+ border: 2px solid var(--c-border-strong);+ border-radius: 50%;+ background: var(--c-bg-raised);+ font: inherit;+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--c-text-muted);+ cursor: pointer;+}++.ent-setup__tick:hover:not(:disabled) {+ border-color: var(--c-primary);+}++.ent-setup__tick:focus-visible {+ outline: 2px solid var(--c-primary);+ outline-offset: 2px;+}++.ent-setup__tick:disabled {+ cursor: default;+}++.ent-setup__step[data-done] .ent-setup__tick {+ border-color: var(--c-success);+ background: var(--c-success);+ color: var(--c-text-on-primary);+}++.ent-setup__step[data-done] .ent__h3 {+ color: var(--c-text-muted);+}++.ent-setup__content {+ flex: 1;+ min-width: 0;+}++.ent-setup__links {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.5rem 1.25rem;+ margin-top: 0.75rem;+}++.ent-setup__link {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--c-accent-text);+ text-decoration: none;+}++.ent-setup__link:hover {+ text-decoration: underline;+ text-underline-offset: 0.2em;+}++/* Copy sits in the corner so the command keeps the full width. */+.ent-setup__code {+ position: relative;+ margin-top: 0.75rem;+}++.ent-setup__code pre {+ margin: 0;+ padding: 0.875rem 5rem 0.875rem 1rem;+ overflow-x: auto;+ border: 1px solid var(--c-border);+ border-radius: var(--radius-md);+ background: var(--c-surface-sunken);+ font-family: var(--font-mono);+ font-size: 0.8125rem;+ line-height: 1.55;+}++.ent-setup__code > .sui-btn {+ position: absolute;+ top: 0.375rem;+ right: 0.375rem;+}diff --git a/frontend/src/processor/proprietary/components/procurement/SetupChecklist.stories.tsx b/frontend/src/processor/proprietary/components/procurement/SetupChecklist.stories.tsxnew file mode 100644index 0000000000..5bf719e754--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/SetupChecklist.stories.tsx@@ -0,0 +1,45 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { SetupChecklist } from "@processor/components/procurement/SetupChecklist";+import "@processor/views/Enterprise.css";++/** The trial's setup steps, one set per deployment; at go-live the same steps form the rollout list. */+const meta: Meta<typeof SetupChecklist> = {+ title: "Portal/Procurement/Setup checklist",+ component: SetupChecklist,+ parameters: { layout: "padded" },+ decorators: [+ (Story) => (+ <div className="ent" style={{ height: "auto", padding: "1.5rem" }}>+ <Story />+ </div>+ ),+ ],+ args: {+ dealId: 1,+ licenseKey: "TRIAL-KEY-0001",+ live: false,+ teamSize: 1,+ onInvite: () => {},+ onDownloadOfflineLicense: () => {},+ downloadingLicense: false,+ },+};+export default meta;+type Story = StoryObj<typeof SetupChecklist>;++export const StirlingCloud: Story = { args: { deployment: "cloud" } };++/** A teammate has joined, so inviting is ticked from the account and cannot be unticked. */+export const CloudTeamInvited: Story = {+ args: { deployment: "cloud", teamSize: 3, dealId: 2 },+};++export const SelfHosted: Story = {+ args: { deployment: "selfhost", dealId: 3 },+};++export const AirGapped: Story = { args: { deployment: "airgap", dealId: 4 } };++export const GoLive: Story = {+ args: { deployment: "selfhost", live: true, dealId: 5 },+};diff --git a/frontend/src/processor/proprietary/components/procurement/SetupChecklist.test.tsx b/frontend/src/processor/proprietary/components/procurement/SetupChecklist.test.tsxnew file mode 100644index 0000000000..d7cd6e822e--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/SetupChecklist.test.tsx@@ -0,0 +1,81 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render as rtlRender, screen } from "@testing-library/react";+import type { ReactElement } from "react";+import { PortalTestProviders } from "@processor/test/TestQueryProvider";+import { SetupChecklist } from "@processor/components/procurement/SetupChecklist";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, fallback?: string, vars?: Record<string, unknown>) =>+ (fallback ?? _key).replace(/\{\{(\w+)\}\}/g, (_, name) =>+ String(vars?.[name] ?? ""),+ ),+ }),+}));++const render = (ui: ReactElement) =>+ rtlRender(ui, { wrapper: PortalTestProviders });++const base = {+ dealId: 7,+ licenseKey: "KEY-123",+ live: false,+ teamSize: 1,+ onInvite: () => {},+ onDownloadOfflineLicense: () => {},+ downloadingLicense: false,+};++describe("SetupChecklist", () => {+ beforeEach(() => window.localStorage.clear());++ it("gives a self-hosted buyer an install command carrying their licence", () => {+ render(<SetupChecklist {...base} deployment="selfhost" />);+ expect(screen.getByText("Install and start Stirling")).toBeInTheDocument();+ expect(screen.getByText(/PREMIUM_KEY=KEY-123/)).toBeInTheDocument();+ expect(screen.queryByText("Invite your team")).not.toBeInTheDocument();+ });++ it("points an air-gapped server at the offline licence file", () => {+ const onDownload = vi.fn();+ render(+ <SetupChecklist+ {...base}+ deployment="airgap"+ onDownloadOfflineLicense={onDownload}+ />,+ );+ expect(+ screen.getByText(/PREMIUM_KEY=file:\/configs\/stirling-enterprise\.lic/),+ ).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "Download licence file" }),+ );+ expect(onDownload).toHaveBeenCalledOnce();+ });++ it("remembers a step the buyer ticks, per deal", () => {+ const { unmount } = render(<SetupChecklist {...base} deployment="cloud" />);+ expect(screen.getByText("0 of 3 done")).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", {+ name: "Mark “Run your first document” done",+ }),+ );+ expect(screen.getByText("1 of 3 done")).toBeInTheDocument();+ unmount();++ render(<SetupChecklist {...base} deployment="cloud" />);+ expect(screen.getByText("1 of 3 done")).toBeInTheDocument();+ render(<SetupChecklist {...base} dealId={8} deployment="cloud" />);+ expect(screen.getByText("0 of 3 done")).toBeInTheDocument();+ });++ it("ticks inviting once a teammate has joined, and keeps it ticked", () => {+ render(<SetupChecklist {...base} deployment="cloud" teamSize={3} />);+ expect(screen.getByText("1 of 3 done")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Mark “Invite your team” done" }),+ ).toBeDisabled();+ });+});diff --git a/frontend/src/processor/proprietary/components/procurement/SetupChecklist.tsx b/frontend/src/processor/proprietary/components/procurement/SetupChecklist.tsxnew file mode 100644index 0000000000..f085fe7033--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/SetupChecklist.tsx@@ -0,0 +1,511 @@+import { useRef, useState, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Button, Card } from "@editor/ui";+import { Icon } from "@editor/ui/Icon";+import { EDITOR_URL } from "@processor/auth/editorUrl";+import { DownloadEditorModal } from "@processor/components/DownloadEditorModal";+import { useCopyFeedback } from "@processor/hooks/useCopyFeedback";+import { useEditorInstalled } from "@processor/hooks/useEditorInstalled";+import {+ DOCKER_IMAGE,+ type DockerImageTag,+} from "@editor/constants/selfHosting";+import type { Deployment } from "@processor/api/procurement";+import { ENTERPRISE_DOCS } from "@processor/components/procurement/enterpriseDocs";+import "@processor/views/Procurement.css";+import "@processor/components/procurement/SetupChecklist.css";++const DOC = ENTERPRISE_DOCS;+const image = (tag: DockerImageTag) => `${DOCKER_IMAGE}:${tag}`;+const IMAGE = image("latest");+/** Bundles the fonts an offline server cannot download. */+const FULL_IMAGE = image("latest-fat");++interface StepLink {+ label: string;+ href?: string;+ onClick?: () => void;+}++interface Step {+ id: string;+ title: string;+ body: string;+ links: StepLink[];+ /** A command to copy, for steps run on the buyer's own machines. */+ code?: string;+ /** Known from the account rather than ticked by the buyer. */+ done?: boolean;+}++/**+ * Getting Stirling itself running, for the deployment the buyer chose: open it on Cloud, or install,+ * sign in and license it on their own servers, with the command that starts it licensed.+ * Shown from the trial onward and kept at go-live, where it becomes the rollout checklist.+ *+ * <p>Ticks the buyer sets are remembered in this browser, per deal: there is no server record of+ * setup progress, and steps done on the buyer's own servers cannot be seen from here anyway.+ */+export function SetupChecklist({+ dealId,+ deployment,+ licenseKey,+ live,+ teamSize,+ onInvite,+ onDownloadOfflineLicense,+ downloadingLicense,+}: {+ dealId: number | null | undefined;+ deployment: string;+ licenseKey: string | null | undefined;+ /** At go-live the same steps read as the rollout checklist. */+ live: boolean;+ /** Seats in use on the team, so inviting is ticked once someone has joined. */+ teamSize: number;+ /** Absent for members, who cannot invite. */+ onInvite?: () => void;+ /** Absent for members: the licence file is the team leader's to download. */+ onDownloadOfflineLicense?: () => void;+ downloadingLicense: boolean;+}) {+ const { t } = useTranslation();+ const [ticked, setTicked] = useTicks(dealId);+ const [downloading, setDownloading] = useState(false);+ const editorInstalled = useEditorInstalled();+ // Buyers arrive from the website, so the app itself is the first thing most of them still need.+ const getApp = (label: string): StepLink => ({+ label,+ onClick: () => setDownloading(true),+ });+ const openApp: StepLink = {+ label: t("portal.enterprise.setup.links.openApp", "Open Stirling"),+ href: EDITOR_URL,+ };+ const kind: Deployment =+ deployment === "selfhost" || deployment === "airgap" ? deployment : "cloud";+ const key = licenseKey ?? "YOUR-LICENCE-KEY";++ const runCommand = (image: string, licence: string) =>+ [+ "docker run -d --name stirling-pdf -p 8080:8080 \\",+ ' -v "$(pwd)/stirling/configs:/configs" \\',+ ' -v "$(pwd)/stirling/logs:/logs" \\',+ " -e SECURITY_ENABLELOGIN=true \\",+ " -e PREMIUM_ENABLED=true \\",+ ` -e PREMIUM_KEY=${licence} \\`,+ ` ${image}`,+ ].join("\n");++ // The same first sign-in on any server the buyer runs: the default admin, then the licence.+ const signInStep: Step = {+ id: "signIn",+ title: t("portal.enterprise.setup.signIn.title", "Sign in as the admin"),+ body: t(+ "portal.enterprise.setup.signIn.body",+ "Open http://your-server:8080 and sign in with admin / stirling. You'll be asked to choose a new password straight away.",+ ),+ links: [],+ };++ const ssoLinks: StepLink[] = [+ {+ label: t("portal.enterprise.setup.links.ssoGuide", "SSO guide"),+ href: DOC.sso,+ },+ {+ label: t("portal.enterprise.setup.links.samlGuide", "SAML guide"),+ href: DOC.saml,+ },+ ];++ const peopleStep = (body: string): Step => ({+ id: "people",+ title: t("portal.enterprise.setup.people.title", "Add your people"),+ body,+ links: [+ getApp(+ t(+ "portal.enterprise.setup.links.downloadForTeam",+ "Get the app for your team",+ ),+ ),+ ...ssoLinks,+ ],+ });++ const steps: Step[] =+ kind === "cloud"+ ? [+ {+ id: "getApp",+ title: t("portal.enterprise.setup.getApp.title", "Get Stirling"),+ body: t(+ "portal.enterprise.setup.getApp.body",+ "Install the desktop app for Windows, Mac or Linux and sign in with the account you just made, or use it straight from your browser.",+ ),+ links: [+ getApp(+ t("portal.enterprise.setup.links.download", "Download the app"),+ ),+ {+ label: t(+ "portal.enterprise.setup.links.browser",+ "Use it in your browser",+ ),+ href: EDITOR_URL,+ },+ ],+ done: editorInstalled,+ },+ {+ id: "firstDocument",+ title: t(+ "portal.enterprise.setup.firstDocument.title",+ "Run your first document",+ ),+ body: t(+ "portal.enterprise.setup.firstDocument.body",+ "Upload a PDF your team works with and try the tools you'd use day to day, such as redact, compress or OCR.",+ ),+ links: [openApp],+ },+ {+ id: "invite",+ title: t(+ "portal.enterprise.setup.invite.title",+ "Invite your team",+ ),+ body: t(+ "portal.enterprise.setup.invite.body",+ "Bring in the people who'll use it, so the trial reflects real work.",+ ),+ links: onInvite+ ? [+ {+ label: t(+ "portal.enterprise.setup.links.invite",+ "Invite teammates",+ ),+ onClick: onInvite,+ },+ ]+ : [],+ done: teamSize > 1,+ },+ // No single sign-on step: on Stirling Cloud it needs self-hosting (see DeploymentOptions).+ ]+ : kind === "selfhost"+ ? [+ {+ id: "install",+ title: t(+ "portal.enterprise.setup.install.title",+ "Install and start Stirling",+ ),+ body: t(+ "portal.enterprise.setup.install.body",+ "Run this on your server. It starts Stirling with your licence applied, and the image includes OCR and office conversion. For larger teams, use Kubernetes.",+ ),+ code: runCommand(IMAGE, key),+ links: [+ {+ label: t(+ "portal.enterprise.setup.links.docker",+ "Docker guide",+ ),+ href: DOC.docker,+ },+ {+ label: t(+ "portal.enterprise.setup.links.kubernetes",+ "Kubernetes guide",+ ),+ href: DOC.kubernetes,+ },+ ],+ },+ signInStep,+ {+ id: "licence",+ title: t(+ "portal.enterprise.setup.licence.title",+ "Check your licence is active",+ ),+ body: t(+ "portal.enterprise.setup.licence.body",+ "Open http://your-server:8080/settings/adminPlan, where your Enterprise licence should show as active. Installed another way? Add the key under premium.key in settings.yml and restart.",+ ),+ links: [+ {+ label: t(+ "portal.enterprise.setup.links.licence",+ "Licence activation",+ ),+ href: DOC.licence,+ },+ ],+ },+ peopleStep(+ t(+ "portal.enterprise.setup.people.bodySelfHosted",+ "Create accounts at /settings/people, or connect your identity provider so your team signs in with their work accounts. They use Stirling in the browser at your server's address, or in the desktop app pointed at it.",+ ),+ ),+ ]+ : [+ {+ id: "offlineLicence",+ title: t(+ "portal.enterprise.setup.offlineLicence.title",+ "Download your offline licence",+ ),+ body: t(+ "portal.enterprise.setup.offlineLicence.body",+ "An air-gapped server can't reach our licence service, so it checks this signed file instead. Keep it with the image you carry across.",+ ),+ links: onDownloadOfflineLicense+ ? [+ {+ label: downloadingLicense+ ? t(+ "portal.enterprise.setup.links.downloading",+ "Downloading...",+ )+ : t(+ "portal.enterprise.setup.links.downloadLicence",+ "Download licence file",+ ),+ onClick: onDownloadOfflineLicense,+ },+ ]+ : [],+ },+ {+ id: "install",+ title: t(+ "portal.enterprise.setup.offlineInstall.title",+ "Bring Stirling across and start it",+ ),+ body: t(+ "portal.enterprise.setup.offlineInstall.body",+ "Pull the full image on a connected machine, carry it and the licence file across, then load and start it. The full image adds the fonts an offline server can't download.",+ ),+ code: [+ "# On a connected machine",+ `docker pull ${FULL_IMAGE}`,+ `docker save -o stirling-pdf.tar ${FULL_IMAGE}`,+ "",+ "# On the air-gapped server, with stirling-enterprise.lic in ./stirling/configs",+ "docker load -i stirling-pdf.tar",+ runCommand(FULL_IMAGE, "file:/configs/stirling-enterprise.lic"),+ ].join("\n"),+ links: [+ {+ label: t(+ "portal.enterprise.setup.links.docker",+ "Docker guide",+ ),+ href: DOC.docker,+ },+ {+ label: t(+ "portal.enterprise.setup.links.ocr",+ "OCR languages",+ ),+ href: DOC.ocr,+ },+ ],+ },+ {+ ...signInStep,+ body: t(+ "portal.enterprise.setup.signIn.bodyAirgap",+ "Open http://your-server:8080 and sign in with admin / stirling, choose a new password, then check /settings/adminPlan shows your licence as active.",+ ),+ },+ peopleStep(+ t(+ "portal.enterprise.setup.people.bodyAirgap",+ "Create accounts at /settings/people, or point Stirling at your internal identity provider so sign-in never leaves your network.",+ ),+ ),+ ];++ const isDone = (step: Step) => step.done || ticked.includes(step.id);+ const doneCount = steps.filter(isDone).length;++ return (+ <Card padding="loose" className="ent-setup">+ <DownloadEditorModal+ open={downloading}+ onClose={() => setDownloading(false)}+ // Their deployment is already chosen; only the apps that connect to it are on offer.+ desktopOnly+ />+ <div className="ent-setup__head">+ <div>+ <h2 className="ent__h2">+ {live+ ? t("portal.enterprise.setup.titleLive", "Go-live checklist")+ : t("portal.enterprise.setup.title", "Get set up")}+ </h2>+ <p className="ent__text">+ {live+ ? t(+ "portal.enterprise.setup.subtitleLive",+ "The steps to finish before you roll out to everyone.",+ )+ : t(+ "portal.enterprise.setup.subtitle",+ "Make the most of your trial by trying it the way you'll run it.",+ )}+ </p>+ </div>+ <span className="ent__chip">+ {t("portal.enterprise.setup.progress", "{{done}} of {{total}} done", {+ done: doneCount,+ total: steps.length,+ })}+ </span>+ </div>+ <ol className="ent-setup__steps">+ {steps.map((step, index) => {+ const done = isDone(step);+ return (+ <li+ key={step.id}+ className="ent-setup__step"+ data-done={done || undefined}+ >+ <button+ type="button"+ className="ent-setup__tick"+ aria-pressed={done}+ aria-label={t(+ "portal.enterprise.setup.markDone",+ "Mark “{{step}}” done",+ {+ step: step.title,+ },+ )}+ // A step known from the account cannot be unticked by hand.+ disabled={step.done}+ onClick={() => setTicked(step.id, !done)}+ >+ {done ? <Icon name="check" size={14} /> : index + 1}+ </button>+ <div className="ent-setup__content">+ <h3 className="ent__h3">{step.title}</h3>+ <p className="ent__text">{step.body}</p>+ {step.code && <CodeBlock code={step.code} />}+ {step.links.length > 0 && (+ <div className="ent-setup__links">+ {step.links.map((link) => (+ <StepAction key={link.label} link={link} />+ ))}+ </div>+ )}+ </div>+ </li>+ );+ })}+ </ol>+ </Card>+ );+}++function StepAction({ link }: { link: StepLink }): ReactNode {+ if (link.onClick) {+ return (+ <Button variant="secondary" size="sm" onClick={link.onClick}>+ {link.label}+ </Button>+ );+ }+ const external = link.href?.startsWith("http");+ return (+ <a+ className="ent-setup__link"+ href={link.href}+ {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}+ >+ {link.label}+ {external && <Icon name="external-link" size={13} />}+ </a>+ );+}++function CodeBlock({ code }: { code: string }) {+ const { t } = useTranslation();+ const { copied, copy: copyCode } = useCopyFeedback();+ const codeRef = useRef<HTMLElement>(null);+ const copy = () => {+ void copyCode(code).then((ok) => {+ if (ok) return;+ // The browser refused: select the command so the admin can copy it by hand.+ const range = document.createRange();+ if (codeRef.current) range.selectNodeContents(codeRef.current);+ window.getSelection()?.removeAllRanges();+ window.getSelection()?.addRange(range);+ });+ };+ return (+ <div className="ent-setup__code">+ <pre>+ <code ref={codeRef}>{code}</code>+ </pre>+ <Button variant="tertiary" size="sm" onClick={copy}>+ {copied+ ? t("portal.enterprise.setup.copied", "Copied")+ : t("portal.enterprise.setup.copy", "Copy")}+ </Button>+ </div>+ );+}++const TICKS_KEY = "stirling-enterprise-setup";++function readTicks(storageKey: string): string[] {+ try {+ const raw = window.localStorage.getItem(storageKey);+ const parsed: unknown = raw ? JSON.parse(raw) : [];+ return Array.isArray(parsed)+ ? parsed.filter((v): v is string => typeof v === "string")+ : [];+ } catch {+ return [];+ }+}++/** The steps the buyer ticked on this deal, kept in this browser. */+function useTicks(+ dealId: number | null | undefined,+): [string[], (id: string, on: boolean) => void] {+ const storageKey = `${TICKS_KEY}:${dealId ?? "none"}`;+ const [state, setState] = useState(() => ({+ key: storageKey,+ ticked: readTicks(storageKey),+ }));+ // Another deal's ticks are read afresh, never carried over and saved under its key.+ if (state.key !== storageKey) {+ setState({ key: storageKey, ticked: readTicks(storageKey) });+ }+ const setTicked = (id: string, on: boolean) => {+ setState((current) => {+ const next = on+ ? [...new Set([...current.ticked, id])]+ : current.ticked.filter((v) => v !== id);+ try {+ window.localStorage.setItem(current.key, JSON.stringify(next));+ } catch {+ // Storage unavailable: the ticks last for this visit only.+ }+ return { key: current.key, ticked: next };+ });+ };+ return [+ state.key === storageKey ? state.ticked : readTicks(storageKey),+ setTicked,+ ];+}diff --git a/frontend/src/processor/proprietary/components/procurement/TrialSetupForm.test.tsx b/frontend/src/processor/proprietary/components/procurement/TrialSetupForm.test.tsxnew file mode 100644index 0000000000..0a4547fa7b--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/TrialSetupForm.test.tsx@@ -0,0 +1,115 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { TrialSetupForm } from "@processor/components/procurement/ProcurementExtras";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++function mount() {+ render(+ <MantineProvider>+ <TrialSetupForm+ busy={false}+ initial={{+ deployment: "cloud",+ seats: 5,+ details: { businessName: "Northwind", contactName: "Dana Lee" },+ }}+ onScheduleCall={vi.fn()}+ onConfirm={vi.fn()}+ />+ </MantineProvider>,+ );+ return screen.getByPlaceholderText(+ "portal.procurement.setup.workEmailPlaceholder",+ );+}++describe("TrialSetupForm work email", () => {+ it("says why the trial can't start once an invalid email is left", () => {+ const input = mount();+ fireEvent.change(input, { target: { value: "dana@northwind" } });+ expect(+ screen.queryByText("portal.procurement.validation.email"),+ ).not.toBeInTheDocument();++ fireEvent.blur(input);+ expect(+ screen.getByText("portal.procurement.validation.email"),+ ).toBeInTheDocument();+ expect(input).toHaveAttribute("aria-invalid", "true");++ fireEvent.change(input, { target: { value: "[email protected]" } });+ expect(+ screen.queryByText("portal.procurement.validation.email"),+ ).not.toBeInTheDocument();+ });++ it("stays quiet about an empty email the buyer hasn't reached yet", () => {+ const input = mount();+ fireEvent.blur(input);+ expect(+ screen.queryByText("portal.procurement.validation.email"),+ ).not.toBeInTheDocument();+ });+});++describe("TrialSetupForm blocked steps", () => {+ it("keeps Continue clickable and asks for the head count instead of moving on", () => {+ render(+ <MantineProvider>+ <TrialSetupForm+ busy={false}+ onScheduleCall={vi.fn()}+ onConfirm={vi.fn()}+ />+ </MantineProvider>,+ );+ const next = screen.getByRole("button", {+ name: "portal.procurement.setup.continue",+ });+ expect(next).toBeEnabled();+ fireEvent.click(next);+ expect(+ screen.getByText("portal.procurement.validation.seats"),+ ).toBeInTheDocument();+ expect(+ screen.queryByPlaceholderText(+ "portal.procurement.setup.workEmailPlaceholder",+ ),+ ).not.toBeInTheDocument();+ });++ it("names every missing detail and the EULA instead of starting the trial", () => {+ const onConfirm = vi.fn();+ render(+ <MantineProvider>+ <TrialSetupForm+ busy={false}+ initial={{ deployment: "cloud", seats: 5, details: {} }}+ onScheduleCall={vi.fn()}+ onConfirm={onConfirm}+ />+ </MantineProvider>,+ );+ const startButton = screen.getByRole("button", {+ name: "portal.procurement.setup.start",+ });+ expect(startButton).toBeEnabled();+ fireEvent.click(startButton);+ expect(onConfirm).not.toHaveBeenCalled();+ expect(+ screen.getAllByText("portal.procurement.validation.required"),+ ).toHaveLength(3);+ expect(+ screen.getByText("portal.procurement.validation.eula"),+ ).toBeInTheDocument();+ expect(+ screen.getByPlaceholderText(+ "portal.procurement.setup.fullNamePlaceholder",+ ),+ ).toHaveAttribute("aria-invalid", "true");+ });+});diff --git a/frontend/src/processor/proprietary/components/procurement/enterpriseDocs.ts b/frontend/src/processor/proprietary/components/procurement/enterpriseDocs.tsnew file mode 100644index 0000000000..e2a4656082--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/enterpriseDocs.ts@@ -0,0 +1,14 @@+/** The pages of the Stirling docs the Enterprise page links to. */+const DOCS = "https://docs.stirlingpdf.com";++export const ENTERPRISE_DOCS = {+ cloud: `${DOCS}/Cloud/`,+ server: `${DOCS}/Server/`,+ docker: `${DOCS}/Server/Install/Docker/`,+ kubernetes: `${DOCS}/Server/Install/Kubernetes/`,+ licence: `${DOCS}/Server/Licensing/Plans-and-Licences/`,+ offlineLicence: `${DOCS}/Server/Licensing/Plans-and-Licences/#activating-your-license`,+ sso: `${DOCS}/Server/Security/OAuth-SSO/`,+ saml: `${DOCS}/Server/Security/SAML-SSO/`,+ ocr: `${DOCS}/Server/Operations/OCR-Languages/`,+} as const;diff --git a/frontend/src/processor/proprietary/components/procurement/enterprisePath.ts b/frontend/src/processor/proprietary/components/procurement/enterprisePath.tsnew file mode 100644index 0000000000..41b46c9771--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/enterprisePath.ts@@ -0,0 +1,24 @@+import { useNavigate } from "react-router-dom";++/** The Enterprise page: trial, quote, agreement and licence, outside the app's own chrome. */+export const ENTERPRISE_PATH = "/enterprise";++/** An older address for the page. Sales emails and campaigns still link to it, so it redirects. */+export const LEGACY_ENTERPRISE_PATH = "/procurement";++export function useOpenEnterprise(): () => void {+ const navigate = useNavigate();+ return () => navigate(ENTERPRISE_PATH);+}++/**+ * Where a billing link that set out to start the Enterprise trial (`?procurement=start`, sent in+ * sales emails) now leads, keeping its other parameters; null for any other billing link.+ */+export function legacyProcurementTarget(search: string): string | null {+ const params = new URLSearchParams(search);+ if (params.get("procurement") !== "start") return null;+ params.delete("procurement");+ const rest = params.toString();+ return rest ? `${ENTERPRISE_PATH}?${rest}` : ENTERPRISE_PATH;+}diff --git a/frontend/src/processor/proprietary/components/procurement/formField.tsx b/frontend/src/processor/proprietary/components/procurement/formField.tsxnew file mode 100644index 0000000000..99b6956587--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/formField.tsx@@ -0,0 +1,187 @@+import {+ cloneElement,+ isValidElement,+ useId,+ type ReactElement,+ type ReactNode,+} from "react";++const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;++export function isEmail(value: string | null | undefined): boolean {+ return EMAIL_RE.test((value ?? "").trim());+}++export function isFilled(value: string | null | undefined): boolean {+ return (value ?? "").trim().length > 0;+}++/**+ * The error a required email field shows, or null. A missing email waits for an attempt to submit;+ * a mistyped one shows as soon as the buyer leaves the field.+ */+export function emailFieldError(+ value: string | null | undefined,+ { tried, touched }: { tried: boolean; touched: boolean },+ messages: { required: string; invalid: string },+): string | null {+ if (isEmail(value)) return null;+ if (!isFilled(value)) return tried ? messages.required : null;+ return tried || touched ? messages.invalid : null;+}++/**+ * Submit buttons in these forms stay enabled, so a blocked click must say why: this moves focus to+ * the first field marked invalid, once React has rendered the errors the click revealed.+ */+export function focusFirstInvalid(root: ParentNode | null = document): void {+ requestAnimationFrame(() => {+ root+ ?.querySelector<HTMLElement>(+ "[data-invalid] input, [data-invalid] select, [data-invalid] textarea",+ )+ ?.focus();+ });+}++type ControlAria = {+ "aria-invalid"?: boolean;+ "aria-required"?: boolean;+ "aria-describedby"?: string;+};++/**+ * A labelled form field for a single control. While `invalid` it turns red and says `error` under+ * the control, which it marks invalid and described by that error, so focusing it reads the reason.+ */+export function Field({+ label,+ required,+ invalid,+ error,+ children,+}: {+ label: string;+ required?: boolean;+ invalid?: boolean;+ error?: string;+ children: ReactNode;+}) {+ const errorId = useId();+ const showError = !!invalid && !!error;+ const control = isValidElement(children)+ ? cloneElement(children as ReactElement<ControlAria>, {+ "aria-invalid": invalid || undefined,+ "aria-required": required || undefined,+ "aria-describedby": showError ? errorId : undefined,+ })+ : children;+ return (+ <label className="portal-qb__field" data-invalid={invalid || undefined}>+ <span className="portal-qb__field-label">+ {label}+ {required && (+ <span className="portal-qb__req" aria-hidden>+ {" *"}+ </span>+ )}+ </span>+ {control}+ {showError && <FieldError id={errorId}>{error}</FieldError>}+ </label>+ );+}++/** A labelled set of option buttons. Not a <label>, which would pass its clicks to the first one. */+export function FieldGroup({+ label,+ children,+}: {+ label: string;+ children: ReactNode;+}) {+ const labelId = useId();+ return (+ <div className="portal-qb__field" role="group" aria-labelledby={labelId}>+ <span id={labelId} className="portal-qb__field-label">+ {label}+ </span>+ {children}+ </div>+ );+}++export function FieldError({+ id,+ children,+}: {+ id?: string;+ children: ReactNode;+}) {+ return (+ <span id={id} className="portal-qb__field-error">+ {children}+ </span>+ );+}++/** A box the buyer must tick to go on, such as accepting the EULA; `error` says so once `invalid`. */+export function ConsentCheckbox({+ checked,+ onChange,+ invalid,+ error,+ className = "portal-qb__eula",+ children,+}: {+ checked: boolean;+ onChange: (checked: boolean) => void;+ invalid: boolean;+ error: string;+ className?: string;+ children: ReactNode;+}) {+ const errorId = useId();+ return (+ <>+ <label className={className} data-invalid={invalid || undefined}>+ <input+ type="checkbox"+ checked={checked}+ aria-invalid={invalid || undefined}+ aria-required+ aria-describedby={invalid ? errorId : undefined}+ onChange={(e) => onChange(e.target.checked)}+ />+ <span>{children}</span>+ </label>+ {invalid && <FieldError id={errorId}>{error}</FieldError>}+ </>+ );+}++/** One choice in a FieldGroup of option cards. */+export function OptionCard({+ on,+ title,+ sub,+ onClick,+}: {+ on: boolean;+ title: string;+ sub: string;+ onClick: () => void;+}) {+ return (+ <button+ type="button"+ className="portal-qb__opt"+ aria-pressed={on}+ data-on={on || undefined}+ onClick={onClick}+ >+ <span className="portal-qb__opt-title">{title}</span>+ <span className="portal-qb__opt-sub">{sub}</span>+ </button>+ );+}diff --git a/frontend/src/processor/proprietary/components/procurement/format.ts b/frontend/src/processor/proprietary/components/procurement/format.tsindex e1e8effe30..d53734fcbe 100644--- a/frontend/src/processor/proprietary/components/procurement/format.ts+++ b/frontend/src/processor/proprietary/components/procurement/format.ts@@ -1,16 +1,56 @@-/** Money formatting for the procurement surface. */+/** Money, date and trial formatting for the procurement surface. */+import type { TFunction } from "i18next";-export const USD = new Intl.NumberFormat(undefined, {- style: "currency",- currency: "USD",- maximumFractionDigits: 0,-});--/** Format a minor-unit (cents) amount as whole USD (no decimals). USD only for now. */-export function money(minor: number, currency: string = "USD"): string {+/**+ * A currency formatter. Only USD gets the narrow "$"; other currencies keep their full symbol so "$"+ * never stands in for CAD or AUD.+ */+function currencyFormat(currency: string, digits: number): Intl.NumberFormat {+ const code = (currency || "USD").toUpperCase();return new Intl.NumberFormat(undefined, {style: "currency",- currency: currency || "USD",- maximumFractionDigits: 0,- }).format(minor / 100);+ currency: code,+ currencyDisplay: code === "USD" ? "narrowSymbol" : "symbol",+ minimumFractionDigits: digits,+ maximumFractionDigits: digits,+ });+}++/** Format a minor-unit (cents) amount in whole units. */+export function money(minor: number, currency: string = "USD"): string {+ return currencyFormat(currency, 0).format(minor / 100);+}++/** Format a per-unit rate in whole units, to four decimals: rates run to fractions of a cent. */+export function unitRate(amount: number, currency: string = "USD"): string {+ return currencyFormat(currency, 4).format(amount);+}++const DAY_MS = 86_400_000;++/** Whole days until `iso`, counting a part day as one; 0 once it has passed. */+export function daysLeft(iso: string): number {+ return Math.max(+ 0,+ Math.ceil((new Date(iso).getTime() - Date.now()) / DAY_MS),+ );+}++/** How long the trial ending at `iso` has left, or that it has expired. */+export function trialLeftLabel(t: TFunction, iso: string): string {+ const left = daysLeft(iso);+ return left === 0+ ? t("portal.procurement.journey.expired", "Trial expired")+ : t("portal.procurement.journey.daysLeft", { count: left });+}++/** A date written out in full, such as "15 November 2026"; a dash when there is none. */+export function longDate(iso: string | null | undefined): string {+ return iso+ ? new Date(iso).toLocaleDateString(undefined, {+ month: "long",+ day: "numeric",+ year: "numeric",+ })+ : "—";}diff --git a/frontend/src/processor/proprietary/components/procurement/prefill.ts b/frontend/src/processor/proprietary/components/procurement/prefill.tsnew file mode 100644index 0000000000..8627b1bdc9--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/prefill.ts@@ -0,0 +1,24 @@+import { createContext, useContext } from "react";++/**+ * Starting values for the procurement forms' required fields. Nothing in the product provides one;+ * a guided demo does, so it can run end to end without typing every field in front of an audience.+ * Each form still lets the values be edited.+ */+export interface ProcurementPrefill {+ seats?: number;+ contactName?: string;+ businessName?: string;+ contactEmail?: string;+ addressLine1?: string;+ city?: string;+ region?: string;+ postalCode?: string;+}++export const ProcurementPrefillContext =+ createContext<ProcurementPrefill | null>(null);++export function useProcurementPrefill(): ProcurementPrefill | null {+ return useContext(ProcurementPrefillContext);+}diff --git a/frontend/src/processor/proprietary/components/procurement/pricingParity.test.ts b/frontend/src/processor/proprietary/components/procurement/pricingParity.test.tsindex 45dc19ec24..02cde680ec 100644--- a/frontend/src/processor/proprietary/components/procurement/pricingParity.test.ts+++ b/frontend/src/processor/proprietary/components/procurement/pricingParity.test.ts@@ -1,19 +1,21 @@import { describe, expect, it } from "vitest";import type { QuoteConfigInput } from "@processor/api/procurement";-import { previewAnnualMinor } from "@processor/components/procurement/QuoteBuilder";-import { priceQuote } from "@processor/mocks/handlers/procurementSaas";+import { previewAnnualMinor } from "@processor/components/procurement/quotePricing";+import {+ priceQuote,+ RATE_CARD,+} from "@processor/mocks/handlers/procurementSaas";/**- * The D71 run-based curve is written three times: the authoritative Java engine- * (ProcurementPricingService), the client footer estimate (QuoteBuilder.previewAnnualMinor), and- * the MSW mock (procurementSaas.priceQuote). The client + mock are deliberately non-authoritative,- * but nothing stopped them silently drifting from the server.+ * The pricing formula runs in three places: the authoritative Java engine+ * (ProcurementPricingService), the client's live estimate (quotePricing.previewAnnualMinor) and the+ * MSW mock (procurementSaas.priceQuote). The rates come from the server's rate card, but the+ * formula itself is written in each, so nothing else stops them drifting apart.*- * This pins both TypeScript copies to each other AND to the exact fixtures locked in the Java- * ProcurementPricingServiceTest. If the rate card changes on the server, that Java test breaks- * first; updating these fixtures to match is the reminder to keep the client/mock in step. If the- * client and mock diverge from one another, this breaks on its own.+ * This pins both TypeScript copies, run over the default rate card, to the exact fixtures locked in+ * the Java ProcurementPricingServiceTest. A formula change on the server breaks that Java test+ * first; updating these fixtures to match is the reminder to change the client and mock too.** Keep these numbers identical to ProcurementPricingServiceTest.*/@@ -79,7 +81,7 @@ const FIXTURES: {describe("procurement pricing parity (client ↔ mock ↔ server fixtures)", () => {for (const f of FIXTURES) {it(`agrees on ${f.name}`, () => {- expect(previewAnnualMinor(f.cfg)).toBe(f.annualNetMinor);+ expect(previewAnnualMinor(f.cfg, RATE_CARD)).toBe(f.annualNetMinor);expect(priceQuote(f.cfg).annualNetMinor).toBe(f.annualNetMinor);});}diff --git a/frontend/src/processor/proprietary/components/procurement/quotePricing.ts b/frontend/src/processor/proprietary/components/procurement/quotePricing.tsnew file mode 100644index 0000000000..a18a96f785--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/quotePricing.ts@@ -0,0 +1,91 @@+/**+ * The server's pricing formula (ProcurementPricingService), run over the rate card it sends, so the+ * builder's live estimate needs no round trip yet can't drift from the server's figures. The server+ * prices the real quote. Minor units (cents); the meter rounds to whole dollars, exactly like the+ * backend, so the preview matches the issued quote. pricingParity.test.ts pins this formula to the+ * server's fixtures.+ */+import type { QuoteConfigInput, RateCard } from "@processor/api/procurement";++// Governance posture: the intensity (runs per PDF) fed to the committed-volume curve.+export const POSTURES = [+ { intensity: 2, key: "essentials" },+ { intensity: 4, key: "governed" },+ { intensity: 7, key: "regulated" },+] as const;+// PDF-size tiers: a multiplier on the rate. Mirrors the server.+export const SIZE_TIERS = [+ { mult: 1.0, key: "compact" },+ { mult: 1.4, key: "standard" },+ { mult: 2.4, key: "heavy" },+] as const;+/** Where a fresh quote starts: Governed, at the Standard PDF size. */+export const DEFAULT_POSTURE = POSTURES[1];+export const DEFAULT_SIZE_TIER = SIZE_TIERS[1];++/** PDFs a user processes a working day, working days a year, and headroom on top. */+const PDFS_PER_USER_DAY = 5;+const WORKING_DAYS = 230;+const VOLUME_HEADROOM = 1.75;++/** A starting annual volume for a team of this size, rounded to a figure that reads as an estimate. */+export function estimateVolume(users: number): number {+ const raw =+ Math.max(0, users) * PDFS_PER_USER_DAY * WORKING_DAYS * VOLUME_HEADROOM;+ const stepSize = raw >= 1_000_000 ? 50_000 : raw >= 100_000 ? 25_000 : 5_000;+ // A small team still processes something: rounding it to zero would leave nothing to price.+ return raw > 0+ ? Math.max(stepSize, Math.round(raw / stepSize) * stepSize)+ : 0;+}++/** Committed runs a year: PDFs times the policies each one runs through. */+function runVolume(cfg: QuoteConfigInput): number {+ return Math.max(0, cfg.volume) * Math.max(1, cfg.intensity);+}++/** Meter-only discount for a term of this many years, clamped to the terms the card prices. */+export function termDiscount(rates: RateCard, termYears: number): number {+ const byYear = rates.termDiscountByYear;+ return byYear[Math.min(Math.max(termYears, 1), byYear.length) - 1] ?? 0;+}++/** Dollars per run after the committed-volume curve, its floor and the PDF-size multiplier. */+export function perRunRate(cfg: QuoteConfigInput, rates: RateCard): number {+ const runVol = runVolume(cfg);+ const volDisc =+ runVol > rates.runCurveKnee+ ? Math.min(+ rates.maxVolumeDiscount,+ rates.discountPerDoubling * Math.log2(runVol / rates.runCurveKnee),+ )+ : 0;+ return (+ Math.max(rates.floorRatePerRun, rates.listRatePerRun * (1 - volDisc)) *+ (cfg.sizeMult || 1)+ );+}++export function previewAnnualMinor(+ cfg: QuoteConfigInput,+ rates: RateCard,+): number {+ const runVol = runVolume(cfg);+ const rate = perRunRate(cfg, rates);+ const termDisc = termDiscount(rates, cfg.termYears);+ const meterNet = Math.round(runVol * rate * (1 - termDisc)) * 100; // whole $ → minor units+ // Standard and priority support are included.+ const support =+ cfg.serviceLevel === "dedicated" ? rates.dedicatedSupportMinor : 0;+ const deploy =+ cfg.deployment === "airgap"+ ? rates.airgapDeployMinor+ : cfg.deployment === "selfhost"+ ? rates.selfHostDeployMinor+ : 0;+ const indemnity = cfg.indemnification+ ? Math.round(meterNet * rates.indemnificationRate)+ : 0;+ const qbr = cfg.qbr ? rates.qbrAnnualMinor : 0;+ return meterNet + support + deploy + indemnity + qbr;+}diff --git a/frontend/src/processor/proprietary/components/procurement/trialDraft.ts b/frontend/src/processor/proprietary/components/procurement/trialDraft.tsnew file mode 100644index 0000000000..51f90af25c--- /dev/null+++ b/frontend/src/processor/proprietary/components/procurement/trialDraft.ts@@ -0,0 +1,40 @@+import type { TrialSetupDetails } from "@processor/api/procurement";++/**+ * A trial setup filled in before signing in, kept so the visitor returns to their own answers+ * rather than a blank form. localStorage, not sessionStorage: confirming a new account's email+ * opens a new tab.+ */+export interface TrialDraft {+ deployment: string;+ seats: number;+ details: TrialSetupDetails;+ /** Ticked before signing in; the trial then starts on return without asking again. */+ eulaAgreed?: boolean;+}++const KEY = "stirling-enterprise-trial-draft";++/** Long enough for a confirmation email read the next morning. */+const TTL_MS = 24 * 60 * 60 * 1000;++export function saveTrialDraft(draft: TrialDraft): void {+ try {+ window.localStorage.setItem(KEY, JSON.stringify({ draft, at: Date.now() }));+ } catch {+ // Private browsing or a full quota: the visitor fills the form in again.+ }+}++/** Consumes the draft, so contact details do not outlive the sign-in they were kept for. */+export function takeTrialDraft(): TrialDraft | null {+ try {+ const raw = window.localStorage.getItem(KEY);+ window.localStorage.removeItem(KEY);+ if (!raw) return null;+ const { draft, at } = JSON.parse(raw) as { draft: TrialDraft; at: number };+ return Date.now() - at < TTL_MS ? draft : null;+ } catch {+ return null;+ }+}diff --git a/frontend/src/processor/proprietary/components/procurement/useProcurement.test.tsx b/frontend/src/processor/proprietary/components/procurement/useProcurement.test.tsxindex fd4b95d367..5b264a8a28 100644--- a/frontend/src/processor/proprietary/components/procurement/useProcurement.test.tsx+++ b/frontend/src/processor/proprietary/components/procurement/useProcurement.test.tsx@@ -148,7 +148,7 @@ it("closes the purchase dialog on expired authorization without replaying the muawait waitFor(() => expect(ctl.started).toBe(true));act(() => {ctl.setOpen(true);- ctl.setExtra("setup");+ ctl.setExtra("schedule");});startAgreement.mockRejectedValue(new SaasSessionRequiredError());await act(async () => {diff --git a/frontend/src/processor/proprietary/components/procurement/useProcurement.ts b/frontend/src/processor/proprietary/components/procurement/useProcurement.tsindex 7e03abbab0..175148ffa7 100644--- a/frontend/src/processor/proprietary/components/procurement/useProcurement.ts+++ b/frontend/src/processor/proprietary/components/procurement/useProcurement.ts@@ -14,7 +14,7 @@ import {fetchSnapshot,issueQuote,recordInterest,- resetProcurement,+ recordLegalConsent,startAgreement,startTrial,type ProcurementSnapshot,@@ -22,16 +22,11 @@ import {type TrialSetupDetails,} from "@editor/portal/api/procurement";-export type ProcurementExtra =- | null- | "license"- | "schedule"- | "trial"- | "setup"- | "documents";+/** A dialog opened over the Enterprise page. */+export type ProcurementExtra = null | "schedule";/**- * Shares a linked account's deal state between the billing summary and procurement dialogs.+ * A linked account's deal state and actions, shared by the Enterprise page and its dialogs.*/export interface ProcurementController {isLinked: boolean;@@ -56,28 +51,26 @@ export interface ProcurementController {setEditing: (b: boolean) => void;extra: ProcurementExtra;setExtra: (e: ProcurementExtra) => void;+ /** The latest quote's invoice PDF, or the one accepting it just returned. */invoicePdf: string | null;- /** Open the trial-setup dialog (deployment + seats) — the trial only starts once it's confirmed. */- onStartTrial: () => void;/**- * Record enterprise interest and open trial setup. Persisting the intent is what keeps the- * enterprise surface off accounts that never asked for it, and makes drop-off at this step- * visible; the dialog opens either way, so a failed write never blocks the buyer.+ * Record enterprise interest. Persisting the intent is what keeps the enterprise surface off+ * accounts that never asked for it, and makes drop-off before the trial visible; it is+ * best-effort, so a failed write never blocks the buyer.*/onExploreEnterprise: () => void;- /** Confirm the setup dialog: start the trial with the chosen deployment/seats, then open the flow. */+ /** Start the trial with the deployment, seats and buyer details from the setup form. */onConfirmSetup: (deployment: string,seats: number,details: TrialSetupDetails,) => void;onExtendTrial: () => void;- onReset: () => void;/** Issue the priced draft. Leaves the modal open: the issued quote becomes the review step. */onGenerate: (draft: QuoteResult) => Promise<void>;/*** Accept the reviewed quote and advance to the agreement step — does NOT charge Stripe. Taken from- * the deal card, and opens the agreement on success.+ * the Enterprise page, and opens the agreement on success.*/onAcceptQuote: () => Promise<void>;onAgree: () => void;@@ -87,21 +80,26 @@ export interface ProcurementController {onDownloadSignedAgreement: () => Promise<void>;}+/**+ * The deal snapshot, null when this account has no link to price against. One shared cache entry+ * for billing and the Enterprise page, so moving between them does not flash the loading state.+ * No retry: the page gates all its content on `loading`, which backoff would hold true.+ */+export function useProcurementSnapshot() {+ const isLinked = usePortalLinked();+ return useQuery<ProcurementSnapshot | null>({+ queryKey: qk.procurement(isLinked),+ queryFn: () => (isLinked ? fetchSnapshot() : Promise.resolve(null)),+ retry: false,+ });+}+export function useProcurement(): ProcurementController {const { t } = useTranslation();const isLinked = usePortalLinked();-- // Through the shared query cache, not a per-mount fetch: the snapshot survives navigation, so- // returning to billing renders the deal from cache instead of flashing the loading state again.- // No retry — a failing snapshot must not hold `loading` true through backoff, since the hero- // gates its whole card on it.const queryClient = useQueryClient();const snapshotKey = qk.procurement(isLinked);- const query = useQuery<ProcurementSnapshot | null>({- queryKey: snapshotKey,- queryFn: () => (isLinked ? fetchSnapshot() : Promise.resolve(null)),- retry: false,- });+ const query = useProcurementSnapshot();const state = toAsyncState(query);const [open, setOpen] = useState(false);const [busy, setBusy] = useState(false);@@ -125,7 +123,7 @@ export function useProcurement(): ProcurementController {function reportError(cause: unknown, message: string) {if (cause instanceof SaasSessionRequiredError) {- // Recovery is in the billing shell; keep unfinished purchases for an explicit retry.+ // Recovery is the session banner above; keep unfinished purchases for an explicit retry.setOpen(false);setExtra(null);setError(null);@@ -138,7 +136,7 @@ export function useProcurement(): ProcurementController {* Run a deal action, then refresh the snapshot so every reader sees the new stage.** `closeOnSuccess` ends the step. Each stage is its own visit — a buyer can sit in one for days —- * so finishing one returns them to the deal card instead of gliding into the next. Deliberately+ * so finishing one returns them to the page instead of gliding into the next. Deliberately* not in a `finally`: a failure has to leave the modal open, or the error banner this sets would* be torn down with it and the buyer would be left with no idea what went wrong.*@@ -170,11 +168,7 @@ export function useProcurement(): ProcurementController {}}- // The setup dialog collects deployment + seats first; the trial starts on confirm. Starting the- // trial is a step in its own right, so it ends on the card — the buyer builds a quote when ready.- const onStartTrial = () => setExtra("setup");const onExploreEnterprise = () => {- setExtra("setup");void recordInterest().then((snap) => queryClient.setQueryData(snapshotKey, snap)).catch((e) => {@@ -187,20 +181,14 @@ export function useProcurement(): ProcurementController {seats: number,details: TrialSetupDetails,) =>- run(async () => {- await startTrial(deployment, seats, details);- setExtra(null);+ run(() => {+ void recordLegalConsent("eula", "trial"); // clickwrap consent, best-effort+ return startTrial(deployment, seats, details);});const onExtendTrial = () => run(extendTrial);- const onReset = () =>- run(async () => {- await resetProcurement();- setEditing(false);- setInvoicePdf(null);- });// Deliberately does not close: the issued quote returns through the snapshot and becomes the// builder's review step, so the buyer reads the paper they just generated instead of being dropped- // back on the card to find it again.+ // back on the page to find it again.const onGenerate = async (draft: QuoteResult) => {await run(async () => {await issueQuote(draft.quoteId);@@ -213,7 +201,7 @@ export function useProcurement(): ProcurementController {* download the plain quote before taking on the legal documents.** This is the one transition that carries straight on into the next stage rather than ending on the- * card. Accepting is an explicit decision the buyer has just taken from the card itself, so putting+ * page. Accepting is an explicit decision the buyer has just taken from the page itself, so putting* them back there to press a second button to see what they accepted reads as a dead end.*/const onAcceptQuote = async () => {@@ -327,12 +315,10 @@ export function useProcurement(): ProcurementController {setEditing,extra,setExtra,- invoicePdf,- onStartTrial,+ invoicePdf: latest?.invoicePdf ?? invoicePdf,onExploreEnterprise,onConfirmSetup,onExtendTrial,- onReset,onGenerate,onAcceptQuote,onAgree,diff --git a/frontend/src/processor/proprietary/contexts/ThemeContext.tsx b/frontend/src/processor/proprietary/contexts/ThemeContext.tsxindex a60d5c5b50..78c37c8a1f 100644--- a/frontend/src/processor/proprietary/contexts/ThemeContext.tsx+++ b/frontend/src/processor/proprietary/contexts/ThemeContext.tsx@@ -23,7 +23,18 @@ interface ThemeContextValue {const ThemeContext = createContext<ThemeContextValue | null>(null);-export function ThemeProvider({ children }: { children: ReactNode }) {+export function ThemeProvider({+ children,+ forcedTheme,+}: {+ children: ReactNode;+ /**+ * Pins the scheme without touching the saved preference, for hosts that own the theme such as+ * Storybook's toolbar. Writing the shared preference makes open tabs flip each other back through+ * storage events.+ */+ forcedTheme?: Theme;+}) {// Mirror the shared theme MODE; re-read on cross-tab storage changes and,// while on "system", on OS scheme changes.const [mode, setMode] = useState<ThemeMode>(() =>@@ -43,7 +54,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {};}, []);- const theme = resolveColorScheme(mode, systemScheme);+ const theme = forcedTheme ?? resolveColorScheme(mode, systemScheme);useEffect(() => {document.documentElement.setAttribute("data-theme", theme);@@ -51,6 +62,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {const value = useMemo<ThemeContextValue>(() => {const setTheme = (next: Theme) => {+ if (forcedTheme) return;preferencesService.setPreference("theme", next);setMode(next);};@@ -59,7 +71,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {setTheme,toggle: () => setTheme(theme === "light" ? "dark" : "light"),};- }, [theme]);+ }, [theme, forcedTheme]);return (<ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>diff --git a/frontend/src/processor/proprietary/contexts/UIContext.test.tsx b/frontend/src/processor/proprietary/contexts/UIContext.test.tsxindex 4cc89d209f..4faafa61f4 100644--- a/frontend/src/processor/proprietary/contexts/UIContext.test.tsx+++ b/frontend/src/processor/proprietary/contexts/UIContext.test.tsx@@ -4,9 +4,8 @@ import { UIProvider, useUI } from "@editor/portal/contexts/UIContext";/*** The context value is memoised, so every piece of state it exposes has to appear in the memo's- * dependency array or consumers never see it change. `trialSetupRequested` was added without it and- * the enterprise CTA silently did nothing: the flag flipped, the memo did not, and no consumer- * re-rendered. There is no `react-hooks/exhaustive-deps` rule in this repo to catch that, so it gets+ * dependency array or consumers never see it change: the flag flips, the memo does not, and no+ * consumer re-renders. There is no `react-hooks/exhaustive-deps` rule in this repo to catch that, so it gets* a test instead.*/function probe() {@@ -15,7 +14,7 @@ function probe() {function Probe() {api = useUI();- seen.push(api.trialSetupRequested);+ seen.push(api.linkModalOpen);return null;}@@ -32,7 +31,7 @@ function probe() {};}-describe("UIContext — the trial-setup signal reaches consumers", () => {+describe("UIContext — state changes reach consumers", () => {it("opens banner prompts without a previous pipeline failure context", () => {const p = probe();const cause = { pipelineId: "rotate", trigger: "upload" as const };@@ -43,16 +42,16 @@ describe("UIContext — the trial-setup signal reaches consumers", () => {expect(p.api.linkModalOpen).toBe(true);expect(p.api.linkModalFailureContext).toBeUndefined();});- it("re-renders consumers when the request is raised and cleared", () => {+ it("re-renders consumers when the link dialog opens and closes", () => {const p = probe();- expect(p.api.trialSetupRequested).toBe(false);+ expect(p.api.linkModalOpen).toBe(false);- act(() => p.api.requestTrialSetup());- expect(p.api.trialSetupRequested).toBe(true);+ act(() => p.api.openLinkModal());+ expect(p.api.linkModalOpen).toBe(true);expect(p.seen).toContain(true);- act(() => p.api.clearTrialSetupRequest());- expect(p.api.trialSetupRequested).toBe(false);+ act(() => p.api.closeLinkModal());+ expect(p.api.linkModalOpen).toBe(false);});});diff --git a/frontend/src/processor/proprietary/contexts/UIContext.tsx b/frontend/src/processor/proprietary/contexts/UIContext.tsxindex 1fac3794eb..b7bc4a6bcc 100644--- a/frontend/src/processor/proprietary/contexts/UIContext.tsx+++ b/frontend/src/processor/proprietary/contexts/UIContext.tsx@@ -50,19 +50,12 @@ interface UIContextValue {) => void;closeLinkModal: () => void;/**- * A one-shot signal like {@link UIContextValue.trialSetupRequested}: the callback route and the+ * A one-shot signal: the callback route and the* dialog mount separately, and there must only ever be one link dialog.*/connectOutcome: ConnectOutcome | null;publishConnectOutcome: (outcome: ConnectOutcome) => void;clearConnectOutcome: () => void;- /**- * A request to begin the enterprise trial, raised from wherever the buyer said yes (the billing- * upsell). Usage & Billing consumes it once the deal is loaded, then starts or resumes the flow.- */- trialSetupRequested: boolean;- requestTrialSetup: () => void;- clearTrialSetupRequest: () => void;}const UIContext = createContext<UIContextValue | null>(null);@@ -94,7 +87,6 @@ export function UIProvider({ children }: { children: ReactNode }) {const [linkModalOpen, setLinkModalOpen] = useState(false);const [linkModalFailureContext, setLinkModalFailureContext] =useState<AccountLinkBlockContext>();- const [trialSetupRequested, setTrialSetupRequested] = useState(false);const [linkModalMode, setLinkModalMode] = useState<LinkModalMode>("link");const [connectOutcome, setConnectOutcome] = useState<ConnectOutcome | null>(null,@@ -142,12 +134,6 @@ export function UIProvider({ children }: { children: ReactNode }) {setConnectOutcome(null);setLinkModalOpen(true);},- trialSetupRequested,- requestTrialSetup: () => {- setMobileNavOpen(false);- setTrialSetupRequested(true);- },- clearTrialSetupRequest: () => setTrialSetupRequested(false),connectOutcome,publishConnectOutcome: (outcome: ConnectOutcome) => {linkModalActive.current = true;@@ -175,7 +161,6 @@ export function UIProvider({ children }: { children: ReactNode }) {linkModalOpen,linkModalMode,linkModalFailureContext,- trialSetupRequested,connectOutcome,],);diff --git a/frontend/src/processor/proprietary/hooks/useCopyFeedback.ts b/frontend/src/processor/proprietary/hooks/useCopyFeedback.tsnew file mode 100644index 0000000000..1eebe277ec--- /dev/null+++ b/frontend/src/processor/proprietary/hooks/useCopyFeedback.ts@@ -0,0 +1,25 @@+import { useEffect, useRef, useState } from "react";+import { copyText } from "@editor/utils/copyText";++/** How long a button reads "Copied" after a successful copy. */+const COPIED_MS = 2000;++/**+ * Copies text and reports `copied` for a moment afterwards, for a button to acknowledge it. `copy`+ * resolves false when the browser refused, so the caller can offer another way.+ */+export function useCopyFeedback() {+ const [copied, setCopied] = useState(false);+ const timer = useRef<ReturnType<typeof setTimeout>>(undefined);+ useEffect(() => () => clearTimeout(timer.current), []);+ const copy = async (text: string): Promise<boolean> => {+ const ok = await copyText(text);+ if (ok) {+ setCopied(true);+ clearTimeout(timer.current);+ timer.current = setTimeout(() => setCopied(false), COPIED_MS);+ }+ return ok;+ };+ return { copied, copy };+}diff --git a/frontend/src/processor/proprietary/mocks/handlers/procurementSaas.ts b/frontend/src/processor/proprietary/mocks/handlers/procurementSaas.tsindex 2f5246ce8d..2ebbaa4e52 100644--- a/frontend/src/processor/proprietary/mocks/handlers/procurementSaas.ts+++ b/frontend/src/processor/proprietary/mocks/handlers/procurementSaas.ts@@ -1,4 +1,5 @@import { http, HttpResponse } from "msw";+import { QUOTE_BELOW_MINIMUM, type RateCard } from "@processor/api/procurement";/*** MSW mock for the real SaaS procurement endpoints (`apiClient.saas` → VITE_SAAS_API_URL, which is@@ -7,6 +8,12 @@ import { http, HttpResponse } from "msw";*/const SAAS = "http://saas.mock";+/** The server's default cap on trial extensions. */+const MAX_TRIAL_EXTENSIONS = 2;++/** The server's default floor on a quote's annual fee: USD 12,000. */+const MIN_ANNUAL_NET_MINOR = 1_200_000;+const EMPTY = {dealId: null,stage: null,@@ -48,36 +55,70 @@ let deal: typeof EMPTY | (Record<string, unknown> & { latestQuote: unknown }) =EMPTY;let seq = 0;-const TERM = [0, 0.03, 0.05, 0.06, 0.07]; // meter-only, 1..5 years+/** The deployment the licence follows: the quote's once there is one, else the trial's. */+function entitledDeployment(): string | null {+ const d = deal as {+ dealId: unknown;+ deployment?: string;+ latestQuote: { config?: Cfg } | null;+ };+ if (d.dealId == null) return null;+ return d.latestQuote?.config?.deployment ?? d.deployment ?? null;+}-// Mirror of ProcurementPricingService (D71): run-based curve, flat priced needs, USD.+/** The server's default rate card (PricingRates.defaults()), sent with the deal like the real one. */+export const RATE_CARD: RateCard = {+ listRatePerRun: 0.01,+ floorRatePerRun: 0.005,+ runCurveKnee: 1_000_000,+ discountPerDoubling: 0.06,+ maxVolumeDiscount: 0.5,+ termDiscountByYear: [0, 0.03, 0.05, 0.06, 0.07],+ indemnificationRate: 0.05,+ dedicatedSupportMinor: 3_000_000,+ selfHostDeployMinor: 1_200_000,+ airgapDeployMinor: 3_600_000,+ qbrAnnualMinor: 800_000,+ trainingOneTimeMinor: 750_000,+};++// Mirror of ProcurementPricingService: run-based curve, flat priced needs, USD.// Exported for the pricing-parity test (see pricingParity.test.ts).export function priceQuote(cfg: Cfg) {- const LIST = 0.01;- const FLOOR = 0.005;+ const R = RATE_CARD;const intensity = Math.max(1, cfg.intensity || 4);const runVol = Math.max(0, cfg.volume) * intensity;const volDisc =- runVol > 1_000_000- ? Math.min(0.5, 0.06 * Math.log2(runVol / 1_000_000))+ runVol > R.runCurveKnee+ ? Math.min(+ R.maxVolumeDiscount,+ R.discountPerDoubling * Math.log2(runVol / R.runCurveKnee),+ ): 0;- // File-size tier (D93) scales the rate after the floor; snap to a known multiplier.+ // The PDF-size tier scales the rate after the floor; snap to a known multiplier.const sizeMult = [1.0, 1.4, 2.4].includes(cfg.sizeMult) ? cfg.sizeMult : 1.0;- const rate = Math.max(FLOOR, LIST * (1 - volDisc)) * sizeMult;- const termDisc = TERM[Math.min(Math.max(cfg.termYears, 1), 5) - 1];+ const rate =+ Math.max(R.floorRatePerRun, R.listRatePerRun * (1 - volDisc)) * sizeMult;+ const termDisc =+ R.termDiscountByYear[+ Math.min(Math.max(cfg.termYears, 1), R.termDiscountByYear.length) - 1+ ];const annualBase = Math.round(runVol * rate) * 100; // whole $ → minorconst meterNet = Math.round(runVol * rate * (1 - termDisc)) * 100;const termDiscount = meterNet - annualBase; // <= 0- const support = cfg.serviceLevel === "dedicated" ? 3_000_000 : 0;+ const support =+ cfg.serviceLevel === "dedicated" ? R.dedicatedSupportMinor : 0;const deploy =cfg.deployment === "airgap"- ? 3_600_000+ ? R.airgapDeployMinor: cfg.deployment === "selfhost"- ? 1_200_000+ ? R.selfHostDeployMinor: 0;- const indemnity = cfg.indemnification ? Math.round(meterNet * 0.05) : 0;- const qbr = cfg.qbr ? 800_000 : 0;- const training = cfg.training ? 750_000 : 0;+ const indemnity = cfg.indemnification+ ? Math.round(meterNet * R.indemnificationRate)+ : 0;+ const qbr = cfg.qbr ? R.qbrAnnualMinor : 0;+ const training = cfg.training ? R.trainingOneTimeMinor : 0;const annualNetMinor = meterNet + support + deploy + indemnity + qbr;const tcvMinor = annualNetMinor * cfg.termYears + training;@@ -178,7 +219,7 @@ export function priceQuote(cfg: Cfg) {invoicePdf: null,config: {volume: cfg.volume,- users: 0,+ users: cfg.users ?? 0,intensity,sizeMult,deployment: cfg.deployment || "cloud",@@ -206,15 +247,109 @@ export function resetProcurementSaasStore() {seq = 0;}+/** The stages a demo can jump straight to. */+export type DemoStage =+ | "trial"+ | "quote"+ | "security"+ | "procurement"+ | "active";++const DEMO_QUOTE: Cfg = {+ volume: 500_000,+ users: 250,+ intensity: 4,+ sizeMult: 1.4,+ // Cloud, not self-hosted: the self-hosted fee alone meets the minimum spend, so a self-hosted+ // deal could never show the builder's minimum guidance.+ deployment: "cloud",+ serviceLevel: "priority",+ termYears: 3,+ indemnification: false,+ training: true,+ qbr: false,+ businessName: "Northwind Logistics",+ contactName: "Dana Lee",+ contactEmail: "[email protected]",+ addressLine1: "500 Howard St",+ city: "San Francisco",+ region: "California",+ postalCode: "94105",+};++/** A trial team far under the minimum spend, so building its quote opens on the minimum check. */+const DEMO_TRIAL_SEATS = 1;++/**+ * Puts the deal straight at a stage with believable data, as if the buyer had walked there, so a+ * demo can skip past steps it doesn't need to show.+ */+export function seedProcurementSaasStage(stage: DemoStage) {+ const day = 86_400_000;+ const now = Date.now();+ const paid = stage === "procurement" || stage === "active";+ const quote =+ stage === "trial"+ ? null+ : {+ ...priceQuote(DEMO_QUOTE),+ status: paid ? "accepted" : "sent",+ stripeQuoteId: "qt_mock_demo",+ quoteNumber: "QT-MOCKPFX-0001-1",+ invoiceUrl: paid+ ? "https://invoice.stripe.com/i/mock_procurement"+ : null,+ invoicePdf: paid+ ? "https://invoice.stripe.com/i/mock_procurement/pdf"+ : null,+ };+ deal = {+ dealId: 1,+ stage,+ deployment: DEMO_QUOTE.deployment,+ seats: stage === "trial" ? DEMO_TRIAL_SEATS : (DEMO_QUOTE.users ?? 0),+ trialStartedAt: new Date(now - 4 * day).toISOString(),+ trialEndsAt: new Date(now + 10 * day).toISOString(),+ trialExtensionsUsed: 0,+ licensed: true,+ licenseKey:+ stage === "active" ? "MOCK-ENTERPRISE-KEY-0001" : "MOCK-TRIAL-KEY-0001",+ agreementSignedVersion: paid ? "SEA v0.9.1" : null,+ businessName: DEMO_QUOTE.businessName,+ contactName: DEMO_QUOTE.contactName,+ contactEmail: DEMO_QUOTE.contactEmail,+ latestQuote: quote,+ };+}++/** The buyer pays their first invoice: the deal goes live, as Stripe's webhook would make it. */+export function markProcurementSaasPaid() {+ const d = deal as Record<string, unknown>;+ if (d.stage !== "procurement") return;+ d.stage = "active";+ d.licenseKey = "MOCK-ENTERPRISE-KEY-0001";+}++/** The deal as the backend returns it from every read and deal-changing call. */+function snapshot() {+ return {+ ...deal,+ minAnnualNetMinor: MIN_ANNUAL_NET_MINOR,+ entitledDeployment: entitledDeployment(),+ rateCard: RATE_CARD,+ maxTrialExtensions: MAX_TRIAL_EXTENSIONS,+ };+}+export const procurementSaasHandlers = [- http.get(`${SAAS}/api/v1/procurement`, () => HttpResponse.json(deal)),+ http.get(`${SAAS}/api/v1/procurement`, () => HttpResponse.json(snapshot())),// Interest: creates the deal at `exploring` when there is none, and never disturbs one that// already exists — so the enterprise surface only appears for accounts that asked for it.http.post(`${SAAS}/api/v1/procurement/interest`, () => {if (deal.dealId == null) {deal = { ...deal, dealId: 1, stage: "exploring" };}- return HttpResponse.json(deal);+ return HttpResponse.json(snapshot());}),http.post(`${SAAS}/api/v1/procurement/trial/start`, async ({ request }) => {const body = (await request.json().catch(() => ({}))) as Partial<{@@ -243,11 +378,14 @@ export const procurementSaasHandlers = [contactEmail: body.contactEmail ?? null,latestQuote: null,};- return HttpResponse.json(deal);+ return HttpResponse.json(snapshot());}),http.post(`${SAAS}/api/v1/procurement/quote`, async ({ request }) => {const cfg = (await request.json()) as Cfg;const quote = priceQuote(cfg);+ if (quote.annualNetMinor < MIN_ANNUAL_NET_MINOR) {+ return HttpResponse.json({ error: QUOTE_BELOW_MINIMUM }, { status: 409 });+ }const d = (deal.dealId ? deal : { dealId: 1, trialExtensionsUsed: 0 }) as Record<string, unknown>;@@ -268,16 +406,36 @@ export const procurementSaasHandlers = [d.trialEndsAt = new Date(base + 7 * 86_400_000).toISOString();d.trialExtensionsUsed = ((d.trialExtensionsUsed as number) ?? 0) + 1;}- return HttpResponse.json(deal);+ return HttpResponse.json(snapshot());}),http.post(`${SAAS}/api/v1/procurement/agreement`, () => {(deal as Record<string, unknown>).stage = "security";- return HttpResponse.json(deal);+ return HttpResponse.json(snapshot());}),http.get(`${SAAS}/api/v1/procurement/agreement/document`, () => {- const q = (deal as { latestQuote: { quoteNumber?: string } | null })- .latestQuote;+ const q = (+ deal as {+ latestQuote: {+ quoteNumber?: string;+ annualNetMinor: number;+ config: {+ businessName?: string;+ deployment: string;+ termYears: number;+ users: number;+ };+ } | null;+ }+ ).latestQuote;if (!q) return new HttpResponse(null, { status: 404 });+ const usd = (minor: number) =>+ `$${Math.round(minor / 100).toLocaleString("en-US")}`;+ const deployName =+ q.config.deployment === "airgap"+ ? "Air-gapped"+ : q.config.deployment === "selfhost"+ ? "Self-hosted"+ : "Stirling Cloud";return HttpResponse.json({docId: "enterprise-agreement",version: "0.9.1",@@ -290,10 +448,17 @@ export const procurementSaasHandlers = ["## Part A — Master Services Agreement","Provider will provide the Stirling PDF Processor and Editor as described in the Order Form.",`## Part B — Order Form · ${q.quoteNumber ?? "Q-MOCK"}`,- "| Term | Value |",- "| --- | --- |",- "| Subscription | Enterprise · Stirling Cloud |",- "| Escalator | +3% at each anniversary during the Term |",+ // One block: a blank line between rows would end the table.+ [+ "| Term | Value |",+ "| --- | --- |",+ `| Customer | ${q.config.businessName?.trim() || "Customer"} |`,+ `| Subscription | Stirling Enterprise · ${deployName} |`,+ `| Users | ${q.config.users.toLocaleString("en-US")} |`,+ `| Initial term | ${q.config.termYears} year${q.config.termYears === 1 ? "" : "s"} |`,+ `| Annual fee | ${usd(q.annualNetMinor)} |`,+ "| Escalator | +3% at each anniversary during the Term |",+ ].join("\n"),"## Part C — Data Processing Addendum","Provider processes Personal Data only on Customer's documented instructions.",].join("\n\n"),@@ -353,7 +518,7 @@ export const procurementSaasHandlers = [d.licensed = true;d.licenseKey = "MOCK-ENTERPRISE-KEY-0001";}- return HttpResponse.json(deal);+ return HttpResponse.json(snapshot());}),http.get(`${SAAS}/api/v1/procurement/license/file`, () => {const q = (deal as { latestQuote: { config?: Cfg } | null }).latestQuote;@@ -368,7 +533,7 @@ export const procurementSaasHandlers = [}),http.post(`${SAAS}/api/v1/procurement/reset`, () => {resetProcurementSaasStore();- return HttpResponse.json(EMPTY);+ return HttpResponse.json(snapshot());}),http.get(`${SAAS}/api/v1/legal/:docId`, ({ params }) => {const docId = String(params.docId);diff --git a/frontend/src/processor/proprietary/views/Enterprise.css b/frontend/src/processor/proprietary/views/Enterprise.cssnew file mode 100644index 0000000000..8a38e1120b--- /dev/null+++ b/frontend/src/processor/proprietary/views/Enterprise.css@@ -0,0 +1,803 @@+.ent {+ /* Narrow pages stack; measured against the page, not the viewport, so it holds in previews too. */+ container-type: inline-size;+ /* The app shell clips overflow to the viewport, so the page scrolls itself. */+ height: 100dvh;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ background: var(--c-bg);+ color: var(--c-text);+}++/* One content width for every row, gutters outside it, so header, hero, body and footer share edges. */+.ent__wrap {+ width: min(72rem, 100% - 4rem);+ margin-inline: auto;+}++.ent__header {+ position: sticky;+ top: 0;+ z-index: 2;+ border-bottom: 1px solid var(--c-border-subtle);+ background: var(--c-bg-raised);+}++.ent__header-inner {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ min-height: 4rem;+}++.ent__brand {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}++.ent__home {+ display: inline-flex;+ color: inherit;+ text-decoration: none;+ border-radius: var(--radius-sm);+}++.ent__home:focus-visible {+ outline: 2px solid var(--c-primary);+ outline-offset: 4px;+}++/* Text-aligned with the stage label below it, so the padding sits outside the column. */+.ent__back {+ margin: 0 0 1rem -12px;+}++.ent__brand-tag {+ padding-left: 0.75rem;+ border-left: 1px solid var(--c-border);+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--c-text-muted);+}++.ent__header-end {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}++/* A borderless button's padding would otherwise hold its label in from the content edge. */+.ent__header-end > .sui-btn--tertiary:last-child {+ margin-right: -0.75rem;+}++.ent__company {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+ padding: 0.375rem 0.75rem;+ border: 0;+ border-right: 1px solid var(--c-border);+ background: none;+ font: inherit;+ font-size: 0.875rem;+ font-weight: 500;+ color: var(--c-text-muted);+}++button.ent__company {+ border-radius: var(--radius-md);+ border-right: 0;+ cursor: pointer;+}++button.ent__company:hover,+button.ent__company[aria-expanded="true"] {+ background: var(--c-hover);+ color: var(--c-text);+}++.ent__main {+ flex: 1;+ display: flex;+ flex-direction: column;+}++.ent__notices:empty {+ display: none;+}++.ent__notices {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ padding-top: 1.5rem;+}++.ent__loading {+ display: flex;+ flex-direction: column;+ gap: 1.5rem;+ padding-block: 3rem;+}++.ent__footer {+ border-top: 1px solid var(--c-border-subtle);+ font-size: 0.875rem;+ color: var(--c-text-muted);+}++.ent__footer-inner {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: center;+ gap: 0.375rem;+ padding-block: 1.5rem;+}++.ent__eyebrow {+ font-size: 0.8125rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--c-accent-text);+}++.ent__h1 {+ margin: 0.5rem 0 0;+ font-size: 2.5rem;+ font-weight: 650;+ line-height: 1.1;+ letter-spacing: -0.02em;+}++.ent__h2 {+ margin: 0;+ font-size: 1.0625rem;+ font-weight: 600;+}++.ent__lede {+ max-width: 36rem;+ margin: 0.75rem 0 0;+ font-size: 1.0625rem;+ line-height: 1.55;+ color: var(--c-text-muted);+}++.ent__text {+ margin: 0.375rem 0 0;+ font-size: 0.875rem;+ line-height: 1.5;+ color: var(--c-text-muted);+}++.ent__hint {+ margin: 0.75rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.45;+ color: var(--c-text-subtle);+}++.ent__note {+ margin: 1rem 0 0;+ font-size: 0.875rem;+ color: var(--c-text-subtle);+}++.ent__actions {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem;+ margin-top: 1.5rem;+}++.ent__landing {+ display: grid;+ grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr);+ gap: 3rem;+ align-items: start;+ padding-block: 3.5rem 4rem;+}++.ent__intro {+ padding-top: 1rem;+}++.ent__ticks {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ margin: 2rem 0 0;+ padding: 0;+ list-style: none;+ font-size: 0.9375rem;+}++.ent__ticks li {+ display: flex;+ align-items: flex-start;+ gap: 0.625rem;+}++.ent__ticks li > :first-child {+ flex: none;+ margin-top: 0.1875rem;+ color: var(--c-success);+}++/* The steps were laid out for a dialog body; this card stands in for it, publishing the same inset+ so their full-bleed trays and footer reach its edges. */+.ent__flow .portal-procflow {+ --flowmodal-inset: 1.75rem;+ --flowmodal-body-end: 1.25rem;+ display: flex;+ flex-direction: column;+ gap: 0.9rem;+ padding: 1.5rem var(--flowmodal-inset) var(--flowmodal-body-end);+ border: 1px solid var(--c-border);+ border-radius: var(--radius-lg);+ background: var(--c-bg-raised);+}++/* The header and this band read as one block; the deal's detail sits below on the page colour. */+.ent__band {+ border-bottom: 1px solid var(--c-border-subtle);+ background: var(--c-bg-raised);+}++/* Columns stretch so the call box and the trial panel finish on one line. */+.ent__hero {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(0, 21rem);+ column-gap: 4rem;+ align-items: stretch;+ padding-block: 3.5rem 0;+}++.ent__hero:has(.ent__back) {+ padding-top: 1.25rem;+}++.ent__hero-main {+ display: flex;+ flex-direction: column;+}++.ent__hero-head {+ padding-bottom: 2rem;+}++.ent__actions:empty {+ display: none;+}++.ent__live {+ display: flex;+ align-items: flex-start;+ gap: 0.75rem;+ /* The width of the call box below it, so the two stack flush. */+ max-width: 44rem;+ margin-top: 1.5rem;+ padding: 1rem 1.25rem;+ border-radius: var(--radius-lg);+ background: var(--c-success-subtle);+}++.ent__live > :first-child {+ flex: none;+ color: var(--c-success);+}++/* Under the stage's buttons, on a line of its own. */+.ent__next-hint {+ flex-basis: 100%;+ max-width: 36rem;+ margin: 0;+ font-size: 0.875rem;+}++.ent__h3 {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+}++.ent__call,+.ent__aside {+ border: 1px solid var(--c-border);+ border-radius: var(--radius-lg);+ background: var(--c-surface);+}++.ent__call {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem 1rem;+ margin-top: auto;+ padding: 1rem 1.25rem;+}++.ent__hero:not(:has(.ent__aside)) .ent__call {+ max-width: 44rem;+}++.ent__call-icon {+ display: grid;+ flex: none;+ place-items: center;+ width: 2.5rem;+ height: 2.5rem;+ border-radius: 50%;+ background: var(--c-primary-subtle);+ color: var(--c-accent-text);+}++.ent__call-text {+ flex: 1 1 16rem;+ min-width: 0;+}++.ent__call-text .ent__text {+ margin-top: 0.125rem;+ text-wrap: pretty;+}++.ent__aside {+ display: flex;+ flex-direction: column;+ padding: 1.375rem 1.5rem 1.25rem;+}++.ent__aside-label {+ font-size: 0.75rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--c-text-muted);+}++.ent__aside-figure {+ margin-top: 0.375rem;+ font-size: 1.75rem;+ font-weight: 650;+ line-height: 1.1;+ letter-spacing: -0.01em;+}++.ent__aside-figure[data-expired] {+ color: var(--c-danger);+}++.ent__aside:not(:has(.ent__actions)) {+ align-self: start;+}++.ent__eyebrow-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.75rem;+}++.ent__chip {+ padding: 0.125rem 0.625rem;+ border: 1px solid var(--c-border);+ border-radius: var(--radius-pill);+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--c-text-muted);+}++.ent__quote-number {+ margin-left: 0.5rem;+ font-family: var(--font-mono);+ letter-spacing: normal;+ text-transform: none;+ color: var(--c-text-subtle);+}++.ent__quote-caption {+ margin-top: 0.25rem;+ font-size: 0.8125rem;+ color: var(--c-text-muted);+}++.ent__facts {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+ margin: 1rem 0 0;+ padding: 0.75rem 0;+ border-block: 1px solid var(--c-border-subtle);+ font-size: 0.8125rem;+}++.ent__facts > div {+ display: flex;+ justify-content: space-between;+ gap: 1rem;+}++.ent__facts dt {+ color: var(--c-text-muted);+}++.ent__facts dd {+ margin: 0;+ font-weight: 600;+}++.ent__quote .ent__actions {+ justify-content: space-between;+}++.ent__quote-valid {+ font-size: 0.8125rem;+ color: var(--c-text-subtle);+}++.ent__trial-bar {+ display: block;+ height: 0.375rem;+ margin-top: 0.875rem;+ overflow: hidden;+ border-radius: var(--radius-pill);+ background: var(--c-border);+}++.ent__trial-bar > span {+ display: block;+ height: 100%;+ border-radius: inherit;+ background: var(--c-primary);+}++.ent__aside .ent__text {+ margin-top: 0.75rem;+}++/* Pinned to the panel's foot, level with the call box beside it. */+.ent__aside .ent__actions {+ gap: 0.25rem;+ margin-top: auto;+ padding-top: 0.75rem;+ /* Borderless buttons: pull the first label back onto the panel's text edge. */+ margin-left: -1.125rem;+}++.ent__aside .ent__hint {+ margin-top: 0.5rem;+}++.ent__stages {+ grid-column: 1 / -1;+ display: flex;+ margin: 2.5rem 0 0;+ padding: 1.75rem 0 2.25rem;+ border-top: 1px solid var(--c-border-subtle);+ list-style: none;+}++/* A step open below leaves only the title above the tracker, so it closes up under it. */+.ent__hero:not(:has(.ent__call)) .ent__stages {+ margin-top: 0;+}++.ent__stage {+ position: relative;+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ font-size: 0.875rem;+ color: var(--c-text-subtle);+}++/* The last stage takes only its own width, so the rails run the full row. */+.ent__stage:last-child {+ flex: none;+}++/* The rail between this stage's dot and the next, coloured once this stage is behind the buyer. */+.ent__stage:not(:last-child)::after {+ content: "";+ position: absolute;+ top: calc(1rem - 1px);+ left: 2.5rem;+ right: 0.5rem;+ height: 2px;+ border-radius: 1px;+ background: var(--c-border);+}++.ent__stage[data-state="done"]:not(:last-child)::after {+ background: var(--c-success);+}++.ent__stage-dot {+ display: grid;+ place-items: center;+ width: 2rem;+ height: 2rem;+ border: 2px solid var(--c-border);+ border-radius: 50%;+ background: var(--c-bg-raised);+ font-size: 0.8125rem;+ font-weight: 600;+}++/* Carries the stage's own layout, so a clickable stage lines up with a plain one. */+.ent__stage-btn {+ display: flex;+ flex-direction: inherit;+ align-items: inherit;+ gap: inherit;+ padding: 0;+ border: 0;+ background: none;+ font: inherit;+ color: inherit;+ text-align: left;+ cursor: pointer;+}++.ent__stage-btn:hover .ent__stage-label {+ color: var(--c-text);+ text-decoration: underline;+ text-underline-offset: 0.2em;+}++.ent__stage-btn:hover .ent__stage-dot {+ border-color: var(--c-primary);+}++.ent__stage-btn:focus-visible {+ outline: 2px solid var(--c-primary);+ outline-offset: 4px;+ border-radius: var(--radius-sm);+}++.ent__stage[data-state="done"] {+ color: var(--c-text-muted);+}++.ent__stage[data-state="done"] .ent__stage-dot {+ border-color: var(--c-success);+ background: var(--c-success);+ color: var(--c-text-on-primary);+}++.ent__stage[data-state="current"] {+ font-weight: 600;+ color: var(--c-text);+}++.ent__stage[data-state="current"] .ent__stage-dot {+ border-color: var(--c-primary);+ background: var(--c-primary);+ color: var(--c-text-on-primary);+ box-shadow: 0 0 0 4px var(--c-primary-subtle);+}++/* A finished stage open for review: marked without moving where the deal stands. */+.ent__stage[data-viewing] {+ color: var(--c-text);+ font-weight: 600;+}++.ent__stage[data-viewing] .ent__stage-dot {+ box-shadow: 0 0 0 4px var(--c-success-subtle);+}++.ent__body {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding-block: 2.5rem 4rem;+}++/* Cards sit on the page colour, so they take the raised surface to stand off it. */+.ent .sui-card {+ background: var(--c-bg-raised);+}++/* Tiles keep each document's name beside its action. */+.ent__body .portal-docmodal {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(17rem, 1fr));+ gap: 0.75rem;+ margin-top: 1.25rem;+}++/* Four would wrap three and one; two by two keeps the set even. */+.ent__body .portal-docmodal:has(> :nth-child(4):last-child) {+ grid-template-columns: repeat(auto-fill, minmax(max(17rem, 40%), 1fr));+}++.ent__body .portal-docmodal__row {+ align-items: center;+ padding: 0.875rem 1rem;+ border: 1px solid var(--c-border);+ border-radius: var(--radius-md);+}++.ent__body .portal-docmodal__row:last-child {+ border-bottom: 1px solid var(--c-border);+}++.ent__body .portal-docmodal__sub {+ text-wrap: pretty;+}++/* In a narrow tile the description wraps, never the button's label. */+.ent__body .portal-docmodal__row > .sui-btn {+ flex: none;+}++/* What's still to come is a short list, not tiles: nothing in it can be opened yet. */+.ent__body .portal-docmodal--later {+ gap: 0.5rem 0.75rem;+ margin-top: 0.75rem;+}++.ent__body .portal-docmodal--later .portal-docmodal__row {+ flex-direction: column;+ align-items: flex-start;+ gap: 0.125rem;+ padding: 0 1rem;+ border: 0;+ border-left: 2px solid var(--c-border);+ border-radius: 0;+}++.ent__body .portal-docmodal--later .portal-docmodal__sub {+ display: none;+}++.ent__body .portal-docmodal__group {+ margin-top: 1.75rem;+ padding-top: 0;+ border-top: 0;+}++/* The licence panel is a boxed inset elsewhere; here it is one row: what it is, the key, copy. */+.ent__license .portal-proc__license {+ display: grid;+ grid-template-areas:+ "label key copy"+ "hint key copy";+ grid-template-columns: minmax(0, 1fr) auto auto;+ align-items: center;+ column-gap: 1rem;+ margin: 0;+ padding: 0;+ border: 0;+ background: none;+}++.ent__license .portal-proc__license-label {+ grid-area: label;+ align-self: end;+ font-size: 1.0625rem;+ letter-spacing: normal;+ text-transform: none;+ color: var(--c-text);+}++.ent__license .portal-proc__license-key {+ grid-area: key;+ margin: 0;+ padding: 0.625rem 1rem;+ border: 1px solid var(--c-border);+ background: var(--c-surface-sunken);+ font-size: 0.9375rem;+ letter-spacing: 0.02em;+ white-space: nowrap;+}++.ent__license .portal-proc__payment-actions {+ grid-area: copy;+ margin: 0;+}++.ent__license .portal-proc__license-hint {+ grid-area: hint;+ align-self: start;+ margin-top: 0.25rem;+ font-size: 0.875rem;+ color: var(--c-text-muted);+}++.ent__license > .portal-proc__license-hint {+ margin-top: 1rem;+}++@container (max-width: 56rem) {+ .ent__landing,+ .ent__hero {+ grid-template-columns: minmax(0, 1fr);+ }++ .ent__landing {+ gap: 2rem;+ }++ .ent__hero {+ row-gap: 1rem;+ }++ .ent__call {+ margin-top: 0;+ }++ .ent__stages {+ margin-top: 1.5rem;+ }+}++@container (max-width: 40rem) {+ .ent__wrap {+ width: calc(100% - 2rem);+ }++ .ent__landing {+ padding-block: 2rem;+ }++ .ent__hero {+ padding-top: 2rem;+ }++ .ent__body {+ padding-block: 1.5rem 3rem;+ }++ .ent__h1 {+ font-size: 2rem;+ }++ .ent__company,+ .ent__brand-tag {+ display: none;+ }++ .ent__stages {+ flex-direction: column;+ gap: 0.75rem;+ }++ .ent__stage {+ flex-direction: row;+ align-items: center;+ }++ .ent__stage:not(:last-child)::after {+ top: 2rem;+ bottom: -0.75rem;+ left: calc(1rem - 1px);+ right: auto;+ width: 2px;+ height: auto;+ }++ .ent__license .portal-proc__license {+ grid-template-areas:+ "label"+ "hint"+ "key"+ "copy";+ grid-template-columns: minmax(0, 1fr);+ row-gap: 0.75rem;+ }++ .ent__license .portal-proc__license-key {+ white-space: normal;+ }+}diff --git a/frontend/src/processor/proprietary/views/Enterprise.stories.tsx b/frontend/src/processor/proprietary/views/Enterprise.stories.tsxnew file mode 100644index 0000000000..3ba90caf66--- /dev/null+++ b/frontend/src/processor/proprietary/views/Enterprise.stories.tsx@@ -0,0 +1,211 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse } from "msw";+import type { Decorator } from "@storybook/react-vite";+import { AuthContext, useAuth } from "@editor/auth/context";+import { WithOrgOwner } from "@processor/test/WithOrgOwner";+import { Enterprise } from "@processor/views/Enterprise";+import type {+ ProcurementSnapshot,+ QuoteResult,+} from "@processor/api/procurement";+import { freeWallet } from "@processor/components/billing/walletFixtures";+import { RATE_CARD } from "@processor/mocks/handlers/procurementSaas";++const SAAS = "http://saas.mock";+const DAY = 86_400_000;++const quote: QuoteResult = {+ quoteId: 488,+ quoteNumber: "Q-2026-0488",+ status: "sent",+ currency: "USD",+ annualNetMinor: 8_400_000,+ tcvMinor: 25_200_000,+ renewalAnnualNetMinor: 8_652_000,+ cpiRatePct: 3,+ lineItems: [],+ validUntil: "2026-11-15",+ stripeQuoteId: "qt_1NWnd488",+ invoiceUrl: null,+ invoicePdf: null,+ config: {+ volume: 500_000,+ users: 250,+ intensity: 4,+ sizeMult: 1.4,+ deployment: "selfhost",+ termYears: 3,+ serviceLevel: "priority",+ indemnification: false,+ training: true,+ qbr: false,+ businessName: "Northwind Logistics",+ },+};++const trial: ProcurementSnapshot = {+ dealId: 1,+ stage: "trial",+ deployment: "selfhost",+ seats: 250,+ trialStartedAt: new Date(Date.now() - 4 * DAY).toISOString(),+ trialEndsAt: new Date(Date.now() + 10 * DAY).toISOString(),+ trialExtensionsUsed: 0,+ licensed: true,+ licenseKey: "STRL-ENT-7K2Q-9XWD-4MPA-TRIAL",+ agreementSignedVersion: null,+ businessName: "Northwind Logistics",+ contactName: "Dana Lee",+ contactEmail: "[email protected]",+ latestQuote: null,+ rateCard: RATE_CARD,+ maxTrialExtensions: 2,+ entitledDeployment: "selfhost",+ minAnnualNetMinor: 1_200_000,+};++function handlers(snapshot: ProcurementSnapshot | null, role = "leader") {+ return [+ http.get(`${SAAS}/api/v1/procurement`, () =>+ HttpResponse.json(snapshot ?? { ...trial, dealId: null, stage: null }),+ ),+ http.post(`${SAAS}/api/v1/procurement/interest`, () =>+ HttpResponse.json({ ...trial, stage: "exploring", licenseKey: null }),+ ),+ http.post(`${SAAS}/api/v1/payg/wallet/refresh`, () =>+ HttpResponse.json({}),+ ),+ http.get(`${SAAS}/api/v1/payg/wallet`, () =>+ HttpResponse.json({ ...freeWallet, role }),+ ),+ http.get("/api/v1/config/app-config", () =>+ HttpResponse.json({ accountLinkAvailable: true }),+ ),+ ];+}++/** Stories default to a signed-in owner; `signedOut` previews a visitor from the website. */+const WithSession: Decorator = (Story, context) => {+ const auth = useAuth();+ return (+ <AuthContext.Provider+ value={{+ ...auth,+ loading: false,+ session: context.parameters.signedOut+ ? null+ : (auth.session ?? ({} as unknown as typeof auth.session)),+ }}+ >+ <Story />+ </AuthContext.Provider>+ );+};++/** The whole Enterprise journey on one page, outside the app's chrome. */+const meta: Meta<typeof Enterprise> = {+ title: "Portal/Procurement/Enterprise",+ component: Enterprise,+ parameters: { layout: "fullscreen" },+ decorators: [WithSession, WithOrgOwner],+};+export default meta;+type Story = StoryObj<typeof Enterprise>;++/** First visit: why Enterprise, beside the trial setup. */+export const Landing: Story = {+ parameters: { msw: { handlers: handlers(null) } },+};++/** A visitor from the website: the page and the trial setup, with sign-in only to start it. */+export const SignedOut: Story = {+ parameters: { signedOut: true, msw: { handlers: handlers(null) } },+};++/** A self-hosted server with no Stirling account yet: connecting comes first. */+export const NotConnected: Story = {+ globals: { linkState: "unlinked" },+ parameters: { msw: { handlers: handlers(null) } },+};++export const Trial: Story = {+ parameters: { msw: { handlers: handlers(trial) } },+};++/** At the quote stage with nothing issued yet: building it is the next step. */+export const QuoteDraft: Story = {+ parameters: {+ msw: { handlers: handlers({ ...trial, stage: "quote" }) },+ },+};++/** An issued quote is a decision: accept it, or open it again to read and circulate. */+export const QuoteIssued: Story = {+ parameters: {+ msw: {+ handlers: handlers({ ...trial, stage: "quote", latestQuote: quote }),+ },+ },+};++/** Quote accepted: the agreement is next, read and signed on the page. */+export const Agreement: Story = {+ parameters: {+ msw: {+ handlers: [+ ...handlers({ ...trial, stage: "security", latestQuote: quote }),+ http.get(`${SAAS}/api/v1/procurement/agreement/document`, () =>+ HttpResponse.json({+ docId: "enterprise-agreement",+ version: "0.9.1",+ versionLabel: "SEA v0.9.1",+ displayName: "Stirling Enterprise Agreement",+ effectiveDate: "2026-07-10",+ status: "draft",+ markdown: Array.from(+ { length: 12 },+ (_, i) =>+ `## ${i + 1}. Section\n\nThe parties agree to the terms set out in this section.`,+ ).join("\n\n"),+ }),+ ),+ ],+ },+ },+};++export const Payment: Story = {+ parameters: {+ msw: {+ handlers: handlers({+ ...trial,+ stage: "procurement",+ agreementSignedVersion: "SEA v0.9.1",+ latestQuote: {+ ...quote,+ status: "accepted",+ invoiceUrl: "https://invoice.stripe.com/i/mock",+ },+ }),+ },+ },+};++export const Live: Story = {+ parameters: {+ msw: {+ handlers: handlers({+ ...trial,+ stage: "active",+ licenseKey: "STRL-ENT-7K2Q-9XWD-4MPA-LIVE",+ agreementSignedVersion: "SEA v0.9.1",+ latestQuote: { ...quote, status: "accepted" },+ }),+ },+ },+};++/** Members follow the deal without its actions. */+export const Member: Story = {+ parameters: { msw: { handlers: handlers(trial, "member") } },+};diff --git a/frontend/src/processor/proprietary/views/Enterprise.test.tsx b/frontend/src/processor/proprietary/views/Enterprise.test.tsxnew file mode 100644index 0000000000..7359256287--- /dev/null+++ b/frontend/src/processor/proprietary/views/Enterprise.test.tsx@@ -0,0 +1,545 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ cleanup,+} from "@testing-library/react";+import { MemoryRouter } from "react-router-dom";+import { MantineProvider } from "@mantine/core";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ProcurementSnapshot } from "@processor/api/procurement";+import { RATE_CARD } from "@processor/mocks/handlers/procurementSaas";+import type { ProcurementController } from "@processor/components/procurement/useProcurement";+import type { TrialDraft } from "@processor/components/procurement/trialDraft";+import { Enterprise } from "@processor/views/Enterprise";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, value?: unknown) =>+ typeof value === "string" ? value : key,+ i18n: { language: "en-US" },+ }),+}));++const state = vi.hoisted(() => ({+ controller: null as unknown as ProcurementController,+ gate: {+ loading: false,+ gated: false,+ available: true,+ error: null as string | null,+ retry: () => {},+ connect: () => {},+ },+ owner: true,+ linkProvider: true as boolean,+ role: "leader",+ signedIn: true,+ draft: null as TrialDraft | null,+ flowStep: null as "builder" | "agreement" | null,+ useProcurement: null as unknown as () => ProcurementController,+}));++vi.mock("@editor/auth", () => ({+ useAuth: () => ({+ loading: false,+ isAnonymous: false,+ session: state.signedIn ? {} : null,+ user: state.signedIn ? { email: "[email protected]" } : null,+ }),+}));+const rememberPendingDestination = vi.hoisted(() => vi.fn());+vi.mock("@editor/services/pendingDestination", () => ({+ rememberPendingDestination,+}));+const saveTrialDraft = vi.hoisted(() => vi.fn());+vi.mock("@processor/components/procurement/trialDraft", () => ({+ saveTrialDraft,+ takeTrialDraft: () => state.draft,+}));++vi.mock("@processor/components/procurement/useProcurement", () => ({+ useProcurement: () => state.useProcurement(),+}));+vi.mock("@processor/hooks/useConnectGate", () => ({+ useConnectGate: () => state.gate,+}));+vi.mock("@processor/hooks/useAccountLinkOwner", () => ({+ useAccountLinkOwner: () => state.owner,+}));+vi.mock("@processor/hooks/useLinkedAccountEmail", () => ({+ useLinkedAccountEmail: () => null,+}));+vi.mock("@processor/contexts/LinkContext", () => ({+ useLinkOptional: () => (state.linkProvider ? {} : null),+}));+vi.mock("@processor/contexts/UIContext", () => ({+ useUI: () => ({ openSettings: vi.fn() }),+}));+vi.mock("@processor/components/account-link/SaasSessionBanner", () => ({+ SaasSessionBanner: () => null,+}));+vi.mock("@processor/components/procurement/ProcurementFlow", () => ({+ ProcurementFlow: () => null,+ procurementFlowStep: () => state.flowStep,+}));+vi.mock("@processor/api/billing", () => ({+ refreshWalletCache: () => Promise.resolve(),+}));+vi.mock("@processor/queries/wallet", () => ({+ walletQuery: (linked: boolean) => ({+ queryKey: ["wallet", linked],+ queryFn: async () => {+ if (state.role === "unavailable") throw new Error("Wallet unavailable");+ return { role: state.role };+ },+ enabled: linked,+ }),+}));++const trial: ProcurementSnapshot = {+ dealId: 1,+ stage: "trial",+ deployment: "selfhost",+ seats: 50,+ trialStartedAt: "2026-09-01T00:00:00Z",+ trialEndsAt: "2099-09-15T00:00:00Z",+ trialExtensionsUsed: 0,+ licensed: true,+ licenseKey: "TRIAL-KEY",+ agreementSignedVersion: null,+ businessName: "Northwind",+ contactName: null,+ contactEmail: null,+ latestQuote: null,+ rateCard: RATE_CARD,+ maxTrialExtensions: 2,+ minAnnualNetMinor: 0,+ entitledDeployment: null,+};++function controller(+ overrides: Partial<ProcurementController> = {},+): ProcurementController {+ const data = overrides.data === undefined ? trial : overrides.data;+ return {+ isLinked: true,+ loading: false,+ loadError: null,+ retry: vi.fn(),+ data,+ started: data?.dealId != null,+ stage: data?.stage ?? undefined,+ latest: data?.latestQuote ?? null,+ isIssued: false,+ isDraft: true,+ busy: false,+ downloading: false,+ downloadingLicense: false,+ downloadingAgreement: false,+ error: null,+ setError: vi.fn(),+ open: false,+ setOpen: vi.fn(),+ editing: false,+ setEditing: vi.fn(),+ extra: null,+ setExtra: vi.fn(),+ invoicePdf: null,+ onExploreEnterprise: vi.fn(),+ onConfirmSetup: vi.fn(),+ onExtendTrial: vi.fn(),+ onGenerate: vi.fn(),+ onAcceptQuote: vi.fn(),+ onAgree: vi.fn(),+ onDownloadPdf: vi.fn(),+ onDownloadOfflineLicense: vi.fn(),+ onDownloadSignedAgreement: vi.fn(),+ ...overrides,+ };+}++function mount() {+ render(+ <MantineProvider>+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ <MemoryRouter>+ <Enterprise />+ </MemoryRouter>+ </QueryClientProvider>+ </MantineProvider>,+ );+}++beforeEach(() => {+ state.gate = { ...state.gate, available: true, connect: vi.fn() };+ state.owner = true;+ state.linkProvider = true;+ state.role = "leader";+ state.signedIn = true;+ state.draft = null;+ state.flowStep = null;+ state.useProcurement = vi.fn(() => state.controller);+ rememberPendingDestination.mockReset();+ saveTrialDraft.mockReset();+});++describe("Enterprise page", () => {+ it("asks a server's owner to connect before anything else", () => {+ state.controller = controller({ isLinked: false, data: null });+ mount();+ fireEvent.click(+ screen.getByRole("button", { name: "portal.procurement.link.cta" }),+ );+ expect(state.gate.connect).toHaveBeenCalledOnce();+ expect(state.controller.onExploreEnterprise).not.toHaveBeenCalled();+ });++ it("tells another administrator that only the owner can connect", () => {+ state.owner = false;+ state.controller = controller({ isLinked: false, data: null });+ mount();+ expect(+ screen.queryByRole("button", { name: "portal.procurement.link.cta" }),+ ).not.toBeInTheDocument();+ expect(+ screen.getByText(+ "Only this server’s owner can connect it. Ask them to open this page.",+ ),+ ).toBeInTheDocument();+ });++ it("records interest once and offers the trial setup to a leader with no deal", async () => {+ state.controller = controller({ data: null });+ mount();+ expect(+ await screen.findByText("portal.procurement.setup.title"),+ ).toBeInTheDocument();+ await waitFor(() =>+ expect(state.controller.onExploreEnterprise).toHaveBeenCalledOnce(),+ );+ });++ it("puts a trial's next step, licence and trial controls on the page", async () => {+ state.controller = controller();+ mount();+ fireEvent.click(+ await screen.findByRole("button", {+ name: "portal.procurement.hero.ctaTrial",+ }),+ );+ expect(state.controller.setOpen).toHaveBeenCalledWith(true);+ expect(screen.getByText("TRIAL-KEY")).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "portal.procurement.trial.extend" }),+ );+ expect(state.controller.onExtendTrial).toHaveBeenCalledOnce();+ expect(state.controller.onExploreEnterprise).not.toHaveBeenCalled();+ });++ it("opens the quote builder from the tracker's quote stage during the trial", async () => {+ state.controller = controller();+ mount();+ fireEvent.click(+ await screen.findByRole("button", {+ name: /journeySteps.quote.label/,+ }),+ );+ expect(state.controller.setOpen).toHaveBeenCalledWith(true);+ });++ it("opens a finished stage read-only from the tracker, leaving the deal where it is", async () => {+ const signed: ProcurementSnapshot = {+ ...trial,+ stage: "procurement",+ agreementSignedVersion: "SEA v1",+ latestQuote: {+ quoteId: 7,+ quoteNumber: "QT-1",+ status: "accepted",+ currency: "usd",+ annualNetMinor: 1_600_000,+ tcvMinor: 1_600_000,+ renewalAnnualNetMinor: 1_650_000,+ cpiRatePct: 3,+ lineItems: [],+ validUntil: null,+ stripeQuoteId: "qt_1",+ invoiceUrl: "https://invoice.example/1",+ invoicePdf: null,+ config: {+ volume: 300_000,+ users: 50,+ intensity: 4,+ sizeMult: 1.4,+ deployment: "selfhost",+ termYears: 1,+ serviceLevel: "standard",+ indemnification: false,+ training: false,+ qbr: false,+ businessName: "Northwind",+ },+ },+ };+ state.controller = controller({ data: signed });+ mount();++ // Back from payment opens the agreement as it was signed.+ fireEvent.click(+ await screen.findByRole("button", { name: "Back to {{stage}}" }),+ );+ expect(screen.getByText("Version")).toBeInTheDocument();+ expect(screen.getByText("Completed")).toBeInTheDocument();++ fireEvent.click(+ screen.getByRole("button", { name: /journeySteps.trial.label/ }),+ );+ expect(screen.getByText("Your trial")).toBeInTheDocument();+ expect(screen.getByText("Completed")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", {+ name: "portal.procurement.payment.viewInvoice",+ }),+ ).not.toBeInTheDocument();++ fireEvent.click(+ screen.getByRole("button", { name: /journeySteps.agreement.label/ }),+ );+ expect(screen.getByText("Version")).toBeInTheDocument();++ fireEvent.click(+ screen.getByRole("button", { name: "portal.enterprise.review.back" }),+ );+ expect(screen.queryByText("Completed")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", {+ name: "portal.procurement.payment.viewInvoice",+ }),+ ).toBeInTheDocument();+ expect(state.controller.setOpen).not.toHaveBeenCalled();++ // Leaving mid-review and coming back (from settings, say) lands on the stage the deal has+ // reached, not the finished one last looked at.+ fireEvent.click(+ screen.getByRole("button", { name: /journeySteps.trial.label/ }),+ );+ cleanup();+ mount();+ expect(+ await screen.findByRole("button", {+ name: "portal.procurement.payment.viewInvoice",+ }),+ ).toBeInTheDocument();+ expect(screen.queryByText("Completed")).not.toBeInTheDocument();+ });++ it("lets a member follow the deal without acting on it", async () => {+ state.role = "member";+ state.controller = controller();+ mount();+ expect(+ await screen.findByText(+ "Your team leader runs this deal. You can follow its progress here.",+ ),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", {+ name: "portal.procurement.hero.ctaTrial",+ }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "portal.procurement.trial.extend" }),+ ).not.toBeInTheDocument();+ });++ it("leaves the quote builder for the trial it was opened from", async () => {+ state.flowStep = "builder";+ state.controller = controller({ open: true });+ mount();+ fireEvent.click(+ await screen.findByRole("button", { name: "Back to {{stage}}" }),+ );+ expect(state.controller.setOpen).toHaveBeenCalledWith(false);+ });++ it("has nothing to go back to from the first stage", async () => {+ state.controller = controller();+ mount();+ await screen.findAllByText("portal.procurement.journeySteps.trial.label");+ expect(+ screen.queryByRole("button", { name: "Back to {{stage}}" }),+ ).not.toBeInTheDocument();+ });++ it("links the logo back into the app", () => {+ state.controller = controller();+ mount();+ expect(+ screen.getByRole("link", { name: "Go to Stirling" }),+ ).toHaveAttribute("href", "/");+ });++ it("says the wallet failed rather than showing a leader the member view", async () => {+ state.role = "unavailable";+ state.controller = controller();+ mount();+ expect(await screen.findByText("Wallet unavailable")).toBeInTheDocument();+ expect(+ screen.queryByText(+ "Your team leader runs this deal. You can follow its progress here.",+ ),+ ).not.toBeInTheDocument();+ });++ it("offers no fresh start while the deal cannot be loaded", async () => {+ state.controller = controller({+ data: null,+ loadError: "Snapshot unavailable",+ });+ mount();+ expect(await screen.findByText("Snapshot unavailable")).toBeInTheDocument();+ expect(+ screen.queryByText("portal.procurement.setup.title"),+ ).not.toBeInTheDocument();+ expect(state.controller.onExploreEnterprise).not.toHaveBeenCalled();+ });++ it("lets a visitor without an account fill in the trial, and asks them to sign in to start it", () => {+ state.signedIn = false;+ mount();+ expect(state.useProcurement).not.toHaveBeenCalled();++ fireEvent.change(+ screen.getByLabelText(/^portal\.procurement\.setup\.seats/),+ {+ target: { value: "40" },+ },+ );+ fireEvent.click(+ screen.getByRole("button", { name: "portal.procurement.setup.continue" }),+ );+ fireEvent.change(+ screen.getByLabelText(/^portal.procurement.setup.fullName/),+ { target: { value: "Dana Lee" } },+ );+ fireEvent.change(+ screen.getByLabelText(/^portal.procurement.setup.businessName/),+ { target: { value: "Northwind" } },+ );+ fireEvent.change(+ screen.getByLabelText(/^portal.procurement.setup.workEmail/),+ { target: { value: "[email protected]" } },+ );+ fireEvent.click(screen.getByRole("checkbox"));+ fireEvent.click(+ screen.getByRole("button", { name: "Sign in to start your trial" }),+ );++ expect(saveTrialDraft).toHaveBeenCalledWith({+ deployment: "cloud",+ seats: 40,+ details: {+ businessName: "Northwind",+ contactName: "Dana Lee",+ contactEmail: "[email protected]",+ inviteEmails: "",+ },+ eulaAgreed: true,+ });+ expect(rememberPendingDestination).toHaveBeenCalledOnce();+ });++ it("returns a visitor from sign-in to their own answers", async () => {+ state.draft = {+ deployment: "selfhost",+ seats: 40,+ details: {+ businessName: "Northwind",+ contactName: "Dana Lee",+ contactEmail: "[email protected]",+ },+ };+ state.controller = controller({ data: null });+ mount();+ expect(+ await screen.findByLabelText(/^portal.procurement.setup.businessName/),+ ).toHaveValue("Northwind");+ expect(+ screen.getByRole("button", { name: "portal.procurement.setup.start" }),+ ).toBeInTheDocument();+ });++ it("starts the trial on return from sign-in when the terms were agreed before it", async () => {+ const details = {+ businessName: "Northwind",+ contactName: "Dana Lee",+ contactEmail: "[email protected]",+ };+ state.draft = {+ deployment: "selfhost",+ seats: 40,+ details,+ eulaAgreed: true,+ };+ state.controller = controller({ data: null });+ mount();+ await waitFor(() =>+ expect(state.controller.onConfirmSetup).toHaveBeenCalledWith(+ "selfhost",+ 40,+ details,+ ),+ );+ expect(state.controller.onConfirmSetup).toHaveBeenCalledOnce();+ expect(state.controller.onExploreEnterprise).not.toHaveBeenCalled();+ // The form it is leaving is never shown while the trial starts.+ expect(+ screen.queryByText("portal.procurement.setup.title"),+ ).not.toBeInTheDocument();+ });++ it("leaves answers given for another account behind", async () => {+ state.draft = {+ deployment: "selfhost",+ seats: 40,+ details: {+ businessName: "Contoso",+ contactName: "Sam Roe",+ contactEmail: "[email protected]",+ },+ eulaAgreed: true,+ };+ state.controller = controller({ data: null });+ mount();+ // A fresh setup, as if no answers were kept.+ expect(+ await screen.findByText("portal.procurement.setup.title"),+ ).toBeInTheDocument();+ await waitFor(() =>+ expect(state.controller.onExploreEnterprise).toHaveBeenCalledOnce(),+ );+ expect(state.controller.onConfirmSetup).not.toHaveBeenCalled();+ expect(screen.queryByDisplayValue("Contoso")).not.toBeInTheDocument();+ });++ it("brings the trial setup back if starting it on return fails", async () => {+ state.draft = {+ deployment: "cloud",+ seats: 1,+ details: { businessName: "Northwind", contactName: "Dana Lee" },+ eulaAgreed: true,+ };+ state.controller = controller({ data: null, error: "Trial failed" });+ mount();+ expect(+ await screen.findByText("portal.procurement.setup.title"),+ ).toBeInTheDocument();+ });+});diff --git a/frontend/src/processor/proprietary/views/Enterprise.tsx b/frontend/src/processor/proprietary/views/Enterprise.tsxnew file mode 100644index 0000000000..dccb6f6d4f--- /dev/null+++ b/frontend/src/processor/proprietary/views/Enterprise.tsx@@ -0,0 +1,1325 @@+import { useEffect, useRef, useState, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Link } from "react-router-dom";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { Banner, Button, Card, Dropdown, Logo, Skeleton } from "@editor/ui";+import { Icon } from "@editor/ui/Icon";+import { useAuth } from "@editor/auth";+import { stripBasePath, withBasePath } from "@editor/constants/app";+import { rememberPendingDestination } from "@editor/services/pendingDestination";+import {+ FLOW_JOURNEY,+ type DealStage,+ type QuoteResult,+} from "@processor/api/procurement";+import { refreshWalletCache } from "@processor/api/billing";+import { openApiUrl } from "@processor/api/externalUrl";+import { qk } from "@processor/queries/keys";+import { walletQuery } from "@processor/queries/wallet";+import { useLinkOptional } from "@processor/contexts/LinkContext";+import { useUI } from "@processor/contexts/UIContext";+import { useConnectGate } from "@processor/hooks/useConnectGate";+import { useAccountLinkOwner } from "@processor/hooks/useAccountLinkOwner";+import { useLinkedAccountEmail } from "@processor/hooks/useLinkedAccountEmail";+import { SaasSessionBanner } from "@processor/components/account-link/SaasSessionBanner";+import {+ useProcurement,+ type ProcurementController,+} from "@processor/components/procurement/useProcurement";+import {+ ProcurementFlow,+ procurementFlowStep,+} from "@processor/components/procurement/ProcurementFlow";+import {+ DocumentsList,+ ScheduleCallModal,+ TrialSetupForm,+} from "@processor/components/procurement/ProcurementExtras";+import { DeploymentOptions } from "@processor/components/procurement/DeploymentOptions";+import { LicensePanel } from "@processor/components/procurement/ProcurementStages";+import { SetupChecklist } from "@processor/components/procurement/SetupChecklist";+import {+ daysLeft,+ longDate,+ money,+ trialLeftLabel,+} from "@processor/components/procurement/format";+import {+ saveTrialDraft,+ takeTrialDraft,+} from "@processor/components/procurement/trialDraft";+import "@processor/views/Procurement.css";+import "@processor/views/Enterprise.css";++/** Stages that still run on the trial licence, so the trial's clock and controls apply. */+const TRIAL_STAGES: DealStage[] = ["trial", "quote", "security"];++/**+ * The whole Enterprise journey on one page: why Enterprise and the trial setup for a new buyer,+ * then where the deal stands, its next action, licence key, trial, documents and a way to talk to+ * us. Building a quote and signing the agreement are long enough to open over it.+ *+ * Open to visitors without an account where the build allows it (the hosted page, linked from+ * the website): they read the page and fill in the trial setup, and sign in only to start it.+ */+export function Enterprise({+ onSignIn = signIn,+}: {+ /** Replaces the redirect to sign-in; the Storybook demo signs in on the spot. */+ onSignIn?: () => void;+}) {+ const { session, isAnonymous, loading } = useAuth();+ if (loading) {+ return (+ <Shell>+ <PageSkeleton />+ </Shell>+ );+ }+ return session && !isAnonymous ? (+ <SignedIn />+ ) : (+ <SignedOut onSignIn={onSignIn} />+ );+}++/**+ * Sign in, then come back here. Remembered for sign-up's confirmation email, which cannot carry a+ * `next`; named in the URL too, so the sign-in screens know where the visitor is headed.+ */+function signIn() {+ const here = `${stripBasePath(window.location.pathname)}${window.location.search}`;+ rememberPendingDestination(here);+ window.location.href = withBasePath(+ `/login?next=${encodeURIComponent(here)}`,+ );+}++function SignedOut({ onSignIn }: { onSignIn: () => void }) {+ const { t } = useTranslation();+ const [scheduling, setScheduling] = useState(false);+ return (+ <Shell+ headerAction={+ <Button variant="secondary" onClick={onSignIn}>+ {t("portal.enterprise.signIn", "Sign in")}+ </Button>+ }+ onSchedule={() => setScheduling(true)}+ >+ <Landing>+ <TrialSetupForm+ busy={false}+ startLabel={t(+ "portal.enterprise.signInToStart",+ "Sign in to start your trial",+ )}+ onScheduleCall={() => setScheduling(true)}+ onConfirm={(deployment, seats, details) => {+ saveTrialDraft({ deployment, seats, details, eulaAgreed: true });+ onSignIn();+ }}+ />+ </Landing>+ <ScheduleCallModal+ open={scheduling}+ onClose={() => setScheduling(false)}+ />+ </Shell>+ );+}++function SignedIn() {+ const { t } = useTranslation();+ const { user } = useAuth();+ const queryClient = useQueryClient();+ const procurement = useProcurement();+ const gate = useConnectGate();+ // No provider on SaaS: the signed-in account is the Stirling account, so there is nothing to link.+ const link = useLinkOptional();+ const isOwner = useAccountLinkOwner();+ const email = useLinkedAccountEmail();+ const { openSettings } = useUI();+ // Answers given before signing in, if this visit is the return from it. Only the account they+ // were given for picks them up: on a shared browser, whoever signs in next must not start a+ // trial on another person's details and consent.+ const [draft] = useState(() => {+ const saved = takeTrialDraft();+ const given = saved?.details.contactEmail?.trim().toLowerCase();+ return given && given === user?.email?.trim().toLowerCase() ? saved : null;+ });+ const { isLinked, data, started, stage, latest, busy } = procurement;+ const wallet = useQuery(walletQuery(isLinked));+ // Members follow the deal; only the team leader can act on it. Unknown while the wallet fails,+ // which a banner says rather than showing a leader the member view.+ const canManage = wallet.data?.role === "leader";+ const roleKnown = wallet.isSuccess;+ // Without the snapshot it's unknown whether a deal exists, so a load error offers no fresh start.+ const exploring =+ !procurement.loadError && (!started || stage === "exploring");++ // A first visit does one of two things, once: back from signing in with the setup finished and the+ // terms agreed, it starts the trial that click asked for; otherwise it records interest, since+ // arriving here is asking about Enterprise. Accounts that never ask stay free of the deal surface,+ // and drop-off before the trial is visible.+ const firstVisitHandled = useRef(false);+ const resumeTrial = draft?.eulaAgreed === true && exploring;+ useEffect(() => {+ if (+ firstVisitHandled.current ||+ !canManage ||+ procurement.loading ||+ procurement.loadError ||+ (started && !resumeTrial)+ )+ return;+ firstVisitHandled.current = true;+ if (resumeTrial && draft) {+ procurement.onConfirmSetup(draft.deployment, draft.seats, draft.details);+ } else {+ procurement.onExploreEnterprise();+ }+ }, [canManage, procurement, started, resumeTrial, draft]);++ // A trial or agreement changes entitlements; billing must not show the old plan on return.+ const previousDeal = useRef(data);+ useEffect(() => {+ const previous = previousDeal.current;+ previousDeal.current = data;+ if (!previous || previous === data) return;+ void refreshWalletCache()+ .catch(() => {})+ .then(() =>+ queryClient.invalidateQueries({ queryKey: qk.wallet(isLinked) }),+ );+ }, [data, isLinked, queryClient]);++ const schedule = () => procurement.setExtra("schedule");++ // While the trial starts from the saved answers the page stays on its placeholder rather than+ // flashing the form it is about to leave. Settled by the attempt ending as well as by an error:+ // a session failure clears the error and would otherwise hold the placeholder for good.+ const startingTrial =+ resumeTrial &&+ canManage &&+ !procurement.error &&+ !procurement.loadError &&+ (!firstVisitHandled.current || busy);+ const loading =+ gate.loading ||+ (isLinked && (procurement.loading || wallet.isPending)) ||+ startingTrial;++ const company =+ latest?.config.businessName?.trim() || data?.businessName?.trim() || null;+ // Building a quote or signing opens within the deal, at the stage it belongs to.+ const flowStep = procurement.open ? procurementFlowStep(procurement) : null;+ const flowOpen = flowStep != null;+ const onInvite = canManage ? () => openSettings("users") : undefined;++ /** The page's main content, by how far the visitor has got: linking, then exploring, then the deal. */+ function body(): ReactNode {+ if (loading) return <PageSkeleton />;+ if (!isLinked)+ return (+ <Landing>+ <ConnectPanel+ available={gate.available}+ isOwner={isOwner}+ onConnect={gate.connect}+ onSchedule={schedule}+ />+ </Landing>+ );+ // The banner above says what failed and offers a retry.+ if (procurement.loadError) return null;+ if (exploring) {+ if (canManage)+ return (+ <Landing>+ <TrialSetupForm+ busy={busy}+ email={email}+ initial={draft}+ onScheduleCall={schedule}+ onConfirm={procurement.onConfirmSetup}+ />+ </Landing>+ );+ return (+ <Landing>+ {roleKnown && (+ <p className="ent__note">+ {t(+ "portal.enterprise.member",+ "Your team leader runs the Enterprise deal. Once it starts, you can follow its progress here.",+ )}+ </p>+ )}+ </Landing>+ );+ }+ return (+ <Deal+ controller={procurement}+ canManage={canManage}+ roleKnown={roleKnown}+ teamSize={wallet.data?.team?.usersInUse ?? 1}+ onInvite={onInvite}+ onSchedule={schedule}+ flowStep={flowStep}+ flow={flowOpen && <ProcurementFlow controller={procurement} />}+ />+ );+ }++ return (+ <Shell+ company={company}+ onInvite={onInvite}+ scrollKey={flowOpen ? "flow" : "page"}+ // A deal carries its own contact section, so the footer would only repeat it.+ onSchedule={loading || !isLinked || exploring ? schedule : undefined}+ >+ <div className="ent__wrap ent__notices">+ {link && <SaasSessionBanner />}+ {gate.error && (+ <RetryBanner message={gate.error} onRetry={gate.retry} />+ )}+ {wallet.isError && (+ <RetryBanner+ message={wallet.error.message}+ onRetry={() => void wallet.refetch()}+ />+ )}+ {procurement.loadError && (+ <RetryBanner+ message={procurement.loadError}+ onRetry={procurement.retry}+ />+ )}+ {procurement.error && !procurement.open && (+ <Banner+ tone="danger"+ title={t("portal.procurement.error.title")}+ onDismiss={() => procurement.setError(null)}+ >+ {procurement.error}+ </Banner>+ )}+ </div>++ {body()}++ {/* Mounted here while no step is open: booking a call opens from anywhere on the page. */}+ {!flowOpen && <ProcurementFlow controller={procurement} />}+ </Shell>+ );+}++/** Something the page could not load, and the way to try again. */+function RetryBanner({+ message,+ onRetry,+}: {+ message: string;+ onRetry: () => void;+}) {+ const { t } = useTranslation();+ return (+ <Banner+ tone="danger"+ title={t("portal.procurement.error.title")}+ action={+ <Button size="sm" onClick={onRetry}>+ {t("portal.accountLink.gate.retry", "Try again")}+ </Button>+ }+ >+ {message}+ </Banner>+ );+}++/** The page's own header and footer, in place of the app's chrome. */+function Shell({+ company,+ headerAction,+ onInvite,+ onSchedule,+ scrollKey,+ children,+}: {+ company?: string | null;+ /** Team actions under the company name; omitted for members, who see it as a label. */+ onInvite?: () => void;+ headerAction?: ReactNode;+ onSchedule?: () => void;+ /** A change of view: the page scrolls itself, so it returns to the top as a new page would. */+ scrollKey?: string;+ children: ReactNode;+}) {+ const { t } = useTranslation();+ const pageRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ pageRef.current?.scrollTo?.({ top: 0 });+ }, [scrollKey]);+ return (+ <div className="ent" ref={pageRef}>+ <header className="ent__header">+ <div className="ent__wrap ent__header-inner">+ <div className="ent__brand">+ {/* The page has no app chrome, so the logo is the way back into the app. */}+ <Link+ to="/"+ className="ent__home"+ aria-label={t("portal.enterprise.home", "Go to Stirling")}+ >+ <Logo+ variant="iconAndText"+ iconHeight="1.5rem"+ textHeight="1rem"+ />+ </Link>+ <span className="ent__brand-tag">+ {t("portal.enterprise.brandTag", "Enterprise")}+ </span>+ </div>+ <div className="ent__header-end">+ {company &&+ (onInvite ? (+ <Dropdown.Root align="end">+ <Dropdown.Trigger>+ <button type="button" className="ent__company">+ {company}+ <Icon name="chevron-down" size={14} />+ </button>+ </Dropdown.Trigger>+ <Dropdown.Menu>+ <Dropdown.Item+ onSelect={onInvite}+ leading={<Icon name="user-plus" size={16} />}+ >+ {t("portal.procurement.hero.inviteTeammates")}+ </Dropdown.Item>+ </Dropdown.Menu>+ </Dropdown.Root>+ ) : (+ <span className="ent__company">{company}</span>+ ))}+ {headerAction}+ </div>+ </div>+ </header>++ <main className="ent__main">{children}</main>++ {onSchedule && (+ <footer className="ent__footer">+ <div className="ent__wrap ent__footer-inner">+ <span>+ {t(+ "portal.enterprise.footer",+ "Questions about Stirling Enterprise?",+ )}+ </span>+ <button+ type="button"+ className="portal-legal__link"+ onClick={onSchedule}+ >+ {t("portal.procurement.hero.scheduleCall")}+ </button>+ </div>+ </footer>+ )}+ </div>+ );+}++function PageSkeleton() {+ return (+ <div className="ent__wrap ent__loading" aria-hidden>+ <Skeleton height="2.5rem" width="60%" />+ <Skeleton height="16rem" shape="rect" />+ </div>+ );+}++/** First visit: what Enterprise is, beside the one thing to do next. */+function Landing({ children }: { children: ReactNode }) {+ const { t } = useTranslation();+ const ticks = [+ t(+ "portal.enterprise.landing.tickDeploy",+ "Run it on Stirling Cloud, your own servers, or fully air-gapped",+ ),+ t(+ "portal.enterprise.landing.tickCompliance",+ "SCIM, data residency and uptime SLAs",+ ),+ t(+ "portal.enterprise.landing.tickAgreement",+ "One agreement covering the MSA, order form, EULA and DPA",+ ),+ ];+ return (+ <div className="ent__wrap ent__landing">+ <section className="ent__intro">+ <span className="ent__eyebrow">+ {t("portal.enterprise.brandTag", "Enterprise")}+ </span>+ <h1 className="ent__h1">+ {t("portal.enterprise.landing.title", "Stirling Enterprise")}+ </h1>+ <p className="ent__lede">+ {t(+ "portal.enterprise.landing.lede",+ "Try it free for 14 days, then build your quote and sign your agreement here. No card required.",+ )}+ </p>+ <ul className="ent__ticks">+ {ticks.map((tick) => (+ <li key={tick}>+ <Icon name="check" size={16} />+ {tick}+ </li>+ ))}+ </ul>+ <DeploymentOptions />+ </section>+ <Card padding="loose" className="ent__panel">+ {children}+ </Card>+ </div>+ );+}++/** Self-hosted, before the server has a Stirling account to run the trial and quote on. */+function ConnectPanel({+ available,+ isOwner,+ onConnect,+ onSchedule,+}: {+ available: boolean;+ isOwner: boolean;+ onConnect: () => void;+ onSchedule: () => void;+}) {+ const { t } = useTranslation();+ if (!available) {+ return (+ <div className="ent__panel-body">+ <h2 className="ent__h2">{t("portal.procurement.link.title")}</h2>+ <p className="ent__text">+ {t(+ "portal.enterprise.connect.unavailable",+ "Connecting to a Stirling account is turned off on this server. Book a call and we’ll set up your trial with you.",+ )}+ </p>+ <div className="ent__actions">+ <Button variant="primary" onClick={onSchedule}>+ {t("portal.procurement.hero.scheduleCall")}+ </Button>+ </div>+ </div>+ );+ }+ return (+ <div className="ent__panel-body">+ <h2 className="ent__h2">{t("portal.procurement.link.title")}</h2>+ <p className="ent__text">{t("portal.procurement.link.description")}</p>+ {isOwner ? (+ <div className="ent__actions">+ <Button variant="primary" onClick={onConnect}>+ {t("portal.procurement.link.cta")}+ </Button>+ </div>+ ) : (+ <p className="ent__note">+ {t(+ "portal.enterprise.connect.ownerOnly",+ "Only this server’s owner can connect it. Ask them to open this page.",+ )}+ </p>+ )}+ </div>+ );+}++/** Which stage of the journey a long step shows, when one is open. */+const FLOW_STEP_STAGE = { builder: "quote", agreement: "security" } as const;++/**+ * The deal page's navigation. The tracker doubles as navigation: a finished stage opens for review,+ * shown as it was left while the deal itself stays put; the deal's own stage returns to its overview+ * or opens its long step; and from the trial, the quote stage is the same as "Build your quote".+ */+function useStageNavigation({+ stage,+ flowStep,+ flowShown,+ canManage,+ setOpen,+}: {+ stage: DealStage;+ flowStep?: "builder" | "agreement" | null;+ /** A long step is on screen, which ends any review. */+ flowShown: boolean;+ canManage: boolean;+ setOpen: (open: boolean) => void;+}) {+ const [review, setReview] = useState<{+ index: number;+ stage: DealStage;+ } | null>(null);+ // Opening a step or the deal moving on ends the review, so it never resurfaces over a later stage.+ if (review && (flowShown || review.stage !== stage)) setReview(null);+ const reviewing = flowShown ? null : (review?.index ?? null);+ const shownStage: DealStage =+ reviewing != null+ ? FLOW_JOURNEY[reviewing].stage+ : flowStep+ ? FLOW_STEP_STAGE[flowStep]+ : stage;+ const currentIdx = Math.max(+ 0,+ FLOW_JOURNEY.findIndex((s) => s.stage === shownStage),+ );+ const actualIdx = FLOW_JOURNEY.findIndex((s) => s.stage === stage);+ const stageAction = (index: number): (() => void) | undefined => {+ const target = FLOW_JOURNEY[index].stage;+ if (index < actualIdx && !flowStep)+ return () => setReview({ index, stage });+ if (index === actualIdx) {+ if (flowStep) return () => setOpen(false);+ if (reviewing != null) return () => setReview(null);+ if (canManage && (target === "quote" || target === "security"))+ return () => setOpen(true);+ return undefined;+ }+ if (canManage && target === "quote" && stage === "trial") {+ return flowStep ? undefined : () => setOpen(true);+ }+ return undefined;+ };+ // The stage before the one on screen. The deal's own stage returns to its overview, closing any+ // step open over it; a stage already finished opens as it was left.+ const backIdx = currentIdx - 1;+ const goBack =+ backIdx >= 0 && backIdx <= actualIdx+ ? () => {+ if (flowStep) setOpen(false);+ setReview(backIdx < actualIdx ? { index: backIdx, stage } : null);+ }+ : undefined;+ return {+ reviewing,+ shownStage,+ currentIdx,+ actualIdx,+ backIdx,+ stageAction,+ goBack,+ endReview: () => setReview(null),+ };+}++/** A deal underway: where it stands, its next action, and everything it has produced so far. */+function Deal({+ controller,+ canManage,+ roleKnown,+ teamSize,+ onInvite,+ onSchedule,+ flowStep,+ flow,+}: {+ controller: ProcurementController;+ canManage: boolean;+ /** False while the viewer's role could not be loaded: neither the leader's nor a member's view. */+ roleKnown: boolean;+ teamSize: number;+ onInvite?: () => void;+ onSchedule: () => void;+ /** The long step open within the deal, if any; the header follows it to its stage. */+ flowStep?: "builder" | "agreement" | null;+ flow?: ReactNode;+}) {+ const { t } = useTranslation();+ const {+ data,+ latest,+ isIssued,+ busy,+ setOpen,+ downloading,+ downloadingLicense,+ downloadingAgreement,+ invoicePdf,+ } = controller;+ const stage = controller.stage ?? "trial";+ const {+ reviewing,+ shownStage,+ currentIdx,+ actualIdx,+ backIdx,+ stageAction,+ goBack,+ endReview,+ } = useStageNavigation({+ stage,+ flowStep,+ flowShown: !!flow,+ canManage,+ setOpen,+ });+ const step = FLOW_JOURNEY[currentIdx];+ const inTrial = TRIAL_STAGES.includes(stage);+ // What the licence is issued for, which a quote can change from the trial's choice.+ const deployment = data?.entitledDeployment ?? data?.deployment ?? "cloud";+ const isLive = stage === "active";+ // Once a quote is on the table it is what the buyer is deciding on, so it takes the panel and+ // the trial's clock drops to a chip beside the stage.+ const quoteOnTable =+ reviewing == null && stage === "quote" && isIssued && latest != null;++ return (+ <>+ <section className="ent__band">+ <div className="ent__wrap ent__hero">+ <div className="ent__hero-main">+ <div className="ent__hero-head">+ {goBack && (+ <Button+ variant="tertiary"+ size="sm"+ className="ent__back"+ leftSection={<Icon name="arrow-left" size={16} />}+ onClick={goBack}+ >+ {t("portal.enterprise.backTo", "Back to {{stage}}", {+ stage: t(FLOW_JOURNEY[backIdx].label),+ })}+ </Button>+ )}+ <div className="ent__eyebrow-row">+ <span className="ent__eyebrow">+ {t(+ "portal.enterprise.stage",+ "Stage {{current}} of {{total}}",+ {+ current: currentIdx + 1,+ total: FLOW_JOURNEY.length,+ },+ )}+ </span>+ {reviewing != null && (+ <span className="ent__chip">+ {t("portal.enterprise.review.completed", "Completed")}+ </span>+ )}+ {quoteOnTable && data?.trialEndsAt && (+ <span className="ent__chip">+ {trialLeftLabel(t, data.trialEndsAt)}+ </span>+ )}+ </div>+ <h1 className="ent__h1">{t(step.label)}</h1>+ <p className="ent__lede">{t(step.blurb)}</p>+ {reviewing != null ? (+ <div className="ent__actions">+ <Button variant="secondary" size="md" onClick={endReview}>+ {t("portal.enterprise.review.back", {+ stage: t(FLOW_JOURNEY[actualIdx].label),+ })}+ </Button>+ </div>+ ) : (+ !flow && (+ <HeroAction+ controller={controller}+ canManage={canManage}+ roleKnown={roleKnown}+ stage={stage}+ />+ )+ )}+ </div>+ {/* Talking to us outranks the trial's own controls, so it sits under the next step. */}+ {!flow && reviewing == null && (+ <div className="ent__call">+ <span className="ent__call-icon">+ <Icon name="calendar" size={20} />+ </span>+ <div className="ent__call-text">+ <h2 className="ent__h3">+ {t(+ "portal.enterprise.callTitle",+ "Talk to a solutions engineer",+ )}+ </h2>+ <p className="ent__text">+ {t(+ "portal.enterprise.callInfo",+ "A 15-minute call. Bring your questions on pricing, deployment or security, or plan your rollout together.",+ )}+ </p>+ </div>+ <Button variant="secondary" onClick={onSchedule}>+ {t("portal.procurement.hero.scheduleCall")}+ </Button>+ </div>+ )}+ </div>++ {quoteOnTable && !flow && (+ <QuotePanel+ quote={latest}+ downloading={downloading}+ onDownload={controller.onDownloadPdf}+ />+ )}+ {reviewing != null && (+ <StageReview stage={shownStage} controller={controller} />+ )}+ {inTrial &&+ data?.trialEndsAt &&+ !quoteOnTable &&+ !flow &&+ reviewing == null && (+ <TrialPanel+ trialStartedAt={data.trialStartedAt}+ trialEndsAt={data.trialEndsAt}+ extensionsUsed={data.trialExtensionsUsed}+ maxExtensions={data.maxTrialExtensions}+ busy={busy}+ onExtend={+ canManage && stage === "trial"+ ? controller.onExtendTrial+ : undefined+ }+ />+ )}++ <StageTracker+ currentIdx={reviewing != null ? actualIdx : currentIdx}+ viewingIdx={reviewing}+ isLive={isLive}+ actionFor={stageAction}+ />+ </div>+ </section>++ <div className="ent__wrap ent__body">+ {flow && <div className="ent__flow">{flow}</div>}+ {/* The trial's purpose, so it leads the page; out of the way while a quote or the+ agreement is open. */}+ {!flow && (+ <SetupChecklist+ dealId={data?.dealId}+ deployment={deployment}+ licenseKey={data?.licenseKey}+ live={isLive}+ teamSize={teamSize}+ onInvite={onInvite}+ onDownloadOfflineLicense={+ canManage ? controller.onDownloadOfflineLicense : undefined+ }+ downloadingLicense={downloadingLicense}+ />+ )}+ {data?.licenseKey && (+ <Card padding="loose" className="ent__license">+ <LicensePanel+ licenseKey={data.licenseKey}+ offlineAvailable={deployment === "airgap"}+ downloadingLicense={downloadingLicense}+ onDownloadOffline={controller.onDownloadOfflineLicense}+ />+ {/* Still on the trial licence; from the agreement on, the file is the committed one. */}+ {deployment === "airgap" && TRIAL_STAGES.includes(stage) && (+ <p className="portal-proc__license-hint">+ {t("portal.procurement.license.trialFileHint")}+ </p>+ )}+ </Card>+ )}+ <Card padding="loose">+ <h2 className="ent__h2">{t("portal.procurement.documents.title")}</h2>+ <p className="ent__text">+ {t("portal.procurement.documents.subtitle")}+ </p>+ <DocumentsList+ agreementVersion={data?.agreementSignedVersion}+ downloadingAgreement={downloadingAgreement}+ onDownloadAgreement={controller.onDownloadSignedAgreement}+ onViewAgreement={+ canManage && stage === "security"+ ? () => setOpen(true)+ : undefined+ }+ quoteAvailable={!!latest?.stripeQuoteId}+ downloadingQuote={downloading}+ onDownloadQuote={controller.onDownloadPdf}+ invoiceUrl={latest?.invoiceUrl}+ invoicePdf={invoicePdf}+ />+ </Card>+ </div>+ </>+ );+}++/** The trial's clock, and extending it while the deal is still at the trial stage. */+function TrialPanel({+ trialStartedAt,+ trialEndsAt,+ extensionsUsed,+ maxExtensions,+ busy,+ onExtend,+}: {+ trialStartedAt: string | null;+ trialEndsAt: string;+ extensionsUsed: number;+ /** How many extensions the server allows; it enforces the cap. */+ maxExtensions: number;+ busy: boolean;+ onExtend?: () => void;+}) {+ const { t } = useTranslation();+ const ends = longDate(trialEndsAt);+ const maxed = extensionsUsed >= maxExtensions;+ const start = trialStartedAt ? new Date(trialStartedAt).getTime() : null;+ const end = new Date(trialEndsAt).getTime();+ const used =+ start != null && end > start+ ? Math.min(1, Math.max(0, (Date.now() - start) / (end - start)))+ : null;+ return (+ <div className="ent__aside">+ <span className="ent__aside-label">+ {t("portal.procurement.trial.title")}+ </span>+ <span+ className="ent__aside-figure"+ data-expired={daysLeft(trialEndsAt) === 0 || undefined}+ >+ {trialLeftLabel(t, trialEndsAt)}+ </span>+ {used != null && (+ <span className="ent__trial-bar" aria-hidden>+ <span style={{ width: `${used * 100}%` }} />+ </span>+ )}+ <p className="ent__text">+ {t("portal.procurement.trial.subtitle", { date: ends })}+ </p>+ {onExtend && (+ <>+ <p className="ent__hint">+ {maxed+ ? t("portal.procurement.trial.bodyMaxed")+ : t("portal.procurement.trial.body")}+ </p>+ <div className="ent__actions">+ <Button+ variant="tertiary"+ loading={busy}+ disabled={maxed}+ onClick={onExtend}+ >+ {maxed+ ? t("portal.procurement.trial.maxed")+ : t("portal.procurement.trial.extend")}+ </Button>+ </div>+ </>+ )}+ </div>+ );+}++const SERVICE_LEVEL_LABEL: Record<string, string> = {+ standard: "portal.procurement.builder.slStandard",+ priority: "portal.procurement.builder.slPriority",+ dedicated: "portal.procurement.builder.slDedicated",+};++/** The issued quote's figures, so the buyer can weigh it without opening the paper. */+function QuotePanel({+ quote,+ downloading,+ onDownload,+}: {+ quote: QuoteResult;+ downloading: boolean;+ onDownload: () => void;+}) {+ const { t } = useTranslation();+ return (+ <div className="ent__aside ent__quote">+ <span className="ent__aside-label">+ {t("portal.enterprise.quotePanel", "Your quote")}+ {quote.quoteNumber && (+ <span className="ent__quote-number">{quote.quoteNumber}</span>+ )}+ </span>+ <span className="ent__aside-figure">+ {money(quote.annualNetMinor, quote.currency)}+ </span>+ <span className="ent__quote-caption">+ {t("portal.procurement.review.annual")}+ </span>+ <dl className="ent__facts">+ {/* A seat count of 0 means none was recorded. */}+ {quote.config.users > 0 && (+ <div>+ <dt>{t("portal.procurement.builder.users")}</dt>+ <dd>{quote.config.users.toLocaleString()}</dd>+ </div>+ )}+ <div>+ <dt>{t("portal.enterprise.deployment", "Deployment")}</dt>+ <dd>{t(`portal.procurement.setup.${quote.config.deployment}`)}</dd>+ </div>+ <div>+ <dt>{t("portal.procurement.builder.serviceLevel")}</dt>+ <dd>+ {SERVICE_LEVEL_LABEL[quote.config.serviceLevel]+ ? t(SERVICE_LEVEL_LABEL[quote.config.serviceLevel])+ : quote.config.serviceLevel}+ </dd>+ </div>+ </dl>+ <p className="ent__text">+ {t("portal.procurement.review.tcv", {+ years: quote.config.termYears,+ tcv: money(quote.tcvMinor, quote.currency),+ })}+ </p>+ <p className="ent__hint">+ {t("portal.procurement.review.renewal", {+ amount: money(quote.renewalAnnualNetMinor, quote.currency),+ pct: quote.cpiRatePct,+ })}+ </p>+ <div className="ent__actions">+ <Button variant="tertiary" loading={downloading} onClick={onDownload}>+ {t("portal.procurement.review.downloadCta")}+ </Button>+ {/* An accepted quote is a commitment, so its offer window no longer applies. */}+ {quote.validUntil && quote.status !== "accepted" && (+ <span className="ent__quote-valid">+ {t("portal.procurement.review.validUntil", {+ date: new Date(quote.validUntil).toLocaleDateString(undefined, {+ timeZone: "UTC",+ }),+ })}+ </span>+ )}+ </div>+ </div>+ );+}++/** A finished stage as it was left, to look back on without changing anything. */+function StageReview({+ stage,+ controller,+}: {+ stage: DealStage;+ controller: ProcurementController;+}) {+ const { t } = useTranslation();+ const { data, latest } = controller;+ if (stage === "quote") {+ return latest ? (+ <QuotePanel+ quote={latest}+ downloading={controller.downloading}+ onDownload={controller.onDownloadPdf}+ />+ ) : null;+ }+ if (!data) return null;+ const company = latest?.config.businessName || data.businessName;+ const invoiceUrl = latest?.invoiceUrl;+ const { invoicePdf } = controller;+ return (+ <div className="ent__aside">+ {stage === "trial" && (+ <>+ <span className="ent__aside-label">+ {t("portal.enterprise.review.trialTitle", "Your trial")}+ </span>+ <dl className="ent__facts">+ <div>+ <dt>{t("portal.enterprise.review.started", "Started")}</dt>+ <dd>{longDate(data.trialStartedAt)}</dd>+ </div>+ <div>+ <dt>+ {t("portal.enterprise.review.trialEnds", "Trial end date")}+ </dt>+ <dd>{longDate(data.trialEndsAt)}</dd>+ </div>+ <div>+ <dt>{t("portal.enterprise.deployment", "Deployment")}</dt>+ <dd>{t(`portal.procurement.setup.${data.deployment}`)}</dd>+ </div>+ {data.seats > 0 && (+ <div>+ <dt>{t("portal.enterprise.review.people", "People")}</dt>+ <dd>{data.seats.toLocaleString()}</dd>+ </div>+ )}+ <div>+ <dt>+ {t("portal.enterprise.review.extensions", "Extensions used")}+ </dt>+ <dd>{data.trialExtensionsUsed}</dd>+ </div>+ </dl>+ </>+ )}+ {stage === "security" && (+ <>+ <span className="ent__aside-label">+ {t("portal.procurement.documents.agreement")}+ </span>+ <dl className="ent__facts">+ {data.agreementSignedVersion && (+ <div>+ <dt>{t("portal.enterprise.review.version", "Version")}</dt>+ <dd>{data.agreementSignedVersion}</dd>+ </div>+ )}+ {company && (+ <div>+ <dt>{t("portal.enterprise.review.company", "Company")}</dt>+ <dd>{company}</dd>+ </div>+ )}+ </dl>+ {data.agreementSignedVersion && (+ <div className="ent__actions">+ <Button+ variant="tertiary"+ loading={controller.downloadingAgreement}+ onClick={controller.onDownloadSignedAgreement}+ >+ {t("portal.procurement.documents.download")}+ </Button>+ </div>+ )}+ </>+ )}+ {stage === "procurement" && (+ <>+ <span className="ent__aside-label">+ {t("portal.procurement.documents.invoice")}+ </span>+ <p className="ent__text">+ {t(+ "portal.enterprise.review.paid",+ "Paid. Your invoice stays available here.",+ )}+ </p>+ <div className="ent__actions">+ {invoiceUrl && (+ <Button variant="tertiary" onClick={() => openApiUrl(invoiceUrl)}>+ {t("portal.enterprise.review.viewInvoice", "View invoice")}+ </Button>+ )}+ {invoicePdf && (+ <Button variant="tertiary" onClick={() => openApiUrl(invoicePdf)}>+ {t("portal.procurement.payment.downloadInvoice")}+ </Button>+ )}+ </div>+ </>+ )}+ </div>+ );+}++/** The hero's call to action: the deal's next step, or that it is live. */+function HeroAction({+ controller,+ canManage,+ roleKnown,+ stage,+}: {+ controller: ProcurementController;+ canManage: boolean;+ roleKnown: boolean;+ stage: DealStage;+}) {+ const { t } = useTranslation();+ if (stage === "active") {+ return (+ <div className="ent__live">+ <Icon name="circle-check" size={22} />+ <div>+ <h2 className="ent__h3">{t("portal.procurement.live.title")}</h2>+ <p className="ent__text">+ {t("portal.procurement.live.description")}+ </p>+ </div>+ </div>+ );+ }+ if (!roleKnown) return null;+ return (+ <NextStep controller={controller} canManage={canManage} stage={stage} />+ );+}++/** What the buyer does next at this stage; a member follows along instead. */+function NextStep({+ controller,+ canManage,+ stage,+}: {+ controller: ProcurementController;+ canManage: boolean;+ stage: DealStage;+}) {+ const { t } = useTranslation();+ const { isIssued, busy, setOpen, latest, invoicePdf } = controller;+ const invoiceUrl = latest?.invoiceUrl;+ if (!canManage) {+ return (+ <p className="ent__note">+ {t(+ "portal.enterprise.memberDeal",+ "Your team leader runs this deal. You can follow its progress here.",+ )}+ </p>+ );+ }+ return (+ <div className="ent__actions">+ {stage === "trial" && (+ <Button variant="primary" size="md" onClick={() => setOpen(true)}>+ {t("portal.procurement.hero.ctaTrial")}+ </Button>+ )}+ {stage === "quote" &&+ (isIssued ? (+ <>+ <Button+ variant="primary"+ size="md"+ loading={busy}+ onClick={() => void controller.onAcceptQuote()}+ >+ {t("portal.procurement.review.acceptCta")}+ </Button>+ <Button variant="secondary" size="md" onClick={() => setOpen(true)}>+ {t("portal.procurement.hero.ctaReviewQuote")}+ </Button>+ </>+ ) : (+ <Button variant="primary" size="md" onClick={() => setOpen(true)}>+ {t("portal.procurement.hero.ctaQuote")}+ </Button>+ ))}+ {stage === "security" && (+ <Button variant="primary" size="md" onClick={() => setOpen(true)}>+ {t("portal.procurement.hero.ctaAgreement")}+ </Button>+ )}+ {stage === "procurement" && (+ <>+ {invoiceUrl && (+ <Button+ variant="primary"+ size="md"+ onClick={() => openApiUrl(invoiceUrl)}+ >+ {t("portal.procurement.payment.viewInvoice")}+ </Button>+ )}+ {invoicePdf && (+ <Button+ variant="secondary"+ size="md"+ onClick={() => openApiUrl(invoicePdf)}+ >+ {t("portal.procurement.payment.downloadInvoice")}+ </Button>+ )}+ <p className="ent__hint ent__next-hint">+ {t("portal.procurement.payment.description")}+ </p>+ </>+ )}+ </div>+ );+}++/** Where the deal stands; stages with something to open are buttons. */+function StageTracker({+ currentIdx,+ viewingIdx,+ isLive,+ actionFor,+}: {+ currentIdx: number;+ /** A finished stage open for review, marked apart from where the deal stands. */+ viewingIdx: number | null;+ isLive: boolean;+ actionFor: (index: number) => (() => void) | undefined;+}) {+ const { t } = useTranslation();+ return (+ <ol+ className="ent__stages"+ aria-label={t("portal.enterprise.stagesLabel", "Progress")}+ >+ {FLOW_JOURNEY.map((s, index) => {+ const done = index < currentIdx || (isLive && index === currentIdx);+ const action = actionFor(index);+ const content = (+ <>+ <span className="ent__stage-dot">+ {done ? <Icon name="check" size={14} /> : index + 1}+ </span>+ <span className="ent__stage-label">{t(s.label)}</span>+ </>+ );+ return (+ <li+ key={s.stage}+ className="ent__stage"+ data-state={+ done ? "done" : index === currentIdx ? "current" : "next"+ }+ data-viewing={index === viewingIdx || undefined}+ aria-current={+ index === viewingIdx+ ? "page"+ : index === currentIdx+ ? "step"+ : undefined+ }+ >+ {action ? (+ <button type="button" className="ent__stage-btn" onClick={action}>+ {content}+ </button>+ ) : (+ content+ )}+ </li>+ );+ })}+ </ol>+ );+}diff --git a/frontend/src/processor/proprietary/views/EnterpriseDemo.stories.tsx b/frontend/src/processor/proprietary/views/EnterpriseDemo.stories.tsxnew file mode 100644index 0000000000..3e82717d81--- /dev/null+++ b/frontend/src/processor/proprietary/views/EnterpriseDemo.stories.tsx@@ -0,0 +1,372 @@+import { useEffect, useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { getResponse, http, HttpResponse } from "msw";+import { BatchInterceptor } from "@mswjs/interceptors";+import { FetchInterceptor } from "@mswjs/interceptors/fetch";+import { XMLHttpRequestInterceptor } from "@mswjs/interceptors/XMLHttpRequest";+import { handlers as portalHandlers } from "@processor/mocks/handlers";+import { useQueryClient } from "@tanstack/react-query";+import { AuthContext, useAuth } from "@editor/auth/context";+import { WithOrgOwner } from "@processor/test/WithOrgOwner";+import { Enterprise } from "@processor/views/Enterprise";+import { freeWallet } from "@processor/components/billing/walletFixtures";+import { ProcurementPrefillContext } from "@processor/components/procurement/prefill";+import { AuthShell } from "@editor/auth/ui/AuthShell";+import SupabaseLoginForm from "@editor/auth/ui/SupabaseLoginForm";+import SignupForm from "@editor/routes/signup/SignupForm";+import DividerWithText from "@editor/components/shared/DividerWithText";+import { Button } from "@editor/ui/Button";+import loginHeader from "@editor/assets/brand/modern-logo/LoginLightModeHeader.svg";+import "@editor/auth/ui/auth-theme.css";+import "@editor/auth/ui/auth.css";+import {+ markProcurementSaasPaid,+ procurementSaasHandlers,+ resetProcurementSaasStore,+ seedProcurementSaasStage,+ type DemoStage,+} from "@processor/mocks/handlers/procurementSaas";++const SAAS = "http://saas.mock";+const TRIAL_DRAFT_KEY = "stirling-enterprise-trial-draft";+const MOCK_INVOICE_URL = "https://invoice.stripe.com/i/mock_procurement";++/** The buyer's answers, so the walk-through needs clicks, not typing. One seat on Stirling Cloud+ * prices far under the minimum spend, so the builder opens on its minimum check. */+const DEMO_PREFILL = {+ seats: 1,+ contactName: "Jordan Lee",+ businessName: "Northwind Logistics",+ contactEmail: "[email protected]",+ addressLine1: "500 Howard St",+ city: "San Francisco",+ region: "California",+ postalCode: "94105",+};++const STAGES: { stage: DemoStage; label: string }[] = [+ { stage: "trial", label: "Trial" },+ { stage: "quote", label: "Quote" },+ { stage: "security", label: "Agreement" },+ { stage: "procurement", label: "Payment" },+ { stage: "active", label: "Live" },+];++/**+ * The whole Enterprise journey, for walking through it end to end: the Enterprise page signed out,+ * signed in on the spot, and on through trial, quote, agreement, payment and go-live against the+ * stateful mock backend. The bar along the bottom drives the mock, and is not part of the product.+ */+function Demo({+ prefill = true,+}: {+ /** The buyer's answers filled in for a presenter; off where viewers walk it themselves. */+ prefill?: boolean;+}) {+ const auth = useAuth();+ const queryClient = useQueryClient();+ const [signedIn, setSignedIn] = useState(false);+ // Who signed in: the page resumes a trial set up before sign-in only for the account it was for.+ const [signedInEmail, setSignedInEmail] = useState<string>(+ DEMO_PREFILL.contactEmail,+ );+ // The Enterprise page sends a visitor to sign-in and back; here that screen is part of the demo.+ const [signingIn, setSigningIn] = useState(false);+ const refresh = () => void queryClient.invalidateQueries();++ // There is no Stripe behind the demo: opening the mock invoice stands in for paying it, so the+ // deal goes live in front of the audience instead of opening a dead tab.+ useEffect(() => {+ const open = window.open;+ window.open = (url, ...rest) => {+ const href = String(url ?? "");+ if (href.startsWith(MOCK_INVOICE_URL)) {+ if (!href.endsWith("/pdf")) {+ markProcurementSaasPaid();+ void queryClient.invalidateQueries();+ }+ return null;+ }+ return open.call(window, url, ...rest);+ };+ return () => {+ window.open = open;+ };+ }, [queryClient]);++ const reset = () => {+ resetProcurementSaasStore();+ try {+ window.localStorage.removeItem(TRIAL_DRAFT_KEY);+ } catch {+ // Storage unavailable: nothing was kept.+ }+ setSignedIn(false);+ setSigningIn(false);+ refresh();+ };++ return (+ <ProcurementPrefillContext.Provider value={prefill ? DEMO_PREFILL : null}>+ <AuthContext.Provider+ value={{+ ...auth,+ loading: false,+ session: signedIn+ ? (auth.session ?? ({} as unknown as typeof auth.session))+ : null,+ user: signedIn+ ? ({ ...auth.user, email: signedInEmail } as typeof auth.user)+ : null,+ }}+ >+ {signingIn ? (+ <DemoSignIn+ prefill={prefill}+ onSignedIn={(email) => {+ setSignedInEmail(email);+ setSigningIn(false);+ setSignedIn(true);+ }}+ />+ ) : (+ <Enterprise onSignIn={() => setSigningIn(true)} />+ )}+ </AuthContext.Provider>++ <div className="ent-demo-bar" role="toolbar" aria-label="Demo controls">+ <span className="ent-demo-bar__label">Demo</span>+ <button type="button" onClick={reset}>+ Reset+ </button>+ <span className="ent-demo-bar__sep" />+ <span className="ent-demo-bar__label">Skip to</span>+ {STAGES.map(({ stage, label }) => (+ <button+ key={stage}+ type="button"+ onClick={() => {+ seedProcurementSaasStage(stage);+ setSignedIn(true);+ refresh();+ }}+ >+ {label}+ </button>+ ))}+ <span className="ent-demo-bar__sep" />+ <button+ type="button"+ onClick={() => {+ markProcurementSaasPaid();+ refresh();+ }}+ >+ Mark invoice paid+ </button>+ </div>+ <style>{DEMO_BAR_CSS}</style>+ </ProcurementPrefillContext.Provider>+ );+}++/** The work email on the trial setup saved before sign-in, if any. */+function draftEmail(): string | null {+ try {+ const raw = window.localStorage.getItem(TRIAL_DRAFT_KEY);+ const saved = raw+ ? (JSON.parse(raw) as { draft?: { details?: { contactEmail?: string } } })+ : null;+ return saved?.draft?.details?.contactEmail ?? null;+ } catch {+ return null;+ }+}++// Folded to a corner tab until the presenter reaches for it, so it stays out of the product's way.+/**+ * The hosted sign-in screen, as a buyer reaches it from the Enterprise page: the product's own+ * shell and forms, with the demo buyer's details filled in. Signing in, with any provider, or+ * creating an account all succeed; the real sign-up's confirmation email is skipped.+ */+function DemoSignIn({+ prefill,+ onSignedIn,+}: {+ prefill: boolean;+ onSignedIn: (email: string) => void;+}) {+ const [creating, setCreating] = useState(false);+ const [name, setName] = useState(prefill ? DEMO_PREFILL.contactName : "");+ // The email given on the trial form, as a buyer would sign in with it: the page only resumes a+ // setup for the account it was filled in for, so a different one here would lose the answers.+ const [email, setEmail] = useState(+ () => (prefill ? DEMO_PREFILL.contactEmail : draftEmail()) ?? "",+ );+ const [password, setPassword] = useState(prefill ? "demo-password" : "");+ const [confirmPassword, setConfirmPassword] = useState(+ prefill ? "demo-password" : "",+ );+ const [submitting, setSubmitting] = useState(false);+ const signIn = async () => {+ setSubmitting(true);+ // Long enough to read as a real sign-in, short enough not to stall the demo.+ await new Promise((resolve) => setTimeout(resolve, 600));+ onSignedIn(email);+ };+ const switchLink = (label: string, onClick: () => void) => (+ <div className="ent-demo-auth__switch">+ <Button variant="tertiary" onClick={onClick}>+ {label}+ </Button>+ </div>+ );+ return (+ <AuthShell>+ {creating ? (+ <>+ <div className="auth-logo-block">+ <img+ src={loginHeader}+ alt="Stirling PDF"+ className="auth-logo-header auth-logo-header--light"+ />+ </div>+ <SignupForm+ showName+ name={name}+ setName={setName}+ email={email}+ setEmail={setEmail}+ password={password}+ setPassword={setPassword}+ confirmPassword={confirmPassword}+ setConfirmPassword={setConfirmPassword}+ onSubmit={() => void signIn()}+ isSubmitting={submitting}+ />+ <DividerWithText text="or" respondsToDarkMode={false} opacity={0.4} />+ {switchLink("Log in", () => setCreating(false))}+ </>+ ) : (+ <>+ <SupabaseLoginForm+ logoSrc={loginHeader}+ state={{+ email,+ setEmail,+ password,+ setPassword,+ error: null,+ setError: () => {},+ isSubmitting: submitting,+ providers: ["google", "github"],+ hasProviders: true,+ signInWithEmail: signIn,+ signInWithProvider: signIn,+ }}+ />+ {switchLink("Create an account", () => setCreating(true))}+ </>+ )}+ </AuthShell>+ );+}++const DEMO_BAR_CSS = `+.ent-demo-bar {+ position: fixed;+ left: 1rem;+ bottom: 1rem;+ z-index: 1000;+ display: flex;+ align-items: center;+ gap: 0.375rem;+ padding: 0.375rem 0.5rem;+ border: 1px solid var(--c-border-strong);+ border-radius: var(--radius-pill);+ background: var(--c-floating-menu-bg);+ color: var(--c-floating-menu-text);+ font: 500 0.8125rem var(--font-sans);+ white-space: nowrap;+ box-shadow: 0 0.5rem 1.5rem var(--c-overlay);+}+.ent-demo-bar:not(:hover, :has(:focus-visible)) > :not(:first-child) {+ display: none;+}+.ent-demo-auth__switch {+ margin-top: 1rem;+ text-align: center;+}+.ent-demo-bar__label {+ padding: 0 0.375rem;+}+.ent-demo-bar__sep {+ width: 1px;+ height: 1.25rem;+ background: currentColor;+ opacity: 0.25;+}+.ent-demo-bar button {+ padding: 0.25rem 0.625rem;+ border: 0;+ border-radius: var(--radius-pill);+ background: none;+ color: inherit;+ font: inherit;+ cursor: pointer;+}+.ent-demo-bar button:hover,+.ent-demo-bar button:focus-visible {+ background: color-mix(in srgb, currentColor 15%, transparent);+ outline: none;+}+`;++const DEMO_HANDLERS = [+ // Stateful first, so the deal moves as the buyer acts on it.+ ...procurementSaasHandlers,+ http.post(`${SAAS}/api/v1/payg/wallet/refresh`, () => HttpResponse.json({})),+ http.get(`${SAAS}/api/v1/payg/wallet`, () =>+ HttpResponse.json({ ...freeWallet, role: "leader" }),+ ),+ http.get("/api/v1/config/app-config", () =>+ HttpResponse.json({ accountLinkAvailable: true }),+ ),+];++/**+ * Answers the demo's requests inside the page. The mock service worker only serves a page it+ * controls, and a first visit or a hard refresh leaves the page uncontrolled, sending every+ * request to the real network mid-presentation; patching fetch and XHR here has no such gap.+ */+function interceptInPage(): () => void {+ const handlers = [...DEMO_HANDLERS, ...portalHandlers];+ const interceptor = new BatchInterceptor({+ name: "enterprise-demo",+ interceptors: [new FetchInterceptor(), new XMLHttpRequestInterceptor()],+ });+ interceptor.on("request", async ({ request, controller }) => {+ const response = await getResponse(handlers, request);+ if (response) controller.respondWith(response);+ });+ interceptor.apply();+ return () => interceptor.dispose();+}++const meta: Meta<typeof Demo> = {+ title: "Portal/Procurement/Enterprise demo",+ component: Demo,+ parameters: {+ layout: "fullscreen",+ msw: { handlers: DEMO_HANDLERS },+ },+ decorators: [WithOrgOwner],+ beforeEach: () => {+ resetProcurementSaasStore();+ return interceptInPage();+ },+};+export default meta;++export const FullJourney: StoryObj<typeof Demo> = {};diff --git a/frontend/src/processor/proprietary/views/Home.tsx b/frontend/src/processor/proprietary/views/Home.tsxindex f44672661f..820da95e0d 100644--- a/frontend/src/processor/proprietary/views/Home.tsx+++ b/frontend/src/processor/proprietary/views/Home.tsx@@ -16,8 +16,6 @@ export function Home() {{/* Paid tiers open with a greeting; free opens with local deployment status. */}{tier !== "free" && <HomeGreeting />}- {/* Per-tier hero. Its footer is the deal-status hero while a procurement- deal is underway (a bolt-on to any tier), otherwise the setup checklist. */}<HomeHero /><ProcessorFlow /></div>diff --git a/frontend/src/processor/proprietary/views/Procurement.css b/frontend/src/processor/proprietary/views/Procurement.cssindex 94a19257f8..be0a2a8311 100644--- a/frontend/src/processor/proprietary/views/Procurement.css+++ b/frontend/src/processor/proprietary/views/Procurement.css@@ -95,6 +95,12 @@.portal-qb__field[data-invalid] select {border-color: var(--c-danger);}+.portal-qb__field-error {+ display: block;+ margin-top: 6px;+ font-size: 12px;+ color: var(--color-red-dark);+}.portal-qb__error {margin: 10px 0 0;font-size: 12px;@@ -193,7 +199,7 @@}.portal-qb__addon {display: flex;- align-items: flex-start;+ align-items: center;gap: 11px;padding: 11px 13px;border-radius: 9px;@@ -211,7 +217,7 @@height: 18px;flex-shrink: 0;border-radius: 5px;- border: 1px solid var(--c-border);+ border: 1.5px solid var(--c-border-strong);display: flex;align-items: center;justify-content: center;@@ -262,10 +268,42 @@border-top: 1px solid var(--c-border-subtle);flex-wrap: wrap;}+.portal-qb__running-label {+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--c-text-muted);+}.portal-qb__running {+ font-size: 20px;+ font-weight: 700;+ line-height: 1.2;+ font-variant-numeric: tabular-nums;+ color: var(--c-text);+}+.portal-qb__running-total {+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: var(--c-text-muted);+}+.portal-qb__totals {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.portal-qb__minimum {font-size: 11.5px;color: var(--c-text-subtle);}+.portal-qb__minimum-callout {+ margin-top: 1rem;+}+.portal-qb__minimum-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+}.portal-qb__foot-btns {display: flex;gap: 10px;@@ -278,6 +316,10 @@padding: 14px var(--flowmodal-inset);margin: 0 calc(-1 * var(--flowmodal-inset));}+/* Runs straight into the footer: a strip of panel between the two read as a stray divider. */+.portal-qb__body:has(> .portal-qb__papertray:last-child) + .portal-qb__foot {+ margin-top: 0;+}.portal-qb__paper {overflow: hidden;}@@ -337,6 +379,12 @@font-weight: 600;color: var(--c-text);}+.portal-qb__line-note {+ margin-right: 8px;+ font-size: 11.5px;+ font-weight: 500;+ color: var(--c-text-subtle);+}.portal-qb__lines li[data-kind="DISCOUNT"] {color: var(--color-green-dark);}@@ -466,32 +514,6 @@gap: 0.75rem;flex-wrap: wrap;}-.portal-hero__icons {- display: flex;- align-items: center;- gap: 0.5rem;-}-.portal-hero__iconbtn {- width: 34px;- height: 34px;- display: inline-flex;- align-items: center;- justify-content: center;- border-radius: 9px;- border: 1px solid var(--c-border);- background: var(--c-surface);- color: var(--c-text-muted);- cursor: pointer;- transition:- background 0.15s ease,- border-color 0.15s ease,- color 0.15s ease;-}-.portal-hero__iconbtn:hover {- background: var(--c-hover);- border-color: var(--c-border-strong);- color: var(--c-text);-}/* Terminal state: the deal is done, so the row reports rather than asks. */.portal-hero__live {display: flex;@@ -576,22 +598,6 @@color: var(--c-text-subtle, var(--c-text-muted));}-/* Hero next-step action row (primary CTA + optional extend-trial). */-/* Hero quick-action chips (the trial countdown pill under the stage sentence). */-.portal-hero__chip--action {- border: 1px solid var(--c-border);- cursor: pointer;- transition:- background 0.12s,- border-color 0.12s,- transform 0.12s;-}-.portal-hero__chip--action:hover {- background: var(--c-surface);- border-color: var(--c-border-strong);- transform: translateY(-1px);-}-/* ── Side dialogs (Key documents / Schedule a call / Trial) ───────────────── *//* Chrome and width come from the shared Modal via FlowModal; only type and content live here. */.portal-sidemodal__title {@@ -648,18 +654,6 @@}/* ── Agreement (security) step ────────────────────────────────────────────── */-/* The terminal steps (payment, live): a stacked eyebrow/title/description with the flow's own footer- bar beneath. No card of their own — the dialog is already the surface. */-.portal-procstage {- display: flex;- flex-direction: column;- gap: 0.4rem;-}-/* Nothing to report on the left of these, so the actions take the whole bar. */-.portal-procstage__foot {- justify-content: flex-end;-}-/* The two document actions read as a pair, close together and set apart from the close beside them. */.portal-agreement__actions {display: flex;@@ -685,21 +679,18 @@column taller than the fields and drag the button back up off the row. */.portal-agreement__signrow {display: flex;- align-items: flex-end;+ align-items: flex-start;gap: 0.9rem;}-/* Consent on the left, the gate's state on the right so it lands under the button it explains. */+/* Level with the inputs rather than the bottom of the row, which field errors would push down: the+ fields' top margin and label height, plus the difference between input and button heights. */+.portal-agreement__signrow > .sui-btn {+ margin-top: calc(0.75rem + 1.5375rem + 0.6406rem);+}.portal-agreement__signfoot {display: flex;+ flex-direction: column;align-items: flex-start;- justify-content: space-between;- gap: 1rem;-}-.portal-agreement__gate {- flex: 0 0 auto;- font-size: 0.6875rem;- color: var(--c-text-subtle);- white-space: nowrap;}.portal-agreement__signrow .portal-agreement__signfields {flex: 1;@@ -719,6 +710,12 @@color: var(--c-text-subtle);cursor: pointer;}+.portal-qb__eula[data-invalid] {+ border-color: var(--c-danger);+}+.portal-agreement__accept[data-invalid] {+ color: var(--color-red-dark);+}.portal-agreement__accept input {margin: 0.1rem 0 0;flex: 0 0 auto;@@ -741,40 +738,13 @@window: flush to the footer while there is more to read, and revealing the tray's bottom paddingonly at the end. Scrolling the paper instead left a permanent grey band under it, which read as abox with contents rather than a document. */-/* `scroll`, not `auto`, and an explicitly styled bar: signing is gated on reaching the end of the- document, so the buyer has to be able to see there is more of it and how far through they are.- Overlay scrollbars fade out when idle, which hid both. Styling the bar also opts Chromium out of- overlay behaviour, so it stays put. Matches the treatment on the files page. */.portal-agreement__tray {background: var(--c-surface-sunken);padding: 14px var(--flowmodal-inset);margin: 0 calc(-1 * var(--flowmodal-inset));- flex: 1 1 auto;- min-height: 0;- overflow-y: scroll;- scrollbar-width: thin;- scrollbar-color: var(--c-text-subtle) var(--c-border-subtle);-}-.portal-agreement__tray::-webkit-scrollbar {- width: 0.625rem;-}-.portal-agreement__tray::-webkit-scrollbar-track {- background: var(--c-border-subtle);- border-radius: 999px;-}-.portal-agreement__tray::-webkit-scrollbar-thumb {- background: var(--c-text-subtle);- border-radius: 999px;- border: 2px solid transparent;- background-clip: content-box;-}-.portal-agreement__tray::-webkit-scrollbar-thumb:hover {- background: var(--c-text-muted);- background-clip: content-box;}.portal-agreement__doc {- /* A floor so a short document still reads as a page; no ceiling, so a long one runs on and the tray- does the scrolling. */+ /* A floor so a short document still reads as a page; no ceiling, so a long one runs on. */min-height: 16rem;padding: 1.35rem 1.6rem;/* No serif token exists in the theme — the serif is specific to rendering legal terms as paper. */@@ -939,6 +909,25 @@color: var(--c-text-subtle);white-space: nowrap;}+/* Paperwork the deal has yet to produce: listed so buyers know it's coming, set back from what's ready. */+.portal-docmodal__group {+ margin: 1.25rem 0 0;+ padding-top: 1rem;+ border-top: 1px solid var(--c-border);+ font-size: 0.75rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--c-text-subtle);+}+.portal-docmodal--later .portal-docmodal__row {+ padding: 0.5rem 0;+ border-bottom: none;+}+.portal-docmodal--later .portal-docmodal__name {+ font-weight: 500;+ color: var(--c-text-muted);+}/* Title row: the step badge rides beside the heading, not on a line of its own. */.portal-sidemodal__title-row {@@ -953,3 +942,23 @@font-size: 0.75rem;color: var(--c-text-subtle);}++.portal-setup {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-setup__foot {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: flex-end;+ gap: 0.75rem;+ padding-top: 1rem;+ border-top: 1px solid var(--c-border-subtle);+}++.portal-setup__foot .portal-sidemodal__foot-hint {+ margin-right: auto;+}diff --git a/frontend/src/processor/proprietary/views/Usage.test.tsx b/frontend/src/processor/proprietary/views/Usage.test.tsxindex c61e103a08..d3ae100cc9 100644--- a/frontend/src/processor/proprietary/views/Usage.test.tsx+++ b/frontend/src/processor/proprietary/views/Usage.test.tsx@@ -97,31 +97,25 @@ vi.mock("@editor/portal/hooks/useBundleFlowState", () => ({useBundleFlowState: () => bundleFlow,}));const procurement = {- isLinked: true,- loading: false,- loadError: null as string | null,- error: null,- open: false,- started: false,- stage: null as ProcurementSnapshot["stage"],- retry: vi.fn(),- onExploreEnterprise: vi.fn(),- onStartTrial: vi.fn(),- setOpen: vi.fn(),+ deal: null as Pick<ProcurementSnapshot, "dealId" | "stage"> | null,+ error: null as Error | null,+ refetch: vi.fn(),};vi.mock("@editor/portal/components/procurement/useProcurement", () => ({- useProcurement: () => procurement,+ useProcurementSnapshot: () => ({+ data: procurement.error ? undefined : procurement.deal,+ error: procurement.error,+ isSuccess: !procurement.error,+ refetch: procurement.refetch,+ }),}));-vi.mock("@editor/portal/components/procurement/ProcurementBanner", () => ({- ControlledDealStatusHero: ({ readOnly }: { readOnly: boolean }) => (+vi.mock("@editor/portal/components/procurement/DealStatusHero", () => ({+ DealStatusHero: ({ onOpen }: { onOpen?: () => void }) => (<div data-testid="procurement-summary">- {readOnly ? "Read-only deal" : "Enterprise deal"}+ {onOpen ? "Enterprise deal" : "Read-only deal"}</div>),}));-vi.mock("@editor/portal/components/procurement/ProcurementFlow", () => ({- ProcurementFlow: () => <div data-testid="procurement-flow" />,-}));vi.mock("@editor/portal/api/fleetStats", () => ({fetchFleetStats: () => Promise.resolve(null),}));@@ -217,13 +211,9 @@ describe("Usage — link-free wallet renderer", () => {bundleFlow.refresh.mockReset();fetchWallet.mockReset();refreshWalletCache.mockReset();- procurement.loading = false;- procurement.loadError = null;- procurement.started = false;- procurement.stage = null;- procurement.onExploreEnterprise.mockReset();- procurement.onStartTrial.mockReset();- procurement.setOpen.mockReset();+ procurement.deal = null;+ procurement.error = null;+ procurement.refetch.mockReset();});it("opens Team once for an over-capacity server and includes the actual allowance", async () => {@@ -627,81 +617,61 @@ describe("Usage — link-free wallet renderer", () => {expect(document.getElementById("ub-plan")).toBeNull();});- it("starts procurement from the billing CTA without leaving Usage", async () => {+ it("opens the Enterprise page from the billing CTA", async () => {fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });renderUsage(<Usage />);fireEvent.click(await screen.findByRole("button", { name: "Get an enterprise quote" }),);- expect(procurement.onExploreEnterprise).toHaveBeenCalledTimes(1);- expect(screen.getByTestId("location")).toHaveTextContent(- "/settings/billing",- );+ expect(screen.getByTestId("location")).toHaveTextContent("/enterprise");});- it.each([- [null, "onExploreEnterprise"],- ["exploring", "onStartTrial"],- ["trial", "setOpen"],- ["quote", "setOpen"],- ["security", "setOpen"],- ["procurement", "setOpen"],- ["active", "setOpen"],- ] as const)("resumes %s once from a sales link", async (stage, action) => {- procurement.stage = stage;- procurement.started = stage !== null;+ it("still offers the quote to a buyer who asked but never started a trial", async () => {+ procurement.deal = { dealId: 1, stage: "exploring" };fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });- renderUsage(<Usage />, "/settings/billing?procurement=start&source=sales");- await waitFor(() => expect(procurement[action]).toHaveBeenCalledTimes(1));- await waitFor(() =>- expect(screen.getByTestId("location")).toHaveTextContent(- "/settings/billing?source=sales",- ),- );- if (stage) expect(procurement.onExploreEnterprise).not.toHaveBeenCalled();+ renderUsage(<Usage />);+ expect(+ await screen.findByRole("button", { name: "Get an enterprise quote" }),+ ).toBeInTheDocument();+ expect(screen.queryByTestId("procurement-summary")).not.toBeInTheDocument();});- it("keeps a failed snapshot's start request pending instead of creating another deal", async () => {- procurement.loadError = "Snapshot unavailable";+ it("does not offer a new deal while the existing one cannot be loaded", async () => {+ procurement.error = new Error("Snapshot unavailable");fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });- renderUsage(<Usage />, "/settings/billing?procurement=start");+ renderUsage(<Usage />);await screen.findByText("The full PDF Editor.");expect(screen.getByText("Snapshot unavailable")).toBeInTheDocument();- expect(procurement.onExploreEnterprise).not.toHaveBeenCalled();- expect(screen.getByTestId("location")).toHaveTextContent(- "procurement=start",- );expect(screen.queryByRole("button", { name: "Get an enterprise quote" }),).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));+ expect(procurement.refetch).toHaveBeenCalledTimes(1);});it("anchors an existing deal before Plan", async () => {- procurement.started = true;- procurement.stage = "trial";+ procurement.deal = { dealId: 1, stage: "trial" };fetchWallet.mockResolvedValue({ ...walletOf("free"), role: "leader" });renderUsage(<Usage />);await screen.findByText("The full PDF Editor.");const section = screen.getByRole("region", { name: "Procurement" });expect(section.nextElementSibling?.id).toBe("ub-plan");+ expect(screen.getByText("Enterprise deal")).toBeInTheDocument();expect(screen.queryByRole("button", { name: "Get an enterprise quote" }),).not.toBeInTheDocument();});- it("shows members the deal without starting or mounting its mutation dialogs", async () => {- procurement.started = true;- procurement.stage = "trial";+ it("shows members the deal with no way into it", async () => {+ procurement.deal = { dealId: 1, stage: "trial" };fetchWallet.mockResolvedValue(walletOf("free"));- renderUsage(<Usage />, "/settings/billing?procurement=start");+ renderUsage(<Usage />);await screen.findByText("The full PDF Editor.");expect(screen.getByText("Read-only deal")).toBeInTheDocument();- expect(screen.queryByTestId("procurement-flow")).not.toBeInTheDocument();- expect(procurement.setOpen).not.toHaveBeenCalled();});it("keeps the deal visible if the wallet fails", async () => {- procurement.started = true;+ procurement.deal = { dealId: 1, stage: "trial" };fetchWallet.mockRejectedValue(new Error("Wallet unavailable"));renderUsage(<Usage />);await screen.findByText("Wallet unavailable");@@ -835,8 +805,7 @@ describe("Usage — refresh cost", () => {refreshWalletCache.mockReset().mockResolvedValue(undefined);fetchLocalUsage.mockReset().mockResolvedValue(null);bundleFlow.status = "none";- procurement.loading = false;- procurement.loadError = null;+ procurement.deal = null;vi.useFakeTimers({ shouldAdvanceTime: true });});diff --git a/frontend/src/processor/proprietary/views/Usage.tsx b/frontend/src/processor/proprietary/views/Usage.tsxindex 50527dd912..ba55425875 100644--- a/frontend/src/processor/proprietary/views/Usage.tsx+++ b/frontend/src/processor/proprietary/views/Usage.tsx@@ -17,10 +17,9 @@ import { Banner, Button } from "@editor/ui";import { BillingScreen, KvRow, formatPeriodDate } from "@editor/billing";import { useLegacySubscriptions } from "@editor/hooks/useLegacySubscriptions";import { LegacySubscriptionPlan } from "@editor/components/shared/config/LegacySubscriptionPlan";-import { useUI } from "@editor/portal/contexts/UIContext";-import { useProcurement } from "@editor/portal/components/procurement/useProcurement";-import { ControlledDealStatusHero } from "@editor/portal/components/procurement/ProcurementBanner";-import { ProcurementFlow } from "@editor/portal/components/procurement/ProcurementFlow";+import { useProcurementSnapshot } from "@processor/components/procurement/useProcurement";+import { DealStatusHero } from "@processor/components/procurement/DealStatusHero";+import { useOpenEnterprise } from "@processor/components/procurement/enterprisePath";import {fetchWallet,refreshWalletCache,@@ -112,51 +111,22 @@ export function Usage({previousSessionRevision.current = sessionRevision;refresh();}, [sessionRevision, refresh]);- const procurement = useProcurement();- const { trialSetupRequested, clearTrialSetupRequest } = useUI();+ const dealQuery = useProcurementSnapshot();+ const deal = dealQuery.data;+ // Session failures surface through the session banner; anything else is shown here, since an+ // unknown deal must not be read as "no deal" and offered a fresh start.+ const dealError =+ dealQuery.error && !(dealQuery.error instanceof SaasSessionRequiredError)+ ? dealQuery.error.message+ : null;+ const openEnterprise = useOpenEnterprise();const [searchParams, setSearchParams] = useSearchParams();- const handledProcurementRequest = useRef(false);- const canManageProcurement = wallet?.role === "leader";+ const isLeader = wallet?.role === "leader";const bundleFlow = useBundleFlowState(wallet?.teamId,- canManageProcurement && wallet?.status === "free",+ isLeader && wallet?.status === "free",);- useEffect(() => {- const requested =- trialSetupRequested || searchParams.get("procurement") === "start";- if (!requested) {- handledProcurementRequest.current = false;- return;- }- if (- handledProcurementRequest.current ||- !wallet ||- !procurement.isLinked ||- procurement.loading ||- procurement.loadError- )- return;- handledProcurementRequest.current = true;- clearTrialSetupRequest();- if (searchParams.get("procurement") === "start") {- const next = new URLSearchParams(searchParams);- next.delete("procurement");- setSearchParams(next, { replace: true });- }- if (!canManageProcurement) return;- if (!procurement.started) procurement.onExploreEnterprise();- else if (procurement.stage === "exploring") procurement.onStartTrial();- else procurement.setOpen(true);- }, [- trialSetupRequested,- searchParams,- setSearchParams,- wallet,- procurement,- canManageProcurement,- clearTrialSetupRequest,- ]);// Locally-accrued usage SaaS hasn't billed yet; added to the synced figure so// "current usage" reflects work since the last daily sync. Best-effort.const hasLocalInstance = localUsersInUse !== undefined;@@ -169,22 +139,6 @@ export function Usage({staleTime: WALLET_POLL_MS,retry: false,});- const previousDeal = useRef(procurement.data);- useEffect(() => {- const previous = previousDeal.current;- previousDeal.current = procurement.data;- if (!previous || previous === procurement.data) return;- // A trial or agreement can change entitlements while the buyer stays on this page.- let cancelled = false;- void refreshWalletCache()- .catch(() => {})- .then(() => {- if (!cancelled) refresh();- });- return () => {- cancelled = true;- };- }, [procurement.data, refresh]);// 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;@@ -442,26 +396,17 @@ export function Usage({{wallet?.team?.held && wallet.role === "leader" && (<TeamSubscriptionChange refreshKey={walletReadAt} />)}- {procurement.loadError && (+ {dealError && (<Bannertone="danger"title={t("portal.procurement.error.title")}action={- <Button size="sm" onClick={procurement.retry}>+ <Button size="sm" onClick={() => void dealQuery.refetch()}>{t("portal.accountLink.gate.retry", "Try again")}</Button>}>- {procurement.loadError}- </Banner>- )}- {procurement.error && !procurement.open && (- <Banner- tone="danger"- title={t("portal.procurement.error.title")}- onDismiss={() => procurement.setError(null)}- >- {procurement.error}+ {dealError}</Banner>)}{sessionRecovery}@@ -535,20 +480,18 @@ export function Usage({: undefined}procurementSection={- procurement.isLinked && procurement.started ? (- <ControlledDealStatusHero- controller={procurement}- readOnly={!canManageProcurement}+ deal?.dealId != null && deal.stage !== "exploring" ? (+ <DealStatusHero+ snapshot={deal}+ onOpen={isLeader ? openEnterprise : undefined}/>) : undefined}onEnterpriseQuote={- canManageProcurement &&- procurement.isLinked &&- !procurement.loading &&- !procurement.loadError &&- !procurement.started- ? procurement.onExploreEnterprise+ isLeader &&+ dealQuery.isSuccess &&+ (deal?.dealId == null || deal.stage === "exploring")+ ? openEnterprise: undefined}paymentSection={@@ -596,7 +539,6 @@ export function Usage({}extras={<>- {canManageProcurement && <ProcurementFlow controller={procurement} />}{!enterpriseProcessor && wallet && wallet.status === "free" && (<FreePlanViewwallet={wallet}diff --git a/frontend/src/processor/saas/auth/EnterpriseAuthBoundary.tsx b/frontend/src/processor/saas/auth/EnterpriseAuthBoundary.tsxnew file mode 100644index 0000000000..65ca7f0a6b--- /dev/null+++ b/frontend/src/processor/saas/auth/EnterpriseAuthBoundary.tsx@@ -0,0 +1,14 @@+import { type ReactNode } from "react";+import { AuthProvider } from "@editor/auth";+import { ensureSaasSupabase } from "@processor/auth/saasSupabase";++/**+ * The hosted Enterprise page is where the website sends buyers, most of whom have no account yet,+ * so it is open to everyone: the page asks for sign-in only when the visitor starts something that+ * needs one. Same provider as the portal boundary, without its gate; the SaaS session provider is+ * already mounted by the platform above.+ */+export function EnterpriseAuthBoundary({ children }: { children: ReactNode }) {+ ensureSaasSupabase();+ return <AuthProvider mode="supabase">{children}</AuthProvider>;+}diff --git a/frontend/src/processor/saas/components/billing/PortalBillingGate.tsx b/frontend/src/processor/saas/components/billing/PortalBillingGate.tsxindex 5c651c6478..748e39f26c 100644--- a/frontend/src/processor/saas/components/billing/PortalBillingGate.tsx+++ b/frontend/src/processor/saas/components/billing/PortalBillingGate.tsx@@ -1,6 +1,10 @@+import { Navigate, useLocation } from "react-router-dom";import { Usage } from "@editor/portal/views/Usage";+import { legacyProcurementTarget } from "@processor/components/procurement/enterprisePath";/** Hosted billing uses app authentication and never offers instance-link renewal. */export function PortalBillingGate() {+ const procurementTarget = legacyProcurementTarget(useLocation().search);+ if (procurementTarget) return <Navigate to={procurementTarget} replace />;return <Usage />;}