#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add SaaS Enterprise trials, usage and procurement access (#8453)
ConnorYohb6413c90c7b9
diff --git a/app/saas/src/main/java/stirling/software/saas/billing/model/BillingSubscription.java b/app/saas/src/main/java/stirling/software/saas/billing/model/BillingSubscription.javaindex 05bf8a8ee2..d57f0a8e42 100644--- a/app/saas/src/main/java/stirling/software/saas/billing/model/BillingSubscription.java+++ b/app/saas/src/main/java/stirling/software/saas/billing/model/BillingSubscription.java@@ -21,7 +21,7 @@ import lombok.Setter;* record a tenant's subscription state.*/@Entity-@Table(name = "billing_subscriptions")+@Table(name = "billing_subscriptions", schema = "public")@NoArgsConstructor@Getter@Setterdiff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.javaindex b60b4efa86..51db653118 100644--- a/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java+++ b/app/saas/src/main/java/stirling/software/saas/config/SaasSchemaOwnership.java@@ -46,6 +46,7 @@ public final class SaasSchemaOwnership {"audit_events","authorities","billing_subscriptions",+ "file_run_events","job_artifact_hash","legal_consent","linked_instance",@@ -59,6 +60,7 @@ public final class SaasSchemaOwnership {"processing_job","processing_job_step","procurement_agreement_signature",+ "procurement_activity","procurement_deal","procurement_quote","saas_team_extensions",@@ -89,7 +91,6 @@ public final class SaasSchemaOwnership {"api_key_daily_usage","api_keys","file_encryption_keys",- "file_run_events","file_share_accesses","file_shares","folders",diff --git a/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java b/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.javaindex e2758cb4d7..66381ee141 100644--- a/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java+++ b/app/saas/src/main/java/stirling/software/saas/controller/SaasTeamController.java@@ -51,6 +51,8 @@ public class SaasTeamController {private final TeamInvitationRepository invitationRepository;private final UserService userService;private final TeamSecurityExpressions teamSecurityExpressions;+ private final stirling.software.saas.procurement.service.EnterpriseEntitlementService+ enterprise;// ========== NEW TEAM INVITATION ENDPOINTS ==========@@ -526,7 +528,7 @@ public class SaasTeamController {// seatCount and maxSeats now share the same backing field on the extension.maxSeats,saasTeamExtensionService.getSeatsUsed(team),- maxSeats,+ enterprise.isActive(team.getId()) ? null : maxSeats,isLeader);}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.javaindex 23e7df301a..a7e4d1989d 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java@@ -56,6 +56,7 @@ import stirling.software.saas.payg.repository.WalletLedgerRepository;import stirling.software.saas.payg.repository.WalletPolicyRepository;import stirling.software.saas.payg.wallet.WalletLedgerEntry;import stirling.software.saas.payg.wallet.WalletPolicy;+import stirling.software.saas.procurement.service.EnterpriseEntitlementService;import stirling.software.saas.repository.SaasTeamExtensionsRepository;import stirling.software.saas.security.UserTeamResolver;import stirling.software.saas.util.AuthenticationUtils;@@ -116,6 +117,7 @@ public class PaygWalletController {private final UserTeamResolver userTeamResolver;private final SaasTeamExtensionsRepository teamExtensionsRepository;private final FleetSeatService fleetSeats;+ private final EnterpriseEntitlementService enterprise;public PaygWalletController(EntitlementService entitlementService,@@ -129,8 +131,10 @@ public class PaygWalletController {PrepaidBundleService prepaidBundleService,UserTeamResolver userTeamResolver,SaasTeamExtensionsRepository teamExtensionsRepository,- FleetSeatService fleetSeats) {+ FleetSeatService fleetSeats,+ EnterpriseEntitlementService enterprise) {this.fleetSeats = fleetSeats;+ this.enterprise = Objects.requireNonNull(enterprise);this.entitlementService = Objects.requireNonNull(entitlementService, "entitlementService");this.billingService = Objects.requireNonNull(billingService, "billingService");this.memberRepo = Objects.requireNonNull(memberRepo, "memberRepo");@@ -267,10 +271,31 @@ public class PaygWalletController {: billing.includedPeriodStart().toLocalDate().toString(),billing.includedPeriodEnd() == null? null- : billing.includedPeriodEnd().toLocalDate().toString());+ : billing.includedPeriodEnd().toLocalDate().toString(),+ enterpriseHolding(teamId));return ResponseEntity.ok(body);}+ private WalletSnapshotResponse.EnterpriseHolding enterpriseHolding(Long teamId) {+ return enterprise+ .findActive(teamId)+ .map(+ ent -> {+ long used =+ ledgerRepo.sumEnterprisePdfs(+ teamId, ent.periodStart(), ent.periodEnd());+ return new WalletSnapshotResponse.EnterpriseHolding(+ ent.status(),+ ent.periodStart().toString() + "Z",+ ent.periodEnd().toString() + "Z",+ ent.accessUntil().toString() + "Z",+ ent.agreedSeats(),+ ent.annualVolume(),+ used);+ })+ .orElse(null);+ }+/*** The team's user-capacity holding. The cap is written from the Team subscription, so a team* holds Team exactly when {@link SaasTeamExtensions#licensedUsers()} states one.@@ -554,6 +579,7 @@ public class PaygWalletController {BILLING_MODE_PAYG,null,null,+ null,null);}}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.java b/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.javaindex 0acf08d624..e666194f5f 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.java@@ -102,7 +102,18 @@ public record WalletSnapshotResponse(String billingMode,BigDecimal bundleRatePerCreditMinor,String includedPeriodStart,- String includedPeriodEnd) {+ String includedPeriodEnd,+ EnterpriseHolding enterprise) {++ /** Agreement quantities and actual PDF inputs over its period; absent when access has ended. */+ public record EnterpriseHolding(+ String status,+ String periodStart,+ String periodEnd,+ String accessUntil,+ Integer agreedSeats,+ Long annualVolume,+ long pdfsUsed) {}// Prepaid usage bundles, aggregated across the team's in-term pools (drawn ahead of the meter,// outside the spend cap):diff --git a/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java b/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.javaindex 85cb4cfa44..d3863c31b6 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java@@ -43,6 +43,7 @@ import stirling.software.saas.payg.repository.ProcessingJobRepository;import stirling.software.saas.payg.repository.WalletLedgerRepository;import stirling.software.saas.payg.shadow.PaygShadowCharge;import stirling.software.saas.payg.wallet.WalletLedgerEntry;+import stirling.software.saas.procurement.service.EnterpriseEntitlementService;/*** Orchestrates a tool call's open-process decision: look up the team's effective policy, resolve@@ -73,6 +74,7 @@ public class JobChargeService {private final WalletLedgerRepository ledgerRepository;private final PrepaidBundleService prepaidBundleService;private final TeamBillingService teamBillingService;+ private final EnterpriseEntitlementService enterprise;public JobChargeService(JobService jobService,@@ -84,7 +86,8 @@ public class JobChargeService {PaygMeterReportingService meterReportingService,WalletLedgerRepository ledgerRepository,PrepaidBundleService prepaidBundleService,- TeamBillingService teamBillingService) {+ TeamBillingService teamBillingService,+ EnterpriseEntitlementService enterprise) {this.jobService = Objects.requireNonNull(jobService, "jobService");this.policyService = Objects.requireNonNull(policyService, "policyService");this.classifier = Objects.requireNonNull(classifier, "classifier");@@ -98,6 +101,7 @@ public class JobChargeService {this.prepaidBundleService =Objects.requireNonNull(prepaidBundleService, "prepaidBundleService");this.teamBillingService = Objects.requireNonNull(teamBillingService, "teamBillingService");+ this.enterprise = Objects.requireNonNull(enterprise, "enterprise");}/**@@ -136,11 +140,13 @@ public class JobChargeService {int units = computeUnits(inputs, policy);job.setDocUnits(units);- FreeGrantDraw freeDraw = consumeFreeGrant(ctx, units);+ boolean covered = enterprise.isActive(ctx.ownerTeamId());+ FreeGrantDraw freeDraw =+ covered ? new FreeGrantDraw(0, null) : consumeFreeGrant(ctx, units);int freeUsed = freeDraw.units();// Prepaid bundle is the tier between the free grant and the meter (free → prepaid →// metered); draw only what the free grant didn't cover.- int bundleUsed = drawBundle(ctx, units - freeUsed);+ int bundleUsed = covered ? 0 : drawBundle(ctx, units - freeUsed);recordShadowRow(ctx,job.getId(),@@ -148,7 +154,8 @@ public class JobChargeService {units,freeUsed,bundleUsed,- freeDraw.periodStart());+ freeDraw.periodStart(),+ covered);// doc_count + fingerprint were set on the fresh job by JobService.openFresh; carry them// onto the ledger DEBIT so usage analytics query one table. Bundle-drawn units are netted// out of the ledger amount so they never count against the spend cap (they're prepaid, not@@ -157,7 +164,7 @@ public class JobChargeService {ctx,job.getId(),policy.getId(),- units,+ covered ? 0 : units,bundleUsed,job.getDocCount(),job.getDocumentFingerprint());@@ -201,9 +208,11 @@ public class JobChargeService {ctx.runId());ProcessingJob job = jobService.open(jobCtx, chargeUnits);- FreeGrantDraw freeDraw = consumeFreeGrant(ctx, chargeUnits);+ boolean covered = enterprise.isActive(ctx.ownerTeamId());+ FreeGrantDraw freeDraw =+ covered ? new FreeGrantDraw(0, null) : consumeFreeGrant(ctx, chargeUnits);int freeUsed = freeDraw.units();- int bundleUsed = drawBundle(ctx, chargeUnits - freeUsed);+ int bundleUsed = covered ? 0 : drawBundle(ctx, chargeUnits - freeUsed);recordShadowRow(ctx,job.getId(),@@ -211,12 +220,13 @@ public class JobChargeService {chargeUnits,freeUsed,bundleUsed,- freeDraw.periodStart());+ freeDraw.periodStart(),+ covered);recordLedgerDebit(ctx,job.getId(),policy.getId(),- chargeUnits,+ covered ? 0 : chargeUnits,bundleUsed,job.getDocCount(),job.getDocumentFingerprint());@@ -380,12 +390,14 @@ public class JobChargeService {int units,int freeUnitsConsumed,int bundleUnitsConsumed,- LocalDateTime includedPeriodStart) {+ LocalDateTime includedPeriodStart,+ boolean enterpriseCovered) {PaygShadowCharge row = new PaygShadowCharge();row.setTeamId(ctx.ownerTeamId());row.setJobId(jobId);row.setPolicyId(policyId);row.setPaygUnits(units);+ row.setEnterpriseCovered(enterpriseCovered);// Free/prepaid/paid split fixed at charge time: metered = paygUnits - freeUnitsConsumed -// bundleUnitsConsumed. A refund restores each portion to its source (grant / pools).row.setFreeUnitsConsumed(freeUnitsConsumed);@@ -442,7 +454,8 @@ public class JobChargeService {refund.setBucket(LedgerBucket.CYCLE);// Mirror the reduced DEBIT: prepaid units never entered the CYCLE spend, so the// compensating credit is the metered portion only (paygUnits − bundle).- refund.setAmountUnits(row.getPaygUnits() - bundleConsumed);+ refund.setAmountUnits(+ row.isEnterpriseCovered() ? 0 : row.getPaygUnits() - bundleConsumed);refund.setReferenceType(ReferenceType.JOB);refund.setReferenceId(jobId.toString());refund.setPolicyId(row.getPolicyId());@@ -551,7 +564,7 @@ public class JobChargeService {return;}PaygShadowCharge row = rowOpt.get();- if (row.getStatus() == ShadowChargeStatus.REFUNDED) {+ if (row.getStatus() == ShadowChargeStatus.REFUNDED || row.isEnterpriseCovered()) {// Refunded rows are zero-net charges; do not emit a meter event.return;}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementService.java b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementService.javaindex 49eca53f37..7a10fefd7c 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementService.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementService.java@@ -26,6 +26,7 @@ import stirling.software.saas.payg.model.FeatureSet;import stirling.software.saas.payg.repository.PaygShadowChargeRepository;import stirling.software.saas.payg.repository.WalletPolicyRepository;import stirling.software.saas.payg.wallet.WalletPolicy;+import stirling.software.saas.procurement.service.EnterpriseEntitlementService;/*** Hot-path entitlement lookup. Returns the {@link EntitlementSnapshot} for a team: the billing@@ -54,6 +55,7 @@ public class EntitlementService {private final WalletPolicyRepository walletPolicyRepository;private final PaygShadowChargeRepository shadowRepository;private final PrepaidBundleService prepaidBundleService;+ private final EnterpriseEntitlementService enterprise;private final Cache<Long, EntitlementSnapshot> snapshotCache;@@ -61,13 +63,15 @@ public class EntitlementService {TeamBillingService teamBillingService,WalletPolicyRepository walletPolicyRepository,PaygShadowChargeRepository shadowRepository,- PrepaidBundleService prepaidBundleService) {+ PrepaidBundleService prepaidBundleService,+ EnterpriseEntitlementService enterprise) {this.teamBillingService = Objects.requireNonNull(teamBillingService, "teamBillingService");this.walletPolicyRepository =Objects.requireNonNull(walletPolicyRepository, "walletPolicyRepository");this.shadowRepository = Objects.requireNonNull(shadowRepository, "shadowRepository");this.prepaidBundleService =Objects.requireNonNull(prepaidBundleService, "prepaidBundleService");+ this.enterprise = Objects.requireNonNull(enterprise, "enterprise");this.snapshotCache =Caffeine.newBuilder().maximumSize(CACHE_MAX_SIZE)@@ -85,6 +89,18 @@ public class EntitlementService {*/public EntitlementSnapshot getSnapshot(Long teamId) {Objects.requireNonNull(teamId, "teamId");+ if (enterprise.isActive(teamId)) {+ TeamBillingContext billing = teamBillingService.forTeam(teamId);+ return new EntitlementSnapshot(+ EntitlementState.FULL,+ FeatureSet.FULL,+ List.copyOf(CapEvaluator.gatesFor(FeatureSet.FULL)),+ 0L,+ null,+ billing.periodStart(),+ billing.periodEnd(),+ billing.subscribed());+ }return snapshotCache.get(teamId, this::computeSnapshot);}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygShadowChargeRepository.java b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygShadowChargeRepository.javaindex 436440f21e..2047d9f5a5 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygShadowChargeRepository.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygShadowChargeRepository.java@@ -37,6 +37,7 @@ public interface PaygShadowChargeRepository extends JpaRepository<PaygShadowChar@Query("SELECT COALESCE(SUM(s.paygUnits - s.freeUnitsConsumed - s.bundleUnitsConsumed), 0) FROM PaygShadowCharge s"+ " WHERE s.teamId = :teamId"+ + " AND s.enterpriseCovered = false"+ " AND s.status = stirling.software.saas.payg.model.ShadowChargeStatus.CHARGED"+ " AND s.occurredAt >= :from AND s.occurredAt < :to")long sumPaidUnits(diff --git a/app/saas/src/main/java/stirling/software/saas/payg/repository/WalletLedgerRepository.java b/app/saas/src/main/java/stirling/software/saas/payg/repository/WalletLedgerRepository.javaindex f94c97b7f5..90c76a28a6 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/repository/WalletLedgerRepository.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/repository/WalletLedgerRepository.java@@ -12,6 +12,19 @@ import stirling.software.saas.payg.wallet.WalletLedgerEntry;public interface WalletLedgerRepository extends JpaRepository<WalletLedgerEntry, Long> {+ /** Successful PDF inputs in the agreement window, including work covered by Enterprise. */+ @Query(+ "SELECT COALESCE(SUM(e.docCount), 0) FROM WalletLedgerEntry e"+ + " WHERE e.teamId = :teamId AND e.entryType = stirling.software.saas.payg.model.LedgerEntryType.DEBIT"+ + " AND e.billingCategory IS NOT NULL AND e.occurredAt >= :start AND e.occurredAt < :end"+ + " AND NOT EXISTS (SELECT r.id FROM WalletLedgerEntry r WHERE r.teamId = e.teamId"+ + " AND r.referenceId = e.referenceId AND r.referenceType = e.referenceType"+ + " AND r.entryType = stirling.software.saas.payg.model.LedgerEntryType.REFUND)")+ long sumEnterprisePdfs(+ @Param("teamId") Long teamId,+ @Param("start") LocalDateTime start,+ @Param("end") LocalDateTime end);+/** Most recent entries for the Plan page activity feed. */List<WalletLedgerEntry> findTop20ByTeamIdOrderByIdDesc(Long teamId);diff --git a/app/saas/src/main/java/stirling/software/saas/payg/shadow/PaygShadowCharge.java b/app/saas/src/main/java/stirling/software/saas/payg/shadow/PaygShadowCharge.javaindex 1881666827..f9c267a566 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/shadow/PaygShadowCharge.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/shadow/PaygShadowCharge.java@@ -58,6 +58,13 @@ public class PaygShadowCharge implements Serializable {@Column(name = "payg_units", nullable = false)private Integer paygUnits;+ /** Fixed at job admission so a later plan change cannot bill or refund included work. */+ @Column(+ name = "enterprise_covered",+ nullable = false,+ columnDefinition = "boolean not null default false")+ private boolean enterpriseCovered;+/*** How many of {@link #paygUnits} were drawn from the team's free grant at charge time. The paid* (Stripe-metered) portion is {@code paygUnits - freeUnitsConsumed}; a refund restores thisdiff --git a/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.java b/app/saas/src/main/java/stirling/software/saas/procurement/api/ProcurementController.javaindex 18ea5ff3d9..ae35e53d39 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@@ -36,6 +36,7 @@ import stirling.software.saas.procurement.pricing.ProcurementPricingService;import stirling.software.saas.procurement.pricing.QuoteConfig;import stirling.software.saas.procurement.pricing.QuoteLineItem;import stirling.software.saas.procurement.service.ProcurementService;+import stirling.software.saas.procurement.service.ProcurementService.ContractPeriod;import stirling.software.saas.security.UserTeamResolver;import stirling.software.saas.util.AuthenticationUtils;@@ -332,6 +333,30 @@ public class ProcurementController {}}+ /** Staff grants use the same trial and licence as the customer-facing procurement journey. */+ public record GrantTrialRequest(long teamId, java.time.LocalDateTime endsAt, String reason) {}++ @PostMapping("/trial/grant")+ @PreAuthorize("hasRole('ADMIN')")+ public ResponseEntity<SnapshotResponse> grantTrial(+ @RequestBody GrantTrialRequest request, Authentication auth) {+ if (request.teamId() <= 0) return ResponseEntity.badRequest().build();+ try {+ return ResponseEntity.ok(+ toSnapshot(+ procurement.grantTrial(+ request.teamId(),+ request.endsAt(),+ request.reason(),+ auth.getName()),+ true));+ } catch (IllegalArgumentException e) {+ return ResponseEntity.badRequest().build();+ } catch (IllegalStateException e) {+ return ResponseEntity.status(HttpStatus.CONFLICT).build();+ }+ }+@PostMapping("/quote")@PreAuthorize("isAuthenticated()")public ResponseEntity<QuoteResponse> buildQuote(@@ -475,17 +500,13 @@ public class ProcurementController {.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- * the subscription + invoice exist, so the buyer is licensed the moment they accept — the deal- * stays in the payment step until the invoice settles. Idempotent.- */+ /** Grants access through the verified invoice due date; the payment step remains visible. */@PostMapping("/provision")@PreAuthorize("hasRole('ADMIN')")- public ResponseEntity<Void> provision(@RequestParam("teamId") long teamId) {+ public ResponseEntity<Void> provision(+ @RequestParam("teamId") long teamId, @RequestBody ContractPeriod period) {try {- procurement.provisionLicense(teamId);+ procurement.provisionLicense(teamId, period);return ResponseEntity.ok().build();} catch (IllegalStateException e) {log.warn("[procurement] provision rejected team={}: {}", teamId, e.getMessage());@@ -494,34 +515,33 @@ 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.- *- * <p>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.- *- * <p>{@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.+ * Applies a paid service period. A missing or mismatched agreement returns 409 for retry or+ * operator reconciliation.*/@PostMapping("/activate")@PreAuthorize("hasRole('ADMIN')")public ResponseEntity<Void> activate(@RequestParam("teamId") long teamId,- @RequestParam(value = "invoiceId", required = false) String invoiceId) {+ @RequestParam(value = "invoiceId") String invoiceId,+ @RequestBody ContractPeriod period) {try {- procurement.markLive(teamId, invoiceId);+ procurement.markLive(teamId, invoiceId, period);} catch (IllegalStateException e) {- log.info(- "[procurement] activate skipped, no deal for team={}: {}",- teamId,- e.getMessage());+ log.info("[procurement] activation rejected team={}: {}", teamId, e.getMessage());+ return ResponseEntity.status(HttpStatus.CONFLICT).build();}return ResponseEntity.ok().build();}+ @PostMapping("/end-access")+ @PreAuthorize("hasRole('ADMIN')")+ public ResponseEntity<Void> endAccess(+ @RequestParam("teamId") long teamId,+ @RequestParam("subscriptionId") String subscriptionId) {+ procurement.endAccess(teamId, subscriptionId);+ 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). Production go-live runs through {@code /activate}.@@ -634,7 +654,7 @@ public class ProcurementController {q.getStripeInvoicePdf(),new QuoteConfigEcho(q.getVolume(),- 0,+ q.getSeats() == null ? 0 : q.getSeats(),q.getIntensity(),q.getSizeMult(),q.getDeployment(),diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/license/KeygenEnterpriseLicenseService.java b/app/saas/src/main/java/stirling/software/saas/procurement/license/KeygenEnterpriseLicenseService.javaindex 22252d892b..a27ec85190 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/license/KeygenEnterpriseLicenseService.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/license/KeygenEnterpriseLicenseService.java@@ -197,8 +197,9 @@ public class KeygenEnterpriseLicenseService implements EnterpriseLicenseServiceprivate Map<String, Object> annualMetadata(Long teamId, LicenseEntitlements ent) {Map<String, Object> m = baseMetadata(teamId, false);int seats = Math.max(0, ent.seats());- m.put("users", seats); // 0 = unlimited- m.put("seat_count", seats); // parity with the self-hosted edge's metadata+ m.put("users", 0);+ m.put("seat_count", 0);+ m.put("agreed_seats", seats);m.put("volume", ent.volume()); // committed PDFs / yearm.put("term_years", ent.termYears());if (ent.serviceLevel() != null && !ent.serviceLevel().isBlank()) {diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementActivity.java b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementActivity.javanew file mode 100644index 0000000000..c89fe6cd5b--- /dev/null+++ b/app/saas/src/main/java/stirling/software/saas/procurement/model/ProcurementActivity.java@@ -0,0 +1,46 @@+package stirling.software.saas.procurement.model;++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;++/** Durable commercial audit trail in the existing procurement_activity table. */+@Entity+@Table(name = "procurement_activity")+@Getter+@NoArgsConstructor+public class ProcurementActivity {+ @Id+ @GeneratedValue(strategy = GenerationType.IDENTITY)+ @Column(name = "activity_id")+ private Long id;++ @Column(name = "deal_id", nullable = false)+ private Long dealId;++ @Column(name = "action", nullable = false, length = 48)+ private String action;++ @Column(name = "detail")+ private String detail;++ @CreationTimestamp+ @Column(name = "created_at", nullable = false)+ private LocalDateTime createdAt;++ public ProcurementActivity(Long dealId, String action, String detail) {+ this.dealId = dealId;+ this.action = action;+ this.detail = detail;+ }+}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.javaindex f0db2fb6db..0f475f8dfe 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@@ -19,11 +19,9 @@ import lombok.NoArgsConstructor;import lombok.Setter;/**- * A linked team's enterprise commercial journey (one per team). Stage mirrors the buyer journey the- * portal renders (trial -> quote -> agreement -> payment -> live). The entitlement that- * actually unlocks the product is the Keygen licence in {@code licenseRef}; the paid subscription,- * once commercial, is mirrored in {@code billing_subscriptions} and referenced by {@code- * subscriptionId}.+ * One commercial journey per team. Trial and purchased-period dates govern SaaS access; the Keygen+ * licence carries the same expiry for self-hosted use. The accepted quote retains the agreed users+ * and annual PDF volume independently of enforced PAYG capacity.*/@Entity@Table(name = "procurement_deal")@@ -99,6 +97,10 @@ public class ProcurementDeal implements Serializable {@Column(name = "subscription_id", length = 255)private String subscriptionId;+ /** Blocks cancelled-period replays without treating an unpaid cutoff as termination. */+ @Column(name = "terminated_subscription_id", length = 255)+ private String terminatedSubscriptionId;+/*** 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@@ -111,6 +113,16 @@ public class ProcurementDeal implements Serializable {@Column(name = "accepted_quote_id")private Long acceptedQuoteId;+ @Column(name = "enterprise_period_start")+ private LocalDateTime enterprisePeriodStart;++ @Column(name = "enterprise_period_end")+ private LocalDateTime enterprisePeriodEnd;++ /** Access may end before the service period when an accepted invoice remains unpaid. */+ @Column(name = "enterprise_access_until")+ private LocalDateTime enterpriseAccessUntil;+@CreationTimestamp@Column(name = "created_at", nullable = false, updatable = false)private LocalDateTime createdAt;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.javaindex 5d1234e9fc..073e84ccc7 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@@ -101,7 +101,10 @@ public class ProcurementPricingService {lines.add(new QuoteLineItem("seats",- "Unlimited users + SSO / SCIM / RBAC / audit",+ cfg.users() > 0+ ? String.format(+ "%,d agreed users + SSO / RBAC / audit", cfg.users())+ : "Users + SSO / RBAC / audit",QuoteLineItem.Kind.INCLUDED,0L));if (termDiscountMinor < 0) {diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementActivityRepository.java b/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementActivityRepository.javanew file mode 100644index 0000000000..45ae1c4900--- /dev/null+++ b/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementActivityRepository.java@@ -0,0 +1,8 @@+package stirling.software.saas.procurement.repository;++import org.springframework.data.jpa.repository.JpaRepository;++import stirling.software.saas.procurement.model.ProcurementActivity;++/** Persists staff actions in the existing commercial audit trail. */+public interface ProcurementActivityRepository extends JpaRepository<ProcurementActivity, Long> {}diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementDealRepository.java b/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementDealRepository.javaindex 14247ba1ba..3f128c2c86 100644--- a/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementDealRepository.java+++ b/app/saas/src/main/java/stirling/software/saas/procurement/repository/ProcurementDealRepository.java@@ -3,6 +3,11 @@ package stirling.software.saas.procurement.repository;import java.util.Optional;import org.springframework.data.jpa.repository.JpaRepository;+import org.springframework.data.jpa.repository.Lock;+import org.springframework.data.jpa.repository.Query;+import org.springframework.data.repository.query.Param;++import jakarta.persistence.LockModeType;import stirling.software.saas.procurement.model.ProcurementDeal;@@ -10,6 +15,11 @@ public interface ProcurementDealRepository extends JpaRepository<ProcurementDealOptional<ProcurementDeal> findByTeamId(Long teamId);+ /** Serializes trial changes and payment callbacks against the accepted agreement. */+ @Lock(LockModeType.PESSIMISTIC_WRITE)+ @Query("SELECT d FROM ProcurementDeal d WHERE d.teamId = :teamId")+ Optional<ProcurementDeal> findByTeamIdForUpdate(@Param("teamId") Long teamId);+boolean existsByTeamId(Long teamId);/** Reset: drop the team's deal (quotes + activity cascade via FK). */diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/service/EnterpriseEntitlementService.java b/app/saas/src/main/java/stirling/software/saas/procurement/service/EnterpriseEntitlementService.javanew file mode 100644index 0000000000..44c3b01db8--- /dev/null+++ b/app/saas/src/main/java/stirling/software/saas/procurement/service/EnterpriseEntitlementService.java@@ -0,0 +1,89 @@+package stirling.software.saas.procurement.service;++import java.time.LocalDateTime;+import java.time.ZoneOffset;+import java.util.Optional;++import org.springframework.context.annotation.Profile;+import org.springframework.stereotype.Service;+import org.springframework.transaction.annotation.Transactional;++import lombok.RequiredArgsConstructor;++import stirling.software.saas.procurement.model.ProcurementDeal;+import stirling.software.saas.procurement.model.ProcurementQuote;+import stirling.software.saas.procurement.repository.ProcurementDealRepository;+import stirling.software.saas.procurement.repository.ProcurementQuoteRepository;++/** Resolves time-bounded Enterprise access independently of the procurement journey stage. */+@Service+@Profile("saas")+@RequiredArgsConstructor+public class EnterpriseEntitlementService {+ private final ProcurementDealRepository deals;+ private final ProcurementQuoteRepository quotes;++ /** Commercial quantities describe the agreement; they never gate processing or admission. */+ public record Entitlement(+ String status,+ LocalDateTime periodStart,+ LocalDateTime periodEnd,+ LocalDateTime accessUntil,+ Integer agreedSeats,+ Long annualVolume) {}++ /**+ * Reads current access without caching so expiry and staff changes apply on the next request.+ */+ @Transactional(readOnly = true)+ public Optional<Entitlement> findActive(Long teamId) {+ if (teamId == null) return Optional.empty();+ return deals.findByTeamId(teamId)+ .flatMap(deal -> resolve(deal, LocalDateTime.now(ZoneOffset.UTC)));+ }++ /** Used by charging and feature gates; quantities in the quote do not restrict access. */+ public boolean isActive(Long teamId) {+ return findActive(teamId).isPresent();+ }++ Optional<Entitlement> resolve(ProcurementDeal deal, LocalDateTime now) {+ if (deal.getEnterprisePeriodStart() != null) {+ if (!contains(deal.getEnterprisePeriodStart(), deal.getEnterpriseAccessUntil(), now)) {+ return Optional.empty();+ }+ ProcurementQuote quote =+ deal.getAcceptedQuoteId() == null+ ? null+ : quotes.findById(deal.getAcceptedQuoteId())+ .filter(q -> deal.getDealId().equals(q.getDealId()))+ .orElse(null);+ if (quote == null || deal.getEnterprisePeriodEnd() == null) return Optional.empty();+ return Optional.of(+ new Entitlement(+ ProcurementDeal.STAGE_LIVE.equals(deal.getStage())+ ? "active"+ : "payment_pending",+ deal.getEnterprisePeriodStart(),+ deal.getEnterprisePeriodEnd(),+ deal.getEnterpriseAccessUntil(),+ quote.getSeats(),+ quote.getVolume()));+ }+ if (contains(deal.getTrialStartedAt(), deal.getTrialEndsAt(), now)) {+ return Optional.of(+ new Entitlement(+ "trial",+ deal.getTrialStartedAt(),+ deal.getTrialEndsAt(),+ deal.getTrialEndsAt(),+ null,+ null));+ }+ return Optional.empty();+ }++ private static boolean contains(LocalDateTime start, LocalDateTime end, LocalDateTime now) {+ return start != null && end != null && !now.isBefore(start) && now.isBefore(end);+ }+}diff --git a/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.java b/app/saas/src/main/java/stirling/software/saas/procurement/service/ProcurementService.javaindex 388b95eef3..93df3c8e7e 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@@ -2,6 +2,7 @@ package stirling.software.saas.procurement.service;import java.time.LocalDate;import java.time.LocalDateTime;+import java.time.ZoneOffset;import java.util.List;import java.util.Locale;import java.util.Optional;@@ -15,6 +16,7 @@ import lombok.extern.slf4j.Slf4j;import stirling.software.common.model.enumeration.TeamRole;import stirling.software.proprietary.model.TeamMembership;import stirling.software.proprietary.security.repository.TeamMembershipRepository;+import stirling.software.proprietary.security.repository.TeamRepository;import stirling.software.saas.procurement.config.ProcurementConfigurationProperties;import stirling.software.saas.procurement.legal.AgreementAssembler;import stirling.software.saas.procurement.legal.AgreementPdfRenderer;@@ -22,6 +24,7 @@ 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.ProcurementActivity;import stirling.software.saas.procurement.model.ProcurementAgreementSignature;import stirling.software.saas.procurement.model.ProcurementDeal;import stirling.software.saas.procurement.model.ProcurementQuote;@@ -29,6 +32,7 @@ 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.ProcurementActivityRepository;import stirling.software.saas.procurement.repository.ProcurementAgreementSignatureRepository;import stirling.software.saas.procurement.repository.ProcurementDealRepository;import stirling.software.saas.procurement.repository.ProcurementQuoteRepository;@@ -39,10 +43,10 @@ import tools.jackson.core.JacksonException;import tools.jackson.databind.ObjectMapper;/**- * Orchestrates a linked team's procurement journey: start a (mock-licensed) trial, build a- * server-priced quote, and accept it. Stripe checkout itself lives in a Supabase edge function the- * portal calls with the accepted quote; on payment the webhook seeds {@code billing_subscriptions}- * and this service issues the annual licence. All amounts are minor units (cents).+ * Orchestrates a linked team's procurement journey: start a trial, build a server-priced quote, and+ * accept it. Stripe checkout itself lives in a Supabase edge function the portal calls with the+ * accepted quote; on payment the webhook seeds {@code billing_subscriptions} and this service+ * issues the annual licence. All amounts are minor units (cents).*/@Slf4j@Service@@ -65,6 +69,8 @@ public class ProcurementService {// 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;+ private final ProcurementActivityRepository activities;+ private final TeamRepository teamRepo;public ProcurementService(ProcurementDealRepository dealRepo,@@ -76,7 +82,9 @@ public class ProcurementService {AgreementAssembler agreementAssembler,AgreementPdfRenderer agreementPdfRenderer,ProcurementAgreementSignatureRepository signatureRepo,- SaasTeamService teams) {+ SaasTeamService teams,+ ProcurementActivityRepository activities,+ TeamRepository teamRepo) {this.dealRepo = dealRepo;this.quoteRepo = quoteRepo;this.pricing = pricing;@@ -87,6 +95,8 @@ public class ProcurementService {this.agreementPdfRenderer = agreementPdfRenderer;this.signatureRepo = signatureRepo;this.teams = teams;+ this.activities = activities;+ this.teamRepo = teamRepo;}/**@@ -110,13 +120,7 @@ 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.- *- * <p>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.- */+ /** Only an unpurchased deal may enter evaluation; an existing trial is never restarted. */static boolean canStartTrial(String stage) {return stage == null|| ProcurementDeal.STAGE_EXPLORING.equals(stage)@@ -149,32 +153,13 @@ public class ProcurementService {});}- /**- * 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- * Keygen licence, and the deal row is the journey state. The buyer's chosen deployment target- * ({@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.- */+ /** Starts evaluation using the same dates for SaaS access and the self-hosted licence. */+ @Transactionalpublic 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.- *- * <p>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.- *- * <p>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.- */+ /** Starts evaluation once; repeated requests retain the original dates and licence. */@Transactionalpublic ProcurementDeal startTrial(Long teamId,@@ -184,13 +169,15 @@ public class ProcurementService {String contactName,String contactEmail,String inviteEmails) {+ teamRepo.lockById(teamId).orElseThrow(() -> new IllegalArgumentException("Team not found"));ProcurementDeal deal =- dealRepo.findByTeamId(teamId).orElseGet(() -> new ProcurementDeal(teamId));+ dealRepo.findByTeamIdForUpdate(teamId).orElseGet(() -> new ProcurementDeal(teamId));if (!canStartTrial(deal.getStage())) {throw new IllegalStateException("Trial cannot be started from stage " + deal.getStage());}- LocalDateTime now = LocalDateTime.now();+ if (deal.getTrialStartedAt() != null) return deal;+ LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);LocalDateTime ends = now.plusDays(config.getTrialDurationDays());deal.setStage(ProcurementDeal.STAGE_TRIAL);deal.setDeployment(normalizeDeployment(deployment));@@ -269,18 +256,20 @@ public class ProcurementService {@Transactionalpublic ProcurementDeal extendTrial(Long teamId) {ProcurementDeal deal =- dealRepo.findByTeamId(teamId)+ dealRepo.findByTeamIdForUpdate(teamId).orElseThrow(() -> new IllegalStateException("No deal for team " + teamId));- // Only extend while still in the trial. Past the trial (e.g. active), licenseRef points at- // the committed annual licence — extending would rewind its expiry.- if (!ProcurementDeal.STAGE_TRIAL.equals(deal.getStage())) {- throw new IllegalStateException("Trial extension only allowed during the trial stage");+ if (deal.getTrialStartedAt() == null+ || deal.getEnterprisePeriodStart() != null+ || deal.getSubscriptionId() != null) {+ throw new IllegalStateException("A purchased agreement cannot be extended as a trial");}if (deal.getTrialExtensionsUsed() >= config.getMaxTrialExtensions()) {throw new IllegalStateException("Trial extension cap reached");}LocalDateTime base =- deal.getTrialEndsAt() != null ? deal.getTrialEndsAt() : LocalDateTime.now();+ deal.getTrialEndsAt() != null+ ? deal.getTrialEndsAt()+ : LocalDateTime.now(ZoneOffset.UTC);LocalDateTime newEnd = base.plusDays(config.getTrialExtensionDays());deal.setTrialEndsAt(newEnd);deal.setTrialExtensionsUsed(deal.getTrialExtensionsUsed() + 1);@@ -290,13 +279,72 @@ public class ProcurementService {return dealRepo.save(deal);}+ /** Staff may extend evaluation without rewinding quotes, signatures or purchase progress. */+ @Transactional+ public ProcurementDeal grantTrial(+ Long teamId, LocalDateTime endsAt, String reason, String actor) {+ teamRepo.lockById(teamId).orElseThrow(() -> new IllegalArgumentException("Team not found"));+ if (endsAt == null+ || !endsAt.isAfter(LocalDateTime.now(ZoneOffset.UTC))+ || reason == null+ || reason.isBlank()) {+ throw new IllegalArgumentException("A future trial end and reason are required");+ }+ ProcurementDeal deal = dealRepo.findByTeamIdForUpdate(teamId).orElse(null);+ if (deal != null+ && (deal.getSubscriptionId() != null || deal.getEnterprisePeriodStart() != null)) {+ throw new IllegalStateException("A purchased agreement cannot be replaced by a trial");+ }+ if (leaderEmail(teamId) == null) throw new IllegalArgumentException("Team has no leader");+ if (deal == null) deal = new ProcurementDeal(teamId);+ LocalDateTime previous = deal.getTrialEndsAt();+ if (previous != null && endsAt.isBefore(previous)) {+ throw new IllegalArgumentException("An extension cannot shorten the trial");+ }+ if (deal.getTrialStartedAt() == null) {+ deal.setTrialStartedAt(LocalDateTime.now(ZoneOffset.UTC));+ if (deal.getStage() == null || ProcurementDeal.STAGE_EXPLORING.equals(deal.getStage()))+ deal.setStage(ProcurementDeal.STAGE_TRIAL);+ }+ if (deal.getLicenseRef() == null) {+ deal.setLicenseRef(licenses.issueTrialLicense(teamId, leaderEmail(teamId), endsAt));+ } else {+ licenses.extendLicense(deal.getLicenseRef(), endsAt);+ }+ deal.setTrialEndsAt(endsAt);+ deal = dealRepo.saveAndFlush(deal);+ activities.save(+ new ProcurementActivity(+ deal.getDealId(),+ "trial_granted",+ OBJECT_MAPPER.writeValueAsString(+ java.util.Map.of(+ "actor",+ actor,+ "reason",+ reason,+ "previousEnd",+ previous == null ? "" : previous.toString(),+ "endsAt",+ endsAt.toString()))));+ log.info(+ "[procurement] staff trial grant team={} actor={} previous={} ends={} reason={}",+ teamId,+ actor,+ previous,+ endsAt,+ reason.replaceAll("[\\r\\n]", " "));+ return dealRepo.save(deal);+ }+/** Price a quote config server-side and persist it as a draft against the team's deal. */@Transactionalpublic ProcurementQuote buildQuote(Long teamId, QuoteConfig cfg, QuoteDetails details) {ProcurementDeal deal =- dealRepo.findByTeamId(teamId).orElseGet(() -> new ProcurementDeal(teamId));- if (ProcurementDeal.STAGE_LIVE.equals(deal.getStage())) {- throw new IllegalStateException("Cannot rebuild a quote on a live deal");+ dealRepo.findByTeamIdForUpdate(teamId).orElseGet(() -> new ProcurementDeal(teamId));+ if (ProcurementDeal.STAGE_LIVE.equals(deal.getStage())+ || deal.getSubscriptionId() != null) {+ throw new IllegalStateException("Cannot replace an accepted agreement");}// (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.@@ -544,18 +592,13 @@ public class ProcurementService {}}- /**- * 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.- * Driven by the accept edge function once the subscription + invoice are created. Idempotent- * (upgrades the existing licence in place); deliberately does NOT change the stage — the deal- * stays in the payment step so the outstanding invoice remains visible until it settles.- */+ /** Grants access through the verified invoice due date while payment is pending. */@Transactional- public ProcurementDeal provisionLicense(Long teamId) {+ public ProcurementDeal provisionLicense(Long teamId, ContractPeriod period) {ProcurementDeal deal =- dealRepo.findByTeamId(teamId)+ dealRepo.findByTeamIdForUpdate(teamId).orElseThrow(() -> new IllegalStateException("No deal for team " + teamId));+ if (!applyPeriod(deal, period, false)) return deal;deal.setLicenseRef(issueOrUpgradeAnnual(deal));deal = dealRepo.save(deal);log.info("[procurement] licence provisioned team={} deal={}", teamId, deal.getDealId());@@ -563,28 +606,15 @@ public class ProcurementService {}/**- * 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.- *- * <p>Idempotent per invoice rather than per stage, which matters because {@code invoice.paid}- * carries two different meanings. Stripe redelivers events, so the <em>same</em> 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- * <em>different</em> 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.+ * Applies the paid invoice service period. Duplicate or older invoices cannot extend access.*/@Transactional- public ProcurementDeal markLive(Long teamId, String paidInvoiceId) {+ public ProcurementDeal markLive(Long teamId, String paidInvoiceId, ContractPeriod period) {ProcurementDeal deal =- dealRepo.findByTeamId(teamId)+ dealRepo.findByTeamIdForUpdate(teamId).orElseThrow(() -> new IllegalStateException("No deal for team " + teamId));- if (ProcurementDeal.STAGE_LIVE.equals(deal.getStage())+ if (deal.getEnterprisePeriodStart() != null+ && ProcurementDeal.STAGE_LIVE.equals(deal.getStage())&& (paidInvoiceId == null || paidInvoiceId.equals(deal.getLastPaidInvoiceId()))) {log.debug("[procurement] invoice.paid already applied team={} deal={} invoice={}",@@ -593,6 +623,7 @@ public class ProcurementService {paidInvoiceId);return deal;}+ if (!applyPeriod(deal, period, true)) return deal;boolean renewal = ProcurementDeal.STAGE_LIVE.equals(deal.getStage());deal.setLicenseRef(issueOrUpgradeAnnual(deal));if (paidInvoiceId != null) deal.setLastPaidInvoiceId(paidInvoiceId);@@ -608,11 +639,74 @@ public class ProcurementService {}/**- * Go live with no invoice reference — the demo control. See {@link #markLive(Long, String)}.+ * Go live with no invoice reference — the demo control. Requires an accepted quote and+ * subscription.*/@Transactionalpublic ProcurementDeal markLive(Long teamId) {- return markLive(teamId, null);+ ProcurementDeal deal =+ dealRepo.findByTeamIdForUpdate(teamId)+ .orElseThrow(() -> new IllegalStateException("No deal for team " + teamId));+ LocalDateTime start = LocalDateTime.now(ZoneOffset.UTC);+ return markLive(+ teamId,+ null,+ new ContractPeriod(+ deal.getSubscriptionId(), start, start.plusYears(1), start.plusYears(1)));+ }++ /** UTC timestamps verified against Stripe by the server-side procurement caller. */+ public record ContractPeriod(+ String subscriptionId,+ LocalDateTime periodStart,+ LocalDateTime periodEnd,+ LocalDateTime accessUntil) {}++ private boolean applyPeriod(ProcurementDeal deal, ContractPeriod period, boolean paid) {+ if (period == null+ || period.periodStart() == null+ || period.periodEnd() == null+ || period.accessUntil() == null+ || !period.periodEnd().isAfter(period.periodStart())+ || period.accessUntil().isAfter(period.periodEnd())+ || !period.accessUntil().isAfter(period.periodStart())) {+ throw new IllegalStateException("A verified service period is required");+ }+ if (deal.getSubscriptionId() == null+ || !deal.getSubscriptionId().equals(period.subscriptionId())+ || deal.getAcceptedQuoteId() == null+ || quoteRepo+ .findById(deal.getAcceptedQuoteId())+ .filter(q -> deal.getDealId().equals(q.getDealId()))+ .isEmpty()) {+ throw new IllegalStateException(+ "The accepted quote and subscription must match this deal");+ }+ if (deal.getEnterprisePeriodStart() != null+ && period.periodStart().isBefore(deal.getEnterprisePeriodStart())) return false;+ if (period.subscriptionId().equals(deal.getTerminatedSubscriptionId())+ && period.periodStart().equals(deal.getEnterprisePeriodStart())) return false;+ if (!paid && ProcurementDeal.STAGE_LIVE.equals(deal.getStage())) return false;+ deal.setEnterprisePeriodStart(period.periodStart());+ deal.setEnterprisePeriodEnd(period.periodEnd());+ deal.setEnterpriseAccessUntil(paid ? period.periodEnd() : period.accessUntil());+ deal.setTerminatedSubscriptionId(null);+ return true;+ }++ /** Immediate subscription termination cannot affect a replacement subscription for the team. */+ @Transactional+ public void endAccess(Long teamId, String subscriptionId) {+ ProcurementDeal deal = dealRepo.findByTeamIdForUpdate(teamId).orElse(null);+ if (deal == null+ || subscriptionId == null+ || !subscriptionId.equals(deal.getSubscriptionId())) return;+ LocalDateTime endedAt = LocalDateTime.now(ZoneOffset.UTC);+ if (deal.getEnterprisePeriodStart() == null) deal.setEnterprisePeriodStart(endedAt);+ deal.setEnterpriseAccessUntil(endedAt);+ deal.setTerminatedSubscriptionId(subscriptionId);+ if (deal.getLicenseRef() != null) licenses.suspendLicense(deal.getLicenseRef());+ dealRepo.save(deal);}/**@@ -649,7 +743,7 @@ public class ProcurementService {return licenses.issueAnnualLicense(deal.getTeamId(),leaderEmail(deal.getTeamId()),- LocalDateTime.now().plusYears(term),+ deal.getEnterpriseAccessUntil(),deal.getLicenseRef(),entitlements);}diff --git a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.javaindex f90b2e52e6..3be0f13d68 100644--- a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java+++ b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java@@ -18,6 +18,15 @@ public interface SaasTeamExtensionsRepository extends JpaRepository<SaasTeamExteCLOUD_SEATS+ " + (SELECT COALESCE(SUM(i.seat_count), 0) FROM stirling_pdf.linked_instance i WHERE i.team_id = e.team_id AND i.revoked_at IS NULL)";+ String ENTERPRISE_ACCESS =+ "EXISTS (SELECT 1 FROM stirling_pdf.procurement_deal d WHERE d.team_id = e.team_id"+ + " AND ((d.enterprise_period_start <= (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')"+ + " AND d.enterprise_access_until > (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')"+ + " AND d.accepted_quote_id IS NOT NULL)"+ + " OR (d.enterprise_period_start IS NULL"+ + " AND d.trial_started_at <= (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')"+ + " AND d.trial_ends_at > (CURRENT_TIMESTAMP AT TIME ZONE 'UTC'))))";+Optional<SaasTeamExtensions> findByTeamId(Long teamId);/**@@ -27,9 +36,11 @@ public interface SaasTeamExtensionsRepository extends JpaRepository<SaasTeamExte@Query(value ="UPDATE stirling_pdf.saas_team_extensions e SET seats_used = seats_used + 1 "- + "WHERE team_id = :teamId AND "+ + "WHERE team_id = :teamId AND ("+ FLEET_SEATS- + " < max_seats",+ + " < max_seats OR "+ + ENTERPRISE_ACCESS+ + ")",nativeQuery = true)int incrementSeatsUsed(@Param("teamId") Long teamId);@@ -45,7 +56,9 @@ public interface SaasTeamExtensionsRepository extends JpaRepository<SaasTeamExtevalue ="SELECT "+ FLEET_SEATS- + " < e.max_seats FROM stirling_pdf.saas_team_extensions e WHERE e.team_id=:teamId",+ + " < e.max_seats OR "+ + ENTERPRISE_ACCESS+ + " FROM stirling_pdf.saas_team_extensions e WHERE e.team_id=:teamId",nativeQuery = true)Boolean fleetHasAvailableSeats(@Param("teamId") Long teamId);diff --git a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.javaindex be729908f4..9338b824c8 100644--- a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java+++ b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java@@ -33,6 +33,7 @@ import org.springframework.security.core.context.SecurityContextHolder;import org.springframework.security.oauth2.core.OAuth2Error;import org.springframework.security.oauth2.core.OAuth2TokenValidator;import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;+import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;import org.springframework.security.oauth2.jwt.Jwt;import org.springframework.security.oauth2.jwt.JwtDecoder;import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;@@ -194,7 +195,11 @@ public class SupabaseSecurityConfig {}String jwks = issuer + "/.well-known/jwks.json";log.info("Configuring JWT decoder with JWKS: {}", jwks);- NimbusJwtDecoder decoder = NimbusJwtDecoder.withJwkSetUri(jwks).build();+ NimbusJwtDecoder decoder =+ NimbusJwtDecoder.withJwkSetUri(jwks)+ .jwsAlgorithm(SignatureAlgorithm.RS256)+ .jwsAlgorithm(SignatureAlgorithm.ES256)+ .build();// Defence-in-depth: signature verification already binds the token to this Supabase// project's JWKS, but enforcing iss/exp/aud explicitly catches tokens that smuggle// through (e.g. JWKS reuse across projects, clock-skew abuse, missing aud).diff --git a/app/saas/src/test/java/stirling/software/saas/billing/model/BillingSubscriptionSchemaTest.java b/app/saas/src/test/java/stirling/software/saas/billing/model/BillingSubscriptionSchemaTest.javanew file mode 100644index 0000000000..265965fa2b--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/billing/model/BillingSubscriptionSchemaTest.java@@ -0,0 +1,46 @@+package stirling.software.saas.billing.model;++import static org.assertj.core.api.Assertions.assertThat;++import java.util.UUID;++import org.junit.jupiter.api.Test;+import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.boot.SpringBootConfiguration;+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;+import org.springframework.boot.persistence.autoconfigure.EntityScan;+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;+import org.springframework.jdbc.core.JdbcTemplate;++import stirling.software.saas.billing.repository.BillingSubscriptionRepository;++@DataJpaTest(+ properties = {+ "spring.jpa.properties.hibernate.default_schema=stirling_pdf",+ "spring.jpa.properties.hibernate.hbm2ddl.schema_filter_provider=org.hibernate.tool.schema.internal.DefaultSchemaFilterProvider",+ "spring.jpa.show-sql=false"+ })+class BillingSubscriptionSchemaTest {+ @Autowired BillingSubscriptionRepository subscriptions;+ @Autowired JdbcTemplate jdbc;++ @Test+ void readsStripeMirrorFromPublicDespiteApplicationDefaultSchema() {+ UUID userId = UUID.randomUUID();+ jdbc.update(+ "INSERT INTO public.billing_subscriptions (id, user_id, status, created_at, updated_at) VALUES (?, ?, 'active', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)",+ "sub_preview",+ userId);++ assertThat(subscriptions.existsActivePaidSubscriptionForUser(userId)).isTrue();+ assertThat(subscriptions.findLatestActiveSubscription(userId))+ .get()+ .extracting(BillingSubscription::getId)+ .isEqualTo("sub_preview");+ }++ @SpringBootConfiguration+ @EntityScan(basePackageClasses = BillingSubscription.class)+ @EnableJpaRepositories(basePackageClasses = BillingSubscriptionRepository.class)+ static class Config {}+}diff --git a/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java b/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.javaindex d6ccdb3f7b..27be012d93 100644--- a/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java+++ b/app/saas/src/test/java/stirling/software/saas/controller/SaasTeamControllerTest.java@@ -80,6 +80,9 @@ class SaasTeamControllerTest {@Mock private UserService userService;@Mock private TeamSecurityExpressions teamSecurityExpressions;+ @Mock+ private stirling.software.saas.procurement.service.EnterpriseEntitlementService enterprise;+@org.mockito.Mock private stirling.software.proprietary.service.OrgOwnerService orgOwnerService;@InjectMocks private SaasTeamController controller;@@ -567,6 +570,24 @@ class SaasTeamControllerTest {@DisplayName("getMyTeams")class GetMyTeams {+ @Test+ void enterpriseRosterHasNoAdmissionCapAndKeepsActualUsage() {+ stubCurrentUser();+ Team team = team(1L, "Enterprise");+ currentUser.setTeam(team);+ when(membershipRepository.findByUserId(currentUser.getId()))+ .thenReturn(List.of(membership(team, currentUser, TeamRole.LEADER)));+ when(saasTeamExtensionService.getMaxSeats(team)).thenReturn(20);+ when(saasTeamExtensionService.getSeatsUsed(team)).thenReturn(27);+ when(enterprise.isActive(1L)).thenReturn(true);+ var response = controller.getMyTeams();+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);+ @SuppressWarnings("unchecked")+ var dtos = (List<SaasTeamController.TeamDetailsDTO>) response.getBody();+ assertThat(dtos.getFirst().getMaxSeats()).isNull();+ assertThat(dtos.getFirst().getSeatsUsed()).isEqualTo(27);+ }+@Test@DisplayName("no memberships -> personal team created, then memberships re-fetched and returned")diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.javaindex 13d240e51f..15499f9c11 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java@@ -96,7 +96,10 @@ class PaygWalletControllerTest {prepaidBundleService,new UserTeamResolver(memberRepo),teamExtensionsRepository,- fleetSeats);+ fleetSeats,+ org.mockito.Mockito.mock(+ stirling.software.saas.procurement.service+ .EnterpriseEntitlementService.class));}/**diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.javaindex 14fc62803a..250f5d48a0 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.java@@ -49,6 +49,7 @@ class WalletSnapshotResponseTest {/* billingMode= */ "prepaid",/* bundleRatePerCreditMinor= */ new BigDecimal("1"),null,+ null,null);}@@ -136,6 +137,7 @@ class WalletSnapshotResponseTest {"payg",null,null,+ null,null);assertThat(free.billableLimit()).isNull();diff --git a/app/saas/src/test/java/stirling/software/saas/payg/charge/JobChargeServiceTest.java b/app/saas/src/test/java/stirling/software/saas/payg/charge/JobChargeServiceTest.javaindex 97d88842d2..a7930c8632 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/charge/JobChargeServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/charge/JobChargeServiceTest.java@@ -78,6 +78,7 @@ class JobChargeServiceTest {private PrepaidBundleService prepaidBundleService;private TeamBillingService teamBillingService;private JobChargeService service;+ private stirling.software.saas.procurement.service.EnterpriseEntitlementService enterprise;private static final LocalDateTime PERIOD_START =YearMonth.now(ZoneOffset.UTC).atDay(1).atStartOfDay();@@ -103,6 +104,10 @@ class JobChargeServiceTest {teamBillingService = Mockito.mock(TeamBillingService.class);when(teamBillingService.forTeam(Mockito.anyLong())).thenReturn(billingContext(GRANT));when(teamBillingService.resolveGrant(Mockito.anyLong(), any())).thenReturn(GRANT);+ enterprise =+ Mockito.mock(+ stirling.software.saas.procurement.service.EnterpriseEntitlementService+ .class);service =new JobChargeService(jobService,@@ -114,7 +119,45 @@ class JobChargeServiceTest {meterReporter,ledgerRepo,prepaidBundleService,- teamBillingService);+ teamBillingService,+ enterprise);+ }++ @Test+ void enterpriseTracksDocumentsWithoutConsumingCreditsOrMeteringAfterExpiry(@TempDir Path tmp)+ throws IOException {+ PricingPolicy policy = stubPolicy(1, Map.of(JobSource.WEB, 10));+ when(policyService.getEffectivePolicy(100L)).thenReturn(policy);+ when(enterprise.isActive(100L)).thenReturn(true);+ ProcessingJob job = openJob(UUID.randomUUID());+ job.setDocCount(2);+ when(jobService.joinOrOpen(any(JobContext.class), anyList()))+ .thenReturn(new JoinOrOpenResult(job, JoinOrOpenResult.Disposition.OPENED));+ when(classifier.classify(any(MultipartFile.class), any(Path.class), eq(policy)))+ .thenReturn(new DocumentMetrics(50, 1024L, "application/pdf", 400));+ service.openProcess(+ new ChargeContext(+ 42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL, BillingCategory.API),+ List.of(jobInput(tmp, "included.pdf", "application/pdf")));+ ArgumentCaptor<PaygShadowCharge> shadow = ArgumentCaptor.forClass(PaygShadowCharge.class);+ verify(shadowRepo).save(shadow.capture());+ assertThat(shadow.getValue().isEnterpriseCovered()).isTrue();+ assertThat(shadow.getValue().getPaygUnits()).isEqualTo(400);+ ArgumentCaptor<WalletLedgerEntry> ledger = ArgumentCaptor.forClass(WalletLedgerEntry.class);+ verify(ledgerRepo).save(ledger.capture());+ assertThat(ledger.getValue().getAmountUnits()).isZero();+ assertThat(ledger.getValue().getDocCount()).isEqualTo(2);+ Mockito.verifyNoInteractions(teamExtRepo, prepaidBundleService);+ when(enterprise.isActive(100L)).thenReturn(false);+ when(shadowRepo.findFirstByJobIdOrderByIdAsc(job.getId()))+ .thenReturn(Optional.of(shadow.getValue()));+ service.meterJobUsage(job.getId());+ Mockito.verifyNoInteractions(meterReporter);+ service.markFirstStepFailed(job.getId(), "failed");+ verify(ledgerRepo, times(2)).save(ledger.capture());+ assertThat(ledger.getValue().getEntryType()).isEqualTo(LedgerEntryType.REFUND);+ assertThat(ledger.getValue().getAmountUnits()).isZero();+ Mockito.verifyNoInteractions(teamExtRepo, prepaidBundleService);}private static TeamBillingContext billingContext(long grant) {diff --git a/app/saas/src/test/java/stirling/software/saas/payg/charge/SupportingFileBillingTest.java b/app/saas/src/test/java/stirling/software/saas/payg/charge/SupportingFileBillingTest.javaindex dc2e0f6f2f..c74e0ca895 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/charge/SupportingFileBillingTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/charge/SupportingFileBillingTest.java@@ -117,7 +117,10 @@ class SupportingFileBillingTest {mock(PaygMeterReportingService.class),ledger,mock(PrepaidBundleService.class),- mock(TeamBillingService.class));+ mock(TeamBillingService.class),+ mock(+ stirling.software.saas.procurement.service+ .EnterpriseEntitlementService.class));}@Testdiff --git a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementServiceTest.java b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementServiceTest.javaindex 8b2dc90c62..e4698b1f9d 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/entitlement/EntitlementServiceTest.java@@ -49,6 +49,7 @@ class EntitlementServiceTest {private PaygShadowChargeRepository ledgerRepo;private PrepaidBundleService prepaidBundleService;private EntitlementService service;+ private stirling.software.saas.procurement.service.EnterpriseEntitlementService enterprise;@Testvoid zeroMeteredCapDoesNotBlockIncludedTeamCredits() {@@ -76,9 +77,28 @@ class EntitlementServiceTest {walletPolicyRepo = Mockito.mock(WalletPolicyRepository.class);ledgerRepo = Mockito.mock(PaygShadowChargeRepository.class);prepaidBundleService = Mockito.mock(PrepaidBundleService.class);+ enterprise =+ Mockito.mock(+ stirling.software.saas.procurement.service.EnterpriseEntitlementService+ .class);service =new EntitlementService(- billingService, walletPolicyRepo, ledgerRepo, prepaidBundleService);+ billingService,+ walletPolicyRepo,+ ledgerRepo,+ prepaidBundleService,+ enterprise);+ }++ @Test+ void enterpriseOverridesAnExhaustedGrantOnlyWhileItIsActive() {+ stubBilling(42L, freeContext(500L, 0L));+ assertThat(service.getSnapshot(42L).state()).isEqualTo(EntitlementState.DEGRADED);+ when(enterprise.isActive(42L)).thenReturn(true);+ assertThat(service.getSnapshot(42L).state()).isEqualTo(EntitlementState.FULL);+ assertThat(service.getSnapshot(42L).periodCapUnits()).isNull();+ when(enterprise.isActive(42L)).thenReturn(false);+ assertThat(service.getSnapshot(42L).state()).isEqualTo(EntitlementState.DEGRADED);}@Testdiff --git a/app/saas/src/test/java/stirling/software/saas/payg/repository/EnterpriseUsageDbTest.java b/app/saas/src/test/java/stirling/software/saas/payg/repository/EnterpriseUsageDbTest.javanew file mode 100644index 0000000000..766a5a4c7f--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/payg/repository/EnterpriseUsageDbTest.java@@ -0,0 +1,75 @@+package stirling.software.saas.payg.repository;++import static org.assertj.core.api.Assertions.assertThat;++import java.time.LocalDateTime;++import org.junit.jupiter.api.Test;+import org.springframework.beans.factory.annotation.Autowired;+import org.springframework.boot.SpringBootConfiguration;+import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;+import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;+import org.springframework.boot.persistence.autoconfigure.EntityScan;+import org.springframework.context.annotation.ComponentScan;+import org.springframework.context.annotation.FilterType;+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;++import jakarta.persistence.EntityManager;+import jakarta.persistence.PersistenceContext;++import stirling.software.saas.payg.model.BillingCategory;+import stirling.software.saas.payg.model.LedgerBucket;+import stirling.software.saas.payg.model.LedgerEntryType;+import stirling.software.saas.payg.model.ReferenceType;+import stirling.software.saas.payg.wallet.WalletLedgerEntry;++@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)+@DataJpaTest(+ properties = {+ "spring.datasource.url=jdbc:h2:mem:enterpriseUsage;MODE=PostgreSQL;DB_CLOSE_DELAY=-1",+ "spring.jpa.hibernate.ddl-auto=create-drop"+ })+class EnterpriseUsageDbTest {+ @Autowired private WalletLedgerRepository ledger;+ @PersistenceContext private EntityManager em;++ @Test+ void agreementCountsIncludedDocumentsAndExcludesRefundsOtherTeamsAndOtherPeriods() {+ LocalDateTime start = LocalDateTime.of(2026, 1, 1, 0, 0);+ entry(7L, "ok", LedgerEntryType.DEBIT, 12, start);+ entry(7L, "failed", LedgerEntryType.DEBIT, 5, start);+ entry(7L, "failed", LedgerEntryType.REFUND, 0, start.plusDays(1));+ entry(8L, "other-team", LedgerEntryType.DEBIT, 100, start);+ entry(7L, "previous", LedgerEntryType.DEBIT, 100, start.minusSeconds(1));+ entry(7L, "next", LedgerEntryType.DEBIT, 100, start.plusYears(1));+ em.flush();+ assertThat(ledger.sumEnterprisePdfs(7L, start, start.plusYears(1))).isEqualTo(12);+ }++ private void entry(Long teamId, String job, LedgerEntryType type, int docs, LocalDateTime at) {+ var entry = new WalletLedgerEntry();+ entry.setTeamId(teamId);+ entry.setReferenceId(job);+ entry.setReferenceType(ReferenceType.JOB);+ entry.setEntryType(type);+ entry.setBucket(LedgerBucket.CYCLE);+ entry.setAmountUnits(0);+ entry.setDocCount(docs);+ entry.setBillingCategory(BillingCategory.API);+ ledger.saveAndFlush(entry);+ em.createQuery("UPDATE WalletLedgerEntry e SET e.occurredAt=:at WHERE e.id=:id")+ .setParameter("at", at)+ .setParameter("id", entry.getId())+ .executeUpdate();+ }++ @SpringBootConfiguration+ @EntityScan(basePackageClasses = WalletLedgerEntry.class)+ @EnableJpaRepositories(+ basePackageClasses = WalletLedgerRepository.class,+ includeFilters =+ @ComponentScan.Filter(+ type = FilterType.ASSIGNABLE_TYPE,+ classes = WalletLedgerRepository.class))+ static class TestApp {}+}diff --git a/app/saas/src/test/java/stirling/software/saas/procurement/service/EnterpriseEntitlementServiceTest.java b/app/saas/src/test/java/stirling/software/saas/procurement/service/EnterpriseEntitlementServiceTest.javanew file mode 100644index 0000000000..e0da176af5--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/procurement/service/EnterpriseEntitlementServiceTest.java@@ -0,0 +1,67 @@+package stirling.software.saas.procurement.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++import java.time.LocalDateTime;+import java.util.Optional;++import org.junit.jupiter.api.Test;++import stirling.software.saas.procurement.model.ProcurementDeal;+import stirling.software.saas.procurement.model.ProcurementQuote;+import stirling.software.saas.procurement.repository.ProcurementDealRepository;+import stirling.software.saas.procurement.repository.ProcurementQuoteRepository;++class EnterpriseEntitlementServiceTest {+ private final ProcurementDealRepository deals = mock(ProcurementDealRepository.class);+ private final ProcurementQuoteRepository quotes = mock(ProcurementQuoteRepository.class);+ private final EnterpriseEntitlementService service =+ new EnterpriseEntitlementService(deals, quotes);+ private final LocalDateTime now = LocalDateTime.of(2026, 10, 12, 12, 0);++ private ProcurementDeal trial() {+ ProcurementDeal deal = new ProcurementDeal(7L);+ deal.setDealId(3L);+ deal.setTrialStartedAt(now.minusDays(7));+ deal.setTrialEndsAt(now.plusDays(7));+ deal.setSeats(100);+ return deal;+ }++ @Test+ void trialSurvivesQuoteAndAgreementAndExpiresAtExactBoundary() {+ ProcurementDeal deal = trial();+ for (String stage : new String[] {"trial", "quote", "security"}) {+ deal.setStage(stage);+ assertThat(service.resolve(deal, now))+ .get()+ .extracting(EnterpriseEntitlementService.Entitlement::status)+ .isEqualTo("trial");+ }+ assertThat(service.resolve(deal, deal.getTrialEndsAt())).isEmpty();+ assertThat(service.resolve(deal, deal.getTrialStartedAt().minusSeconds(1))).isEmpty();+ }++ @Test+ void paidAccessUsesAcceptedQuoteAndDoesNotFallbackToTrialWhenItEnds() {+ ProcurementDeal deal = trial();+ deal.setStage("active");+ deal.setAcceptedQuoteId(9L);+ deal.setEnterprisePeriodStart(now.minusDays(1));+ deal.setEnterprisePeriodEnd(now.plusYears(1));+ deal.setEnterpriseAccessUntil(now.plusDays(1));+ ProcurementQuote quote = new ProcurementQuote();+ quote.setDealId(3L);+ quote.setSeats(20);+ quote.setVolume(50000);+ when(quotes.findById(9L)).thenReturn(Optional.of(quote));+ var result = service.resolve(deal, now).orElseThrow();+ assertThat(result.agreedSeats()).isEqualTo(20);+ assertThat(result.annualVolume()).isEqualTo(50000);+ assertThat(service.resolve(deal, now.plusDays(1))).isEmpty();+ quote.setDealId(99L);+ assertThat(service.resolve(deal, now)).isEmpty();+ }+}diff --git a/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementLifecycleTest.java b/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementLifecycleTest.javanew file mode 100644index 0000000000..c099764a6c--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/procurement/service/ProcurementLifecycleTest.java@@ -0,0 +1,317 @@+package stirling.software.saas.procurement.service;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.Mockito.clearInvocations;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;+import static org.mockito.Mockito.when;++import java.time.LocalDateTime;+import java.time.ZoneOffset;+import java.util.List;+import java.util.Optional;++import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import stirling.software.common.model.enumeration.TeamRole;+import stirling.software.proprietary.model.Team;+import stirling.software.proprietary.model.TeamMembership;+import stirling.software.proprietary.security.model.User;+import stirling.software.proprietary.security.repository.TeamMembershipRepository;+import stirling.software.proprietary.security.repository.TeamRepository;+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.license.EnterpriseLicenseService;+import stirling.software.saas.procurement.model.ProcurementDeal;+import stirling.software.saas.procurement.model.ProcurementQuote;+import stirling.software.saas.procurement.pricing.ProcurementPricingService;+import stirling.software.saas.procurement.repository.ProcurementActivityRepository;+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;++class ProcurementLifecycleTest {+ private final ProcurementDealRepository deals = mock(ProcurementDealRepository.class);+ private final ProcurementQuoteRepository quotes = mock(ProcurementQuoteRepository.class);+ private final EnterpriseLicenseService licenses = mock(EnterpriseLicenseService.class);+ private final ProcurementActivityRepository audit = mock(ProcurementActivityRepository.class);+ private final TeamMembershipRepository members = mock(TeamMembershipRepository.class);+ private final TeamRepository teams = mock(TeamRepository.class);+ private final ProcurementService service =+ new ProcurementService(+ deals,+ quotes,+ mock(ProcurementPricingService.class),+ licenses,+ new ProcurementConfigurationProperties(),+ members,+ mock(AgreementAssembler.class),+ mock(AgreementPdfRenderer.class),+ mock(ProcurementAgreementSignatureRepository.class),+ mock(SaasTeamService.class),+ audit,+ teams);+ private final ProcurementDeal deal = new ProcurementDeal(7L);+ private final LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);++ @BeforeEach+ void setup() {+ deal.setDealId(3L);+ when(teams.lockById(7L)).thenReturn(Optional.of(new Team()));+ when(deals.findByTeamIdForUpdate(7L)).thenReturn(Optional.of(deal));+ when(deals.save(any())).thenAnswer(call -> call.getArgument(0));+ when(deals.saveAndFlush(any())).thenAnswer(call -> call.getArgument(0));+ }++ @Test+ void retryingAnExpiredTrialCannotRestartIt() {+ deal.setStage("trial");+ deal.setTrialStartedAt(now.minusDays(20));+ deal.setTrialEndsAt(now.minusDays(6));+ service.startTrial(7L, "cloud", 20, null, null, null, null);+ assertThat(deal.getTrialEndsAt()).isEqualTo(now.minusDays(6));+ verifyNoInteractions(licenses);+ }++ @Test+ void staffExtensionKeepsQuoteProgressAndIsAudited() {+ var user = new User();+ user.setEmail("[email protected]");+ var member = new TeamMembership();+ member.setUser(user);+ when(members.findByTeamIdAndRole(7L, TeamRole.LEADER)).thenReturn(List.of(member));+ deal.setStage("security");+ deal.setTrialStartedAt(now.minusDays(10));+ deal.setTrialEndsAt(now.plusDays(4));+ deal.setLicenseRef("trial-key");+ service.grantTrial(7L, now.plusDays(20), "Evaluation extension", "operator");+ assertThat(deal.getStage()).isEqualTo("security");+ verify(licenses).extendLicense("trial-key", now.plusDays(20));+ verify(audit).save(any());+ }++ @Test+ void staffExtensionRepairsAMissingTrialLicenseWithoutRestartingTheTrial() {+ var user = new User();+ user.setEmail("[email protected]");+ var member = new TeamMembership();+ member.setUser(user);+ when(members.findByTeamIdAndRole(7L, TeamRole.LEADER)).thenReturn(List.of(member));+ deal.setStage("security");+ deal.setTrialStartedAt(now.minusDays(10));+ deal.setTrialEndsAt(now.plusDays(4));+ deal.setTrialExtensionsUsed(2);+ when(licenses.issueTrialLicense(7L, "[email protected]", now.plusDays(20)))+ .thenReturn("replacement-trial-key");++ service.grantTrial(7L, now.plusDays(20), "Evaluation extension", "operator");++ assertThat(deal.getLicenseRef()).isEqualTo("replacement-trial-key");+ assertThat(deal.getTrialStartedAt()).isEqualTo(now.minusDays(10));+ assertThat(deal.getTrialEndsAt()).isEqualTo(now.plusDays(20));+ assertThat(deal.getTrialExtensionsUsed()).isEqualTo(2);+ assertThat(deal.getStage()).isEqualTo("security");+ verify(licenses, never()).extendLicense(any(), any());+ verify(audit).save(any());+ }++ @Test+ void demoActivationWithoutADealRaisesAConflict() {+ when(deals.findByTeamIdForUpdate(7L)).thenReturn(Optional.empty());++ assertThatThrownBy(() -> service.markLive(7L))+ .isInstanceOf(IllegalStateException.class)+ .hasMessage("No deal for team 7");+ verifyNoInteractions(licenses);+ }++ @Test+ void demoActivationUsesTheLockedSubscription() {+ accepted();++ service.markLive(7L);++ assertThat(deal.getStage()).isEqualTo("active");+ assertThat(deal.getEnterprisePeriodEnd())+ .isEqualTo(deal.getEnterprisePeriodStart().plusYears(1));+ verify(deals, never()).findByTeamId(any());+ }++ @Test+ void invoicePaymentUsesPurchasedDatesAndOlderCallbacksCannotRewindThem() {+ accepted();+ var period =+ new ProcurementService.ContractPeriod(+ "sub_1", now, now.plusYears(1), now.plusDays(30));+ service.provisionLicense(7L, period);+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusDays(30));+ service.markLive(7L, "in_1", period);+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(1));+ service.provisionLicense(7L, period);+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(1));+ var renewal =+ new ProcurementService.ContractPeriod(+ "sub_1", now.plusYears(1), now.plusYears(2), now.plusYears(2));+ service.markLive(7L, "in_2", renewal);+ service.markLive(7L, "in_1", period);+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(2));+ assertThat(deal.getLastPaidInvoiceId()).isEqualTo("in_2");+ }++ @Test+ void anExistingPaidAgreementCanReconcileItsMissingDates() {+ accepted();+ deal.setStage("active");+ deal.setLastPaidInvoiceId("in_existing");+ service.markLive(+ 7L,+ "in_existing",+ new ProcurementService.ContractPeriod(+ "sub_1", now, now.plusYears(1), now.plusYears(1)));+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(1));+ }++ @Test+ void callbacksMustMatchTheAcceptedSubscriptionAndQuote() {+ accepted();+ var period =+ new ProcurementService.ContractPeriod(+ "other", now, now.plusYears(1), now.plusYears(1));+ assertThatThrownBy(() -> service.markLive(7L, "in_other", period))+ .isInstanceOf(IllegalStateException.class);+ assertThatThrownBy(() -> service.grantTrial(7L, now.plusDays(30), "Extension", "operator"))+ .isInstanceOf(IllegalStateException.class);+ verifyNoInteractions(licenses);+ }++ @Test+ void cancellationOnlyEndsTheMatchingSubscription() {+ accepted();+ deal.setEnterpriseAccessUntil(now.plusYears(1));+ deal.setLicenseRef("paid-key");+ service.endAccess(7L, "old_subscription");+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(1));+ assertThat(deal.getTerminatedSubscriptionId()).isNull();+ service.endAccess(7L, "sub_1");+ assertThat(deal.getEnterpriseAccessUntil()).isBefore(now.plusSeconds(10));+ assertThat(deal.getTerminatedSubscriptionId()).isEqualTo("sub_1");+ verify(licenses).suspendLicense("paid-key");+ }++ @Test+ void anotherPaidInvoiceCannotReactivateTheCancelledPeriod() {+ accepted();+ var period =+ new ProcurementService.ContractPeriod(+ "sub_1", now, now.plusYears(1), now.plusDays(30));+ service.markLive(7L, "in_original", period);+ deal.setLicenseRef("paid-key");+ service.endAccess(7L, "sub_1");+ LocalDateTime endedAt = deal.getEnterpriseAccessUntil();+ clearInvocations(licenses);++ service.markLive(7L, "in_replay", period);++ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(endedAt);+ assertThat(deal.getLastPaidInvoiceId()).isEqualTo("in_original");+ assertThat(deal.getTerminatedSubscriptionId()).isEqualTo("sub_1");+ verifyNoInteractions(licenses);+ }++ @Test+ void cancellationBeforePaymentBlocksBothProvisionAndPaidReplays() {+ accepted();+ var period =+ new ProcurementService.ContractPeriod(+ "sub_1", now, now.plusYears(1), now.plusDays(30));+ service.provisionLicense(7L, period);+ service.endAccess(7L, "sub_1");+ LocalDateTime endedAt = deal.getEnterpriseAccessUntil();+ clearInvocations(licenses);++ service.provisionLicense(7L, period);+ service.markLive(7L, "in_late", period);++ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(endedAt);+ assertThat(deal.getStage()).isEqualTo("procurement");+ assertThat(deal.getLastPaidInvoiceId()).isNull();+ verifyNoInteractions(licenses);+ }++ @Test+ void paymentAfterAnUnpaidCutoffRestoresThePurchasedPeriod() {+ accepted();+ var period =+ new ProcurementService.ContractPeriod(+ "sub_1", now.minusDays(40), now.plusMonths(11), now.minusDays(10));+ service.provisionLicense(7L, period);+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.minusDays(10));++ service.markLive(7L, "in_recovered", period);++ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusMonths(11));+ assertThat(deal.getStage()).isEqualTo("active");+ assertThat(deal.getTerminatedSubscriptionId()).isNull();+ }++ @Test+ void aLaterPurchasedPeriodClearsTheTerminationMarker() {+ accepted();+ var period =+ new ProcurementService.ContractPeriod(+ "sub_1", now, now.plusYears(1), now.plusDays(30));+ service.markLive(7L, "in_original", period);+ service.endAccess(7L, "sub_1");+ var renewal =+ new ProcurementService.ContractPeriod(+ "sub_1", now.plusYears(1), now.plusYears(2), now.plusYears(2));++ service.markLive(7L, "in_renewal", renewal);++ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(2));+ assertThat(deal.getTerminatedSubscriptionId()).isNull();+ service.markLive(7L, "in_old_replay", period);+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(2));+ assertThat(deal.getLastPaidInvoiceId()).isEqualTo("in_renewal");+ }++ @Test+ void anAcceptedReplacementSubscriptionCanUseTheSamePeriod() {+ accepted();+ var period =+ new ProcurementService.ContractPeriod(+ "sub_1", now, now.plusYears(1), now.plusDays(30));+ service.markLive(7L, "in_original", period);+ service.endAccess(7L, "sub_1");+ deal.setSubscriptionId("sub_replacement");++ service.markLive(+ 7L,+ "in_replacement",+ new ProcurementService.ContractPeriod(+ "sub_replacement", now, now.plusYears(1), now.plusYears(1)));++ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(1));+ assertThat(deal.getTerminatedSubscriptionId()).isNull();+ service.endAccess(7L, "sub_1");+ assertThat(deal.getEnterpriseAccessUntil()).isEqualTo(now.plusYears(1));+ }++ private void accepted() {+ deal.setStage("procurement");+ deal.setSubscriptionId("sub_1");+ deal.setAcceptedQuoteId(9L);+ var quote = new ProcurementQuote();+ quote.setDealId(3L);+ quote.setSeats(20);+ quote.setVolume(50000);+ when(quotes.findById(9L)).thenReturn(Optional.of(quote));+ }+}diff --git a/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java b/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.javaindex 27c775bf74..bde4480e54 100644--- a/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java+++ b/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java@@ -18,6 +18,8 @@ class FleetSeatQueriesTest {"CREATE TABLE stirling_pdf.saas_team_extensions (team_id BIGINT PRIMARY KEY, seats_used INT, max_seats INT)");sql.execute("CREATE TABLE stirling_pdf.linked_instance (team_id BIGINT, seat_count INT, revoked_at TIMESTAMP)");+ sql.execute(+ "CREATE TABLE stirling_pdf.procurement_deal (team_id BIGINT, accepted_quote_id BIGINT, enterprise_period_start TIMESTAMP, enterprise_access_until TIMESTAMP, trial_started_at TIMESTAMP, trial_ends_at TIMESTAMP)");sql.execute("INSERT INTO stirling_pdf.saas_team_extensions VALUES (1, 1, 5)");assertThat(total(db)).isEqualTo(1);sql.execute(@@ -34,6 +36,23 @@ class FleetSeatQueriesTest {sql.execute("UPDATE stirling_pdf.saas_team_extensions SET seats_used=0");sql.execute("INSERT INTO stirling_pdf.linked_instance VALUES (1, NULL, NULL)");assertThat(total(db)).isZero();+ sql.execute("UPDATE stirling_pdf.saas_team_extensions SET seats_used=10");+ sql.execute(+ "INSERT INTO stirling_pdf.procurement_deal VALUES (1, NULL, NULL, NULL, CURRENT_TIMESTAMP - INTERVAL '1' DAY, CURRENT_TIMESTAMP + INTERVAL '1' DAY)");+ assertThat(available(db)).isTrue();+ assertThat(claim(db)).isEqualTo(1);+ sql.execute(+ "UPDATE stirling_pdf.procurement_deal SET trial_ends_at=CURRENT_TIMESTAMP - INTERVAL '1' SECOND");+ assertThat(available(db)).isFalse();+ assertThat(claim(db)).isZero();+ sql.execute(+ "UPDATE stirling_pdf.procurement_deal SET accepted_quote_id=42, enterprise_period_start=CURRENT_TIMESTAMP - INTERVAL '1' DAY, enterprise_access_until=CURRENT_TIMESTAMP + INTERVAL '1' DAY");+ assertThat(available(db)).isTrue();+ assertThat(claim(db)).isEqualTo(1);+ sql.execute(+ "UPDATE stirling_pdf.procurement_deal SET enterprise_access_until=CURRENT_TIMESTAMP - INTERVAL '1' SECOND, trial_ends_at=CURRENT_TIMESTAMP + INTERVAL '10' DAY");+ assertThat(available(db)).isFalse();+ assertThat(claim(db)).isZero();}}}diff --git a/app/saas/src/test/java/stirling/software/saas/security/SupabaseJwtSignatureTest.java b/app/saas/src/test/java/stirling/software/saas/security/SupabaseJwtSignatureTest.javanew file mode 100644index 0000000000..6b135e147a--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/security/SupabaseJwtSignatureTest.java@@ -0,0 +1,161 @@+package stirling.software.saas.security;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;+import static org.mockito.Mockito.mock;++import java.net.InetSocketAddress;+import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.util.Date;+import java.util.List;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.springframework.mock.env.MockEnvironment;+import org.springframework.security.oauth2.jwt.JwtDecoder;+import org.springframework.security.oauth2.jwt.JwtException;+import org.springframework.test.util.ReflectionTestUtils;++import com.nimbusds.jose.JOSEException;+import com.nimbusds.jose.JWSAlgorithm;+import com.nimbusds.jose.JWSHeader;+import com.nimbusds.jose.crypto.ECDSASigner;+import com.nimbusds.jose.crypto.MACSigner;+import com.nimbusds.jose.crypto.RSASSASigner;+import com.nimbusds.jose.jwk.Curve;+import com.nimbusds.jose.jwk.ECKey;+import com.nimbusds.jose.jwk.JWKSet;+import com.nimbusds.jose.jwk.RSAKey;+import com.nimbusds.jose.jwk.gen.ECKeyGenerator;+import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;+import com.nimbusds.jwt.JWTClaimsSet;+import com.nimbusds.jwt.SignedJWT;+import com.sun.net.httpserver.HttpServer;++import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.security.service.ApiKeyAuthenticationService;+import stirling.software.proprietary.security.service.TeamService;+import stirling.software.proprietary.security.service.UserService;+import stirling.software.saas.service.SaasTeamService;+import stirling.software.saas.service.SupabaseUserService;++class SupabaseJwtSignatureTest {+ private HttpServer server;+ private String issuer;+ private ECKey ec;+ private RSAKey rsa;+ private JwtDecoder decoder;++ @BeforeEach+ void setup() throws Exception {+ ec = new ECKeyGenerator(Curve.P_256).keyID("preview-ec").generate();+ rsa = new RSAKeyGenerator(2048).keyID("existing-rsa").generate();+ byte[] jwks =+ new JWKSet(List.of(ec.toPublicJWK(), rsa.toPublicJWK()))+ .toString()+ .getBytes(StandardCharsets.UTF_8);+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ server.createContext(+ "/auth/v1/.well-known/jwks.json",+ exchange -> {+ try (exchange) {+ exchange.getResponseHeaders().set("Content-Type", "application/json");+ exchange.sendResponseHeaders(200, jwks.length);+ exchange.getResponseBody().write(jwks);+ }+ });+ server.start();+ issuer = "http://127.0.0.1:" + server.getAddress().getPort() + "/auth/v1";+ SupabaseSecurityConfig config =+ new SupabaseSecurityConfig(+ mock(UserService.class),+ mock(TeamService.class),+ mock(SupabaseUserService.class),+ mock(SaasTeamService.class),+ new ApplicationProperties(),+ mock(ApiKeyAuthenticationService.class),+ new MockEnvironment());+ ReflectionTestUtils.setField(config, "issuer", issuer);+ ReflectionTestUtils.setField(config, "expectedAud", "authenticated");+ ReflectionTestUtils.setField(config, "clockSkewSeconds", 0L);+ decoder = config.jwtDecoder();+ }++ @AfterEach+ void stopServer() {+ if (server != null) server.stop(0);+ }++ @ParameterizedTest+ @ValueSource(strings = {"ES256", "RS256"})+ void acceptsSupportedProjectKeys(String algorithm) throws Exception {+ String token = signed(algorithm, claims(issuer, "authenticated", 300));+ assertThat(decoder.decode(token).getSubject()).isEqualTo("preview-user");+ }++ @Test+ void rejectsAnotherIssuerEvenWhenSignedByKnownKey() throws Exception {+ String token =+ signed("ES256", claims("https://other.supabase.co/auth/v1", "authenticated", 300));+ assertThatThrownBy(() -> decoder.decode(token)).isInstanceOf(JwtException.class);+ }++ @Test+ void rejectsWrongAudience() throws Exception {+ String token = signed("ES256", claims(issuer, "other", 300));+ assertThatThrownBy(() -> decoder.decode(token)).isInstanceOf(JwtException.class);+ }++ @Test+ void rejectsExpiredToken() throws Exception {+ String token = signed("ES256", claims(issuer, "authenticated", -300));+ assertThatThrownBy(() -> decoder.decode(token)).isInstanceOf(JwtException.class);+ }++ @Test+ void rejectsSignatureFromAnotherProject() throws Exception {+ SignedJWT token =+ new SignedJWT(+ new JWSHeader.Builder(JWSAlgorithm.ES256).keyID(ec.getKeyID()).build(),+ claims(issuer, "authenticated", 300));+ token.sign(new ECDSASigner(new ECKeyGenerator(Curve.P_256).generate()));+ assertThatThrownBy(() -> decoder.decode(token.serialize()))+ .isInstanceOf(JwtException.class);+ }++ @Test+ void rejectsSymmetricTokens() throws Exception {+ SignedJWT token =+ new SignedJWT(+ new JWSHeader(JWSAlgorithm.HS256), claims(issuer, "authenticated", 300));+ token.sign(new MACSigner(new byte[32]));+ assertThatThrownBy(() -> decoder.decode(token.serialize()))+ .isInstanceOf(JwtException.class);+ }++ private JWTClaimsSet claims(String tokenIssuer, String audience, long secondsToExpiry) {+ return new JWTClaimsSet.Builder()+ .subject("preview-user")+ .issuer(tokenIssuer)+ .audience(audience)+ .issueTime(Date.from(Instant.now().minusSeconds(600)))+ .expirationTime(Date.from(Instant.now().plusSeconds(secondsToExpiry)))+ .build();+ }++ private String signed(String algorithm, JWTClaimsSet claims) throws JOSEException {+ boolean elliptic = algorithm.equals("ES256");+ SignedJWT token =+ new SignedJWT(+ new JWSHeader.Builder(JWSAlgorithm.parse(algorithm))+ .keyID(elliptic ? ec.getKeyID() : rsa.getKeyID())+ .build(),+ claims);+ token.sign(elliptic ? new ECDSASigner(ec) : new RSASSASigner(rsa));+ return token.serialize();+ }+}diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 7004716ec4..b32dbf52d5 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -8175,9 +8175,22 @@ pdfs = "PDFs processed"users = "Users"[portal.billing.enterprise]+active = "Agreement active through {{date}}"cta = "Get an enterprise quote"+included = "Included in Enterprise"+payment_pending = "Payment pending · access through {{date}}"+pdfsAgreed = "{{used}} / {{agreed}} PDFs"+pdfsOver_one = "{{count}} PDF over agreed volume"+pdfsOver_other = "{{count}} PDFs over agreed volume"+pdfsUsed_one = "{{count}} PDF processed"+pdfsUsed_other = "{{count}} PDFs processed"+period = "Agreement period: {{start}} – {{end}}"sub = "Air-gapped deployment, SCIM, data residency, uptime SLAs, and an agreement to match."title = "Running Stirling in a regulated environment?"+trial = "{{days}}-day trial · ends {{date}}"+usersAgreed = "{{used}} / {{agreed}} agreed users"+usersOver_one = "{{count}} user over agreed quantity"+usersOver_other = "{{count}} users over agreed quantity"[portal.billing.freePlan]checkoutErrorTitle = "Couldn't start checkout"diff --git a/frontend/editor/src/cloud/components/onboarding/useSaasOnboardingState.ts b/frontend/editor/src/cloud/components/onboarding/useSaasOnboardingState.tsindex 22f41ec12d..6406fbe77a 100644--- a/frontend/editor/src/cloud/components/onboarding/useSaasOnboardingState.ts+++ b/frontend/editor/src/cloud/components/onboarding/useSaasOnboardingState.ts@@ -86,7 +86,8 @@ export function useSaasOnboardingState({// Usage meter only makes sense for free-tier wallets with allowance left;// the team slide is for leaders (anonymous guests are never leaders).- const showUsageSlide = wallet?.status === "free" && wallet.freeRemaining > 0;+ const showUsageSlide =+ wallet?.status === "free" && !wallet.enterprise && wallet.freeRemaining > 0;const showTeamSlide = isTeamLeader;const flowSlideIds = useMemo(diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/Plan.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/Plan.tsxindex 0cbe8b1019..ec932fe17a 100644--- a/frontend/editor/src/cloud/components/shared/config/configSections/Plan.tsx+++ b/frontend/editor/src/cloud/components/shared/config/configSections/Plan.tsx@@ -1,4 +1,5 @@/** Account-owned legacy billing can coexist with the current team's wallet. */+import { BillingScreen } from "@app/billing/BillingScreen";import React, { useCallback } from "react";import { Center, Group, Loader, Stack } from "@mantine/core";import { Banner, Button } from "@app/ui";@@ -66,6 +67,8 @@ const Plan: React.FC = () => {);}+ if (wallet.enterprise) return <BillingScreen wallet={wallet} />;+if (wallet.status === "subscribed") {return wallet.role === "leader" ? (<PaygLeaderdiff --git a/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx b/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsxindex d5ae7995f2..2c9e8bca5b 100644--- a/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx+++ b/frontend/editor/src/cloud/contexts/SaaSTeamContext.tsx@@ -28,7 +28,7 @@ interface Team {memberCount: number;seatCount: number;seatsUsed: number;- maxSeats: number;+ maxSeats: number | null;isLeader: boolean;}diff --git a/frontend/editor/src/cloud/hooks/useFreeCreditsSummary.ts b/frontend/editor/src/cloud/hooks/useFreeCreditsSummary.tsindex 04319ffa4b..2f586b7a65 100644--- a/frontend/editor/src/cloud/hooks/useFreeCreditsSummary.ts+++ b/frontend/editor/src/cloud/hooks/useFreeCreditsSummary.ts@@ -36,7 +36,9 @@ export function useFreeCreditsSummary(): NavFooterCredits | null {);const live = wallet- ? toCredits(wallet.status, wallet.freeRemaining, wallet.freeAllowance)+ ? wallet.enterprise+ ? null+ : toCredits(wallet.status, wallet.freeRemaining, wallet.freeAllowance): undefined;// useWallet reuses the snapshot reference when nothing changed, so keying ondiff --git a/frontend/editor/src/portal-saas/contexts/usePlanTier.test.tsx b/frontend/editor/src/portal-saas/contexts/usePlanTier.test.tsxindex d2a9666bff..e90e5ad453 100644--- a/frontend/editor/src/portal-saas/contexts/usePlanTier.test.tsx+++ b/frontend/editor/src/portal-saas/contexts/usePlanTier.test.tsx@@ -1,5 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, waitFor } from "@testing-library/react";+import { act, render, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { qk } from "@app/portal/queries/keys";const fetchWallet = vi.fn();vi.mock("@portal/api/billing", () => ({@@ -13,6 +15,20 @@ function Probe() {return <span data-testid="tier">{usePlanTier()}</span>;}+function renderTier() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ });+ return {+ client,+ ...render(+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>,+ ),+ };+}+describe("usePlanTier (SaaS) — tier from wallet", () => {beforeEach(() => {fetchWallet.mockReset();@@ -20,16 +36,34 @@ describe("usePlanTier (SaaS) — tier from wallet", () => {it("subscribed wallet → pro", async () => {fetchWallet.mockResolvedValue({ status: "subscribed" });- const { getByTestId } = render(<Probe />);+ const { getByTestId } = renderTier();await waitFor(() => expect(getByTestId("tier").textContent).toBe("pro"));});it("free wallet → free (also the loading default)", async () => {fetchWallet.mockResolvedValue({ status: "free" });- const { getByTestId } = render(<Probe />);+ const { getByTestId } = renderTier();// Free before the fetch resolves and after — it never flips to pro.expect(getByTestId("tier").textContent).toBe("free");await waitFor(() => expect(fetchWallet).toHaveBeenCalledTimes(1));expect(getByTestId("tier").textContent).toBe("free");});++ it.each(["trial", "active", "payment_pending"])(+ "%s Enterprise overrides the underlying plan and refreshes on expiry",+ async (status) => {+ fetchWallet.mockResolvedValue({ status: "free", enterprise: { status } });+ const { getByTestId, client } = renderTier();+ await waitFor(() =>+ expect(getByTestId("tier").textContent).toBe("enterprise"),+ );+ act(() =>+ client.setQueryData(qk.wallet(true), {+ status: "free",+ enterprise: null,+ }),+ );+ await waitFor(() => expect(getByTestId("tier").textContent).toBe("free"));+ },+ );});diff --git a/frontend/editor/src/portal-saas/contexts/usePlanTier.ts b/frontend/editor/src/portal-saas/contexts/usePlanTier.tsindex 6b877c3640..03a0dbf566 100644--- a/frontend/editor/src/portal-saas/contexts/usePlanTier.ts+++ b/frontend/editor/src/portal-saas/contexts/usePlanTier.ts@@ -1,14 +1,14 @@-import { useAsync } from "@portal/hooks/useAsync";-import { fetchWallet } from "@portal/api/billing";-import type { Tier } from "@portal/contexts/TierContext";+import { useQuery } from "@tanstack/react-query";+import { walletQuery } from "@app/portal/queries/wallet";+import type { Tier } from "@app/portal/contexts/TierContext";/*** The plan tier the portal runs on, SaaS flavor: the signed-in account IS the* SaaS account, so the tier comes straight from the wallet — no link concept.- * `subscribed` → the metered Processor tier; anything else (including while the- * wallet is still loading) → free. Enterprise stays a mocks-only tier.+ * Shares the billing query so trial, payment and expiry changes refresh every surface together.*/export function usePlanTier(): Tier {- const { data: wallet } = useAsync(() => fetchWallet(), []);+ const { data: wallet } = useQuery(walletQuery(true));+ if (wallet?.enterprise) return "enterprise";return wallet?.status === "subscribed" ? "pro" : "free";}diff --git a/frontend/editor/src/portal/components/procurement/useProcurement.ts b/frontend/editor/src/portal/components/procurement/useProcurement.tsindex 5c1b215404..3958f72f9f 100644--- a/frontend/editor/src/portal/components/procurement/useProcurement.ts+++ b/frontend/editor/src/portal/components/procurement/useProcurement.ts@@ -154,6 +154,11 @@ export function useProcurement(): ProcurementController {try {await fn();queryClient.setQueryData(snapshotKey, await fetchSnapshot());+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: qk.wallet(true) }),+ queryClient.invalidateQueries({ queryKey: qk.teamMy() }),+ queryClient.invalidateQueries({ queryKey: ["portal", "users"] }),+ ]);if (opts?.closeOnSuccess) setOpen(false);return true;} catch (e) {diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsxindex 60348c37af..1485b6548a 100644--- a/frontend/editor/src/portal/views/Usage.tsx+++ b/frontend/editor/src/portal/views/Usage.tsx@@ -221,7 +221,10 @@ export function Usage({return t("portal.usage.error.walletUnavailable","Wallet unavailable: {{status}} {{statusText}}",- { status: walletError.status, statusText: walletError.statusText },+ {+ status: walletError.status,+ statusText: walletError.statusText,+ },);return walletError instanceof Error? walletError.message@@ -366,7 +369,8 @@ export function Usage({return false;}, [queryClient, hasLocalInstance, refresh]);- const enterpriseProcessor = serverPlan?.licenseType === "ENTERPRISE";+ const enterpriseProcessor =+ Boolean(wallet?.enterprise) || serverPlan?.licenseType === "ENTERPRISE";const paying = Boolean(wallet?.processor?.active || wallet?.team?.held);const ownsLegacySubscription = legacyBilling.subscriptions.length > 0;const legacyTeamSubscription = legacyBilling.subscriptions.find(@@ -502,7 +506,9 @@ export function Usage({pdfsProcessed={fleetStats?.pdfsProcessed ?? null}licenseSection={renderLicenseSection?.(refreshAfterLicense)}onAddCapacity={- checkout && wallet?.role === "leader" ? addCapacity : undefined+ !enterpriseProcessor && checkout && wallet?.role === "leader"+ ? addCapacity+ : undefined}onActivateProcessor={!enterpriseProcessor &&diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsxindex c860f40488..a00d553489 100644--- a/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx+++ b/frontend/editor/src/proprietary/billing/BillingScreen.stories.tsx@@ -22,6 +22,41 @@ const meta: Meta<typeof BillingScreen> = {export default meta;type Story = StoryObj<typeof BillingScreen>;+export const EnterpriseTrial: Story = {+ args: {+ wallet: {+ ...freeWallet,+ enterprise: {+ status: "trial",+ periodStart: "2026-10-12T00:00:00Z",+ periodEnd: "2026-10-26T00:00:00Z",+ accessUntil: "2026-10-26T00:00:00Z",+ agreedSeats: null,+ annualVolume: null,+ pdfsUsed: 840,+ },+ },+ },+};++export const EnterpriseOverAgreement: Story = {+ args: {+ wallet: {+ ...freeWallet,+ team: { ...freeWallet.team, usersInUse: 27 },+ enterprise: {+ status: "active",+ periodStart: "2026-10-12T00:00:00Z",+ periodEnd: "2027-10-12T00:00:00Z",+ accessUntil: "2027-10-12T00:00:00Z",+ agreedSeats: 20,+ annualVolume: 100000,+ pdfsUsed: 112000,+ },+ },+ },+};+export const SelfHostedLicense: Story = {args: {wallet: freeWallet,diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.tsxindex 3176a24213..92b53f4ed2 100644--- a/frontend/editor/src/proprietary/billing/BillingScreen.tsx+++ b/frontend/editor/src/proprietary/billing/BillingScreen.tsx@@ -6,7 +6,7 @@ import {ComparePlansModal,type ComparePlan,} from "@app/billing/ComparePlansModal";-import { formatMinor } from "@app/billing/format";+import { formatMinor, formatPeriodDate } from "@app/billing/format";import { KvRow } from "@app/billing/KvRow";import { TeamPlanRow } from "@app/billing/TeamPlanRow";import { ProcessorPlanRow } from "@app/billing/ProcessorPlanRow";@@ -131,7 +131,8 @@ export function BillingScreen({const { t } = useTranslation();const [comparing, setComparing] = useState(false);- const enterpriseProcessor = serverPlan?.licenseType === "ENTERPRISE";+ const enterpriseProcessor =+ Boolean(wallet?.enterprise) || serverPlan?.licenseType === "ENTERPRISE";const paying = Boolean(wallet?.processor?.active) && !enterpriseProcessor;const teamHeld = Boolean(wallet?.team?.held);const processedCount =@@ -140,6 +141,21 @@ export function BillingScreen({: pdfsProcessed;const identity = useMemo(() => {+ if (wallet?.enterprise) {+ const agreement = wallet.enterprise;+ return {+ name: t("portal.billing.serverPlan.enterprise", "Enterprise"),+ sub: t(`portal.billing.enterprise.${agreement.status}`, {+ date: formatPeriodDate(agreement.accessUntil, { year: true }),+ days: Math.ceil(+ (Date.parse(agreement.periodEnd) -+ Date.parse(agreement.periodStart)) /+ 86_400_000,+ ),+ }),+ chips: [],+ };+ }if (serverPlan)return {name:@@ -239,15 +255,17 @@ export function BillingScreen({* The column the matrix marks as the caller's own. A Server licence sits in the Team column:* it is the same hundred-user deal the cloud sells, bought locally instead.*/- const currentPlan: ComparePlan | null = serverPlan- ? serverPlan.licenseType === "ENTERPRISE"- ? "enterprise"- : "team"- : !wallet- ? null- : paying || teamHeld- ? "team"- : "free";+ const currentPlan: ComparePlan | null = wallet?.enterprise+ ? "enterprise"+ : serverPlan+ ? serverPlan.licenseType === "ENTERPRISE"+ ? "enterprise"+ : "team"+ : !wallet+ ? null+ : paying || teamHeld+ ? "team"+ : "free";/*** {@code freeAllowance} is whatever grant the WALLET carries, so it describes the Team columndiff --git a/frontend/editor/src/proprietary/billing/EnterprisePlan.test.tsx b/frontend/editor/src/proprietary/billing/EnterprisePlan.test.tsxnew file mode 100644index 0000000000..92322f734a--- /dev/null+++ b/frontend/editor/src/proprietary/billing/EnterprisePlan.test.tsx@@ -0,0 +1,88 @@+import { expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { TeamPlanRow } from "@app/billing/TeamPlanRow";+import { ProcessorPlanRow } from "@app/billing/ProcessorPlanRow";+import { BillingScreen } from "@app/billing/BillingScreen";+import { freeWallet } from "@app/billing/walletFixtures";+import type { Wallet } from "@app/billing/types";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (+ key: string,+ fallback?: string | Record<string, unknown>,+ vars?: Record<string, unknown>,+ ) => {+ const copy: Record<string, string> = {+ "portal.billing.enterprise.usersAgreed":+ "{{used}} / {{agreed}} agreed users",+ "portal.billing.enterprise.usersOver":+ "{{count}} users over agreed quantity",+ "portal.billing.enterprise.pdfsAgreed": "{{used}} / {{agreed}} PDFs",+ "portal.billing.enterprise.pdfsOver":+ "{{count}} PDFs over agreed volume",+ "portal.billing.enterprise.trial": "{{days}}-day trial · ends {{date}}",+ "portal.billing.enterprise.included": "Included in Enterprise",+ };+ const values = typeof fallback === "object" ? fallback : vars;+ return (+ copy[key] ?? (typeof fallback === "string" ? fallback : key)+ ).replace(/\{\{(\w+)\}\}/g, (_, k: string) => String(values?.[k] ?? ""));+ },+ }),+}));++const wallet: Wallet = {+ ...freeWallet,+ team: { ...freeWallet.team, usersInUse: 27 },+ enterprise: {+ status: "active",+ periodStart: "2026-10-12T00:00:00Z",+ periodEnd: "2027-10-12T00:00:00Z",+ accessUntil: "2027-10-12T00:00:00Z",+ agreedSeats: 20,+ annualVolume: 1000,+ pdfsUsed: 1250,+ },+};++it("shows actual users and PDFs over the agreement without selling more capacity", () => {+ render(+ <MantineProvider>+ <TeamPlanRow wallet={wallet} onAddCapacity={vi.fn()} />+ <ProcessorPlanRow+ wallet={wallet}+ onActivate={vi.fn()}+ onGovern={vi.fn()}+ />+ </MantineProvider>,+ );+ expect(screen.getByText("27 / 20 agreed users")).toBeInTheDocument();+ expect(screen.getByText("7 users over agreed quantity")).toBeInTheDocument();+ expect(screen.getByText("1,250 / 1,000 PDFs")).toBeInTheDocument();+ expect(screen.getByText("250 PDFs over agreed volume")).toBeInTheDocument();+ expect(screen.queryByRole("button")).not.toBeInTheDocument();+});++it("identifies the trial and its end date even when the underlying wallet is free", () => {+ render(+ <MantineProvider>+ <BillingScreen+ wallet={{+ ...wallet,+ enterprise: {+ ...wallet.enterprise!,+ status: "trial",+ accessUntil: "2026-10-26T00:00:00Z",+ periodEnd: "2026-10-26T00:00:00Z",+ annualVolume: null,+ },+ }}+ />+ </MantineProvider>,+ );+ expect(screen.getByText("Enterprise")).toBeInTheDocument();+ expect(screen.getByText(/14-day trial.*ends.*26/)).toBeInTheDocument();+ expect(screen.queryByText("Activate Processor")).not.toBeInTheDocument();+});diff --git a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsxindex e786b32daf..46db5f8c82 100644--- a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx@@ -94,6 +94,37 @@ export function ProcessorPlanRow({}) {const { t } = useTranslation();const name = t("portal.billing.processor.rowName", "Processor");+ if (wallet?.enterprise) {+ const { annualVolume, pdfsUsed, periodStart, periodEnd } =+ wallet.enterprise;+ const over =+ annualVolume != null ? Math.max(0, pdfsUsed - annualVolume) : 0;+ return (+ <MeterRow+ name={name}+ mid={+ over > 0+ ? t("portal.billing.enterprise.pdfsOver", { count: over })+ : t("portal.billing.enterprise.included")+ }+ fact={+ annualVolume != null && annualVolume > 0+ ? t("portal.billing.enterprise.pdfsAgreed", {+ used: pdfsUsed.toLocaleString(),+ agreed: annualVolume.toLocaleString(),+ })+ : t("portal.billing.enterprise.pdfsUsed", { count: pdfsUsed })+ }+ midTitle={t("portal.billing.enterprise.period", {+ start: formatPeriodDate(periodStart, { year: true }),+ end: formatPeriodDate(periodEnd, { year: true }),+ })}+ tone={over > 0 ? "warn" : "paid"}+ showTrack={annualVolume != null && annualVolume > 0}+ pct={annualVolume ? (pdfsUsed / annualVolume) * 100 : 0}+ />+ );+ }if (included)return (<MeterRowdiff --git a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsxindex d0d51a38b9..d51b0e34cf 100644--- a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx+++ b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx@@ -40,6 +40,37 @@ export function TeamPlanRow({legacyAllowance?: LegacyTeamAllowance;}) {const { t } = useTranslation();+ if (wallet?.enterprise) {+ const agreed = wallet.enterprise.agreedSeats;+ const used = wallet.team.fleet+ ? fleetUsersInUse(wallet.team, deviceId, occupiedSeats)+ : (occupiedSeats ?? wallet.team.usersInUse);+ const over =+ agreed != null && agreed > 0 && used != null+ ? Math.max(0, used - agreed)+ : 0;+ return (+ <MeterRow+ name={t("portal.billing.team.rowName", "Users")}+ mid={+ over > 0+ ? t("portal.billing.enterprise.usersOver", { count: over })+ : t("portal.billing.enterprise.included")+ }+ fact={+ agreed != null && agreed > 0+ ? t("portal.billing.enterprise.usersAgreed", {+ used: used ?? "—",+ agreed,+ })+ : t("portal.billing.team.factNoLimit", { users: used ?? "—" })+ }+ tone={over > 0 ? "warn" : "paid"}+ showTrack={agreed != null && agreed > 0 && used != null}+ pct={agreed && used != null ? (used / agreed) * 100 : 0}+ />+ );+ }if (serverPlan) {const unlimited = serverPlan.licenseType === "SERVER";const users = serverPlan.usersInUse;diff --git a/frontend/editor/src/proprietary/billing/types.ts b/frontend/editor/src/proprietary/billing/types.tsindex 44e2c16b5f..af686e0c69 100644--- a/frontend/editor/src/proprietary/billing/types.ts+++ b/frontend/editor/src/proprietary/billing/types.ts@@ -8,6 +8,17 @@export type WalletStatus = "free" | "subscribed";export type WalletRole = "leader" | "member";+/** Current agreement quantities and actual PDF inputs for its service period. */+export interface EnterpriseHolding {+ status: "trial" | "payment_pending" | "active";+ periodStart: string;+ periodEnd: string;+ accessUntil: string;+ agreedSeats: number | null;+ annualVolume: number | null;+ pdfsUsed: number;+}+/** One team member's billing-relevant row (name/email + their period spend). */export interface WalletMember {userId: string;@@ -66,6 +77,7 @@ export interface ProcessorHolding {}export interface Wallet {+ enterprise?: EnterpriseHolding | null;/** Caller's primary team_id; null on the synthetic empty snapshot for team-less callers. */teamId: number | null;/**diff --git a/frontend/editor/src/saas/portal/usersBackend.ts b/frontend/editor/src/saas/portal/usersBackend.tsindex ccc2d6e844..eefc6b9422 100644--- a/frontend/editor/src/saas/portal/usersBackend.ts+++ b/frontend/editor/src/saas/portal/usersBackend.ts@@ -32,7 +32,7 @@ interface TeamDetailsDTO {memberCount: number;seatCount: number;seatsUsed: number;- maxSeats: number;+ maxSeats: number | null;isLeader: boolean;current?: boolean;currentUserId?: number;@@ -69,7 +69,7 @@ const FREE_USER_ALLOWANCE = 5;* `SaasTeamExtensions.licensedUsers()`: a team on the free allowance has no limit to show, and the* unlimited sentinel is never a number.*/-function normalizeSeatLimit(max: number | undefined): number | null {+function normalizeSeatLimit(max: number | null | undefined): number | null {if (!max || max <= FREE_USER_ALLOWANCE || max >= 2147483647) return null;return max;}