From d0d197f09f84a5609aa8191dc08187f4c873b12d Mon Sep 17 00:00:00 2001 From: ConnorYoh <40631091+ConnorYoh@users.noreply.github.com> Date: Wed, 5 Aug 2026 16:23:50 +0100 Subject: [PATCH] Procurement: draft Enterprise Agreement + signature, legal pages & consent, quote/agreement split (#7021) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Consolidates the enterprise procurement and legal work into one PR off `main`. Supersedes #7020 (closed; every commit from it is contained here). Sits on top of PAYG prepaid bundles (#7032) and the `--color-*` → `--c-*` portal token rename. ## Why Enterprise procurement was a mock. The stage screens read from a fake state machine, the "agreement" was prose hardcoded in a component, and nothing a buyer did was recorded anywhere. To actually sell to an enterprise we need three things it didn't have: a real document they can read and sign, a record that proves they signed that exact version, and a licence that flips when they pay. ## What **The agreement is a real versioned document** - Registry at `resources/legal/manifest.json` + `legal///*.md`. Publishing a new version is a markdown file and a manifest bump, no code change. `@`-prefixed parts are generated sections. - `AgreementAssembler` builds MSA (Part A) + generated Order Form (Part B) + DPA (Part C) as one document. Only the Order Form varies per deal. - `AgreementPdfRenderer` goes through our own pipeline (commonmark → `FileToPdf`/WeasyPrint), so we dogfood it. - Immutable signature record pinning document id and version, a SHA-256 of the exact rendered markdown, the variable snapshot, typed signatory details, timestamp and IP. **Legal document pages and consent logging** - `GET /api/v1/legal/{docId}` serves any registry document; a viewer modal renders it with a draft badge. The SLA exhibit is viewable for the first time. - `legal_consent` + `POST /api/v1/legal/consent`. EULA clickwrap is recorded once: at trial start, or at the quote step only if there was no trial. **Quote and Agreement are separate steps** The quote step is a plain itemised review (figures, renewal, PO) with download and "Accept quote". Accepting advances to the agreement and does not charge Stripe. Signing the agreement is still the commitment point. **One quote number** We no longer mint our own reference. The Stripe quote number is the identifier everywhere, so the UI and the memo can't disagree. `quote_number` is nullable until Stripe assigns it at finalisation (`20260808000000`). **Payment takes the deal live** `invoice.paid` on the stripe-webhook moves the deal to live and the UI reflects it. Nothing watched for payment before, so a paid customer sat in "payment" forever. Needs `invoice.paid` enabled on the webhook endpoint in the Stripe dashboard. **Security** Any signup could self-issue a $0 enterprise licence, from three things compounding: leader-on-signup, no entitlement gate, and no ACV floor. So: `startTrial` now has a stage guard (it was replacing committed licences), the offline `.lic` is gated on entitlement, the ACV floor is enforced before the quote persists, and the air-gap check reads the quote's deployment rather than the deal's. Invitee emails are redacted in logs. Dev and Storybook were hitting real Stripe; both now route through `resolveDemoResponse`. **Removed the dead procurement island** The original stage-by-stage page survived the rebuild with no route and no consumer, so it was invisible to review but still cost a reader's time. 16 unreferenced files, 182 lines of superseded API, 53 orphaned en-US keys, and `Procurement.css` from 1665 to 968 lines. Nothing deleted had a live consumer. ## Screenshots Home, deal underway (hero card footer): Quote builder, step 1: Agreement, ready to sign: Payment and live: ## How to test **Storybook** covers every state without a backend: ```bash cd frontend && npm run storybook ``` Then `Portal/Procurement/*`: | Story | What to look at | | --- | --- | | `DealStatusHero` — Trial / Quote / Agreement / Payment / Live | One hero per stage: progress band, one-line status, stage CTA | | `QuoteBuilder` — Default | 4 steps. Users + volume drive the price; Governance and PDF size are multipliers; step 4 is the itemised review | | `ProcurementAgreement` — Default / Signing | Header actions, always-visible scrollbar on the paper, one-line signature row | | `ProcurementStages` — Payment / Live / License | "View & pay invoice" opens Stripe directly; licence key and `.lic` download | | `Views/Home` — Subscribed In Procurement | The hero in real page context | Note: `ProcurementAgreement` renders "Could not load the agreement" in Storybook because it fetches the document from the backend. The chrome is accurate, the paper body needs the app. **Full flow** needs SaaS running and a linked team: 1. Home → **Explore enterprise** → trial setup (deployment + seats). EULA is recorded here. 2. **Build your quote** → 4 steps → Generate. Buyer details are required first. 3. Review the itemised quote → **Accept quote**. Confirm Stripe was *not* charged. 4. Agreement → tick, fill signatory, **Sign agreement**. Check `procurement_signature` for the version and content hash. 5. **View & pay invoice** → pay in Stripe test mode → deal should move to live on the `invoice.paid` webhook. Worth reviewing specifically: the licence cannot be issued without entitlement (step 3 before payment), and `startTrial` on an already-committed deal is rejected rather than overwriting. ## Verification - `:saas compileJava` + `spotlessJavaCheck` - `task frontend:check:all` green end to end: 9 typecheck variants, eslint at zero warnings, `theme-lint`, `lint:css`, prettier, build, **1656 tests across 188 files** - 7 deno tests on the `invoice.paid` handler, covering all four shapes Stripe uses for the subscription reference ## Open, not addressed here - **The commercial model contradicts itself in three places.** The Order Form says annual-in-advance, the MSA §2.3/§3.2 implies otherwise, the quote engine computes `tcv = annualNet × termYears` flat, and Stripe only invoices one year. Needs a decision before this is customer-facing. - The 25 MB data-processing increments vs the ×1.4/×2.4 size multiplier, deferred pending Matt. - All legal text is **draft**. It renders with a draft badge and is not presented as executed; counsel's read is still a publish gate. - `{{subprocessor_url}}` / `{{eula_url}}` awaiting marketing's final links. - `frontend-a11y` is red on pre-existing portal contrast debt, deferred by decision. ## Schema notes Two migrations land on the SaaS side (`v3`), both applied by that repo's PR CI: - `20260808000000` drops the NOT NULL on `procurement_quote.quote_number`, which is required rather than cosmetic — the number now comes from Stripe at finalisation, so a draft holds NULL, and `ddl-auto` cannot drop an existing NOT NULL itself. - `20260809000000` adds `procurement_deal.last_paid_invoice_id`, nullable. Nothing here needs a migration in this repo: Flyway is not on the classpath, so the Java side only ever adds via `ddl-auto`, and Postgres migrations run ahead of the app deploy. --- app/saas/build.gradle | 5 + .../software/saas/config/SaasJpaConfig.java | 6 +- .../software/saas/legal/LegalConsent.java | 62 + .../saas/legal/LegalConsentRepository.java | 5 + .../saas/legal/LegalConsentService.java | 47 + .../software/saas/legal/LegalController.java | 133 ++ .../saas/legal/LegalDocumentMeta.java | 27 + .../saas/legal/LegalDocumentRegistry.java | 151 ++ .../saas/payg/bundle/PrepaidBundle.java | 15 +- .../api/ProcurementController.java | 247 ++- .../ProcurementConfigurationProperties.java | 13 + .../procurement/legal/AgreementAssembler.java | 278 ++++ .../legal/AgreementPdfRenderer.java | 71 + .../procurement/legal/AgreementSigning.java | 12 + .../procurement/legal/AssembledAgreement.java | 16 + .../model/ProcurementAgreementSignature.java | 86 + .../procurement/model/ProcurementDeal.java | 33 + .../procurement/model/ProcurementQuote.java | 6 +- .../pricing/ProcurementPricingService.java | 49 +- ...ocurementAgreementSignatureRepository.java | 29 + .../service/ProcurementService.java | 390 ++++- .../legal/enterprise-agreement/0.9.1/dpa.md | 53 + .../legal/enterprise-agreement/0.9.1/msa.md | 119 ++ .../main/resources/legal/eula/1.0.0/eula.md | 75 + .../src/main/resources/legal/manifest.json | 38 + .../src/main/resources/legal/sla/1.0.0/sla.md | 37 + .../subprocessors/1.0.0/subprocessors.md | 19 + .../ProcurementTrialRestartPolicyTest.java | 44 + frontend/.storybook/a11y-baseline.json | 22 +- .../public/locales/en-US/translation.toml | 241 ++- frontend/editor/src/portal/ViewRouter.tsx | 2 - .../editor/src/portal/api/externalUrl.test.ts | 51 + frontend/editor/src/portal/api/externalUrl.ts | 25 + frontend/editor/src/portal/api/procurement.ts | 369 ++--- .../portal/components/EditorStatusCard.css | 99 +- .../components/EditorStatusCard.stories.tsx | 30 +- .../portal/components/EditorStatusCard.tsx | 179 +-- .../portal/components/HomeHero.stories.tsx | 21 +- .../editor/src/portal/components/HomeHero.tsx | 72 +- .../src/portal/components/SetupChecklist.css | 122 -- .../components/SetupChecklist.stories.tsx | 66 - .../src/portal/components/SetupChecklist.tsx | 150 -- .../src/portal/components/WelcomeBanner.css | 103 -- .../components/WelcomeBanner.stories.tsx | 41 - .../src/portal/components/WelcomeBanner.tsx | 97 -- .../billing/BundleCheckoutModal.tsx | 4 +- .../components/billing/EnterpriseUpsell.tsx | 13 +- .../components/billing/FreePlanView.tsx | 1 - .../components/billing/LinkAccountPrompt.tsx | 6 +- .../components/billing/PrepayModalHeader.tsx | 100 +- .../components/billing/SpendLimitCard.tsx | 2 +- .../billing/StripeCheckoutModal.tsx | 1 - .../src/portal/components/billing/billing.css | 53 - .../editor/src/portal/components/icons.tsx | 29 + .../procurement/ActionModal.stories.tsx | 51 - .../components/procurement/ActionModal.tsx | 166 -- .../procurement/DealJourney.stories.tsx | 30 - .../components/procurement/DealJourney.tsx | 99 -- .../procurement/DealStatusHero.stories.tsx | 6 +- .../components/procurement/DealStatusHero.tsx | 311 ++-- .../components/procurement/DocRow.stories.tsx | 62 - .../portal/components/procurement/DocRow.tsx | 89 -- .../procurement/DocumentLedger.stories.tsx | 30 - .../components/procurement/DocumentLedger.tsx | 160 -- .../procurement/LockedState.stories.tsx | 18 - .../components/procurement/LockedState.tsx | 36 - .../ProcurementAgreement.stories.tsx | 14 +- .../procurement/ProcurementAgreement.tsx | 369 +++-- .../procurement/ProcurementBanner.stories.tsx | 79 - .../procurement/ProcurementBanner.tsx | 65 +- .../procurement/ProcurementExtras.stories.tsx | 7 +- .../procurement/ProcurementExtras.tsx | 542 +++++-- .../procurement/ProcurementFlow.stories.tsx | 10 +- .../procurement/ProcurementFlow.tsx | 110 +- .../procurement/ProcurementHome.stories.tsx | 18 - .../procurement/ProcurementHome.tsx | 22 - .../procurement/ProcurementModal.stories.tsx | 4 +- .../procurement/ProcurementModal.tsx | 115 +- .../procurement/ProcurementStages.tsx | 102 +- .../components/procurement/QuoteBuilder.tsx | 377 ++++- .../procurement/StageStepper.stories.tsx | 20 - .../components/procurement/StageStepper.tsx | 52 - .../portal/components/procurement/format.ts | 32 +- .../procurement/useProcurement.test.tsx | 137 ++ .../components/procurement/useProcurement.ts | 165 +- .../portal/components/shared/FlowModal.css | 52 + .../components/shared/FlowModal.test.tsx | 94 ++ .../portal/components/shared/FlowModal.tsx | 52 + .../components/shared/StepModalHeader.css | 92 ++ .../components/shared/StepModalHeader.tsx | 127 ++ .../src/portal/contexts/UIContext.test.tsx | 47 + .../editor/src/portal/contexts/UIContext.tsx | 16 + .../src/portal/contexts/ViewContext.tsx | 2 - .../src/portal/hooks/useOnboardingProgress.ts | 63 - .../editor/src/portal/mocks/handlers/index.ts | 3 - .../src/portal/mocks/handlers/procurement.ts | 92 -- .../portal/mocks/handlers/procurementSaas.ts | 122 +- .../editor/src/portal/mocks/procurement.ts | 307 ---- .../portal/mocks/procurementMachine.test.ts | 86 - .../src/portal/mocks/procurementMachine.ts | 114 -- frontend/editor/src/portal/queries/keys.ts | 3 + frontend/editor/src/portal/queries/users.ts | 5 +- .../editor/src/portal/views/Home.stories.tsx | 1 + frontend/editor/src/portal/views/Home.tsx | 2 +- .../editor/src/portal/views/Procurement.css | 1383 ++++++----------- .../editor/src/portal/views/Procurement.tsx | 15 - frontend/eslint.config.mjs | 7 +- 107 files changed, 5347 insertions(+), 4601 deletions(-) create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalConsentRepository.java create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalConsentService.java create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalController.java create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentMeta.java create mode 100644 app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentRegistry.java create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementPdfRenderer.java create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementSigning.java create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/legal/AssembledAgreement.java create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementAgreementSignature.java create mode 100644 app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementAgreementSignatureRepository.java create mode 100644 app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/dpa.md create mode 100644 app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/msa.md create mode 100644 app/saas/src/main/resources/legal/eula/1.0.0/eula.md create mode 100644 app/saas/src/main/resources/legal/manifest.json create mode 100644 app/saas/src/main/resources/legal/sla/1.0.0/sla.md create mode 100644 app/saas/src/main/resources/legal/subprocessors/1.0.0/subprocessors.md create mode 100644 app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementTrialRestartPolicyTest.java create mode 100644 frontend/editor/src/portal/api/externalUrl.test.ts create mode 100644 frontend/editor/src/portal/api/externalUrl.ts delete mode 100644 frontend/editor/src/portal/components/SetupChecklist.css delete mode 100644 frontend/editor/src/portal/components/SetupChecklist.stories.tsx delete mode 100644 frontend/editor/src/portal/components/SetupChecklist.tsx delete mode 100644 frontend/editor/src/portal/components/WelcomeBanner.css delete mode 100644 frontend/editor/src/portal/components/WelcomeBanner.stories.tsx delete mode 100644 frontend/editor/src/portal/components/WelcomeBanner.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/ActionModal.stories.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/ActionModal.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/DealJourney.stories.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/DealJourney.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/DocRow.stories.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/DocRow.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/DocumentLedger.stories.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/DocumentLedger.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/LockedState.stories.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/LockedState.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/ProcurementBanner.stories.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/ProcurementHome.stories.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/ProcurementHome.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/StageStepper.stories.tsx delete mode 100644 frontend/editor/src/portal/components/procurement/StageStepper.tsx create mode 100644 frontend/editor/src/portal/components/procurement/useProcurement.test.tsx create mode 100644 frontend/editor/src/portal/components/shared/FlowModal.css create mode 100644 frontend/editor/src/portal/components/shared/FlowModal.test.tsx create mode 100644 frontend/editor/src/portal/components/shared/FlowModal.tsx create mode 100644 frontend/editor/src/portal/components/shared/StepModalHeader.css create mode 100644 frontend/editor/src/portal/components/shared/StepModalHeader.tsx create mode 100644 frontend/editor/src/portal/contexts/UIContext.test.tsx delete mode 100644 frontend/editor/src/portal/hooks/useOnboardingProgress.ts delete mode 100644 frontend/editor/src/portal/mocks/handlers/procurement.ts delete mode 100644 frontend/editor/src/portal/mocks/procurement.ts delete mode 100644 frontend/editor/src/portal/mocks/procurementMachine.test.ts delete mode 100644 frontend/editor/src/portal/mocks/procurementMachine.ts delete mode 100644 frontend/editor/src/portal/views/Procurement.tsx diff --git a/app/saas/build.gradle b/app/saas/build.gradle index 495f583a74..a954e6d05a 100644 --- a/app/saas/build.gradle +++ b/app/saas/build.gradle @@ -6,6 +6,11 @@ dependencies { implementation project(':common') implementation project(':proprietary') + // Markdown -> HTML for rendering versioned legal documents (agreement) to PDF via the + // shared FileToPdf/WeasyPrint path in :common. Same library the core Markdown-to-PDF tool uses. + implementation "org.commonmark:commonmark:$commonmarkVersion" + implementation "org.commonmark:commonmark-ext-gfm-tables:$commonmarkVersion" + api 'org.springframework.boot:spring-boot-starter-security' api 'org.springframework.boot:spring-boot-starter-data-jpa' api 'org.springframework.boot:spring-boot-starter-oauth2-resource-server' diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java b/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java index cd991cc44e..612c6e3171 100644 --- a/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java +++ b/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java @@ -20,7 +20,8 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; "stirling.software.saas.ai.repository", "stirling.software.saas.payg.repository", "stirling.software.saas.payg.bundle", - "stirling.software.saas.procurement.repository" + "stirling.software.saas.procurement.repository", + "stirling.software.saas.legal" }) @EntityScan({ "stirling.software.saas.accountlink", @@ -28,6 +29,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; "stirling.software.saas.billing.model", "stirling.software.saas.ai.model", "stirling.software.saas.payg", - "stirling.software.saas.procurement.model" + "stirling.software.saas.procurement.model", + "stirling.software.saas.legal" }) public class SaasJpaConfig {} diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java new file mode 100644 index 0000000000..5698133fe8 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsent.java @@ -0,0 +1,62 @@ +package stirling.software.saas.legal; + +import java.io.Serializable; +import java.time.LocalDateTime; + +import org.hibernate.annotations.CreationTimestamp; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * An append-only record that a user accepted a versioned legal document at a particular moment in + * the product. Distinct from a signed agreement (which is a negotiated, signature-bearing artifact, + * see {@code ProcurementAgreementSignature}); this captures the lighter clickwrap consents — the + * EULA accepted at trial start and at quote generation — with the exact document version, so what + * was agreed is auditable even after the document versions up. + */ +@Entity +@Table(name = "legal_consent") +@NoArgsConstructor +@Getter +@Setter +public class LegalConsent implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "consent_id") + private Long consentId; + + @Column(name = "team_id") + private Long teamId; + + @Column(name = "user_id") + private Long userId; + + @Column(name = "document_id", nullable = false, length = 64) + private String documentId; + + @Column(name = "document_version", nullable = false, length = 32) + private String documentVersion; + + // Where in the product the consent was given: "trial", "quote", etc. + @Column(name = "context", nullable = false, length = 32) + private String context; + + @Column(name = "signer_ip", length = 64) + private String signerIp; + + @CreationTimestamp + @Column(name = "consented_at", nullable = false, updatable = false) + private LocalDateTime consentedAt; +} diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentRepository.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentRepository.java new file mode 100644 index 0000000000..9d79640cd0 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentRepository.java @@ -0,0 +1,5 @@ +package stirling.software.saas.legal; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface LegalConsentRepository extends JpaRepository {} diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentService.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentService.java new file mode 100644 index 0000000000..c6377f35b7 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalConsentService.java @@ -0,0 +1,47 @@ +package stirling.software.saas.legal; + +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** Records clickwrap consents to versioned legal documents (see {@link LegalConsent}). */ +@Slf4j +@Service +@Profile("saas") +@RequiredArgsConstructor +public class LegalConsentService { + + private final LegalDocumentRegistry registry; + private final LegalConsentRepository consents; + + /** + * Record that the given user accepted the current version of {@code documentId} in {@code + * context} (e.g. "trial", "quote"). No-op for an unknown document. Best-effort: callers treat a + * failure as non-fatal so it never blocks the flow the consent accompanies. + */ + @Transactional + public void record(Long teamId, Long userId, String documentId, String context, String ip) { + LegalDocumentMeta meta = registry.meta(documentId).orElse(null); + if (meta == null) { + log.warn("[legal] consent for unknown document '{}' ignored", documentId); + return; + } + LegalConsent consent = new LegalConsent(); + consent.setTeamId(teamId); + consent.setUserId(userId); + consent.setDocumentId(meta.id()); + consent.setDocumentVersion(meta.version()); + consent.setContext(context); + consent.setSignerIp(ip); + consents.save(consent); + log.info( + "[legal] consent recorded team={} doc={} v{} context={}", + teamId, + meta.id(), + meta.version(), + context); + } +} 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.java new file mode 100644 index 0000000000..308b3e99bd --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalController.java @@ -0,0 +1,133 @@ +package stirling.software.saas.legal; + +import java.util.Optional; + +import org.springframework.context.annotation.Profile; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.v3.oas.annotations.Hidden; + +import jakarta.servlet.http.HttpServletRequest; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +import stirling.software.proprietary.model.TeamMembership; +import stirling.software.proprietary.security.database.repository.UserRepository; +import stirling.software.proprietary.security.model.User; +import stirling.software.proprietary.security.repository.TeamMembershipRepository; +import stirling.software.saas.util.AuthenticationUtils; + +/** + * Serves the versioned legal documents (EULA, SLA exhibit, subprocessors) for in-product viewing, + * and records the lighter clickwrap consents. The enterprise agreement itself is served + signed + * through the procurement controller, since it needs a quote to fill its Order Form. + */ +@Slf4j +@Hidden +@RestController +@RequestMapping("/api/v1/legal") +@Profile("saas") +@RequiredArgsConstructor +public class LegalController { + + private final LegalDocumentRegistry registry; + private final LegalConsentService consents; + private final TeamMembershipRepository memberRepo; + private final UserRepository userRepository; + + /** A legal document rendered for viewing: registry metadata + the static markdown body. */ + public record LegalDocumentResponse( + String docId, + String version, + String versionLabel, + String displayName, + String effectiveDate, + String status, + String markdown) {} + + public record ConsentRequest(String documentId, String context) {} + + /** Fetch a legal document's current version as markdown. 404 for an unknown document. */ + @GetMapping("/{docId}") + @PreAuthorize("isAuthenticated()") + public ResponseEntity document(@PathVariable String docId) { + return registry.meta(docId) + .>map( + meta -> + ResponseEntity.ok( + new LegalDocumentResponse( + meta.id(), + meta.version(), + meta.versionLabel(), + meta.displayName(), + meta.effectiveDate(), + meta.status(), + registry.staticMarkdown(docId)))) + .orElseGet(() -> ResponseEntity.notFound().build()); + } + + /** + * Record a clickwrap consent (e.g. the EULA accepted at trial start or quote generation). + * Best-effort — a teamless caller still returns 200 so the accompanying flow is never blocked. + */ + @PostMapping("/consent") + @PreAuthorize("isAuthenticated()") + public ResponseEntity consent( + @RequestBody ConsentRequest request, Authentication auth, HttpServletRequest http) { + if (request == null || request.documentId() == null || request.context() == null) { + return ResponseEntity.badRequest().build(); + } + Optional membership = primaryMembership(auth); + Long teamId = membership.map(m -> m.getTeam().getId()).orElse(null); + Long userId = membership.map(m -> m.getUser().getId()).orElse(null); + // Best-effort for real: consent is audit metadata, not an authorisation gate, so a failed + // write must not fail the trial start or quote generation this call accompanies. Previously + // that only held because the caller happened to swallow the 500. + try { + consents.record( + teamId, userId, request.documentId(), request.context(), clientIp(http)); + } catch (RuntimeException e) { + log.warn( + "[legal] consent not recorded doc={} context={}: {}", + request.documentId(), + request.context(), + e.getMessage()); + } + return ResponseEntity.ok().build(); + } + + private Optional primaryMembership(Authentication auth) { + User user; + try { + user = AuthenticationUtils.getCurrentUser(auth, userRepository); + } catch (SecurityException e) { + return Optional.empty(); + } + return memberRepo.findPrimaryMembership(user.getId()).stream().findFirst(); + } + + /** + * Best guess at the caller's address, for the audit record. + * + *

Informational only, and must stay that way: the first {@code X-Forwarded-For} hop is set + * by the client, so a stored address is trivially spoofable and is not evidence of where a + * consent or signature came from. Treat it as a hint when reconstructing events, never as + * proof. + */ + private static String clientIp(HttpServletRequest request) { + String forwarded = request.getHeader("X-Forwarded-For"); + if (forwarded != null && !forwarded.isBlank()) { + return forwarded.split(",")[0].trim(); + } + return request.getRemoteAddr(); + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentMeta.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentMeta.java new file mode 100644 index 0000000000..9f35e42053 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentMeta.java @@ -0,0 +1,27 @@ +package stirling.software.saas.legal; + +import java.util.List; + +/** + * One legal document's registry entry, as declared in {@code legal/manifest.json}. Immutable + * snapshot loaded at startup by {@link LegalDocumentRegistry}. + * + *

{@code parts} lists the pieces, in render order, that make up the document. A plain entry + * (e.g. {@code "msa.md"}) is a static markdown file under {@code legal///}; an entry + * prefixed with {@code "@"} (e.g. {@code "@order-form"}) is a dynamic section that a document + * assembler generates at render time. + */ +public record LegalDocumentMeta( + String id, + String label, + String displayName, + String version, + String effectiveDate, + String status, + List parts) { + + /** Fully-qualified version label shown to users and stored on signatures, e.g. "SEA v0.9.1". */ + public String versionLabel() { + return label + " v" + version; + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentRegistry.java b/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentRegistry.java new file mode 100644 index 0000000000..ffbe030863 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/legal/LegalDocumentRegistry.java @@ -0,0 +1,151 @@ +package stirling.software.saas.legal; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import jakarta.annotation.PostConstruct; + +import lombok.extern.slf4j.Slf4j; + +/** + * Loads the versioned legal-document registry from {@code legal/manifest.json} on startup and + * serves document metadata + rendered markdown from the classpath. + * + *

Publishing a new version of any document is a content-only change: drop the markdown under + * {@code legal///} and bump that document's {@code version} in the manifest — no + * code change. Signatures pin the exact {@code {id, version, contentHash}} they were signed against + * (see the procurement agreement flow), so historical documents stay reproducible. + * + *

Token slots of the form {{name}} in the markdown are filled at render time. This + * registry fills the document-level common tokens ({@code version}, {@code version_date}, {@code + * subprocessor_url}, {@code eula_url}); callers that need per-quote tokens (the enterprise + * agreement's Order Form) fill the rest. + */ +@Slf4j +@Service +public class LegalDocumentRegistry { + + private static final String MANIFEST = "legal/manifest.json"; + private static final Pattern TOKEN = Pattern.compile("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*}}"); + + private final ObjectMapper objectMapper = new ObjectMapper(); + + private final Map documents = new LinkedHashMap<>(); + private String subprocessorUrl = ""; + private String eulaUrl = ""; + + @PostConstruct + void load() throws IOException { + JsonNode root; + try (InputStream in = new ClassPathResource(MANIFEST).getInputStream()) { + root = objectMapper.readTree(in); + } + subprocessorUrl = root.path("subprocessorUrl").asText(""); + eulaUrl = root.path("eulaUrl").asText(""); + JsonNode docs = root.path("documents"); + docs.fieldNames() + .forEachRemaining( + id -> { + JsonNode d = docs.get(id); + List parts = + objectMapper.convertValue( + d.path("parts"), + objectMapper + .getTypeFactory() + .constructCollectionType( + List.class, String.class)); + documents.put( + id, + new LegalDocumentMeta( + id, + d.path("label").asText(id), + d.path("displayName").asText(id), + d.path("version").asText("0"), + d.path("effectiveDate").asText(""), + d.path("status").asText("draft"), + parts == null ? List.of() : parts)); + }); + log.info("[legal] loaded {} document(s) from {}", documents.size(), MANIFEST); + } + + public Optional meta(String docId) { + return Optional.ofNullable(documents.get(docId)); + } + + public String subprocessorUrl() { + return subprocessorUrl; + } + + public String eulaUrl() { + return eulaUrl; + } + + /** Document-level tokens available to every document (before any per-quote tokens). */ + public Map commonTokens(LegalDocumentMeta meta) { + Map t = new LinkedHashMap<>(); + t.put("version", meta.version()); + t.put("version_date", meta.effectiveDate()); + t.put("subprocessor_url", subprocessorUrl); + t.put("eula_url", eulaUrl); + return t; + } + + /** Read one static markdown part of a document from the classpath. */ + public String readPart(LegalDocumentMeta meta, String partFile) { + String path = "legal/" + meta.id() + "/" + meta.version() + "/" + partFile; + try (InputStream in = new ClassPathResource(path).getInputStream()) { + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new IllegalStateException("Missing legal document part: " + path, e); + } + } + + /** + * The concatenated static parts of a document (dynamic {@code @}-parts skipped), with only the + * common tokens filled. Use for fully-static documents (EULA, SLA, subprocessors). + */ + public String staticMarkdown(String docId) { + LegalDocumentMeta meta = + meta(docId) + .orElseThrow( + () -> new IllegalArgumentException("Unknown document: " + docId)); + Map tokens = commonTokens(meta); + StringBuilder sb = new StringBuilder(); + for (String part : meta.parts()) { + if (part.startsWith("@")) continue; // dynamic section — not part of the static body + if (sb.length() > 0) sb.append("\n\n"); + sb.append(fill(readPart(meta, part), tokens)); + } + return sb.toString(); + } + + /** Replace {@code {{token}}} slots; unknown tokens are left intact so gaps are visible. */ + public static String fill(String markdown, Map tokens) { + Matcher m = TOKEN.matcher(markdown); + StringBuilder out = new StringBuilder(); + while (m.find()) { + String key = m.group(1); + String value = tokens.get(key); + m.appendReplacement( + out, + value == null + ? Matcher.quoteReplacement(m.group(0)) + : Matcher.quoteReplacement(value)); + } + m.appendTail(out); + return out.toString(); + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java index e2dff403a7..f864bf4d98 100644 --- a/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java +++ b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java @@ -34,17 +34,22 @@ import lombok.Setter; @Entity @Table( name = "payg_prepaid_bundle", - // Declared here for ddl-auto (fresh schemas) and to document intent. The authoritative creator - // in production is the Supabase CLI migration 20260720000000_payg_prepaid_bundle, which builds + // Declared here for ddl-auto (fresh schemas) and to document intent. The authoritative + // creator + // in production is the Supabase CLI migration 20260720000000_payg_prepaid_bundle, which + // builds // the partial forms (WHERE units_remaining > 0 / WHERE stripe_ref IS NOT NULL). Flyway was // retired for SaaS (#7100), so there is no migration twin — names match the CLI migration. indexes = { - // Hot-path FIFO draw lookup — findDrawableForUpdate runs a locked read on every billable - // charge past the free grant; without it that degrades to a locked scan as the table grows. + // Hot-path FIFO draw lookup — findDrawableForUpdate runs a locked read on every + // billable + // charge past the free grant; without it that degrades to a locked scan as the table + // grows. @Index( name = "idx_payg_prepaid_bundle_team_expiry", columnList = "team_id, expires_at"), - // One pool per Stripe payment — the idempotency guard so a redelivered invoice.paid can't + // One pool per Stripe payment — the idempotency guard so a redelivered invoice.paid + // can't // credit the same purchase twice. @Index( name = "uq_payg_prepaid_bundle_stripe_ref", 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.java index d67a0fddbf..1c495b3afd 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 @@ -22,6 +22,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.v3.oas.annotations.Hidden; +import jakarta.servlet.http.HttpServletRequest; + import lombok.extern.slf4j.Slf4j; import stirling.software.common.model.enumeration.TeamRole; @@ -30,6 +32,8 @@ import stirling.software.proprietary.security.database.repository.UserRepository import stirling.software.proprietary.security.model.User; import stirling.software.proprietary.security.repository.TeamMembershipRepository; import stirling.software.saas.procurement.config.ProcurementConfigurationProperties; +import stirling.software.saas.procurement.legal.AgreementSigning; +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; @@ -178,7 +182,17 @@ public class ProcurementController { String taxId) {} /** Trial setup captured before the trial starts: deployment target + seat count. */ - public record StartTrialRequest(String deployment, int users) {} + /** + * Setup step 2 collects the buying entity; all of it is optional so an older client still + * starts. + */ + public record StartTrialRequest( + String deployment, + int users, + String businessName, + String contactName, + String contactEmail, + String inviteEmails) {} public record SnapshotResponse( Long dealId, @@ -190,8 +204,33 @@ public class ProcurementController { int trialExtensionsUsed, boolean licensed, String licenseKey, + // Version label of the signed agreement PDF available for download, else null. + String agreementSignedVersion, + // Buying entity captured at trial setup; null on deals started before that step. + String businessName, + String contactName, + String contactEmail, QuoteResponse latestQuote) {} + /** The filled agreement for review: registry metadata + the rendered markdown body. */ + public record AgreementDocumentResponse( + String docId, + String version, + String versionLabel, + String displayName, + String effectiveDate, + String status, + String markdown) {} + + /** Buyer-supplied signing inputs from the agreement stage. */ + public record SignAgreementRequest( + String customerLegalName, + String signatoryName, + String signatoryTitle, + boolean authorityConfirmed) {} + + public record SignAgreementResponse(Long signatureId, String versionLabel, boolean pdfStored) {} + // ---- endpoints ---------------------------------------------------------- /** @@ -213,7 +252,8 @@ public class ProcurementController { } private static final SnapshotResponse EMPTY_SNAPSHOT = - new SnapshotResponse(null, null, null, 0, null, null, 0, false, null, null); + new SnapshotResponse( + null, null, null, 0, null, null, 0, false, null, null, null, null, null, null); /** * Download the offline / air-gapped licence file (.lic) for the team — available for an @@ -239,6 +279,15 @@ public class ProcurementController { .orElseGet(() -> ResponseEntity.notFound().build()); } + /** Mark the account as looking at enterprise. Idempotent; never disturbs an existing deal. */ + @PostMapping("/interest") + @PreAuthorize("isAuthenticated()") + public ResponseEntity recordInterest(Authentication auth) { + Long teamId = requireLeader(auth); + if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + return ResponseEntity.ok(toSnapshot(procurement.recordInterest(teamId), true)); + } + @PostMapping("/trial/start") @PreAuthorize("isAuthenticated()") public ResponseEntity startTrial( @@ -248,8 +297,30 @@ public class ProcurementController { // Body is optional so an older client (no setup step) still starts a cloud trial. String deployment = request != null ? request.deployment() : null; int seats = request != null ? request.users() : 0; - return ResponseEntity.ok( - toSnapshot(procurement.startTrial(teamId, deployment, seats), true)); + ProcurementDeal deal; + try { + deal = + procurement.startTrial( + teamId, + deployment, + seats, + request != null ? request.businessName() : null, + request != null ? request.contactName() : null, + request != null ? request.contactEmail() : null, + request != null ? request.inviteEmails() : null); + } catch (IllegalStateException e) { + // Past the trial the deal holds a committed licence; restarting would replace it. + log.warn("[procurement] trial start rejected team={}: {}", teamId, e.getMessage()); + return ResponseEntity.status(HttpStatus.CONFLICT).build(); + } + // After the trial exists, so a rejected invite can never stop it starting. + if (request != null) { + procurement.sendTrialInvites( + teamId, + primaryMembership(auth).map(TeamMembership::getUser).orElse(null), + request.inviteEmails()); + } + return ResponseEntity.ok(toSnapshot(deal, true)); } @PostMapping("/trial/extend") @@ -270,8 +341,17 @@ public class ProcurementController { @RequestBody QuoteRequest request, Authentication auth) { Long teamId = requireLeader(auth); if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); - return ResponseEntity.ok( - toQuote(procurement.buildQuote(teamId, request.toConfig(), request.toDetails()))); + try { + return ResponseEntity.ok( + toQuote( + procurement.buildQuote( + teamId, request.toConfig(), request.toDetails()))); + } catch (IllegalStateException e) { + // Below the minimum deal size, or the deal is already live. A client error, not a + // fault. + log.warn("[procurement] quote rejected team={}: {}", teamId, e.getMessage()); + return ResponseEntity.status(HttpStatus.CONFLICT).build(); + } } // Issue + accept are Supabase edge functions (they own Stripe): issue-procurement-quote turns a @@ -293,6 +373,111 @@ public class ProcurementController { } } + /** + * The filled Stirling Enterprise Agreement (MSA + Order Form + DPA) for the team's current + * quote, as markdown, for the buyer to review before signing. 404 when there's no quote yet. + */ + @GetMapping("/agreement/document") + @PreAuthorize("isAuthenticated()") + public ResponseEntity agreementDocument(Authentication auth) { + Long teamId = requireLeader(auth); + if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + return procurement + .agreementDocument(teamId) + .>map( + a -> + ResponseEntity.ok( + new AgreementDocumentResponse( + a.docId(), + a.version(), + a.versionLabel(), + a.displayName(), + a.effectiveDate(), + a.status(), + a.markdown()))) + .orElseGet(() -> ResponseEntity.notFound().build()); + } + + /** + * Record a signed agreement: capture the typed legal name / signatory / title / authority, pin + * the exact document version + content hash + variable snapshot, and store the rendered PDF + * (best-effort). The caller then proceeds to accept the quote as before. + */ + @PostMapping("/agreement/sign") + @PreAuthorize("isAuthenticated()") + public ResponseEntity signAgreement( + @RequestBody SignAgreementRequest request, + Authentication auth, + HttpServletRequest http) { + Long teamId = requireLeader(auth); + if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + if (request == null + || request.signatoryName() == null + || request.signatoryName().isBlank() + || !request.authorityConfirmed()) { + return ResponseEntity.badRequest().build(); + } + try { + ProcurementAgreementSignature sig = + procurement.signAgreement( + teamId, + new AgreementSigning( + request.customerLegalName(), + request.signatoryName(), + request.signatoryTitle(), + request.authorityConfirmed()), + clientIp(http)); + return ResponseEntity.ok( + new SignAgreementResponse( + sig.getSignatureId(), sig.getDocumentLabel(), sig.getPdf() != null)); + } catch (IllegalStateException e) { + return ResponseEntity.status(HttpStatus.CONFLICT).build(); + } + } + + /** Download the stored signed-agreement PDF for the team. 404 if none was rendered/stored. */ + @GetMapping("/agreement/signature/pdf") + @PreAuthorize("isAuthenticated()") + public ResponseEntity signaturePdf(Authentication auth) { + Long teamId = requireLeader(auth); + if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + return procurement + .signedAgreementPdf(teamId) + .>map( + pdf -> + ResponseEntity.ok() + .header( + HttpHeaders.CONTENT_DISPOSITION, + "attachment;" + + " filename=\"stirling-enterprise-agreement.pdf\"") + .contentType(MediaType.APPLICATION_PDF) + .body(pdf)) + .orElseGet(() -> ResponseEntity.notFound().build()); + } + + /** + * Download the current (unsigned) agreement as a PDF — the document shown at the sign step. 404 + * when there's no quote yet or the render runtime is unavailable. + */ + @GetMapping("/agreement/document/pdf") + @PreAuthorize("isAuthenticated()") + public ResponseEntity agreementDocumentPdf(Authentication auth) { + Long teamId = requireLeader(auth); + if (teamId == null) return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); + return procurement + .agreementDocumentPdf(teamId) + .>map( + pdf -> + ResponseEntity.ok() + .header( + HttpHeaders.CONTENT_DISPOSITION, + "attachment;" + + " filename=\"stirling-enterprise-agreement.pdf\"") + .contentType(MediaType.APPLICATION_PDF) + .body(pdf)) + .orElseGet(() -> ResponseEntity.notFound().build()); + } + /** * Provision on accept: upgrade the team's licence to the committed annual term, valid * immediately. Called server-side by the accept edge function (ROLE_ADMIN via X-API-Key) once @@ -311,9 +496,38 @@ public class ProcurementController { } } + /** + * Go live once payment settles: advance the deal to active and re-affirm the annual licence. + * Called server-side by the {@code invoice.paid} webhook (ROLE_ADMIN via X-API-Key), alongside + * {@code /provision}, which runs earlier at accept and deliberately leaves the stage alone. + * + *

Answers 200 when the team has no deal at all, rather than erroring: a committed + * subscription can be closed directly in Stripe by sales with no portal deal behind it, and a + * non-2xx would have Stripe retry a webhook that can never succeed. + * + *

{@code invoiceId} is what makes this idempotent without swallowing renewals: the same + * invoice twice is a redelivery, a different one is next year's payment and has to re-issue the + * licence. Optional so an older caller still works, at the cost of that distinction. + */ + @PostMapping("/activate") + @PreAuthorize("hasRole('ADMIN')") + public ResponseEntity activate( + @RequestParam("teamId") long teamId, + @RequestParam(value = "invoiceId", required = false) String invoiceId) { + try { + procurement.markLive(teamId, invoiceId); + } catch (IllegalStateException e) { + log.info( + "[procurement] activate skipped, no deal for team={}: {}", + teamId, + e.getMessage()); + } + return ResponseEntity.ok().build(); + } + /** * Demo/manual stand-in for the {@code invoice.paid} webhook: mark the deal live (issue the - * annual licence, advance to active). The real go-live is webhook-driven once payment settles. + * annual licence, advance to active). Production go-live runs through {@code /activate}. */ @PostMapping("/go-live") @PreAuthorize("isAuthenticated()") @@ -360,6 +574,21 @@ public class ProcurementController { .orElse(null); } + /** + * Best-effort client IP for the signature record: first X-Forwarded-For hop, else the peer. + * + *

Informational only. That header is client-set, so {@code signer_ip} is spoofable and is + * not evidence of where a signature came from — the document hash and version are what make the + * record trustworthy. Treat the address as a hint, never as proof. + */ + private static String clientIp(HttpServletRequest request) { + String forwarded = request.getHeader("X-Forwarded-For"); + if (forwarded != null && !forwarded.isBlank()) { + return forwarded.split(",")[0].trim(); + } + return request.getRemoteAddr(); + } + /** * Build the snapshot for a deal. {@code includeLicenseKey} is true only for the team leader; a * member sees {@code licensed} but not the key itself (see {@link #snapshot}). Mutation @@ -381,6 +610,10 @@ public class ProcurementController { deal.getTrialExtensionsUsed(), deal.getLicenseRef() != null, includeLicenseKey ? deal.getLicenseRef() : null, + procurement.signedAgreementLabel(deal.getDealId()).orElse(null), + deal.getBusinessName(), + deal.getContactName(), + deal.getContactEmail(), latest); } diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/config/ProcurementConfigurationProperties.java b/app/saas/src/main/java/stirling/software/saas/procurement/config/ProcurementConfigurationProperties.java index 98ec0cd573..ad745cf5bc 100644 --- a/app/saas/src/main/java/stirling/software/saas/procurement/config/ProcurementConfigurationProperties.java +++ b/app/saas/src/main/java/stirling/software/saas/procurement/config/ProcurementConfigurationProperties.java @@ -30,4 +30,17 @@ public class ProcurementConfigurationProperties { * /go-live is a stand-in for the invoice.paid webhook and would let a leader activate unpaid. */ private boolean demoControlsEnabled = false; + + /** + * Smallest annual fee, in minor units, that may be quoted. The pricing curve has no natural + * floor — a small enough committed volume rounds the meter to zero — and every registered user + * is the leader of their own team, so without this any signup could price a $0 enterprise + * quote, accept it, and be provisioned a committed licence. 12_000_00 is USD 12,000/yr, the + * self-hosted deploy fee, chosen so the floor cannot sit below a line item the quote itself can + * contain. + * + *

This is a commercial number, not a technical one: set it to whatever the smallest + * enterprise deal you will actually sign is. Zero disables the check. + */ + private long minAnnualNetMinor = 12_000_00L; } diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java new file mode 100644 index 0000000000..c641f2e596 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementAssembler.java @@ -0,0 +1,278 @@ +package stirling.software.saas.procurement.legal; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +import stirling.software.saas.legal.LegalDocumentMeta; +import stirling.software.saas.legal.LegalDocumentRegistry; +import stirling.software.saas.procurement.model.ProcurementQuote; +import stirling.software.saas.procurement.pricing.ProcurementPricingService; +import stirling.software.saas.procurement.pricing.QuoteConfig; +import stirling.software.saas.procurement.pricing.QuoteLineItem; + +/** + * Builds the full Stirling Enterprise Agreement for a specific quote: the static MSA (Part A) and + * DPA (Part C) from the {@link LegalDocumentRegistry}, with the dynamic Order Form (Part B) + * generated from the quote and slotted where the manifest's {@code @order-form} part sits. + * + *

Only the Order Form varies per deal; the MSA and DPA bodies are rendered verbatim with token + * substitution. The set of values used is returned as {@code variablesJson} so a signature can pin + * exactly what was rendered. + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class AgreementAssembler { + + public static final String DOC_ID = "enterprise-agreement"; + + private static final DateTimeFormatter DATE = + DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.US); + private static final String BLANK = "\\_\\_\\_\\_\\_\\_\\_\\_\\_\\_"; + + private final LegalDocumentRegistry registry; + private final ProcurementPricingService pricing; + private final ObjectMapper objectMapper = new ObjectMapper(); + + /** + * Render the agreement for a quote. {@code signing} is null for a preview (before signing) — + * the effective date and signature block then read as blanks / "On signature". + */ + public AssembledAgreement assemble(ProcurementQuote quote, AgreementSigning signing) { + LegalDocumentMeta meta = + registry.meta(DOC_ID) + .orElseThrow( + () -> + new IllegalStateException( + "Enterprise agreement not registered")); + + Map tokens = tokens(quote, signing, meta); + + StringBuilder md = new StringBuilder(); + for (String part : meta.parts()) { + if (md.length() > 0) md.append("\n\n"); + if ("@order-form".equals(part)) { + md.append(LegalDocumentRegistry.fill(orderForm(quote, tokens), tokens)); + } else { + md.append(LegalDocumentRegistry.fill(registry.readPart(meta, part), tokens)); + } + } + + String variablesJson; + try { + variablesJson = objectMapper.writeValueAsString(tokens); + } catch (Exception e) { + variablesJson = "{}"; + } + + return new AssembledAgreement( + meta.id(), + meta.version(), + meta.versionLabel(), + meta.displayName(), + meta.effectiveDate(), + meta.status(), + md.toString(), + variablesJson); + } + + private Map tokens( + ProcurementQuote quote, AgreementSigning signing, LegalDocumentMeta meta) { + QuoteConfig cfg = toConfig(quote); + boolean signed = signing != null; + + String legalName = + signed && notBlank(signing.customerLegalName()) + ? signing.customerLegalName().trim() + : (notBlank(quote.getBusinessName()) + ? quote.getBusinessName().trim() + : "Customer"); + + Map t = new LinkedHashMap<>(registry.commonTokens(meta)); + t.put("effective_date", signed ? LocalDate.now().format(DATE) : "On signature"); + t.put("customer_legal_name", cell(legalName)); + t.put("quote_ref", nz(quote.getQuoteNumber())); + t.put("deployment", ProcurementPricingService.deploymentName(quote.getDeployment())); + t.put("committed_pdfs_yr", String.format(Locale.US, "%,d", Math.max(0, quote.getVolume()))); + t.put("posture", ProcurementPricingService.postureName(quote.getIntensity())); + t.put("processes_per_pdf", String.valueOf(Math.max(1, quote.getIntensity()))); + t.put("rate_per_pdf", String.format(Locale.US, "$%.4f", pricing.effectiveRatePerPdf(cfg))); + t.put("term_years", String.valueOf(quote.getTermYears())); + t.put("term_discount_pct", pricing.termDiscountPct(quote.getTermYears()) + "%"); + t.put("sla_tier", slaTier(quote.getServiceLevel())); + t.put("annual_fee_y1", money(quote.getAnnualNetMinor())); + t.put("contract_total", money(quote.getTcvMinor())); + t.put("elected_or_not", quote.isIndemnification() ? "Elected" : "Not elected"); + t.put("po_number", notBlank(quote.getPoNumber()) ? cell(quote.getPoNumber()) : "—"); + t.put( + "customer_signatory", + signed && notBlank(signing.signatoryName()) + ? cell(signing.signatoryName()) + : BLANK); + t.put( + "customer_signatory_title", + signed && notBlank(signing.signatoryTitle()) + ? cell(signing.signatoryTitle()) + : BLANK); + return t; + } + + /** + * Make a buyer-supplied value safe to slot into a markdown table cell. + * + *

An unescaped {@code |} or newline splits the cell and breaks the Order Form's table. That + * matters beyond appearance: this markdown is what gets hashed into the signature record, so a + * value that restructures the table means the SHA-256 we keep as proof covers a document + * reading differently from the one the signatory saw. + */ + private static String cell(String raw) { + return raw.trim().replace("|", "\\|").replaceAll("\\s*\\R+\\s*", " "); + } + + /** Part B — the Order Form. Generated from the quote; the only per-deal section. */ + private String orderForm(ProcurementQuote quote, Map t) { + String date = t.get("effective_date"); + String signatory = t.get("customer_signatory"); + String signatoryTitle = t.get("customer_signatory_title"); + + StringBuilder sb = new StringBuilder(); + sb.append("## Part B — Order Form · {{quote_ref}}\n\n"); + sb.append("| Term | Value |\n| --- | --- |\n"); + row(sb, "Customer", "{{customer_legal_name}}"); + row(sb, "Subscription", "Enterprise · {{deployment}}"); + row(sb, "Purchase order", "{{po_number}}"); + row(sb, "Committed Volume", "{{committed_pdfs_yr}} PDFs / year at the {{posture}} posture"); + row(sb, "Committed rate", "{{rate_per_pdf}} per PDF"); + row(sb, "Service level", "{{sla_tier}} (per SLA Exhibit)"); + row( + sb, + "Term", + "{{term_years}} year(s) · term discount {{term_discount_pct}} on committed processing"); + row(sb, "Itemized services", itemizedServices(quote)); + row(sb, "Annual Fee (year 1)", "{{annual_fee_y1}}"); + row(sb, "Total (paid in advance)", "{{contract_total}}"); + row(sb, "Escalator", "+3% at each anniversary during the Term"); + row( + sb, + "Payment", + "Full {{term_years}}-year term invoiced in advance on acceptance · net 30 · ACH," + + " wire, or check"); + row(sb, "Overage", "Committed rate, billed quarterly in arrears"); + row( + sb, + "Data schedule", + "First 25 MB per file included; each additional 25 MB or part thereof (decimal MB," + + " rounded up per file, measured once at ingestion) draws down 1 PDF Process." + + " Frozen for the Term (MSA §3.5)."); + row( + sb, + "Drawdown schedule", + "{{posture}}: {{processes_per_pdf}} PDF Processes per PDF (MSA §3.3, frozen for the Term)"); + row( + sb, + "Enhanced IP Protection", + "{{elected_or_not}} — extends §7.3 to patent claims at the §8.2 super-cap"); + row(sb, "Standard terms", "SSO, SCIM, RBAC, and audit logs included."); + + sb.append( + "\n**Itemized services menu (include as elected):** Self-hosted deployment $12,000/yr" + + " · Air-gapped deployment $36,000/yr · Dedicated SE/CSM $30,000/yr · Enhanced IP" + + " Protection (patent coverage, Section 7.3) 5% of committed processing fees ·" + + " Onboarding & training $7,500 one-time · Quarterly business reviews $8,000/yr." + + " Baseline IP indemnification (copyright, trademark, trade secret) is included at" + + " no charge.\n\n"); + sb.append( + "**Signatures.** By signing, each signatory represents they have authority to bind" + + " their Party. Signatures delivered electronically or in counterparts are" + + " effective as originals.\n\n"); + sb.append("| Provider | Customer |\n| --- | --- |\n"); + sb.append("| Stirling PDF, Inc. | {{customer_legal_name}} |\n"); + sb.append("| Name: Matt Joseph | Name: ").append(signatory).append(" |\n"); + sb.append("| Title: CEO | Title: ").append(signatoryTitle).append(" |\n"); + sb.append("| Date: ").append(date).append(" | Date: ").append(date).append(" |\n"); + return sb.toString(); + } + + /** + * The elected add-on lines, taken from the quote's stored breakdown (excludes the base meter). + */ + private String itemizedServices(ProcurementQuote quote) { + List lines = parseLineItems(quote.getLineItemsJson()); + List elected = new ArrayList<>(); + for (QuoteLineItem li : lines) { + if (li.key().equals("usage") + || li.key().equals("seats") + || li.key().equals("multi-year")) { + continue; + } + String suffix = li.kind() == QuoteLineItem.Kind.ONE_TIME ? " (one-time)" : "/yr"; + elected.add(li.label() + " " + money(li.amountMinor()) + suffix); + } + return elected.isEmpty() ? "None elected" : String.join(" · ", elected); + } + + private List parseLineItems(String json) { + if (json == null || json.isBlank()) return List.of(); + try { + return objectMapper.readValue( + json, + objectMapper + .getTypeFactory() + .constructCollectionType(List.class, QuoteLineItem.class)); + } catch (Exception e) { + log.warn("[legal] could not parse quote line items for the order form", e); + return List.of(); + } + } + + private static QuoteConfig toConfig(ProcurementQuote q) { + int users = q.getSeats() == null ? 0 : q.getSeats(); + return new QuoteConfig( + q.getVolume(), + users, + q.getIntensity(), + q.getSizeMult(), + q.getDeployment(), + q.getTermYears(), + q.getServiceLevel(), + q.isIndemnification(), + q.isTraining(), + q.isQbr(), + q.getCurrency()); + } + + private static void row(StringBuilder sb, String term, String value) { + sb.append("| ").append(term).append(" | ").append(value).append(" |\n"); + } + + private static String slaTier(String serviceLevel) { + if ("dedicated".equalsIgnoreCase(serviceLevel)) return "Dedicated"; + if ("priority".equalsIgnoreCase(serviceLevel)) return "Priority"; + return "Standard"; + } + + /** Minor units (cents) → whole-dollar display; the quote figures are whole dollars. */ + private static String money(long minor) { + return String.format(Locale.US, "$%,d", minor / 100L); + } + + private static boolean notBlank(String s) { + return s != null && !s.isBlank(); + } + + private static String nz(String s) { + return s == null ? "" : s; + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementPdfRenderer.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementPdfRenderer.java new file mode 100644 index 0000000000..8204df6514 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementPdfRenderer.java @@ -0,0 +1,71 @@ +package stirling.software.saas.procurement.legal; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import org.commonmark.Extension; +import org.commonmark.ext.gfm.tables.TablesExtension; +import org.commonmark.node.Node; +import org.commonmark.parser.Parser; +import org.commonmark.renderer.html.HtmlRenderer; +import org.springframework.stereotype.Service; + +import lombok.RequiredArgsConstructor; + +import stirling.software.common.configuration.RuntimePathConfig; +import stirling.software.common.service.CustomPDFDocumentFactory; +import stirling.software.common.util.CustomHtmlSanitizer; +import stirling.software.common.util.FileToPdf; +import stirling.software.common.util.TempFileManager; + +/** + * Renders an assembled agreement's markdown to a PDF, dogfooding Stirling's own conversion path: + * commonmark (markdown → HTML) then {@link FileToPdf#convertHtmlToPdf} (HTML → PDF via WeasyPrint), + * the same pipeline as the product's Markdown-to-PDF tool. + * + *

The signed PDF is a stored artifact, but it must never block signing: {@link #tryRender} + * returns {@code null} if the conversion runtime (WeasyPrint) is unavailable, so the signature is + * still recorded and the buyer keeps the on-the-fly download. + */ +@Service +@RequiredArgsConstructor +public class AgreementPdfRenderer { + + private final RuntimePathConfig runtimePathConfig; + private final TempFileManager tempFileManager; + private final CustomHtmlSanitizer customHtmlSanitizer; + private final CustomPDFDocumentFactory pdfDocumentFactory; + + private static final List EXTENSIONS = List.of(TablesExtension.create()); + + /** Render to PDF, or return null if the conversion runtime isn't available. */ + public byte[] tryRender(String markdown) { + try { + return render(markdown); + } catch (Exception e) { + org.slf4j.LoggerFactory.getLogger(AgreementPdfRenderer.class) + .warn( + "[legal] agreement PDF render unavailable; recording signature without a" + + " stored PDF: {}", + e.getMessage()); + return null; + } + } + + private byte[] render(String markdown) throws Exception { + Parser parser = Parser.builder().extensions(EXTENSIONS).build(); + Node document = parser.parse(markdown); + HtmlRenderer renderer = HtmlRenderer.builder().extensions(EXTENSIONS).build(); + String html = renderer.render(document); + + byte[] pdfBytes = + FileToPdf.convertHtmlToPdf( + runtimePathConfig.getWeasyPrintPath(), + null, + html.getBytes(StandardCharsets.UTF_8), + "agreement.html", + tempFileManager, + customHtmlSanitizer); + return pdfDocumentFactory.createNewBytesBasedOnOldDocument(pdfBytes); + } +} diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementSigning.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementSigning.java new file mode 100644 index 0000000000..600ecda415 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AgreementSigning.java @@ -0,0 +1,12 @@ +package stirling.software.saas.procurement.legal; + +/** + * The buyer-supplied inputs captured at the moment of signing the enterprise agreement: the legal + * entity name, the signatory's typed name and title, and their representation of authority to bind. + * Null when the agreement is rendered for preview (before signing). + */ +public record AgreementSigning( + String customerLegalName, + String signatoryName, + String signatoryTitle, + boolean authorityConfirmed) {} diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/legal/AssembledAgreement.java b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AssembledAgreement.java new file mode 100644 index 0000000000..3e88cf555a --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/procurement/legal/AssembledAgreement.java @@ -0,0 +1,16 @@ +package stirling.software.saas.procurement.legal; + +/** + * A rendered enterprise agreement: the full markdown the buyer sees (MSA + Order Form + DPA, tokens + * filled), plus the registry metadata that pins it. {@code variablesJson} is the exact set of + * Order-Form values as rendered, stored alongside a signature so the document is reproducible. + */ +public record AssembledAgreement( + String docId, + String version, + String versionLabel, + String displayName, + String effectiveDate, + String status, + String markdown, + String variablesJson) {} diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementAgreementSignature.java b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementAgreementSignature.java new file mode 100644 index 0000000000..425b100ba9 --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementAgreementSignature.java @@ -0,0 +1,86 @@ +package stirling.software.saas.procurement.model; + +import java.io.Serializable; +import java.time.LocalDateTime; + +import org.hibernate.annotations.CreationTimestamp; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * An immutable record of a signed enterprise agreement. Each signature pins the exact legal + * document it was signed against — {@code documentId} + {@code documentVersion} + a SHA-256 {@code + * contentHash} of the rendered markdown — plus the Order-Form variable snapshot and the typed + * signatory details, so the agreement stays reproducible even after the templates version up. The + * rendered PDF is stored when the conversion runtime is available. + */ +@Entity +@Table(name = "procurement_agreement_signature") +@NoArgsConstructor +@Getter +@Setter +public class ProcurementAgreementSignature implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "signature_id") + private Long signatureId; + + @Column(name = "deal_id", nullable = false) + private Long dealId; + + @Column(name = "quote_id", nullable = false) + private Long quoteId; + + // Which legal document, and which version of it, was signed. + @Column(name = "document_id", nullable = false, length = 64) + private String documentId; + + @Column(name = "document_version", nullable = false, length = 32) + private String documentVersion; + + @Column(name = "document_label", length = 64) + private String documentLabel; + + // SHA-256 (hex) of the exact rendered agreement markdown the buyer accepted. + @Column(name = "content_hash", nullable = false, length = 64) + private String contentHash; + + // The Order-Form variable values as rendered, so the document can be reproduced. + @Column(name = "variables_json", columnDefinition = "text") + private String variablesJson; + + @Column(name = "customer_legal_name", length = 255) + private String customerLegalName; + + @Column(name = "signatory_name", nullable = false, length = 255) + private String signatoryName; + + @Column(name = "signatory_title", length = 255) + private String signatoryTitle; + + @Column(name = "authority_confirmed", nullable = false) + private boolean authorityConfirmed; + + @Column(name = "signer_ip", length = 64) + private String signerIp; + + // The rendered PDF artifact; null when the conversion runtime was unavailable at signing. + @Column(name = "pdf") + private byte[] pdf; + + @CreationTimestamp + @Column(name = "signed_at", nullable = false, updatable = false) + private LocalDateTime signedAt; +} diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementDeal.java b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementDeal.java index 3a5d3db902..f0db2fb6db 100644 --- a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementDeal.java +++ b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementDeal.java @@ -34,6 +34,13 @@ public class ProcurementDeal implements Serializable { private static final long serialVersionUID = 1L; + /** + * Interest, before any commitment: the account asked about enterprise but has not started a + * trial. Kept as a real stage so intent survives a refresh, so the enterprise surface is only + * shown to accounts that asked for it, and so drop-off at the cheapest step is measurable. + */ + public static final String STAGE_EXPLORING = "exploring"; + public static final String STAGE_TRIAL = "trial"; public static final String STAGE_QUOTE = "quote"; public static final String STAGE_AGREEMENT = "security"; @@ -69,12 +76,38 @@ public class ProcurementDeal implements Serializable { @Column(name = "trial_extensions_used", nullable = false) private int trialExtensionsUsed; + // Captured at trial setup, so the buying entity is known before any quote exists — the quote's + // own copies seed from these and may then diverge (a deal can change hands mid-cycle). + // Nullable: trials started before this step, and older clients, supply none. + @Column(name = "business_name", length = 255) + private String businessName; + + @Column(name = "contact_name", length = 255) + private String contactName; + + @Column(name = "contact_email", length = 320) + private String contactEmail; + + // Addresses the buyer named at setup. Kept as the record of what was asked for; the invitations + // themselves go out through the team-invite path when the trial starts. + @Column(name = "invite_emails", length = 2000) + private String inviteEmails; + @Column(name = "license_ref", length = 128) private String licenseRef; @Column(name = "subscription_id", length = 255) private String subscriptionId; + /** + * The last Stripe invoice whose payment was applied to this deal. Distinguishes a redelivered + * {@code invoice.paid} for a payment already handled from a genuine renewal, which has to + * re-issue: the committed licence expires term years from issue, so a renewal that doesn't + * re-issue leaves the licence lapsing after the customer has paid. + */ + @Column(name = "last_paid_invoice_id", length = 255) + private String lastPaidInvoiceId; + @Column(name = "accepted_quote_id") private Long acceptedQuoteId; diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementQuote.java b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementQuote.java index aa94128172..19e9e01004 100644 --- a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementQuote.java +++ b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementQuote.java @@ -47,7 +47,11 @@ public class ProcurementQuote implements Serializable { @Column(name = "deal_id", nullable = false) private Long dealId; - @Column(name = "quote_number", nullable = false, length = 64) + /** + * Stripe's quote number, the deal's one buyer-facing reference. Null until the quote is issued: + * Stripe assigns it at finalisation, and the issue edge function writes it back then. + */ + @Column(name = "quote_number", length = 64) private String quoteNumber; @Column(name = "status", nullable = false, length = 24) diff --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.java index 08ade5a157..5d1234e9fc 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 @@ -60,12 +60,7 @@ public class ProcurementPricingService { rates.discountPerDoubling() * (Math.log(runVol / (double) RUN_CURVE_KNEE) / LOG2)) : 0.0; - double rate = Math.max(rates.floorRatePerRun(), rates.listRatePerRun() * (1.0 - volDisc)); - // File-size multiplier (D93): larger, image-heavy PDFs cost more OCR/compute/storage. Folds - // into the per-run rate after the floor, so it flows through the meter, TCV and renewal. - // QuoteConfig has already snapped it to a known tier, so a tampered request can't sneak a - // cheaper factor in. - rate *= cfg.sizeMult(); + double rate = perRunRate(cfg, rates); double termDisc = rates.termDiscount(cfg.termYears()); // The meter is a whole-dollar figure (the quote reads in dollars), then minor units. @@ -160,6 +155,48 @@ public class ProcurementPricingService { return new QuoteBreakdown(lines, annualNet, tcv, renewalAnnual, cfg.currency()); } + /** + * The per-run rate after the committed-volume curve, the half-cent floor, and the file-size + * multiplier — the same value {@link #price} meters against. Extracted so read-only callers + * (the Order Form) can quote it without re-deriving the curve. + */ + private static double perRunRate(QuoteConfig cfg, PricingRates rates) { + long runVol = Math.max(0, cfg.volume()) * (long) Math.max(1, cfg.intensity()); + double volDisc = + runVol > RUN_CURVE_KNEE + ? Math.min( + 0.5, + rates.discountPerDoubling() + * (Math.log(runVol / (double) RUN_CURVE_KNEE) / LOG2)) + : 0.0; + return Math.max(rates.floorRatePerRun(), rates.listRatePerRun() * (1.0 - volDisc)) + * cfg.sizeMult(); + } + + /** + * The effective per-PDF rate at the chosen posture, in dollars (4-decimal quote figure). This + * is what the Order Form and quote copy speak in — never the per-run rate. Read-only; does not + * affect billing. + */ + public double effectiveRatePerPdf(QuoteConfig cfg) { + return perRunRate(cfg, PricingRates.defaults()) * Math.max(1, cfg.intensity()); + } + + /** The multi-year term discount as a whole-percent figure for the Order Form (0.05 → 5). */ + public int termDiscountPct(int termYears) { + return (int) Math.round(PricingRates.defaults().termDiscount(termYears) * 100.0); + } + + /** Buyer-facing posture name (Essentials / Governed / Regulated) for the given intensity. */ + public static String postureName(int intensity) { + return postureLabel(intensity); + } + + /** Buyer-facing deployment name (Stirling Cloud / Self-hosted / Air-gapped). */ + public static String deploymentName(String deployment) { + return deploymentLabel(deployment); + } + /** The default CPI escalator (fraction) applied to the annual fee on each post-term renewal. */ public double cpiEscalator() { return PricingRates.defaults().cpiEscalator(); diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementAgreementSignatureRepository.java b/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementAgreementSignatureRepository.java new file mode 100644 index 0000000000..419189617e --- /dev/null +++ b/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementAgreementSignatureRepository.java @@ -0,0 +1,29 @@ +package stirling.software.saas.procurement.repository; + +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import stirling.software.saas.procurement.model.ProcurementAgreementSignature; + +public interface ProcurementAgreementSignatureRepository + extends JpaRepository { + + Optional findFirstByDealIdOrderBySignedAtDesc(Long dealId); + + Optional findFirstByQuoteIdOrderBySignedAtDesc(Long quoteId); + + /** + * Version labels of a deal's signatures, newest first. Projects just the label column so the + * frequently-polled snapshot never loads the PDF bytes. A signature means the agreement is + * signed; the PDF is resolved (stored or re-rendered) at download time. + */ + @Query( + "SELECT s.documentLabel FROM ProcurementAgreementSignature s" + + " WHERE s.dealId = :dealId" + + " ORDER BY s.signedAt DESC") + List findSignedLabels(@Param("dealId") Long dealId); +} 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.java index cae1cf36fb..a739e538b2 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 @@ -5,7 +5,6 @@ import java.time.LocalDateTime; import java.util.List; import java.util.Locale; import java.util.Optional; -import java.util.UUID; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; @@ -20,16 +19,24 @@ import stirling.software.common.model.enumeration.TeamRole; import stirling.software.proprietary.model.TeamMembership; import stirling.software.proprietary.security.repository.TeamMembershipRepository; import stirling.software.saas.procurement.config.ProcurementConfigurationProperties; +import stirling.software.saas.procurement.legal.AgreementAssembler; +import stirling.software.saas.procurement.legal.AgreementPdfRenderer; +import stirling.software.saas.procurement.legal.AgreementSigning; +import stirling.software.saas.procurement.legal.AssembledAgreement; import stirling.software.saas.procurement.license.EnterpriseLicenseService; import stirling.software.saas.procurement.license.LicenseEntitlements; +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.ProcurementPricingService; import stirling.software.saas.procurement.pricing.QuoteBreakdown; import stirling.software.saas.procurement.pricing.QuoteConfig; +import stirling.software.saas.procurement.repository.ProcurementAgreementSignatureRepository; import stirling.software.saas.procurement.repository.ProcurementDealRepository; import stirling.software.saas.procurement.repository.ProcurementQuoteRepository; +import stirling.software.saas.service.SaasTeamService; +import stirling.software.saas.util.LogRedactionUtils; /** * Orchestrates a linked team's procurement journey: start a (mock-licensed) trial, build a @@ -52,6 +59,12 @@ public class ProcurementService { private final EnterpriseLicenseService licenses; private final ProcurementConfigurationProperties config; private final TeamMembershipRepository memberRepo; + private final AgreementAssembler agreementAssembler; + private final AgreementPdfRenderer agreementPdfRenderer; + private final ProcurementAgreementSignatureRepository signatureRepo; + // Trial-setup invitations run through the team-invite path, with its seat, role and + // rate-limit rules rather than a second implementation here. + private final SaasTeamService teams; public ProcurementService( ProcurementDealRepository dealRepo, @@ -59,13 +72,21 @@ public class ProcurementService { ProcurementPricingService pricing, EnterpriseLicenseService licenses, ProcurementConfigurationProperties config, - TeamMembershipRepository memberRepo) { + TeamMembershipRepository memberRepo, + AgreementAssembler agreementAssembler, + AgreementPdfRenderer agreementPdfRenderer, + ProcurementAgreementSignatureRepository signatureRepo, + SaasTeamService teams) { this.dealRepo = dealRepo; this.quoteRepo = quoteRepo; this.pricing = pricing; this.licenses = licenses; this.config = config; this.memberRepo = memberRepo; + this.agreementAssembler = agreementAssembler; + this.agreementPdfRenderer = agreementPdfRenderer; + this.signatureRepo = signatureRepo; + this.teams = teams; } /** @@ -89,11 +110,45 @@ public class ProcurementService { return dealRepo.findByTeamId(teamId); } + /** + * Starting a trial is only legitimate before one exists, while the buyer is still exploring, or + * to restart within the trial itself. A null stage is a deal that has just been constructed. + * + *

Package-private so the policy can be tested without the service's ten dependencies. Adding + * a later stage here would let a leader replace a paying customer's committed licence. + */ + static boolean canStartTrial(String stage) { + return stage == null + || ProcurementDeal.STAGE_EXPLORING.equals(stage) + || ProcurementDeal.STAGE_TRIAL.equals(stage); + } + @Transactional(readOnly = true) public List quotesForDeal(Long dealId) { return quoteRepo.findByDealIdOrderByCreatedAtDesc(dealId); } + /** + * Record that the account is looking at enterprise. Creates the deal at {@code exploring} when + * there is none; an existing deal is returned untouched, so this can never walk a live deal + * backwards or restart a trial. + */ + @Transactional + public ProcurementDeal recordInterest(Long teamId) { + return dealRepo.findByTeamId(teamId) + .orElseGet( + () -> { + ProcurementDeal deal = new ProcurementDeal(teamId); + deal.setStage(ProcurementDeal.STAGE_EXPLORING); + ProcurementDeal saved = dealRepo.save(deal); + log.info( + "[procurement] interest recorded team={} deal={}", + teamId, + saved.getDealId()); + return saved; + }); + } + /** * Start (or restart) the free trial for a team: issue a mock trial licence and stamp the trial * window on the deal. No Stripe: a no-card trial has no subscription; the entitlement is the @@ -101,10 +156,40 @@ public class ProcurementService { * ({@code cloud}/{@code selfhost}/{@code airgap}) and seat count are captured here so the quote * builder opens seeded to their environment; both are still editable when the quote is built. */ - @Transactional public ProcurementDeal startTrial(Long teamId, String deployment, int seats) { + return startTrial(teamId, deployment, seats, null, null, null, null); + } + + /** + * Start (or restart) the trial, capturing the buying entity if the setup step collected it. + * Blank details are ignored rather than written, so a re-run without them keeps what is there. + * + *

Only from before the trial or during it. Past that, {@code licenseRef} points at the + * committed annual licence, and this method would replace it with a fresh 14-day trial key + * while Stripe kept billing — the same hazard {@link #extendTrial} guards against, one step + * worse because it re-issues rather than re-dates. It would also rewind the stage and reset the + * extension counter. + * + *

The transaction is declared here rather than on the 3-arg overload: that one only + * delegates, and Spring's proxy cannot intercept a self-invocation, so an annotation there does + * nothing for either path. This is the method the controller calls, and it reaches out to + * Keygen between the read and the write. + */ + @Transactional + public ProcurementDeal startTrial( + Long teamId, + String deployment, + int seats, + String businessName, + String contactName, + String contactEmail, + String inviteEmails) { ProcurementDeal deal = dealRepo.findByTeamId(teamId).orElseGet(() -> new ProcurementDeal(teamId)); + if (!canStartTrial(deal.getStage())) { + throw new IllegalStateException( + "Trial cannot be started from stage " + deal.getStage()); + } LocalDateTime now = LocalDateTime.now(); LocalDateTime ends = now.plusDays(config.getTrialDurationDays()); deal.setStage(ProcurementDeal.STAGE_TRIAL); @@ -113,6 +198,10 @@ public class ProcurementService { deal.setTrialStartedAt(now); deal.setTrialEndsAt(ends); deal.setTrialExtensionsUsed(0); + if (isNotBlank(businessName)) deal.setBusinessName(businessName.trim()); + if (isNotBlank(contactName)) deal.setContactName(contactName.trim()); + if (isNotBlank(contactEmail)) deal.setContactEmail(contactEmail.trim()); + if (isNotBlank(inviteEmails)) deal.setInviteEmails(inviteEmails.trim()); deal.setLicenseRef(licenses.issueTrialLicense(teamId, leaderEmail(teamId), ends)); deal = dealRepo.save(deal); log.info( @@ -128,6 +217,45 @@ public class ProcurementService { /** * Constrain a caller-supplied deployment to the known set; anything else falls back to cloud. */ + /** + * Send the invitations named at trial setup. Best-effort per address: a rejection (already a + * member, an invitee with their own paid plan, the hourly rate limit) must not fail the trial, + * so each is logged and skipped rather than propagated. + * + *

Note the first accepted invitation converts a personal team into a shared one with + * unlimited seats — that is {@code inviteUserToTeam}'s own rule, and naming teammates here is + * the buyer asking for exactly that. + */ + public void sendTrialInvites( + Long teamId, stirling.software.proprietary.security.model.User inviter, String emails) { + if (inviter == null || !isNotBlank(emails)) return; + for (String raw : emails.split("[,;\s]+")) { + String email = raw.trim(); + if (email.isEmpty()) continue; + try { + teams.inviteUserToTeam(teamId, email, inviter); + // Redacted: an invitee list is third-party PII, and these logs are the one place it + // would otherwise be written in full. LogRedactionUtils is what the rest of the + // SaaS + // module uses for the same reason. + log.info( + "[procurement] trial invite sent team={} to={}", + teamId, + LogRedactionUtils.redactEmail(email)); + } catch (Exception e) { + log.warn( + "[procurement] trial invite skipped team={} to={}: {}", + teamId, + LogRedactionUtils.redactEmail(email), + e.getMessage()); + } + } + } + + private static boolean isNotBlank(String value) { + return value != null && !value.isBlank(); + } + private static String normalizeDeployment(String deployment) { if (deployment == null) return "cloud"; String d = deployment.trim().toLowerCase(Locale.ROOT); @@ -172,16 +300,32 @@ public class ProcurementService { } // (Re)building a quote returns the deal to the quote stage and drops any prior acceptance, // so a rebuild from security/payment can't leave a stale stage or accepted-quote pointer. + QuoteBreakdown breakdown = pricing.price(cfg); + // Enforced before anything is persisted, and server-side rather than in the builder: the + // pricing curve has no natural floor (a small enough committed volume rounds the meter to + // zero) and every registered user leads their own team, so without this any signup could + // 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( + "Quoted annual fee " + + breakdown.annualNetMinor() + + " is below the minimum enterprise deal size " + + floor); + } + deal.setStage(ProcurementDeal.STAGE_QUOTE); deal.setAcceptedQuoteId(null); deal = dealRepo.save(deal); - QuoteBreakdown breakdown = pricing.price(cfg); - ProcurementQuote quote = new ProcurementQuote(); quote.setDealId(deal.getDealId()); - quote.setQuoteNumber(nextQuoteNumber(deal.getDealId())); - // Priced but not yet issued: the edge fn creates the Stripe Quote and flips this to SENT. + // No quote number here: the deal's one reference is Stripe's, and Stripe does not assign it + // until the quote is finalised. The edge fn creates the Stripe Quote, flips this to SENT, + // and + // writes the number back. Nothing displays a reference in between — the builder only shows + // one + // for an issued quote, and the agreement is not assembled until after issue. quote.setStatus(ProcurementQuote.STATUS_DRAFT); quote.setCurrency(cfg.currency()); quote.setVolume(cfg.volume()); @@ -210,10 +354,11 @@ public class ProcurementService { quote.setLineItemsJson(writeLineItems(breakdown)); quote.setValidUntil(LocalDate.now().plusDays(30)); quote = quoteRepo.save(quote); + // Logged by id, not reference: a draft has no reference until Stripe issues it. log.info( "[procurement] quote built team={} quote={} annualNet={} tcv={}", teamId, - quote.getQuoteNumber(), + quote.getQuoteId(), quote.getAnnualNetMinor(), quote.getTcvMinor()); return quote; @@ -241,6 +386,164 @@ public class ProcurementService { return deal; } + /** The quote a team is currently transacting on: its accepted quote, else the most recent. */ + @Transactional(readOnly = true) + public Optional currentQuote(Long teamId) { + return dealRepo.findByTeamId(teamId) + .flatMap( + deal -> { + if (deal.getAcceptedQuoteId() != null) { + Optional accepted = + quoteRepo.findById(deal.getAcceptedQuoteId()); + if (accepted.isPresent()) return accepted; + } + return quoteRepo + .findByDealIdOrderByCreatedAtDesc(deal.getDealId()) + .stream() + .findFirst(); + }); + } + + /** + * The filled enterprise agreement for a team's current quote, rendered for review (unsigned). + */ + @Transactional(readOnly = true) + public Optional agreementDocument(Long teamId) { + return currentQuote(teamId).map(q -> agreementAssembler.assemble(q, null)); + } + + /** + * The current (unsigned) agreement rendered to PDF, for download at the sign step. Empty when + * there's no quote yet or the render runtime is unavailable. The signed PDF (with the signature + * block filled) is a separate artifact recorded at signing (see {@link #latestSignature}). + */ + @Transactional(readOnly = true) + public Optional agreementDocumentPdf(Long teamId) { + return currentQuote(teamId) + .map(q -> agreementAssembler.assemble(q, null)) + .map(a -> agreementPdfRenderer.tryRender(a.markdown())); + } + + /** + * Record a signed enterprise agreement: assemble the final document, hash it, render + store + * the PDF (best-effort), and persist an immutable signature pinned to the exact document + * version. Does not itself accept the quote into a subscription — the caller proceeds to accept + * as before. + * + *

Deliberately not {@code @Transactional}: rendering the PDF shells out to WeasyPrint, and + * holding the deal's row lock across an external process buys nothing here. The only write is a + * single insert, which {@code save} makes atomic on its own. + */ + public ProcurementAgreementSignature signAgreement( + Long teamId, AgreementSigning signing, String signerIp) { + ProcurementDeal deal = + dealRepo.findByTeamId(teamId) + .orElseThrow(() -> new IllegalStateException("No deal for team " + teamId)); + ProcurementQuote quote = + currentQuote(teamId) + .orElseThrow( + () -> + new IllegalStateException( + "No quote to sign for team " + teamId)); + + // Signing is only meaningful against an issued quote at the agreement stage. Without this a + // direct API call could record a signature over a draft (whose quote_ref is still empty), + // or + // re-sign a deal that has already moved on. + if (!ProcurementDeal.STAGE_AGREEMENT.equals(deal.getStage())) { + throw new IllegalStateException( + "Deal is not at the agreement stage for team " + teamId); + } + if (!ProcurementQuote.STATUS_SENT.equals(quote.getStatus())) { + throw new IllegalStateException("Quote is not issued for team " + teamId); + } + + AssembledAgreement assembled = agreementAssembler.assemble(quote, signing); + + ProcurementAgreementSignature sig = new ProcurementAgreementSignature(); + sig.setDealId(deal.getDealId()); + sig.setQuoteId(quote.getQuoteId()); + sig.setDocumentId(assembled.docId()); + sig.setDocumentVersion(assembled.version()); + sig.setDocumentLabel(assembled.versionLabel()); + sig.setContentHash(sha256(assembled.markdown())); + sig.setVariablesJson(assembled.variablesJson()); + sig.setCustomerLegalName(signing.customerLegalName()); + sig.setSignatoryName(signing.signatoryName()); + sig.setSignatoryTitle(signing.signatoryTitle()); + sig.setAuthorityConfirmed(signing.authorityConfirmed()); + sig.setSignerIp(signerIp); + sig.setPdf(agreementPdfRenderer.tryRender(assembled.markdown())); + sig = signatureRepo.save(sig); + log.info( + "[procurement] agreement signed team={} quote={} doc={} pdf={}", + teamId, + quote.getQuoteId(), + assembled.versionLabel(), + sig.getPdf() != null); + return sig; + } + + /** The latest recorded signature for a team's deal, if any (for the signed-PDF download). */ + @Transactional(readOnly = true) + public Optional latestSignature(Long teamId) { + return dealRepo.findByTeamId(teamId) + .flatMap( + deal -> + signatureRepo.findFirstByDealIdOrderBySignedAtDesc( + deal.getDealId())); + } + + /** + * The version label of the deal's latest signed agreement, if any. Used to surface the + * "download signed agreement" action once a signature exists; the snapshot polls this, so it + * deliberately avoids loading the PDF bytes. + * + *

Deliberately not conditional on a stored PDF: download re-renders from the pinned document + * version on demand, so the action works whether or not the render succeeded at signing time. + */ + @Transactional(readOnly = true) + public Optional signedAgreementLabel(Long dealId) { + return signatureRepo.findSignedLabels(dealId).stream().findFirst(); + } + + /** + * The signed agreement as a PDF for download: the artifact stored at signing, or — if the + * render runtime was unavailable then — re-rendered now from the signature's details. Empty + * when the team has no signature or the render runtime is still unavailable. + */ + @Transactional(readOnly = true) + public Optional signedAgreementPdf(Long teamId) { + return latestSignature(teamId) + .flatMap( + sig -> { + if (sig.getPdf() != null) return Optional.of(sig.getPdf()); + return quoteRepo + .findById(sig.getQuoteId()) + .map( + q -> + agreementAssembler.assemble( + q, + new AgreementSigning( + sig.getCustomerLegalName(), + sig.getSignatoryName(), + sig.getSignatoryTitle(), + sig.isAuthorityConfirmed()))) + .map(a -> agreementPdfRenderer.tryRender(a.markdown())); + }); + } + + private static String sha256(String s) { + try { + byte[] digest = + java.security.MessageDigest.getInstance("SHA-256") + .digest(s.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return java.util.HexFormat.of().formatHex(digest); + } catch (java.security.NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 unavailable", e); + } + } + /** * Provision on accept: upgrade the team's licence to the committed annual term (valid * immediately), so the buyer can get going the moment they accept — before the invoice is paid. @@ -260,22 +563,58 @@ public class ProcurementService { } /** - * Mark the deal fully live (advance to the active stage) once payment settles. In production - * this is the {@code invoice.paid} webhook; here it's the demo/manual stand-in. Re-affirms the + * Mark the deal fully live (advance to the active stage) once payment settles — driven by the + * {@code invoice.paid} webhook, and by the demo control when those are enabled. Re-affirms the * annual licence in case provisioning didn't run at accept. + * + *

Idempotent per invoice rather than per stage, which matters because {@code invoice.paid} + * carries two different meanings. Stripe redelivers events, so the same invoice + * arriving twice must do nothing. But the renewal payment a year later is also an {@code + * invoice.paid}, and the committed licence expires term years from issue — so a + * different invoice has to re-issue, moving the expiry out, or the customer's licence + * lapses after they have paid. Keying on the stage alone couldn't tell those apart and treated + * every renewal as a duplicate. + * + * @param paidInvoiceId the Stripe invoice that was paid, or null when the caller has no invoice + * to identify the payment by (the demo control). Null keeps the old conservative behaviour: + * a live deal short-circuits, since there is nothing to tell a renewal from a repeat. */ @Transactional - public ProcurementDeal markLive(Long teamId) { + public ProcurementDeal markLive(Long teamId, String paidInvoiceId) { ProcurementDeal deal = dealRepo.findByTeamId(teamId) .orElseThrow(() -> new IllegalStateException("No deal for team " + teamId)); + if (ProcurementDeal.STAGE_LIVE.equals(deal.getStage()) + && (paidInvoiceId == null || paidInvoiceId.equals(deal.getLastPaidInvoiceId()))) { + log.debug( + "[procurement] invoice.paid already applied team={} deal={} invoice={}", + teamId, + deal.getDealId(), + paidInvoiceId); + return deal; + } + boolean renewal = ProcurementDeal.STAGE_LIVE.equals(deal.getStage()); deal.setLicenseRef(issueOrUpgradeAnnual(deal)); + if (paidInvoiceId != null) deal.setLastPaidInvoiceId(paidInvoiceId); deal.setStage(ProcurementDeal.STAGE_LIVE); deal = dealRepo.save(deal); - log.info("[procurement] deal live team={} deal={}", teamId, deal.getDealId()); + log.info( + "[procurement] deal live team={} deal={} renewal={} invoice={}", + teamId, + deal.getDealId(), + renewal, + paidInvoiceId); return deal; } + /** + * Go live with no invoice reference — the demo control. See {@link #markLive(Long, String)}. + */ + @Transactional + public ProcurementDeal markLive(Long teamId) { + return markLive(teamId, null); + } + /** * Issue or upgrade the committed annual licence from the deal's accepted (else latest) quote, * stamping the full entitlement snapshot onto it and upgrading the trial licence in place when @@ -327,15 +666,34 @@ public class ProcurementService { * before paying — that's bounded: the trial licence carries {@code expiry = trialEndsAt}, so * the file the verifier accepts self-expires at trial end. The buyer must re-download after * provisioning to get the committed-term file (the portal warns about this). + * + *

Once a quote exists, the quote's deployment decides — not the deal's. They are two + * different values: the deal's is chosen free at trial setup, the quote's is the one carrying + * the air-gap deploy fee. Reading the deal's here meant selecting air-gapped in the trial and + * then buying a cloud quote still yielded the offline file, and after provisioning it was + * checked out against the committed annual licence — so the self-expiry above no longer bounded + * it. */ @Transactional(readOnly = true) public Optional offlineLicenseFile(Long teamId) { ProcurementDeal deal = dealRepo.findByTeamId(teamId).orElse(null); if (deal == null || deal.getLicenseRef() == null) return Optional.empty(); - if (!"airgap".equalsIgnoreCase(deal.getDeployment())) return Optional.empty(); + if (!"airgap".equalsIgnoreCase(entitledDeployment(deal))) return Optional.empty(); return Optional.of(licenses.checkOutLicenseFile(deal.getLicenseRef())); } + /** + * The deployment the team is actually entitled to: the priced quote's once one exists, + * 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); + if (quote != null && quote.getDeployment() != null && !quote.getDeployment().isBlank()) { + return quote.getDeployment(); + } + return deal.getDeployment(); + } + /** * Reset a team's procurement: delete the deal (quotes + activity cascade). For * re-demos/testing. @@ -346,12 +704,6 @@ public class ProcurementService { log.info("[procurement] deal reset team={}", teamId); } - private String nextQuoteNumber(Long dealId) { - int seq = quoteRepo.findByDealIdOrderByCreatedAtDesc(dealId).size() + 1; - String token = UUID.randomUUID().toString().substring(0, 4).toUpperCase(Locale.ROOT); - return String.format(Locale.ROOT, "QT-%s-%04d", token, seq); - } - private String writeLineItems(QuoteBreakdown breakdown) { try { return OBJECT_MAPPER.writeValueAsString(breakdown.lineItems()); diff --git a/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/dpa.md b/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/dpa.md new file mode 100644 index 0000000000..12cceaef65 --- /dev/null +++ b/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/dpa.md @@ -0,0 +1,53 @@ +## Part C — Data Processing Addendum + +This DPA forms part of the Agreement and applies where Provider processes Personal Data on Customer's behalf. + +### C1. Roles; scope; instructions + +Customer is the controller (or a processor on behalf of its own controllers); Provider is a processor (or subprocessor, as applicable). Provider processes Personal Data only on Customer's documented instructions — including processing initiated by Customer's users, policies, pipelines, and API calls — unless required by law (in which case Provider informs Customer unless legally prohibited). **Provider will inform Customer without undue delay if, in Provider's opinion, an instruction infringes the GDPR, UK GDPR, or other applicable data-protection law.** Customer is responsible for the lawfulness of the Personal Data it submits and the instructions it gives; Customer's rights under this DPA include instruction, audit (C9), objection to subprocessors (C5), assistance (C6), and return or deletion of data (C10). + +### C2. Details of processing + +**Subject matter/nature:** PDF processing and governance (classification, redaction, routing, retention, conversion, signing, extraction, AI-assisted analysis). **Duration:** the Term plus the deletion period. **Categories of data:** any Personal Data contained in Customer files and metadata (names, contact details, identifiers, financial or health data if present in Customer files), account data of Customer users. **Data subjects:** Customer's employees, users, customers, and other persons appearing in Customer files. **Sensitive data:** may be present in Customer files at Customer's discretion; Customer is responsible for the lawful basis. + +### C3. Confidentiality; personnel + +Provider ensures persons authorized to process Personal Data are bound by confidentiality and receive security training. Zero-standing-access applies: content access is just-in-time, logged, and audited (MSA Section 4.2). + +### C4. Security measures (Annex II summary) + +Encryption in transit (TLS 1.2+) and at rest (AES-256); zero-standing-access with audited JIT elevation; role-based access control; SSO/SCIM; tenant isolation; vulnerability management and penetration testing; audit logging of processing events (including file name, hash, size, and operations); backup and recovery. For Self-hosted and Air-gapped deployments, Customer operates the runtime environment and is responsible for infrastructure-level controls; Provider's measures apply to license/metering services and support access. + +### C5. Subprocessors + +Customer generally authorizes the subprocessors listed at {{subprocessor_url}}: cloud infrastructure (Amazon Web Services), payment processing (Stripe, as independent controller for payment data), email delivery (Google), account infrastructure (Supabase), product telemetry (PostHog, EU-hosted; pseudonymous usage events, never file content), and AI model providers: **Anthropic** (Claude models — receives prompts and the document text or excerpts needed for the requested AI feature) and **Voyage AI** (embedding models — receives extracted text excerpts solely to generate embeddings where Customer enables Ingestion/RAG features). AI features are optional and may be disabled; where used, AI providers receive only the content needed for the requested feature. **Whole Customer files are never transmitted to any AI provider.** Neither AI provider trains on Customer data (verified against the signed provider agreements, Jul 10, 2026). Provider gives thirty (30) days' notice of new subprocessors; Customer may object on reasonable data-protection grounds, and if unresolved, may terminate the affected Services with a pro-rata refund. **Provider imposes data-protection obligations on each subprocessor by written contract that are at least as protective as this DPA, and remains fully responsible to Customer for each subprocessor's performance.** + +### C6. Data subject requests; assistance + +Taking into account the nature of the processing, Provider provides reasonable assistance (including through the Processor's search, redaction, and audit tools) for Customer's obligations under GDPR Articles 32–36: security of processing, breach notification to authorities and data subjects, data protection impact assessments, and prior consultations with supervisory authorities, as well as responses to data subject requests. Provider forwards requests received directly to Customer and does not respond except as legally required. **Provider makes available to Customer all information necessary to demonstrate compliance with this DPA and allows for and contributes to audits, including inspections, per Section C9.** + +### C7. Breach notification + +Per MSA Section 5.3: without undue delay after becoming aware of a Personal Data Breach, and in any event within forty-eight (48) hours of awareness, with information provided in phases as available — including the nature of the breach, categories and approximate volumes affected, likely consequences, and measures taken or proposed. + +### C8. International transfers + +Where Personal Data subject to GDPR/UK GDPR is transferred to countries without adequacy, the Parties incorporate the EU Standard Contractual Clauses (Commission Decision 2021/914): **Module 2** (controller-to-processor) where Customer is a controller, and **Module 3** (processor-to-processor) where Customer acts as a processor, with the following selections — Clause 7 (docking): included; Clause 9(a): Option 2 (general written authorization, 30 days' notice per C5); Clause 11(a) optional language: not used; Clause 17: the law of Ireland; Clause 18: the courts of Ireland; competent supervisory authority: the Irish Data Protection Commission (per Annex I.C). Annex I (parties, description of transfer: as per Section C2), Annex II (technical and organizational measures: as per Section C4), and Annex III (subprocessors: as per Section C5 and {{subprocessor_url}}) are completed by reference to this DPA. For UK transfers, the UK International Data Transfer Addendum applies with its Tables completed by reference to the foregoing. Provider is not certified under the EU-U.S. Data Privacy Framework; the SCCs are the transfer mechanism. + +**Note:** Provider does not currently offer contractual EU data residency for Stirling Cloud; residency is achieved via Self-hosted or Air-gapped deployment. + +### C9. Audits + +Provider's security reports and documentation (Section 5.1) are the ordinary means of demonstrating compliance. Customer may additionally audit — by itself or a mandated auditor — once per year on thirty (30) days' notice, and at any time where: (a) a security incident affecting Customer Personal Data has occurred; (b) provided documentation reveals a material deficiency; (c) a competent supervisory authority requires it; or (d) Customer reasonably suspects material noncompliance with this DPA. Audits are conducted during business hours, under confidentiality, at Customer's cost, with reasonable notice, without unreasonable interference with Provider's operations, and without access to other customers' data. + +### C10. Return & deletion + +On termination, at Customer's choice, Provider returns Customer file content and Personal Data (export of Customer files and the governed-record metadata) and/or deletes them — from live systems within thirty (30) days and from backups within ninety (90) days — except as retention is required by law, and certifies deletion on request. Where Customer uses HYOK, key destruction by Customer renders content cryptographically inaccessible immediately. + +### C11. CCPA/CPRA + +Provider is a "service provider" under the CCPA/CPRA. Provider: (a) processes Personal Information only for the business purposes specified in this Agreement — providing, securing, metering, and supporting the Services described in Section C2; (b) shall not sell or share Personal Information; (c) shall not retain, use, or disclose it for any purpose other than those business purposes, or outside the direct business relationship between the Parties; (d) shall not combine it with Personal Information received from other sources, except as permitted by CCPA regulations for the business purposes; (e) provides the same level of privacy protection required of businesses by the CCPA; (f) will notify Customer if it determines it can no longer meet its CCPA obligations; (g) grants Customer the right, upon reasonable notice, to take reasonable and appropriate steps to ensure Provider's use of Personal Information is consistent with Customer's obligations, and to stop and remediate any unauthorized use; and (h) flows these requirements down to its subprocessors per Section C5. Provider certifies that it understands these restrictions and will comply with them. + +### C12. Liability + +Liability under this DPA is subject to the MSA's limitations (Section 8). diff --git a/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/msa.md b/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/msa.md new file mode 100644 index 0000000000..cd3f6742eb --- /dev/null +++ b/app/saas/src/main/resources/legal/enterprise-agreement/0.9.1/msa.md @@ -0,0 +1,119 @@ +# Stirling Enterprise Agreement + +One signature executes all three parts: the Master Services Agreement (Part A), the Order Form (Part B), and the Data Processing Addendum (Part C). The Stirling EULA & Commercial Terms is incorporated by reference. + +## Part A — Master Services Agreement + +This Master Services Agreement (the "Agreement") is entered into as of {{effective_date}} (the "Effective Date") by and between **Stirling PDF, Inc.**, a Delaware corporation with offices at 548 Market Street PMB 887643, San Francisco, CA 94104 ("Provider"), and **{{customer_legal_name}}** ("Customer"). Each a "Party," together the "Parties." + +### 1. Services & License + +1.1 **The Services.** Provider will provide the Stirling PDF Processor (the "Processor") — the hosted or customer-deployed platform for distributing PDF editors and governing PDF processing, including policies, pipelines, the Stirling Agent, API access, and the administrative console — and the Stirling PDF Editor (the "Editor"), as described in the Order Form. + +1.2 **License grants.** Provider grants Customer, for the Term: (a) a non-exclusive, non-transferable right to access and use the Processor for Customer's internal business operations, up to the Committed Volume; and (b) a non-exclusive right to deploy and distribute the Editor to Customer's authorized users without limit on user count. Open-source components of the Editor remain governed by their own licenses, which control for those components. + +1.3 **Deployment.** The Services are delivered via the deployment stated in the Order Form (Stirling Cloud, Self-hosted, or Air-gapped). Self-hosted deployments validate their license and report metering data online; Air-gapped deployments verify a signed activation bundle offline and reconcile usage periodically as described in the Documentation. Customer shall not disable, circumvent, or falsify license validation or usage metering. **The metered rate does not vary by deployment**; deployment-specific services are priced as line items in the Order Form. + +1.4 **Restrictions.** Customer shall not: resell or provide the Services to third parties as a service bureau; reverse engineer non-open-source components; use the Services to violate law; or exceed the scope of the Order Form other than through Overage (Section 3.4). + +### 2. Term & Renewal + +2.1 **Initial Term.** {{term_years}} year(s) from the Effective Date. + +2.2 **Renewal.** The Agreement auto-renews for successive periods equal to the Initial Term unless either Party gives sixty (60) days' written notice of non-renewal before the end of the then-current term. The Annual Fee for each renewal year equals the immediately preceding year's Annual Fee increased by three percent (3%) — the same formula as Section 2.3. Itemized services escalate at the same rate unless restated in a superseding Order Form. + +2.3 **In-term escalator.** The Annual Fee (including itemized services) increases by a fixed three percent (3%) at each anniversary of the Effective Date during the Term. + +### 3. Fees & Payment + +3.1 **Annual Fee.** Customer shall pay the Annual Fee stated in the Order Form, calculated as the Committed Volume ({{committed_pdfs_yr}} PDFs per year) at {{rate_per_pdf}} per PDF at the {{posture}} governance posture, plus the itemized services in the Order Form, less the term discount stated there. + +3.2 **Invoicing.** Fees are invoiced annually in advance, due net thirty (30) days. Late amounts accrue interest at 1.5% per month or the maximum permitted by law, whichever is less. Fees are exclusive of taxes; Customer is responsible for all taxes other than Provider's income taxes. + +3.3 **Committed Volume; measurement.** The Committed Volume is denominated in PDFs processed per year at the stated posture, and converts to a drawdown allowance in PDF Processes at the fixed conversion schedule below, which is frozen for the Term: + +| Posture | PDF Processes per PDF | +| --- | --- | +| Essentials | 2 | +| Governed | 4 | +| Regulated | 7 | + +A **"PDF Process"** is one policy execution, one pipeline run, or one Stirling Agent returned artifact, applied to one file, plus Data Processing increments under Section 3.5. For clarity: a pipeline run counts as one PDF Process regardless of the number of operations in its chain; a Stirling Agent artifact counts as one regardless of the number of messages that produced it; failed processes (those that do not complete) are not counted; reprocessing the same file and duplicate submissions are counted; counts are whole numbers (no rounding). The Processor's audit log records each PDF Process and is the system of record, subject to Section 3.7. Provider will make a per-file usage statement (file identifier, size, processes, drawdown) available for audit. + +**Worked example.** At the Governed posture, a commitment of 90,000,000 PDFs/year provides a drawdown allowance of 360,000,000 PDF Processes. A 60 MB file that runs the four Governed policies draws down 4 PDF Processes plus 2 Data Processing increments (Section 3.5) = 6 PDF Processes. The allowance is a purchased quantity, not a feature limit: Customer may run any number of policies or pipelines; actual consumption simply draws the allowance down faster, and consumption beyond it bills as Overage (Section 3.4). + +3.4 **Overage.** Consumption beyond the Committed Volume in a contract year is billed quarterly in arrears at the committed rate stated in the Order Form. Overage does not increase subsequent years' Committed Volume. + +3.5 **Data Processing.** Each file includes its first twenty-five (25) megabytes (decimal, 1 MB = 1,000,000 bytes) at no additional drawdown. Each additional twenty-five (25) megabytes or part thereof (rounded up per file) draws down one (1) additional PDF Process. File size is measured once per file at ingestion, on the file as submitted. This schedule is stated here in full, is frozen for the Term, and is not subject to alteration through the Documentation. + +3.6 **No refunds.** Except as expressly stated (Sections 7.1, 7.3, 10.3, and DPA Section C5), fees are non-refundable and Committed Volume does not roll over between contract years. + +3.7 **Billing disputes.** Customer may dispute any invoice or metering record in good faith within sixty (60) days of the invoice date. Provider will investigate promptly, provide the relevant audit-log extracts and usage statements, and correct confirmed errors by credit or refund. The audit log is presumptively accurate but not conclusive; Customer may rebut it with reasonable evidence. Undisputed amounts remain payable when due. + +### 4. Data Protection + +4.1 The Data Processing Addendum at Part C (the "DPA") is incorporated into this Agreement and governs Provider's processing of Customer Personal Data, in compliance with the GDPR, UK GDPR, and CCPA/CPRA to the extent applicable. + +4.2 **Zero-standing-access.** Customer file content is encrypted in transit and at rest. Provider personnel have no standing access to Customer file content; access is granted just-in-time under audited elevation, solely as necessary to provide the Services or as instructed by Customer. Document metadata is maintained to operate the governed record. Where the Order Form includes BYOK or HYOK key management, the key terms in the Documentation apply. + +### 5. Security & Availability + +5.1 **Security program.** Provider maintains a written information security program including access controls, encryption (TLS 1.2+ in transit, AES-256 at rest), audit logging, vulnerability management, and personnel security. Provider will provide its available security documentation (including its security program overview and penetration-test attestation) upon request under confidentiality. + +5.2 **Availability.** For Stirling Cloud deployments, Provider targets 99.9% monthly uptime, excluding scheduled maintenance announced at least 48 hours in advance. The uptime figure is a target, not a credited commitment, and no service credits apply. Support response commitments for the {{sla_tier}} tier are set out in the SLA Exhibit referenced by the Order Form. + +5.3 **Breach notice.** Provider will notify Customer without undue delay after becoming aware of a Personal Data Breach affecting Customer Personal Data, and in any event within forty-eight (48) hours of awareness. Provider may provide information in phases as it becomes available and will supplement its notice as investigation proceeds. + +5.4 **Updates.** Provider will make security patches and product upgrades available to Customer at no additional charge for supported versions. + +### 6. Confidentiality + +6.1 Each Party shall protect the other's Confidential Information with at least the care it uses for its own similar information and no less than reasonable care, use it solely to perform under this Agreement, and disclose it only to personnel and advisors with a need to know who are bound by confidentiality obligations at least as protective. Confidential Information excludes information that is public without breach, independently developed, or rightfully received from a third party. + +6.2 Compelled disclosure is permitted with prompt notice (where lawful) and reasonable cooperation to seek protective treatment. + +6.3 Obligations survive three (3) years after termination; trade secrets survive as long as they remain trade secrets. + +### 7. Warranties & Indemnification + +7.1 **Performance warranty.** Provider warrants the Services will perform materially in accordance with the Documentation. Customer's exclusive remedy for breach is re-performance or, if Provider cannot re-perform within thirty (30) days, termination of the affected Services and a pro-rata refund of prepaid, unused fees for those Services. + +7.2 **Mutual warranties.** Each Party warrants it has the authority to enter this Agreement and will comply with applicable law in its performance. + +7.3 **IP indemnification.** Provider shall defend Customer against third-party claims that the Services, as provided and used per this Agreement, infringe a copyright or trademark or misappropriate a trade secret, and shall indemnify Customer for resulting damages finally awarded or agreed in settlement. Where **Enhanced IP Protection** is elected on the Order Form, this obligation extends to patent claims and carries the enhanced cap stated in Section 8.2. Exclusions: combinations with non-Provider materials, Customer content, modifications not made by Provider, and use after notice to stop. Provider may procure rights, modify, or replace the Services; if none is practicable, Provider may terminate the affected Services and refund prepaid, unused fees. This section states Customer's exclusive remedy for IP claims. + +7.4 **Customer indemnification.** Customer shall defend and indemnify Provider against third-party claims arising from Customer content, Customer's breach of Section 1.4, or Customer's violation of law. + +7.5 **Disclaimer.** EXCEPT AS EXPRESSLY STATED, THE SERVICES ARE PROVIDED WITHOUT OTHER WARRANTIES, EXPRESS OR IMPLIED, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. AI-ASSISTED OUTPUTS (INCLUDING CLASSIFICATION, EXTRACTION, AND AGENT ARTIFACTS) ARE PROBABILISTIC; CUSTOMER IS RESPONSIBLE FOR HUMAN REVIEW WHERE OUTPUTS HAVE LEGAL OR REGULATORY EFFECT. + +### 8. Limitation of Liability + +8.1 NEITHER PARTY IS LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR LOST PROFITS OR REVENUE. + +8.2 **General cap.** EACH PARTY'S AGGREGATE LIABILITY IS CAPPED AT THE FEES PAID OR PAYABLE UNDER THIS AGREEMENT IN THE TWELVE (12) MONTHS PRECEDING THE FIRST EVENT GIVING RISE TO LIABILITY. **Super-cap:** for breaches of Section 6 (Confidentiality), breaches of the DPA or Section 4–5 security obligations, and IP indemnification under Section 7.3, the cap is TWO TIMES (2x) such fees. **Uncapped:** fraud, willful misconduct, Customer's payment obligations, and Customer's indemnification under Section 7.4 for claims arising from Customer's willful violation of law. + +8.3 All claims arising from the same event or series of connected events count as a single claim for the purposes of the caps in Section 8.2. + +### 9. General + +9.1 **Entire agreement; precedence.** This Agreement (Parts A–C, the Order Form, the SLA Exhibit, and the Standard Contractual Clauses where applicable) is the entire agreement and supersedes prior proposals and quotes, including {{quote_ref}}. Only the following provisions of the Stirling EULA & Commercial Terms are incorporated: Section 3 (Definitions), Section 8 (AI features), Section 10 (Self-hosted and desktop software), and Section 11 (Fair use). The website Terms of Service do not apply to this Agreement; without limitation, their arbitration and class-waiver provisions, online auto-renewal rules, unilateral-amendment provision, self-serve pricing, and clickwrap acceptance mechanism are expressly excluded. Precedence: Order Form → Standard Contractual Clauses (for international transfers) → DPA → MSA → SLA Exhibit → incorporated EULA sections → Documentation. + +9.2 **Governing law; venue.** Delaware law, excluding conflicts rules. Exclusive jurisdiction and venue in the state or federal courts located in San Francisco County, California, and the Parties consent to personal jurisdiction there. + +9.3 **Assignment.** Neither Party may assign without the other's consent, except to a successor in a merger, acquisition, or sale of substantially all assets, with notice. + +9.4 **Notices.** Written notices to the addresses on the Order Form; email permitted with confirmation of receipt. + +9.5 **Force majeure; independent contractors; waiver; severability.** Standard terms apply: neither Party is liable for delay caused by events beyond reasonable control; the Parties are independent contractors; failure to enforce is not waiver; unenforceable provisions are severed with the remainder in effect. + +9.6 **Publicity.** Neither Party may use the other's name or marks publicly without prior written consent, except Provider may identify Customer as a customer with Customer's prior approval of the specific use. + +9.7 **Suspension.** Provider may suspend the Services for material breach that threatens the security or integrity of the Services, with notice and opportunity to cure where practicable. Undisputed unpaid fees more than thirty (30) days late are grounds for suspension after ten (10) days' notice. + +### 10. Termination + +10.1 Either Party may terminate for material breach uncured thirty (30) days after written notice, or immediately upon the other's insolvency. + +10.2 On termination: Customer's access ends (self-hosted licenses expire per the license mechanism); each Party returns or destroys the other's Confidential Information; the DPA's deletion terms govern Customer Personal Data; Sections 3 (accrued fees), 6, 7, 8, 9, and 10 survive. + +10.3 If Customer terminates for Provider's uncured material breach, Provider refunds prepaid fees for the unused remainder of the then-current contract year. diff --git a/app/saas/src/main/resources/legal/eula/1.0.0/eula.md b/app/saas/src/main/resources/legal/eula/1.0.0/eula.md new file mode 100644 index 0000000000..f6dd32d5e1 --- /dev/null +++ b/app/saas/src/main/resources/legal/eula/1.0.0/eula.md @@ -0,0 +1,75 @@ +# Stirling EULA & Commercial Terms + +This document fills the EULA slot the website Terms of Service §5 already contemplates ("If a separate end-user license (EULA) accompanies software, that license governs to the extent of any conflict"). It carries the commercial terms of the actual product: the PDF Process meter, spend limits, prepaid capacity, the free allotment, trials, self-hosted licensing, and AI features. For customers under a signed Stirling Enterprise Agreement, that agreement controls. + +**Effective:** {{version_date}} · **Version:** {{version}} + +## 1. Agreement; precedence + +These EULA & Commercial Terms ("EULA") supplement the Stirling Terms of Service (stirling.com/legal/terms-of-service). If they conflict, this EULA controls for the software and the commercial terms below. Open-source components are governed by their own licenses, which control for those components. By clicking accept, creating a workspace, or using the software, you agree on behalf of yourself and, if applicable, the organization you represent ("you"). + +## 2. The products + +**The Stirling PDF Editor** is free: manual editing, the tool catalog, and team administration (including SSO) carry no subscription fee or per-seat charge, whether used in the browser, as a desktop application, or self-hosted. Usage limits on automated processing, fair-use rules (Section 11), support levels, and the feature set may change over time, and third-party costs (such as your own hosting) are yours. The Editor's open-source components remain available under their own licenses independently of this EULA. **The Stirling PDF Processor** is the paid platform that processes PDFs automatically — policies, pipelines, the Stirling Agent, and API processing — billed on the meter below. + +## 3. Definitions + +**"PDF Process"** — one policy execution, one pipeline run (regardless of the number of operations in its chain), or one Stirling Agent returned artifact (a processed file or summary, regardless of the number of messages that produced it), applied to one file. **"Data Processing"** — the data-volume component of the meter: files carry their first 25 MB included per file; volume past that is billed per Section 4. **"file"** — a document processed by the Processor. Chatting with the Stirling Agent is free; only returned artifacts meter. + +## 4. Metered billing (pay as you go) + +4.1 **Rates.** 1¢ per PDF Process, plus Data Processing at 1¢ per 25 MB increment past the first 25 MB of each file. Megabytes are decimal (1 MB = 1,000,000 bytes); size is measured once per file as submitted; increments round up ("part thereof" counts — a 26 MB file incurs one Data Processing increment, a 60 MB file incurs two). Rates may change on thirty (30) days' notice; changes apply prospectively. **Example:** two policies on a 3 MB contract = 2¢; two policies on a 60 MB scan set = 2¢ + 2¢ data = 4¢. + +4.2 **Free allotment.** New workspaces receive a one-time allotment of 500 PDF Processes. A file processed by two processes consumes two of the 500. When the allotment is exhausted, processing pauses until the Processor is switched on. + +4.3 **Invoices.** Usage is invoiced monthly on the 1st for the prior cycle, charged to your payment method on file (card or ACH debit). You authorize these charges. + +4.4 **Usage records.** The Processor's audit log is the system of record, subject to Section 4.5. Your Usage & Billing page shows consumption, and a per-file usage statement (name, size, processes, charge) is available for download. + +4.5 **Billing disputes.** You may dispute a charge or metering record in good faith within sixty (60) days of the invoice or charge date. We will investigate, provide the relevant usage-statement detail, and correct confirmed errors by credit or refund. The audit log is presumptively accurate but not conclusive; reasonable contrary evidence will be considered. Undisputed amounts remain payable. + +## 5. Spend limits + +5.1 You may set a monthly spend limit. By default, processing pauses when usage reaches the limit; queued documents resume when you raise the limit or the cycle resets. Nothing already processed is lost. + +5.2 If you enable **keep-processing** ("Keep processing if you hit your limit"), usage past the limit continues to accrue and be billed per Section 4; the limit then functions as a notification threshold. You can change the limit or the toggle at any time in Usage & Billing. + +## 6. Cancellation; downgrade + +You may revert to the free Editor plan at any time from Usage & Billing. Accrued usage remains payable. Your policies, configuration, and history are retained per the Terms of Service data-retention practices. + +## 7. Prepaid capacity (self-serve annual) + +7.1 **Offer.** You may prepay twelve (12) months of processing capacity for the price of ten (10) (the "12-for-10 rate"), sized at purchase. Payment by card, or by bank transfer against a generated invoice (net 30); prepaid capacity activates when payment clears. + +7.2 **No renewal of prepaid capacity; automatic transition to pay-as-you-go.** Prepaid capacity does not renew for another prepaid term. At purchase, you affirmatively consent to the following transition, which is disclosed before you pay: when the term ends, metered billing (Section 4) applies automatically at then-current rates so processing does not pause. We remind you thirty (30) days before term end; the reminder states the metered rates that will apply and how to cancel or revert to the free Editor plan (one click in Usage & Billing). + +7.3 **Consumption; overage; expiry.** Capacity draws down in PDF Processes. If you exhaust capacity mid-term, you may top up at the same 12-for-10 rate, or metered billing applies at list rates (with a card on file) or processing pauses (without one). Unused capacity expires at term end and is not refunded and does not roll over. + +7.4 **Cap.** Self-serve prepaid capacity is limited to 1,000,000 PDF Processes per year; larger commitments are available under a Stirling Enterprise Agreement. + +## 8. AI features + +AI features — classification, extraction, redaction-assist, and the Stirling Agent — are optional. They run only when you invoke a feature that uses them, and an administrator can disable them for the workspace; the rest of the Processor works without them. When used, they call machine-learning models from the providers listed at {{subprocessor_url}}. Currently: **Anthropic** (Claude models), which receives prompts and the document text or excerpts needed to perform the requested task; and **Voyage AI** (embedding models), which receives extracted text excerpts solely to generate embeddings when you enable Ingestion/RAG features. Only the document text or excerpts needed for the requested feature are sent — not your whole files — and only when that feature runs. AI charges are included in the price of whatever runs — there is no separate AI surcharge. Your content is not used to train models, by us or by these providers (verified against our signed provider agreements). AI outputs are probabilistic; review outputs before relying on them where accuracy has legal effect. + +## 9. Evaluations and trials + +Enterprise trials run fourteen (14) days, require no payment method, and are provided for evaluation only, AS IS, without service level commitments. Either party may end an evaluation at any time; on expiry your workspace continues on the free Editor plan. + +## 10. Self-hosted and desktop software + +10.1 **License.** We grant you a non-exclusive, non-transferable license to install and run the Editor and, with an active plan, the self-hosted Processor, for your internal business use. Open-source components remain under their own licenses. + +10.2 **License validation and metering.** Self-hosted Processor deployments validate their license online and transmit usage metering data (process counts, file sizes, and file hashes for billing integrity, and diagnostic data — never file content or file names) to Stirling. File names used for unique PDF identification remain on your server and are not transmitted. Air-gapped deployments verify a signed activation bundle offline and reconcile usage periodically. You will not disable, circumvent, or falsify validation or metering. **The meter is the same regardless of where the software runs.** + +10.3 **Updates.** Security patches and upgrades are made available for supported versions; some updates may install automatically per Terms of Service §5. + +10.4 **Authorized users and administration.** "Authorized Users" are your employees, and the employees of your affiliates and contractors working on your behalf, whom you provision through your workspace. You are responsible for your users' credentials, your administrators' actions, and your users' compliance with this EULA. One workspace serves one legal entity and its affiliates; serving unrelated third parties requires a separate agreement. You may not redistribute the Processor or offer it as a hosted service to others. On termination or downgrade, self-hosted Processor licenses expire per the license mechanism; installed Editor copies remain usable under the free plan. We may verify license compliance through the validation mechanism in Section 10.2. + +## 11. Fair use + +Free-tier and flat-price features are subject to fair use: we may throttle or decline usage patterns that abuse free processing (for example, automation disguised as manual editing) after notice where practicable. + +## 12. Changes to this EULA + +We may update this EULA. Material changes take effect thirty (30) days after notice. Changes that materially increase your price or reduce your rights take effect at your next billing cycle or prepaid term start, or upon your affirmative acceptance — whichever comes first — except changes strictly necessary for legal compliance or security, which may take effect sooner with notice. Continued use after the effective date is acceptance. Version history is available at {{eula_url}}. diff --git a/app/saas/src/main/resources/legal/manifest.json b/app/saas/src/main/resources/legal/manifest.json new file mode 100644 index 0000000000..c34559275d --- /dev/null +++ b/app/saas/src/main/resources/legal/manifest.json @@ -0,0 +1,38 @@ +{ + "subprocessorUrl": "https://www.stirlingpdf.com/legal/subprocessors", + "eulaUrl": "https://www.stirlingpdf.com/legal/eula", + "documents": { + "enterprise-agreement": { + "label": "SEA", + "displayName": "Stirling Enterprise Agreement", + "version": "0.9.1", + "effectiveDate": "2026-07-10", + "status": "draft", + "parts": ["msa.md", "@order-form", "dpa.md"] + }, + "eula": { + "label": "EULA", + "displayName": "Stirling EULA & Commercial Terms", + "version": "1.0.0", + "effectiveDate": "2026-07-10", + "status": "draft", + "parts": ["eula.md"] + }, + "sla": { + "label": "SLA", + "displayName": "Stirling SLA Exhibit", + "version": "1.0.0", + "effectiveDate": "2026-07-10", + "status": "draft", + "parts": ["sla.md"] + }, + "subprocessors": { + "label": "SUBP", + "displayName": "Stirling Subprocessors", + "version": "1.0.0", + "effectiveDate": "2026-07-10", + "status": "draft", + "parts": ["subprocessors.md"] + } + } +} diff --git a/app/saas/src/main/resources/legal/sla/1.0.0/sla.md b/app/saas/src/main/resources/legal/sla/1.0.0/sla.md new file mode 100644 index 0000000000..42271171d5 --- /dev/null +++ b/app/saas/src/main/resources/legal/sla/1.0.0/sla.md @@ -0,0 +1,37 @@ +# SLA Exhibit — Stirling Enterprise Agreement + +Referenced by the Order Form's service-level row and MSA §5.2. One document, three tiers; the Order Form's tier selection determines the applicable column. Uptime is a target, not a credited commitment: no service credits apply at any tier. Tiers differentiate support response, channels, and people. + +## 1. Availability + +For Stirling Cloud deployments, Provider targets **99.9% monthly uptime**, measured at the API and console endpoints, excluding scheduled maintenance announced at least 48 hours in advance and events beyond Provider's reasonable control. Current and historical status is published at the system status page. No service credits apply; persistent material failure to meet the target is addressed through MSA §7.1 (performance warranty and remedies) and §10 (termination for material breach). + +Self-hosted and Air-gapped deployments: availability of the runtime is Customer's responsibility; this Section applies to Provider's license, metering, and update services. + +## 2. Support tiers + +| | **Standard** | **Priority** | **Dedicated** | +| --- | --- | --- | --- | +| Included with | Every Enterprise Agreement | Every Enterprise Agreement | The Dedicated SE/CSM line item ($30,000/yr) | +| Hours | Business hours (Mon–Fri, 9:00–18:00 US Eastern, excl. US holidays) | Business hours + extended (7:00–21:00 US Eastern) | 24×7 for Severity 1 | +| Channels | Email, in-product | Email, in-product, private Slack/Teams channel | All Priority channels + named Solutions Engineer and CSM | +| Severity 1 first response (production down / processing halted org-wide) | 8 business hours | 4 hours | 1 hour, 24×7 | +| Severity 2 (major feature degraded, no workaround) | Next business day | 8 business hours | 4 hours | +| Severity 3 (minor defect, workaround exists) | 3 business days | 2 business days | Next business day | +| Severity 4 (question, cosmetic) | 5 business days | 3 business days | 2 business days | +| Escalation path | Support queue | Support lead | Named SE → CSM → Provider executive | +| Business reviews | — | — | Quarterly, where the QBR line item is elected | + +First response = a qualified human engaging with the issue, not an acknowledgment autoresponder. Resolution times are not committed; Provider works Severity 1 issues continuously within the tier's hours until resolved or downgraded. + +## 3. Severity is set by Customer, subject to reasonable reclassification + +Customer designates severity at filing; Provider may reclassify with explanation. Severity 1 requires production impact in a live (non-evaluation) environment. + +## 4. Maintenance and updates + +Scheduled maintenance is announced at least 48 hours ahead and targeted at low-usage windows. Security patches for supported versions ship to all tiers at no charge (MSA §5.4). Trials and evaluations are provided AS IS and are outside this Exhibit (EULA §9). + +## 5. Exclusions + +This Exhibit does not apply to: issues caused by Customer's environment, modifications, or third-party systems; usage exceeding the fair-use provisions; Preview/Beta features; or Force Majeure events (MSA §9.5). diff --git a/app/saas/src/main/resources/legal/subprocessors/1.0.0/subprocessors.md b/app/saas/src/main/resources/legal/subprocessors/1.0.0/subprocessors.md new file mode 100644 index 0000000000..670ae53150 --- /dev/null +++ b/app/saas/src/main/resources/legal/subprocessors/1.0.0/subprocessors.md @@ -0,0 +1,19 @@ +# Stirling PDF — Subprocessors + +Referenced by DPA §C5 and Annex III, and by EULA §8. Changes to this list carry 30 days' notice per DPA §C5. Last updated: {{version_date}}. + +Stirling PDF, Inc. uses the following subprocessors to provide the Services. Customer files are processed within Stirling's own infrastructure. AI features are optional and can be disabled; where they are used, AI providers receive only the document text or excerpts needed for the requested feature, never whole customer files. + +| Subprocessor | Purpose | Data processed | Location | +| --- | --- | --- | --- | +| **Amazon Web Services (AWS)** | Cloud infrastructure and storage for Stirling Cloud | Customer files (encrypted at rest), account and usage data | United States (EU region availability per deployment — see DPA §C8 note) | +| **Stripe** | Payment processing | Billing contact and transaction data. Payment card details go directly to Stripe, which acts as an independent controller for them | United States | +| **Supabase** | Account and workspace data infrastructure | Account, workspace, and configuration data | United States | +| **Google** | Transactional and operational email delivery | Names, email addresses, message content of service emails | United States | +| **Anthropic** | AI models (Claude) powering the Stirling Agent and AI-assisted features | Prompts and the document text or excerpts needed for the requested feature — never whole files; only where AI features are used | United States | +| **Voyage AI** | Embedding models for Ingestion/RAG features | Extracted text excerpts, only where the customer enables Ingestion/RAG, solely to generate embeddings — never customer files | United States | +| **PostHog** | Product telemetry and usage analytics | Pseudonymous usage events and diagnostic data — never file content | European Union (EU-hosted) | + +Neither AI provider uses customer data for model training (contractually confirmed). + +Self-hosted and air-gapped deployments: customer files remain in the customer's environment; Stirling receives license-validation and metering data only (process counts, file sizes, file hashes — never file names or content). diff --git a/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementTrialRestartPolicyTest.java b/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementTrialRestartPolicyTest.java new file mode 100644 index 0000000000..86f361ff87 --- /dev/null +++ b/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementTrialRestartPolicyTest.java @@ -0,0 +1,44 @@ +package stirling.software.saas.procurement.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import stirling.software.saas.procurement.model.ProcurementDeal; + +/** + * Which stages may (re)start a trial is a security policy, not a convenience. + * + *

From the agreement stage onward a deal's {@code licenseRef} points at the committed annual + * licence. Starting a trial replaces it with a fresh 14-day key, rewinds the stage and resets the + * extension counter — so an unguarded restart would downgrade a paying customer's entitlement while + * Stripe kept billing them. This pins the allowed set so widening it has to be deliberate. + */ +class ProcurementTrialRestartPolicyTest { + + @Test + @DisplayName("allowed before a deal exists, while exploring, and within the trial") + void allowsOnlyPreCommitmentStages() { + assertThat(ProcurementService.canStartTrial(null)).isTrue(); + assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_EXPLORING)).isTrue(); + assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_TRIAL)).isTrue(); + } + + @Test + @DisplayName("refused once the deal is quoting or beyond") + void refusesCommittedStages() { + assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_QUOTE)).isFalse(); + assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_AGREEMENT)).isFalse(); + assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_PAYMENT)).isFalse(); + assertThat(ProcurementService.canStartTrial(ProcurementDeal.STAGE_LIVE)).isFalse(); + } + + @Test + @DisplayName("an unrecognised stage is refused, not waved through") + void refusesUnknownStages() { + // A stage added later, or a hand-edited row, must fail closed. + assertThat(ProcurementService.canStartTrial("renewal")).isFalse(); + assertThat(ProcurementService.canStartTrial("")).isFalse(); + } +} diff --git a/frontend/.storybook/a11y-baseline.json b/frontend/.storybook/a11y-baseline.json index 10fc530c77..a31d84613b 100644 --- a/frontend/.storybook/a11y-baseline.json +++ b/frontend/.storybook/a11y-baseline.json @@ -1707,6 +1707,9 @@ "editor/src/portal/components/billing/InvoicesList.stories.tsx :: Default": [ "color-contrast" ], + "editor/src/portal/components/billing/LinkAccountPrompt.stories.tsx :: Default": [ + "color-contrast" + ], "editor/src/portal/components/billing/PrepaidCapacityCard.stories.tsx :: Bundle Healthy": [ "aria-progressbar-name", "color-contrast" @@ -2107,22 +2110,15 @@ "color-contrast" ], "editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: License": [ - "aria-dialog-name" + "color-contrast" ], "editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: License Trial": [ - "aria-dialog-name" - ], - "editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: Schedule Call": [ - "aria-dialog-name" + "color-contrast" ], "editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: Trial Manage": [ - "aria-dialog-name" - ], - "editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: Trial Manage Maxed": [ - "aria-dialog-name" + "color-contrast" ], "editor/src/portal/components/procurement/ProcurementExtras.stories.tsx :: Trial Setup": [ - "aria-dialog-name", "color-contrast" ], "editor/src/portal/components/procurement/ProcurementFlow.stories.tsx :: Default": [ @@ -2135,6 +2131,9 @@ "editor/src/portal/components/procurement/ProcurementHome.stories.tsx :: Default": [ "color-contrast" ], + "editor/src/portal/components/procurement/ProcurementModal.stories.tsx :: Open": [ + "color-contrast" + ], "editor/src/portal/components/procurement/ProcurementStages.stories.tsx :: License": [ "color-contrast" ], @@ -2144,6 +2143,9 @@ "editor/src/portal/components/procurement/ProcurementStages.stories.tsx :: License Online Only": [ "color-contrast" ], + "editor/src/portal/components/procurement/ProcurementStages.stories.tsx :: Payment": [ + "color-contrast" + ], "editor/src/portal/components/procurement/QuoteBuilder.stories.tsx :: Default": [ "color-contrast" ], diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml index bf00cfd08d..33cf0ee8e1 100644 --- a/frontend/editor/public/locales/en-US/translation.toml +++ b/frontend/editor/public/locales/en-US/translation.toml @@ -7331,13 +7331,16 @@ tagline = "Native app for Microsoft Windows" title = "Windows" [portal.home.editor] -activeUsers = "{{n}} active" -install = "Install the editor" -invite = "Invite teammates" -name = "Stirling PDF Editor" +activeOfDeployed = "{{active}} of {{total}} active this month" +name = "PDF Editor" open = "Open in browser" updated = "updated {{time}}" +[portal.home.editor.deploy] +finish = "Finish deployment" +options = "View deployment options" +start = "Deploy the Editor" + [portal.home.editor.target] cloud = "Managed Cloud" docker = "Self-hosted · Docker" @@ -7348,25 +7351,6 @@ afternoon = "Good afternoon" evening = "Good evening" morning = "Good morning" -[portal.home.onboarding.enterprise] -body = "Org-wide SSO + SCIM + RBAC, committed volume pricing, and air-gapped deployment." -cta = "Start Trial" -ctaQuote = "Get Quote" -lead = "For 250+ employees." -tag = "Enterprise" - -[portal.home.onboarding.steps.editor] -blurb = "Install the desktop app or self-host" -title = "Download the editor" - -[portal.home.onboarding.steps.invite] -blurb = "Bring your team into the secure workspace" -title = "Invite teammates" - -[portal.home.onboarding.steps.policies] -blurb = "{{active}} active · {{recommended}} recommended" -title = "Confirm your policies" - [portal.infrastructure] manageEditorDeployment = "Manage Editor deployment" sectionsAriaLabel = "Infrastructure sections" @@ -7767,6 +7751,12 @@ pipelines = "Pipelines" policies = "Policies" sources = "Sources" +[portal.legal] +draft = "{{label}} · draft" +loadError = "Could not load this document. Please try again." +loading = "Loading…" +title = "Legal document" + [portal.nav] agent-builder = "Agent Builder" components = "Components" @@ -8430,19 +8420,27 @@ email = "Email intake" subtitle = "Get your team evaluated, contracted, and onboarded. Every document in one place." title = "Procurement" -[portal.procurement.action] -download = "Download" -pay = "Pay now" -request = "Request" -sign = "Review & sign" -upload = "Upload" - [portal.procurement.agreement] -agreeCta = "Agree & subscribe" -confirm = "I have read and agree to the Stirling Enterprise Agreement." -eyebrow = "Agreement" -intro = "One combined agreement covers your deal: Master Service Agreement, Order Form, EULA, and Data Processing Agreement. Review it, then agree to accept the quote into a committed subscription." -title = "Review your enterprise agreement" +agreeCta = "Sign agreement" +confidential = "Confidential" +confirm = "I have read and agree to this Agreement, and I represent that I am authorized to sign it on behalf of the organization named above." +docName = "Stirling Enterprise Agreement" +docSub = "MSA, Order Form, EULA and DPA, combined into one signature." +download = "Download" +downloadDraftError = "Could not generate the agreement PDF - the document renderer is unavailable. Please try again shortly or contact support." +downloadError = "Could not download the signed agreement. Please try again." +legalName = "Legal entity name" +legalNamePlaceholder = "The legal entity that will sign" +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" +signatoryTitlePlaceholder = "e.g. General Counsel" +signError = "Could not record your signature. Please try again." [portal.procurement.builder] addons = "Add-ons" @@ -8455,16 +8453,19 @@ 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." contactEmail = "Contact email" contactEmailPlaceholder = "jane@acme.com" contactName = "Contact name" contactNamePlaceholder = "Jane Doe" continue = "Continue" +done = "Done" eula = "I have read and agree to the Stirling Enterprise EULA. It governs the agreement generated from this quote." generate = "Generate quote" -included = "Included" -indemnification = "IP indemnification" -indemnificationSub = "We defend qualifying IP claims, per the EULA" +indemnification = "Enhanced IP Protection" +indemnificationSub = "Extends our IP defense to patent claims. Baseline copyright, trademark and trade-secret indemnification is included free." +paperEyebrow = "Enterprise quote" +paperFor = "Prepared for" pdfSize = "PDF size" poNumber = "PO number" poNumberPlaceholder = "Optional" @@ -8512,6 +8513,7 @@ training = "Onboarding & training" trainingSub = "Live sessions to get your team running" users = "Total users" usersPlaceholder = "e.g. 250" +viewEula = "Read it" volEstimated = "Estimated from {{count}} users (~2,000 PDFs each, including automation). Edit if you know better." volManual = "Using your figure. Re-estimate from your team size any time." volNoUsers = "Not sure? Enter your team size and we'll estimate it." @@ -8520,54 +8522,55 @@ volumePlaceholder = "e.g. 1,000,000" years_one = "{{count}} year" years_other = "{{count}} years" -[portal.procurement.docs] -count_one = "{{count}} doc" -count_other = "{{count}} docs" -done = "Done" -here = "You're here" -hide = "Hide" -optional = "Optional" -paidAddon = "Paid add-on" -show = "Show" -subtitle = "Everything you need at each step of the journey, surfaced as the deal moves through it." -supportingSubtitle = "SOC 2, security reviews, tax forms and more, ready when your security or procurement team asks. Some carry a one-time fee." -supportingTitle = "Supporting your evaluation" +[portal.procurement.documents] +agreement = "Enterprise Agreement" +agreementSub = "MSA, Order Form and DPA in one signature." +download = "Download" +eula = "EULA & Commercial Terms" +eulaSub = "The software and self-serve commercial terms." +invoice = "Invoice" +invoiceSub = "Your first subscription invoice." +laterInvoice = "Available after you accept" +laterQuote = "Available once your quote is issued" +quote = "Quote" +quoteSub = "Your itemised enterprise quote." +sla = "SLA Exhibit" +slaSub = "Support tiers and response targets." +subprocessors = "Subprocessors" +subprocessorsSub = "Third parties that process data on your behalf." +subtitle = "Your deal paperwork, available any time." title = "Documents" -upcoming = "Upcoming" +view = "View" [portal.procurement.error] title = "Something went wrong" [portal.procurement.hero] -company = "Your enterprise deal" -ctaLive = "You're live" -ctaPayment = "Add payment" +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" -eyebrow = "Enterprise procurement" +documents = "Documents" +eyebrow = "Enterprise" +eyebrowCompany = "{{company}} Enterprise" inviteTeammates = "Invite teammates" licenseKey = "Licence key" -nextStep = "Next step: {{action}}" -notStarted = "Not started" +liveSub = "Your organization is provisioned and your licence is active." +liveTitle = "You are live on Stirling Enterprise" +next = "Next: {{stage}}" open = "Open procurement" scheduleCall = "Schedule a call" -setup1Sub = "Invite your teammates" -setup1Title = "Deploy the PDF Editor" -setup2Sub = "Turn on processing across editors and other sources" -setup2Title = "Connect the PDF Processor" -setup3Sub = "Turn on Security, Compliance, Routing, or Retention when you need them" -setup3Title = "Add recommended policies" +sentenceAgreement = "review and sign the agreement" +sentenceLive = "provisioning and rollout" +sentencePayment = "purchase order and payment" +sentenceQuote = "review and accept your quote" +sentenceTrial = "set up your trial workspace" [portal.procurement.journey] daysLeft_one = "{{count}} day left" daysLeft_other = "{{count}} days left" -engineerLabel = "Your solutions engineer" -eyebrow = "Your rollout" -live = "You're live on Stirling Enterprise" -nextStep = "Next step: {{action}}" -subtitle = "Your solutions engineer is on every step. One next action at a time; the full checklist is below." -title = "From trial to live, one guided path" -trialTitle = "Enterprise trial" [portal.procurement.journeySteps.agreement] blurb = "One signature covers MSA, order form, EULA and DPA." @@ -8616,45 +8619,26 @@ description = "Your subscription is active and your licence is issued. Your team eyebrow = "Live" title = "You're live on Stirling Enterprise" -[portal.procurement.locked] -description = "Trial keys, committed-volume quotes, the one-signature agreement, payment, and your document ledger all live here once you start an enterprise evaluation." -eyebrow = "Enterprise only" -talkToSales = "Talk to sales" -title = "The procurement track opens with Enterprise" - [portal.procurement.milestone] -download = "Download PDF" downloadError = "Could not download the quote PDF just yet — please try again in a moment." -edit = "Edit quote" - -[portal.procurement.modal] -cancel = "Cancel" -chooseFile = "Choose file" -close = "Close" -downloadBody = "Your download will begin shortly." -downloadCta = "Download" -downloadTitle = "Download" -noFile = "No file selected" -payBody = "Pay your committed contract by card or bank transfer through Stripe. Your workspace provisions as soon as payment clears." -payCta = "Continue to Stripe" -payTitle = "Confirm payment" -requestBodyFree = "We generate this on demand. Confirm and your solutions engineer will send it across shortly." -requestBodyPaid = "This is a paid add-on. Confirm and your solutions engineer will scope it and send the paperwork." -requestCta = "Request" -requestTitle = "Request this document" -signBody = "Opens the Stirling Enterprise Agreement for e-signature: one signature covers the MSA, order form, EULA and DPA. We countersign automatically and you advance to payment." -signCta = "Open for signature" -signTitle = "Review and sign your agreement" -uploadBody = "Send us your PO and we invoice against it on your terms. Drag in the PDF or pick a file below." -uploadCta = "Upload purchase order" -uploadTitle = "Upload your purchase order" [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" +poNumber = "Purchase order: {{po}}" +renewal = "Renews at {{amount}}/year after the term (+{{pct}}% CPI)" +tcv = "{{years}}-year term, paid in full up front: {{tcv}}" +validUntil = "Valid until {{date}}" + [portal.procurement.schedule] fallback = "Couldn't load the scheduler." fallbackLink = "Open scheduling in a new tab" @@ -8664,25 +8648,33 @@ title = "Schedule a call" [portal.procurement.setup] airgap = "Air-gapped" -airgapSub = "Fully offline, isolated network. Includes a downloadable licence file." -cloud = "Cloud" -cloudSub = "Fully managed by Stirling. Nothing for you to run." -deployment = "Where will you run Stirling?" -seats = "Team size" -seatsHint = "Roughly how many people will use it. You can refine this when you build your quote." -seatsPlaceholder = "e.g. 250" +airgapSub = "Sealed, no outbound" +back = "Back" +businessName = "Business name" +businessNamePlaceholder = "Acme Corp" +cloud = "Stirling Cloud" +cloudSub = "Managed, fastest start" +continue = "Continue" +deployment = "Where should it deploy?" +eula = "I agree to the Stirling EULA & Commercial Terms." +fullName = "Full name" +fullNamePlaceholder = "Your name" +invites = "Invite teammates · optional" +invitesPlaceholder = "sam@acme.com, lee@acme.com" +scheduleCall = "Schedule a call" +seats = "People testing" +seatsPlaceholder = "e.g. 15" selfhost = "Self-hosted" -selfhostSub = "Run it in your own cloud or data centre." +selfhostSub = "Docker or Kubernetes" start = "Start trial" -subtitle = "Tell us how you plan to run Stirling so we can tailor your trial and quote. No card required." +stepOf = "Step {{n}} of {{total}}" +subtitle = "Free for 14 days, no card required." +subtitleDetails = "A few details for your quote and agreement." +talkFirst = "Prefer to talk first?" title = "Set up your trial" - -[portal.procurement.status] -action = "Action needed" -available = "Available" -complete = "Complete" -pending = "Pending" -request = "On request" +viewEula = "Read it" +workEmail = "Work email" +workEmailPlaceholder = "you@company.com" [portal.procurement.trial] body = "Extending adds 7 days and notifies your solutions engineer." @@ -8693,12 +8685,6 @@ maxed = "Maxed out" subtitle = "Your free trial runs through {{date}}. No card required." title = "Enterprise trial" -[portal.procurement.upsell] -homeBadge = "Enterprise" -homeBody = "Committed volume pricing, org-wide SSO + SCIM + RBAC, 90-day immutable audit, and a dedicated SE." -homeCta = "Start Trial →" -homeHeadline = "Process millions of PDFs." - [portal.search] ariaLabel = "Search" placeholder = "Search Stirling — endpoints, pipelines, docs…" @@ -8923,6 +8909,9 @@ name = "Name" namePlaceholder = "e.g. Claims intake" type = "Type" +[portal.stepModal] +close = "Close" + [portal.usage] managePayment = "Manage Payment" subtitle = "Consumption, invoices, and plan management for every PDF Stirling has billed, in one console." @@ -8985,14 +8974,6 @@ summary = "Owns a team — manages its members' resources and shared configs." limited = "{{used}} / {{limit}}" unlimited = "{{used}} · Unlimited" -[portal.welcome] -ariaLabel = "Welcome to Stirling PDF" -install = "Install the editor" -invite = "Invite teammates" -openInBrowser = "Open in browser" -productName = "PDF Editor" -stats = "30M downloads · 60+ PDF operations · Free forever" - [printFile] title = "Print File" diff --git a/frontend/editor/src/portal/ViewRouter.tsx b/frontend/editor/src/portal/ViewRouter.tsx index 76adc1ad1d..8e77c20830 100644 --- a/frontend/editor/src/portal/ViewRouter.tsx +++ b/frontend/editor/src/portal/ViewRouter.tsx @@ -11,7 +11,6 @@ import { Policies } from "@portal/views/Policies"; import { EditorAdmin } from "@portal/views/EditorAdmin"; import { Infrastructure } from "@portal/views/Infrastructure"; import { PortalBillingGate } from "@portal/components/billing/PortalBillingGate"; -import { Procurement } from "@portal/views/Procurement"; import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext"; // Lazy so the generated docs manifest (bundled JSON) lands in its own chunk. @@ -62,7 +61,6 @@ export function ViewRouter() { element={} /> } /> - } /> null); +} + +afterEach(() => vi.restoreAllMocks()); + +describe("openApiUrl", () => { + it("opens an https URL in a new tab with noopener", () => { + const open = spyOpen(); + openApiUrl("https://invoice.stripe.com/i/abc123"); + expect(open).toHaveBeenCalledWith( + "https://invoice.stripe.com/i/abc123", + "_blank", + "noopener,noreferrer", + ); + }); + + it("opens a relative URL by resolving it against the origin", () => { + const open = spyOpen(); + openApiUrl("/invoices/abc.pdf"); + expect(open).toHaveBeenCalledWith( + `${window.location.origin}/invoices/abc.pdf`, + "_blank", + "noopener,noreferrer", + ); + }); + + // The reason this module exists: a navigation sink must not evaluate script. + it.each([ + "javascript:alert(document.domain)", + "JavaScript:alert(1)", + "data:text/html,", + "vbscript:msgbox(1)", + "file:///etc/passwd", + ])("refuses %s", (hostile) => { + const open = spyOpen(); + openApiUrl(hostile); + expect(open).not.toHaveBeenCalled(); + }); + + it("does nothing for an empty or missing URL", () => { + const open = spyOpen(); + openApiUrl(null); + openApiUrl(undefined); + openApiUrl(""); + expect(open).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/editor/src/portal/api/externalUrl.ts b/frontend/editor/src/portal/api/externalUrl.ts new file mode 100644 index 0000000000..10919e1544 --- /dev/null +++ b/frontend/editor/src/portal/api/externalUrl.ts @@ -0,0 +1,25 @@ +/** + * Open a URL that arrived from the API — a Stripe hosted-invoice page or invoice + * PDF — in a new tab, after checking its scheme. + * + * These values are relayed from Stripe through our own edge functions, so they + * are not attacker-controlled today. But a `javascript:` or `data:` URL reaching + * a navigation sink is an XSS primitive, and nothing between Stripe and this call + * promises the field can only ever hold a web address. Anything that is not plain + * http(s) is dropped instead of opened. + */ +export function openApiUrl(url: string | null | undefined): void { + if (!url) return; + let parsed: URL; + try { + parsed = new URL(url, window.location.origin); + } catch { + console.warn("[portal] refusing to open an unparseable URL"); + return; + } + if (parsed.protocol !== "https:" && parsed.protocol !== "http:") { + console.warn(`[portal] refusing to open a ${parsed.protocol} URL`); + return; + } + window.open(parsed.href, "_blank", "noopener,noreferrer"); +} diff --git a/frontend/editor/src/portal/api/procurement.ts b/frontend/editor/src/portal/api/procurement.ts index 4d8a28e057..b49de2f6b6 100644 --- a/frontend/editor/src/portal/api/procurement.ts +++ b/frontend/editor/src/portal/api/procurement.ts @@ -1,12 +1,12 @@ import { apiClient } from "@portal/api/http"; +import { resolveDemoResponse } from "@portal/api/demoData"; +import { saasApiBase } from "@portal/api/saasApiBase"; import { getSupabaseClient } from "@app/auth/supabase/supabaseClient"; -import type { Tier } from "@portal/contexts/TierContext"; /* - * Procurement models the enterprise commercial journey, trial → quote → - * agreement → payment → implementation, plus the paperwork ledger that rides - * alongside it. The journey is enterprise-only; free/pro tiers receive a - * minimal locked payload the view renders as an upgrade prompt. + * Procurement models the enterprise commercial journey: trial → quote → agreement → payment → + * implementation. It is surfaced by the deal-status hero on Home and the takeover flow beside it; + * there is no separate procurement route. */ /* ──────────────────────────────────────────────────────────────────────── */ @@ -19,11 +19,8 @@ import type { Tier } from "@portal/contexts/TierContext"; * Payment read more plainly than the internal `security` / `procurement`). */ export type DealStage = - | "trial" - | "quote" - | "security" - | "procurement" - | "active"; + /** Asked about enterprise, nothing committed yet. Precedes the journey rather than joining it. */ + "exploring" | "trial" | "quote" | "security" | "procurement" | "active"; export interface JourneyStep { stage: DealStage; @@ -38,9 +35,14 @@ export interface JourneyStep { gatingAction: string; } -/** Ordered journey definition, the stepper renders this verbatim. */ -/** `label`/`blurb`/`gatingAction` values are i18n keys — render with t(). */ -export const JOURNEY: JourneyStep[] = [ +/** + * The commercial flow's stages, rendered verbatim as the hero's progress band. Quote and Agreement + * are distinct: the buyer accepts the quote first (no Stripe), then signs the agreement, which is + * what accepts into a committed subscription. + * + *

`label`/`blurb`/`gatingAction` are i18n keys — render with t(). + */ +export const FLOW_JOURNEY: JourneyStep[] = [ { stage: "trial", label: "portal.procurement.journeySteps.trial.label", @@ -73,204 +75,9 @@ export const JOURNEY: JourneyStep[] = [ }, ]; -/** - * The commercial flow's stepper stages. The real backend collapses quote + agreement into one - * accept step (accepting the issued quote is accepting the agreement), so the flow shows one fewer - * step than the mock ledger's {@link JOURNEY} — the separate "Agreement" step is dropped. Reuses - * JOURNEY's i18n keys. - */ -export const FLOW_JOURNEY: JourneyStep[] = JOURNEY.filter( - (s) => s.stage !== "security", -); - -/* ──────────────────────────────────────────────────────────────────────── */ -/* Deal header */ -/* ──────────────────────────────────────────────────────────────────────── */ - -export interface SolutionsEngineer { - name: string; - title: string; - email: string; -} - -export interface TrialInfo { - /** License key seeded for the evaluation. */ - key: string; - /** ISO date the trial began. */ - startedOn: string; - /** ISO date the trial expires. */ - endsOn: string; - /** Whole days remaining (derived in the fixture for a stable demo number). */ - daysLeft: number; - extensionsUsed: number; - maxExtensions: number; -} - -export interface QuoteInfo { - number: string; - /** Annual contract value, in USD. */ - amount: number; - /** Contract term, e.g. "12 months". */ - term: string; - /** ISO date the quote expires. */ - validUntil: string; -} - -export interface Deal { - company: string; - currentStage: DealStage; - engineer: SolutionsEngineer; - trial: TrialInfo; - quote: QuoteInfo; -} - -/* ──────────────────────────────────────────────────────────────────────── */ -/* Document ledger + supporting pool */ -/* ──────────────────────────────────────────────────────────────────────── */ - -/** - * Lifecycle of a single document. - * available: ready to grab now (download/sign/pay/upload as the action says) - * action: waiting on the buyer to act (the gating paperwork of a stage) - * pending: issued, awaiting the other side / a system step - * request: not generated yet; the buyer asks for it (some carry a fee) - * complete: done, kept for the record - */ -export type DocStatus = - | "available" - | "action" - | "pending" - | "request" - | "complete"; - -/** What pressing the document's button does. */ -export type DocAction = "download" | "sign" | "pay" | "upload" | "request"; - -export interface LedgerDoc { - id: string; - name: string; - /** Sub-line describing what the document is / what it covers. */ - sub: string; - status: DocStatus; - action: DocAction; - /** Buyer-skippable paperwork (e.g. paid onboarding). */ - optional?: boolean; - /** One-off fee in USD when the document/service is a paid add-on. */ - fee?: number; -} - -/** Document ledger grouped by the journey stage the paperwork belongs to. */ -export interface LedgerGroup { - stage: DealStage; - /** Buyer-facing stage name (matches JourneyStep.label). */ - label: string; - docs: LedgerDoc[]; -} - -/** Categories the stage-agnostic supporting pool is grouped under. */ -export type SupportingCategory = - | "security" - | "legal" - | "corporate" - | "procurement"; - -export interface SupportingGroup { - category: SupportingCategory; - label: string; - docs: LedgerDoc[]; -} - -/* ──────────────────────────────────────────────────────────────────────── */ -/* Full procurement payload */ -/* ──────────────────────────────────────────────────────────────────────── */ - -export interface ProcurementResponse { - tier: Tier; - /** True only for enterprise, gates the whole journey + ledger. */ - unlocked: boolean; - /** Present only when unlocked. */ - deal: Deal | null; - journey: JourneyStep[]; - ledger: LedgerGroup[]; - supporting: SupportingGroup[]; -} - -/** GET /v1/procurement?tier=…, the deal, journey, ledger and supporting pool. */ -export async function fetchProcurement( - tier: Tier, -): Promise { - return apiClient.local.json( - `/v1/procurement?tier=${encodeURIComponent(tier)}`, - ); -} - -/* - * Commercial actions. Each mutates the deal server-side and returns the updated - * ProcurementResponse, the new canonical state, which the view applies so the - * journey progresses. The MSW layer answers these today; a real backend honours - * the same contracts unchanged. - */ - -/** Advance the deal to the next stage (the journey's primary CTA). */ -export async function advanceStage( - fromStage: DealStage, -): Promise { - return apiClient.local.json("/v1/procurement/advance", { - method: "POST", - body: { fromStage }, - }); -} - -/** Sign the Stirling Enterprise Agreement (MSA + order form + EULA + DPA). */ -export async function signAgreement( - docId: string, -): Promise { - // A real backend opens an e-signature envelope and completes on callback; - // here it completes immediately and advances the deal. - return apiClient.local.json("/v1/procurement/sign", { - method: "POST", - body: { docId }, - }); -} - -/** Pay the contract online (card / bank transfer via Stripe). */ -export async function payOnline(): Promise { - return apiClient.local.json("/v1/procurement/pay", { - method: "POST", - }); -} - -/** Upload a purchase order to invoice against (an alternate payment path). */ -export async function uploadPurchaseOrder( - file: File, -): Promise { - // A real backend takes the PO as multipart; the mock only needs the name. - return apiClient.local.json( - "/v1/procurement/purchase-order", - { - method: "POST", - body: { fileName: file.name }, - }, - ); -} - -/** Request a document that is generated on demand (some carry a one-off fee). */ -export async function requestDocument( - docId: string, - action: DocAction, -): Promise { - return apiClient.local.json( - `/v1/procurement/documents/${encodeURIComponent(docId)}/request`, - { method: "POST", body: { action } }, - ); -} - // ============================================================================ -// Enterprise procurement — real SaaS backend (/api/v1/procurement). -// -// The journey/ledger visuals above still ride the MSW mock; the commercial spine -// below (trial, server-priced quote, accept -> Stripe checkout) is the real thing, -// served by the saas Java backend and gated on a linked account. +// Enterprise procurement — the real SaaS backend (/api/v1/procurement): trial, +// server-priced quote, agreement, accept -> Stripe. Gated on a linked account. // ============================================================================ export type QuoteLineItemKind = @@ -288,7 +95,11 @@ export interface QuoteLineItem { export interface QuoteResult { quoteId: number; - quoteNumber: string; + /** + * Stripe's quote number — the deal's one reference, shown on the quote, the agreement and the + * invoice. Null while the quote is a local draft: Stripe assigns it only at finalisation. + */ + quoteNumber: string | null; /** draft (priced, editable) | sent (issued Stripe quote — PDF + shareable) | accepted | expired. */ status: string; currency: string; @@ -332,6 +143,12 @@ export interface ProcurementSnapshot { licensed: boolean; /** The team's Keygen licence key (present once licensed); shown in the portal to copy/install. */ licenseKey: string | null; + /** Version label of the signed agreement PDF available to download (e.g. "SEA v0.9.1"), else null. */ + agreementSignedVersion: string | null; + /** Buying entity captured at trial setup; null on deals started before that step existed. */ + businessName: string | null; + contactName: string | null; + contactEmail: string | null; latestQuote: QuoteResult | null; } @@ -385,13 +202,37 @@ export function fetchLicenseFile(): Promise { * Start the trial with the buyer's chosen deployment target and seat count (captured in the setup * step). These seed the quote builder; both remain editable when the quote is built. */ +/** Details collected by trial setup's second step; every field optional server-side. */ +export interface TrialSetupDetails { + businessName?: string; + contactName?: string; + contactEmail?: string; + /** + * Raw comma/space/semicolon separated addresses. Recorded on the deal AND sent through the + * team-invite path once the trial starts; a rejected address is skipped, never fatal. + */ + inviteEmails?: string; +} + export function startTrial( deployment: string, seats: number, + details?: TrialSetupDetails, ): Promise { return apiClient.saas.json( "/api/v1/procurement/trial/start", - { method: "POST", body: { deployment, users: seats } }, + { method: "POST", body: { deployment, users: seats, ...details } }, + ); +} + +/** + * Record that this account is looking at enterprise. Idempotent, and never disturbs an existing + * deal — so it is safe to call on every entry into the flow. + */ +export function recordInterest(): Promise { + return apiClient.saas.json( + "/api/v1/procurement/interest", + { method: "POST" }, ); } @@ -418,12 +259,114 @@ export function buildQuote(cfg: QuoteConfigInput): Promise { }); } +/** The filled enterprise agreement (MSA + Order Form + DPA) for the current quote, as markdown. */ +export interface AgreementDocument { + docId: string; + version: string; + /** e.g. "SEA v0.9.1" — the exact document version a signature will be pinned to. */ + versionLabel: string; + displayName: string; + effectiveDate: string; + /** "draft" until counsel clears it — the UI badges drafts. */ + status: string; + markdown: string; +} + +/** Buyer-supplied signing inputs captured on the agreement stage. */ +export interface SignAgreementInput { + customerLegalName: string; + signatoryName: string; + signatoryTitle: string; + authorityConfirmed: boolean; +} + +export interface SignAgreementResult { + signatureId: number; + versionLabel: string; + /** Whether the signed PDF was rendered + stored (false when the render runtime was unavailable). */ + pdfStored: boolean; +} + +/** Fetch the filled agreement to review before signing. */ +export function fetchAgreementDocument(): Promise { + return apiClient.saas.json( + "/api/v1/procurement/agreement/document", + ); +} + +/** Record the signed agreement (pins version + hash + variable snapshot + signatory + PDF). */ +export function recordAgreementSignature( + input: SignAgreementInput, +): Promise { + return apiClient.saas.json( + "/api/v1/procurement/agreement/sign", + { method: "POST", body: input }, + ); +} + +/** Fetch a static legal document (eula, sla, subprocessors) by id for in-product viewing. */ +export function fetchLegalDocument(docId: string): Promise { + return apiClient.saas.json(`/api/v1/legal/${docId}`); +} + +/** Download the stored, signed enterprise-agreement PDF for the team (post-signing). */ +export function fetchSignedAgreementPdf(): Promise { + return apiClient.saas.blob("/api/v1/procurement/agreement/signature/pdf"); +} + +/** Download the current (unsigned) enterprise-agreement PDF — the document shown at the sign step. */ +export function fetchAgreementPdf(): Promise { + return apiClient.saas.blob("/api/v1/procurement/agreement/document/pdf"); +} + +/** + * Record a clickwrap consent to a legal document (e.g. the EULA at trial start / quote generation). + * Best-effort — never block the flow it accompanies on a consent-logging failure. + */ +export function recordLegalConsent( + documentId: string, + context: string, +): Promise { + return apiClient.saas + .json("/api/v1/legal/consent", { + method: "POST", + body: { documentId, context }, + }) + .catch(() => undefined); +} + // ---- Stripe Quote operations (Supabase edge functions) --------------------- // Java has no Stripe SDK, so issuing/accepting the quote and fetching its PDF run in edge functions // that own Stripe; they persist results back through SECURITY DEFINER RPCs. The portal invokes them // directly (same pattern the PAYG checkout uses). +/** + * Fixture response for an edge function while demo data is on. + * + * These calls go out through the Supabase client rather than {@code apiClient}, which is where demo + * data is normally intercepted — so until this existed they were never mocked. The portal has no + * service worker: the MSW handlers are matched by URL inside {@link resolveDemoResponse}, so the URL + * has to be reconstructed here to match what mocks/handlers/procurementSaas.ts registers. + * + * This mattered rather more than a missing fixture: issue and accept create a real Stripe Quote and a + * real committed subscription. With a live session — the normal state when developing against the + * shared project — pressing "Generate quote" in dev billed nothing but left real objects behind. + */ +async function demoEdgeResponse( + fn: string, + quoteId: number, +): Promise { + const base = saasApiBase(); + if (!base) return undefined; + return resolveDemoResponse(new URL(`${base}/functions/v1/${fn}`), { + method: "POST", + body: { quote_id: quoteId }, + }); +} + async function invokeEdge(fn: string, quoteId: number): Promise { + const demo = await demoEdgeResponse(fn, quoteId); + if (demo) return (await demo.json()) as T; const supabase = getSupabaseClient(); if (!supabase) throw new Error("No SaaS session"); const { data, error } = await supabase.functions.invoke(fn, { @@ -446,6 +389,8 @@ export function acceptQuote(quoteId: number): Promise { /** Fetch the Stripe-generated quote PDF as a blob (for download / share). */ export async function fetchQuotePdf(quoteId: number): Promise { + const demo = await demoEdgeResponse("get-procurement-quote-pdf", quoteId); + if (demo) return await demo.blob(); const supabase = getSupabaseClient(); if (!supabase) throw new Error("No SaaS session"); const { data, error } = await supabase.functions.invoke( diff --git a/frontend/editor/src/portal/components/EditorStatusCard.css b/frontend/editor/src/portal/components/EditorStatusCard.css index e71a50bac3..692d08adc3 100644 --- a/frontend/editor/src/portal/components/EditorStatusCard.css +++ b/frontend/editor/src/portal/components/EditorStatusCard.css @@ -13,20 +13,18 @@ .portal-editor-hero__row { display: flex; align-items: center; - gap: 1.25rem; - padding: 1rem 1.25rem; - background: color-mix(in srgb, var(--c-primary) 22%, var(--c-hero-dark)); + gap: 0.75rem; + padding: 0.625rem 0.875rem; + background: var(--c-surface); } .portal-editor-hero__logo { - width: 3.5rem; - height: 3.5rem; - border-radius: 0.875rem; + width: 2rem; + height: 2rem; + border-radius: 0.5rem; overflow: hidden; flex-shrink: 0; - box-shadow: - 0 2px 8px rgba(0, 0, 0, 0.1), - 0 0 0 1px rgba(0, 0, 0, 0.06); + box-shadow: var(--shadow-sm); } .portal-editor-hero__mark { width: 100%; @@ -39,7 +37,7 @@ min-width: 0; display: flex; flex-direction: column; - gap: 0.5rem; + gap: 0.25rem; } .portal-editor-hero__title-row { @@ -50,31 +48,36 @@ } .portal-editor-hero__name { - font-size: 1.125rem; + font-size: 0.9375rem; font-weight: 700; - color: #fff; + color: var(--c-text); margin-right: 0.125rem; } -.portal-editor-hero__chip { - display: inline-flex; - align-items: center; - gap: 0.3125rem; - padding: 0.25rem 0.6875rem; - border-radius: var(--radius-pill); - border: 1px solid rgba(255, 255, 255, 0.16); - background: rgba(255, 255, 255, 0.08); - color: rgba(255, 255, 255, 0.85); - font-size: 0.71875rem; - font-weight: 600; - cursor: pointer; - transition: background var(--motion-fast); +/* The deployment host, sat inline with the name as the rail's subject. */ +.portal-editor-hero__host { + font-family: var(--font-mono); + font-size: 0.8125rem; + font-weight: 500; + color: var(--c-text-muted); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } -.portal-editor-hero__chip:hover { - background: rgba(255, 255, 255, 0.16); + +/* Quiet separator between the host and the adoption count. */ +.portal-editor-hero__dot { + width: 0.3125rem; + height: 0.3125rem; + border-radius: 999px; + background: var(--c-border); + flex-shrink: 0; } -.portal-editor-hero__chip svg { - color: rgba(255, 255, 255, 0.6); + +.portal-editor-hero__actives { + font-size: 0.75rem; + color: var(--c-text-muted); + white-space: nowrap; } .portal-editor-hero__meta { @@ -83,15 +86,10 @@ gap: 0.5rem; flex-wrap: wrap; font-size: 0.75rem; - color: rgba(255, 255, 255, 0.5); -} -.portal-editor-hero__host { - color: rgba(255, 255, 255, 0.92); - font-family: var(--font-mono); - font-weight: 500; + color: var(--c-text-subtle); } .portal-editor-hero__meta-sep { - color: rgba(255, 255, 255, 0.3); + color: var(--c-border); } .portal-editor-hero__action { @@ -101,35 +99,6 @@ gap: 0.5rem; } -/* Icon-only actions (e.g. install) on the dark header. */ -.portal-editor-hero__icon-btn { - display: grid; - place-items: center; - width: 2.25rem; - height: 2.25rem; - flex-shrink: 0; - border-radius: var(--radius-md); - border: 1px solid rgba(255, 255, 255, 0.16); - background: rgba(255, 255, 255, 0.08); - color: #fff; - cursor: pointer; - transition: background var(--motion-fast); -} -.portal-editor-hero__icon-btn:hover { - background: rgba(255, 255, 255, 0.16); -} - -/* White CTA on the dark header, matching the marketing card. */ -.portal-editor-hero__action .portal-editor-hero__cta.sui-btn { - background: #ffffff; - border-color: #ffffff; - color: var(--c-hero-dark-cta-text); -} -.portal-editor-hero__action .portal-editor-hero__cta.sui-btn:hover { - background: rgba(255, 255, 255, 0.88); - border-color: rgba(255, 255, 255, 0.88); -} - @media (max-width: 48rem) { .portal-editor-hero__row { flex-wrap: wrap; diff --git a/frontend/editor/src/portal/components/EditorStatusCard.stories.tsx b/frontend/editor/src/portal/components/EditorStatusCard.stories.tsx index 9e73983026..144ded6dc4 100644 --- a/frontend/editor/src/portal/components/EditorStatusCard.stories.tsx +++ b/frontend/editor/src/portal/components/EditorStatusCard.stories.tsx @@ -1,19 +1,6 @@ import type { Meta, StoryObj } from "@storybook/react-vite"; import { http, HttpResponse } from "msw"; import { EditorStatusCard } from "@portal/components/EditorStatusCard"; -import { SetupChecklist } from "@portal/components/SetupChecklist"; -import type { OnboardingProgress } from "@portal/hooks/useOnboardingProgress"; - -const progress: OnboardingProgress = { - loading: false, - deployed: true, - editorDone: true, - policiesDone: true, - inviteDone: false, - policiesActive: 3, - policiesRecommended: 4, - allComplete: false, -}; const meta: Meta = { title: "Portal/Home/EditorStatusCard", @@ -31,25 +18,14 @@ const meta: Meta = { export default meta; type Story = StoryObj; -/** The deployed-Editor status card on its own. */ +/** The deployment rail, reporting a live deployment. */ export const Default: Story = {}; -/** As it renders on the subscribed home: the setup checklist attached as the footer. */ -export const WithSetupChecklist: Story = { - args: { - footer: , - }, -}; - /** - * Backend without the editor-deployment endpoint (404): the status row is - * skipped and the card falls back to just the footer (setup checklist). It - * lights up automatically once /v1/editor/deployment is served. + * Backend without the editor-deployment endpoint (404): the rail keeps its identity and the neutral + * deploy ask, and states no host or adoption figure, since neither can be read. */ export const DeploymentUnavailable: Story = { - args: { - footer: , - }, parameters: { msw: { handlers: [ diff --git a/frontend/editor/src/portal/components/EditorStatusCard.tsx b/frontend/editor/src/portal/components/EditorStatusCard.tsx index 9726cc1009..b506a0a366 100644 --- a/frontend/editor/src/portal/components/EditorStatusCard.tsx +++ b/frontend/editor/src/portal/components/EditorStatusCard.tsx @@ -3,15 +3,12 @@ import { Fragment, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { Button, Skeleton } from "@app/ui"; import { useTier } from "@portal/contexts/TierContext"; -import { useView } from "@portal/contexts/ViewContext"; -import { useEditorDeployment } from "@portal/queries/infrastructure"; -import { type EditorInstance } from "@portal/api/editorDeploy"; +import { EDITOR_URL } from "@portal/auth/editorUrl"; import { - DownloadIcon, - ExternalLinkIcon, - UsersIcon, - UserPlusIcon, -} from "@portal/components/icons"; + useEditorDeployment, + useFleetStats, +} from "@portal/queries/infrastructure"; +import { type EditorInstance } from "@portal/api/editorDeploy"; import { DownloadEditorModal } from "@portal/components/DownloadEditorModal"; import "@portal/components/EditorStatusCard.css"; @@ -48,41 +45,64 @@ function primaryInstance(instances: EditorInstance[]): EditorInstance | null { ); } +/** + * The rail's primary action matures with adoption rather than deployment alone (marketing note + * D243): the loud ask only stands while the org is still one person on an undeployed editor. Once + * a deployment is in flight, finishing it takes over; once teammates are in, the ask goes quiet. + */ +type DeployAsk = "finish" | "start" | "options"; + +function deployAsk( + instances: EditorInstance[], + activeUsers: number, +): DeployAsk { + const deployed = instances.some((i) => i.status === "healthy"); + if (!deployed && instances.some((i) => i.status === "pairing")) + return "finish"; + if (!deployed && activeUsers <= 1) return "start"; + return "options"; +} + interface EditorStatusCardProps { - /** - * Rendered as an attached footer strip inside the card (e.g. the "Finish - * setting up" checklist), matching the free-tier hero's footer seam. - */ + /** Attached footer strip inside the card — the deal-status hero while a deal is underway. */ footer?: ReactNode; - /** - * Hide the active-users / invite chips. Used on enterprise, where the - * attached procurement deal hero already owns the invite action. - */ - hideChips?: boolean; } /** - * Subscribed/enterprise home hero: a status card for the org's deployed PDF - * Editor. Reads the same `/v1/editor/deployment` data as the Editor admin view - * (host, version, live users, deployment shape) and headlines the busiest - * instance, with a single "Open in browser" action to the workspace URL. + * The Home hero: the deployment rail for the org's PDF Editor. Host and build meta come from the + * same `/v1/editor/deployment` data as the Editor admin view, headlining the busiest instance; the + * adoption count is the figure Usage & Billing reports. The rail always renders — it carries the + * deploy ask itself — and each figure stands down independently when its source can't supply it. */ -export function EditorStatusCard({ footer, hideChips }: EditorStatusCardProps) { +export function EditorStatusCard({ footer }: EditorStatusCardProps) { const { t } = useTranslation(); const { tier } = useTier(); - const { setActiveView } = useView(); const [installOpen, setInstallOpen] = useState(false); const { data, loading } = useEditorDeployment(tier); + // The adoption figure is the same one Usage & Billing reports, read through the shared cache so + // the two agree and only one request is made. Either field is null when the backend can't compute + // it (e.g. EE auditing off), in which case the rail states no figure rather than a misleading 0. + const { data: fleet } = useFleetStats(); + const adoption = + fleet?.activeThisMonth != null && fleet.editorsDeployed != null + ? { active: fleet.activeThisMonth, total: fleet.editorsDeployed } + : null; const view = useMemo(() => { if (!data) return null; - const primary = primaryInstance(data.instances); - if (!primary) return null; const activeUsers = data.instances.reduce((s, i) => s + i.activeUsers, 0); + const ask = deployAsk(data.instances, activeUsers); + const primary = primaryInstance(data.instances); + // Nothing deployed yet: the rail still shows, carrying the deploy ask. Only the host and + // build meta are instance-derived, so they simply stand down. + if (!primary) { + return { host: null, activeUsers, ask, meta: [] as string[] }; + } const targetLabel = t(`portal.home.editor.target.${primary.target}`); return { host: primary.host, activeUsers, + ask, workspaceUrl: data.summary.workspaceUrl, meta: [ // Skip the deployment label when it just repeats the host (e.g. the @@ -95,21 +115,8 @@ export function EditorStatusCard({ footer, hideChips }: EditorStatusCardProps) { }; }, [data, t]); - const ready = !loading && !!view; - // The editor-deployment endpoint isn't implemented on every backend yet. - // When it's unavailable (finished loading with no data — e.g. a 404), skip - // the status row entirely and fall back to just the footer (the setup - // checklist, which reads supported endpoints). It lights up automatically - // once the backend serves /v1/editor/deployment. - const unavailable = !loading && !view; - - if (unavailable) { - return footer ? ( -

- {footer} -
- ) : null; - } + // Only the deploy ask can go loud; unknown deployment state keeps it quiet. + const loudAsk = !!view && view.ask !== "options"; return (
- {!ready || !view ? ( + {/* Each figure stands down on its own: the host and build meta need the deployment + endpoint, the adoption count needs fleet stats. Neither absence blanks the rail, and + nothing is asserted that its own source could not supply. */} + {loading ? ( <> @@ -133,65 +143,60 @@ export function EditorStatusCard({ footer, hideChips }: EditorStatusCardProps) { {t("portal.home.editor.name")} - {!hideChips && ( - + {view?.host && ( + {view.host} + )} + {adoption && ( + <> + + + {t("portal.home.editor.activeOfDeployed", adoption)} + + )}
-
- {view.host} - {view.meta.map((item, i) => ( - - · - {item} - - ))} -
+ {view && view.meta.length > 0 && ( +
+ {view.meta.map((item, i) => ( + + {i > 0 && ( + · + )} + {item} + + ))} +
+ )} )} + {/* Open in browser is a left-seated secondary in every state, and carries no arrow + (marketing note D244); the deploy ask beside it is the only button that can go loud. + Reaching the editor never depends on deployment data — it falls back to the configured + editor URL — so this stays live even when the deployment endpoint is unavailable. */}
- {!hideChips && ( - - )} - +
diff --git a/frontend/editor/src/portal/components/HomeHero.stories.tsx b/frontend/editor/src/portal/components/HomeHero.stories.tsx index dd1ea07c04..8784bde97a 100644 --- a/frontend/editor/src/portal/components/HomeHero.stories.tsx +++ b/frontend/editor/src/portal/components/HomeHero.stories.tsx @@ -16,17 +16,10 @@ const meta = { export default meta; type Story = StoryObj; -/** Pay-as-you-go tier: welcome header + setup checklist until onboarding completes. */ -export const Default: Story = { - args: { tier: "pro" }, -}; - -/** Free tier renders the same welcome-header composition as pro. */ -export const FreeTier: Story = { - args: { tier: "free" }, -}; - -/** Enterprise tier hides the status chips — the procurement deal hero owns the invite step. */ -export const EnterpriseTier: Story = { - args: { tier: "enterprise" }, -}; +/** + * The hero is the Editor deployment rail on every tier and in both editions — it reports its own + * deployment state and deploy ask, so there is nothing tier-specific left to compose. A live + * procurement deal attaches the deal-status hero as the rail's footer; that comes from + * useProcurement, so it follows the mocked backend rather than a story arg. + */ +export const Default: Story = {}; diff --git a/frontend/editor/src/portal/components/HomeHero.tsx b/frontend/editor/src/portal/components/HomeHero.tsx index 03bcc17ed0..e81d42dfef 100644 --- a/frontend/editor/src/portal/components/HomeHero.tsx +++ b/frontend/editor/src/portal/components/HomeHero.tsx @@ -1,60 +1,50 @@ -import type { Tier } from "@portal/contexts/TierContext"; +import { useEffect } from "react"; +import { Skeleton } from "@app/ui"; import { useUI } from "@portal/contexts/UIContext"; -import { WelcomeBanner } from "@portal/components/WelcomeBanner"; import { EditorStatusCard } from "@portal/components/EditorStatusCard"; -import { SetupChecklist } from "@portal/components/SetupChecklist"; -import { useOnboardingProgress } from "@portal/hooks/useOnboardingProgress"; import { ControlledDealStatusHero } from "@portal/components/procurement/ProcurementBanner"; import { ProcurementFlow } from "@portal/components/procurement/ProcurementFlow"; import { useProcurement } from "@portal/components/procurement/useProcurement"; /** - * The Home hero, composed with a procurement-aware, progress-aware footer: - * - * - no live deployment → welcome header (+ setup steps until complete) - * - deployment live → deployed-Editor status header (+ steps until complete) - * - onboarding complete → header only; the setup steps collapse away - * - enterprise → status header with chips hidden (the deal hero owns invite) - * - * The footer is the deal-status hero while a procurement deal is underway - * (procurement is a bolt-on to any tier); otherwise the setup checklist, until - * every step is done — then it collapses to just the header, matching the - * deployed-status card. The procurement takeover modals render alongside. + * The Home hero: always the Editor deployment rail, carrying the deal-status hero as its footer + * while a procurement deal is underway (procurement is a bolt-on to any tier). The rail states its + * own deployment status and deploy ask, so there is nothing for a tier to choose between. The + * procurement takeover modals render alongside. */ -export function HomeHero({ tier }: { tier: Tier }) { - const { openLinkModal } = useUI(); +export function HomeHero() { const procurement = useProcurement(); - const progress = useOnboardingProgress(); + const { trialSetupRequested, clearTrialSetupRequest } = useUI(); const dealActive = procurement.isLinked && procurement.started && !!procurement.data; - // Start the enterprise flow right here on Home: open the trial-setup modal when the account is - // linked, otherwise prompt to link first — no navigating off to the procurement view. - const onStartEnterprise = () => { - if (procurement.isLinked) procurement.onStartTrial(); - else openLinkModal(); - }; - - // Steps collapse once onboarding is complete; a live deal always keeps its - // hero. Otherwise the setup checklist carries the (progress-aware) steps. - const footer = dealActive ? ( - - ) : progress.allComplete ? undefined : ( - - ); - - // The live-status header (EditorStatusCard) needs a real deployment to show; - // without one it renders nothing, so route to it only when actually deployed. - // Everything else — including a step completed via the local download flag — - // keeps the always-present welcome header, so the card never vanishes. - const showStatus = progress.deployed; + // Someone said yes to enterprise elsewhere (the billing upsell, a sales link). Open trial setup + // once the snapshot has landed, so a buyer who already has a deal is not asked to start another. + useEffect(() => { + if (!trialSetupRequested || procurement.loading) return; + clearTrialSetupRequest(); + if (!procurement.started) procurement.onExploreEnterprise(); + }, [trialSetupRequested, procurement, clearTrialSetupRequest]); return ( <> - {showStatus ? ( - + {procurement.loading ? ( + // Hold the rail's shape rather than committing to a footer: branching before the snapshot + // lands paints the no-deal rail first, flashing on every refresh of an active deal. +
+
+ + +
+
) : ( - + + ) : undefined + } + /> )} diff --git a/frontend/editor/src/portal/components/SetupChecklist.css b/frontend/editor/src/portal/components/SetupChecklist.css deleted file mode 100644 index 0fcb71e678..0000000000 --- a/frontend/editor/src/portal/components/SetupChecklist.css +++ /dev/null @@ -1,122 +0,0 @@ -/* ──────────────────────────────────────────────────────────────────────── */ -/* Getting-started steps (home-hero body) */ -/* ──────────────────────────────────────────────────────────────────────── */ - -.portal-setup { - display: flex; - flex-direction: column; -} - -.portal-setup__list { - list-style: none; - margin: 0; - padding: 0; -} - -.portal-setup__row { - display: grid; - grid-template-columns: auto 1fr; - align-items: center; - gap: 0.875rem; - width: 100%; - padding: 0.6875rem 1.25rem; - border: none; - border-top: 1px solid var(--c-border-subtle); - background: transparent; - text-align: left; - cursor: pointer; - transition: background var(--motion-fast); -} -.portal-setup__item:first-child .portal-setup__row { - border-top: none; -} -.portal-setup__row:hover { - background: var(--c-hover); -} - -/* Numbered step marker */ -.portal-setup__num { - display: grid; - place-items: center; - width: 1.5rem; - height: 1.5rem; - flex-shrink: 0; - border-radius: 50%; - border: 1px solid var(--c-border); - font-size: 0.75rem; - font-weight: 600; - color: var(--c-text-subtle); -} -/* Completed step: filled green check. */ -.portal-setup__num.is-done { - border-color: var(--color-green); - background: var(--color-green); - color: #fff; -} -.portal-setup__row.is-done .portal-setup__text strong { - color: var(--c-text-muted); -} - -.portal-setup__text { - display: flex; - flex-direction: column; - min-width: 0; -} -.portal-setup__text strong { - font-size: 0.875rem; - font-weight: 600; - color: var(--c-text); -} -.portal-setup__text span { - font-size: 0.75rem; - line-height: 1.4; - color: var(--c-text-subtle); -} - -/* ── Enterprise upsell rung ── */ -.portal-setup__enterprise { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1rem; - flex-wrap: wrap; - padding: 0.75rem 1.25rem; - border-top: 1px solid var(--c-border-subtle); - background: linear-gradient( - 90deg, - color-mix(in srgb, var(--c-primary) 5%, transparent) 0%, - transparent 55% - ); -} - -.portal-setup__enterprise-copy { - display: flex; - align-items: center; - gap: 0.75rem; - min-width: 0; - flex: 1; -} - -.portal-setup__enterprise-tag { - flex-shrink: 0; - padding: 0.1875rem 0.5625rem; - border-radius: var(--radius-md); - font-size: 0.59375rem; - font-weight: 700; - letter-spacing: 0.06em; - text-transform: uppercase; - color: var(--c-primary-hover); - background: var(--c-primary-tint); -} - -.portal-setup__enterprise-text { - margin: 0; - font-size: 0.8125rem; - line-height: 1.45; - color: var(--c-text-subtle); - min-width: 0; -} -.portal-setup__enterprise-text strong { - color: var(--c-text); - font-weight: 700; -} diff --git a/frontend/editor/src/portal/components/SetupChecklist.stories.tsx b/frontend/editor/src/portal/components/SetupChecklist.stories.tsx deleted file mode 100644 index 432be155d7..0000000000 --- a/frontend/editor/src/portal/components/SetupChecklist.stories.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { SetupChecklist } from "@portal/components/SetupChecklist"; -import type { OnboardingProgress } from "@portal/hooks/useOnboardingProgress"; - -const base: OnboardingProgress = { - loading: false, - deployed: false, - editorDone: false, - policiesDone: false, - inviteDone: false, - policiesActive: 0, - policiesRecommended: 6, - allComplete: false, -}; - -const meta: Meta = { - title: "Portal/Home/SetupChecklist", - component: SetupChecklist, - parameters: { layout: "padded" }, - args: { progress: base }, - decorators: [ - (S) => ( -
- -
- ), - ], -}; -export default meta; -type Story = StoryObj; - -/** A fresh workspace — no step complete yet. */ -export const NotStarted: Story = {}; - -/** Policies confirmed; editor + invite still open. */ -export const InProgress: Story = { - args: { - progress: { - ...base, - policiesDone: true, - policiesActive: 2, - policiesRecommended: 5, - }, - }, -}; - -/** Editor deployed + policies on; only the invite step remains. */ -export const AlmostDone: Story = { - args: { - progress: { - ...base, - editorDone: true, - policiesDone: true, - policiesActive: 4, - policiesRecommended: 3, - }, - }, -}; diff --git a/frontend/editor/src/portal/components/SetupChecklist.tsx b/frontend/editor/src/portal/components/SetupChecklist.tsx deleted file mode 100644 index d854beb771..0000000000 --- a/frontend/editor/src/portal/components/SetupChecklist.tsx +++ /dev/null @@ -1,150 +0,0 @@ -import { useState } from "react"; -import { useTranslation } from "react-i18next"; -import { Button } from "@app/ui"; -import { useTier } from "@portal/contexts/TierContext"; -import { useView } from "@portal/contexts/ViewContext"; -import type { OnboardingProgress } from "@portal/hooks/useOnboardingProgress"; -import { DownloadEditorModal } from "@portal/components/DownloadEditorModal"; -import CheckRounded from "@mui/icons-material/CheckRounded"; -import "@portal/components/SetupChecklist.css"; - -/* ──────────────────────────────────────────────────────────────────────── */ -/* Enterprise upsell rung */ -/* ──────────────────────────────────────────────────────────────────────── */ - -/** - * Enterprise on-ramp rung. The CTA differs by tier: free orgs start a guided - * trial, subscribed (paying) orgs jump straight to a quote — both open the - * procurement flow. When {@code onStart} is given the CTA opens the flow's setup - * modal over Home; otherwise it falls back to navigating to the procurement view. - */ -function EnterpriseRung({ - paying, - onStart, -}: { - paying: boolean; - onStart?: () => void; -}) { - const { t } = useTranslation(); - const { setActiveView } = useView(); - return ( -
-
- - {t("portal.home.onboarding.enterprise.tag")} - -

- {t("portal.home.onboarding.enterprise.lead")}{" "} - {t("portal.home.onboarding.enterprise.body")} -

-
- -
- ); -} - -/* ──────────────────────────────────────────────────────────────────────── */ -/* Getting-started steps */ -/* ──────────────────────────────────────────────────────────────────────── */ - -interface Step { - id: string; - title: string; - blurb: string; - done: boolean; - onClick: () => void; -} - -/** - * Numbered getting-started steps, rendered as the body of the home hero. Each - * row opens its in-app surface; a completed step (from {@link OnboardingProgress}) - * swaps its number for a check. When every step is done the parent collapses the - * hero to the deployed-status header and stops rendering this list entirely. - */ -export function SetupChecklist({ - progress, - onStartEnterprise, -}: { - progress: OnboardingProgress; - /** Start the enterprise flow in place (opens the setup modal over Home). Falls back to - * navigating to the procurement view when omitted (e.g. in isolated stories). */ - onStartEnterprise?: () => void; -}) { - const { t } = useTranslation(); - const { tier } = useTier(); - const { setActiveView } = useView(); - const [downloadOpen, setDownloadOpen] = useState(false); - - const steps: Step[] = [ - { - id: "editor", - title: t("portal.home.onboarding.steps.editor.title"), - blurb: t("portal.home.onboarding.steps.editor.blurb"), - done: progress.editorDone, - // Downloads are per-OS, so open the install picker rather than route away. - onClick: () => setDownloadOpen(true), - }, - { - id: "policies", - title: t("portal.home.onboarding.steps.policies.title"), - blurb: t("portal.home.onboarding.steps.policies.blurb", { - active: progress.policiesActive, - recommended: progress.policiesRecommended, - }), - done: progress.policiesDone, - onClick: () => setActiveView("policies"), - }, - { - id: "invite", - title: t("portal.home.onboarding.steps.invite.title"), - blurb: t("portal.home.onboarding.steps.invite.blurb"), - done: progress.inviteDone, - onClick: () => setActiveView("users"), - }, - ]; - - return ( -
-
    - {steps.map((s, i) => ( -
  1. - -
  2. - ))} -
- - - - setDownloadOpen(false)} - /> -
- ); -} diff --git a/frontend/editor/src/portal/components/WelcomeBanner.css b/frontend/editor/src/portal/components/WelcomeBanner.css deleted file mode 100644 index 157ee24ac0..0000000000 --- a/frontend/editor/src/portal/components/WelcomeBanner.css +++ /dev/null @@ -1,103 +0,0 @@ -/* ──────────────────────────────────────────────────────────────────────── */ -/* Free-tier welcome hero — compact product header + steps */ -/* ──────────────────────────────────────────────────────────────────────── */ - -.portal-welcome { - border-radius: var(--radius-xl); - border: 1px solid var(--c-border-subtle); - overflow: hidden; - isolation: isolate; - background: var(--c-surface); -} - -/* ── Dark product header strip ── */ -.portal-welcome__header { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1rem; - flex-wrap: wrap; - padding: 0.875rem 1.25rem; - background: color-mix(in srgb, var(--c-primary) 22%, var(--c-hero-dark)); -} - -.portal-welcome__brand { - display: flex; - align-items: center; - gap: 0.875rem; - min-width: 0; -} - -.portal-welcome__mark { - display: grid; - place-items: center; - flex-shrink: 0; -} -.portal-welcome__mark img { - display: block; - height: 1.75rem; - width: auto; -} - -.portal-welcome__brand-text { - display: flex; - align-items: baseline; - gap: 0.625rem; - min-width: 0; - flex-wrap: wrap; -} - -.portal-welcome__product { - font-size: 1.125rem; - font-weight: 700; - letter-spacing: -0.01em; - color: #fff; -} - -.portal-welcome__stats { - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - font-size: 0.8125rem; - color: rgba(255, 255, 255, 0.55); -} - -/* Header action group: icon buttons + the CTA. */ -.portal-welcome__actions { - display: flex; - align-items: center; - gap: 0.5rem; -} -.portal-welcome__icon-btn { - display: grid; - place-items: center; - width: 2.25rem; - height: 2.25rem; - flex-shrink: 0; - border-radius: var(--radius-md); - border: 1px solid rgba(255, 255, 255, 0.16); - background: rgba(255, 255, 255, 0.08); - color: #fff; - cursor: pointer; - transition: background var(--motion-fast); -} -.portal-welcome__icon-btn:hover { - background: rgba(255, 255, 255, 0.16); -} - -/* White CTA on the dark header, matching the marketing card. */ -.portal-welcome__header .portal-welcome__cta.sui-btn { - background: #ffffff; - border-color: #ffffff; - color: var(--c-hero-dark-cta-text); -} -.portal-welcome__header .portal-welcome__cta.sui-btn:hover { - background: rgba(255, 255, 255, 0.88); - border-color: rgba(255, 255, 255, 0.88); -} - -/* ── Steps + enterprise (setup checklist) sit directly under the header ── */ -.portal-welcome__footer { - background: var(--c-surface); -} diff --git a/frontend/editor/src/portal/components/WelcomeBanner.stories.tsx b/frontend/editor/src/portal/components/WelcomeBanner.stories.tsx deleted file mode 100644 index 8dba4caf36..0000000000 --- a/frontend/editor/src/portal/components/WelcomeBanner.stories.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { WelcomeBanner } from "@portal/components/WelcomeBanner"; -import { SetupChecklist } from "@portal/components/SetupChecklist"; -import type { OnboardingProgress } from "@portal/hooks/useOnboardingProgress"; - -const progress: OnboardingProgress = { - loading: false, - deployed: false, - editorDone: false, - policiesDone: true, - inviteDone: false, - policiesActive: 2, - policiesRecommended: 5, - allComplete: false, -}; - -const meta: Meta = { - title: "Portal/Home/WelcomeBanner", - component: WelcomeBanner, - parameters: { layout: "padded" }, - decorators: [ - (S) => ( -
- -
- ), - ], -}; -export default meta; -type Story = StoryObj; - -/** The hero on its own, no attached footer. */ -export const Default: Story = {}; - -/** The hero as it renders on the free-tier home: the "Finish setting up" - * checklist attached as the footer strip. */ -export const WithSetupChecklist: Story = { - args: { - footer: , - }, -}; diff --git a/frontend/editor/src/portal/components/WelcomeBanner.tsx b/frontend/editor/src/portal/components/WelcomeBanner.tsx deleted file mode 100644 index c1d6857bdb..0000000000 --- a/frontend/editor/src/portal/components/WelcomeBanner.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import type { ReactNode } from "react"; -import { useState } from "react"; -import { useTranslation } from "react-i18next"; -import { Button } from "@app/ui"; -import { useView } from "@portal/contexts/ViewContext"; -import { EDITOR_URL } from "@portal/auth/editorUrl"; -import { - DownloadIcon, - ExternalLinkIcon, - UserPlusIcon, -} from "@portal/components/icons"; -import { DownloadEditorModal } from "@portal/components/DownloadEditorModal"; -import markDark from "@app/assets/brand/modern-logo/StirlingPDFLogoNoTextDark.svg"; -import "@portal/components/WelcomeBanner.css"; - -/* ──────────────────────────────────────────────────────────────────────── */ -/* Free-tier welcome hero */ -/* */ -/* A compact product header — brand mark, "PDF Editor" + social-proof */ -/* stats, and a single "Open in browser" CTA — over the getting-started */ -/* steps (passed in as {@code footer}). Deliberately lean: the onboarding */ -/* steps, not marketing copy, are the point of the card. */ -/* ──────────────────────────────────────────────────────────────────────── */ - -interface WelcomeBannerProps { - /** - * The getting-started steps + enterprise rung, rendered inside the card - * below the header. Kept as a slot so the hero stays a presentational shell. - */ - footer?: ReactNode; -} - -export function WelcomeBanner({ footer }: WelcomeBannerProps) { - const { t } = useTranslation(); - const { setActiveView } = useView(); - const [installOpen, setInstallOpen] = useState(false); - - return ( -
-
-
- - - -
- - {t("portal.welcome.productName")} - - - {t("portal.welcome.stats")} - -
-
-
- - - -
-
- - {footer &&
{footer}
} - - setInstallOpen(false)} - /> -
- ); -} diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx index b5d0d58a3b..7d322a7be6 100644 --- a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx +++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx @@ -665,7 +665,6 @@ export function BundleCheckoutModal({ {t("portal.billing.prepaid.buy.cancel", "Cancel")} - @@ -701,7 +700,6 @@ export function BundleCheckoutModal({ {t("portal.billing.prepaid.buy.back", "Back")} diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsx index d3a1baf036..e2bbb24a34 100644 --- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx +++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx @@ -85,7 +85,6 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) { const switchOnAction = isLeader ? ( } diff --git a/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx b/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx index c099836ee4..f07083f215 100644 --- a/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx +++ b/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx @@ -1,15 +1,14 @@ import { useTranslation } from "react-i18next"; -import { Button } from "@app/ui"; -// The trademarked Stirling wordmark — the font is baked into the SVG (no brand webfont is loaded), so -// we render the same asset the portal nav uses rather than styled text. Theme-switched in CSS. -import wordmarkLight from "@app/assets/brand/modern-logo/StirlingProcessorLogoBlackText.svg"; -import wordmarkDark from "@app/assets/brand/modern-logo/StirlingProcessorLogoWhiteText.svg"; +import { StepModalHeader } from "@portal/components/shared/StepModalHeader"; /** - * Shared header for the prepay-flow modals — the prepaid wizard (activation → calculator → pay, of 3) - * and the metered checkout (spend limit → payment, of 2): Stirling brand + "Step N of M" badge + close, - * an M-segment progress bar, and the step title. Pass {@code step=undefined} to hide the badge + - * progress (e.g. a terminal confirmation). + * The prepay flows' stepped header — the prepaid wizard (activation → calculator → pay, of 3) and + * the metered checkout (spend limit → payment, of 2). + * + * Chrome and copy only: the layout is the shared {@link StepModalHeader}, so this flow reads the + * same as every other stepped modal. Keeps the billing root class, which the framed-checkout rule + * targets to own the header's padding. Pass {@code step=undefined} to hide the badge + progress + * (e.g. a terminal confirmation). */ export function PrepayModalHeader({ step, @@ -24,68 +23,27 @@ export function PrepayModalHeader({ onClose: () => void; }) { const { t } = useTranslation(); - const showSteps = step != null; - const filled = step ?? 0; return ( -
-
-
- Stirling - -
-
- {showSteps && ( - - {t( - "portal.billing.prepaid.buy.step", - "Step {{current}} of {{total}}", - { current: step, total }, - )} - - )} -
-
- {showSteps && ( -
- = 1 ? "is-filled" : ""} /> - = 2 ? "is-filled" : ""} /> - {total >= 3 && = 3 ? "is-filled" : ""} />} -
- )} -
{title}
-
+ ); } diff --git a/frontend/editor/src/portal/components/billing/SpendLimitCard.tsx b/frontend/editor/src/portal/components/billing/SpendLimitCard.tsx index 9ee2fa1f5e..5c7b510618 100644 --- a/frontend/editor/src/portal/components/billing/SpendLimitCard.tsx +++ b/frontend/editor/src/portal/components/billing/SpendLimitCard.tsx @@ -191,7 +191,7 @@ export function SpendLimitCard({ > {t("portal.billing.spendLimit.cancel", "Cancel")} - diff --git a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx index 4787c40b37..ee76a780c2 100644 --- a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx +++ b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx @@ -451,7 +451,6 @@ export function StripeCheckoutModal({ {t("portal.billing.checkout.cap.back", "Back")} - - - } - > -

{copy.body}

- {needsFile && ( -
- setFile(e.target.files?.[0] ?? null)} - /> - - - {file ? file.name : t("portal.procurement.modal.noFile")} - -
- )} - - ); -} diff --git a/frontend/editor/src/portal/components/procurement/DealJourney.stories.tsx b/frontend/editor/src/portal/components/procurement/DealJourney.stories.tsx deleted file mode 100644 index a59386dc3a..0000000000 --- a/frontend/editor/src/portal/components/procurement/DealJourney.stories.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { DealJourney } from "@portal/components/procurement/DealJourney"; -import { buildProcurement } from "@portal/mocks/procurement"; -import type { Deal } from "@portal/api/procurement"; -import "@portal/views/Procurement.css"; - -const data = buildProcurement("enterprise"); -const deal = data.deal as Deal; - -const meta: Meta = { - title: "Portal/Procurement/DealJourney", - component: DealJourney, - parameters: { layout: "padded" }, - args: { deal, journey: data.journey, onAdvance: () => {} }, -}; -export default meta; -type Story = StoryObj; - -// Mid-journey at the Agreement stage, the seeded deal state. -export const Default: Story = {}; - -// Evaluating: the trial strip shows runway + key; next step builds the quote. -export const AtTrial: Story = { - args: { deal: { ...deal, currentStage: "trial" } }, -}; - -// Terminal stage, provisioning, no further CTA. -export const Live: Story = { - args: { deal: { ...deal, currentStage: "active" } }, -}; diff --git a/frontend/editor/src/portal/components/procurement/DealJourney.tsx b/frontend/editor/src/portal/components/procurement/DealJourney.tsx deleted file mode 100644 index 3e8c86e58d..0000000000 --- a/frontend/editor/src/portal/components/procurement/DealJourney.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import { useTranslation } from "react-i18next"; -import { Button, Card } from "@app/ui"; -import type { Deal, DealStage, JourneyStep } from "@portal/api/procurement"; -import { StageStepper } from "@portal/components/procurement/StageStepper"; - -/** - * The deal's commercial journey in one card: who's guiding it (the solutions - * engineer), where it sits (the stage stepper), trial runway while evaluating, - * and the single next action that advances the deal. Mirrors "one next action - * at a time"; the full per-stage checklist lives in the Documents card. - */ -export function DealJourney({ - deal, - journey, - onAdvance, - advancing = false, -}: { - deal: Deal; - journey: JourneyStep[]; - onAdvance: (stage: DealStage) => void; - advancing?: boolean; -}) { - const { t } = useTranslation(); - const { engineer, trial, currentStage } = deal; - const currentStep = journey.find((s) => s.stage === currentStage); - const isTerminal = - journey.length > 0 && journey[journey.length - 1].stage === currentStage; - - return ( - -
-
- - {t("portal.procurement.journey.eyebrow")} - -

- {t("portal.procurement.journey.title")} -

-

- {t("portal.procurement.journey.subtitle")} -

-
-
- - {t("portal.procurement.journey.engineerLabel")} - - {engineer.name} - - {engineer.email} - -
-
- -
- -
- - {currentStage === "trial" && ( -
- - {t("portal.procurement.journey.trialTitle")} - - - {t("portal.procurement.journey.daysLeft", { - count: trial.daysLeft, - })} - - {trial.key} -
- )} - -
-
- - - {isTerminal - ? t("portal.procurement.journey.live") - : t("portal.procurement.journey.nextStep", { - action: currentStep ? t(currentStep.gatingAction) : "", - })} - -
- {!isTerminal && currentStep && ( - - )} -
-
- ); -} diff --git a/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx b/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx index 9421de28bb..77c008ce41 100644 --- a/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx +++ b/frontend/editor/src/portal/components/procurement/DealStatusHero.stories.tsx @@ -12,6 +12,10 @@ const base: ProcurementSnapshot = { trialExtensionsUsed: 0, licensed: false, licenseKey: null, + businessName: null, + contactName: null, + contactEmail: null, + agreementSignedVersion: null, latestQuote: null, }; @@ -23,11 +27,11 @@ const meta: Meta = { args: { canSchedule: true, onExpand: () => {}, + onAcceptQuote: () => {}, onLicense: () => {}, onInvite: () => {}, onSchedule: () => {}, onManageTrial: () => {}, - onNavigate: () => {}, }, }; export default meta; diff --git a/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx b/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx index 092e259bb3..ef2172bb27 100644 --- a/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx +++ b/frontend/editor/src/portal/components/procurement/DealStatusHero.tsx @@ -1,31 +1,62 @@ -import { useEffect } from "react"; +import { useEffect, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { Button } from "@app/ui"; -import type { ViewId } from "@portal/contexts/ViewContext"; import { FLOW_JOURNEY, + type DealStage, type ProcurementSnapshot, } from "@portal/api/procurement"; -import { StageStepper } from "@portal/components/procurement/StageStepper"; +import { + CalendarIcon, + CheckIcon, + DocumentsIcon, + KeyIcon, + UserPlusIcon, +} from "@portal/components/icons"; import { warmCalendly } from "@portal/components/procurement/CalendlyInline"; +import { openApiUrl } from "@portal/api/externalUrl"; import "@portal/views/Procurement.css"; +/** What each stage asks of the buyer, read out in the stage sentence. */ +const STAGE_SENTENCE: Record = { + // Exploring sits on the Trial rung: same sentence, since the ask is what differs. + exploring: "portal.procurement.hero.sentenceTrial", + trial: "portal.procurement.hero.sentenceTrial", + quote: "portal.procurement.hero.sentenceQuote", + security: "portal.procurement.hero.sentenceAgreement", + procurement: "portal.procurement.hero.sentencePayment", + active: "portal.procurement.hero.sentenceLive", +}; + +/** The primary action for each stage; expanding the flow runs it. */ +const STAGE_CTA: Record = { + 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-status hero on Home (procurement lives here, not as a nav tab). Adapts to the - * deal stage: quick-action chips (trial countdown → manage, licence key, invite teammates, - * schedule a call), a rollout checklist during the trial, and a stage-specific primary CTA that - * expands the flow into the takeover modal. Matches the marketing prototype. + * The enterprise deal-status hero on Home (procurement lives here, not as a nav tab) — this card IS + * the procurement surface. It 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. */ export function DealStatusHero({ snapshot, busy = false, canSchedule, onExpand, + onAcceptQuote, onLicense, onInvite, onSchedule, onManageTrial, - onNavigate, + onDocuments, }: { snapshot: ProcurementSnapshot; busy?: boolean; @@ -33,11 +64,17 @@ export function DealStatusHero({ * "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; - onNavigate: (view: ViewId) => void; + /** Open the Documents reference (agreement, quote, invoice, EULA, SLA, subprocessors). */ + onDocuments: () => void; }) { const { t } = useTranslation(); @@ -49,129 +86,181 @@ export function DealStatusHero({ const stage = snapshot.stage ?? "trial"; const inTrial = stage === "trial"; - const cta = - stage === "trial" - ? t("portal.procurement.hero.ctaTrial") - : stage === "quote" - ? t("portal.procurement.hero.ctaQuote") - : stage === "procurement" - ? t("portal.procurement.hero.ctaPayment") - : t("portal.procurement.hero.ctaLive"); + 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(); - const setupSteps: { title: string; sub: string; view: ViewId }[] = [ - { - title: t("portal.procurement.hero.setup1Title"), - sub: t("portal.procurement.hero.setup1Sub"), - view: "users", - }, - { - title: t("portal.procurement.hero.setup2Title"), - sub: t("portal.procurement.hero.setup2Sub"), - view: "sources", - }, - { - title: t("portal.procurement.hero.setup3Title"), - sub: t("portal.procurement.hero.setup3Sub"), - view: "policies", - }, - ]; + // 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, + FLOW_JOURNEY.findIndex((s) => s.stage === journeyStage), + ); + const nextStage = FLOW_JOURNEY[currentIdx + 1]; return (
-
+
- {t("portal.procurement.hero.eyebrow")} + {company + ? t("portal.procurement.hero.eyebrowCompany", { company }) + : t("portal.procurement.hero.eyebrow")} - - {t("portal.procurement.hero.company")} - -
-
+ +
+ {FLOW_JOURNEY.map((s, i) => ( + + ))} +
+ +

+ {t(FLOW_JOURNEY[currentIdx].label)} + {` · ${t(STAGE_SENTENCE[stage])} `} + {nextStage && ( + + {t("portal.procurement.hero.next", { + stage: t(nextStage.label), + })} + + )} +

+ {inTrial && snapshot.trialEndsAt && ( - - )} - {snapshot.licenseKey && ( - - )} - {stage !== "active" && ( - - )} - {canSchedule && ( - +
+ +
)}
-
- -
- - {inTrial && ( -
    - {setupSteps.map((s) => ( -
  • - -
  • - ))} -
+ {isLive && ( +
+ + + + + + {t("portal.procurement.hero.liveTitle")} + + + {t("portal.procurement.hero.liveSub")} + + +
)} -
- - - {t("portal.procurement.hero.nextStep", { action: cta })} - -
- + + + ) : invoiceUrl ? ( + + ) : ( + + )} +
+ {snapshot.licenseKey && ( + + + + )} + + + + {!isLive && ( + + + + )} + {canSchedule && ( + + + + )}
); } +/** 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 ( + + ); +} + 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/editor/src/portal/components/procurement/DocRow.stories.tsx b/frontend/editor/src/portal/components/procurement/DocRow.stories.tsx deleted file mode 100644 index 695b8c6941..0000000000 --- a/frontend/editor/src/portal/components/procurement/DocRow.stories.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { DocRow } from "@portal/components/procurement/DocRow"; -import type { LedgerDoc } from "@portal/api/procurement"; -import "@portal/views/Procurement.css"; - -const meta: Meta = { - title: "Portal/Procurement/DocRow", - component: DocRow, - parameters: { layout: "padded" }, - args: { onAction: () => {} }, -}; -export default meta; -type Story = StoryObj; - -const sign: LedgerDoc = { - id: "d1", - name: "Stirling Enterprise Agreement", - sub: "One signature: MSA + order form + EULA + DPA.", - status: "action", - action: "sign", -}; - -const download: LedgerDoc = { - id: "d2", - name: "SOC 2 Type II report", - sub: "Independent audit of our security controls.", - status: "available", - action: "download", -}; - -const paidAddon: LedgerDoc = { - id: "d3", - name: "Onboarding & training", - sub: "Guided rollout and live training for your team.", - status: "request", - action: "request", - optional: true, - fee: 7_500, -}; - -const done: LedgerDoc = { - id: "d4", - name: "Formal quote", - sub: "Committed-volume pricing, term and line items.", - status: "complete", - action: "download", -}; - -// Deal-advancing action, filled purple CTA. -export const SignAction: Story = { args: { doc: sign } }; - -// Quiet outline action for a ready download. -export const Download: Story = { args: { doc: download } }; - -// Optional paid add-on, chips flag it and the fee folds into the CTA. -export const PaidAddon: Story = { args: { doc: paidAddon } }; - -// Completed paperwork keeps a record but offers no further action. -export const Complete: Story = { args: { doc: done } }; - -// A row in a future, not-yet-reached stage, dimmed, marked "Upcoming", inert. -export const Locked: Story = { args: { doc: sign, locked: true } }; diff --git a/frontend/editor/src/portal/components/procurement/DocRow.tsx b/frontend/editor/src/portal/components/procurement/DocRow.tsx deleted file mode 100644 index b4329fbfa4..0000000000 --- a/frontend/editor/src/portal/components/procurement/DocRow.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import { useTranslation } from "react-i18next"; -import { Button, Chip, StatusBadge } from "@app/ui"; -import type { LedgerDoc } from "@portal/api/procurement"; -import { - ACTION_LABEL_KEY, - STATUS_LABEL_KEY, - STATUS_TONE, - USD, -} from "@portal/components/procurement/format"; - -/** Maps a document's action to the button accent + variant. */ -function buttonStyle(doc: LedgerDoc): { - variant: "primary" | "secondary"; - accent: "premium" | "default"; -} { - // The agreement signature and online payment are the deal-advancing actions; - // give them the filled premium CTA. Everything else is a quieter outline. - if (doc.action === "sign" || doc.action === "pay") { - return { variant: "primary", accent: "premium" }; - } - return { variant: "secondary", accent: "default" }; -} - -/** - * A single document in the ledger or supporting pool: name + sub-line on the - * left, status badge and action button on the right. Optional/fee-bearing docs - * carry a chip so the buyer sees a paid add-on before clicking. `locked` is for - * rows in a future, not-yet-reached stage: dimmed, marked "Upcoming", inert. - */ -export function DocRow({ - doc, - onAction, - locked = false, -}: { - doc: LedgerDoc; - onAction: (doc: LedgerDoc) => void; - locked?: boolean; -}) { - const { t } = useTranslation(); - const { variant, accent } = buttonStyle(doc); - // Locked (future-stage), in-progress (pending) and completed paperwork all - // offer no action; only "available", "action" and "request" docs do. - const actionable = - !locked && doc.status !== "complete" && doc.status !== "pending"; - const label = t(ACTION_LABEL_KEY[doc.action]); - const actionLabel = - doc.fee !== undefined ? `${label} · ${USD.format(doc.fee)}` : label; - - return ( -
-
-
- {doc.name} - {doc.optional && ( - - {t("portal.procurement.docs.optional")} - - )} - {doc.fee !== undefined && ( - - {t("portal.procurement.docs.paidAddon")} - - )} -
-

{doc.sub}

-
-
- - {locked - ? t("portal.procurement.docs.upcoming") - : t(STATUS_LABEL_KEY[doc.status])} - - {actionable && ( - - )} -
-
- ); -} diff --git a/frontend/editor/src/portal/components/procurement/DocumentLedger.stories.tsx b/frontend/editor/src/portal/components/procurement/DocumentLedger.stories.tsx deleted file mode 100644 index 5de6692999..0000000000 --- a/frontend/editor/src/portal/components/procurement/DocumentLedger.stories.tsx +++ /dev/null @@ -1,30 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { DocumentLedger } from "@portal/components/procurement/DocumentLedger"; -import { buildProcurement } from "@portal/mocks/procurement"; -import "@portal/views/Procurement.css"; - -const data = buildProcurement("enterprise"); - -const meta: Meta = { - title: "Portal/Procurement/DocumentLedger", - component: DocumentLedger, - parameters: { layout: "padded" }, - args: { - groups: data.ledger, - supporting: data.supporting, - journey: data.journey, - currentStage: data.deal?.currentStage ?? "trial", - onAction: () => {}, - }, -}; -export default meta; -type Story = StoryObj; - -// Mid-journey: the Agreement stage is open, earlier stages read as done, later -// stages are locked previews, and the supporting pool sits collapsed below. -export const Default: Story = {}; - -// Day one: only the Trial stage has been reached; everything ahead is locked. -export const AtTrial: Story = { - args: { currentStage: "trial" }, -}; diff --git a/frontend/editor/src/portal/components/procurement/DocumentLedger.tsx b/frontend/editor/src/portal/components/procurement/DocumentLedger.tsx deleted file mode 100644 index aa9e6ae8ce..0000000000 --- a/frontend/editor/src/portal/components/procurement/DocumentLedger.tsx +++ /dev/null @@ -1,160 +0,0 @@ -import { useEffect, useState } from "react"; -import { useTranslation } from "react-i18next"; -import { Card, Chip, Collapsible } from "@app/ui"; -import type { - DealStage, - JourneyStep, - LedgerDoc, - LedgerGroup, - SupportingGroup, -} from "@portal/api/procurement"; -import { DocRow } from "@portal/components/procurement/DocRow"; - -/** - * The "Documents" card: every artifact the deal needs, as a stage accordion - * that mirrors the journey. Only the current stage is open by default; earlier - * stages read as done, later stages are locked previews. A collapsed-by-default - * "Supporting your evaluation" pool holds the stage-agnostic paperwork. - */ -export function DocumentLedger({ - groups, - supporting, - journey, - currentStage, - onAction, -}: { - groups: LedgerGroup[]; - supporting: SupportingGroup[]; - journey: JourneyStep[]; - currentStage: DealStage; - onAction: (doc: LedgerDoc) => void; -}) { - const { t } = useTranslation(); - const order = journey.map((s) => s.stage); - const curIdx = order.indexOf(currentStage); - // Follow the deal: the stage you're in opens first; any other stage can be - // peeked. null collapses them all. Advancing moves the open section along. - const [openStage, setOpenStage] = useState(currentStage); - const [supportingOpen, setSupportingOpen] = useState(false); - useEffect(() => setOpenStage(currentStage), [currentStage]); - - return ( - -
-

- {t("portal.procurement.docs.title")} -

-

- {t("portal.procurement.docs.subtitle")} -

-
- -
- {groups.map((group) => { - const idx = order.indexOf(group.stage); - const done = idx < curIdx; - const cur = group.stage === currentStage; - const locked = idx > curIdx; - const blurb = journey.find((s) => s.stage === group.stage)?.blurb; - const open = openStage === group.stage; - const count = group.docs.length; - - return ( - setOpenStage(open ? null : group.stage)} - header={ - <> - - - {t(group.label)} - - {blurb && ( - - · {t(blurb)} - - )} - {cur && ( - - {t("portal.procurement.docs.here")} - - )} - {done && ( - - {t("portal.procurement.docs.done")} - - )} - - } - aside={ - - {t("portal.procurement.docs.count", { count })} - - } - > -
- {group.docs.map((doc) => ( - - ))} -
-
- ); - })} - - {supporting.length > 0 && ( - setSupportingOpen((o) => !o)} - header={ - - - {t("portal.procurement.docs.supportingTitle")} - - - {t("portal.procurement.docs.supportingSubtitle")} - - - } - aside={ - - {supportingOpen - ? t("portal.procurement.docs.hide") - : t("portal.procurement.docs.show")} - - } - > -
- {supporting.map((group) => ( -
-
{group.label}
-
- {group.docs.map((doc) => ( - - ))} -
-
- ))} -
-
- )} -
-
- ); -} diff --git a/frontend/editor/src/portal/components/procurement/LockedState.stories.tsx b/frontend/editor/src/portal/components/procurement/LockedState.stories.tsx deleted file mode 100644 index eae9db4d99..0000000000 --- a/frontend/editor/src/portal/components/procurement/LockedState.stories.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { LockedState } from "@portal/components/procurement/LockedState"; -import { JOURNEY } from "@portal/api/procurement"; -import "@portal/views/Procurement.css"; - -const meta: Meta = { - title: "Portal/Procurement/LockedState", - component: LockedState, - parameters: { layout: "padded" }, - args: { onTalkToSales: () => {} }, -}; -export default meta; -type Story = StoryObj; - -// Shown to free/pro buyers, the journey preview behind the upgrade prompt. -export const Default: Story = { - args: { journey: JOURNEY }, -}; diff --git a/frontend/editor/src/portal/components/procurement/LockedState.tsx b/frontend/editor/src/portal/components/procurement/LockedState.tsx deleted file mode 100644 index 8e70ba18c4..0000000000 --- a/frontend/editor/src/portal/components/procurement/LockedState.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { useTranslation } from "react-i18next"; -import { Button, Card, EmptyState } from "@app/ui"; -import type { JourneyStep } from "@portal/api/procurement"; -import { StageStepper } from "@portal/components/procurement/StageStepper"; - -/** - * Enterprise-only gate for free/pro buyers. Shows the journey as a greyed - * preview behind an upgrade prompt so the buyer understands what the - * commercial track looks like before they talk to sales. - */ -export function LockedState({ - journey, - onTalkToSales, -}: { - journey: JourneyStep[]; - onTalkToSales: () => void; -}) { - const { t } = useTranslation(); - return ( -
- - {t("portal.procurement.locked.talkToSales")} - - } - /> - - - -
- ); -} diff --git a/frontend/editor/src/portal/components/procurement/ProcurementAgreement.stories.tsx b/frontend/editor/src/portal/components/procurement/ProcurementAgreement.stories.tsx index a6ca8dfcf5..fd47d867c6 100644 --- a/frontend/editor/src/portal/components/procurement/ProcurementAgreement.stories.tsx +++ b/frontend/editor/src/portal/components/procurement/ProcurementAgreement.stories.tsx @@ -69,10 +69,9 @@ const meta: Meta = { args: { quote, busy: false, - downloading: false, onAgree: () => {}, - onDownload: () => {}, - onEdit: () => {}, + onRequestChanges: () => {}, + onClose: () => {}, }, }; export default meta; @@ -81,12 +80,7 @@ type Story = StoryObj; export const Default: Story = {}; -// Agreeing: the primary CTA shows its loading state while the accept call is in flight. -export const Agreeing: Story = { +// Signing: the primary CTA shows its loading state while the accept call is in flight. +export const Signing: Story = { args: { busy: true }, }; - -// Downloading: the secondary action shows its loading state instead. -export const Downloading: Story = { - args: { downloading: true }, -}; diff --git a/frontend/editor/src/portal/components/procurement/ProcurementAgreement.tsx b/frontend/editor/src/portal/components/procurement/ProcurementAgreement.tsx index 336b6af5cb..318f23aca5 100644 --- a/frontend/editor/src/portal/components/procurement/ProcurementAgreement.tsx +++ b/frontend/editor/src/portal/components/procurement/ProcurementAgreement.tsx @@ -1,152 +1,267 @@ -import { useState } from "react"; +import { useRef, useState } from "react"; import { useTranslation } from "react-i18next"; -import { Button, Card } from "@app/ui"; -import type { QuoteResult } from "@portal/api/procurement"; -import { money } from "@portal/components/procurement/format"; +import Markdown from "react-markdown"; +import remarkGfm from "remark-gfm"; +import { Button } from "@app/ui"; +import { + fetchAgreementDocument, + fetchAgreementPdf, + recordAgreementSignature, + type QuoteResult, +} from "@portal/api/procurement"; +import { DownloadIcon } from "@portal/components/icons"; +import { StepModalHeader } from "@portal/components/shared/StepModalHeader"; +import { useAsync } from "@portal/hooks/useAsync"; import "@portal/views/Procurement.css"; /** - * The agreement (security) step: a single combined Stirling Enterprise Agreement — Master Service - * Agreement + Order Form (from the issued quote) + EULA + Data Processing Agreement — that the buyer - * reviews and agrees to before it's accepted into a subscription. No e-signature for now: an explicit - * "I agree" click stands in (the terms reference the accepted quote). Document body is static legal - * copy; the surrounding UI is translated. + * 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 + * (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. */ export function ProcurementAgreement({ quote, busy, - downloading, onAgree, - onDownload, - onEdit, + onRequestChanges, + onClose, }: { quote: QuoteResult; busy: boolean; - downloading: boolean; - /** Accept the quote straight into a committed subscription (this is also the agreement). */ + /** Accept the quote straight into a committed subscription (runs after the signature is saved). */ onAgree: () => void; - onDownload: () => void; - onEdit: () => 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. */ + onClose?: () => void; }) { const { t } = useTranslation(); - const [checked, setChecked] = useState(false); - const annual = money(quote.annualNetMinor, quote.currency); - const tcv = money(quote.tcvMinor, quote.currency); - const renewal = money(quote.renewalAnnualNetMinor, quote.currency); - const years = quote.config.termYears; + const { data: doc, loading } = useAsync(fetchAgreementDocument, []); + + const [legalName, setLegalName] = useState(quote.config.businessName ?? ""); + 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(null); + + const downloadMsa = async () => { + setDownloadingMsa(true); + setDownloadError(false); + try { + const blob = await fetchAgreementPdf(); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "stirling-enterprise-agreement.pdf"; + document.body.appendChild(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 60_000); + } catch { + // Surface the failure — the PDF is rendered server-side, so a failure here means the + // render service is unavailable rather than something the buyer can retry around. + setDownloadError(true); + } finally { + setDownloadingMsa(false); + } + }; + + const onScroll = () => { + const el = docRef.current; + if (!el) return; + if (el.scrollTop + el.clientHeight >= el.scrollHeight - 24) { + setScrolledToEnd(true); + } + }; + + const ready = + scrolledToEnd && + confirmed && + legalName.trim().length > 0 && + signatory.trim().length > 0; + + const sign = async () => { + setError(false); + setSigning(true); + try { + await recordAgreementSignature({ + customerLegalName: legalName.trim(), + signatoryName: signatory.trim(), + signatoryTitle: title.trim(), + authorityConfirmed: confirmed, + }); + onAgree(); // proceed into the committed subscription + } 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. + setSigning(false); + } + }; return ( - - - {t("portal.procurement.agreement.eyebrow")} - -

- {t("portal.procurement.agreement.title")} -

-

- {t("portal.procurement.agreement.intro")} -

+
+ + {/* On the document, like the quote's: it downloads what is on screen. */} + + {/* Redlines are a conversation, not a form: this hands the buyer to their SE rather than + pretending the terms can be amended in the app. */} + +
+ } + /> -
-

1. Master Service Agreement

-

- This Stirling Enterprise Agreement ("Agreement") is entered into - between Stirling PDF Inc. ("Stirling") and the customer identified on - the Order Form ("Customer"). It governs Customer's access to and use - of the Stirling enterprise platform and related services (the - "Service"). Stirling will provide the Service with commercially - reasonable skill and care and in accordance with the service levels - set out in the Order Form. -

+ {/* 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. */} +
+
+ {loading &&

{t("portal.procurement.agreement.loading")}

} + {!loading && !doc && ( +

{t("portal.procurement.agreement.loadError")}

+ )} + {doc && ( + <> + {/* Letterhead: the reference ties the terms to the quote they price, and the version + label pins what was signed. The document's own heading follows, so this adds a + masthead rather than repeating the title. */} +
+ + {t("portal.procurement.agreement.confidential")} + + + {t("portal.procurement.agreement.ref", { + ref: quote.quoteNumber, + version: doc.versionLabel, + })} + +
+
+ {doc.markdown} +
+ + )} +
+
-

2. Order Form

-

- Quote {quote.quoteNumber} forms the Order Form for - this Agreement. Customer commits to a {years}-year term at{" "} - {annual} per year (total contract value{" "} - {tcv}), billed annually in advance by invoice. Fees - are exclusive of taxes. The committed volume, service level, and - add-ons are itemised below: + {error && ( +

+ {t("portal.procurement.agreement.signError")}

-
    - {quote.lineItems.map((li) => ( -
  • - {li.label} - - {li.kind === "INCLUDED" - ? t("portal.procurement.builder.included") - : money(li.amountMinor, quote.currency)} + )} + {downloadError && ( +

    + {t("portal.procurement.agreement.downloadDraftError")} +

    + )} + + {/* 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. */} +
    +
    +
    +
  • - ))} -
+ setLegalName(e.target.value)} + /> + + + +
+ +
-

3. Term, renewal and annual fee adjustment

-

- This Agreement runs for the committed {years}-year term set out in the - Order Form. It then renews automatically for successive one-year terms - unless either party gives written notice of non-renewal at least 30 - days before the end of the then-current term. On each renewal the - annual fee increases by {quote.cpiRatePct}%, a fixed CPI adjustment. - Based on this quote, the first renewal year would be approximately{" "} - {renewal} per year; the committed term above is - billed at the rate in the Order Form and is not affected. -

- -

4. End-User License Agreement

-

- Subject to the terms of this Agreement, Stirling grants Customer a - non-exclusive, non-transferable right to use the Service for its - internal business purposes during the term. Customer is responsible - for its users' compliance and for the content it processes. The - Service, and all intellectual property in it, remains Stirling's. -

- -

5. Data Processing Agreement

-

- Where Stirling processes personal data on Customer's behalf, it does - so only on Customer's documented instructions and applies appropriate - technical and organisational measures. Sub-processors, international - transfers, and security commitments are as described in Stirling's - Data Processing Agreement and Trust Center, incorporated here by - reference. -

- -

6. Acceptance

-

- By agreeing below, Customer accepts this Agreement and the Order Form. - On acceptance, Stirling will issue the committed annual subscription - and its first invoice. This preview stands in for e-signature during - the pilot. -

+ {/* 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. */} +
+ + {doc && !scrolledToEnd && ( + + {t("portal.procurement.agreement.scrollHint")} + + )} +
- - - -
- - - -
- + ); } diff --git a/frontend/editor/src/portal/components/procurement/ProcurementBanner.stories.tsx b/frontend/editor/src/portal/components/procurement/ProcurementBanner.stories.tsx deleted file mode 100644 index 28e9d2f99a..0000000000 --- a/frontend/editor/src/portal/components/procurement/ProcurementBanner.stories.tsx +++ /dev/null @@ -1,79 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { ProcurementBanner } from "@portal/components/procurement/ProcurementBanner"; -import type { ProcurementController } from "@portal/components/procurement/useProcurement"; -import type { ProcurementSnapshot } from "@portal/api/procurement"; - -const snapshot: ProcurementSnapshot = { - dealId: 1, - stage: "trial", - deployment: "cloud", - seats: 250, - trialStartedAt: "2026-06-25T00:00:00Z", - trialEndsAt: "2026-07-09T00:00:00Z", - trialExtensionsUsed: 0, - licensed: false, - licenseKey: null, - latestQuote: null, -}; - -function makeController( - overrides: Partial = {}, -): ProcurementController { - return { - isLinked: true, - loading: false, - data: null, - started: false, - stage: undefined, - latest: null, - isIssued: false, - isDraft: true, - busy: false, - downloading: false, - downloadingLicense: false, - error: null, - setError: () => {}, - open: false, - setOpen: () => {}, - editing: false, - setEditing: () => {}, - extra: null, - setExtra: () => {}, - invoicePdf: null, - onStartTrial: () => {}, - onConfirmSetup: () => {}, - onExtendTrial: () => {}, - onReset: () => {}, - onGenerate: () => {}, - onAgree: () => {}, - onDownloadPdf: async () => {}, - onDownloadOfflineLicense: async () => {}, - ...overrides, - }; -} - -/** Deal-status hero once a deal is underway, otherwise the enterprise on-ramp. */ -const meta: Meta = { - title: "Portal/Procurement/ProcurementBanner", - component: ProcurementBanner, - parameters: { layout: "padded" }, -}; -export default meta; - -type Story = StoryObj; - -/** No deal yet: the enterprise on-ramp upsell. */ -export const Upsell: Story = { - args: { controller: makeController() }, -}; - -/** A deal is underway: the wired deal-status hero. */ -export const DealUnderway: Story = { - args: { - controller: makeController({ - started: true, - data: snapshot, - stage: snapshot.stage, - }), - }, -}; diff --git a/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx b/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx index d47ffa0b48..626cc8e9fb 100644 --- a/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx +++ b/frontend/editor/src/portal/components/procurement/ProcurementBanner.tsx @@ -1,13 +1,10 @@ -import { useTranslation } from "react-i18next"; -import { Button, Card } from "@app/ui"; import { useView } from "@portal/contexts/ViewContext"; import { DealStatusHero } from "@portal/components/procurement/DealStatusHero"; import type { ProcurementController } from "@portal/components/procurement/useProcurement"; /** - * The deal-status hero, wired to a shared ProcurementController. Rendered both - * standalone (the /procurement route) and as the Home hero card's footer once a - * deal is underway. Assumes an active deal (controller.data present). + * The deal-status hero, wired to a shared ProcurementController. Rendered as the Home hero card's + * footer once a deal is underway; assumes an active deal (controller.data present). */ export function ControlledDealStatusHero({ controller, @@ -21,60 +18,18 @@ export function ControlledDealStatusHero({ snapshot={controller.data} busy={controller.busy} canSchedule={controller.isLinked} - onExpand={() => controller.setOpen(true)} + 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={() => setActiveView("users")} onSchedule={() => controller.setExtra("schedule")} onManageTrial={() => controller.setExtra("trial")} - onNavigate={setActiveView} + onDocuments={() => controller.setExtra("documents")} /> ); } - -/** - * Enterprise on-ramp shown when no deal exists yet. Only used on the dedicated - * /procurement route — on Home the setup checklist's Enterprise rung owns the - * on-ramp, so this doesn't render there. - */ -export function ProcurementUpsell({ - controller, -}: { - controller: ProcurementController; -}) { - const { t } = useTranslation(); - return ( - -
- - {t("portal.procurement.upsell.homeBadge")} - -

- {t("portal.procurement.upsell.homeHeadline")} - {t("portal.procurement.upsell.homeBody")} -

-
- -
- ); -} - -/** Deal-status hero when a deal is underway, otherwise the enterprise on-ramp. */ -export function ProcurementBanner({ - controller, -}: { - controller: ProcurementController; -}) { - return controller.isLinked && controller.started && controller.data ? ( - - ) : ( - - ); -} diff --git a/frontend/editor/src/portal/components/procurement/ProcurementExtras.stories.tsx b/frontend/editor/src/portal/components/procurement/ProcurementExtras.stories.tsx index 06361da844..7a6c6ffb18 100644 --- a/frontend/editor/src/portal/components/procurement/ProcurementExtras.stories.tsx +++ b/frontend/editor/src/portal/components/procurement/ProcurementExtras.stories.tsx @@ -31,6 +31,10 @@ const SNAPSHOT: ProcurementSnapshot = { trialExtensionsUsed: 0, licensed: false, licenseKey: null, + agreementSignedVersion: null, + businessName: null, + contactName: null, + contactEmail: null, latestQuote: null, }; @@ -72,13 +76,14 @@ export const ScheduleCall: Story = { ), }; -// Deployment + seat count captured before the trial starts. +// Two steps before the trial starts: how they'll run it, then who is buying. export const TrialSetup: Story = { render: () => ( {}} busy={false} + onScheduleCall={() => {}} onConfirm={() => {}} /> ), diff --git a/frontend/editor/src/portal/components/procurement/ProcurementExtras.tsx b/frontend/editor/src/portal/components/procurement/ProcurementExtras.tsx index 44bbea1264..10ea20ed0c 100644 --- a/frontend/editor/src/portal/components/procurement/ProcurementExtras.tsx +++ b/frontend/editor/src/portal/components/procurement/ProcurementExtras.tsx @@ -1,11 +1,20 @@ import { useEffect, useState } from "react"; -import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; +import Markdown from "react-markdown"; +import remarkGfm from "remark-gfm"; import { Button } from "@app/ui"; -import type { ProcurementSnapshot } from "@portal/api/procurement"; +import { + fetchLegalDocument, + recordLegalConsent, + type ProcurementSnapshot, + type TrialSetupDetails, +} from "@portal/api/procurement"; +import { StepModalHeader } from "@portal/components/shared/StepModalHeader"; import { CalendlyInline } from "@portal/components/procurement/CalendlyInline"; import { LicensePanel } from "@portal/components/procurement/ProcurementStages"; -import { useFocusTrap } from "@portal/components/procurement/ProcurementModal"; +import { FlowModal } from "@portal/components/shared/FlowModal"; +import { useAsync } from "@portal/hooks/useAsync"; +import { openApiUrl } from "@portal/api/externalUrl"; import "@portal/views/Procurement.css"; /** @@ -14,6 +23,8 @@ import "@portal/views/Procurement.css"; * scheduler. The shells and wiring are real so the hero behaves like the marketing prototype. */ +const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + function SideModal({ open, onClose, @@ -21,56 +32,243 @@ function SideModal({ subtitle, children, footer, + headerAside, wide = false, }: { open: boolean; onClose: () => void; title: string; subtitle?: string; + /** Sits on the title row, before the close button (e.g. a "Step 1 of 2" badge). */ + headerAside?: React.ReactNode; children: React.ReactNode; footer?: React.ReactNode; wide?: boolean; }) { - const { t } = useTranslation(); - const trapRef = useFocusTrap(open); - - useEffect(() => { - if (!open) return; - const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose(); - document.addEventListener("keydown", onKey); - return () => document.removeEventListener("keydown", onKey); - }, [open, onClose]); - - if (!open) return null; - return createPortal( -
e.target === e.currentTarget && onClose()} - > -
- -
-

{title}

+ return ( + +
+

{title}

+ {headerAside} +
{subtitle &&

{subtitle}

} + + } + > + {children} +
+ ); +} + +/** + * Reader for a versioned legal document (EULA, SLA exhibit, subprocessors), fetched from the + * backend registry and rendered as markdown. Open when {@code docId} is set. Drafts are badged. + */ +export function LegalDocumentModal({ + docId, + onClose, +}: { + docId: string | null; + onClose: () => void; +}) { + const { t } = useTranslation(); + const { data, loading } = useAsync( + () => (docId ? fetchLegalDocument(docId) : Promise.resolve(null)), + [docId], + ); + return ( + + {loading && ( +

{t("portal.legal.loading")}

+ )} + {!loading && !data && ( +

{t("portal.legal.loadError")}

+ )} + {data && ( +
+ {data.markdown}
-
{children}
- {footer &&
{footer}
} + )} +
+ ); +} + +// ── Documents ──────────────────────────────────────────────────────────────── +/** + * 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. + */ +export function DocumentsModal({ + open, + onClose, + agreementVersion, + downloadingAgreement, + onDownloadAgreement, + onViewAgreement, + quoteAvailable, + downloadingQuote, + onDownloadQuote, + 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; + quoteAvailable: boolean; + downloadingQuote?: boolean; + onDownloadQuote: () => void; + invoiceUrl?: string | null; + invoicePdf?: string | null; +}) { + const { t } = useTranslation(); + const [legalDoc, setLegalDoc] = useState(null); + const invoice = invoiceUrl || invoicePdf || null; + + return ( + <> + +
    + + + openApiUrl(invoice), + } + : { + unavailable: t("portal.procurement.documents.laterInvoice"), + } + } + /> + setLegalDoc("eula"), + }} + /> + setLegalDoc("sla"), + }} + /> + setLegalDoc("subprocessors"), + }} + /> +
+
+ 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, +}: { + name: string; + sub: string; + action: + | { label: string; onClick: () => void; loading?: boolean } + | { unavailable: string }; +}) { + return ( +
  • +
    + {name} + {sub}
    -
  • , - document.body, + {"unavailable" in action ? ( + {action.unavailable} + ) : ( + + )} + ); } @@ -154,82 +352,233 @@ export function TrialSetupModal({ open, onClose, busy, + email, + onScheduleCall, onConfirm, }: { open: boolean; onClose: () => void; busy: boolean; - onConfirm: (deployment: string, seats: number) => void; + /** 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. */ + onScheduleCall: () => void; + onConfirm: ( + deployment: string, + seats: number, + details: TrialSetupDetails, + ) => void; }) { const { t } = useTranslation(); + const [step, setStep] = useState(0); const [deployment, setDeployment] = useState("cloud"); const [seats, setSeats] = useState(""); + const [contactName, setContactName] = useState(""); + const [businessName, setBusinessName] = useState(""); + const [contactEmail, setContactEmail] = useState(""); + const [inviteEmails, setInviteEmails] = useState(""); + const [eula, setEula] = useState(false); + const [legalDoc, setLegalDoc] = useState(null); // Reset to defaults each time the dialog opens, so a cancelled setup doesn't linger. useEffect(() => { if (open) { + setStep(0); setDeployment("cloud"); setSeats(""); + setContactName(""); + setBusinessName(""); + setContactEmail(email ?? ""); + setInviteEmails(""); + setEula(false); } - }, [open]); + }, [open, 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 confirm = () => { + void recordLegalConsent("eula", "trial"); // clickwrap consent, best-effort + onConfirm(deployment, Math.max(0, Number(seats) || 0), { + businessName: businessName.trim(), + contactName: contactName.trim(), + contactEmail: contactEmail.trim(), + inviteEmails: inviteEmails.trim(), + }); + }; return ( - onConfirm(deployment, Math.max(0, Number(seats) || 0))} - > - {t("portal.procurement.setup.start")} - - } - > - + + + ) : ( + <> + + + + ) + } + > + - -

    - {t("portal.procurement.setup.seatsHint")} -

    -
    + {step === 0 && ( + <> + + + + )} + + {step === 1 && ( + <> +
    + + +
    + + + + + + )} + + setLegalDoc(null)} /> + ); } @@ -280,7 +629,6 @@ export function TrialManageModal({ } @@ -103,46 +113,63 @@ export function ProcurementFlow({ {isLinked && started && ( <> -
    - -
    - - {(editing || - (isDraft && (stage === "trial" || stage === "quote"))) && ( + {builderShowing && ( 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} /> )} - {/* Quote + agreement are one step: review the itemised quote and the agreement, then - accept straight into a committed subscription. Once accepted you can't go back. - ("security" is the retired agreement stage — still handled so an older deal that - stopped there isn't left blank.) */} - {!editing && - isIssued && - (stage === "quote" || stage === "security") && - latest && ( - setEditing(true)} - /> - )} + {/* Agreement step: review and sign the enterprise agreement. Signing accepts the quote + into a committed subscription (Stripe). */} + {agreementShowing && latest && ( + { + setOpen(false); + setExtra("schedule"); + }} + onClose={() => setOpen(false)} + /> + )} {!editing && stage === "procurement" && latest && ( )} - {!editing && stage === "active" && } + {!editing && stage === "active" && ( + + )} )} @@ -151,6 +178,8 @@ export function ProcurementFlow({ open={extra === "setup"} onClose={() => setExtra(null)} busy={busy} + email={scheduleEmail ?? undefined} + onScheduleCall={() => setExtra("schedule")} onConfirm={onConfirmSetup} /> {data?.licenseKey && ( @@ -185,6 +214,23 @@ export function ProcurementFlow({ }} /> )} + 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/editor/src/portal/components/procurement/ProcurementHome.stories.tsx b/frontend/editor/src/portal/components/procurement/ProcurementHome.stories.tsx deleted file mode 100644 index ae424922ad..0000000000 --- a/frontend/editor/src/portal/components/procurement/ProcurementHome.stories.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import type { Meta, StoryObj } from "@storybook/react-vite"; -import { ProcurementHome } from "@portal/components/procurement/ProcurementHome"; - -/** - * The end-to-end procurement experience (Home hero + takeover modal), driven by the `procurementSaas` - * MSW handlers: start trial → build quote → generate (issue Stripe Quote) → milestone (download PDF / - * accept). `autoOpen` opens the modal so the flow is immediately clickable. - */ -const meta: Meta = { - title: "Portal/Procurement/ProcurementHome", - component: ProcurementHome, - parameters: { layout: "fullscreen" }, -}; -export default meta; - -type Story = StoryObj; - -export const Default: Story = { args: { autoOpen: true } }; diff --git a/frontend/editor/src/portal/components/procurement/ProcurementHome.tsx b/frontend/editor/src/portal/components/procurement/ProcurementHome.tsx deleted file mode 100644 index 1877e0bc3c..0000000000 --- a/frontend/editor/src/portal/components/procurement/ProcurementHome.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import { ProcurementBanner } from "@portal/components/procurement/ProcurementBanner"; -import { ProcurementFlow } from "@portal/components/procurement/ProcurementFlow"; -import { useProcurement } from "@portal/components/procurement/useProcurement"; -import "@portal/views/Procurement.css"; - -/** - * The standalone procurement experience: a deal-status hero (or enterprise - * on-ramp when no deal exists) above the full-screen takeover flow that holds - * the journey — build + issue a quote, review + agree to the enterprise - * agreement, then accept into a committed subscription. Rendered at - * /procurement (autoOpen). On Home the deal-status hero instead attaches to the - * tier hero card's footer (see HomeHero) so this component isn't used there. - */ -export function ProcurementHome({ autoOpen = false }: { autoOpen?: boolean }) { - const controller = useProcurement(autoOpen); - return ( - <> - - - - ); -} diff --git a/frontend/editor/src/portal/components/procurement/ProcurementModal.stories.tsx b/frontend/editor/src/portal/components/procurement/ProcurementModal.stories.tsx index 7fb8b865f2..14934905d6 100644 --- a/frontend/editor/src/portal/components/procurement/ProcurementModal.stories.tsx +++ b/frontend/editor/src/portal/components/procurement/ProcurementModal.stories.tsx @@ -31,9 +31,7 @@ export const Open: Story = { contract and go live.

    - +
    diff --git a/frontend/editor/src/portal/components/procurement/ProcurementModal.tsx b/frontend/editor/src/portal/components/procurement/ProcurementModal.tsx index 852c4e68c4..881bb778ce 100644 --- a/frontend/editor/src/portal/components/procurement/ProcurementModal.tsx +++ b/frontend/editor/src/portal/components/procurement/ProcurementModal.tsx @@ -1,104 +1,49 @@ -import { useEffect, useRef } from "react"; -import { createPortal } from "react-dom"; -import { useTranslation } from "react-i18next"; +import type { ReactNode } from "react"; +import { FlowModal } from "@portal/components/shared/FlowModal"; import "@portal/views/Procurement.css"; -/** Keep keyboard focus inside an open dialog: focus it on open and wrap Tab at the edges. */ -export function useFocusTrap(open: boolean) { - const ref = useRef(null); - useEffect(() => { - if (!open) return; - const panel = ref.current; - if (!panel) return; - const prev = document.activeElement as HTMLElement | null; - const focusables = () => - Array.from( - panel.querySelectorAll( - 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])', - ), - ).filter((el) => !el.hasAttribute("disabled")); - (focusables()[0] ?? panel).focus(); - const onKey = (e: KeyboardEvent) => { - if (e.key !== "Tab") return; - const items = focusables(); - if (items.length === 0) return; - const first = items[0]; - const last = items[items.length - 1]; - if (e.shiftKey && document.activeElement === first) { - e.preventDefault(); - last.focus(); - } else if (!e.shiftKey && document.activeElement === last) { - e.preventDefault(); - first.focus(); - } - }; - panel.addEventListener("keydown", onKey); - return () => { - panel.removeEventListener("keydown", onKey); - prev?.focus?.(); - }; - }, [open]); - return ref; -} - /** - * Full-screen takeover modal for the procurement flow, copying the prototype's modal design - * (portaled to body, dimmed + blurred backdrop, rounded panel, close button). The Home deal-status - * hero expands into this. + * 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; - children: React.ReactNode; + /** + * 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; }) { - const { t } = useTranslation(); - const trapRef = useFocusTrap(open); - - useEffect(() => { - if (!open) return; - const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose(); - document.addEventListener("keydown", onKey); - return () => document.removeEventListener("keydown", onKey); - }, [open, onClose]); - - if (!open) return null; - - return createPortal( -
    e.target === e.currentTarget && onClose()} + return ( + +

    {title}

    + {subtitle &&

    {subtitle}

    } + + ) + } > -
    - -
    -

    {title}

    - {subtitle &&

    {subtitle}

    } -
    -
    {children}
    -
    -
    , - document.body, + {children} + ); } diff --git a/frontend/editor/src/portal/components/procurement/ProcurementStages.tsx b/frontend/editor/src/portal/components/procurement/ProcurementStages.tsx index 35460a7ba5..fcf926f481 100644 --- a/frontend/editor/src/portal/components/procurement/ProcurementStages.tsx +++ b/frontend/editor/src/portal/components/procurement/ProcurementStages.tsx @@ -1,61 +1,92 @@ import { useState } from "react"; import { useTranslation } from "react-i18next"; -import { Button, Card } from "@app/ui"; +import { Button } from "@app/ui"; +import { openApiUrl } from "@portal/api/externalUrl"; import "@portal/views/Procurement.css"; /** - * The stage-specific cards shown inside the procurement takeover modal once a quote exists: the - * issued-quote milestone, the subscription-created payment step, and the live confirmation. Each is - * a pure presentational view driven by props; ProcurementHome owns the state and the actions. + * 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. */ +/** 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 ( - +
    + + {t("portal.procurement.payment.eyebrow")} +

    {t("portal.procurement.payment.title")}

    {t("portal.procurement.payment.description")}

    - {(invoiceUrl || invoicePdf) && ( -
    - {invoiceUrl && ( - - )} - {invoicePdf && ( - - )} + {(invoiceUrl || invoicePdf || signedAgreementVersion) && ( +
    +
    + {signedAgreementVersion && onDownloadSignedAgreement && ( + + )} + {invoicePdf && ( + + )} + {invoiceUrl && ( + + )} +
    )} - +
    ); } /** The live confirmation once the deal is active. */ -export function LiveStageCard() { +export function LiveStageCard({ + signedAgreementVersion, + downloadingAgreement, + onDownloadSignedAgreement, +}: { + signedAgreementVersion?: string | null; + downloadingAgreement?: boolean; + onDownloadSignedAgreement?: () => void; +} = {}) { const { t } = useTranslation(); return ( - +
    {t("portal.procurement.live.eyebrow")} @@ -65,7 +96,20 @@ export function LiveStageCard() {

    {t("portal.procurement.live.description")}

    - + {signedAgreementVersion && onDownloadSignedAgreement && ( +
    +
    + +
    +
    + )} +
    ); } diff --git a/frontend/editor/src/portal/components/procurement/QuoteBuilder.tsx b/frontend/editor/src/portal/components/procurement/QuoteBuilder.tsx index b392247563..98fcbd4f04 100644 --- a/frontend/editor/src/portal/components/procurement/QuoteBuilder.tsx +++ b/frontend/editor/src/portal/components/procurement/QuoteBuilder.tsx @@ -3,18 +3,24 @@ import { useTranslation } from "react-i18next"; import { Button } from "@app/ui"; import { DocumentsIcon, + DownloadIcon, PoliciesIcon, UsersIcon, } from "@portal/components/icons"; import { money } from "@portal/components/procurement/format"; import { buildQuote, + recordLegalConsent, type QuoteConfigInput, type QuoteResult, } from "@portal/api/procurement"; +import { LegalDocumentModal } from "@portal/components/procurement/ProcurementExtras"; +import { StepModalHeader } from "@portal/components/shared/StepModalHeader"; import "@portal/views/Procurement.css"; -const STEPS = ["volume", "plan", "details"] as const; +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 = [ @@ -30,22 +36,57 @@ const SIZE_TIERS = [ ] as const; /** - * The enterprise quote builder — volume → commitment & service → details. A client-side preview - * drives the live footer total; the backend is authoritative. Completing the form generates the - * quote directly (build + issue in one step) — the issued quote is then shown as the milestone, so - * there's no redundant in-builder preview. + * The enterprise quote builder — volume → commitment & service → details → review. A client-side + * preview drives the live footer total; the backend is authoritative. Generating builds and issues in + * one go, and the issued quote comes back as the fourth step: the buyer reads the real itemised paper + * and can download it, but does not accept here. Accepting is a decision taken from the deal card, + * deliberately, so circulating the quote internally is not a dead end in a modal. */ export function QuoteBuilder({ deployment, seats = 0, + email, + onClose, + dealDetails, initial, + eulaAlreadyAgreed = false, onGenerate, + issued, + downloading = false, + onDownload, }: { deployment: string; /** Seat count from the trial setup; seeds the users field + volume estimate on a fresh quote. */ 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. */ + onClose?: () => void; + /** + * The buying entity captured at trial setup. Seeds a fresh quote's details step so it confirms + * what is already known rather than asking twice; the buyer can still correct it here, since a + * deal can change hands between trial and quote. + */ + dealDetails?: { + businessName?: string | null; + contactName?: string | null; + contactEmail?: string | null; + }; /** Seed the builder from an existing quote's config (re-editing a quote). */ initial?: QuoteConfigInput; + /** + * The issued quote, which is what the review step shows. Its arrival is also what opens that step: + * the parent issues the quote and it lands by snapshot refresh, so there is no synchronous result + * to advance on. Null while re-editing, so editing reopens the form rather than the paper. + */ + issued?: QuoteResult | null; + downloading?: boolean; + onDownload?: () => void; + /** + * The buyer already accepted the EULA (e.g. at trial start). When true, the EULA clickwrap is + * hidden here and no consent is recorded at quote time — it's only collected once. + */ + eulaAlreadyAgreed?: boolean; /** Called with the priced DRAFT quote; the parent issues it as a Stripe Quote. */ onGenerate: (quote: QuoteResult) => void; }) { @@ -65,9 +106,9 @@ export function QuoteBuilder({ indemnification: false, training: false, qbr: false, - businessName: "", - contactName: "", - contactEmail: "", + businessName: dealDetails?.businessName ?? "", + contactName: dealDetails?.contactName ?? "", + contactEmail: dealDetails?.contactEmail ?? email ?? "", addressLine1: "", addressLine2: "", city: "", @@ -79,29 +120,81 @@ export function QuoteBuilder({ ); // A seeded quote carries a volume but no user count, so treat it as manually set. const [manualVolume, setManualVolume] = useState(initial != null); - const [eula, setEula] = 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(null); const [busy, setBusy] = useState(false); + // Only surface field errors once the buyer tries to generate — no red fields on first sight. + const [showErrors, setShowErrors] = useState(false); function set(k: K, v: QuoteConfigInput[K]) { setCfg((c) => ({ ...c, [k]: v })); } - // Re-editing an existing quote: everything is seeded, so jump to the last step (details) with the + // 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, + }; + 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(STEPS.length - 1); + 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); + }, [issued?.quoteId]); + const preview = previewAnnualMinor(cfg); const tcvPreview = preview * cfg.termYears + (cfg.training ? 750_000 : 0); + // 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 running = onPaper + ? { + annual: money(issued.annualNetMinor, issued.currency), + years: issued.config.termYears, + tcv: money(issued.tcvMinor, issued.currency), + } + : { + annual: money(preview), + years: cfg.termYears, + tcv: money(tcvPreview), + }; + // 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); + return; + } setBusy(true); try { - onGenerate(await buildQuote(cfg)); + 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); } finally { setBusy(false); } @@ -109,22 +202,16 @@ export function QuoteBuilder({ return (
    -
    -

    - {t("portal.procurement.builder.title")} -

    - - {t("portal.procurement.builder.stepOf", { - n: step + 1, - total: STEPS.length, - })} - -
    -
    - {STEPS.map((s, i) => ( - - ))} -
    +
    {step === 0 && ( @@ -171,15 +258,6 @@ export function QuoteBuilder({ ? t("portal.procurement.builder.volManual") : t("portal.procurement.builder.volNoUsers")}

    - - )} - - {step === 1 && ( - } - title={t("portal.procurement.builder.s2Title")} - sub={t("portal.procurement.builder.s2Sub")} - >
    {POSTURES.map((p) => ( @@ -209,7 +287,15 @@ export function QuoteBuilder({ ))}
    +
    + )} + {step === 1 && ( + } + title={t("portal.procurement.builder.s2Title")} + sub={t("portal.procurement.builder.s2Sub")} + >
    {[1, 2, 3, 4, 5].map((y) => ( @@ -287,7 +373,11 @@ export function QuoteBuilder({ sub={t("portal.procurement.builder.s3Sub")} >
    - + set("businessName", e.target.value)} /> - +
    - + set("contactEmail", e.target.value)} /> - +
    - + set("city", e.target.value)} /> - + set("region", e.target.value)} /> - +
    - + {!eulaAlreadyAgreed && ( + + )} + {showErrors && !canGenerate && ( +

    + {t("portal.procurement.builder.completeRequired")} +

    + )} )} + + {/* 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 && ( +
    +
    +
    +
    +
    Stirling PDF
    +
    + {t("portal.procurement.builder.paperEyebrow")} +
    +
    +
    +
    + {issued.quoteNumber} +
    + {issued.validUntil && ( +
    + {t("portal.procurement.review.validUntil", { + date: new Date(issued.validUntil).toLocaleDateString(), + })} +
    + )} + {/* 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. */} + +
    +
    + + {issued.config.businessName?.trim() && ( +
    +
    + {t("portal.procurement.builder.paperFor")} +
    +
    + {issued.config.businessName} +
    +
    + )} + +
      + {issued.lineItems.map((li) => ( +
    • + {li.label} + {money(li.amountMinor, issued.currency)} +
    • + ))} +
    + +
    +
    +
    + {t("portal.procurement.review.annual")} +
    +
    + {t("portal.procurement.review.tcv", { + years: issued.config.termYears, + tcv: money(issued.tcvMinor, issued.currency), + })} +
    +
    + {t("portal.procurement.review.renewal", { + amount: money( + issued.renewalAnnualNetMinor, + issued.currency, + ), + pct: issued.cpiRatePct, + })} +
    + {issued.config.poNumber?.trim() && ( +
    + {t("portal.procurement.review.poNumber", { + po: issued.config.poNumber.trim(), + })} +
    + )} +
    +
    + {money(issued.annualNetMinor, issued.currency)} +
    +
    +
    +
    + )}
    - {t("portal.procurement.builder.running", { - annual: money(preview), - years: cfg.termYears, - tcv: money(tcvPreview), - })} + {t("portal.procurement.builder.running", running)}
    {step > 0 && ( @@ -408,7 +630,6 @@ export function QuoteBuilder({ {step === 0 && ( )} {step === 1 && ( - )} - {step === 2 && ( - )} + {/* No Accept here: the review step ends on the deal card, where accepting is one of two + deliberate choices rather than the only way out of a modal. Download lives on the + document itself. */} + {step === REVIEW_STEP && ( + + )}
    + setLegalDoc(null)} />
    ); } @@ -470,14 +690,25 @@ function Step({ function Field({ label, + required, + invalid, children, }: { label: string; + required?: boolean; + invalid?: boolean; children: React.ReactNode; }) { return ( -
    ); diff --git a/frontend/editor/src/portal/views/Procurement.css b/frontend/editor/src/portal/views/Procurement.css index e26fd74a31..b721768952 100644 --- a/frontend/editor/src/portal/views/Procurement.css +++ b/frontend/editor/src/portal/views/Procurement.css @@ -1,34 +1,10 @@ -.portal-proc { - display: flex; - flex-direction: column; - gap: 1.25rem; - padding: 1.5rem; - max-width: 84rem; - margin: 0 auto; -} - -/* Page header */ -.portal-proc__header { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 1rem; -} - -.portal-proc__title { - margin: 0; - font-size: 1.375rem; - font-weight: 600; - color: var(--c-text); -} - .portal-proc__subtitle { margin: 0.25rem 0 0; font-size: 0.8125rem; color: var(--c-text-subtle); } -/* Eyebrow label shared by the journey header + SE block */ +/* Eyebrow label above a stage panel's heading */ .portal-proc__eyebrow { display: block; font-size: 0.6875rem; @@ -38,613 +14,33 @@ color: var(--c-text-subtle); margin-bottom: 0.25rem; } - -/* ── Journey card ─────────────────────────────────────────────────────── */ -/* Stacked, border-divided sections: header / stepper / trial / next step. */ -.portal-proc__journey-head { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 1rem; - padding: 1.25rem 1.5rem; - border-bottom: 1px solid var(--c-border-subtle); - flex-wrap: wrap; -} - -.portal-proc__journey-title { - margin: 0; - font-size: 1.0625rem; - font-weight: 700; - color: var(--c-text); -} - -.portal-proc__journey-sub { - margin: 0.25rem 0 0; - max-width: 36rem; - font-size: 0.8125rem; - line-height: 1.5; - color: var(--c-text-subtle); -} - -.portal-proc__se { - display: flex; - flex-direction: column; - text-align: right; - flex-shrink: 0; -} - -.portal-proc__se .portal-proc__eyebrow { - margin-bottom: 0.25rem; -} - -.portal-proc__se-name { - font-size: 0.8125rem; - font-weight: 600; - color: var(--c-text); -} - -.portal-proc__se-email { - font-size: 0.75rem; - color: var(--c-primary); - text-decoration: none; -} - -.portal-proc__se-email:hover { - text-decoration: underline; -} - -/* Stepper band */ -.portal-proc__journey-stepper { - padding: 1.125rem 1.5rem; - border-bottom: 1px solid var(--c-border-subtle); -} - -.portal-proc__steps { - display: flex; - align-items: flex-start; -} - -.portal-proc__steps--locked { - opacity: 0.55; - filter: grayscale(0.4); - pointer-events: none; -} - -.portal-proc__step { - display: flex; - flex-direction: column; - align-items: center; - gap: 0.4rem; - min-width: 4rem; -} - -.portal-proc__step-dot { - width: 0.875rem; - height: 0.875rem; - border-radius: 50%; - background: var(--c-border); -} - -.portal-proc__step--complete .portal-proc__step-dot { - background: var(--color-green); -} - -.portal-proc__step--current .portal-proc__step-dot { - background: var(--color-purple); - box-shadow: 0 0 0 4px var(--color-purple-light); -} - -.portal-proc__step-label { - font-size: 0.6875rem; - font-weight: 500; - text-align: center; - white-space: nowrap; - color: var(--c-text-subtle); -} - -.portal-proc__step--complete .portal-proc__step-label { - color: var(--c-text-subtle); -} - -.portal-proc__step--current .portal-proc__step-label { - font-weight: 700; - color: var(--c-text); -} - -/* Connector aligns with the 0.875rem dots: (14px − 2px) / 2 = 6px down */ -.portal-proc__step-line { - flex: 1; - height: 2px; - margin: 0.375rem 0.375rem 0; - background: var(--c-border-subtle); -} - -.portal-proc__step-line[data-filled="true"] { - background: var(--color-green); -} - -/* Trial status strip (shown while evaluating) */ -.portal-proc__trial { - display: flex; - align-items: center; - gap: 0.625rem; - flex-wrap: wrap; - padding: 0.75rem 1.5rem; - border-bottom: 1px solid var(--c-border-subtle); - background: var(--color-bg-code); -} - -.portal-proc__trial-title { - font-size: 0.8125rem; - font-weight: 600; - color: var(--c-text); -} - -.portal-proc__trial-dim { - font-size: 0.78125rem; - color: var(--c-text-subtle); -} - -.portal-proc__trial-key { - font-family: - ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; - font-size: 0.6875rem; - color: var(--c-text-subtle); - background: var(--c-surface); - border: 1px solid var(--c-border); - border-radius: 0.375rem; - padding: 0.1875rem 0.5rem; -} - -/* Next-step row: one primary action at a time */ -.portal-proc__next { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1rem; - flex-wrap: wrap; - padding: 1rem 1.5rem; -} - -.portal-proc__next-label { - display: flex; - align-items: center; - gap: 0.625rem; - font-size: 0.84375rem; - font-weight: 600; - color: var(--c-text); -} - -.portal-proc__next-dot { - width: 0.5rem; - height: 0.5rem; - border-radius: 50%; - background: var(--color-amber); - flex-shrink: 0; -} - -.portal-proc__next-dot[data-live="true"] { - background: var(--color-green); -} - -/* ── Documents card ───────────────────────────────────────────────────── */ -.portal-proc__docs-head { - padding: 1.125rem 1.5rem; - border-bottom: 1px solid var(--c-border-subtle); -} - -.portal-proc__docs-title { - margin: 0; - font-size: 0.9375rem; - font-weight: 700; - color: var(--c-text); -} - -.portal-proc__docs-sub { - margin: 0.25rem 0 0; - font-size: 0.78125rem; - color: var(--c-text-subtle); -} - -.portal-proc__docs-body { - padding: 0.375rem 1.5rem 1.125rem; -} - -/* Accordion spacing — the disclosure chrome itself lives in shared Collapsible - (.sui-collapsible); here we only space the stacked sections. */ -.portal-proc__docs-body .sui-collapsible { - margin-top: 0.875rem; -} - -/* Stage header bits */ -.portal-proc__stage-dot { - width: 0.4375rem; - height: 0.4375rem; - border-radius: 50%; - flex-shrink: 0; -} - -.portal-proc__stage-dot[data-state="done"] { - background: var(--color-green); -} - -.portal-proc__stage-dot[data-state="current"] { - background: var(--color-purple); -} - -.portal-proc__stage-dot[data-state="upcoming"] { - background: var(--c-border); -} - -.portal-proc__stage-label { - font-size: 0.75rem; - font-weight: 700; - letter-spacing: 0.03em; - text-transform: uppercase; - color: var(--c-text-subtle); -} - -.portal-proc__stage-label[data-current] { - color: var(--c-text); -} - -.portal-proc__stage-hint { - font-size: 0.71875rem; - color: var(--c-text-subtle); -} - -.portal-proc__stage-count { - font-size: 0.6875rem; - color: var(--c-text-subtle); -} - -/* Document lists inside the accordion */ -.portal-proc__doc-list { - border-top: 1px solid var(--c-border-subtle); -} - -.portal-proc__doc-list--boxed { - border: 1px solid var(--c-border-subtle); - border-radius: 0.5rem; - overflow: hidden; -} - -/* Supporting section — extra separation from the stage accordion above it. - Scoped to match the general .sui-collapsible spacing rule's specificity. */ -.portal-proc__docs-body .portal-proc__supporting-acc { - margin-top: 1.5rem; -} - -.portal-proc__supporting-head { - display: flex; - flex-direction: column; - gap: 0.125rem; - min-width: 0; -} - -.portal-proc__supporting-sub { - font-size: 0.71875rem; - font-weight: 400; - line-height: 1.45; - color: var(--c-text-subtle); -} - -.portal-proc__acc-toggle-label { - font-size: 0.75rem; - font-weight: 600; - color: var(--c-primary); -} - -.portal-proc__supporting-groups { - display: flex; - flex-direction: column; - gap: 1rem; - border-top: 1px solid var(--c-border-subtle); - padding: 0.875rem; -} - -.portal-proc__group-label { - font-size: 0.6875rem; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.05em; - color: var(--c-text-subtle); - margin-bottom: 0.5rem; -} - -/* ── Document rows (ledger + supporting) ──────────────────────────────── */ -.portal-proc__doc { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1rem; - padding: 0.75rem 0.875rem; - border-bottom: 1px solid var(--c-border-subtle); -} - -.portal-proc__doc:last-child { - border-bottom: none; -} - -.portal-proc__doc[data-locked] { - opacity: 0.6; -} - -.portal-proc__doc-text { - min-width: 0; -} - -.portal-proc__doc-name-row { - display: flex; - align-items: center; - gap: 0.5rem; - flex-wrap: wrap; -} - -.portal-proc__doc-name { - font-size: 0.84375rem; - font-weight: 600; - color: var(--c-text); -} - -.portal-proc__doc-sub { - margin: 0.0625rem 0 0; - font-size: 0.71875rem; - line-height: 1.4; - color: var(--c-text-subtle); -} - -.portal-proc__doc-actions { - display: flex; - align-items: center; - gap: 0.75rem; - flex-shrink: 0; -} - -/* ── Locked state ─────────────────────────────────────────────────────── */ -.portal-proc__locked { - display: flex; - flex-direction: column; - gap: 1.25rem; -} - -/* ── Action modal ─────────────────────────────────────────────────────── */ -.portal-proc__modal-body { - margin: 0 0 1rem; - font-size: 0.875rem; - line-height: 1.55; - color: var(--c-text-muted); -} - -.portal-proc__modal-actions { - display: flex; - align-items: center; - justify-content: flex-end; - gap: 0.625rem; -} - -.portal-proc__upload { - display: flex; - align-items: center; - gap: 0.75rem; -} - -.portal-proc__upload-input { - display: none; -} - -.portal-proc__upload-name { - font-size: 0.75rem; - color: var(--c-text-subtle); -} - -@media (max-width: 48rem) { - .portal-proc__journey-head { - flex-direction: column; - } - - .portal-proc__se { - text-align: left; - } - - .portal-proc__steps { - overflow-x: auto; - } -} - -/* ── Enterprise upsell CTA (Home / Usage on-ramp) ─────────────────────────── */ -.portal-proc__upsell { - display: flex; - align-items: center; - justify-content: space-between; - gap: 1rem; - flex-wrap: wrap; -} -.portal-proc__upsell-badge { - display: inline-block; - font-size: 0.625rem; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.06em; - color: var(--c-primary); - background: var(--c-primary-subtle); - padding: 0.15rem 0.5rem; - border-radius: 0.375rem; - margin-bottom: 0.4rem; -} -.portal-proc__upsell-copy { - margin: 0; - font-size: 0.8125rem; - line-height: 1.45; - color: var(--c-text-subtle); - max-width: 44rem; -} -.portal-proc__upsell-copy strong { - color: var(--c-text); -} - -/* ── Quote builder ────────────────────────────────────────────────────────── */ -.portal-proc__builder-head { - display: flex; - align-items: baseline; - justify-content: space-between; - margin-bottom: 1rem; -} .portal-proc__builder-title { margin: 0; font-size: 1rem; font-weight: 650; color: var(--c-text); } -.portal-proc__builder-step { - font-size: 0.75rem; - color: var(--c-text-subtle); -} -.portal-proc__builder-body { - display: flex; - flex-direction: column; - gap: 0.85rem; -} -.portal-proc__field { - display: flex; - flex-direction: column; - gap: 0.3rem; - font-size: 0.8125rem; - color: var(--c-text-subtle); -} -.portal-proc__field input, -.portal-proc__field select { - padding: 0.45rem 0.6rem; - border: 1px solid var(--c-border); - border-radius: 0.5rem; - font-size: 0.875rem; - background: var(--c-input-bg); - color: var(--c-text); -} -.portal-proc__builder-addons { - display: flex; - flex-direction: column; - gap: 0.4rem; - font-size: 0.8125rem; - color: var(--c-text-muted); -} -.portal-proc__builder-addons label { - display: flex; - align-items: center; - gap: 0.5rem; -} -.portal-proc__builder-actions { - display: flex; - justify-content: flex-end; - gap: 0.6rem; - margin-top: 0.5rem; -} -.portal-proc__quote-head { - display: flex; - align-items: baseline; - justify-content: space-between; - border-bottom: 1px solid var(--c-border); - padding-bottom: 0.5rem; -} -.portal-proc__quote-number { - font-weight: 650; - color: var(--c-text); -} -.portal-proc__quote-valid { - font-size: 0.75rem; - color: var(--c-text-subtle); -} -.portal-proc__quote-lines { - list-style: none; - margin: 0; - padding: 0; -} -.portal-proc__quote-lines li { - display: flex; - justify-content: space-between; - padding: 0.4rem 0; - font-size: 0.8125rem; - color: var(--c-text-muted); - border-bottom: 1px solid var(--c-border-subtle); -} -.portal-proc__quote-lines li[data-kind="DISCOUNT"] { - color: var(--c-success); -} -.portal-proc__quote-total { - display: flex; - justify-content: space-between; - align-items: baseline; - padding: 0.6rem 0 0.2rem; - font-size: 0.9375rem; -} -.portal-proc__quote-total strong { - font-size: 1.25rem; - color: var(--c-text); -} -.portal-proc__quote-tcv { - font-size: 0.75rem; - color: var(--c-text-subtle); -} /* ══ Quote builder — copied from the marketing prototype (tight density) ═════ */ .portal-qb { - background: var(--c-surface); - border: 1px solid var(--c-border); - border-radius: 14px; - box-shadow: inset 0 0 0 1px var(--c-border-subtle); - overflow: hidden; -} -.portal-qb__head { display: flex; - align-items: center; - justify-content: space-between; - padding: 18px 24px 14px; - border-bottom: 1px solid var(--c-border-subtle); - background: linear-gradient( - 180deg, - color-mix(in srgb, var(--c-primary) 5.5%, transparent) 0%, - transparent 100% - ); -} -.portal-qb__title { - margin: 0; - font-size: 16px; - font-weight: 700; - color: var(--c-text); -} -.portal-qb__stepchip { - font-size: 11px; - font-weight: 700; - color: var(--c-text-subtle); - background: var(--c-surface-sunken); - padding: 3px 10px; - border-radius: 999px; -} -.portal-qb__progress { - display: flex; - gap: 6px; - padding: 12px 24px 0; -} -.portal-qb__progress span { - flex: 1; - height: 6px; - border-radius: 999px; - background: var(--c-surface-sunken); - transition: background 0.3s; -} -.portal-qb__progress span[data-on] { - background: var(--c-primary); + flex-direction: column; } +/* No padding or scroll of its own: FlowModal's panel supplies both, and nesting a second scroll + container inside a scrolling panel gave the builder two scrollbars. */ +/* This gap is the builder's only vertical rhythm: the blocks inside carry no bottom margins of their + own, so spacing cannot double up the way a margin plus a gap did. The top margin is the breathing + room under the stepped header, which deliberately has no bottom margin so its host sets this. */ .portal-qb__body { - padding: 20px 24px; - max-height: 56vh; - overflow-y: auto; + display: flex; + flex-direction: column; + gap: 0.75rem; + margin-top: 1.05rem; } .portal-qb__intro { display: flex; align-items: center; gap: 12px; - margin-bottom: 18px; } .portal-qb__intro-icon { width: 38px; @@ -667,9 +63,10 @@ color: var(--c-text-subtle); margin-top: 1px; } +/* No bottom margin: inside .portal-qb__body the gap spaces these, and inside .portal-qb__row a + margin only reserved dead space under the inputs. */ .portal-qb__field { display: block; - margin-bottom: 18px; } .portal-qb__field-label { display: block; @@ -691,6 +88,18 @@ background: var(--c-input-bg); color: var(--c-text); } +.portal-qb__req { + color: var(--c-danger); +} +.portal-qb__field[data-invalid] input, +.portal-qb__field[data-invalid] select { + border-color: var(--c-danger); +} +.portal-qb__error { + margin: 10px 0 0; + font-size: 12px; + color: var(--c-danger); +} .portal-qb__row { display: flex; gap: 14px; @@ -701,7 +110,7 @@ min-width: 190px; } .portal-qb__hint { - margin: 7px 0 0; + margin: 0; font-size: 11.5px; color: var(--c-text-subtle); line-height: 1.4; @@ -736,11 +145,22 @@ gap: 10px; flex-wrap: wrap; } +/* Short-label options that should sit across one row rather than wrapping 2 + 1. Tighter padding + and label size so each caption fits on a single line at three-across. Deliberately no `nowrap`: + a longer translation should wrap rather than clip or push the card out of the row. */ +.portal-qb__opts--across .portal-qb__opt { + min-width: 0; + padding: 11px 12px; +} +.portal-qb__opts--across .portal-qb__opt-sub { + font-size: 11px; + line-height: 1.35; +} .portal-qb__opt { text-align: left; flex: 1; min-width: 150px; - padding: 12px 14px; + padding: 9px 11px; border-radius: 9px; border: 1px solid var(--c-border); background: var(--c-surface); @@ -834,7 +254,11 @@ align-items: center; justify-content: space-between; gap: 12px; - padding: 14px 24px; + /* Bleeds to the panel's edges by reading the shell's own inset, so changing FlowModal's padding + can no longer leave this footer stopping short of them. */ + margin: 0.85rem calc(-1 * var(--flowmodal-inset)) + calc(-1 * var(--flowmodal-body-end)); + padding: 0.8rem var(--flowmodal-inset) 0.9rem; border-top: 1px solid var(--c-border-subtle); flex-wrap: wrap; } @@ -846,13 +270,13 @@ display: flex; gap: 10px; } -/* Step 4 — the itemised quote paper */ +/* Step 4 — the itemised quote paper, on a sunken tray that runs to the panel's edges. No scroll of + its own: the dialog body already scrolls, and nesting a second scroller gave the builder two + scrollbars. The bleed reads the shell's inset rather than hard-coding a copy of it. */ .portal-qb__papertray { background: var(--c-surface-sunken); - padding: 18px; - max-height: 56vh; - overflow-y: auto; - margin: -20px -24px; + padding: 14px var(--flowmodal-inset); + margin: 0 calc(-1 * var(--flowmodal-inset)); } .portal-qb__paper { background: var(--c-surface); @@ -880,6 +304,11 @@ .portal-qb__paper-meta { text-align: right; } +/* Reads as a link on the document rather than a button in a toolbar: right-aligned under the quote's + own metadata, with the row's padding trimmed so it sits tight to the date above it. */ +.portal-qb__paper-download { + margin: 0.2rem -0.5rem -0.25rem 0; +} .portal-qb__quote-number { font-size: 12.5px; font-weight: 700; @@ -955,27 +384,24 @@ margin-top: 3px; } -/* ── Enterprise upsell text wrapper (Home on-ramp) ────────────────────────── */ -.portal-proc__upsell-text { - flex: 1 1 20rem; -} - /* ── Deal-status hero (Home, active deal) ─────────────────────────────────── */ .portal-hero { border: 1px solid var(--c-border); border-radius: 12px; padding: 1.1rem 1.25rem; - background: - radial-gradient( - 120% 140% at 100% 0%, - color-mix(in srgb, var(--c-hue-violet) 8%, transparent), - transparent 55% - ), - var(--c-surface); + background: var(--c-surface); display: flex; flex-direction: column; gap: 1rem; } + +/* Attached under the editor rail the two read as one card, so the hero drops its standalone frame + and lets the footer's top border be the only seam. It keeps the frame on the procurement view, + where it stands alone. */ +.portal-editor-hero__footer .portal-hero { + border: none; + border-radius: 0; +} .portal-hero__top { display: flex; align-items: flex-start; @@ -983,25 +409,56 @@ gap: 1rem; flex-wrap: wrap; } +.portal-hero__ident { + flex: 1; + min-width: 0; +} .portal-hero__eyebrow { display: block; font-size: 0.6875rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; - color: var(--c-primary); + color: var(--c-text-subtle); + margin-bottom: 0.55rem; } -.portal-hero__company { - display: block; - font-size: 1.0625rem; - font-weight: 650; +/* The journey band: one segment per stage, filled through the current one. A progress indicator, + so it lives inside the block whose progress it reports and deliberately does not pulse. */ +.portal-hero__bar { + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 0.625rem; +} +.portal-hero__bar span { + flex: 1; + height: 6px; + border-radius: 999px; + background: var(--c-hover); + transition: background 0.3s ease; +} +.portal-hero__bar span[data-on] { + background: var(--c-primary); +} +/* The hero's one-line status: bold stage · what it asks, then Next: … */ +.portal-hero__sentence { + margin: 0; + font-size: 0.84375rem; + line-height: 1.5; + color: var(--c-text-muted); +} +.portal-hero__sentence strong { + font-weight: 700; color: var(--c-text); - margin-top: 0.2rem; +} +.portal-hero__sentence-next { + color: var(--c-text-subtle); } .portal-hero__chips { display: flex; gap: 0.4rem; flex-wrap: wrap; + margin-top: 0.5rem; } .portal-hero__chip { font-size: 0.6875rem; @@ -1011,88 +468,74 @@ border-radius: 999px; padding: 0.2rem 0.6rem; } -.portal-hero__stepper { - overflow-x: auto; -} -.portal-hero__next { +/* One action row: the stage's primary CTA leads, quiet icon actions sit beside it. No dividers. */ +.portal-hero__cta { display: flex; align-items: center; - justify-content: space-between; gap: 0.75rem; flex-wrap: wrap; - padding-top: 0.85rem; - border-top: 1px solid var(--c-border-subtle); } -.portal-hero__next-label { +.portal-hero__icons { + display: flex; + align-items: center; + gap: 0.5rem; +} +.portal-hero__iconbtn { + width: 34px; + height: 34px; display: inline-flex; align-items: center; - gap: 0.45rem; - font-size: 0.8125rem; - font-weight: 600; - color: var(--c-text-muted); -} -.portal-hero__next-dot { - width: 0.5rem; - height: 0.5rem; - border-radius: 999px; - background: var(--c-primary); - box-shadow: 0 0 0 3px var(--c-primary-subtle); -} - -/* ── Full-screen takeover modal (procurement flow) ────────────────────────── */ -.portal-procmodal { - position: fixed; - inset: 0; - z-index: 1000; - display: flex; - align-items: flex-start; justify-content: center; - padding: clamp(0.5rem, 4vh, 3rem) 1rem; - overflow-y: auto; - background: var(--c-overlay); - backdrop-filter: blur(6px) saturate(160%); - -webkit-backdrop-filter: blur(6px) saturate(160%); - animation: portal-procmodal-fade 0.15s ease-out; -} -@keyframes portal-procmodal-fade { - from { - opacity: 0; - } - to { - opacity: 1; - } -} -.portal-procmodal__panel { - position: relative; - width: 100%; - max-width: 62rem; - background: var(--c-surface); + border-radius: 9px; border: 1px solid var(--c-border); - border-radius: 14px; - box-shadow: 0 24px 64px rgba(0, 0, 0, 0.28); - padding: 1.5rem 1.5rem 1.75rem; -} -.portal-procmodal__close { - position: absolute; - top: 0.85rem; - right: 0.85rem; - border: none; - background: var(--c-border-subtle); - color: var(--c-text-subtle); - width: 1.9rem; - height: 1.9rem; - border-radius: 8px; - font-size: 0.85rem; + 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-procmodal__close:hover { - background: var(--c-border); +.portal-hero__iconbtn:hover { + background: var(--c-hover); + border-color: var(--c-border-strong); color: var(--c-text); } -.portal-procmodal__header { - margin-bottom: 1.25rem; - padding-right: 2.5rem; +/* Terminal state: the deal is done, so the row reports rather than asks. */ +.portal-hero__live { + display: flex; + align-items: center; + gap: 0.75rem; } +.portal-hero__live-tile { + width: 40px; + height: 40px; + flex-shrink: 0; + border-radius: 11px; + display: flex; + align-items: center; + justify-content: center; + /* Holds a CheckIcon, which takes its stroke from `color` and its size from its own prop. */ + color: var(--c-success); + background: var(--c-success-subtle); +} +.portal-hero__live-text { + display: flex; + flex-direction: column; + min-width: 0; +} +.portal-hero__live-title { + font-size: 0.90625rem; + font-weight: 700; + color: var(--c-text); +} +.portal-hero__live-sub { + font-size: 0.78125rem; + color: var(--c-text-subtle); + margin-top: 1px; +} + +/* ── Procurement takeover: heading type only, the shell is the shared Modal ── */ .portal-procmodal__title { margin: 0; font-size: 1.35rem; @@ -1104,15 +547,6 @@ font-size: 0.875rem; color: var(--c-text-subtle); } -.portal-procmodal__body { - display: flex; - flex-direction: column; - gap: 1.25rem; -} - -.portal-proc__modal-stepper { - overflow-x: auto; -} .portal-proc__payment-actions { display: flex; gap: 0.6rem; @@ -1124,7 +558,7 @@ padding: 1rem; border: 1px solid var(--c-border); border-radius: 0.6rem; - background: var(--color-surface-2, rgba(0, 0, 0, 0.02)); + background: var(--c-surface-sunken); } .portal-proc__license-label { display: block; @@ -1139,7 +573,7 @@ margin-top: 0.4rem; padding: 0.55rem 0.7rem; border-radius: 0.4rem; - background: var(--color-surface-3, rgba(0, 0, 0, 0.05)); + background: var(--c-surface-raised); font-family: var(--font-mono, monospace); font-size: 0.85rem; word-break: break-all; @@ -1150,45 +584,9 @@ font-size: 0.75rem; color: var(--c-text-subtle, var(--c-text-muted)); } -.portal-proc__milestone-for { - margin: 0.15rem 0 0; - font-size: 0.8125rem; - font-weight: 600; - color: var(--c-text-muted); -} -.portal-proc__milestone-lines { - margin: 0.85rem 0 0.5rem; -} -.portal-proc__milestone-totals { - display: flex; - align-items: baseline; - gap: 1rem; - flex-wrap: wrap; - margin: 0.75rem 0 0.25rem; -} -.portal-proc__milestone-annual { - font-size: 1.75rem; - font-weight: 700; - color: var(--c-text); -} -.portal-proc__milestone-annual small { - font-size: 0.8125rem; - font-weight: 500; - color: var(--c-text-subtle); -} -.portal-proc__milestone-tcv { - font-size: 0.8125rem; - color: var(--c-text-subtle); -} /* Hero next-step action row (primary CTA + optional extend-trial). */ -.portal-hero__next-actions { - display: flex; - gap: 0.5rem; - flex-wrap: wrap; -} - -/* Hero quick-action chips (clickable pills next to the company name). */ +/* Hero quick-action chips (the trial countdown pill under the stage sentence). */ .portal-hero__chip--action { border: 1px solid var(--c-border); cursor: pointer; @@ -1203,101 +601,8 @@ transform: translateY(-1px); } -/* Hero rollout checklist (trial): the "do this now" setup steps. */ -.portal-hero__checklist { - list-style: none; - margin: 0; - padding: 0; - border-top: 1px solid var(--c-border-subtle); -} -.portal-hero__checklist li { - border-bottom: 1px solid var(--c-border-subtle); -} -.portal-hero__checklist button { - display: flex; - align-items: center; - gap: 0.85rem; - width: 100%; - padding: 0.7rem 0.25rem; - background: none; - border: none; - cursor: pointer; - text-align: left; -} -.portal-hero__checklist button:hover { - background: var(--c-hover, var(--c-border-subtle)); -} -.portal-hero__check-dot { - width: 0.5rem; - height: 0.5rem; - border-radius: 999px; - background: var(--c-border); - flex-shrink: 0; -} -.portal-hero__check-text { - flex: 1; - min-width: 0; -} -.portal-hero__check-title { - display: block; - font-size: 0.85rem; - font-weight: 600; - color: var(--c-text); -} -.portal-hero__check-sub { - display: block; - font-size: 0.75rem; - color: var(--c-text-subtle); - margin-top: 0.05rem; -} -.portal-hero__check-pill { - font-size: 0.6875rem; - font-weight: 600; - color: var(--c-text-subtle); - background: var(--c-border-subtle); - border-radius: 999px; - padding: 0.15rem 0.55rem; - flex-shrink: 0; -} - /* ── Side dialogs (Key documents / Schedule a call / Trial) ───────────────── */ -.portal-sidemodal { - position: fixed; - inset: 0; - z-index: 1100; - display: flex; - align-items: center; - justify-content: center; - padding: 1rem; - overflow-y: auto; - background: var(--c-overlay); - backdrop-filter: blur(4px); - -webkit-backdrop-filter: blur(4px); - animation: portal-procmodal-fade 0.15s ease-out; - /* Portaled to , outside .portal-scope, so set the portal UI font explicitly. */ - font-family: var(--font-sans); -} -.portal-sidemodal__panel { - position: relative; - width: 100%; - max-width: 30rem; - background: var(--c-surface); - border: 1px solid var(--c-border); - border-radius: 14px; - box-shadow: 0 24px 64px rgba(0, 0, 0, 0.28); - padding: 1.35rem 1.4rem 1.4rem; - max-height: 86vh; - overflow-y: auto; -} -/* Wide enough for Calendly's two-pane layout (its single-column layout below ~680px inner width is - tall and scrolls); paired with the embed's taller fixed height so the time view needs no scroll. */ -.portal-sidemodal__panel--wide { - max-width: 52rem; -} -.portal-sidemodal__header { - margin-bottom: 1rem; - padding-right: 2rem; -} +/* Chrome and width come from the shared Modal via FlowModal; only type and content live here. */ .portal-sidemodal__title { margin: 0; font-size: 1.05rem; @@ -1316,15 +621,6 @@ color: var(--c-text-subtle); line-height: 1.55; } -.portal-sidemodal__footer { - display: flex; - align-items: center; - justify-content: space-between; - gap: 0.75rem; - margin-top: 1.1rem; - padding-top: 0.9rem; - border-top: 1px solid var(--c-border-subtle); -} .portal-sidemodal__ghost { border: none; background: none; @@ -1336,63 +632,6 @@ color: var(--c-text-muted); } -/* Key documents ledger. */ -.portal-docs__group + .portal-docs__group { - margin-top: 1rem; -} -.portal-docs__group-title { - font-size: 0.6875rem; - font-weight: 700; - text-transform: uppercase; - letter-spacing: 0.05em; - color: var(--c-text-subtle); - margin-bottom: 0.4rem; -} -.portal-docs__list { - list-style: none; - margin: 0; - padding: 0; -} -.portal-docs__row { - display: flex; - align-items: center; - gap: 0.75rem; - padding: 0.55rem 0; - border-top: 1px solid var(--c-border-subtle); -} -.portal-docs__row-text { - flex: 1; - min-width: 0; -} -.portal-docs__row-name { - display: block; - font-size: 0.8125rem; - font-weight: 600; - color: var(--c-text); -} -.portal-docs__row-sub { - display: block; - font-size: 0.72rem; - color: var(--c-text-subtle); - margin-top: 0.05rem; -} -.portal-docs__row-action { - font-size: 0.6875rem; - font-weight: 600; - border-radius: 999px; - padding: 0.2rem 0.6rem; - flex-shrink: 0; - color: var(--c-text-subtle); - background: var(--c-border-subtle); -} -.portal-docs__row-action[data-status="action"] { - color: var(--c-primary); - background: var(--c-primary-subtle); -} -.portal-docs__row-action[data-status="request"] { - color: var(--c-text-subtle); -} - /* Calendly scheduler embed (Schedule a call). The widget is always light (Calendly renders inputs on white), so give it a white surface — it reads as a clean card even inside the dark-mode modal. */ .portal-calendly { @@ -1418,17 +657,173 @@ } /* ── Agreement (security) step ────────────────────────────────────────────── */ -.portal-agreement__doc { - margin: 1rem 0; - max-height: 22rem; - overflow-y: auto; - padding: 1rem 1.1rem; - border: 1px solid var(--c-border); - border-radius: 10px; - background: var(--color-bg-subtle, var(--c-bg)); - font-size: 0.8125rem; - line-height: 1.55; +/* 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; + align-items: center; + gap: 0.1rem; +} + +/* The signature block: the three fields that name the bound party and its signatory, on the same line + as the act of signing, with the consent directly beneath them and no rule between. Fields shrink + below the row's usual floor so all three plus the button hold one line at the takeover's width; + they wrap rather than clip if a translation runs long. */ +/* No rule above it: the tray's grey ends where the signature block begins, which is boundary enough, + and a border there cut the document off from the page it sits on. */ +.portal-agreement__signbar { + flex-direction: column; + align-items: stretch; + gap: 0.6rem; + border-top: none; +} +/* Bottom-aligned: a field is a label above an input, so aligning to the block's centre or its top + leaves the button off the input row. Sharing the input's bottom edge puts its centre on theirs, both + being 37px. The gate note is deliberately NOT in this row — hanging it off the button would make the + column taller than the fields and drag the button back up off the row. */ +.portal-agreement__signrow { + display: flex; + align-items: flex-end; + gap: 0.9rem; +} +/* Consent on the left, the gate's state on the right so it lands under the button it explains. */ +.portal-agreement__signfoot { + display: flex; + 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; + gap: 0.6rem; + min-width: 0; +} +.portal-agreement__signrow .portal-qb__field { + min-width: 8.5rem; +} +/* Unboxed: a line of small print under the fields, not a panel competing with the document. */ +.portal-agreement__accept { + display: flex; + align-items: flex-start; + gap: 0.5rem; + font-size: 0.75rem; + line-height: 1.45; + color: var(--c-text-subtle); + cursor: pointer; +} +.portal-agreement__accept input { + margin: 0.1rem 0 0; + flex: 0 0 auto; +} + +/* The agreement is presented as paper, not as app copy in a box: a sunken tray running to the panel's + edges, with the terms on white stock in a serif face. Signing is the most consequential thing a + buyer does here, so the document should read like the document it is. */ +/* The document takes every pixel the dialog can spare: it is what the buyer is here to read, and a + fixed height left it a small white box floating in a tall panel. The chain has to carry the fill — + each link needs min-height:0 or a flex child refuses to shrink below its content. */ +.portal-agreement { + display: flex; + flex-direction: column; + gap: 0.75rem; + flex: 1 1 auto; + min-height: 0; +} +/* The tray is the scroll container, so the paper inside it behaves like a page being scrolled past a + window: flush to the footer while there is more to read, and revealing the tray's bottom padding + only at the end. Scrolling the paper instead left a permanent grey band under it, which read as a + box 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. */ + min-height: 16rem; + padding: 1.35rem 1.6rem; + border: 1px solid var(--c-border-subtle); + border-radius: 12px; + background: var(--c-surface); + box-shadow: var(--shadow-sm); + /* No serif token exists in the theme — the serif is specific to rendering legal terms as paper. */ + font-family: Georgia, "Times New Roman", "Liberation Serif", serif; + font-size: 0.84rem; + line-height: 1.62; + color: var(--c-text-muted); +} +/* Masthead above the document's own heading: confidentiality on the left, the quote reference and + signed version on the right, over the rule that opens the terms. */ +.portal-agreement__letterhead { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; + padding-bottom: 0.6rem; + margin-bottom: 1rem; + border-bottom: 2px solid var(--c-text); + font-family: var(--font-sans); + font-size: 0.6875rem; + letter-spacing: 0.04em; + color: var(--c-text-subtle); +} +.portal-agreement__confidential { + font-weight: 700; + text-transform: uppercase; +} +/* The document's own title, centred like an executed agreement's. */ +.portal-agreement__md > h1:first-child, +.portal-agreement__md > h2:first-child { + text-align: center; + font-size: 1.05rem; + letter-spacing: 0.02em; + text-transform: uppercase; + margin-bottom: 1rem; } .portal-agreement__doc h4 { margin: 1rem 0 0.35rem; @@ -1445,29 +840,129 @@ .portal-agreement__doc strong { color: var(--c-text); } -.portal-agreement__accept { - margin-top: 0.25rem; +.portal-agreement__md h1 { + font-size: 0.95rem; + font-weight: 700; + color: var(--c-text); + margin: 1.1rem 0 0.5rem; } -.portal-agreement__lines { - margin: 0.4rem 0 0.6rem; +.portal-agreement__md h2 { + font-size: 0.875rem; + font-weight: 650; + color: var(--c-text); + margin: 1rem 0 0.4rem; } -.portal-proc__reset { - display: flex; - justify-content: center; - padding-top: 0.5rem; +.portal-agreement__md h3 { + font-size: 0.8125rem; + font-weight: 650; + color: var(--c-text); + margin: 0.9rem 0 0.3rem; } -.portal-proc__reset button { +.portal-agreement__md h1:first-child, +.portal-agreement__md h2:first-child { + margin-top: 0; +} +.portal-agreement__md p { + margin: 0 0 0.55rem; +} +.portal-agreement__md strong { + color: var(--c-text); +} +.portal-agreement__md ul { + margin: 0 0 0.6rem; + padding-left: 1.1rem; +} +.portal-agreement__md li { + margin-bottom: 0.2rem; +} +.portal-agreement__md table { + border-collapse: collapse; + width: 100%; + margin: 0.4rem 0 0.8rem; + font-size: 0.78rem; +} +.portal-agreement__md th, +.portal-agreement__md td { + border: 1px solid var(--c-border); + padding: 0.35rem 0.5rem; + text-align: left; + vertical-align: top; +} +.portal-agreement__md th { + background: var(--c-bg); + font-weight: 650; + color: var(--c-text); +} +.portal-agreement__signfields { + margin-top: 0.75rem; +} +.portal-proc__error { + color: var(--c-danger); + font-size: 0.8125rem; + margin: 0.5rem 0 0; +} +.portal-legal__link { border: none; background: none; + padding: 0; + font: inherit; + color: var(--c-text); + text-decoration: underline; + cursor: pointer; +} +.portal-legal__link:hover { + color: var(--c-text); +} +.portal-docmodal { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; +} +.portal-docmodal__row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding: 0.85rem 0; + border-bottom: 1px solid var(--c-border); +} +.portal-docmodal__row:last-child { + border-bottom: none; +} +.portal-docmodal__text { + display: flex; + flex-direction: column; + gap: 0.15rem; + min-width: 0; +} +.portal-docmodal__name { + font-weight: 650; + font-size: 0.875rem; + color: var(--c-text); +} +.portal-docmodal__sub { + font-size: 0.75rem; + color: var(--c-text-muted); +} +.portal-docmodal__later { + flex-shrink: 0; font-size: 0.75rem; color: var(--c-text-subtle); - cursor: pointer; - text-decoration: underline; + white-space: nowrap; } -.portal-proc__reset button:hover:not(:disabled) { + +/* Title row: the step badge rides beside the heading, not on a line of its own. */ +.portal-sidemodal__title-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; +} + +/* Quiet hint sat opposite the primary action in a dialog footer. */ +.portal-sidemodal__foot-hint { + font-size: 0.75rem; color: var(--c-text-subtle); } -.portal-proc__reset button:disabled { - opacity: 0.5; - cursor: default; -} diff --git a/frontend/editor/src/portal/views/Procurement.tsx b/frontend/editor/src/portal/views/Procurement.tsx deleted file mode 100644 index 1f6e2329a9..0000000000 --- a/frontend/editor/src/portal/views/Procurement.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { ProcurementHome } from "@portal/components/procurement/ProcurementHome"; -import "@portal/views/Procurement.css"; - -/** - * /procurement — procurement is no longer a nav tab; it lives on Home as the deal-status hero. - * This route is kept for deep links (and the Usage "Build your quote" CTA): it renders the same - * surface, opening the takeover modal once a deal is underway. - */ -export function Procurement() { - return ( -
    - -
    - ); -} diff --git a/frontend/eslint.config.mjs b/frontend/eslint.config.mjs index d2853d8f1e..256bdf640a 100644 --- a/frontend/eslint.config.mjs +++ b/frontend/eslint.config.mjs @@ -258,12 +258,7 @@ export default defineConfig( // can't represent. Exempt ONLY the raw-