Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

PAYG prepaid usage bundles (#7032)

ConnorYoh3813ca360ea0
diff --git a/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java b/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java
index 53a5f34c15..cd991cc44e 100644
--- a/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java
+++ b/app/saas/src/main/java/stirling/software/saas/config/SaasJpaConfig.java
@@ -19,6 +19,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
"stirling.software.saas.billing.repository",
"stirling.software.saas.ai.repository",
"stirling.software.saas.payg.repository",
+ "stirling.software.saas.payg.bundle",
"stirling.software.saas.procurement.repository"
})
@EntityScan({
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.java
index 18da81ae2b..2ab19ad4cb 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
@@ -41,6 +41,7 @@ import stirling.software.saas.payg.api.WalletSnapshotResponse.CategoryBreakdown;
import stirling.software.saas.payg.api.WalletSnapshotResponse.MemberRow;
import stirling.software.saas.payg.billing.TeamBillingContext;
import stirling.software.saas.payg.billing.TeamBillingService;
+import stirling.software.saas.payg.bundle.PrepaidBundleService;
import stirling.software.saas.payg.entitlement.EntitlementService;
import stirling.software.saas.payg.entitlement.EntitlementSnapshot;
import stirling.software.saas.payg.model.BillingCategory;
@@ -86,6 +87,8 @@ public class PaygWalletController {
static final String STATUS_SUBSCRIBED = "subscribed";
static final String ROLE_LEADER = "leader";
static final String ROLE_MEMBER = "member";
+ static final String BILLING_MODE_PREPAID = "prepaid";
+ static final String BILLING_MODE_PAYG = "payg";
/**
* Placeholder ceiling for the team-less empty snapshot only (authenticated caller without a
@@ -104,6 +107,7 @@ public class PaygWalletController {
private final WalletLedgerRepository ledgerRepo;
private final PaygShadowChargeRepository shadowRepo;
private final UserRepository userRepository;
+ private final PrepaidBundleService prepaidBundleService;
public PaygWalletController(
EntitlementService entitlementService,
@@ -113,7 +117,8 @@ public class PaygWalletController {
WalletPolicyRepository policyRepo,
WalletLedgerRepository ledgerRepo,
PaygShadowChargeRepository shadowRepo,
- UserRepository userRepository) {
+ UserRepository userRepository,
+ PrepaidBundleService prepaidBundleService) {
this.entitlementService = Objects.requireNonNull(entitlementService, "entitlementService");
this.billingService = Objects.requireNonNull(billingService, "billingService");
this.memberRepo = Objects.requireNonNull(memberRepo, "memberRepo");
@@ -122,6 +127,8 @@ public class PaygWalletController {
this.ledgerRepo = Objects.requireNonNull(ledgerRepo, "ledgerRepo");
this.shadowRepo = Objects.requireNonNull(shadowRepo, "shadowRepo");
this.userRepository = Objects.requireNonNull(userRepository, "userRepository");
+ this.prepaidBundleService =
+ Objects.requireNonNull(prepaidBundleService, "prepaidBundleService");
}
// ---------------------------------------------------------------------------------------
@@ -187,6 +194,18 @@ public class PaygWalletController {
? buildMemberRows(teamId, snap.periodStart(), snap.periodEnd())
: List.of();
+ // Prepaid bundles, aggregated across the team's in-term pools. Drawn ahead of the meter and
+ // kept out of the spend cap, so they're a separate dimension from the metered spend above.
+ PrepaidBundleService.PrepaidSummary prepaid = prepaidBundleService.summarize(teamId);
+ long prepaidRemaining = prepaid == null ? 0L : prepaid.unitsRemaining();
+ long prepaidTotal = prepaid == null ? 0L : prepaid.unitsTotal();
+ String prepaidExpiresAt =
+ prepaid == null || prepaid.expiresAt() == null
+ ? null
+ : ISO_DATE.format(prepaid.expiresAt().toLocalDate());
+ // Prepaid while pools still have units to draw; once exhausted the meter is live again.
+ String billingMode = prepaidRemaining > 0 ? BILLING_MODE_PREPAID : BILLING_MODE_PAYG;
+
WalletSnapshotResponse body =
new WalletSnapshotResponse(
teamId,
@@ -211,7 +230,11 @@ public class PaygWalletController {
breakdowns.docs(),
analytics.docsProcessed(),
analytics.uniquePdfs(),
- analytics.sizeMultiplierPdfs());
+ analytics.sizeMultiplierPdfs(),
+ prepaidRemaining,
+ prepaidTotal,
+ prepaidExpiresAt,
+ billingMode);
return ResponseEntity.ok(body);
}
@@ -485,6 +508,10 @@ public class PaygWalletController {
new CategoryBreakdown(0, 0, 0),
0,
0,
- 0);
+ 0,
+ 0L,
+ 0L,
+ null,
+ BILLING_MODE_PAYG);
}
}
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.java
index 8147bd030c..3d381ef165 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
@@ -79,7 +79,20 @@ public record WalletSnapshotResponse(
CategoryBreakdown categoryDocs,
int docsProcessedThisPeriod,
int uniquePdfsThisPeriod,
- int sizeMultiplierPdfsThisPeriod) {
+ int sizeMultiplierPdfsThisPeriod,
+ long prepaidUnitsRemaining,
+ long prepaidUnitsTotal,
+ String prepaidExpiresAt,
+ String billingMode) {
+
+ // Prepaid usage bundles, aggregated across the team's in-term pools (drawn ahead of the meter,
+ // outside the spend cap):
+ // prepaidUnitsRemaining — Σ units left across active pools (0 when exhausted / none)
+ // prepaidUnitsTotal — Σ capacity of in-term pools (the "X of Y used" denominator; 0 = no
+ // bundle this term, so the FE hides the prepaid card)
+ // prepaidExpiresAt — soonest term end (ISO date) for the countdown; null when no bundle
+ // billingMode — "prepaid" while prepaid units remain, else "payg" (the meter is
+ // live)
// The count dimension, kept distinct from units (which now scale with file size):
// categoryDocs — per-category INPUT-file counts (parallel to
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java
new file mode 100644
index 0000000000..e2dff403a7
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundle.java
@@ -0,0 +1,105 @@
+package stirling.software.saas.payg.bundle;
+
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+import org.hibernate.annotations.CreationTimestamp;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Index;
+import jakarta.persistence.Table;
+
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+
+/**
+ * A prepaid, expiring pool of PDF-process units bought up-front at a discount ("12 months for the
+ * price of 10"). Consumed after the team's free grant and before the meter (free -> prepaid ->
+ * metered); draws are booked to the {@code BOUGHT} ledger bucket, so a bundle never counts toward
+ * the spend cap or the Stripe meter.
+ *
+ * <p>Carries only capacity + term + the Stripe link. The one-time amount and currency live on the
+ * Stripe Checkout Session / PaymentIntent referenced by {@link #stripeRef}; how many units a PDF
+ * costs comes from the team's pricing policy at charge time, not from the bundle. Status is
+ * derived, never stored (see {@link #isDrawable}).
+ *
+ * <p>A team may hold several pools at once (top-ups); they are drawn FIFO by soonest {@link
+ * #expiresAt}. Unused units forfeit at expiry (no roll-over).
+ */
+@Entity
+@Table(
+ name = "payg_prepaid_bundle",
+ // Declared here for ddl-auto (fresh schemas) and to document intent. The authoritative creator
+ // in production is the Supabase CLI migration 20260720000000_payg_prepaid_bundle, which builds
+ // the partial forms (WHERE units_remaining > 0 / WHERE stripe_ref IS NOT NULL). Flyway was
+ // retired for SaaS (#7100), so there is no migration twin — names match the CLI migration.
+ indexes = {
+ // Hot-path FIFO draw lookup — findDrawableForUpdate runs a locked read on every billable
+ // charge past the free grant; without it that degrades to a locked scan as the table grows.
+ @Index(
+ name = "idx_payg_prepaid_bundle_team_expiry",
+ columnList = "team_id, expires_at"),
+ // One pool per Stripe payment — the idempotency guard so a redelivered invoice.paid can't
+ // credit the same purchase twice.
+ @Index(
+ name = "uq_payg_prepaid_bundle_stripe_ref",
+ columnList = "stripe_ref",
+ unique = true),
+ })
+@NoArgsConstructor
+@Getter
+@Setter
+public class PrepaidBundle implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "bundle_id")
+ private Long id;
+
+ @Column(name = "team_id", nullable = false)
+ private Long teamId;
+
+ /** Capacity granted at purchase — the denominator of the "X of Y used" meter. */
+ @Column(name = "units_total", nullable = false)
+ private long unitsTotal;
+
+ /** Live balance; pessimistic-locked on draw. */
+ @Column(name = "units_remaining", nullable = false)
+ private long unitsRemaining;
+
+ @Column(name = "purchased_at", nullable = false)
+ private LocalDateTime purchasedAt;
+
+ /** {@code purchasedAt + 12 months}. Unused units forfeit after this instant. */
+ @Column(name = "expires_at", nullable = false)
+ private LocalDateTime expiresAt;
+
+ /**
+ * Stripe Checkout Session / PaymentIntent id for the one-time payment that created this pool.
+ * The amount + currency + receipt live on that object; a unique index makes the webhook credit
+ * idempotent. {@code null} only for pools seeded outside the purchase flow (tests/backfill).
+ */
+ @Column(name = "stripe_ref", length = 128)
+ private String stripeRef;
+
+ @CreationTimestamp
+ @Column(name = "created_at", nullable = false, updatable = false)
+ private LocalDateTime createdAt;
+
+ /** In-term (not yet expired) as of {@code now} — regardless of remaining balance. */
+ public boolean isInTerm(LocalDateTime now) {
+ return expiresAt.isAfter(now);
+ }
+
+ /** Has units left AND is still in term — i.e. a charge may draw from it. */
+ public boolean isDrawable(LocalDateTime now) {
+ return unitsRemaining > 0 && isInTerm(now);
+ }
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundleRepository.java b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundleRepository.java
new file mode 100644
index 0000000000..48d29517d6
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundleRepository.java
@@ -0,0 +1,55 @@
+package stirling.software.saas.payg.bundle;
+
+import java.time.LocalDateTime;
+import java.util.List;
+
+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 org.springframework.stereotype.Repository;
+
+import jakarta.persistence.LockModeType;
+
+@Repository
+public interface PrepaidBundleRepository extends JpaRepository<PrepaidBundle, Long> {
+
+ /**
+ * A team's still-drawable pools (units left, not expired), soonest-expiring first, locked for
+ * the draw transaction. Mirrors {@code PaygTeamExtensionsRepository.findByIdForUpdate}: the
+ * PESSIMISTIC_WRITE lock serialises concurrent charges for the same team so two jobs can't both
+ * draw the same remaining unit, keeping the per-job {@code bundle_units_consumed} split exact.
+ * Drawn FIFO — the caller depletes the earliest-expiring pool first so capacity is used before
+ * it lapses. Filters on {@code expires_at} so an expired pool is never drawn even if the expiry
+ * sweep hasn't run (lazy expiry).
+ */
+ @Lock(LockModeType.PESSIMISTIC_WRITE)
+ @Query(
+ "SELECT b FROM PrepaidBundle b WHERE b.teamId = :teamId AND b.unitsRemaining > 0"
+ + " AND b.expiresAt > :now ORDER BY b.expiresAt ASC")
+ List<PrepaidBundle> findDrawableForUpdate(
+ @Param("teamId") Long teamId, @Param("now") LocalDateTime now);
+
+ /**
+ * A team's in-term pools (not yet expired), soonest-expiring first — read-only, for the wallet
+ * snapshot. Includes exhausted-but-in-term pools so the "X of Y used" meter keeps the right
+ * denominator for the current term. Small per team; the service aggregates in Java.
+ */
+ @Query(
+ "SELECT b FROM PrepaidBundle b WHERE b.teamId = :teamId AND b.expiresAt > :now"
+ + " ORDER BY b.expiresAt ASC")
+ List<PrepaidBundle> findInTerm(@Param("teamId") Long teamId, @Param("now") LocalDateTime now);
+
+ /**
+ * A team's in-term pools (not yet expired), soonest-expiring first, locked — for the refund
+ * restore path. Unlike {@link #findDrawableForUpdate} this includes pools already drawn to zero
+ * (that's exactly where a just-drawn charge's units go back), capped at {@code units_total} by
+ * the caller.
+ */
+ @Lock(LockModeType.PESSIMISTIC_WRITE)
+ @Query(
+ "SELECT b FROM PrepaidBundle b WHERE b.teamId = :teamId AND b.expiresAt > :now"
+ + " ORDER BY b.expiresAt ASC")
+ List<PrepaidBundle> findInTermForUpdate(
+ @Param("teamId") Long teamId, @Param("now") LocalDateTime now);
+}
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundleService.java b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundleService.java
new file mode 100644
index 0000000000..1faefc8510
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/payg/bundle/PrepaidBundleService.java
@@ -0,0 +1,148 @@
+package stirling.software.saas.payg.bundle;
+
+import java.time.LocalDateTime;
+import java.util.List;
+
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Draws down and restores prepaid unit pools ({@link PrepaidBundle}). Sits between the free grant
+ * and the meter in the charge pipeline (free → prepaid → metered): a charge first spends the team's
+ * free grant, then this service spends prepaid pools FIFO by soonest expiry, and only the remainder
+ * meters to Stripe / counts against the cap.
+ *
+ * <p>Methods participate in the caller's transaction (default REQUIRED propagation), so the draw's
+ * pessimistic write lock is held for the whole {@code openProcess} transaction — the same
+ * discipline as the free-grant deduction, so concurrent same-team charges can't both spend the last
+ * unit.
+ */
+@Service
+@Profile("saas")
+@RequiredArgsConstructor
+@Slf4j
+public class PrepaidBundleService {
+
+ private final PrepaidBundleRepository bundleRepository;
+
+ /**
+ * Spend up to {@code units} from the team's drawable pools, earliest-expiring first, returning
+ * how many were actually drawn (0..{@code units}). Pools past their term are skipped (lazy
+ * expiry — the {@code expires_at} filter means an expired pool is never drawn even before the
+ * expiry sweep runs). A partial draw is normal: the remainder meters.
+ */
+ @Transactional
+ public int draw(Long teamId, int units) {
+ if (teamId == null || units <= 0) {
+ return 0;
+ }
+ List<PrepaidBundle> pools =
+ bundleRepository.findDrawableForUpdate(teamId, LocalDateTime.now());
+ int remaining = units;
+ int drawn = 0;
+ for (PrepaidBundle pool : pools) {
+ if (remaining <= 0) {
+ break;
+ }
+ long take = Math.min(remaining, pool.getUnitsRemaining());
+ if (take <= 0) {
+ continue;
+ }
+ pool.setUnitsRemaining(pool.getUnitsRemaining() - take);
+ drawn += (int) take;
+ remaining -= (int) take;
+ }
+ if (drawn > 0) {
+ bundleRepository.saveAll(pools);
+ }
+ return drawn;
+ }
+
+ /**
+ * Return {@code units} to the team's in-term pools on a refund, earliest-expiring first,
+ * capping each pool at its original {@code units_total}. Best-effort: units that can't be
+ * placed (all in-term pools already at capacity, or every pool expired in the tiny window since
+ * the draw) are dropped with a debug log — first-step-failure refunds are effectively
+ * immediate, so in practice the drawn-from pools are still open and take the units straight
+ * back.
+ */
+ @Transactional
+ public int restore(Long teamId, int units) {
+ if (teamId == null || units <= 0) {
+ return 0;
+ }
+ List<PrepaidBundle> pools =
+ bundleRepository.findInTermForUpdate(teamId, LocalDateTime.now());
+ int remaining = units;
+ for (PrepaidBundle pool : pools) {
+ if (remaining <= 0) {
+ break;
+ }
+ long headroom = pool.getUnitsTotal() - pool.getUnitsRemaining();
+ if (headroom <= 0) {
+ continue;
+ }
+ long give = Math.min(remaining, headroom);
+ pool.setUnitsRemaining(pool.getUnitsRemaining() + give);
+ remaining -= (int) give;
+ }
+ int restored = units - remaining;
+ if (restored > 0) {
+ bundleRepository.saveAll(pools);
+ }
+ if (remaining > 0) {
+ log.debug(
+ "restore: {} of {} prepaid units couldn't be placed for team {} (no in-term"
+ + " headroom)",
+ remaining,
+ units,
+ teamId);
+ }
+ return restored;
+ }
+
+ /**
+ * Aggregate a team's in-term pools for the wallet snapshot: total remaining + total capacity +
+ * soonest expiry. Includes exhausted-but-in-term pools so the "X of Y used" meter keeps the
+ * right denominator for the term. Returns {@code null} when the team has no in-term bundle.
+ */
+ @Transactional(readOnly = true)
+ public PrepaidSummary summarize(Long teamId) {
+ if (teamId == null) {
+ return null;
+ }
+ List<PrepaidBundle> pools = bundleRepository.findInTerm(teamId, LocalDateTime.now());
+ if (pools.isEmpty()) {
+ return null;
+ }
+ long remaining = 0L;
+ long total = 0L;
+ LocalDateTime soonest = null;
+ for (PrepaidBundle pool : pools) {
+ remaining += pool.getUnitsRemaining();
+ total += pool.getUnitsTotal();
+ if (soonest == null || pool.getExpiresAt().isBefore(soonest)) {
+ soonest = pool.getExpiresAt();
+ }
+ }
+ return new PrepaidSummary(remaining, total, soonest);
+ }
+
+ /**
+ * Total prepaid units a team can still draw right now (in-term pools only); 0 when it has none.
+ * The entitlement gate uses this so a team with a live prepaid pool stays entitled even without
+ * a metered subscription — paid-for capacity is usable on its own merit.
+ */
+ @Transactional(readOnly = true)
+ public long prepaidRemainingUnits(Long teamId) {
+ PrepaidSummary summary = summarize(teamId);
+ return summary == null ? 0L : summary.unitsRemaining();
+ }
+
+ /** Aggregated prepaid balance for a team's in-term pools. */
+ public record PrepaidSummary(long unitsRemaining, long unitsTotal, LocalDateTime expiresAt) {}
+}
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.java
index b71caddbee..2fc175f224 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
@@ -17,6 +17,7 @@ import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
+import stirling.software.saas.payg.bundle.PrepaidBundleService;
import stirling.software.saas.payg.docs.DocumentClassifier;
import stirling.software.saas.payg.docs.DocumentMetrics;
import stirling.software.saas.payg.job.JobContext;
@@ -68,6 +69,7 @@ public class JobChargeService {
private final PaygTeamExtensionsRepository teamExtensionsRepository;
private final PaygMeterReportingService meterReportingService;
private final WalletLedgerRepository ledgerRepository;
+ private final PrepaidBundleService prepaidBundleService;
public JobChargeService(
JobService jobService,
@@ -77,7 +79,8 @@ public class JobChargeService {
ProcessingJobRepository jobRepository,
PaygTeamExtensionsRepository teamExtensionsRepository,
PaygMeterReportingService meterReportingService,
- WalletLedgerRepository ledgerRepository) {
+ WalletLedgerRepository ledgerRepository,
+ PrepaidBundleService prepaidBundleService) {
this.jobService = Objects.requireNonNull(jobService, "jobService");
this.policyService = Objects.requireNonNull(policyService, "policyService");
this.classifier = Objects.requireNonNull(classifier, "classifier");
@@ -88,6 +91,8 @@ public class JobChargeService {
this.meterReportingService =
Objects.requireNonNull(meterReportingService, "meterReportingService");
this.ledgerRepository = Objects.requireNonNull(ledgerRepository, "ledgerRepository");
+ this.prepaidBundleService =
+ Objects.requireNonNull(prepaidBundleService, "prepaidBundleService");
}
/**
@@ -128,14 +133,20 @@ public class JobChargeService {
job.setDocUnits(units);
int freeUsed = consumeFreeGrant(ctx, units);
- recordShadowRow(ctx, job.getId(), policy.getId(), units, freeUsed);
+ // 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);
+ recordShadowRow(ctx, job.getId(), policy.getId(), units, freeUsed, bundleUsed);
// doc_count + fingerprint were set on the fresh job by JobService.openFresh; carry them
- // onto the ledger DEBIT so usage analytics query one table.
+ // 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
+ // metered CYCLE spend).
recordLedgerDebit(
ctx,
job.getId(),
policy.getId(),
units,
+ bundleUsed,
job.getDocCount(),
job.getDocumentFingerprint());
@@ -179,12 +190,14 @@ public class JobChargeService {
ProcessingJob job = jobService.open(jobCtx, chargeUnits);
int freeUsed = consumeFreeGrant(ctx, chargeUnits);
- recordShadowRow(ctx, job.getId(), policy.getId(), chargeUnits, freeUsed);
+ int bundleUsed = drawBundle(ctx, chargeUnits - freeUsed);
+ recordShadowRow(ctx, job.getId(), policy.getId(), chargeUnits, freeUsed, bundleUsed);
recordLedgerDebit(
ctx,
job.getId(),
policy.getId(),
chargeUnits,
+ bundleUsed,
job.getDocCount(),
job.getDocumentFingerprint());
@@ -223,6 +236,24 @@ public class JobChargeService {
return freeUsed;
}
+ /**
+ * Draw this job's prepaid portion from the team's bundles — the tier after the free grant and
+ * before the meter — returning the units taken (0..{@code units}). Same guard as {@link
+ * #consumeFreeGrant}; {@link PrepaidBundleService#draw} holds a pessimistic pool lock inside
+ * this {@code openProcess} transaction so concurrent same-team charges split the pools exactly.
+ * Any remainder is the metered paid portion.
+ */
+ private int drawBundle(ChargeContext ctx, int units) {
+ BillingCategory category = ctx.billingCategory();
+ if (category == null || category == BillingCategory.BYPASSED || ctx.ownerTeamId() == null) {
+ return 0;
+ }
+ if (units <= 0) {
+ return 0;
+ }
+ return prepaidBundleService.draw(ctx.ownerTeamId(), units);
+ }
+
/**
* The live spend record. Everything the customer-facing side reads — the wallet endpoint's
* {@code spendUnitsThisPeriod}, the per-category breakdown ({@code wallet_category_summary}
@@ -237,18 +268,27 @@ public class JobChargeService {
java.util.UUID jobId,
Long policyId,
int units,
+ int bundleUnitsConsumed,
int docCount,
String documentFingerprint) {
BillingCategory category = ctx.billingCategory();
if (category == null || category == BillingCategory.BYPASSED) {
return;
}
+ // Prepaid (bundle) units are netted out of the metered CYCLE spend, so the cap + the Stripe
+ // meter don't charge again for capacity already bought up front. (Free-grant units are NOT
+ // netted here — they still count toward CYCLE/cap; only the bundle split is removed.)
+ // doc_count stays the full count so the PDF is still counted once by usage analytics (which
+ // sum doc_count over DEBIT rows, bucket-agnostic). A fully-prepaid charge therefore writes
+ // a
+ // 0-unit DEBIT that still counts toward "PDFs processed".
+ int meteredUnits = units - bundleUnitsConsumed;
WalletLedgerEntry entry = new WalletLedgerEntry();
entry.setTeamId(ctx.ownerTeamId());
entry.setActorUserId(ctx.ownerUserId());
entry.setEntryType(LedgerEntryType.DEBIT);
entry.setBucket(LedgerBucket.CYCLE);
- entry.setAmountUnits(-units);
+ entry.setAmountUnits(-meteredUnits);
entry.setReferenceType(ReferenceType.JOB);
entry.setReferenceId(jobId.toString());
entry.setPolicyId(policyId);
@@ -297,15 +337,17 @@ public class JobChargeService {
java.util.UUID jobId,
Long policyId,
int units,
- int freeUnitsConsumed) {
+ int freeUnitsConsumed,
+ int bundleUnitsConsumed) {
PaygShadowCharge row = new PaygShadowCharge();
row.setTeamId(ctx.ownerTeamId());
row.setJobId(jobId);
row.setPolicyId(policyId);
row.setPaygUnits(units);
- // Free-vs-paid split fixed at charge time: paid (metered) = paygUnits - freeUnitsConsumed,
- // and a refund restores freeUnitsConsumed to the team's grant.
+ // 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);
+ row.setBundleUnitsConsumed(bundleUnitsConsumed);
// No legacy comparison: the legacy credit engine has been removed, so diff stays at 0.
row.setLegacyCreditsCharged(0);
row.setDiffPct(0);
@@ -349,11 +391,15 @@ public class JobChargeService {
// on the CHARGED→REFUNDED transition) prevents double-credits on re-invocation.
BillingCategory category = row.getBillingCategory();
if (category != null && category != BillingCategory.BYPASSED) {
+ int bundleConsumed =
+ row.getBundleUnitsConsumed() == null ? 0 : row.getBundleUnitsConsumed();
WalletLedgerEntry refund = new WalletLedgerEntry();
refund.setTeamId(row.getTeamId());
refund.setEntryType(LedgerEntryType.REFUND);
refund.setBucket(LedgerBucket.CYCLE);
- refund.setAmountUnits(row.getPaygUnits());
+ // 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.setReferenceType(ReferenceType.JOB);
refund.setReferenceId(jobId.toString());
refund.setPolicyId(row.getPolicyId());
@@ -367,6 +413,11 @@ public class JobChargeService {
if (freeConsumed > 0 && row.getTeamId() != null) {
teamExtensionsRepository.restoreFreeUnits(row.getTeamId(), freeConsumed);
}
+ // Return the prepaid units this job drew to the team's pools (best-effort — see
+ // PrepaidBundleService.restore).
+ if (bundleConsumed > 0 && row.getTeamId() != null) {
+ prepaidBundleService.restore(row.getTeamId(), bundleConsumed);
+ }
}
}
}
@@ -506,10 +557,14 @@ public class JobChargeService {
// free grant is app-side only (Stripe's Prices are plain per-unit, no free tier), so the
// free units were already withheld when this row's free_units_consumed was set.
int freeConsumed = row.getFreeUnitsConsumed() == null ? 0 : row.getFreeUnitsConsumed();
- int paidUnits = units - freeConsumed;
+ int bundleConsumed =
+ row.getBundleUnitsConsumed() == null ? 0 : row.getBundleUnitsConsumed();
+ // Metered = units beyond BOTH the free grant and the prepaid bundle; only this hits Stripe.
+ int paidUnits = units - freeConsumed - bundleConsumed;
if (paidUnits <= 0) {
log.debug(
- "close({}): all {} units came from the free grant → no meter event",
+ "close({}): all {} units covered by free grant + prepaid bundle → no meter"
+ + " event",
jobId,
units);
return;
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/charge/SaasClassificationRunBiller.java b/app/saas/src/main/java/stirling/software/saas/payg/charge/SaasClassificationRunBiller.java
index 79533fb102..a4536d6c23 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/charge/SaasClassificationRunBiller.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/charge/SaasClassificationRunBiller.java
@@ -17,8 +17,8 @@ import stirling.software.saas.payg.model.ProcessType;
import stirling.software.saas.util.AuthenticationUtils;
/**
- * Charges one PAYG unit per document as an AUTOMATION job, matching what a server-side
- * classify policy step bills.
+ * Charges one PAYG unit per document as an AUTOMATION job, matching what a server-side classify
+ * policy step bills.
*/
@Component
@Profile("saas")
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.java
index 397a714bfa..f2863a56d5 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
@@ -18,6 +18,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.saas.payg.billing.TeamBillingContext;
import stirling.software.saas.payg.billing.TeamBillingService;
+import stirling.software.saas.payg.bundle.PrepaidBundleService;
import stirling.software.saas.payg.cap.CapEvaluator;
import stirling.software.saas.payg.cap.CapEvaluator.Evaluation;
import stirling.software.saas.payg.model.EntitlementState;
@@ -51,17 +52,21 @@ public class EntitlementService {
private final TeamBillingService teamBillingService;
private final WalletPolicyRepository walletPolicyRepository;
private final WalletLedgerRepository ledgerRepository;
+ private final PrepaidBundleService prepaidBundleService;
private final Cache<Long, EntitlementSnapshot> snapshotCache;
public EntitlementService(
TeamBillingService teamBillingService,
WalletPolicyRepository walletPolicyRepository,
- WalletLedgerRepository ledgerRepository) {
+ WalletLedgerRepository ledgerRepository,
+ PrepaidBundleService prepaidBundleService) {
this.teamBillingService = Objects.requireNonNull(teamBillingService, "teamBillingService");
this.walletPolicyRepository =
Objects.requireNonNull(walletPolicyRepository, "walletPolicyRepository");
this.ledgerRepository = Objects.requireNonNull(ledgerRepository, "ledgerRepository");
+ this.prepaidBundleService =
+ Objects.requireNonNull(prepaidBundleService, "prepaidBundleService");
this.snapshotCache =
Caffeine.newBuilder()
.maximumSize(CACHE_MAX_SIZE)
@@ -135,21 +140,45 @@ public class EntitlementService {
long periodSpend = signedNet < 0 ? -signedNet : 0L;
Long cap = billing.monthlyCapDocUnits();
eval = CapEvaluator.evaluate(periodSpend, cap, warnAtPct, degradeAtPct, degradedSet);
+ // A live prepaid pool sits OUTSIDE the metered cap: bundle draws are netted out of
+ // period
+ // spend in JobChargeService, so they never count toward it. So a subscribed team that
+ // has
+ // hit its cap but still holds prepaid capacity stays fully entitled — the job draws
+ // from
+ // the pool, not the meter, and the cap is irrelevant while the pool has balance.
+ // Queried
+ // lazily (only when the cap would otherwise degrade) to keep the under-cap path off the
+ // prepaid table.
+ if (eval.state() == EntitlementState.DEGRADED
+ && prepaidBundleService.prepaidRemainingUnits(teamId) > 0L) {
+ eval = fullyEntitledOnPrepaid();
+ }
snapshotSpend = periodSpend;
snapshotCap = cap;
} else {
- // Unsubscribed: gate on the one-time lifetime free grant. Exhausted (remaining ≤ 0, or
- // no grant configured) → DEGRADED so billable categories hard-stop; otherwise evaluate
- // the warn/degrade band on used-of-grant.
+ // Unsubscribed: gate on the one-time lifetime free grant, then on a prepaid pool. While
+ // the free grant has balance, evaluate the warn/degrade band on used-of-grant. Once the
+ // free grant is spent, a live prepaid pool keeps the team fully entitled — paid-for
+ // capacity is usable on its own merit, independent of any metered subscription (the
+ // pool
+ // is drawn in JobChargeService; only the metered remainder stays gated on the sub).
+ // Only
+ // when BOTH the free grant and prepaid are exhausted do billable categories hard-stop.
long grant = billing.freeGrantUnits();
long remaining = billing.freeRemainingUnits();
long used = Math.max(0L, grant - remaining);
if (remaining <= 0L) {
- eval =
- new Evaluation(
- EntitlementState.DEGRADED,
- degradedSet,
- CapEvaluator.gatesFor(degradedSet));
+ long prepaidRemaining = prepaidBundleService.prepaidRemainingUnits(teamId);
+ if (prepaidRemaining > 0L) {
+ eval = fullyEntitledOnPrepaid();
+ } else {
+ eval =
+ new Evaluation(
+ EntitlementState.DEGRADED,
+ degradedSet,
+ CapEvaluator.gatesFor(degradedSet));
+ }
} else {
eval = CapEvaluator.evaluate(used, grant, warnAtPct, degradeAtPct, degradedSet);
}
@@ -168,6 +197,17 @@ public class EntitlementService {
billing.subscribed());
}
+ /**
+ * A team holding a live prepaid pool is fully entitled regardless of the free-grant or the
+ * monthly-cap gate: the pool is drawn in the charge pipeline and its units are netted out of
+ * metered spend, so it sits OUTSIDE both gates. All feature gates are on. Shared by the
+ * unsubscribed (grant-exhausted) and subscribed (over-cap) branches.
+ */
+ private static Evaluation fullyEntitledOnPrepaid() {
+ return new Evaluation(
+ EntitlementState.FULL, FeatureSet.FULL, CapEvaluator.gatesFor(FeatureSet.FULL));
+ }
+
/**
* Inclusive-start / exclusive-end window for the calendar-month period. Test seam — takes a
* clock value so tests don't race the calendar boundary. The live snapshot window comes from
diff --git a/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java b/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
index 9581177369..d28b0fd09d 100644
--- a/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
+++ b/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicy.java
@@ -114,6 +114,19 @@ public class PricingPolicy implements Serializable {
@Column(name = "stripe_price_id", nullable = false, length = 128)
private Set<String> stripePriceIds = new HashSet<>();
+ /**
+ * One-time Stripe Price id for prepaid-bundle checkout — same {@code unit_amount} as the
+ * metered price (Stripe {@code currency_options} cover all currencies on one Price). Read by
+ * the create-payg-bundle-checkout edge fn via {@code payg_get_bundle_checkout_context}. Null =
+ * bundles not offered for this policy. Money lives in Stripe; this is just the handle.
+ */
+ @Column(name = "bundle_stripe_price_id", length = 128)
+ private String bundleStripePriceId;
+
+ /** Stripe coupon id applying the 12-for-10 prepaid discount. Null = bundles not offered. */
+ @Column(name = "bundle_coupon_id", length = 128)
+ private String bundleCouponId;
+
/**
* Exactly one row in the table has {@code is_default = true}; enforced by partial unique idx.
*/
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.java
index 57aea1a0e4..6a00ea6d18 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
@@ -67,6 +67,20 @@ public class PaygShadowCharge implements Serializable {
@Column(name = "free_units_consumed", nullable = false)
private Integer freeUnitsConsumed = 0;
+ /**
+ * How many of {@link #paygUnits} were drawn from prepaid bundles (the {@code BOUGHT} bucket) at
+ * charge time — the tier between the free grant and the meter. The paid (Stripe-metered)
+ * portion is {@code paygUnits - freeUnitsConsumed - bundleUnitsConsumed}; a refund restores
+ * this many units to the pool(s) they came from. {@code 0} for pre-bundle rows and jobs that
+ * drew none. The {@code columnDefinition} default keeps the ddl-auto ADD COLUMN safe on the
+ * populated table.
+ */
+ @Column(
+ name = "bundle_units_consumed",
+ nullable = false,
+ columnDefinition = "integer not null default 0")
+ private Integer bundleUnitsConsumed = 0;
+
@Column(name = "legacy_credits_charged", nullable = false)
private Integer legacyCreditsCharged;
diff --git a/app/saas/src/test/java/stirling/software/saas/config/SaasJpaConfigScanTest.java b/app/saas/src/test/java/stirling/software/saas/config/SaasJpaConfigScanTest.java
index faf7f561ec..1ec5d64214 100644
--- a/app/saas/src/test/java/stirling/software/saas/config/SaasJpaConfigScanTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/config/SaasJpaConfigScanTest.java
@@ -25,7 +25,10 @@ class SaasJpaConfigScanTest {
"stirling.software.saas.repository",
"stirling.software.saas.billing.repository",
"stirling.software.saas.ai.repository",
- "stirling.software.saas.payg.repository");
+ "stirling.software.saas.payg.repository",
+ // PrepaidBundleRepository lives in payg.bundle, not payg.repository — the repo
+ // scan is leaf-level, not recursive.
+ "stirling.software.saas.payg.bundle");
private static final List<String> EXPECTED_ENTITY_PACKAGES =
List.of(
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.java
index 1625116af0..01e112a1c8 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
@@ -39,6 +39,7 @@ import stirling.software.saas.payg.api.PaygWalletController.UpdateCapRequest;
import stirling.software.saas.payg.api.WalletSnapshotResponse.MemberRow;
import stirling.software.saas.payg.billing.TeamBillingContext;
import stirling.software.saas.payg.billing.TeamBillingService;
+import stirling.software.saas.payg.bundle.PrepaidBundleService;
import stirling.software.saas.payg.entitlement.EntitlementService;
import stirling.software.saas.payg.entitlement.EntitlementSnapshot;
import stirling.software.saas.payg.model.BillingCategory;
@@ -69,6 +70,7 @@ class PaygWalletControllerTest {
@Mock private WalletLedgerRepository ledgerRepo;
@Mock private PaygShadowChargeRepository shadowRepo;
@Mock private UserRepository userRepository;
+ @Mock private PrepaidBundleService prepaidBundleService;
private PaygWalletController controller;
@@ -83,7 +85,8 @@ class PaygWalletControllerTest {
policyRepo,
ledgerRepo,
shadowRepo,
- userRepository);
+ userRepository,
+ prepaidBundleService);
}
/**
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.java
index e8547de268..55dfdb40e3 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
@@ -39,7 +39,11 @@ class WalletSnapshotResponseTest {
/* categoryDocs= */ new CategoryBreakdown(3, 2, 1),
/* docsProcessedThisPeriod= */ 6,
/* uniquePdfsThisPeriod= */ 5,
- /* sizeMultiplierPdfsThisPeriod= */ 2);
+ /* sizeMultiplierPdfsThisPeriod= */ 2,
+ /* prepaidUnitsRemaining= */ 40_000L,
+ /* prepaidUnitsTotal= */ 120_000L,
+ /* prepaidExpiresAt= */ "2027-06-01",
+ /* billingMode= */ "prepaid");
}
@Test
@@ -115,7 +119,11 @@ class WalletSnapshotResponseTest {
new CategoryBreakdown(0, 0, 0),
0,
0,
- 0);
+ 0,
+ 0L,
+ 0L,
+ null,
+ "payg");
assertThat(free.billableLimit()).isNull();
assertThat(free.pricePerDocMinor()).isNull();
diff --git a/app/saas/src/test/java/stirling/software/saas/payg/bundle/PrepaidBundleServiceTest.java b/app/saas/src/test/java/stirling/software/saas/payg/bundle/PrepaidBundleServiceTest.java
new file mode 100644
index 0000000000..2c700fcd1b
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/payg/bundle/PrepaidBundleServiceTest.java
@@ -0,0 +1,172 @@
+package stirling.software.saas.payg.bundle;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+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.util.List;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import stirling.software.saas.payg.bundle.PrepaidBundleService.PrepaidSummary;
+
+/**
+ * Unit tests for the prepaid-bundle draw/restore/summarize money logic. The repository is mocked,
+ * so these pin the in-Java arithmetic (FIFO depletion, per-pool caps, best-effort restore,
+ * aggregation) — the FIFO-by-expiry ordering and the expiry/lock filters live in the repository
+ * JPQL and are covered separately by the query definitions, not here.
+ */
+class PrepaidBundleServiceTest {
+
+ private static final Long TEAM = 42L;
+ private static final LocalDateTime SOON = LocalDateTime.of(2026, 8, 1, 0, 0);
+ private static final LocalDateTime LATER = LocalDateTime.of(2026, 12, 1, 0, 0);
+
+ private PrepaidBundleRepository repo;
+ private PrepaidBundleService service;
+
+ @BeforeEach
+ void setUp() {
+ repo = Mockito.mock(PrepaidBundleRepository.class);
+ service = new PrepaidBundleService(repo);
+ }
+
+ private static PrepaidBundle pool(long total, long remaining, LocalDateTime expiresAt) {
+ PrepaidBundle b = new PrepaidBundle();
+ b.setTeamId(TEAM);
+ b.setUnitsTotal(total);
+ b.setUnitsRemaining(remaining);
+ b.setExpiresAt(expiresAt);
+ return b;
+ }
+
+ // ── draw ────────────────────────────────────────────────────────────────
+
+ @Test
+ void draw_nullTeamOrNonPositiveUnits_returnsZeroWithoutTouchingRepo() {
+ assertThat(service.draw(null, 100)).isZero();
+ assertThat(service.draw(TEAM, 0)).isZero();
+ assertThat(service.draw(TEAM, -5)).isZero();
+ verifyNoInteractions(repo);
+ }
+
+ @Test
+ void draw_partialFromSinglePool_leavesRemainder() {
+ PrepaidBundle p = pool(1000, 1000, SOON);
+ when(repo.findDrawableForUpdate(eq(TEAM), any())).thenReturn(List.of(p));
+
+ int drawn = service.draw(TEAM, 300);
+
+ assertThat(drawn).isEqualTo(300);
+ assertThat(p.getUnitsRemaining()).isEqualTo(700);
+ verify(repo).saveAll(List.of(p));
+ }
+
+ @Test
+ void draw_spansPoolsFifo_cappedAtEachPoolBalance() {
+ // Repo returns soonest-expiring first; the earlier pool is depleted before the later one.
+ PrepaidBundle first = pool(1000, 100, SOON);
+ PrepaidBundle second = pool(1000, 1000, LATER);
+ when(repo.findDrawableForUpdate(eq(TEAM), any())).thenReturn(List.of(first, second));
+
+ int drawn = service.draw(TEAM, 250);
+
+ assertThat(drawn).isEqualTo(250);
+ assertThat(first.getUnitsRemaining()).isZero(); // fully depleted first
+ assertThat(second.getUnitsRemaining()).isEqualTo(850); // 150 taken from the later pool
+ }
+
+ @Test
+ void draw_moreThanAvailable_drawsOnlyWhatExists() {
+ PrepaidBundle p = pool(1000, 120, SOON);
+ when(repo.findDrawableForUpdate(eq(TEAM), any())).thenReturn(List.of(p));
+
+ int drawn = service.draw(TEAM, 500);
+
+ assertThat(drawn).isEqualTo(120); // partial draw; the remainder meters
+ assertThat(p.getUnitsRemaining()).isZero();
+ }
+
+ @Test
+ void draw_noDrawablePools_returnsZeroAndDoesNotSave() {
+ when(repo.findDrawableForUpdate(eq(TEAM), any())).thenReturn(List.of());
+
+ assertThat(service.draw(TEAM, 100)).isZero();
+ verify(repo, never()).saveAll(any());
+ }
+
+ // ── restore ─────────────────────────────────────────────────────────────
+
+ @Test
+ void restore_capsEachPoolAtItsOriginalTotal() {
+ // Two in-term pools with headroom 60 then 200; restoring 100 fills the first, spills 40 to
+ // the
+ // second, and never exceeds units_total on either.
+ PrepaidBundle first = pool(1000, 940, SOON); // headroom 60
+ PrepaidBundle second = pool(1000, 800, LATER); // headroom 200
+ when(repo.findInTermForUpdate(eq(TEAM), any())).thenReturn(List.of(first, second));
+
+ int restored = service.restore(TEAM, 100);
+
+ assertThat(restored).isEqualTo(100);
+ assertThat(first.getUnitsRemaining()).isEqualTo(1000); // capped at total
+ assertThat(second.getUnitsRemaining()).isEqualTo(840);
+ verify(repo).saveAll(List.of(first, second));
+ }
+
+ @Test
+ void restore_dropsUnitsThatCannotBePlaced() {
+ // Only 60 headroom for a 100 restore → 60 restored, 40 dropped (best-effort).
+ PrepaidBundle p = pool(1000, 940, SOON);
+ when(repo.findInTermForUpdate(eq(TEAM), any())).thenReturn(List.of(p));
+
+ int restored = service.restore(TEAM, 100);
+
+ assertThat(restored).isEqualTo(60);
+ assertThat(p.getUnitsRemaining()).isEqualTo(1000);
+ }
+
+ @Test
+ void restore_nullTeamOrNonPositive_returnsZeroWithoutRepo() {
+ assertThat(service.restore(null, 10)).isZero();
+ assertThat(service.restore(TEAM, 0)).isZero();
+ verifyNoInteractions(repo);
+ }
+
+ // ── summarize / prepaidRemainingUnits ─────────────────────────────────────
+
+ @Test
+ void summarize_nullWhenNoInTermPools() {
+ when(repo.findInTerm(eq(TEAM), any())).thenReturn(List.of());
+ assertThat(service.summarize(TEAM)).isNull();
+ }
+
+ @Test
+ void summarize_sumsBalancesAndPicksSoonestExpiry() {
+ when(repo.findInTerm(eq(TEAM), any()))
+ .thenReturn(List.of(pool(1000, 250, LATER), pool(500, 500, SOON)));
+
+ PrepaidSummary summary = service.summarize(TEAM);
+
+ assertThat(summary.unitsRemaining()).isEqualTo(750);
+ assertThat(summary.unitsTotal()).isEqualTo(1500);
+ assertThat(summary.expiresAt()).isEqualTo(SOON); // earliest across pools
+ }
+
+ @Test
+ void prepaidRemainingUnits_delegatesToSummary_zeroWhenNone() {
+ when(repo.findInTerm(eq(TEAM), any())).thenReturn(List.of());
+ assertThat(service.prepaidRemainingUnits(TEAM)).isZero();
+
+ when(repo.findInTerm(eq(TEAM), any()))
+ .thenReturn(List.of(pool(1000, 400, SOON), pool(1000, 350, LATER)));
+ assertThat(service.prepaidRemainingUnits(TEAM)).isEqualTo(750);
+ }
+}
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.java
index e669e1b5bd..43abfe24e1 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
@@ -31,6 +31,7 @@ import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.multipart.MultipartFile;
+import stirling.software.saas.payg.bundle.PrepaidBundleService;
import stirling.software.saas.payg.docs.DocumentClassifier;
import stirling.software.saas.payg.docs.DocumentMetrics;
import stirling.software.saas.payg.job.JobContext;
@@ -70,6 +71,7 @@ class JobChargeServiceTest {
private PaygTeamExtensionsRepository teamExtRepo;
private PaygMeterReportingService meterReporter;
private WalletLedgerRepository ledgerRepo;
+ private PrepaidBundleService prepaidBundleService;
private JobChargeService service;
@BeforeEach
@@ -82,6 +84,9 @@ class JobChargeServiceTest {
teamExtRepo = Mockito.mock(PaygTeamExtensionsRepository.class);
meterReporter = Mockito.mock(PaygMeterReportingService.class);
ledgerRepo = Mockito.mock(WalletLedgerRepository.class);
+ // Defaults to draw()==0 (Mockito int default) → no prepaid consumed unless a test stubs it,
+ // so existing free/metered assertions are unaffected.
+ prepaidBundleService = Mockito.mock(PrepaidBundleService.class);
// findByIdForUpdate defaults to Optional.empty() (Mockito) → no free grant consumed unless
// a test stubs the sidecar row. The free split is decided at openProcess time now, not at
// close, so the meter tests just set free_units_consumed on the shadow row directly.
@@ -94,7 +99,8 @@ class JobChargeServiceTest {
jobRepo,
teamExtRepo,
meterReporter,
- ledgerRepo);
+ ledgerRepo,
+ prepaidBundleService);
}
@AfterEach
@@ -202,6 +208,42 @@ class JobChargeServiceTest {
assertThat(debit.getBillingCategory()).isEqualTo(BillingCategory.API);
}
+ @Test
+ void openProcess_prepaidBundleDraw_netsBundleUnitsOutOfLedgerAndRecordsSplit(@TempDir Path tmp)
+ throws IOException {
+ // Bundle covers 3 of the 4 charged units. Only the metered remainder (1) lands in the
+ // ledger's CYCLE spend (so prepaid stays outside the cap + Stripe meter), while the shadow
+ // row freezes the split and doc_count is untouched (the PDF is still counted once).
+ PricingPolicy policy = stubPolicy(/*minCharge*/ 1, Map.of(JobSource.WEB, 10));
+ when(policyService.getEffectivePolicy(100L)).thenReturn(policy);
+ ProcessingJob newJob = openJob(UUID.randomUUID());
+ when(jobService.joinOrOpen(any(JobContext.class), anyList()))
+ .thenReturn(new JoinOrOpenResult(newJob, JoinOrOpenResult.Disposition.OPENED));
+ when(classifier.classify(any(MultipartFile.class), any(Path.class), eq(policy)))
+ .thenReturn(new DocumentMetrics(50, 1024L, "application/pdf", 4));
+ // No free grant (findByIdForUpdate defaults empty); prepaid pools cover 3 of the 4 units.
+ when(prepaidBundleService.draw(eq(100L), eq(4))).thenReturn(3);
+
+ JobInput in = jobInput(tmp, "in.pdf", "application/pdf");
+ service.openProcess(
+ new ChargeContext(
+ 42L, 100L, JobSource.WEB, ProcessType.SINGLE_TOOL, BillingCategory.API),
+ List.of(in));
+
+ ArgumentCaptor<PaygShadowCharge> shadowCaptor =
+ ArgumentCaptor.forClass(PaygShadowCharge.class);
+ verify(shadowRepo).save(shadowCaptor.capture());
+ assertThat(shadowCaptor.getValue().getPaygUnits()).isEqualTo(4);
+ assertThat(shadowCaptor.getValue().getBundleUnitsConsumed()).isEqualTo(3);
+
+ ArgumentCaptor<WalletLedgerEntry> ledgerCaptor =
+ ArgumentCaptor.forClass(WalletLedgerEntry.class);
+ verify(ledgerRepo).save(ledgerCaptor.capture());
+ // 4 charged − 3 prepaid = 1 metered unit, stored negative.
+ assertThat(ledgerCaptor.getValue().getAmountUnits()).isEqualTo(-1);
+ assertThat(ledgerCaptor.getValue().getBucket()).isEqualTo(LedgerBucket.CYCLE);
+ }
+
@Test
void openProcess_bypassedCategory_writesShadowRowButNoLedgerDebit(@TempDir Path tmp)
throws IOException {
diff --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.java
index 430e1b7e0e..3079115c6e 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
@@ -17,6 +17,7 @@ import org.mockito.Mockito;
import stirling.software.saas.payg.billing.TeamBillingContext;
import stirling.software.saas.payg.billing.TeamBillingService;
+import stirling.software.saas.payg.bundle.PrepaidBundleService;
import stirling.software.saas.payg.model.EntitlementState;
import stirling.software.saas.payg.model.FeatureGate;
import stirling.software.saas.payg.model.FeatureSet;
@@ -47,6 +48,7 @@ class EntitlementServiceTest {
private TeamBillingService billingService;
private WalletPolicyRepository walletPolicyRepo;
private WalletLedgerRepository ledgerRepo;
+ private PrepaidBundleService prepaidBundleService;
private EntitlementService service;
@BeforeEach
@@ -54,7 +56,10 @@ class EntitlementServiceTest {
billingService = Mockito.mock(TeamBillingService.class);
walletPolicyRepo = Mockito.mock(WalletPolicyRepository.class);
ledgerRepo = Mockito.mock(WalletLedgerRepository.class);
- service = new EntitlementService(billingService, walletPolicyRepo, ledgerRepo);
+ prepaidBundleService = Mockito.mock(PrepaidBundleService.class);
+ service =
+ new EntitlementService(
+ billingService, walletPolicyRepo, ledgerRepo, prepaidBundleService);
}
@Test
@@ -122,10 +127,13 @@ class EntitlementServiceTest {
}
@Test
- void exhaustedGrant_returnsDegradedWithMinimalGates() {
- // Grant fully consumed (remaining 0) → billable categories hard-stop for an unsubscribed
- // team. The displayed cap stays the grant size; spend reads as the full grant.
+ void exhaustedGrantAndNoPrepaid_returnsDegradedWithMinimalGates() {
+ // Grant fully consumed (remaining 0) AND no prepaid pool → billable categories hard-stop
+ // for
+ // an unsubscribed team. The displayed cap stays the grant size; spend reads as the full
+ // grant.
stubBilling(42L, freeContext(100L, 0L));
+ when(prepaidBundleService.prepaidRemainingUnits(42L)).thenReturn(0L);
when(walletPolicyRepo.findByTeamId(42L))
.thenReturn(Optional.of(walletPolicyThresholds(FeatureSet.MINIMAL)));
@@ -142,6 +150,110 @@ class EntitlementServiceTest {
.doesNotContain(FeatureGate.AUTOMATION, FeatureGate.AI_SUPPORT);
}
+ @Test
+ void exhaustedGrantButLivePrepaidPool_staysFullyEntitled() {
+ // Free grant spent (remaining 0) but the team holds a paid prepaid pool → fully entitled,
+ // NOT degraded, even with no metered subscription. All gates (incl. AUTOMATION + AI) are
+ // on;
+ // the pool is drawn in the charge pipeline. This is the Phase-1 fix: paid-for usage is
+ // usable
+ // on its own merit rather than gated behind a subscription that may not have provisioned.
+ stubBilling(42L, freeContext(100L, 0L));
+ when(prepaidBundleService.prepaidRemainingUnits(42L)).thenReturn(480_000L);
+ when(walletPolicyRepo.findByTeamId(42L))
+ .thenReturn(Optional.of(walletPolicyThresholds(FeatureSet.MINIMAL)));
+
+ EntitlementSnapshot snap = service.getSnapshot(42L);
+
+ assertThat(snap.state()).isEqualTo(EntitlementState.FULL);
+ assertThat(snap.featureSet()).isEqualTo(FeatureSet.FULL);
+ assertThat(snap.enabledGates())
+ .containsExactlyInAnyOrder(
+ FeatureGate.OFFSITE_PROCESSING,
+ FeatureGate.AUTOMATION,
+ FeatureGate.AI_SUPPORT,
+ FeatureGate.CLIENT_SIDE);
+ assertThat(snap.subscribed()).isFalse();
+ }
+
+ @Test
+ void grantStillHasBalance_prepaidNotConsulted() {
+ // While the free grant has balance, the gate never queries prepaid (lazy — only checked
+ // when
+ // the grant is exhausted). Keeps the common free-tier path off the prepaid table.
+ stubBilling(42L, freeContext(500L, 400L));
+ when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());
+
+ service.getSnapshot(42L);
+
+ Mockito.verifyNoInteractions(prepaidBundleService);
+ }
+
+ @Test
+ void subscribedOverCapButLivePrepaidPool_staysFullyEntitled() {
+ // Subscribed team at/over its metered cap but holding a live prepaid pool → fully entitled,
+ // NOT degraded. Prepaid sits outside the cap (its draws are netted out of metered spend in
+ // JobChargeService), so the job draws from the pool and the cap is irrelevant while it
+ // lasts.
+ stubBilling(42L, subscribedContext(1000L));
+ when(walletPolicyRepo.findByTeamId(42L))
+ .thenReturn(Optional.of(walletPolicyThresholds(FeatureSet.MINIMAL)));
+ // 1000 spent of a 1000 cap → 100% → cap gate degrades, but the pool overrides it.
+ when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(-1000L);
+ when(prepaidBundleService.prepaidRemainingUnits(42L)).thenReturn(5000L);
+
+ EntitlementSnapshot snap = service.getSnapshot(42L);
+
+ assertThat(snap.state()).isEqualTo(EntitlementState.FULL);
+ assertThat(snap.featureSet()).isEqualTo(FeatureSet.FULL);
+ assertThat(snap.enabledGates())
+ .containsExactlyInAnyOrder(
+ FeatureGate.OFFSITE_PROCESSING,
+ FeatureGate.AUTOMATION,
+ FeatureGate.AI_SUPPORT,
+ FeatureGate.CLIENT_SIDE);
+ // Still a subscribed team; the cap figures are unchanged, only the entitlement is
+ // overridden.
+ assertThat(snap.subscribed()).isTrue();
+ assertThat(snap.periodCapUnits()).isEqualTo(1000L);
+ assertThat(snap.periodSpendUnits()).isEqualTo(1000L);
+ }
+
+ @Test
+ void subscribedOverCapNoPrepaid_returnsDegraded() {
+ // Subscribed, over cap, no pool → degraded as before (regression guard: the pool override
+ // must
+ // not open the gate for a team that has none).
+ stubBilling(42L, subscribedContext(1000L));
+ when(walletPolicyRepo.findByTeamId(42L))
+ .thenReturn(Optional.of(walletPolicyThresholds(FeatureSet.MINIMAL)));
+ when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(-1000L);
+ when(prepaidBundleService.prepaidRemainingUnits(42L)).thenReturn(0L);
+
+ EntitlementSnapshot snap = service.getSnapshot(42L);
+
+ assertThat(snap.state()).isEqualTo(EntitlementState.DEGRADED);
+ assertThat(snap.featureSet()).isEqualTo(FeatureSet.MINIMAL);
+ assertThat(snap.enabledGates())
+ .containsExactlyInAnyOrder(FeatureGate.OFFSITE_PROCESSING, FeatureGate.CLIENT_SIDE);
+ }
+
+ @Test
+ void subscribedUnderCap_prepaidNotConsulted() {
+ // Under cap → FULL, so the prepaid pool is never queried (lazy — only when the cap gate
+ // would
+ // otherwise degrade). Keeps the common subscribed path off the prepaid table.
+ stubBilling(42L, subscribedContext(1000L));
+ when(walletPolicyRepo.findByTeamId(42L))
+ .thenReturn(Optional.of(walletPolicyThresholds(FeatureSet.MINIMAL)));
+ when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(-250L);
+
+ EntitlementSnapshot snap = service.getSnapshot(42L);
+
+ assertThat(snap.state()).isEqualTo(EntitlementState.FULL);
+ Mockito.verifyNoInteractions(prepaidBundleService);
+ }
+
@Test
void grantInWarnBand_returnsWarnedButFullFeatureSet() {
// grant 100, remaining 15 → used 85 = 85% (between warn 80 and degrade 100).
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 72099ba949..48677633c4 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -5511,8 +5511,8 @@ title = "Recent billable activity"
[payg.cap]
amount = "Cap amount"
custom = "Custom"
-docsEstimate = "≈ {{docs}} processed PDFs / month"
-docsRate = "at {{rate}} / PDF"
+docsEstimate = "≈ {{docs}} credits / month"
+docsRate = "at {{rate}} / credit"
noCapDesc = "Usage is billed without an upper limit. You can re-enable a cap at any time."
noCapLabel = "No cap"
noneShort = "No cap"
@@ -5612,6 +5612,28 @@ docs = "PDFs"
subtitle = "Billable PDFs each teammate has processed this period."
title = "Team member usage"
+[payg.prepaid]
+chip = "Prepaid year"
+
+[payg.prepaid.banner]
+exhausted = "Your prepaid capacity is used up; metered billing has resumed. Top up to keep the discount."
+expiring_one = "Your prepaid year ends in {{count}} day. Unused capacity expires — top up to start a fresh year."
+expiring_other = "Your prepaid year ends in {{count}} days. Unused capacity expires — top up to start a fresh year."
+low = "You're down to {{pct}}% of your prepaid capacity. Top up any time to keep processing uninterrupted."
+
+[payg.prepaid.card]
+subtitle = "Used before metered billing and outside your spend cap."
+title = "Prepaid capacity"
+
+[payg.prepaid.meter]
+capSuffix = "of {{total}} prepaid credits"
+expires = "Expires {{date}}"
+
+[payg.prepaid.state]
+exhausted = "Used up"
+healthy = "Plenty left"
+low = "Running low"
+
[payg.role]
leader = "Team owner"
member = "Member"
@@ -6331,10 +6353,21 @@ typing = "Typing"
loading = "Loading"
redirectingToEditor = "Redirecting to the editor..."
+[portal.billing.activation]
+maybeLater = "Maybe later"
+title = "Switch on the Processor"
+
+[portal.billing.activation.payg]
+sub = "Set a monthly limit. Pay for what you run."
+title = "Pay as you go"
+
+[portal.billing.activation.prepay]
+badge = "2 months free"
+sub = "One invoice, card or bank transfer."
+title = "Prepay a year"
+
[portal.billing.checkout]
noClientSecret = "Edge function returned no client_secret."
-stepCount = "Step {{step}} of 2"
-subtitle = "Add a card to keep going past your free Editor-plan grant. Stripe handles the rest."
title = "Add a payment method"
[portal.billing.checkout.activationSlow]
@@ -6343,12 +6376,14 @@ close = "Close"
title = "Almost there"
[portal.billing.checkout.cap]
+amountAria = "Monthly spend limit"
back = "Back"
continue = "Continue to payment"
error = "Couldn't set your spend limit"
-finePrint = "Invoices post on the 1st. Cancel anytime and revert to the Editor plan; your policies and history stay intact."
-note = "Processing pauses if you reach it. You're never billed past this, and you can change it any time."
-subtitle = "You're billed only for PDFs you process past your first 500 free, never for seats — so your ceiling is yours from day one."
+finePrint = "Invoices post monthly. Cancel anytime."
+noLimit = "No limit"
+note = "You're never billed past your limit. Processing just pauses."
+perMonth = "/ mo"
title = "Set your spend limit"
[portal.billing.checkout.card]
@@ -6364,6 +6399,10 @@ body = "Your payment went through. We're switching on metered processing across
hint = "Please keep this window open."
title = "Activating your Processor plan..."
+[portal.billing.checkout.pay]
+limit = "Monthly spend limit {{amount}}/mo. Processing pauses at the limit."
+limitNoCap = "No spend limit. Processing won't pause. Invoices post monthly."
+
[portal.billing.enterpriseUpsell]
cta = "Explore Enterprise"
description = "Committed volume discounts, air-gapped deployment, custom MSA and security reviews, and 3rd-party distributor partnerships."
@@ -6385,10 +6424,12 @@ currentPlan = "Current plan"
freeForever = "Free forever"
noTeamResolved = "No team is resolved on your wallet yet — refresh and try again."
ownerOnly = "Only the team owner can switch on the Processor plan."
+payInvoice = "Pay invoice to complete"
planName = "Editor"
ssoIncluded = "SSO included"
switchOnProcessor = "Switch on the Processor →"
unlimitedUsers = "Unlimited users"
+viewQuote = "View quote"
[portal.billing.invoices]
columnAmount = "Amount"
@@ -6448,6 +6489,105 @@ unit = "PDFs"
unitsPending_one = "{{units}} meter unit pending sync from linked instances"
unitsPending_other = "{{units}} meter units pending sync from linked instances"
+[portal.billing.prepaid]
+capSuffix = "of {{total}} prepaid credits"
+expires = "Expires {{date}}"
+eyebrow = "Prepaid capacity"
+note = "Used before metered billing and outside your spend limit."
+topUp = "Top up"
+
+[portal.billing.prepaid.buy]
+back = "Back"
+calcTitle = "Calculate your annual payment"
+cancel = "Cancel"
+cancelPurchase = "Cancel purchase"
+close = "Close"
+continueToPayment = "Continue to payment"
+finalise = "Finalise"
+invoiceErrorTitle = "Couldn't generate the invoice"
+loadingTitle = "Loading your quote"
+payTitle = "Pay for your year"
+step = "Step {{current}} of {{total}}"
+
+[portal.billing.prepaid.calc]
+change = "Change"
+deployRow = "Deployment"
+done = "Done"
+enterpriseHint = "This is enterprise scale. At this volume, enterprise rates beat any self-serve discount. Rate lock, terms, and a quote in minutes."
+governanceRow = "Governance"
+governanceValue = "{{label}} · {{count}} policies"
+handlesLabel = "Your Processor"
+handlesValue = "handles {{volume}} credits / mo"
+pipelinesLabel = "Pipelines"
+policiesMeta = "{{count}} policies"
+poolCaption = "One pool of {{credits}} credits for the year. Heavy months borrow from light ones."
+priceLabel = "Your year · 12 months for the price of 10"
+rateUnknown = "We'll show the exact price at checkout."
+savings = "You save {{amount}} · 2 months free."
+sizingRow = "Sizing"
+sizingValue = "{{label}} · {{desc}}"
+usersLabel = "Total users"
+
+[portal.billing.prepaid.consent]
+label = "I understand that when my prepaid capacity is used up or expires after 12 months, processing automatically continues at the standard metered pay-as-you-go rate (up to my spend limit) unless I cancel, and that I can cancel anytime from the billing portal."
+
+[portal.billing.prepaid.deploy]
+cloud = "Stirling Cloud"
+cloudDesc = "Managed by Stirling. Live in minutes."
+cloudValue = "Stirling Cloud · Managed"
+selfhost = "Self-hosted"
+selfhostDesc = "Runs on private infrastructure. Same rate."
+selfhostValue = "Self-hosted · Private infrastructure"
+
+[portal.billing.prepaid.offer]
+cta = "Review offer"
+subtitle = "Prepay a year of PDF processing and get two months free, used before metered billing, outside your spend limit."
+title = "Get 12 months for the price of 10"
+
+[portal.billing.prepaid.pay]
+accountName = "Account holder name"
+accountNamePlaceholder = "e.g. Jane Smith"
+companyName = "Company name (optional)"
+companyNamePlaceholder = "e.g. Acme Inc."
+downloadInvoice = "Download invoice"
+payOnline = "Pay online"
+poNumber = "PO number (optional)"
+poNumberPlaceholder = "e.g. PO-2026-0142"
+
+[portal.billing.prepaid.pipelines]
+advanced = "Advanced"
+advancedDesc = "Pipelines drive most of your processing."
+none = "None"
+noneDesc = "Not running pipelines yet. Turn them on any time."
+standard = "Standard"
+standardDesc = "A few pipelines re-process arriving PDFs."
+
+[portal.billing.prepaid.posture]
+essentials = "Essentials"
+essentialsDesc = "Classification, the default, plus Sharing"
+governed = "Governed"
+governedDesc = "Adds Security and Routing"
+regulated = "Regulated"
+regulatedDesc = "Every category, incl. Compliance, Retention, Ingestion"
+
+[portal.billing.prepaid.review]
+download = "Download quote (PDF)"
+downloading = "Preparing…"
+share = "share for approval"
+
+[portal.billing.prepaid.size]
+compact = "Compact"
+compactDesc = "Files under 25 MB, no data charges"
+heavy = "Heavy"
+heavyDesc = "Scanned or image-heavy, routinely 50 MB+"
+standard = "Standard"
+standardDesc = "Mostly small, some scans past 25 MB"
+
+[portal.billing.prepaid.state]
+exhausted = "Used up"
+healthy = "Plenty left"
+low = "Running low"
+
[portal.billing.spendLimit]
adjustLimit = "Adjust limit"
cancel = "Cancel"
@@ -6457,7 +6597,7 @@ capSuffixWithDocs = "/ month · ≈ {{documents}} documents"
displaySub = "You're only billed for what you process automatically — never past the ceiling."
editTitle = "Set your monthly ceiling"
eyebrow = "Spend limit"
-guardrailBody = "a hard ceiling — you're never billed past it. At the cap, metered processing pauses (unlimited PDF editing keeps working) until you raise it or the cycle resets. Nothing is lost."
+guardrailBody = "a hard ceiling; you're never billed past it. At the cap, metered processing pauses (unlimited PDF editing keeps working) until you raise it or the cycle resets. Nothing is lost."
guardrailLabel = "Your guardrail:"
noCap = "no cap"
pctUsed = "{{pct}}% used"
diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/Payg.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/Payg.tsx
index 53f4b98486..7774b6bc72 100644
--- a/frontend/editor/src/cloud/components/shared/config/configSections/Payg.tsx
+++ b/frontend/editor/src/cloud/components/shared/config/configSections/Payg.tsx
@@ -16,7 +16,7 @@
* V1 — so it shows a real empty state, not fabricated rows
*/
import React, { useState } from "react";
-import { Group, Stack, Text } from "@mantine/core";
+import { Alert, Badge, Group, Stack, Text } from "@mantine/core";
import { Button } from "@app/ui/Button";
import { useRenderCount } from "@app/hooks/useRenderCount";
import OpenInNewIcon from "@mui/icons-material/OpenInNew";
@@ -27,6 +27,10 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMoreRounded";
import BoltIcon from "@mui/icons-material/BoltRounded";
import AllInclusiveIcon from "@mui/icons-material/AllInclusiveRounded";
import { alert as showToast } from "@app/components/toast";
+import {
+ PrepaidCapacityMeterPanel,
+ prepaidSnapshotFromWallet,
+} from "@app/components/shared/config/configSections/usageMeters";
// Relative (not @app/*) so the co-located CSS + sibling component resolve directly.
// eslint-disable-next-line no-restricted-imports
import "./Payg.css";
@@ -665,6 +669,59 @@ function StripePortalLink({
);
}
+// ─── Prepaid bundle ───────────────────────────────────────────────────────
+
+function daysUntil(iso: string | null): number | null {
+ if (!iso) return null;
+ const end = new Date(iso).getTime();
+ if (Number.isNaN(end)) return null;
+ return Math.ceil((end - Date.now()) / 86_400_000);
+}
+
+/**
+ * Contextual nudge when prepaid capacity is running low, exhausted, or its term
+ * is nearly up (the demo's "top up to keep processing" strip). Leader-only CTA —
+ * members can't buy. Returns null when nothing needs saying.
+ */
+function PrepaidBanner({
+ snap,
+}: {
+ snap: NonNullable<ReturnType<typeof prepaidSnapshotFromWallet>>;
+}) {
+ const { t } = useTranslation();
+ const pctLeft = snap.total > 0 ? (snap.remaining / snap.total) * 100 : 0;
+ const days = daysUntil(snap.expiresAt);
+ const exhausted = snap.remaining <= 0;
+ const low = !exhausted && pctLeft <= 20;
+ const expiringSoon = days != null && days >= 0 && days <= 30;
+ if (!exhausted && !low && !expiringSoon) return null;
+
+ const message = exhausted
+ ? t(
+ "payg.prepaid.banner.exhausted",
+ "Your prepaid capacity is used up — metered billing has resumed. Top up to keep the discount.",
+ )
+ : low
+ ? t(
+ "payg.prepaid.banner.low",
+ "You're down to {{pct}}% of your prepaid capacity. Top up any time to keep processing uninterrupted.",
+ { pct: Math.max(1, Math.round(pctLeft)) },
+ )
+ : t(
+ "payg.prepaid.banner.expiring",
+ "Your prepaid year ends in {{count}} days. Unused capacity expires — top up to start a fresh year.",
+ // This arm only renders when expiringSoon (days is a valid number); ?? 0 satisfies the
+ // count option's number type.
+ { count: days ?? 0 },
+ );
+
+ return (
+ <Alert color={exhausted ? "red" : "yellow"} variant="light">
+ <span>{message}</span>
+ </Alert>
+ );
+}
+
// ─── Main component ───────────────────────────────────────────────────────
const Payg: React.FC<PaygProps> = ({
@@ -676,6 +733,10 @@ const Payg: React.FC<PaygProps> = ({
useRenderCount(role === "LEADER" ? "PaygLeader" : "PaygMember");
const { t } = useTranslation();
const isLeader = role === "LEADER";
+ const prepaid = prepaidSnapshotFromWallet(wallet);
+ // Read-only prepaid display. The buy/top-up flow lives on the portal Processor page (the
+ // create-payg-bundle-checkout edge fn is driven from there); this editor Plan page only shows an
+ // existing prepaid balance and is slated for removal on a separate branch.
const fmt = (iso: string) =>
new Date(iso).toLocaleDateString(undefined, {
@@ -686,6 +747,8 @@ const Payg: React.FC<PaygProps> = ({
return (
<div className="payg">
<Stack gap="md">
+ {prepaid && <PrepaidBanner snap={prepaid} />}
+
{/* The modal chrome already renders the section title ("Billing &
usage"), so we lead with the descriptive subtitle + role pill. */}
<div className="payg-planhead">
@@ -700,11 +763,18 @@ const Payg: React.FC<PaygProps> = ({
},
)}
</span>
- <span className="payg-role-pill" data-leader={isLeader}>
- {isLeader
- ? t("payg.role.leader", "Team owner")
- : t("payg.role.member", "Member")}
- </span>
+ <Group gap="xs" wrap="nowrap">
+ {wallet.billingMode === "prepaid" && (
+ <Badge color="blue" variant="light" radius="sm">
+ {t("payg.prepaid.chip", "Prepaid year")}
+ </Badge>
+ )}
+ <span className="payg-role-pill" data-leader={isLeader}>
+ {isLeader
+ ? t("payg.role.leader", "Team owner")
+ : t("payg.role.member", "Member")}
+ </span>
+ </Group>
</div>
<div className="payg-planhead__split">
@@ -751,6 +821,25 @@ const Payg: React.FC<PaygProps> = ({
<UsageHero wallet={wallet} />
+ {prepaid && (
+ <div className="payg-card">
+ <Stack gap="sm">
+ <div>
+ <div className="payg-card__title">
+ {t("payg.prepaid.card.title", "Prepaid capacity")}
+ </div>
+ <div className="payg-card__subtitle">
+ {t(
+ "payg.prepaid.card.subtitle",
+ "Used before metered billing and outside your spend cap.",
+ )}
+ </div>
+ </div>
+ <PrepaidCapacityMeterPanel snap={prepaid} />
+ </Stack>
+ </div>
+ )}
+
{isLeader ? (
<CapEditor
capUsd={wallet.capUsd}
diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/SpendCapControl.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/SpendCapControl.tsx
index 654691c2fc..d6b8b336f4 100644
--- a/frontend/editor/src/cloud/components/shared/config/configSections/SpendCapControl.tsx
+++ b/frontend/editor/src/cloud/components/shared/config/configSections/SpendCapControl.tsx
@@ -43,11 +43,11 @@ const SpendCapControl: React.FC<SpendCapControlProps> = ({
noCap: t("payg.cap.noCapLabel", "No cap"),
save: saveLabel ?? t("payg.cap.save", "Update cap"),
docsEstimate: (docs) =>
- t("payg.cap.docsEstimate", "≈ {{docs}} processed PDFs / month", {
+ t("payg.cap.docsEstimate", "≈ {{docs}} credits / month", {
docs,
}),
docsRate: (rate) =>
- t("payg.cap.docsRate", "at {{rate}} / PDF", { rate }),
+ t("payg.cap.docsRate", "at {{rate}} / credit", { rate }),
noCapDesc: t(
"payg.cap.noCapDesc",
"Usage is billed without an upper limit. You can re-enable a cap at any time.",
diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.css b/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.css
index 46df9ddee4..54f4113f8f 100644
--- a/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.css
+++ b/frontend/editor/src/cloud/components/shared/config/configSections/UpgradeModal.css
@@ -208,6 +208,13 @@
margin: 0 0 14px;
line-height: 1.45;
}
+/* Field caption above a segmented control in the bundle calculator. */
+.upm-field-label {
+ font-size: 0.8rem;
+ font-weight: 600;
+ color: var(--upm-text);
+ margin-bottom: 6px;
+}
/* Cap selection (presets + custom + no-cap + estimate) now lives in the shared
SpendCapControl (SpendCapControl.css). The old upm-cap-* / upm-no-cap-toggle
diff --git a/frontend/editor/src/cloud/components/shared/config/configSections/usageMeters.tsx b/frontend/editor/src/cloud/components/shared/config/configSections/usageMeters.tsx
index 4c8804027c..cb6eb511c9 100644
--- a/frontend/editor/src/cloud/components/shared/config/configSections/usageMeters.tsx
+++ b/frontend/editor/src/cloud/components/shared/config/configSections/usageMeters.tsx
@@ -7,7 +7,12 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useWallet, type Wallet } from "@app/hooks/useWallet";
-import { currencySymbol, MeterBar, meterState } from "@app/billing";
+import {
+ currencySymbol,
+ formatPeriodDate,
+ MeterBar,
+ meterState,
+} from "@app/billing";
import "@app/components/shared/config/configSections/Payg.css";
import "@app/components/shared/config/configSections/PaygFree.css";
@@ -139,3 +144,73 @@ export function SpendCapMeterPanel({ snap }: { snap: SpendCapSnapshot }) {
/>
);
}
+
+// ─── Prepaid bundle capacity meter ──────────────────────────────────────────
+
+export interface PrepaidSnapshot {
+ /** Prepaid units still available across the team's in-term pools. */
+ remaining: number;
+ /** Total capacity of in-term pools — the "X of Y" denominator. */
+ total: number;
+ /** ISO date the soonest pool expires; null when no bundle. */
+ expiresAt: string | null;
+}
+
+/**
+ * Derive the prepaid-capacity snapshot from a wallet. Returns null when the team
+ * holds no in-term bundle ({@code prepaidUnitsTotal === 0}) so callers can skip
+ * the card entirely rather than render an empty meter.
+ */
+export function prepaidSnapshotFromWallet(
+ wallet: Wallet | null,
+): PrepaidSnapshot | null {
+ if (!wallet || wallet.prepaidUnitsTotal <= 0) return null;
+ return {
+ remaining: wallet.prepaidUnitsRemaining,
+ total: wallet.prepaidUnitsTotal,
+ expiresAt: wallet.prepaidExpiresAt,
+ };
+}
+
+/**
+ * Prepaid capacity meter. The bar fills as the pool is drawn down ({@code used =
+ * total − remaining}), so it WARNs when the pool is running low and DEGRADEs once
+ * exhausted — same bands as the free/cap meters. Prepaid is consumed ahead of the
+ * meter and outside the spend cap, so it reads as its own dimension.
+ */
+export function PrepaidCapacityMeterPanel({ snap }: { snap: PrepaidSnapshot }) {
+ const { t } = useTranslation();
+ const used = Math.max(0, snap.total - snap.remaining);
+ const { state, pct } = meterState(used, snap.total);
+ const stateLabel =
+ state === "DEGRADED"
+ ? t("payg.prepaid.state.exhausted", "Used up")
+ : state === "WARNED"
+ ? t("payg.prepaid.state.low", "Running low")
+ : t("payg.prepaid.state.healthy", "Plenty left");
+
+ return (
+ <MeterBar
+ state={state}
+ pct={pct}
+ figure={snap.remaining.toLocaleString()}
+ capSuffix={t(
+ "payg.prepaid.meter.capSuffix",
+ "of {{total}} prepaid PDFs",
+ {
+ total: snap.total.toLocaleString(),
+ },
+ )}
+ statusLabel={stateLabel}
+ meta={
+ snap.expiresAt ? (
+ <span>
+ {t("payg.prepaid.meter.expires", "Expires {{date}}", {
+ date: formatPeriodDate(snap.expiresAt, { year: true }),
+ })}
+ </span>
+ ) : undefined
+ }
+ />
+ );
+}
diff --git a/frontend/editor/src/cloud/hooks/useWallet.ts b/frontend/editor/src/cloud/hooks/useWallet.ts
index 0641535946..ccef26a8bc 100644
--- a/frontend/editor/src/cloud/hooks/useWallet.ts
+++ b/frontend/editor/src/cloud/hooks/useWallet.ts
@@ -136,7 +136,11 @@ function reuseIfEqual(prev: Wallet | null, next: Wallet): Wallet {
prev.spendUnitsThisPeriod !== next.spendUnitsThisPeriod ||
prev.docsProcessedThisPeriod !== next.docsProcessedThisPeriod ||
prev.uniquePdfsThisPeriod !== next.uniquePdfsThisPeriod ||
- prev.sizeMultiplierPdfsThisPeriod !== next.sizeMultiplierPdfsThisPeriod
+ prev.sizeMultiplierPdfsThisPeriod !== next.sizeMultiplierPdfsThisPeriod ||
+ prev.billingMode !== next.billingMode ||
+ prev.prepaidUnitsRemaining !== next.prepaidUnitsRemaining ||
+ prev.prepaidUnitsTotal !== next.prepaidUnitsTotal ||
+ prev.prepaidExpiresAt !== next.prepaidExpiresAt
) {
return next;
}
diff --git a/frontend/editor/src/portal/billing/stripe.test.ts b/frontend/editor/src/portal/billing/stripe.test.ts
index 53a732fb63..5b6d97b9f9 100644
--- a/frontend/editor/src/portal/billing/stripe.test.ts
+++ b/frontend/editor/src/portal/billing/stripe.test.ts
@@ -5,9 +5,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
* already-subscribed-redirect vs neither-secret-nor-url mapping, the mock flag,
* unconfigured Supabase, and the portal-session path.
*/
-const { getClient, invoke } = vi.hoisted(() => ({
+const { getClient, invoke, rpc } = vi.hoisted(() => ({
getClient: vi.fn(),
invoke: vi.fn(),
+ rpc: vi.fn(),
}));
vi.mock("@portal/auth/saasSupabase", () => ({ ensureSaasSupabase: vi.fn() }));
@@ -17,16 +18,24 @@ vi.mock("@app/auth/supabase/supabaseClient", () => ({
}));
import {
+ acceptBundleStripeQuote,
+ cancelBundleQuote,
+ createBundleStripeQuote,
createCheckoutSession,
createPortalSession,
+ fetchBundleQuotePdf,
+ finalizeBundleInvoice,
+ getLatestBundleQuote,
StripeFunctionError,
+ upsertBundleQuote,
} from "@portal/billing/stripe";
const req = { teamId: 1, successUrl: "s", cancelUrl: "c" } as const;
beforeEach(() => {
invoke.mockReset();
- getClient.mockReset().mockReturnValue({ functions: { invoke } });
+ rpc.mockReset();
+ getClient.mockReset().mockReturnValue({ functions: { invoke }, rpc });
});
afterEach(() => vi.restoreAllMocks());
@@ -41,7 +50,6 @@ describe("createCheckoutSession", () => {
clientSecret: "cs_123",
redirectUrl: null,
alreadySubscribed: false,
- mock: false,
});
});
@@ -60,14 +68,6 @@ describe("createCheckoutSession", () => {
expect(s.clientSecret).toBeNull();
});
- it("flags a mock client secret", async () => {
- invoke.mockResolvedValue({
- data: { success: true, client_secret: "cs_mock_abc" },
- error: null,
- });
- expect((await createCheckoutSession(req)).mock).toBe(true);
- });
-
it("throws when success is false", async () => {
invoke.mockResolvedValue({
data: { success: false, error: "no team" },
@@ -91,6 +91,276 @@ describe("createCheckoutSession", () => {
});
});
+describe("createBundleStripeQuote", () => {
+ it("sends team_id + quote_id (+ po_number) and maps the Stripe quote handles", async () => {
+ invoke.mockResolvedValue({
+ data: {
+ success: true,
+ stripe_quote_id: "qt_1",
+ stripe_quote_number: "QT-0007",
+ },
+ error: null,
+ });
+ const q = await createBundleStripeQuote({
+ teamId: 1,
+ quoteId: 7,
+ poNumber: "PO-9",
+ });
+ expect(q).toEqual({ stripeQuoteId: "qt_1", stripeQuoteNumber: "QT-0007" });
+ const [name, opts] = invoke.mock.calls[0];
+ expect(name).toBe("create-payg-bundle-quote");
+ expect(opts.body).toMatchObject({
+ team_id: 1,
+ quote_id: 7,
+ po_number: "PO-9",
+ });
+ });
+
+ it("throws when the edge fn reports failure", async () => {
+ invoke.mockResolvedValue({
+ data: { success: false, error: "bundle_pricing_not_configured" },
+ error: null,
+ });
+ await expect(
+ createBundleStripeQuote({ teamId: 1, quoteId: 7 }),
+ ).rejects.toThrow(/bundle_pricing_not_configured/);
+ });
+});
+
+describe("acceptBundleStripeQuote", () => {
+ it("maps the invoice response and sends quote_id", async () => {
+ invoke.mockResolvedValue({
+ data: {
+ success: true,
+ invoice_id: "in_1",
+ hosted_invoice_url: "https://pay/in_1",
+ invoice_pdf: "https://pdf/in_1",
+ status: "open",
+ },
+ error: null,
+ });
+ const inv = await acceptBundleStripeQuote({ teamId: 1, quoteId: 7 });
+ expect(inv).toEqual({
+ invoiceId: "in_1",
+ hostedInvoiceUrl: "https://pay/in_1",
+ invoicePdf: "https://pdf/in_1",
+ status: "open",
+ });
+ const [name, opts] = invoke.mock.calls[0];
+ expect(name).toBe("accept-payg-bundle-quote");
+ expect(opts.body).toMatchObject({ team_id: 1, quote_id: 7 });
+ });
+
+ it("throws when the edge fn reports failure", async () => {
+ invoke.mockResolvedValue({
+ data: { success: false, error: "quote_not_issued" },
+ error: null,
+ });
+ await expect(
+ acceptBundleStripeQuote({ teamId: 1, quoteId: 7 }),
+ ).rejects.toThrow(/quote_not_issued/);
+ });
+});
+
+describe("cancelBundleQuote", () => {
+ it("sends team_id + quote_id and resolves on success", async () => {
+ invoke.mockResolvedValue({ data: { success: true }, error: null });
+ await cancelBundleQuote({ teamId: 1, quoteId: 7 });
+ const [name, opts] = invoke.mock.calls[0];
+ expect(name).toBe("cancel-payg-bundle-quote");
+ expect(opts.body).toMatchObject({ team_id: 1, quote_id: 7 });
+ });
+
+ it("throws when the edge fn reports failure (e.g. already paid)", async () => {
+ invoke.mockResolvedValue({
+ data: { success: false, error: "invoice_already_paid" },
+ error: null,
+ });
+ await expect(cancelBundleQuote({ teamId: 1, quoteId: 7 })).rejects.toThrow(
+ /invoice_already_paid/,
+ );
+ });
+});
+
+describe("fetchBundleQuotePdf", () => {
+ it("returns the PDF blob from the GET route", async () => {
+ const blob = new Blob(["%PDF"], { type: "application/pdf" });
+ invoke.mockResolvedValue({ data: blob, error: null });
+ const out = await fetchBundleQuotePdf(7);
+ expect(out).toBe(blob);
+ const [name, opts] = invoke.mock.calls[0];
+ expect(name).toBe("create-payg-bundle-quote?quote_id=7");
+ expect(opts.method).toBe("GET");
+ });
+
+ it("throws when the response is not a file", async () => {
+ invoke.mockResolvedValue({ data: { success: false }, error: null });
+ await expect(fetchBundleQuotePdf(7)).rejects.toBeInstanceOf(
+ StripeFunctionError,
+ );
+ });
+});
+
+describe("upsertBundleQuote", () => {
+ const quoteInput = {
+ teamId: 1,
+ users: 25,
+ posturePolicies: 4,
+ sizeMult: 1.2,
+ pipelineMult: 1,
+ provisionedMonthlyVolume: 10000,
+ poolCredits: 576000,
+ priceMinor: 480000,
+ currency: "usd",
+ consented: true,
+ eulaVersion: "2026-07-draft",
+ } as const;
+
+ it("maps the RPC row and sends p_* args (create — no p_quote_id)", async () => {
+ rpc.mockResolvedValue({
+ data: [
+ {
+ quote_id: 7,
+ status: "issued",
+ valid_until: "2026-08-16T00:00:00Z",
+ },
+ ],
+ error: null,
+ });
+ const q = await upsertBundleQuote(quoteInput);
+ expect(q).toEqual({
+ quoteId: 7,
+ status: "issued",
+ validUntil: "2026-08-16T00:00:00Z",
+ });
+ const [fn, args] = rpc.mock.calls[0];
+ expect(fn).toBe("payg_upsert_bundle_quote");
+ expect(args).toMatchObject({
+ p_team_id: 1,
+ p_posture_policies: 4,
+ p_size_mult: 1.2,
+ p_pipeline_mult: 1,
+ p_pool_credits: 576000,
+ p_users: 25,
+ p_price_minor: 480000,
+ p_currency: "usd",
+ p_consented: true,
+ p_eula_version: "2026-07-draft",
+ });
+ expect(args).not.toHaveProperty("p_quote_id");
+ });
+
+ it("passes p_quote_id when editing an existing quote", async () => {
+ rpc.mockResolvedValue({
+ data: [{ quote_id: 7, status: "issued", valid_until: "x" }],
+ error: null,
+ });
+ await upsertBundleQuote({ ...quoteInput, quoteId: 7 });
+ expect(rpc.mock.calls[0][1]).toMatchObject({ p_quote_id: 7 });
+ });
+
+ it("throws a StripeFunctionError (with code) on an RPC error", async () => {
+ rpc.mockResolvedValue({
+ data: null,
+ error: { message: "not a leader", code: "42501" },
+ });
+ const err = await upsertBundleQuote(quoteInput).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(StripeFunctionError);
+ expect((err as StripeFunctionError).code).toBe("42501");
+ });
+});
+
+describe("finalizeBundleInvoice", () => {
+ it("maps the invoice response and sends quote_id (+ optional po_number)", async () => {
+ invoke.mockResolvedValue({
+ data: {
+ success: true,
+ invoice_id: "in_1",
+ hosted_invoice_url: "https://pay/in_1",
+ invoice_pdf: "https://pdf/in_1",
+ status: "open",
+ },
+ error: null,
+ });
+ const inv = await finalizeBundleInvoice({
+ teamId: 1,
+ quoteId: 7,
+ poNumber: "PO-9",
+ });
+ expect(inv).toEqual({
+ invoiceId: "in_1",
+ hostedInvoiceUrl: "https://pay/in_1",
+ invoicePdf: "https://pdf/in_1",
+ status: "open",
+ });
+ const [name, opts] = invoke.mock.calls[0];
+ expect(name).toBe("finalize-payg-bundle-invoice");
+ expect(opts.body).toMatchObject({
+ team_id: 1,
+ quote_id: 7,
+ po_number: "PO-9",
+ });
+ });
+
+ it("throws when the edge fn reports failure", async () => {
+ invoke.mockResolvedValue({
+ data: { success: false, error: "quote_not_accepted" },
+ error: null,
+ });
+ await expect(
+ finalizeBundleInvoice({ teamId: 1, quoteId: 7 }),
+ ).rejects.toThrow(/quote_not_accepted/);
+ });
+});
+
+describe("getLatestBundleQuote", () => {
+ it("maps the latest open quote row (numeric size_mult coerced)", async () => {
+ rpc.mockResolvedValue({
+ data: [
+ {
+ quote_id: 7,
+ users: 25,
+ posture_policies: 4,
+ size_mult: "1.2",
+ pipeline_mult: 1,
+ pool_credits: 576000,
+ price_minor: 480000,
+ currency: "usd",
+ consented_at: "2026-07-17T00:00:00Z",
+ stripe_quote_id: "qt_1",
+ stripe_quote_number: "QT-0007",
+ stripe_ref: "in_1",
+ valid_until: "2026-08-16T00:00:00Z",
+ },
+ ],
+ error: null,
+ });
+ const q = await getLatestBundleQuote(1);
+ expect(q).toEqual({
+ quoteId: 7,
+ users: 25,
+ posturePolicies: 4,
+ sizeMult: 1.2,
+ pipelineMult: 1,
+ poolCredits: 576000,
+ priceMinor: 480000,
+ currency: "usd",
+ consentedAt: "2026-07-17T00:00:00Z",
+ stripeQuoteId: "qt_1",
+ stripeQuoteNumber: "QT-0007",
+ stripeRef: "in_1",
+ validUntil: "2026-08-16T00:00:00Z",
+ });
+ expect(rpc.mock.calls[0][0]).toBe("payg_get_latest_bundle_quote");
+ expect(rpc.mock.calls[0][1]).toEqual({ p_team_id: 1 });
+ });
+
+ it("returns null when the team has no open quote", async () => {
+ rpc.mockResolvedValue({ data: [], error: null });
+ expect(await getLatestBundleQuote(1)).toBeNull();
+ });
+});
+
describe("createPortalSession", () => {
it("returns the portal URL", async () => {
invoke.mockResolvedValue({
diff --git a/frontend/editor/src/portal/billing/stripe.ts b/frontend/editor/src/portal/billing/stripe.ts
index 930ed3fef3..8b9690d3f6 100644
--- a/frontend/editor/src/portal/billing/stripe.ts
+++ b/frontend/editor/src/portal/billing/stripe.ts
@@ -1,3 +1,4 @@
+import type { Stripe } from "@stripe/stripe-js";
import { getSupabaseClient } from "@app/auth/supabase/supabaseClient";
import { ensureSaasSupabase } from "@portal/auth/saasSupabase";
@@ -53,7 +54,6 @@ interface CheckoutResponse {
url?: string;
portal_url?: string;
already_subscribed?: boolean;
- mock?: boolean;
error?: string;
}
@@ -87,6 +87,158 @@ async function invoke<T>(
return data;
}
+/** Call a SECURITY DEFINER public.* RPC with the admin's JWT (same client as {@link invoke}). */
+async function rpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {
+ ensureSaasSupabase();
+ const supabase = getSupabaseClient();
+ if (!supabase) {
+ throw new StripeFunctionError(
+ "SaaS Supabase not configured — set VITE_SUPABASE_URL.",
+ "unconfigured",
+ );
+ }
+ const { data, error } = await supabase.rpc(fn, args);
+ if (error) {
+ throw new StripeFunctionError(
+ error.message ?? `RPC ${fn} failed`,
+ (error as { code?: string }).code,
+ );
+ }
+ return data as T;
+}
+
+/** Inputs to {@link upsertBundleQuote} — the sized config + computed figures. */
+export interface BundleQuoteInput {
+ teamId: number;
+ users: number;
+ posturePolicies: number;
+ sizeMult: number;
+ pipelineMult: number;
+ provisionedMonthlyVolume: number;
+ /** Size-folded run-credits = the Stripe line quantity when this quote is paid. */
+ poolCredits: number;
+ /** Discounted total in minor units; null when the per-run rate is unknown. */
+ priceMinor: number | null;
+ currency: string;
+ /** Affirmative consent to the prepaid→metered auto-transition (ARL/EULA §7.2). */
+ consented: boolean;
+ eulaVersion: string;
+ /** When set, edits that existing (unpaid) quote instead of creating a new one. */
+ quoteId?: number;
+}
+
+/** A persisted prepaid-bundle quote (proforma) — {@code payg_upsert_bundle_quote} result. */
+export interface BundleQuote {
+ quoteId: number;
+ status: string;
+ validUntil: string;
+}
+
+interface BundleQuoteRow {
+ quote_id: number;
+ status: string;
+ valid_until: string;
+}
+
+/**
+ * Create (or edit an unpaid) prepaid-bundle quote via {@code payg_upsert_bundle_quote}. LEADER-gated
+ * server-side. The quote persists the sized config + figures so the buyer can download a numbered
+ * proforma to share for approval and check out against it later; capacity is still credited only on
+ * payment (the webhook), never here.
+ */
+export async function upsertBundleQuote(
+ input: BundleQuoteInput,
+): Promise<BundleQuote> {
+ const rows = await rpc<BundleQuoteRow[]>("payg_upsert_bundle_quote", {
+ p_team_id: input.teamId,
+ p_posture_policies: input.posturePolicies,
+ p_size_mult: input.sizeMult,
+ p_pipeline_mult: input.pipelineMult,
+ p_pool_credits: input.poolCredits,
+ p_users: input.users,
+ p_provisioned_monthly_volume: input.provisionedMonthlyVolume,
+ p_price_minor: input.priceMinor,
+ p_currency: input.currency,
+ p_consented: input.consented,
+ p_eula_version: input.eulaVersion,
+ ...(input.quoteId != null ? { p_quote_id: input.quoteId } : {}),
+ });
+ const row = rows?.[0];
+ if (!row) {
+ throw new StripeFunctionError("payg_upsert_bundle_quote returned no row");
+ }
+ return {
+ quoteId: row.quote_id,
+ status: row.status,
+ validUntil: row.valid_until,
+ };
+}
+
+/** A team's latest open bundle quote — {@code payg_get_latest_bundle_quote} result, for resume. */
+export interface LatestBundleQuote {
+ quoteId: number;
+ users: number | null;
+ posturePolicies: number;
+ sizeMult: number;
+ pipelineMult: number;
+ poolCredits: number;
+ priceMinor: number | null;
+ currency: string | null;
+ consentedAt: string | null;
+ stripeQuoteId: string | null;
+ stripeQuoteNumber: string | null;
+ /** The generated invoice id, set once the quote is accepted — lets the modal resume to the pay step. */
+ stripeRef: string | null;
+ validUntil: string;
+}
+
+interface LatestBundleQuoteRow {
+ quote_id: number;
+ users: number | null;
+ posture_policies: number;
+ size_mult: number | string;
+ pipeline_mult: number;
+ pool_credits: number;
+ price_minor: number | null;
+ currency: string | null;
+ consented_at: string | null;
+ stripe_quote_id: string | null;
+ stripe_quote_number: string | null;
+ stripe_ref: string | null;
+ valid_until: string;
+}
+
+/**
+ * Fetch the team's most-recent OPEN (draft/issued, unexpired) bundle quote via
+ * {@code payg_get_latest_bundle_quote}, so the modal can resume it instead of minting a fresh Stripe
+ * quote on every reopen. Returns null when the team has none.
+ */
+export async function getLatestBundleQuote(
+ teamId: number,
+): Promise<LatestBundleQuote | null> {
+ const rows = await rpc<LatestBundleQuoteRow[]>(
+ "payg_get_latest_bundle_quote",
+ { p_team_id: teamId },
+ );
+ const row = rows?.[0];
+ if (!row) return null;
+ return {
+ quoteId: row.quote_id,
+ users: row.users,
+ posturePolicies: row.posture_policies,
+ sizeMult: Number(row.size_mult),
+ pipelineMult: row.pipeline_mult,
+ poolCredits: row.pool_credits,
+ priceMinor: row.price_minor,
+ currency: row.currency,
+ consentedAt: row.consented_at,
+ stripeQuoteId: row.stripe_quote_id,
+ stripeQuoteNumber: row.stripe_quote_number,
+ stripeRef: row.stripe_ref,
+ validUntil: row.valid_until,
+ };
+}
+
/**
* Result of {@link createCheckoutSession}. Exactly ONE of {@code clientSecret}
* or {@code redirectUrl} is set: clientSecret drives embedded Stripe Checkout
@@ -97,7 +249,6 @@ export interface CheckoutSession {
clientSecret: string | null;
redirectUrl: string | null;
alreadySubscribed: boolean;
- mock: boolean;
}
/**
@@ -144,13 +295,207 @@ export async function createCheckoutSession(
clientSecret,
redirectUrl,
alreadySubscribed,
- mock: Boolean(res.mock) || clientSecret?.startsWith("cs_mock_") === true,
};
}
-/** {@code VITE_STRIPE_PUBLISHABLE_KEY} — the Stripe pk used by embedded Checkout. */
+/** Result of {@link createBundleStripeQuote} — the Stripe-issued quote handles. */
+export interface BundleStripeQuote {
+ stripeQuoteId: string;
+ stripeQuoteNumber: string | null;
+}
+
+interface BundleStripeQuoteRequest {
+ teamId: number;
+ /** The persisted quote row (from {@link upsertBundleQuote}) to turn into a Stripe quote. */
+ quoteId: number;
+ /** Optional PO number printed on the quote + carried to the eventual invoice. */
+ poNumber?: string;
+ /** Net terms for the eventual invoice; defaults to 30 on the server. */
+ daysUntilDue?: number;
+}
+
+interface BundleStripeQuoteResponse {
+ success?: boolean;
+ stripe_quote_id?: string;
+ stripe_quote_number?: string | null;
+ error?: string;
+}
+
+/**
+ * Create + finalize the Stripe QUOTE backing a persisted quote row, via {@code create-payg-bundle-quote}.
+ * The customer-facing quote number + PDF are Stripe's. On edit the server cancels the prior Stripe quote
+ * and issues a new one. Capacity is credited only when the accepted quote's invoice is PAID (the webhook).
+ */
+export async function createBundleStripeQuote(
+ req: BundleStripeQuoteRequest,
+): Promise<BundleStripeQuote> {
+ const res = await invoke<BundleStripeQuoteResponse>(
+ "create-payg-bundle-quote",
+ {
+ team_id: req.teamId,
+ quote_id: req.quoteId,
+ ...(req.poNumber ? { po_number: req.poNumber } : {}),
+ ...(req.daysUntilDue != null ? { days_until_due: req.daysUntilDue } : {}),
+ },
+ );
+ if (!res.success || !res.stripe_quote_id) {
+ throw new StripeFunctionError(
+ res.error ?? "create-payg-bundle-quote failed",
+ );
+ }
+ return {
+ stripeQuoteId: res.stripe_quote_id,
+ stripeQuoteNumber: res.stripe_quote_number ?? null,
+ };
+}
+
+/** A raised Stripe invoice — the {@code accept-payg-bundle-quote} result. */
+export interface BundleInvoice {
+ invoiceId: string;
+ /** Stripe-hosted page where the buyer pays / downloads the invoice. */
+ hostedInvoiceUrl: string | null;
+ invoicePdf: string | null;
+ status: string | null;
+}
+
+interface BundleInvoiceResponse {
+ success?: boolean;
+ invoice_id?: string;
+ hosted_invoice_url?: string | null;
+ invoice_pdf?: string | null;
+ status?: string | null;
+ error?: string;
+}
+
+/**
+ * Accept the Stripe quote for a persisted quote row, via {@code accept-payg-bundle-quote}. Acceptance
+ * generates the net-terms invoice as a DRAFT (auto_advance off) and returns the hosted URL; the
+ * payment step ({@link finalizeBundleInvoice}) stamps the recipient + PO and finalizes it. Payable by
+ * card on the hosted page, or by bank transfer / PO. Capacity is credited only on invoice.paid.
+ */
+export async function acceptBundleStripeQuote(req: {
+ teamId: number;
+ quoteId: number;
+}): Promise<BundleInvoice> {
+ const res = await invoke<BundleInvoiceResponse>("accept-payg-bundle-quote", {
+ team_id: req.teamId,
+ quote_id: req.quoteId,
+ });
+ if (!res.success || !res.invoice_id) {
+ throw new StripeFunctionError(
+ res.error ?? "accept-payg-bundle-quote failed",
+ );
+ }
+ return {
+ invoiceId: res.invoice_id,
+ hostedInvoiceUrl: res.hosted_invoice_url ?? null,
+ invoicePdf: res.invoice_pdf ?? null,
+ status: res.status ?? null,
+ };
+}
+
+/**
+ * Finalize the accepted bundle invoice (stamping an optional PO), via {@code finalize-payg-bundle-invoice}.
+ * Returns the hosted checkout URL + PDF. Called by both Download-invoice and Pay-online; idempotent
+ * server-side (an already-finalized invoice comes back as-is, PO locked).
+ */
+export async function finalizeBundleInvoice(req: {
+ teamId: number;
+ quoteId: number;
+ poNumber?: string;
+ /** Optional company — becomes the invoice bill-to name (no length cap). */
+ companyName?: string;
+ /** Required account-holder name — the bill-to when there's no company, else an "Account holder" field. */
+ accountName?: string;
+}): Promise<BundleInvoice> {
+ const res = await invoke<BundleInvoiceResponse>(
+ "finalize-payg-bundle-invoice",
+ {
+ team_id: req.teamId,
+ quote_id: req.quoteId,
+ ...(req.poNumber ? { po_number: req.poNumber } : {}),
+ ...(req.companyName ? { company_name: req.companyName } : {}),
+ ...(req.accountName ? { account_name: req.accountName } : {}),
+ },
+ );
+ if (!res.success || !res.invoice_id) {
+ throw new StripeFunctionError(
+ res.error ?? "finalize-payg-bundle-invoice failed",
+ );
+ }
+ return {
+ invoiceId: res.invoice_id,
+ hostedInvoiceUrl: res.hosted_invoice_url ?? null,
+ invoicePdf: res.invoice_pdf ?? null,
+ status: res.status ?? null,
+ };
+}
+
+/**
+ * Cancel an unpaid prepaid-bundle purchase via {@code cancel-payg-bundle-quote}: the edge fn voids the
+ * invoice (delete if draft, void if finalized), best-effort cancels the Stripe quote, and voids the quote
+ * row so the buyer can start over. Nothing was charged (capacity is credited on invoice.paid), so there's
+ * no refund. Throws a StripeFunctionError on failure (e.g. {@code invoice_already_paid}).
+ */
+export async function cancelBundleQuote(req: {
+ teamId: number;
+ quoteId: number;
+}): Promise<void> {
+ const res = await invoke<{ success?: boolean; error?: string }>(
+ "cancel-payg-bundle-quote",
+ { team_id: req.teamId, quote_id: req.quoteId },
+ );
+ if (!res.success) {
+ throw new StripeFunctionError(
+ res.error ?? "cancel-payg-bundle-quote failed",
+ );
+ }
+}
+
+/**
+ * Fetch the Stripe-rendered quote PDF for a persisted quote, via the {@code create-payg-bundle-quote}
+ * GET route (streams application/pdf). Returns a Blob the caller can object-URL for download.
+ */
+export async function fetchBundleQuotePdf(quoteId: number): Promise<Blob> {
+ ensureSaasSupabase();
+ const supabase = getSupabaseClient();
+ if (!supabase) {
+ throw new StripeFunctionError(
+ "SaaS Supabase not configured — set VITE_SUPABASE_URL.",
+ "unconfigured",
+ );
+ }
+ const { data, error } = await supabase.functions.invoke<Blob>(
+ `create-payg-bundle-quote?quote_id=${quoteId}`,
+ { method: "GET" },
+ );
+ if (error) {
+ throw new StripeFunctionError(error.message ?? "quote PDF fetch failed");
+ }
+ if (!(data instanceof Blob)) {
+ throw new StripeFunctionError("quote PDF response was not a file");
+ }
+ return data;
+}
+
+/**
+ * {@code VITE_STRIPE_PUBLISHABLE_KEY} — the Stripe pk used by embedded Checkout. Coalesces to "" when
+ * unset so the declared `string` return type is honest (Vite substitutes `undefined` for a missing
+ * env var); callers guard with a falsy check.
+ */
export function getStripePublishableKey(): string {
- return import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY;
+ return import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY ?? "";
+}
+
+// Process-wide memoized Stripe.js loader, shared by the embedded-checkout modals so the SDK promise
+// is created once rather than per-modal. loadStripe is dynamically imported so its chunk only loads
+// when a checkout modal reaches its payment step.
+let stripePromise: Promise<Stripe | null> | null = null;
+export function loadStripeOnce(pk: string): Promise<Stripe | null> {
+ if (stripePromise === null) {
+ stripePromise = import("@stripe/stripe-js").then((m) => m.loadStripe(pk));
+ }
+ return stripePromise;
}
/**
diff --git a/frontend/editor/src/portal/components/billing/ActivationChoiceModal.stories.tsx b/frontend/editor/src/portal/components/billing/ActivationChoiceModal.stories.tsx
new file mode 100644
index 0000000000..c76c5ef21b
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/ActivationChoiceModal.stories.tsx
@@ -0,0 +1,20 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { ActivationChoiceModal } from "@portal/components/billing/ActivationChoiceModal";
+import "@portal/components/billing/billing.css";
+
+const meta: Meta<typeof ActivationChoiceModal> = {
+ title: "Portal/Billing/ActivationChoiceModal",
+ component: ActivationChoiceModal,
+ parameters: { layout: "fullscreen" },
+ args: {
+ open: true,
+ onClose: () => {},
+ onChoosePayg: () => {},
+ onChoosePrepay: () => {},
+ },
+};
+export default meta;
+type Story = StoryObj<typeof ActivationChoiceModal>;
+
+/** The "turn on the Processor" fork — pay as you go vs prepay a year. */
+export const Default: Story = {};
diff --git a/frontend/editor/src/portal/components/billing/ActivationChoiceModal.tsx b/frontend/editor/src/portal/components/billing/ActivationChoiceModal.tsx
new file mode 100644
index 0000000000..3b110fe187
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/ActivationChoiceModal.tsx
@@ -0,0 +1,119 @@
+import { useTranslation } from "react-i18next";
+import { Button, Card, Modal } from "@app/ui";
+import { PrepayModalHeader } from "@portal/components/billing/PrepayModalHeader";
+
+/** A clickable door-card (Card-as-button, matching ComponentCard's a11y pattern). */
+function DoorCard({
+ accent,
+ title,
+ badge,
+ sub,
+ ariaLabel,
+ onClick,
+}: {
+ accent?: boolean;
+ title: string;
+ badge?: string;
+ sub: string;
+ ariaLabel: string;
+ onClick: () => void;
+}) {
+ return (
+ <Card
+ interactive
+ padding="default"
+ role="button"
+ tabIndex={0}
+ aria-label={ariaLabel}
+ className={
+ "portal-billing__door" + (accent ? " portal-billing__door--accent" : "")
+ }
+ onClick={onClick}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ onClick();
+ }
+ }}
+ >
+ <span className="portal-billing__door-head">
+ <span className="portal-billing__door-title">{title}</span>
+ {badge && <span className="portal-billing__door-badge">{badge}</span>}
+ </span>
+ <span className="portal-billing__door-sub">{sub}</span>
+ </Card>
+ );
+}
+
+/**
+ * The "turn on the Processor" fork (demo D97): a free team chooses how to pay
+ * before any card is entered. Two door-cards, matching the demo —
+ *
+ * - Pay as you go → the metered subscription checkout (spend limit + card).
+ * - Prepay a year → the discounted bundle (calculator + one-time payment); the
+ * backend silently stands up the metered subscription off the saved card so
+ * metering resumes when the pool empties, so no spend-limit step is needed.
+ *
+ * Same per-PDF rate on both paths — prepay just front-loads two free months.
+ */
+export function ActivationChoiceModal({
+ open,
+ onClose,
+ onChoosePayg,
+ onChoosePrepay,
+}: {
+ open: boolean;
+ onClose: () => void;
+ onChoosePayg: () => void;
+ onChoosePrepay: () => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ width="md"
+ className="portal-billing__bundle-modal"
+ ariaLabel={t(
+ "portal.billing.activation.title",
+ "Switch on the Processor",
+ )}
+ >
+ <PrepayModalHeader
+ step={1}
+ title={t("portal.billing.activation.title", "Switch on the Processor")}
+ onClose={onClose}
+ />
+ <div className="portal-billing__door-grid">
+ <DoorCard
+ title={t("portal.billing.activation.payg.title", "Pay as you go")}
+ sub={t(
+ "portal.billing.activation.payg.sub",
+ "Set a monthly limit. Pay for what you run.",
+ )}
+ ariaLabel={t("portal.billing.activation.payg.title", "Pay as you go")}
+ onClick={onChoosePayg}
+ />
+ <DoorCard
+ accent
+ title={t("portal.billing.activation.prepay.title", "Prepay a year")}
+ badge={t("portal.billing.activation.prepay.badge", "2 months free")}
+ sub={t(
+ "portal.billing.activation.prepay.sub",
+ "One invoice, card or bank transfer.",
+ )}
+ ariaLabel={t(
+ "portal.billing.activation.prepay.title",
+ "Prepay a year",
+ )}
+ onClick={onChoosePrepay}
+ />
+ </div>
+ <div className="portal-billing__door-later">
+ <Button variant="quiet" onClick={onClose}>
+ {t("portal.billing.activation.maybeLater", "Maybe later")}
+ </Button>
+ </div>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.stories.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.stories.tsx
new file mode 100644
index 0000000000..07d1f2a000
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.stories.tsx
@@ -0,0 +1,45 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { useState } from "react";
+import { Button } from "@app/ui";
+import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";
+import {
+ prepaidWallet,
+ subscribedWallet,
+} from "@portal/components/billing/walletFixtures";
+import "@portal/components/billing/billing.css";
+
+// Direct checkout: no quote round-trip. With no Stripe key in Storybook, the pay step falls back
+// to the mock card placeholder + "Complete purchase" button (no network), so no MSW handler needed.
+const meta: Meta<typeof BundleCheckoutModal> = {
+ title: "Portal/Billing/BundleCheckoutModal",
+ component: BundleCheckoutModal,
+ parameters: { layout: "fullscreen" },
+};
+export default meta;
+type Story = StoryObj<typeof BundleCheckoutModal>;
+
+/** Opens on mount so the calculator step is visible without interaction. */
+function OpenOnMount({ wallet }: { wallet: typeof subscribedWallet }) {
+ const [open, setOpen] = useState(true);
+ return (
+ <div style={{ padding: 24 }}>
+ <Button onClick={() => setOpen(true)}>Open</Button>
+ <BundleCheckoutModal
+ open={open}
+ wallet={wallet}
+ onClose={() => setOpen(false)}
+ onComplete={() => setOpen(false)}
+ />
+ </div>
+ );
+}
+
+/** First purchase — the "Get 12 months for the price of 10" calculator. */
+export const FirstPurchase: Story = {
+ render: () => <OpenOnMount wallet={subscribedWallet} />,
+};
+
+/** Topping up an existing bundle — same flow, "Top up prepaid capacity" title. */
+export const TopUp: Story = {
+ render: () => <OpenOnMount wallet={prepaidWallet} />,
+};
diff --git a/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx
new file mode 100644
index 0000000000..6bb442f6ed
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/BundleCheckoutModal.tsx
@@ -0,0 +1,1393 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ Banner,
+ Button,
+ Checkbox,
+ FormField,
+ Input,
+ Modal,
+ NumberInput,
+ Skeleton,
+} from "@app/ui";
+import {
+ BUNDLE_PIPELINE_TIERS,
+ BUNDLE_POLICY_POSTURES,
+ BUNDLE_SIZE_TIERS,
+ type BundleQuoteBreakdown,
+ computeBundleQuote,
+ formatMinor,
+} from "@app/billing";
+import type { Wallet } from "@portal/api/billing";
+import {
+ acceptBundleStripeQuote,
+ cancelBundleQuote,
+ createBundleStripeQuote,
+ fetchBundleQuotePdf,
+ finalizeBundleInvoice,
+ getLatestBundleQuote,
+ StripeFunctionError,
+ upsertBundleQuote,
+ type BundleInvoice,
+ type BundleQuote,
+ type BundleStripeQuote,
+ type LatestBundleQuote,
+} from "@portal/billing/stripe";
+import { PrepayModalHeader } from "@portal/components/billing/PrepayModalHeader";
+
+/**
+ * Prepaid-bundle purchase modal for the Processor billing page — "12 months for
+ * the price of 10". Three steps inside the shared portal {@link Modal}:
+ *
+ * 1. Size your year — buyers size the purchase in PEOPLE. Team size drives an
+ * estimated volume (≈80 PDFs/user/mo), provisioned ~3× above expected; the
+ * finer settings (governance posture, file size, pipelines) scale it up. All
+ * local, via the shared {@code computeBundleQuote} brain.
+ * The calculator is the quote page: it also carries a "Download quote (PDF)"
+ * link, which (like Accept) mints the Stripe QUOTE lazily via
+ * create-payg-bundle-quote — nothing is minted just by sizing.
+ * 2. Review + pay — the same quote receipt card (with "Download quote (PDF)") plus recipient details
+ * + consent. "Finalise" accepts the quote and generates the net-terms invoice, then the step flips
+ * to the finalized state (Download invoice / Pay online). Paying opens Stripe's hosted invoice;
+ * capacity lands via the webhook on invoice.paid, never here. No separate confirmation screen.
+ *
+ * The pool is denominated in size-folded RUNS — the same currency the meter charges
+ * on consumption — so a flat per-run rate reproduces the marketing calculator's
+ * total. The run-based brain (policy-count posture, pipelines, 1¢/run, 10/12) lives
+ * in {@code @app/billing}, shared with the backend.
+ */
+
+/** Default team size the calculator opens on. */
+const DEFAULT_USERS = 25;
+
+/**
+ * EULA version the prepay consent is recorded against (ARL/EULA §7.2). Legal owns
+ * the final value + copy; placeholder until the terms are finalised. Sent to the
+ * checkout edge fn as proof of what was agreed, and recorded in the session metadata.
+ */
+const CONSENT_EULA_VERSION = "2026-07-draft";
+
+function policiesFor(id: string): number {
+ return (
+ BUNDLE_POLICY_POSTURES.find((p) => p.id === id)?.policies ??
+ BUNDLE_POLICY_POSTURES[0].policies
+ );
+}
+function sizeMultFor(id: string): number {
+ return BUNDLE_SIZE_TIERS.find((s) => s.id === id)?.mult ?? 1;
+}
+function pipelineMultFor(id: string): number {
+ return BUNDLE_PIPELINE_TIERS.find((p) => p.id === id)?.mult ?? 1;
+}
+
+// Reverse maps — resume a persisted quote (which stores the multipliers) back to the picker ids.
+function postureIdFor(policies: number): string {
+ return (
+ BUNDLE_POLICY_POSTURES.find((p) => p.policies === policies)?.id ??
+ BUNDLE_POLICY_POSTURES[0].id
+ );
+}
+function sizeIdFor(mult: number): string {
+ return (
+ BUNDLE_SIZE_TIERS.find((s) => Math.abs(s.mult - mult) < 0.001)?.id ??
+ BUNDLE_SIZE_TIERS[0].id
+ );
+}
+function pipelineIdFor(mult: number): string {
+ return (
+ BUNDLE_PIPELINE_TIERS.find((p) => p.mult === mult)?.id ??
+ BUNDLE_PIPELINE_TIERS[0].id
+ );
+}
+
+/**
+ * Pre-quote calculator progress, persisted per team so closing the modal / reloading doesn't lose the
+ * buyer's place. Once a real quote exists it's the source of truth (loaded server-side), so this is
+ * only the "still sizing, nothing minted yet" fallback.
+ */
+interface CalcSettings {
+ users: number;
+ postureId: string;
+ sizeId: string;
+ pipelineId: string;
+ poNumber: string;
+ companyName: string;
+ accountName: string;
+ consented: boolean;
+}
+function calcStorageKey(teamId: number): string {
+ return `payg-bundle-calc:${teamId}`;
+}
+function readCalcSettings(teamId: number): CalcSettings | null {
+ try {
+ const raw = sessionStorage.getItem(calcStorageKey(teamId));
+ if (!raw) return null;
+ // Untrusted sessionStorage — coerce rather than assert, so a stale or schema-drifted blob can't
+ // inject a wrong-typed `users` into the pricing arithmetic (the id fields are additionally
+ // laundered by the ...IdFor() lookups downstream, but we default them here too).
+ const p = JSON.parse(raw) as Partial<Record<keyof CalcSettings, unknown>>;
+ const users = Number(p.users);
+ return {
+ users: Number.isFinite(users) && users > 0 ? users : DEFAULT_USERS,
+ postureId: typeof p.postureId === "string" ? p.postureId : "governed",
+ sizeId: typeof p.sizeId === "string" ? p.sizeId : "standard",
+ pipelineId: typeof p.pipelineId === "string" ? p.pipelineId : "none",
+ poNumber: typeof p.poNumber === "string" ? p.poNumber : "",
+ companyName: typeof p.companyName === "string" ? p.companyName : "",
+ accountName: typeof p.accountName === "string" ? p.accountName : "",
+ consented: p.consented === true,
+ };
+ } catch {
+ return null;
+ }
+}
+function writeCalcSettings(teamId: number, s: CalcSettings): void {
+ try {
+ sessionStorage.setItem(calcStorageKey(teamId), JSON.stringify(s));
+ } catch {
+ // sessionStorage unavailable (private mode / quota) — progress just won't persist.
+ }
+}
+function clearCalcSettings(teamId: number): void {
+ try {
+ sessionStorage.removeItem(calcStorageKey(teamId));
+ } catch {
+ // ignore
+ }
+}
+
+/**
+ * Open a URL in a new tab, falling back to same-tab navigation. A popup blocker can null the
+ * {@code window.open} even from a click, and reliably does when the open follows an await (as the
+ * invoice-PDF download does) — the fallback guarantees the buyer still reaches the invoice / PDF.
+ * Returns true if a new tab opened, false if it fell back to navigating this tab away.
+ */
+function openUrl(url: string): boolean {
+ const win = window.open(url, "_blank", "noopener,noreferrer");
+ if (win) return true;
+ window.location.assign(url);
+ return false;
+}
+
+interface Props {
+ open: boolean;
+ onClose: () => void;
+ /** Drives teamId, per-run rate, currency, and top-up vs first-buy copy. */
+ wallet: Wallet;
+ /** Fired after a completed purchase so the parent can refetch the wallet. */
+ onComplete?: () => void;
+}
+
+type Phase = "calc" | "pay";
+
+export function BundleCheckoutModal({
+ open,
+ onClose,
+ wallet,
+ onComplete,
+}: Props) {
+ const { t } = useTranslation();
+ const teamId = wallet.teamId;
+ const currency = wallet.currency ?? "usd";
+ const pricePerDocMinor = wallet.pricePerDocMinor;
+
+ const [phase, setPhase] = useState<Phase>("calc");
+ const [users, setUsers] = useState(DEFAULT_USERS);
+ const [postureId, setPostureId] = useState<string>("governed");
+ const [sizeId, setSizeId] = useState<string>("standard");
+ const [pipelineId, setPipelineId] = useState<string>("none");
+ const [consented, setConsented] = useState(false);
+ // Optional PO reference — stamped on the Stripe quote and carried to its invoice.
+ const [poNumber, setPoNumber] = useState("");
+ // Invoice recipient: company is optional (becomes the bill-to name); the account-holder name is
+ // required and appears on the invoice. Both stamped at finalize alongside the PO.
+ const [companyName, setCompanyName] = useState("");
+ const [accountName, setAccountName] = useState("");
+ // The persisted quote id, reused across edits so we drive ONE quote row (rather than spawning a new
+ // one on every click). Null until first persisted (or when there's no SaaS backend).
+ const [quoteId, setQuoteId] = useState<number | null>(null);
+ // The Stripe quote — created LAZILY on the first Download/Accept, then reused. We deliberately do NOT
+ // mint a Stripe quote just for opening the review step (a buyer tweaking the calculator would
+ // otherwise leave a trail of dead quotes). Null until first minted, or when there's no SaaS backend.
+ const [stripeQuote, setStripeQuote] = useState<BundleStripeQuote | null>(
+ null,
+ );
+ // The config signature the current stripeQuote was minted for. Editing back to the calculator and
+ // returning reuses that quote UNLESS this changed — so we only re-mint when the sizing/PO actually
+ // differs, not on every trip through review.
+ const [stripeQuoteSig, setStripeQuoteSig] = useState<string | null>(null);
+ // The invoice generated when the quote is accepted (awaiting payment); null when simulated.
+ const [invoice, setInvoice] = useState<BundleInvoice | null>(null);
+ // On resume, the total the quote was persisted at (server value), frozen so the receipt shows what
+ // the buyer actually quoted rather than a figure recomputed from a since-changed rate. Paired with
+ // the pool size it was persisted at — once the buyer edits the sizing (pool changes) we drop back to
+ // the live estimate, since editing re-mints and re-persists anyway.
+ const [persistedPriceMinor, setPersistedPriceMinor] = useState<number | null>(
+ null,
+ );
+ const [persistedPoolCredits, setPersistedPoolCredits] = useState<
+ number | null
+ >(null);
+ // Accept / Download in-flight + last error, surfaced on the calculator (the quote page).
+ const [busy, setBusy] = useState(false);
+ const [pdfBusy, setPdfBusy] = useState(false);
+ const [actionError, setActionError] = useState<string | null>(null);
+ // True while the on-open resume is in flight, so we show a loader instead of flashing the calculator
+ // before it swaps to the resumed step (e.g. payment). `wasOpen` lets us flip it synchronously on the
+ // open transition (below) so even the first render is the loader, not the calculator.
+ const [resolving, setResolving] = useState(false);
+ const [wasOpen, setWasOpen] = useState(false);
+ // Guards the persist effect so it can't overwrite storage with defaults before hydration finishes.
+ const hydratedRef = useRef(false);
+
+ // On open: resume the team's latest OPEN quote if one exists (the server is the source of truth) —
+ // reopening then continues that quote rather than minting a new one. If there's no quote yet, restore
+ // pre-quote calculator progress from sessionStorage. On close: reset in-memory state (the server quote
+ // and the stored progress persist for next time).
+ useEffect(() => {
+ if (!open) {
+ hydratedRef.current = false;
+ setPhase("calc");
+ setUsers(DEFAULT_USERS);
+ setPostureId("governed");
+ setSizeId("standard");
+ setPipelineId("none");
+ setConsented(false);
+ setPoNumber("");
+ setCompanyName("");
+ setAccountName("");
+ setQuoteId(null);
+ setStripeQuote(null);
+ setStripeQuoteSig(null);
+ setInvoice(null);
+ setPersistedPriceMinor(null);
+ setPersistedPoolCredits(null);
+ setBusy(false);
+ setPdfBusy(false);
+ setActionError(null);
+ return;
+ }
+ if (teamId == null) {
+ hydratedRef.current = true;
+ return;
+ }
+ let cancelled = false;
+ (async () => {
+ let latest: LatestBundleQuote | null;
+ try {
+ latest = await getLatestBundleQuote(teamId);
+ } catch {
+ latest = null; // no backend / not a leader — fall through to local progress
+ }
+ if (cancelled) return;
+ const saved = readCalcSettings(teamId);
+ if (latest) {
+ // Resume the existing quote: restore its sizing + consent + id (landing on the calculator), and
+ // relink any already-minted Stripe quote so Download/Accept reuse it rather than minting anew.
+ setUsers(latest.users ?? DEFAULT_USERS);
+ setPostureId(postureIdFor(latest.posturePolicies));
+ setSizeId(sizeIdFor(latest.sizeMult));
+ setPipelineId(pipelineIdFor(latest.pipelineMult));
+ setConsented(latest.consentedAt != null);
+ setQuoteId(latest.quoteId);
+ setPersistedPriceMinor(latest.priceMinor);
+ setPersistedPoolCredits(latest.poolCredits);
+ if (saved?.poNumber) setPoNumber(saved.poNumber);
+ if (saved?.companyName) setCompanyName(saved.companyName);
+ if (saved?.accountName) setAccountName(saved.accountName);
+ if (latest.stripeQuoteId) {
+ setStripeQuote({
+ stripeQuoteId: latest.stripeQuoteId,
+ stripeQuoteNumber: latest.stripeQuoteNumber,
+ });
+ // Match the reuse signature so resuming doesn't immediately re-mint the Stripe quote.
+ setStripeQuoteSig(
+ `${latest.poolCredits}|${(saved?.poNumber ?? "").trim()}`,
+ );
+ }
+ // Already accepted (an invoice exists) → resume straight to the payment step rather than the
+ // calculator. acceptBundleStripeQuote is idempotent: with stripe_ref set it retrieves the
+ // existing draft invoice instead of re-accepting.
+ if (latest.stripeRef) {
+ try {
+ const inv = await acceptBundleStripeQuote({
+ teamId,
+ quoteId: latest.quoteId,
+ });
+ if (!cancelled) {
+ setInvoice(inv);
+ setPhase("pay");
+ }
+ } catch {
+ // Couldn't reload the invoice; leave the buyer on the calculator (Continue re-accepts).
+ }
+ }
+ } else if (saved) {
+ setUsers(saved.users);
+ setPostureId(saved.postureId);
+ setSizeId(saved.sizeId);
+ setPipelineId(saved.pipelineId);
+ setPoNumber(saved.poNumber);
+ setCompanyName(saved.companyName ?? "");
+ setAccountName(saved.accountName ?? "");
+ setConsented(saved.consented);
+ }
+ hydratedRef.current = true;
+ if (!cancelled) setResolving(false);
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [open, teamId]);
+
+ // Persist pre-quote calculator progress so close/reload keeps the buyer's place. Held until hydration
+ // completes so it can't clobber restored values.
+ useEffect(() => {
+ if (!open || teamId == null || !hydratedRef.current) return;
+ writeCalcSettings(teamId, {
+ users,
+ postureId,
+ sizeId,
+ pipelineId,
+ poNumber,
+ companyName,
+ accountName,
+ consented,
+ });
+ }, [
+ open,
+ teamId,
+ users,
+ postureId,
+ sizeId,
+ pipelineId,
+ poNumber,
+ companyName,
+ accountName,
+ consented,
+ ]);
+
+ const quote = useMemo(
+ () =>
+ computeBundleQuote({
+ users,
+ posturePolicies: policiesFor(postureId),
+ sizeMult: sizeMultFor(sizeId),
+ pipelineMult: pipelineMultFor(pipelineId),
+ ratePerRunMinor: pricePerDocMinor,
+ }),
+ [users, postureId, sizeId, pipelineId, pricePerDocMinor],
+ );
+
+ // The receipt shows the persisted (server) total on resume so it matches the quote the buyer
+ // created, not a figure recomputed from a since-changed rate — but only while the sizing is
+ // unchanged (same pool). Editing the calculator changes the pool and reverts to the live estimate.
+ // savings tracks whichever total is shown so the receipt stays internally consistent.
+ const receiptQuote = useMemo(() => {
+ if (
+ persistedPriceMinor == null ||
+ persistedPoolCredits !== quote.poolCredits
+ ) {
+ return quote;
+ }
+ return {
+ ...quote,
+ priceMinor: persistedPriceMinor,
+ savingsMinor:
+ quote.listMinor != null
+ ? quote.listMinor - persistedPriceMinor
+ : quote.savingsMinor,
+ };
+ }, [quote, persistedPriceMinor, persistedPoolCredits]);
+
+ // Flip the loader on synchronously the moment the modal opens (React's "adjust state during render"),
+ // so the resume runs behind a loader from the very first frame — the calculator never shows en route to
+ // a resumed payment step. The effect above clears it once the resume resolves.
+ if (open !== wasOpen) {
+ setWasOpen(open);
+ setResolving(open && teamId != null);
+ }
+
+ if (!open || teamId == null) return null;
+
+ // calc → pay only needs a valid pool; consent + the account-holder name are captured on the payment
+ // step, so they gate the commit (accept + finalize).
+ const canContinue = quote.poolCredits > 0 && !quote.overEnterprise;
+ const nameProvided = accountName.trim().length > 0;
+ // Once the invoice is issued, the recipient details + consent are already captured on it and the fields
+ // are locked, so on resume Pay/Download just re-open the existing invoice — don't re-gate on the (now
+ // read-only, possibly-unrestored) inputs, or the buttons would be permanently disabled.
+ const invoiceIssued = invoice != null && invoice.status !== "draft";
+ const canAccept =
+ canContinue && (invoiceIssued || (consented && nameProvided));
+
+ // Persist (create or edit) the quote row. Returns null when there's no SaaS backend
+ // (Storybook/preview) — the review step then runs in a simulated state.
+ async function ensureQuote(): Promise<BundleQuote | null> {
+ if (teamId == null || quote.poolCredits <= 0) return null;
+ try {
+ const q = await upsertBundleQuote({
+ teamId,
+ users,
+ posturePolicies: policiesFor(postureId),
+ sizeMult: sizeMultFor(sizeId),
+ pipelineMult: pipelineMultFor(pipelineId),
+ provisionedMonthlyVolume: quote.provisionedMonthlyVolume,
+ poolCredits: quote.poolCredits,
+ priceMinor: quote.priceMinor,
+ currency,
+ consented,
+ eulaVersion: CONSENT_EULA_VERSION,
+ quoteId: quoteId ?? undefined,
+ });
+ setQuoteId(q.quoteId);
+ return q;
+ } catch (e) {
+ if (e instanceof StripeFunctionError && e.code === "unconfigured") {
+ return null; // no backend (Storybook/preview) — the flow simulates
+ }
+ throw e; // surfaced by the review step's error banner
+ }
+ }
+
+ // Lazily create (or reuse) the Stripe quote. Called ONLY from Download / Accept — never just from
+ // sizing — so tweaking the calculator never mints throwaway Stripe quotes. Reused as long as the
+ // sizing/PO is unchanged (so a Download then Accept is one quote); a real change re-mints and the edge
+ // fn cancels the superseded Stripe quote. Null with no SaaS backend.
+ async function ensureStripeQuote(): Promise<{
+ quoteId: number;
+ stripeQuote: BundleStripeQuote;
+ } | null> {
+ if (teamId == null) return null;
+ const sig = `${quote.poolCredits}|${poNumber.trim()}`;
+ if (stripeQuote && stripeQuoteSig === sig && quoteId != null) {
+ return { quoteId, stripeQuote }; // unchanged since last mint — reuse, no new quote
+ }
+ const q = await ensureQuote();
+ if (!q) return null;
+ const sq = await createBundleStripeQuote({
+ teamId,
+ quoteId: q.quoteId,
+ poNumber: poNumber.trim() || undefined,
+ });
+ setStripeQuote(sq);
+ setStripeQuoteSig(sig);
+ return { quoteId: q.quoteId, stripeQuote: sq };
+ }
+
+ // Continue to payment: mint (or reuse) the Stripe quote and advance to the payment step. We deliberately
+ // do NOT accept here — acceptance is the commitment and requires consent, which is captured on the
+ // payment step. Deferring accept also lets the buyer go Back and re-size (accepting locks the quote).
+ // No SaaS backend (Storybook/preview) → ensureStripeQuote returns null and we advance simulated.
+ async function handleContinue() {
+ if (!canContinue || busy || pdfBusy || teamId == null) return;
+ setBusy(true);
+ setActionError(null);
+ try {
+ await ensureStripeQuote();
+ setPhase("pay");
+ } catch (e) {
+ if (e instanceof StripeFunctionError && e.code === "unconfigured") {
+ setPhase("pay");
+ return;
+ }
+ setActionError(e instanceof Error ? e.message : String(e)); // stays on calc
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ // Commit the purchase, shared by Download-invoice + Pay-online (both gated on consent in the UI):
+ // record the pay-step consent on the quote (accept 409s without it), ACCEPT the quote to generate the
+ // invoice, then finalize it (stamping any PO, which locks it). Idempotent server-side — a re-accept
+ // returns the existing invoice, an already-finalized invoice comes back as-is. Returns the current
+ // (simulated) invoice when there's no SaaS backend.
+ async function acceptAndFinalize(): Promise<BundleInvoice | null> {
+ if (teamId == null || quoteId == null) return invoice;
+ await ensureQuote(); // persists consented=true (pay-step state) so accept can verify it
+ await acceptBundleStripeQuote({ teamId, quoteId });
+ const inv = await finalizeBundleInvoice({
+ teamId,
+ quoteId,
+ poNumber: poNumber.trim() || undefined,
+ companyName: companyName.trim() || undefined,
+ accountName: accountName.trim() || undefined,
+ });
+ setInvoice(inv);
+ return inv;
+ }
+
+ async function downloadInvoice() {
+ if (busy || pdfBusy || (!invoiceIssued && (!consented || !nameProvided)))
+ return;
+ setPdfBusy(true);
+ setActionError(null);
+ try {
+ const inv = await acceptAndFinalize();
+ if (inv?.invoicePdf) {
+ openUrl(inv.invoicePdf);
+ }
+ } catch (e) {
+ if (e instanceof StripeFunctionError && e.code === "unconfigured") return;
+ setActionError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setPdfBusy(false);
+ }
+ }
+
+ // Finalise (pre-payment): record consent + accept + finalize the invoice. Stays on the payment step —
+ // the view then flips to the finalized state (Download invoice / Pay online). No hosted redirect yet.
+ async function handleFinalise() {
+ if (!canAccept || busy || pdfBusy) return;
+ setBusy(true);
+ setActionError(null);
+ try {
+ await acceptAndFinalize(); // sets invoice → invoiceIssued flips the view to the paid actions
+ } catch (e) {
+ if (e instanceof StripeFunctionError && e.code === "unconfigured") {
+ // No SaaS backend (Storybook/preview) — simulate a finalized invoice so the view still flips.
+ setInvoice({
+ invoiceId: "sim",
+ hostedInvoiceUrl: null,
+ invoicePdf: null,
+ status: "open",
+ });
+ return;
+ }
+ setActionError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ // Pay online (post-finalise): open the hosted invoice, then close + let the parent refresh/poll.
+ // Payment clears out of band (the invoice.paid webhook), so there's no in-modal confirmation step.
+ function payOnline() {
+ if (busy || pdfBusy) return;
+ if (teamId != null) clearCalcSettings(teamId);
+ // If the hosted invoice opened in a new tab, close the modal and let the parent poll; if a popup
+ // blocker forced same-tab navigation, openUrl is already taking us to Stripe — nothing left to do.
+ if (invoice?.hostedInvoiceUrl && !openUrl(invoice.hostedInvoiceUrl)) return;
+ onClose();
+ onComplete?.();
+ }
+
+ // Download the Stripe-rendered quote PDF. Mints the quote (if not already) — that's what makes the
+ // PDF exist — then streams it. No SaaS backend → nothing to download.
+ async function downloadPdf() {
+ if (busy || pdfBusy || quote.poolCredits <= 0) return;
+ setPdfBusy(true);
+ setActionError(null);
+ try {
+ const ensured = await ensureStripeQuote();
+ if (!ensured) return;
+ const blob = await fetchBundleQuotePdf(ensured.quoteId);
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `${ensured.stripeQuote.stripeQuoteNumber ?? "stirling-quote"}.pdf`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+ } catch (e) {
+ if (e instanceof StripeFunctionError && e.code === "unconfigured") return;
+ setActionError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setPdfBusy(false);
+ }
+ }
+
+ // Cancel an unpaid, already-accepted purchase and start over. Once accepted, the Stripe quote is
+ // terminal (editing + re-continuing would hit quote_already_accepted), so "back" can't just re-open the
+ // calculator — we void the invoice + quote server-side, then drop the accepted linkage and return to the
+ // calculator. Sizing is kept so they can adjust and re-quote; consent must be given again.
+ async function cancelPurchase() {
+ if (teamId == null || quoteId == null || busy || pdfBusy) return;
+ setBusy(true);
+ setActionError(null);
+ try {
+ await cancelBundleQuote({ teamId, quoteId });
+ } catch (e) {
+ if (!(e instanceof StripeFunctionError && e.code === "unconfigured")) {
+ setActionError(e instanceof Error ? e.message : String(e)); // stays on the pay step
+ return;
+ }
+ // No SaaS backend (Storybook/preview) — nothing to void; fall through and reset locally.
+ } finally {
+ setBusy(false);
+ }
+ setInvoice(null);
+ setStripeQuote(null);
+ setStripeQuoteSig(null);
+ setQuoteId(null);
+ setConsented(false);
+ setPhase("calc");
+ }
+
+ const footer =
+ phase === "calc" ? (
+ <div className="portal-billing__checkout-cap-actions">
+ <Button variant="quiet" disabled={pdfBusy} onClick={onClose}>
+ {t("portal.billing.prepaid.buy.cancel", "Cancel")}
+ </Button>
+ <Button
+ accent="premium"
+ disabled={!canContinue || pdfBusy}
+ onClick={handleContinue}
+ rightSection={<span aria-hidden>›</span>}
+ >
+ {t(
+ "portal.billing.prepaid.buy.continueToPayment",
+ "Continue to payment",
+ )}
+ </Button>
+ </div>
+ ) : invoiceIssued ? (
+ // Finalized: the invoice exists. Cancel purchase voids + restarts; Pay online opens the hosted invoice.
+ <div className="portal-billing__checkout-cap-actions">
+ <Button
+ variant="quiet"
+ disabled={busy || pdfBusy}
+ onClick={cancelPurchase}
+ >
+ {t("portal.billing.prepaid.buy.cancelPurchase", "Cancel purchase")}
+ </Button>
+ <Button accent="premium" disabled={busy || pdfBusy} onClick={payOnline}>
+ {t("portal.billing.prepaid.pay.payOnline", "Pay online")}
+ </Button>
+ </div>
+ ) : (
+ // Pre-finalize: review the quote, then Finalise to issue the invoice (Back re-opens the calculator).
+ <div className="portal-billing__checkout-cap-actions">
+ <Button
+ variant="quiet"
+ disabled={busy || pdfBusy}
+ onClick={() => setPhase("calc")}
+ >
+ {t("portal.billing.prepaid.buy.back", "Back")}
+ </Button>
+ <Button
+ accent="premium"
+ disabled={!canAccept || busy || pdfBusy}
+ onClick={handleFinalise}
+ >
+ {t("portal.billing.prepaid.buy.finalise", "Finalise")}
+ </Button>
+ </div>
+ );
+
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ width="md"
+ className="portal-billing__bundle-modal portal-billing__checkout-modal--framed"
+ ariaLabel={t(
+ "portal.billing.prepaid.offer.title",
+ "Get 12 months for the price of 10",
+ )}
+ footer={resolving ? undefined : footer}
+ >
+ <PrepayModalHeader
+ step={resolving ? undefined : phase === "pay" ? 3 : 2}
+ title={
+ resolving
+ ? t("portal.billing.prepaid.buy.loadingTitle", "Loading your quote")
+ : phase === "pay"
+ ? t("portal.billing.prepaid.buy.payTitle", "Pay for your year")
+ : t(
+ "portal.billing.prepaid.buy.calcTitle",
+ "Calculate your annual payment",
+ )
+ }
+ onClose={onClose}
+ />
+ <div className="portal-billing__checkout-scroll">
+ {resolving && (
+ <div className="portal-billing__bundle-pay" aria-busy="true">
+ <Skeleton height="3rem" />
+ <Skeleton height="8rem" />
+ <Skeleton height="3rem" />
+ </div>
+ )}
+ {!resolving && phase === "calc" && (
+ <CalculatorStep
+ users={users}
+ setUsers={setUsers}
+ postureId={postureId}
+ setPostureId={setPostureId}
+ sizeId={sizeId}
+ setSizeId={setSizeId}
+ pipelineId={pipelineId}
+ setPipelineId={setPipelineId}
+ quote={receiptQuote}
+ currency={currency}
+ onDownload={downloadPdf}
+ downloading={pdfBusy}
+ actionError={actionError}
+ />
+ )}
+ {!resolving && phase === "pay" && (
+ <PaymentStep
+ quote={receiptQuote}
+ currency={currency}
+ onDownloadQuote={downloadPdf}
+ poNumber={poNumber}
+ setPoNumber={setPoNumber}
+ companyName={companyName}
+ setCompanyName={setCompanyName}
+ accountName={accountName}
+ setAccountName={setAccountName}
+ consented={consented}
+ setConsented={setConsented}
+ poLocked={invoiceIssued}
+ onDownloadInvoice={downloadInvoice}
+ downloading={pdfBusy}
+ actionError={actionError}
+ />
+ )}
+ </div>
+ </Modal>
+ );
+}
+
+// ─── Shared: the quote receipt card ──────────────────────────────────────────
+// The sized plan, its price + savings, the credit pool, and a shareable proforma download. Shown on both
+// the calculator step and the payment step (so the buyer can review + download the quote before/after
+// finalizing it).
+
+function QuoteReceipt({
+ quote,
+ currency,
+ onDownload,
+ downloading,
+}: {
+ quote: BundleQuoteBreakdown;
+ currency: string;
+ /** Mint-if-needed + stream the Stripe quote PDF. */
+ onDownload: () => void;
+ downloading: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="portal-billing__bundle-receipt">
+ <div className="portal-billing__bundle-receipt-row portal-billing__bundle-receipt-row--head">
+ <span>
+ {t("portal.billing.prepaid.calc.handlesLabel", "Your Processor")}
+ </span>
+ <strong>
+ {t(
+ "portal.billing.prepaid.calc.handlesValue",
+ "handles {{volume}} credits / mo",
+ { volume: quote.provisionedMonthlyVolume.toLocaleString() },
+ )}
+ </strong>
+ </div>
+ {quote.priceMinor != null ? (
+ <>
+ <div className="portal-billing__bundle-receipt-row">
+ <span>
+ {t(
+ "portal.billing.prepaid.calc.priceLabel",
+ "Your year · 12 months for the price of 10",
+ )}
+ </span>
+ <strong className="portal-billing__bundle-receipt-price">
+ {formatMinor(quote.priceMinor, currency)}
+ </strong>
+ </div>
+ {quote.savingsMinor != null && quote.savingsMinor > 0 && (
+ <p className="portal-billing__bundle-savings">
+ {t(
+ "portal.billing.prepaid.calc.savings",
+ "You save {{amount}} · 2 months free.",
+ { amount: formatMinor(quote.savingsMinor, currency) },
+ )}
+ </p>
+ )}
+ </>
+ ) : (
+ <p className="portal-billing__bundle-savings">
+ {t(
+ "portal.billing.prepaid.calc.rateUnknown",
+ "We'll show the exact price at checkout.",
+ )}
+ </p>
+ )}
+ {quote.poolCredits > 0 && (
+ <p className="portal-billing__bundle-pool">
+ {t(
+ "portal.billing.prepaid.calc.poolCaption",
+ "One pool of {{credits}} credits for the year. Heavy months borrow from light ones.",
+ { credits: quote.poolCredits.toLocaleString() },
+ )}
+ </p>
+ )}
+ {quote.poolCredits > 0 && (
+ <div
+ role="button"
+ tabIndex={0}
+ aria-disabled={downloading}
+ className="portal-billing__bundle-download"
+ onClick={onDownload}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ onDownload();
+ }
+ }}
+ >
+ <svg
+ width="13"
+ height="13"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden
+ >
+ <path d="M12 3v12m0 0l-4-4m4 4l4-4M4 21h16" />
+ </svg>
+ {downloading
+ ? t("portal.billing.prepaid.review.downloading", "Preparing…")
+ : t(
+ "portal.billing.prepaid.review.download",
+ "Download quote (PDF)",
+ )}
+ {!downloading && (
+ <span className="portal-billing__bundle-download-share">
+ · {t("portal.billing.prepaid.review.share", "share for approval")}
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+// ─── Step 1: users-first calculator ──────────────────────────────────────────
+
+interface CalcProps {
+ users: number;
+ setUsers: (v: number) => void;
+ postureId: string;
+ setPostureId: (v: string) => void;
+ sizeId: string;
+ setSizeId: (v: string) => void;
+ pipelineId: string;
+ setPipelineId: (v: string) => void;
+ quote: BundleQuoteBreakdown;
+ currency: string;
+ /** Mint-if-needed + stream the Stripe quote PDF. */
+ onDownload: () => void;
+ /** PDF download in flight. */
+ downloading: boolean;
+ /** Last Download error, surfaced inline. */
+ actionError: string | null;
+}
+
+interface PickerCard {
+ id: string;
+ title: string;
+ meta?: string;
+ desc: string;
+}
+
+function CalculatorStep({
+ users,
+ setUsers,
+ postureId,
+ setPostureId,
+ sizeId,
+ setSizeId,
+ pipelineId,
+ setPipelineId,
+ quote,
+ currency,
+ onDownload,
+ downloading,
+ actionError,
+}: CalcProps) {
+ const { t } = useTranslation();
+ // Deployment is a display-only finer setting (same rate self-serve); expanded
+ // tracks which row's card picker is bloomed (demo: one open at a time).
+ const [deployId, setDeployId] = useState<string>("cloud");
+ const [expanded, setExpanded] = useState<string | null>(null);
+
+ const deployCards: PickerCard[] = [
+ {
+ id: "cloud",
+ title: t("portal.billing.prepaid.deploy.cloud", "Stirling Cloud"),
+ desc: t(
+ "portal.billing.prepaid.deploy.cloudDesc",
+ "Managed by Stirling. Live in minutes.",
+ ),
+ },
+ {
+ id: "selfhost",
+ title: t("portal.billing.prepaid.deploy.selfhost", "Self-hosted"),
+ desc: t(
+ "portal.billing.prepaid.deploy.selfhostDesc",
+ "Runs on private infrastructure. Same rate.",
+ ),
+ },
+ ];
+ const sizeCards: PickerCard[] = [
+ {
+ id: "compact",
+ title: t("portal.billing.prepaid.size.compact", "Compact"),
+ meta: "×1",
+ desc: t(
+ "portal.billing.prepaid.size.compactDesc",
+ "Files under 25 MB, no data charges",
+ ),
+ },
+ {
+ id: "standard",
+ title: t("portal.billing.prepaid.size.standard", "Standard"),
+ meta: "×1.2",
+ desc: t(
+ "portal.billing.prepaid.size.standardDesc",
+ "Mostly small, some scans past 25 MB",
+ ),
+ },
+ {
+ id: "heavy",
+ title: t("portal.billing.prepaid.size.heavy", "Heavy"),
+ meta: "×2",
+ desc: t(
+ "portal.billing.prepaid.size.heavyDesc",
+ "Scanned or image-heavy, routinely 50 MB+",
+ ),
+ },
+ ];
+ const postureCards: PickerCard[] = [
+ {
+ id: "essentials",
+ title: t("portal.billing.prepaid.posture.essentials", "Essentials"),
+ meta: t(
+ "portal.billing.prepaid.calc.policiesMeta",
+ "{{count}} policies",
+ {
+ count: 2,
+ },
+ ),
+ desc: t(
+ "portal.billing.prepaid.posture.essentialsDesc",
+ "Classification, the default, plus Sharing",
+ ),
+ },
+ {
+ id: "governed",
+ title: t("portal.billing.prepaid.posture.governed", "Governed"),
+ meta: t(
+ "portal.billing.prepaid.calc.policiesMeta",
+ "{{count}} policies",
+ {
+ count: 4,
+ },
+ ),
+ desc: t(
+ "portal.billing.prepaid.posture.governedDesc",
+ "Adds Security and Routing",
+ ),
+ },
+ {
+ id: "regulated",
+ title: t("portal.billing.prepaid.posture.regulated", "Regulated"),
+ meta: t(
+ "portal.billing.prepaid.calc.policiesMeta",
+ "{{count}} policies",
+ {
+ count: 7,
+ },
+ ),
+ desc: t(
+ "portal.billing.prepaid.posture.regulatedDesc",
+ "Every category, incl. Compliance, Retention, Ingestion",
+ ),
+ },
+ ];
+ const pipelineCards: PickerCard[] = [
+ {
+ id: "none",
+ title: t("portal.billing.prepaid.pipelines.none", "None"),
+ desc: t(
+ "portal.billing.prepaid.pipelines.noneDesc",
+ "Not running pipelines yet. Turn them on any time.",
+ ),
+ },
+ {
+ id: "standard",
+ title: t("portal.billing.prepaid.pipelines.standard", "Standard"),
+ desc: t(
+ "portal.billing.prepaid.pipelines.standardDesc",
+ "A few pipelines re-process arriving PDFs.",
+ ),
+ },
+ {
+ id: "advanced",
+ title: t("portal.billing.prepaid.pipelines.advanced", "Advanced"),
+ desc: t(
+ "portal.billing.prepaid.pipelines.advancedDesc",
+ "Pipelines drive most of your processing.",
+ ),
+ },
+ ];
+
+ const find = (cards: PickerCard[], id: string) =>
+ cards.find((c) => c.id === id) ?? cards[0];
+ const size = find(sizeCards, sizeId);
+ const posture = find(postureCards, postureId);
+ const pipeline = find(pipelineCards, pipelineId);
+ const policies =
+ BUNDLE_POLICY_POSTURES.find((p) => p.id === postureId)?.policies ?? 0;
+
+ const deployValue =
+ deployId === "cloud"
+ ? t(
+ "portal.billing.prepaid.deploy.cloudValue",
+ "Stirling Cloud · Managed",
+ )
+ : t(
+ "portal.billing.prepaid.deploy.selfhostValue",
+ "Self-hosted · Private infrastructure",
+ );
+ const sizeValue = t(
+ "portal.billing.prepaid.calc.sizingValue",
+ "{{label}} · {{desc}}",
+ { label: size.title, desc: size.desc },
+ );
+ const postureValue = t(
+ "portal.billing.prepaid.calc.governanceValue",
+ "{{label}} · {{count}} policies",
+ { label: posture.title, count: policies },
+ );
+
+ const rows = [
+ {
+ id: "deploy",
+ label: t("portal.billing.prepaid.calc.deployRow", "Deployment"),
+ value: deployValue,
+ cards: deployCards,
+ activeId: deployId,
+ onPick: setDeployId,
+ },
+ {
+ id: "size",
+ label: t("portal.billing.prepaid.calc.sizingRow", "Sizing"),
+ value: sizeValue,
+ cards: sizeCards,
+ activeId: sizeId,
+ onPick: setSizeId,
+ },
+ {
+ id: "posture",
+ label: t("portal.billing.prepaid.calc.governanceRow", "Governance"),
+ value: postureValue,
+ cards: postureCards,
+ activeId: postureId,
+ onPick: setPostureId,
+ },
+ {
+ id: "pipes",
+ label: t("portal.billing.prepaid.calc.pipelinesLabel", "Pipelines"),
+ value: pipeline.title,
+ cards: pipelineCards,
+ activeId: pipelineId,
+ onPick: setPipelineId,
+ },
+ ];
+
+ return (
+ <div className="portal-billing__bundle-calc">
+ {actionError && (
+ <Banner
+ tone="danger"
+ title={t(
+ "portal.billing.prepaid.buy.invoiceErrorTitle",
+ "Couldn't generate the invoice",
+ )}
+ >
+ {actionError}
+ </Banner>
+ )}
+ <div className="portal-billing__bundle-field">
+ <div className="portal-billing__bundle-field-label">
+ {t("portal.billing.prepaid.calc.usersLabel", "Total users")}
+ </div>
+ <div className="portal-billing__bundle-users">
+ <NumberInput
+ value={users}
+ onChange={(v) => setUsers(typeof v === "number" ? v : 0)}
+ min={0}
+ step={1}
+ allowNegative={false}
+ aria-label={t(
+ "portal.billing.prepaid.calc.usersLabel",
+ "Total users",
+ )}
+ />
+ </div>
+ </div>
+
+ {/* Finer settings as progressive-disclosure rows — a "Change" blooms the card picker. */}
+ <div className="portal-billing__bundle-rows">
+ {rows.map((row) => {
+ const open = expanded === row.id;
+ return (
+ <div key={row.id} className="portal-billing__bundle-row">
+ <div
+ role="button"
+ tabIndex={0}
+ className="portal-billing__bundle-row-head"
+ aria-expanded={open}
+ onClick={() => setExpanded(open ? null : row.id)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ setExpanded(open ? null : row.id);
+ }
+ }}
+ >
+ <span className="portal-billing__bundle-row-label">
+ {row.label}
+ </span>
+ <span className="portal-billing__bundle-row-value">
+ {row.value}
+ <span className="portal-billing__bundle-row-change">
+ {open
+ ? t("portal.billing.prepaid.calc.done", "Done")
+ : t("portal.billing.prepaid.calc.change", "Change")}
+ </span>
+ </span>
+ </div>
+ {open && (
+ <div className="portal-billing__bundle-row-body">
+ <div className="portal-billing__bundle-cards">
+ {row.cards.map((card) => {
+ const active = card.id === row.activeId;
+ const pick = () => {
+ row.onPick(card.id);
+ setExpanded(null);
+ };
+ return (
+ <div
+ key={card.id}
+ role="button"
+ tabIndex={0}
+ aria-pressed={active}
+ className={
+ "portal-billing__bundle-card" +
+ (active
+ ? " portal-billing__bundle-card--active"
+ : "")
+ }
+ onClick={pick}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ pick();
+ }
+ }}
+ >
+ <span className="portal-billing__bundle-card-head">
+ <span className="portal-billing__bundle-card-title">
+ {card.title}
+ </span>
+ {card.meta && (
+ <span className="portal-billing__bundle-card-meta">
+ {card.meta}
+ </span>
+ )}
+ </span>
+ <span className="portal-billing__bundle-card-desc">
+ {card.desc}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Receipt — the sized plan, its price, the credit pool, and a shareable proforma. */}
+ <QuoteReceipt
+ quote={quote}
+ currency={currency}
+ onDownload={onDownload}
+ downloading={downloading}
+ />
+
+ {quote.overEnterprise && (
+ <p className="portal-billing__bundle-savings">
+ {t(
+ "portal.billing.prepaid.calc.enterpriseHint",
+ "This is enterprise scale. At this volume, enterprise rates beat any self-serve discount. Rate lock, terms, and a quote in minutes.",
+ )}
+ </p>
+ )}
+ </div>
+ );
+}
+
+// ─── Step 2: pay for your year (quote already accepted → PO · download · pay) ──
+
+function PaymentStep({
+ quote,
+ currency,
+ onDownloadQuote,
+ poNumber,
+ setPoNumber,
+ companyName,
+ setCompanyName,
+ accountName,
+ setAccountName,
+ consented,
+ setConsented,
+ poLocked,
+ onDownloadInvoice,
+ downloading,
+ actionError,
+}: {
+ quote: BundleQuoteBreakdown;
+ currency: string;
+ /** Mint-if-needed + stream the Stripe quote PDF (the receipt card's download link). */
+ onDownloadQuote: () => void;
+ poNumber: string;
+ setPoNumber: (v: string) => void;
+ companyName: string;
+ setCompanyName: (v: string) => void;
+ accountName: string;
+ setAccountName: (v: string) => void;
+ consented: boolean;
+ setConsented: (v: boolean) => void;
+ /** True once the invoice is finalized (first Download/Pay) — recipient fields + consent lock. */
+ poLocked: boolean;
+ /** Finalize + open the invoice PDF. */
+ onDownloadInvoice: () => void;
+ downloading: boolean;
+ actionError: string | null;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="portal-billing__bundle-pay">
+ {actionError && (
+ <Banner
+ tone="danger"
+ title={t(
+ "portal.billing.prepaid.buy.invoiceErrorTitle",
+ "Couldn't generate the invoice",
+ )}
+ >
+ {actionError}
+ </Banner>
+ )}
+ <QuoteReceipt
+ quote={quote}
+ currency={currency}
+ onDownload={onDownloadQuote}
+ downloading={downloading}
+ />
+ {/* Recipient + PO capture. Hidden once the invoice is issued: locked onto the invoice and we don't
+ hold the values to re-display, so empty disabled inputs would just read as broken. Company + PO
+ share a row to keep the step compact. */}
+ {!poLocked && (
+ <div className="portal-billing__bundle-fields">
+ <FormField
+ label={t(
+ "portal.billing.prepaid.pay.accountName",
+ "Account holder name",
+ )}
+ required
+ >
+ <Input
+ inputSize="sm"
+ value={accountName}
+ onChange={(e) => setAccountName(e.target.value)}
+ placeholder={t(
+ "portal.billing.prepaid.pay.accountNamePlaceholder",
+ "e.g. Jane Smith",
+ )}
+ />
+ </FormField>
+ <div className="portal-billing__bundle-field-row">
+ <FormField
+ label={t(
+ "portal.billing.prepaid.pay.companyName",
+ "Company name (optional)",
+ )}
+ >
+ <Input
+ inputSize="sm"
+ value={companyName}
+ onChange={(e) => setCompanyName(e.target.value)}
+ placeholder={t(
+ "portal.billing.prepaid.pay.companyNamePlaceholder",
+ "e.g. Acme Inc.",
+ )}
+ />
+ </FormField>
+ <FormField
+ label={t(
+ "portal.billing.prepaid.pay.poNumber",
+ "PO number (optional)",
+ )}
+ >
+ <Input
+ inputSize="sm"
+ value={poNumber}
+ onChange={(e) => setPoNumber(e.target.value)}
+ placeholder={t(
+ "portal.billing.prepaid.pay.poNumberPlaceholder",
+ "e.g. PO-2026-0142",
+ )}
+ />
+ </FormField>
+ </div>
+ </div>
+ )}
+ {/* Consent (pre-finalize only): acknowledges that once the prepaid pool is used up / expires,
+ metered pay-as-you-go continues (up to the spend limit) unless cancelled — no annual auto-renewal
+ is claimed, since the bundle isn't a subscription. Hidden once the invoice is issued: it's locked
+ and already recorded, so a disabled checkbox just adds noise. Legal owns the wording. */}
+ {!poLocked && (
+ <div className="portal-billing__bundle-consent">
+ <Checkbox
+ checked={consented}
+ onChange={(e) => setConsented(e.currentTarget.checked)}
+ label={t(
+ "portal.billing.prepaid.consent.label",
+ "I understand that when my prepaid capacity is used up or expires after 12 months, processing automatically continues at the standard metered pay-as-you-go rate (up to my spend limit) unless I cancel, and that I can cancel anytime from the billing portal.",
+ )}
+ />
+ </div>
+ )}
+ {/* Download invoice appears once the invoice is finalized (its PDF exists). Pre-finalize, the
+ receipt card's "Download quote (PDF)" is the shareable document. */}
+ {poLocked && (
+ <div className="portal-billing__bundle-foot-end">
+ <Button
+ variant="quiet"
+ disabled={downloading}
+ onClick={onDownloadInvoice}
+ >
+ {downloading
+ ? t("portal.billing.prepaid.review.downloading", "Preparing…")
+ : t(
+ "portal.billing.prepaid.pay.downloadInvoice",
+ "Download invoice",
+ )}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/portal/components/billing/CardPlaceholder.tsx b/frontend/editor/src/portal/components/billing/CardPlaceholder.tsx
new file mode 100644
index 0000000000..af1cd78b1b
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/CardPlaceholder.tsx
@@ -0,0 +1,34 @@
+import { useTranslation } from "react-i18next";
+import { LockIcon } from "@portal/components/icons";
+
+/**
+ * Card-form stand-in shown on the checkout payment step when no Stripe publishable key is configured
+ * (Storybook / preview / mis-config), so the step still reads correctly without mounting Stripe.
+ * Shared by the subscription checkout and the prepaid-bundle checkout modals.
+ */
+export function CardPlaceholder() {
+ const { t } = useTranslation();
+ return (
+ <div className="portal-billing__card-placeholder">
+ <div className="portal-billing__card-placeholder-head">
+ <span>{t("portal.billing.checkout.card.label", "Card details")}</span>
+ <span className="portal-billing__card-placeholder-badge">Stripe</span>
+ </div>
+ <div className="portal-billing__card-placeholder-field">
+ <LockIcon size={13} />
+ <span>
+ {t(
+ "portal.billing.checkout.card.fields",
+ "Card number · MM / YY · CVC · ZIP",
+ )}
+ </span>
+ </div>
+ <p className="portal-billing__card-placeholder-note">
+ {t(
+ "portal.billing.checkout.card.note",
+ "Card details collected by Stripe. Stirling never stores PAN or CVC.",
+ )}
+ </p>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/portal/components/billing/FreePlanView.tsx b/frontend/editor/src/portal/components/billing/FreePlanView.tsx
index a2027ff756..5b704f3860 100644
--- a/frontend/editor/src/portal/components/billing/FreePlanView.tsx
+++ b/frontend/editor/src/portal/components/billing/FreePlanView.tsx
@@ -8,6 +8,10 @@ import { WalletMeter } from "@portal/components/billing/WalletMeter";
import { FreePdfEditorsCard } from "@portal/components/billing/FreePdfEditorsCard";
import { EnterpriseUpsell } from "@portal/components/billing/EnterpriseUpsell";
import { StripeCheckoutModal } from "@portal/components/billing/StripeCheckoutModal";
+import { ActivationChoiceModal } from "@portal/components/billing/ActivationChoiceModal";
+import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";
+import { PrepaidCapacityCard } from "@portal/components/billing/PrepaidCapacityCard";
+import { useBundleFlowState } from "@portal/hooks/useBundleFlowState";
interface Props {
wallet: Wallet;
@@ -32,7 +36,9 @@ function isSaasCurrency(c: string | null): c is SaasCurrency {
*/
export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {
const { t } = useTranslation();
- const [modalOpen, setModalOpen] = useState(false);
+ // Activation fork (demo D97): choose → the metered checkout (payg) or the
+ // discounted bundle (prepay). Exactly one is open at a time.
+ const [step, setStep] = useState<"choose" | "payg" | "prepay" | null>(null);
const [missingTeam, setMissingTeam] = useState<string | null>(null);
const isLeader = wallet.role === "leader";
@@ -40,7 +46,12 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {
? wallet.currency
: "usd";
- function openCheckout() {
+ // Where this team sits in the prepaid-bundle flow, read on load so the CTA names
+ // the resume action rather than always restarting the fork. Leader + team gated
+ // (the RPC 403s otherwise). Refreshed when any activation modal closes.
+ const flow = useBundleFlowState(wallet.teamId, isLeader);
+
+ function requireTeam(): boolean {
if (wallet.teamId == null) {
setMissingTeam(
t(
@@ -48,23 +59,44 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {
"No team is resolved on your wallet yet — refresh and try again.",
),
);
- return;
+ return false;
}
setMissingTeam(null);
- setModalOpen(true);
+ return true;
+ }
+
+ // No quote yet → open the pay-as-you-go vs prepay fork. A quote already in flight
+ // → skip the fork and reopen the bundle modal directly; its resume effect lands
+ // on the calculator (quote) or the payment step (invoice awaiting payment).
+ function openActivation() {
+ if (requireTeam()) setStep("choose");
+ }
+ function resumeBundle() {
+ if (requireTeam()) setStep("prepay");
+ }
+
+ // Closing any activation modal re-reads the flow state so the CTA reflects a
+ // freshly-minted quote / invoice without a full page reload.
+ function closeModals() {
+ setStep(null);
+ flow.refresh();
}
const switchOnAction = isLeader ? (
<Button
variant="primary"
accent="premium"
- onClick={openCheckout}
+ onClick={flow.status === "none" ? openActivation : resumeBundle}
disabled={wallet.teamId == null}
>
- {t(
- "portal.billing.freePlan.switchOnProcessor",
- "Switch on the Processor →",
- )}
+ {flow.status === "invoice"
+ ? t("portal.billing.freePlan.payInvoice", "Pay invoice to complete")
+ : flow.status === "quote"
+ ? t("portal.billing.freePlan.viewQuote", "View quote")
+ : t(
+ "portal.billing.freePlan.switchOnProcessor",
+ "Switch on the Processor →",
+ )}
</Button>
) : null;
@@ -93,6 +125,15 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {
<FreePdfEditorsCard />
+ {/* Prepaid capacity is usable independent of a metered subscription, so surface it here on the
+ free plan too (not just the subscribed dashboard) whenever the team holds a live pool. */}
+ {wallet.prepaidUnitsRemaining > 0 && (
+ <PrepaidCapacityCard
+ wallet={wallet}
+ onBuy={isLeader ? resumeBundle : undefined}
+ />
+ )}
+
{/* Processor trial — meter with the inline upgrade CTA */}
<WalletMeter
wallet={wallet}
@@ -123,10 +164,17 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {
{/* Volume discount / Enterprise */}
<EnterpriseUpsell />
+ <ActivationChoiceModal
+ open={step === "choose"}
+ onClose={closeModals}
+ onChoosePayg={() => setStep("payg")}
+ onChoosePrepay={() => setStep("prepay")}
+ />
+
{wallet.teamId != null && (
<StripeCheckoutModal
- open={modalOpen}
- onClose={() => setModalOpen(false)}
+ open={step === "payg"}
+ onClose={closeModals}
teamId={wallet.teamId}
currency={currency}
pricePerDocMinor={wallet.pricePerDocMinor}
@@ -134,6 +182,22 @@ export function FreePlanView({ wallet, unsynced, onSubscribed }: Props) {
onComplete={() => onSubscribed?.() ?? Promise.resolve(false)}
/>
)}
+
+ {/* Prepay reuses the bundle modal (free team → first-purchase copy, no cap
+ step). On completion the webhook credits the pool AND silently creates
+ the metered subscription off the saved card, so we poll like the payg
+ path to flip the wallet to subscribed. */}
+ {wallet.teamId != null && (
+ <BundleCheckoutModal
+ open={step === "prepay"}
+ onClose={closeModals}
+ wallet={wallet}
+ onComplete={() => {
+ closeModals();
+ void onSubscribed?.();
+ }}
+ />
+ )}
</div>
);
}
diff --git a/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.tsx b/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.tsx
new file mode 100644
index 0000000000..038b8be6d5
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/PrepaidCapacityCard.tsx
@@ -0,0 +1,109 @@
+import { useTranslation } from "react-i18next";
+import { Button, Card } from "@app/ui";
+import { formatPeriodDate, MeterBar, meterState } from "@app/billing";
+import type { Wallet } from "@portal/api/billing";
+
+/**
+ * Prepaid-bundle capacity for the subscribed Processor dashboard, and the entry
+ * point for buying it. Two faces, driven by whether the team holds a bundle:
+ *
+ * - No bundle → a slim "Get 12 months for the price of 10" offer nudge with a
+ * "Review offer" CTA (the demo's commit-nudge card), shown only when a buyer
+ * ({@code onBuy}, leader) is present.
+ * - Bundle held → the capacity meter (fills as the pool is drawn down, so it
+ * warns as capacity runs low) plus a "Top up" action for the leader.
+ *
+ * Prepaid is consumed before metered billing and sits outside the spend limit, so
+ * it reads as its own dimension. Buying/topping up opens {@code BundleCheckoutModal}
+ * via {@code onBuy}; members (no {@code onBuy}) get the display-only meter.
+ */
+export function PrepaidCapacityCard({
+ wallet,
+ onBuy,
+}: {
+ wallet: Wallet;
+ /** Leader-only: opens the purchase/top-up modal. Omit for members. */
+ onBuy?: () => void;
+}) {
+ const { t } = useTranslation();
+
+ // No bundle yet — show the buy nudge (leader only), else nothing.
+ if (wallet.prepaidUnitsTotal <= 0) {
+ if (!onBuy) return null;
+ return (
+ <Card padding="loose" className="portal-billing__prepaid-offer">
+ <div>
+ <div className="portal-billing__section-title">
+ {t(
+ "portal.billing.prepaid.offer.title",
+ "Get 12 months for the price of 10",
+ )}
+ </div>
+ <p className="portal-billing__prepaid-offer-sub">
+ {t(
+ "portal.billing.prepaid.offer.subtitle",
+ "Prepay a year of PDF processing and get two months free — used before metered billing, outside your spend limit.",
+ )}
+ </p>
+ </div>
+ <Button variant="secondary" onClick={onBuy}>
+ {t("portal.billing.prepaid.offer.cta", "Review offer")}
+ </Button>
+ </Card>
+ );
+ }
+
+ const remaining = wallet.prepaidUnitsRemaining;
+ const total = wallet.prepaidUnitsTotal;
+ const used = Math.max(0, total - remaining);
+ const { state, pct } = meterState(used, total);
+ const stateLabel =
+ state === "DEGRADED"
+ ? t("portal.billing.prepaid.state.exhausted", "Used up")
+ : state === "WARNED"
+ ? t("portal.billing.prepaid.state.low", "Running low")
+ : t("portal.billing.prepaid.state.healthy", "Plenty left");
+
+ return (
+ <Card padding="loose">
+ <span className="portal-billing__eyebrow">
+ {t("portal.billing.prepaid.eyebrow", "Prepaid capacity")}
+ </span>
+ <MeterBar
+ state={state}
+ pct={pct}
+ figure={remaining.toLocaleString()}
+ capSuffix={t(
+ "portal.billing.prepaid.capSuffix",
+ "of {{total}} prepaid PDFs",
+ {
+ total: total.toLocaleString(),
+ },
+ )}
+ statusLabel={stateLabel}
+ meta={
+ wallet.prepaidExpiresAt ? (
+ <span>
+ {t("portal.billing.prepaid.expires", "Expires {{date}}", {
+ date: formatPeriodDate(wallet.prepaidExpiresAt, { year: true }),
+ })}
+ </span>
+ ) : undefined
+ }
+ />
+ <div className="portal-billing__prepaid-foot">
+ <p className="portal-billing__section-sub">
+ {t(
+ "portal.billing.prepaid.note",
+ "Used before metered billing and outside your spend limit.",
+ )}
+ </p>
+ {onBuy && (
+ <Button variant="secondary" size="sm" onClick={onBuy}>
+ {t("portal.billing.prepaid.topUp", "Top up")}
+ </Button>
+ )}
+ </div>
+ </Card>
+ );
+}
diff --git a/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx b/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx
new file mode 100644
index 0000000000..c099836ee4
--- /dev/null
+++ b/frontend/editor/src/portal/components/billing/PrepayModalHeader.tsx
@@ -0,0 +1,91 @@
+import { useTranslation } from "react-i18next";
+import { Button } from "@app/ui";
+// The trademarked Stirling wordmark — the font is baked into the SVG (no brand webfont is loaded), so
+// we render the same asset the portal nav uses rather than styled text. Theme-switched in CSS.
+import wordmarkLight from "@app/assets/brand/modern-logo/StirlingProcessorLogoBlackText.svg";
+import wordmarkDark from "@app/assets/brand/modern-logo/StirlingProcessorLogoWhiteText.svg";
+
+/**
+ * Shared header for the prepay-flow modals — the prepaid wizard (activation → calculator → pay, of 3)
+ * and the metered checkout (spend limit → payment, of 2): Stirling brand + "Step N of M" badge + close,
+ * an M-segment progress bar, and the step title. Pass {@code step=undefined} to hide the badge +
+ * progress (e.g. a terminal confirmation).
+ */
+export function PrepayModalHeader({
+ step,
+ total = 3,
+ title,
+ onClose,
+}: {
+ step?: number;
+ /** Total steps in this flow (3 for the prepaid wizard, 2 for the metered checkout). */
+ total?: number;
+ title: string;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation();
+ const showSteps = step != null;
+ const filled = step ?? 0;
+ return (
+ <div className="portal-billing__bundle-head">
+ <div className="portal-billing__bundle-head-top">
+ <div className="portal-billing__bundle-brand">
+ <img
+ src={wordmarkLight}
+ alt="Stirling"
+ className="portal-billing__bundle-wordmark wordmark-light-only"
+ />
+ <img
+ src={wordmarkDark}
+ alt=""
+ aria-hidden
+ className="portal-billing__bundle-wordmark wordmark-dark-only"
+ />
+ </div>
+ <div className="portal-billing__bundle-head-right">
+ {showSteps && (
+ <span className="portal-billing__bundle-step">
+ {t(
+ "portal.billing.prepaid.buy.step",
+ "Step {{current}} of {{total}}",
+ { current: step, total },
+ )}
+ </span>
+ )}
+ <Button
+ variant="tertiary"
+ accent="neutral"
+ size="sm"
+ shape="circle"
+ onClick={onClose}
+ aria-label={t("portal.billing.prepaid.buy.close", "Close")}
+ leftSection={
+ <svg
+ viewBox="0 0 24 24"
+ width="16"
+ height="16"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.75}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden
+ >
+ <line x1="18" y1="6" x2="6" y2="18" />
+ <line x1="6" y1="6" x2="18" y2="18" />
+ </svg>
+ }
+ />
+ </div>
+ </div>
+ {showSteps && (
+ <div className="portal-billing__bundle-progress" aria-hidden>
+ <span className={filled >= 1 ? "is-filled" : ""} />
+ <span className={filled >= 2 ? "is-filled" : ""} />
+ {total >= 3 && <span className={filled >= 3 ? "is-filled" : ""} />}
+ </div>
+ )}
+ <div className="portal-billing__bundle-head-title">{title}</div>
+ </div>
+ );
+}
diff --git a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
index 65d32ed8ea..c30a7d68b5 100644
--- a/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
+++ b/frontend/editor/src/portal/components/billing/StripeCheckoutModal.tsx
@@ -1,19 +1,24 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Banner, Button, Modal, Skeleton, Spinner } from "@app/ui";
-import { SpendCapControl } from "@app/billing";
+import {
+ currencySymbol,
+ docCapForMoney,
+ formatMinor,
+} from "@app/billing/format";
import {
EmbeddedCheckout,
EmbeddedCheckoutProvider,
} from "@stripe/react-stripe-js";
-import type { Stripe } from "@stripe/stripe-js";
import { updateCap } from "@portal/api/billing";
import {
createCheckoutSession,
getStripePublishableKey,
+ loadStripeOnce,
type SaasCurrency,
} from "@portal/billing/stripe";
-import { LockIcon } from "@portal/components/icons";
+import { CardPlaceholder } from "@portal/components/billing/CardPlaceholder";
+import { PrepayModalHeader } from "@portal/components/billing/PrepayModalHeader";
interface Props {
open: boolean;
@@ -29,10 +34,10 @@ interface Props {
/** Optional billing email prefill (Stripe locks the field when set). */
billingOwnerEmail?: string;
/**
- * Fired when Stripe (or the mock continue button) signals payment success.
- * Runs the caller's activation flow (poll the wallet until the subscription
- * webhook lands) and resolves {@code true} once subscribed, {@code false} if
- * it's taking longer than the poll window.
+ * Fired when Stripe signals payment success. Runs the caller's activation flow
+ * (poll the wallet until the subscription webhook lands) and resolves {@code
+ * true} once subscribed, {@code false} if it's taking longer than the poll
+ * window.
*/
onComplete: () => Promise<boolean>;
}
@@ -51,29 +56,6 @@ const DEFAULT_CAP_USD = 100;
* If the team is already subscribed the edge function short-circuits to a Stripe
* Customer Portal URL; we open it in a new tab and close.
*/
-let stripePromise: Promise<Stripe | null> | null = null;
-function loadStripeOnce(pk: string): Promise<Stripe | null> {
- if (stripePromise === null) {
- stripePromise = import("@stripe/stripe-js").then((m) => m.loadStripe(pk));
- }
- return stripePromise;
-}
-
-/** Two-segment progress header: step 1 = spend limit, step 2 = payment. */
-function StepProgress({ step }: { step: 1 | 2 }) {
- const { t } = useTranslation();
- return (
- <div className="portal-billing__checkout-progress">
- <div className="portal-billing__checkout-steps" aria-hidden>
- <span className="is-done" />
- <span className={step >= 2 ? "is-done" : ""} />
- </div>
- <span className="portal-billing__checkout-stepcount">
- {t("portal.billing.checkout.stepCount", "Step {{step}} of 2", { step })}
- </span>
- </div>
- );
-}
/** Payment done, waiting for the subscription webhook to activate the plan. */
function CheckoutFinalizing() {
@@ -125,33 +107,114 @@ function CheckoutActivationSlow({ onClose }: { onClose: () => void }) {
}
/**
- * Placeholder for the card form when no Stripe publishable key is configured
- * (Storybook / preview / mis-config). Mirrors the real embedded form's framing
- * so the step reads correctly without mounting Stripe.
+ * Spend-limit picker for step 1: a primary editable amount ({@code $ 100 / mo}) with quick-pick chips
+ * below. The amount field is the main entry — always visible, defaulted, and typeable — and clicking a
+ * chip (or "No cap") just writes into it. Controlled via {@code capUsd}/{@code onChange}
+ * (null = no cap, a number = a monthly ceiling).
*/
-function CardPlaceholder() {
+function SpendLimitPicker({
+ capUsd,
+ onChange,
+ currency,
+ pricePerDocMinor,
+ presets,
+ disabled,
+}: {
+ capUsd: number | null;
+ onChange: (v: number | null) => void;
+ currency: SaasCurrency;
+ pricePerDocMinor?: number | null;
+ presets: readonly number[];
+ disabled?: boolean;
+}) {
const { t } = useTranslation();
+ const sym = currencySymbol(currency);
+ const isNoCap = capUsd === null;
+ // Local mirror so partial typing isn't clobbered by the controlled value; resync when not focused
+ // (e.g. a chip sets the amount, or an initial cap loads in).
+ const [text, setText] = useState(capUsd != null ? String(capUsd) : "");
+ const [focused, setFocused] = useState(false);
+ useEffect(() => {
+ if (!focused) setText(capUsd != null ? String(capUsd) : "");
+ }, [capUsd, focused]);
+
+ const docs = docCapForMoney(capUsd, pricePerDocMinor);
+
+ const onInput = (raw: string) => {
+ const cleaned = raw.replace(/[^0-9]/g, "");
+ setText(cleaned);
+ onChange(cleaned === "" ? 0 : parseInt(cleaned, 10));
+ };
+
return (
- <div className="portal-billing__card-placeholder">
- <div className="portal-billing__card-placeholder-head">
- <span>{t("portal.billing.checkout.card.label", "Card details")}</span>
- <span className="portal-billing__card-placeholder-badge">Stripe</span>
- </div>
- <div className="portal-billing__card-placeholder-field">
- <LockIcon size={13} />
- <span>
- {t(
- "portal.billing.checkout.card.fields",
- "Card number · MM / YY · CVC · ZIP",
+ <div className="portal-billing__caplimit">
+ <div
+ className="portal-billing__caplimit-field"
+ data-nocap={isNoCap ? "true" : "false"}
+ >
+ <span className="portal-billing__caplimit-sym">{sym}</span>
+ <input
+ className="portal-billing__caplimit-input"
+ inputMode="numeric"
+ value={isNoCap ? "" : text}
+ placeholder={
+ isNoCap ? t("portal.billing.checkout.cap.noLimit", "No limit") : ""
+ }
+ aria-label={t(
+ "portal.billing.checkout.cap.amountAria",
+ "Monthly spend limit",
)}
+ onChange={(e) => onInput(e.target.value)}
+ onFocus={() => setFocused(true)}
+ onBlur={() => setFocused(false)}
+ disabled={disabled}
+ />
+ <span className="portal-billing__caplimit-suffix">
+ {t("portal.billing.checkout.cap.perMonth", "/ mo")}
</span>
</div>
- <p className="portal-billing__card-placeholder-note">
- {t(
- "portal.billing.checkout.card.note",
- "Card details collected by Stripe. Stirling never stores PAN or CVC.",
- )}
- </p>
+
+ <div className="portal-billing__caplimit-chips">
+ {presets.map((p) => (
+ <Button
+ key={p}
+ type="button"
+ variant="quiet"
+ className="portal-billing__caplimit-chip"
+ data-selected={capUsd === p ? "true" : "false"}
+ onClick={() => onChange(p)}
+ disabled={disabled}
+ >
+ {sym}
+ {p.toLocaleString()}
+ </Button>
+ ))}
+ <Button
+ type="button"
+ variant="quiet"
+ className="portal-billing__caplimit-chip"
+ data-selected={isNoCap ? "true" : "false"}
+ onClick={() => onChange(null)}
+ disabled={disabled}
+ >
+ {t("payg.cap.noCapLabel", "No cap")}
+ </Button>
+ </div>
+
+ {docs != null && (
+ <div className="portal-billing__caplimit-estimate">
+ <span className="portal-billing__caplimit-estimate-main">
+ {t("payg.cap.docsEstimate", "≈ {{docs}} credits / month", {
+ docs: docs.toLocaleString(),
+ })}
+ </span>
+ <span className="portal-billing__caplimit-estimate-sub">
+ {t("payg.cap.docsRate", "at {{rate}} / credit", {
+ rate: formatMinor(pricePerDocMinor ?? 0, currency),
+ })}
+ </span>
+ </div>
+ )}
</div>
);
}
@@ -294,30 +357,36 @@ export function StripeCheckoutModal({
if (dismissable) onClose();
};
- const onCapStep = phase === "cap";
- const title = onCapStep
- ? t("portal.billing.checkout.cap.title", "Set your spend limit")
- : t("portal.billing.checkout.title", "Add a payment method");
- const subtitle = onCapStep
- ? t(
- "portal.billing.checkout.cap.subtitle",
- "You're billed only for PDFs you process past your first 500 free, never for seats — so your ceiling is yours from day one.",
- )
- : t(
- "portal.billing.checkout.subtitle",
- "Add a card to keep going past your free Editor-plan grant. Stripe handles the rest.",
- );
+ // The chosen cap, formatted for the payment-step recap (null = "No cap" was picked on step 1).
+ const capLabel =
+ capUsd != null
+ ? new Intl.NumberFormat(undefined, {
+ style: "currency",
+ currency: currency.toUpperCase(),
+ maximumFractionDigits: 0,
+ }).format(capUsd)
+ : null;
return (
<Modal
open={open}
onClose={handleClose}
- width="xl"
- className="portal-billing__checkout-modal"
+ /* Only the Stripe checkout step needs the room; every other step stays narrow. The checkout
+ step also gets a wider-than-xl cap so the embedded Stripe iframe clears its ~1000px
+ two-column threshold (below it, Stripe falls back to the single-column "portrait" layout). */
+ width={phase === "checkout" ? "xl" : "md"}
+ className={[
+ "portal-billing__checkout-modal",
+ phase === "cap" || phase === "checkout"
+ ? "portal-billing__checkout-modal--framed"
+ : "",
+ phase === "checkout" ? "portal-billing__checkout-modal--wide" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
disableBackdropClose={!dismissable}
disableEscapeClose={!dismissable}
- title={title}
- subtitle={subtitle}
+ ariaLabel={t("portal.billing.checkout.cap.title", "Set your spend limit")}
>
{phase === "finalizing" && <CheckoutFinalizing />}
{phase === "activationSlow" && (
@@ -326,80 +395,117 @@ export function StripeCheckoutModal({
{phase === "cap" && (
<div className="portal-billing__checkout-cap">
- <StepProgress step={1} />
- <SpendCapControl
- capUsd={capUsd}
- onChange={setCapUsd}
- pricePerDocMinor={pricePerDocMinor}
- currency={currency}
- presets={CAP_PRESETS}
- note={t(
- "portal.billing.checkout.cap.note",
- "Processing pauses if you reach it. You're never billed past this, and you can change it any time.",
+ <PrepayModalHeader
+ step={2}
+ total={3}
+ title={t(
+ "portal.billing.checkout.cap.title",
+ "Set your spend limit",
)}
+ onClose={handleClose}
/>
- <p className="portal-billing__checkout-finePrint">
- {t(
- "portal.billing.checkout.cap.finePrint",
- "Invoices post on the 1st. Cancel anytime and revert to the Editor plan; your policies and history stay intact.",
- )}
- </p>
- {capError && (
- <Banner
- tone="danger"
- title={t(
- "portal.billing.checkout.cap.error",
- "Couldn't set your spend limit",
+ <div className="portal-billing__checkout-scroll">
+ <SpendLimitPicker
+ capUsd={capUsd}
+ onChange={setCapUsd}
+ pricePerDocMinor={pricePerDocMinor}
+ currency={currency}
+ presets={CAP_PRESETS}
+ disabled={capBusy}
+ />
+ <p className="portal-billing__checkout-finePrint">
+ {t(
+ "portal.billing.checkout.cap.note",
+ "You're never billed past your limit. Processing just pauses.",
)}
- >
- {capError}
- </Banner>
- )}
- <div className="portal-billing__checkout-cap-actions">
- <Button variant="quiet" onClick={onClose} disabled={capBusy}>
- {t("portal.billing.checkout.cap.back", "Back")}
- </Button>
- <Button
- accent="premium"
- loading={capBusy}
- onClick={handleContinue}
- rightSection={<span aria-hidden>›</span>}
- >
- {t("portal.billing.checkout.cap.continue", "Continue to payment")}
- </Button>
+ </p>
+ <p className="portal-billing__checkout-finePrint">
+ {t(
+ "portal.billing.checkout.cap.finePrint",
+ "Invoices post monthly. Cancel anytime.",
+ )}
+ </p>
+ {capError && (
+ <Banner
+ tone="danger"
+ title={t(
+ "portal.billing.checkout.cap.error",
+ "Couldn't set your spend limit",
+ )}
+ >
+ {capError}
+ </Banner>
+ )}
+ <div className="portal-billing__checkout-cap-actions">
+ <Button variant="quiet" onClick={onClose} disabled={capBusy}>
+ {t("portal.billing.checkout.cap.back", "Back")}
+ </Button>
+ <Button
+ accent="premium"
+ loading={capBusy}
+ onClick={handleContinue}
+ rightSection={<span aria-hidden>›</span>}
+ >
+ {t(
+ "portal.billing.checkout.cap.continue",
+ "Continue to payment",
+ )}
+ </Button>
+ </div>
</div>
</div>
)}
{phase === "checkout" && (
<div className="portal-billing__checkout-pay">
- <StepProgress step={2} />
- {!publishableKey && <CardPlaceholder />}
- {publishableKey && error && (
- <Banner
- tone="danger"
- title={t(
- "portal.billing.checkout.error.title",
- "Couldn't start checkout",
- )}
- >
- {error}
- </Banner>
- )}
- {publishableKey && loading && !error && (
- <div className="portal-billing__skeleton" aria-hidden>
- <Skeleton height="3rem" />
- <Skeleton height="18rem" />
- </div>
- )}
- {publishableKey && canRender && stripe && clientSecret && (
- <EmbeddedCheckoutProvider
- stripe={stripe}
- options={{ clientSecret, onComplete: handleStripeComplete }}
- >
- <EmbeddedCheckout />
- </EmbeddedCheckoutProvider>
- )}
+ <PrepayModalHeader
+ step={3}
+ total={3}
+ title={t("portal.billing.checkout.title", "Add a payment method")}
+ onClose={handleClose}
+ />
+ <div className="portal-billing__checkout-scroll">
+ <p className="portal-billing__checkout-limit">
+ {capLabel
+ ? t(
+ "portal.billing.checkout.pay.limit",
+ "Monthly spend limit {{amount}}/mo. Processing pauses at the limit.",
+ { amount: capLabel },
+ )
+ : t(
+ "portal.billing.checkout.pay.limitNoCap",
+ "No spend limit. Processing won't pause. Invoices post monthly.",
+ )}
+ </p>
+ {!publishableKey && <CardPlaceholder />}
+ {publishableKey && error && (
+ <Banner
+ tone="danger"
+ title={t(
+ "portal.billing.checkout.error.title",
+ "Couldn't start checkout",
+ )}
+ >
+ {error}
+ </Banner>
+ )}
+ {publishableKey && loading && !error && (
+ <div className="portal-billing__skeleton" aria-hidden>
+ <Skeleton height="3rem" />
+ <Skeleton height="18rem" />
+ </div>
+ )}
+ {publishableKey && canRender && stripe && clientSecret && (
+ <div className="portal-billing__checkout-embed">
+ <EmbeddedCheckoutProvider
+ stripe={stripe}
+ options={{ clientSecret, onComplete: handleStripeComplete }}
+ >
+ <EmbeddedCheckout />
+ </EmbeddedCheckoutProvider>
+ </div>
+ )}
+ </div>
</div>
)}
</Modal>
diff --git a/frontend/editor/src/portal/components/billing/SubscribedPlanView.stories.tsx b/frontend/editor/src/portal/components/billing/SubscribedPlanView.stories.tsx
index 4083c687f0..1b9c5cc2f8 100644
--- a/frontend/editor/src/portal/components/billing/SubscribedPlanView.stories.tsx
+++ b/frontend/editor/src/portal/components/billing/SubscribedPlanView.stories.tsx
@@ -1,7 +1,10 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { http, HttpResponse } from "msw";
import { SubscribedPlanView } from "@portal/components/billing/SubscribedPlanView";
-import { subscribedWallet } from "@portal/components/billing/walletFixtures";
+import {
+ prepaidWallet,
+ subscribedWallet,
+} from "@portal/components/billing/walletFixtures";
import "@portal/components/billing/billing.css";
const card = http.get("*/api/v1/payg/payment-method", () =>
@@ -64,12 +67,18 @@ const invoices = http.get("*/api/v1/payg/invoices", () =>
const meta: Meta<typeof SubscribedPlanView> = {
title: "Portal/Billing/SubscribedPlanView",
component: SubscribedPlanView,
- parameters: { layout: "padded", msw: { handlers: [card, invoices] } },
+ parameters: {
+ layout: "padded",
+ msw: { handlers: [card, invoices] },
+ },
};
export default meta;
type Story = StoryObj<typeof SubscribedPlanView>;
-/** The full Processor-plan dashboard — leader, within cap. */
+/**
+ * The full Processor-plan dashboard — leader, within cap, no prepaid bundle yet.
+ * Surfaces the "Get 12 months for the price of 10" prepay nudge ("Review offer").
+ */
export const Leader: Story = { args: { wallet: subscribedWallet } };
/** Approaching the cap — surfaces the over-cap warning banner + projection. */
@@ -83,3 +92,6 @@ export const ApproachingCap: Story = {
},
},
};
+
+/** Drawing on a prepaid bundle — surfaces the capacity meter + a "Top up" action. */
+export const WithPrepaid: Story = { args: { wallet: prepaidWallet } };
diff --git a/frontend/editor/src/portal/components/billing/SubscribedPlanView.tsx b/frontend/editor/src/portal/components/billing/SubscribedPlanView.tsx
index 4d92eecf77..ba787a6ad6 100644
--- a/frontend/editor/src/portal/components/billing/SubscribedPlanView.tsx
+++ b/frontend/editor/src/portal/components/billing/SubscribedPlanView.tsx
@@ -7,6 +7,8 @@ import type { LocalUsage } from "@portal/api/link";
import { useStripePortal } from "@portal/hooks/useStripePortal";
import { FreePdfEditorsCard } from "@portal/components/billing/FreePdfEditorsCard";
import { PdfsProcessedCard } from "@portal/components/billing/PdfsProcessedCard";
+import { PrepaidCapacityCard } from "@portal/components/billing/PrepaidCapacityCard";
+import { BundleCheckoutModal } from "@portal/components/billing/BundleCheckoutModal";
import { SpendThisMonthCard } from "@portal/components/billing/SpendThisMonthCard";
import { SpendLimitCard } from "@portal/components/billing/SpendLimitCard";
import { PaymentMethodCard } from "@portal/components/billing/PaymentMethodCard";
@@ -40,9 +42,13 @@ export function SubscribedPlanView({
}: Props) {
const { t } = useTranslation();
const [adjusting, setAdjusting] = useState(false);
+ const [bundleOpen, setBundleOpen] = useState(false);
const portal = useStripePortal(wallet);
const isLeader = wallet.role === "leader";
+ // Buying/topping up prepaid capacity is a commercial action — leader-only, and
+ // needs a resolved team to scope checkout.
+ const canBuyBundle = isLeader && wallet.teamId != null;
const spent =
wallet.estimatedBillMinor != null ? wallet.estimatedBillMinor / 100 : 0;
const capActive = !wallet.noCap && wallet.capUsd != null;
@@ -100,6 +106,11 @@ export function SubscribedPlanView({
<FreePdfEditorsCard />
+ <PrepaidCapacityCard
+ wallet={wallet}
+ onBuy={canBuyBundle ? () => setBundleOpen(true) : undefined}
+ />
+
<PdfsProcessedCard wallet={wallet} unsynced={unsynced} />
<div className="portal-billing__spend-row">
@@ -127,6 +138,15 @@ export function SubscribedPlanView({
{portal.error}
</Banner>
)}
+
+ {canBuyBundle && (
+ <BundleCheckoutModal
+ open={bundleOpen}
+ onClose={() => setBundleOpen(false)}
+ wallet={wallet}
+ onComplete={onWalletChange}
+ />
+ )}
</div>
);
}
diff --git a/frontend/editor/src/portal/components/billing/billing.css b/frontend/editor/src/portal/components/billing/billing.css
index 3ab25438db..cfcbf50697 100644
--- a/frontend/editor/src/portal/components/billing/billing.css
+++ b/frontend/editor/src/portal/components/billing/billing.css
@@ -129,16 +129,6 @@
gap: 0.75rem;
}
-/* Widen the checkout modal past the ~1000px iframe threshold where Stripe
- Embedded Checkout flips from its single-column ("mobile") layout to the
- two-column desktop one — matching the SaaS Plan page's UpgradeModal (1100px
- cap → ~1056px iframe). Two-class selector so it beats .sui-modal--xl's
- max-width regardless of stylesheet order. width:100% still shrinks it on
- narrow viewports, where Stripe falls back to single column on its own. */
-.sui-modal.portal-billing__checkout-modal {
- max-width: 1100px;
-}
-
/* Post-checkout activation state, shown inside the checkout modal while the
subscription webhook lands (and the "almost there" fallback if it lags). */
.portal-billing__checkout-finalizing {
@@ -1048,38 +1038,50 @@
color: var(--color-amber, var(--c-warning));
}
-/* ── Checkout modal: 2-step (spend limit → payment) ──────────────────── */
-.portal-billing__checkout-cap,
-.portal-billing__checkout-pay {
+/* ── Checkout modal: spend-limit + payment steps ─────────────────────────
+ Framed layout: the PrepayModalHeader stays fixed and only the content below
+ it scrolls (not the whole modal). The phase fills the modal body as a flex
+ column — header (fixed) + a scroll region. */
+.portal-billing__checkout-modal--framed .sui-modal__body {
+ padding: 0;
+ overflow: hidden;
+ /* Flex column + min-height:0 so the body is bounded by the modal's max-height and its children's
+ flex sizing takes effect — otherwise the phase grows to full content height and nothing scrolls. */
display: flex;
flex-direction: column;
- gap: 1rem;
+ min-height: 0;
}
-
-.portal-billing__checkout-progress {
- display: flex;
- align-items: center;
- gap: 0.75rem;
+/* Checkout step only: wider than the xl preset so the embedded Stripe iframe clears its ~1000px
+ two-column threshold (otherwise it renders the narrow single-column "portrait" layout). Two-class
+ selector to beat .sui-modal--xl's max-width regardless of stylesheet order. */
+.sui-modal.portal-billing__checkout-modal--wide {
+ max-width: 1120px;
}
-.portal-billing__checkout-steps {
- display: flex;
- gap: 0.375rem;
- flex: 1;
+/* Let the Stripe embedded checkout fill the scroll region's full width (it's the widest thing here). */
+.portal-billing__checkout-embed {
+ width: 100%;
}
-.portal-billing__checkout-steps span {
- height: 4px;
- flex: 1;
- border-radius: var(--radius-pill);
- background: var(--c-border);
+.portal-billing__checkout-cap,
+.portal-billing__checkout-pay {
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 auto;
+ min-height: 0;
}
-.portal-billing__checkout-steps span.is-done {
- background: var(--c-primary);
+/* Header owns its padding now that the modal body's is removed; stays fixed at the top. */
+.portal-billing__checkout-modal--framed .portal-billing__bundle-head {
+ flex: 0 0 auto;
+ margin-bottom: 0;
+ padding: 1rem 1.125rem 0.875rem;
}
-.portal-billing__checkout-stepcount {
- font-size: 0.75rem;
- font-weight: 600;
- color: var(--c-text-subtle);
- white-space: nowrap;
+.portal-billing__checkout-scroll {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+ padding: 0.25rem 1.125rem 1.125rem;
}
.portal-billing__checkout-finePrint {
@@ -1088,6 +1090,16 @@
line-height: 1.55;
color: var(--c-text-subtle);
}
+
+/* Payment-step recap of the spend limit chosen on step 1 (the card form itself is Stripe's iframe). */
+.portal-billing__checkout-limit {
+ margin: 0;
+ padding: 0.625rem 0.875rem;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: 8px;
+ font-size: 0.8125rem;
+ color: var(--c-text-subtle);
+}
.portal-billing__checkout-cap-actions {
display: flex;
justify-content: space-between;
@@ -1095,6 +1107,91 @@
margin-top: 0.25rem;
}
+/* Amount-first spend-limit picker (step 1): the $ /mo field is the primary control; the quick chips
+ below just write into it. Flat estimate (no accent box) to match the demo. */
+.portal-billing__caplimit {
+ display: flex;
+ flex-direction: column;
+ gap: 0.875rem;
+}
+.portal-billing__caplimit-field {
+ display: flex;
+ align-items: baseline;
+ gap: 0.5rem;
+ padding: 0.75rem 1rem;
+ border: 1px solid var(--c-border);
+ border-radius: 10px;
+ background: var(--c-surface);
+}
+.portal-billing__caplimit-field:focus-within {
+ border-color: var(--c-primary);
+}
+.portal-billing__caplimit-sym {
+ font-size: 1.5rem;
+ font-weight: 700;
+ color: var(--c-text-subtle);
+}
+.portal-billing__caplimit-input {
+ flex: 1;
+ min-width: 0;
+ border: none;
+ outline: none;
+ background: transparent;
+ color: var(--c-text);
+ font-size: 1.5rem;
+ font-weight: 700;
+ font-variant-numeric: tabular-nums;
+}
+.portal-billing__caplimit-input::placeholder {
+ color: var(--c-text-subtle);
+ font-weight: 600;
+}
+.portal-billing__caplimit-suffix {
+ font-size: 0.9375rem;
+ color: var(--c-text-subtle);
+}
+.portal-billing__caplimit-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+}
+.portal-billing__caplimit-chip {
+ height: 34px;
+ padding: 0 16px;
+ border-radius: 999px;
+ border: 1px solid var(--c-border);
+ background: var(--c-surface-sunken);
+ color: var(--c-text-muted);
+ font-size: 0.85rem;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+.portal-billing__caplimit-chip:hover:not(:disabled) {
+ border-color: var(--c-text-subtle);
+ color: var(--c-text);
+}
+.portal-billing__caplimit-chip[data-selected="true"] {
+ background: color-mix(in srgb, var(--c-primary) 12%, transparent);
+ border-color: var(--c-primary);
+ color: var(--c-primary);
+}
+.portal-billing__caplimit-chip:disabled {
+ opacity: 0.45;
+}
+.portal-billing__caplimit-estimate {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+}
+.portal-billing__caplimit-estimate-main {
+ font-size: 0.875rem;
+ color: var(--c-text-muted);
+}
+.portal-billing__caplimit-estimate-sub {
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+}
+
/* Card-form placeholder shown when Stripe isn't configured (Storybook / preview). */
.portal-billing__card-placeholder {
display: flex;
@@ -1141,3 +1238,387 @@
line-height: 1.5;
color: var(--c-text-subtle);
}
+
+/* ── Prepaid bundle: buy nudge + top-up + purchase modal ───────────────────── */
+
+/* Slim commit-nudge card shown when the team holds no bundle: title/subtitle
+ left, "Review offer" CTA right. Mirrors the demo's prepay nudge. */
+.portal-billing__prepaid-offer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ flex-wrap: wrap;
+}
+.portal-billing__prepaid-offer-sub {
+ margin: 0.25rem 0 0;
+ font-size: 0.875rem;
+ line-height: 1.5;
+ color: var(--c-text-subtle);
+ max-width: 46ch;
+}
+
+/* Meter card foot: the "used before metered billing" note + a leader Top-up. */
+.portal-billing__prepaid-foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 1rem;
+ margin-top: 0.75rem;
+}
+.portal-billing__prepaid-foot .portal-billing__section-sub {
+ margin: 0;
+}
+
+/* Purchase modal — calculator step. */
+.portal-billing__bundle-calc {
+ display: flex;
+ flex-direction: column;
+ gap: 1.25rem;
+}
+.portal-billing__bundle-fields {
+ display: flex;
+ flex-direction: column;
+ gap: 1rem;
+}
+.portal-billing__bundle-field-label {
+ font-size: 0.8125rem;
+ font-weight: 600;
+ color: var(--c-text-muted);
+ margin-bottom: 0.375rem;
+}
+.portal-billing__bundle-field-hint {
+ margin: 0.375rem 0 0;
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+ line-height: 1.4;
+}
+.portal-billing__bundle-summary {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ padding: 1rem 1.125rem;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: var(--radius-md);
+ background: var(--color-bg-subtle);
+}
+.portal-billing__bundle-summary-row {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 1rem;
+ font-size: 0.9375rem;
+}
+.portal-billing__bundle-summary-row strong {
+ font-size: 1rem;
+}
+.portal-billing__bundle-savings {
+ margin: 0;
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+}
+.portal-billing__bundle-pool {
+ margin: 0;
+ font-size: 0.75rem;
+ color: var(--c-text-subtle);
+ line-height: 1.45;
+}
+
+/* Users field — compact stepper box (demo D147: hugs its content). */
+.portal-billing__bundle-users {
+ max-width: 12rem;
+}
+
+/* Progressive-disclosure finer settings: summary rows that bloom a card picker. */
+.portal-billing__bundle-rows {
+ border: 1px solid var(--c-border-subtle);
+ border-radius: var(--radius-md);
+ overflow: hidden;
+}
+.portal-billing__bundle-row + .portal-billing__bundle-row {
+ border-top: 1px solid var(--c-border-subtle);
+}
+.portal-billing__bundle-row-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+ width: 100%;
+ padding: 0.75rem 0.875rem;
+ border: none;
+ background: transparent;
+ cursor: pointer;
+ text-align: left;
+ font: inherit;
+}
+.portal-billing__bundle-row-label {
+ font-size: 0.75rem;
+ font-weight: 600;
+ color: var(--c-text-subtle);
+}
+.portal-billing__bundle-row-value {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 0.625rem;
+ font-size: 0.8125rem;
+ font-weight: 600;
+ color: var(--c-text);
+ text-align: right;
+}
+.portal-billing__bundle-row-change {
+ font-size: 0.75rem;
+ font-weight: 600;
+ color: var(--c-primary);
+ flex-shrink: 0;
+}
+.portal-billing__bundle-row-body {
+ padding: 0 0.875rem 0.875rem;
+}
+
+/* Card pickers (deployment / sizing / governance / pipelines). */
+.portal-billing__bundle-cards {
+ display: flex;
+ gap: 0.625rem;
+ flex-wrap: wrap;
+}
+.portal-billing__bundle-card {
+ flex: 1;
+ min-width: 9.5rem;
+ padding: 0.75rem 0.875rem;
+ border: 1px solid var(--c-border);
+ border-radius: var(--radius-sm);
+ background: var(--c-surface);
+ cursor: pointer;
+ text-align: left;
+ font: inherit;
+}
+.portal-billing__bundle-card--active {
+ border-color: var(--c-primary);
+ box-shadow: inset 0 0 0 1px var(--c-primary);
+}
+.portal-billing__bundle-card-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 0.5rem;
+}
+.portal-billing__bundle-card-title {
+ font-size: 0.8125rem;
+ font-weight: 700;
+ color: var(--c-text);
+}
+.portal-billing__bundle-card--active .portal-billing__bundle-card-title {
+ color: var(--c-primary);
+}
+.portal-billing__bundle-card-meta {
+ font-size: 0.6875rem;
+ font-weight: 600;
+ color: var(--c-text-subtle);
+ flex-shrink: 0;
+}
+.portal-billing__bundle-card--active .portal-billing__bundle-card-meta {
+ color: var(--c-primary);
+}
+.portal-billing__bundle-card-desc {
+ margin-top: 0.1875rem;
+ font-size: 0.7188rem;
+ line-height: 1.4;
+ color: var(--c-text-subtle);
+}
+
+/* Receipt card — "your Processor / your year / pool / download". */
+.portal-billing__bundle-receipt {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ padding: 1rem 1.125rem;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: var(--radius-md);
+ background: var(--color-bg-subtle);
+}
+.portal-billing__bundle-receipt-row {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 1rem;
+ font-size: 0.875rem;
+ color: var(--c-text-muted);
+}
+.portal-billing__bundle-receipt-row strong {
+ font-size: 0.9375rem;
+ color: var(--c-text);
+}
+/* First row reads as the header — bold both sides ("Your Processor / handles N credits / mo"). */
+.portal-billing__bundle-receipt-row--head span {
+ font-weight: 700;
+ color: var(--c-text);
+}
+.portal-billing__bundle-receipt-price {
+ color: var(--c-primary) !important;
+}
+.portal-billing__bundle-consent {
+ padding-top: 0.75rem;
+ border-top: 1px solid var(--c-border-subtle);
+}
+/* Recipient fields on the payment step, kept compact so the step fits without scrolling. */
+.portal-billing__bundle-fields {
+ display: flex;
+ flex-direction: column;
+ gap: 0.625rem;
+}
+/* Company name + PO number share a row. */
+.portal-billing__bundle-field-row {
+ display: flex;
+ gap: 0.625rem;
+}
+.portal-billing__bundle-field-row > * {
+ flex: 1 1 0;
+ min-width: 0;
+}
+/* Bundle modal header — brand · step badge · progress · step title. */
+.portal-billing__bundle-head {
+ display: flex;
+ flex-direction: column;
+ gap: 0.875rem;
+ margin-bottom: 1.25rem;
+}
+.portal-billing__bundle-head-top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+.portal-billing__bundle-brand {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-weight: 700;
+ font-size: 0.9375rem;
+ color: var(--c-text);
+}
+/* Trademarked wordmark SVG (theme-switched via .wordmark-light-only/.wordmark-dark-only). Height
+ matches the portal nav's 22px wordmark so the modal and app read as one brand. No `display` here —
+ the theme-switch utilities own visibility. */
+.portal-billing__bundle-wordmark {
+ height: 1.375rem;
+ width: auto;
+}
+.portal-billing__bundle-head-right {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+.portal-billing__bundle-step {
+ padding: 0.1875rem 0.625rem;
+ border: 1px solid var(--c-border-subtle);
+ border-radius: 999px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ color: var(--c-text-subtle);
+ white-space: nowrap;
+}
+.portal-billing__bundle-progress {
+ display: flex;
+ gap: 0.375rem;
+}
+.portal-billing__bundle-progress > span {
+ flex: 1;
+ height: 4px;
+ border-radius: 999px;
+ background: var(--c-border-subtle);
+}
+.portal-billing__bundle-progress > span.is-filled {
+ background: var(--c-primary);
+}
+.portal-billing__bundle-head-title {
+ font-size: 1.25rem;
+ font-weight: 700;
+ color: var(--c-text);
+}
+
+/* Payment step: quote receipt + recipient fields + consent. */
+.portal-billing__bundle-pay {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+}
+/* "Download quote (PDF) · share for approval" — a quiet link under the receipt. */
+.portal-billing__bundle-download {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4375rem;
+ margin-top: 0.25rem;
+ padding: 0.5rem 0 0;
+ border: none;
+ border-top: 1px solid var(--c-border-subtle);
+ background: none;
+ cursor: pointer;
+ font: inherit;
+ font-size: 0.75rem;
+ font-weight: 600;
+ color: var(--c-primary);
+ text-align: left;
+}
+.portal-billing__bundle-download-share {
+ color: var(--c-text-subtle);
+ font-weight: 400;
+}
+.portal-billing__bundle-foot-end {
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.5rem;
+}
+
+/* Activation fork (demo D97): two "how do you want to pay?" door-cards. */
+.portal-billing__door-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 12px;
+}
+/* "Maybe later" — a quiet dismiss under the door-cards, left-aligned. */
+.portal-billing__door-later {
+ display: flex;
+ justify-content: flex-start;
+ margin-top: 1rem;
+}
+@media (max-width: 560px) {
+ .portal-billing__door-grid {
+ grid-template-columns: 1fr;
+ }
+}
+.portal-billing__door {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ height: 100%;
+ text-align: left;
+ cursor: pointer;
+}
+.portal-billing__door--accent {
+ border-color: var(--c-primary);
+ background: var(--c-primary-subtle);
+}
+.portal-billing__door-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+}
+.portal-billing__door-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--c-text);
+}
+.portal-billing__door-badge {
+ flex-shrink: 0;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--c-primary);
+ background: var(--c-surface);
+ padding: 2px 8px;
+ border-radius: 8px;
+}
+.portal-billing__door-sub {
+ font-size: 12.5px;
+ line-height: 1.5;
+ color: var(--c-text-subtle);
+}
diff --git a/frontend/editor/src/portal/components/billing/walletFixtures.ts b/frontend/editor/src/portal/components/billing/walletFixtures.ts
index cd754af3fc..a3dcc3c5a2 100644
--- a/frontend/editor/src/portal/components/billing/walletFixtures.ts
+++ b/frontend/editor/src/portal/components/billing/walletFixtures.ts
@@ -23,6 +23,10 @@ export const freeWallet: Wallet = {
docsProcessedThisPeriod: 90,
uniquePdfsThisPeriod: 84,
sizeMultiplierPdfsThisPeriod: 12,
+ billingMode: "payg",
+ prepaidUnitsRemaining: 0,
+ prepaidUnitsTotal: 0,
+ prepaidExpiresAt: null,
members: [],
recent: [],
};
@@ -50,6 +54,10 @@ export const subscribedWallet: Wallet = {
docsProcessedThisPeriod: 1750,
uniquePdfsThisPeriod: 1600,
sizeMultiplierPdfsThisPeriod: 320,
+ billingMode: "payg",
+ prepaidUnitsRemaining: 0,
+ prepaidUnitsTotal: 0,
+ prepaidExpiresAt: null,
members: [
{
userId: "u1",
@@ -66,3 +74,16 @@ export const subscribedWallet: Wallet = {
],
recent: [],
};
+
+/**
+ * Subscribed team currently drawing on a prepaid bundle — {@code billingMode:
+ * "prepaid"} with a mid-drawn pool (78k of 120k left) expiring in-term. Drives the
+ * prepaid-capacity card + the "Prepaid year" chip.
+ */
+export const prepaidWallet: Wallet = {
+ ...subscribedWallet,
+ billingMode: "prepaid",
+ prepaidUnitsRemaining: 78000,
+ prepaidUnitsTotal: 120000,
+ prepaidExpiresAt: "2027-03-01",
+};
diff --git a/frontend/editor/src/portal/hooks/useBundleFlowState.test.tsx b/frontend/editor/src/portal/hooks/useBundleFlowState.test.tsx
new file mode 100644
index 0000000000..159ac12f83
--- /dev/null
+++ b/frontend/editor/src/portal/hooks/useBundleFlowState.test.tsx
@@ -0,0 +1,107 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, render, waitFor } from "@testing-library/react";
+
+/**
+ * The billing page's CTA is driven entirely by this hook's derived status, so the
+ * quote → invoice → none classification (and the leader/team gate that keeps the
+ * RPC from firing) are what the guards below lock down.
+ */
+const { getLatestBundleQuote } = vi.hoisted(() => ({
+ getLatestBundleQuote: vi.fn(),
+}));
+vi.mock("@portal/billing/stripe", () => ({ getLatestBundleQuote }));
+
+import { useBundleFlowState } from "@portal/hooks/useBundleFlowState";
+import type { LatestBundleQuote } from "@portal/billing/stripe";
+
+const baseQuote: LatestBundleQuote = {
+ quoteId: 7,
+ users: 25,
+ posturePolicies: 4,
+ sizeMult: 1.2,
+ pipelineMult: 1,
+ poolCredits: 576000,
+ priceMinor: 480000,
+ currency: "usd",
+ consentedAt: null,
+ stripeQuoteId: "qt_1",
+ stripeQuoteNumber: "QT-0007",
+ stripeRef: null,
+ validUntil: "2026-08-16T00:00:00Z",
+};
+
+let latest: ReturnType<typeof useBundleFlowState>;
+function Probe({
+ teamId,
+ enabled,
+}: {
+ teamId: number | null;
+ enabled?: boolean;
+}) {
+ latest = useBundleFlowState(teamId, enabled);
+ return null;
+}
+
+beforeEach(() => {
+ getLatestBundleQuote.mockReset();
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe("useBundleFlowState", () => {
+ it("classifies no open quote as 'none'", async () => {
+ getLatestBundleQuote.mockResolvedValue(null);
+ render(<Probe teamId={1} />);
+ await waitFor(() => expect(latest.loading).toBe(false));
+ expect(latest.status).toBe("none");
+ expect(latest.latest).toBeNull();
+ expect(getLatestBundleQuote).toHaveBeenCalledWith(1);
+ });
+
+ it("classifies an un-accepted quote as 'quote'", async () => {
+ getLatestBundleQuote.mockResolvedValue({ ...baseQuote, stripeRef: null });
+ render(<Probe teamId={1} />);
+ await waitFor(() => expect(latest.status).toBe("quote"));
+ expect(latest.latest?.quoteId).toBe(7);
+ });
+
+ it("classifies an accepted quote (invoice awaiting payment) as 'invoice'", async () => {
+ getLatestBundleQuote.mockResolvedValue({ ...baseQuote, stripeRef: "in_1" });
+ render(<Probe teamId={1} />);
+ await waitFor(() => expect(latest.status).toBe("invoice"));
+ });
+
+ it("stays 'none' and never reads the RPC when disabled", async () => {
+ render(<Probe teamId={1} enabled={false} />);
+ await waitFor(() => expect(latest.loading).toBe(false));
+ expect(latest.status).toBe("none");
+ expect(getLatestBundleQuote).not.toHaveBeenCalled();
+ });
+
+ it("stays 'none' and never reads the RPC without a team", async () => {
+ render(<Probe teamId={null} />);
+ await waitFor(() => expect(latest.loading).toBe(false));
+ expect(latest.status).toBe("none");
+ expect(getLatestBundleQuote).not.toHaveBeenCalled();
+ });
+
+ it("falls back to 'none' when the RPC rejects (no backend / not a leader)", async () => {
+ getLatestBundleQuote.mockRejectedValue(new Error("42501"));
+ render(<Probe teamId={1} />);
+ await waitFor(() => expect(latest.loading).toBe(false));
+ expect(latest.status).toBe("none");
+ });
+
+ it("re-reads on refresh() so a freshly-minted invoice flips the status", async () => {
+ getLatestBundleQuote.mockResolvedValueOnce(null);
+ render(<Probe teamId={1} />);
+ await waitFor(() => expect(latest.status).toBe("none"));
+
+ getLatestBundleQuote.mockResolvedValueOnce({
+ ...baseQuote,
+ stripeRef: "in_1",
+ });
+ act(() => latest.refresh());
+ await waitFor(() => expect(latest.status).toBe("invoice"));
+ expect(getLatestBundleQuote).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/editor/src/portal/hooks/useBundleFlowState.ts b/frontend/editor/src/portal/hooks/useBundleFlowState.ts
new file mode 100644
index 0000000000..0ded198c8b
--- /dev/null
+++ b/frontend/editor/src/portal/hooks/useBundleFlowState.ts
@@ -0,0 +1,75 @@
+import { useCallback, useEffect, useState } from "react";
+import {
+ getLatestBundleQuote,
+ type LatestBundleQuote,
+} from "@portal/billing/stripe";
+
+/**
+ * Where a team sits in the prepaid-bundle purchase:
+ * - none → no open quote; the buyer hasn't started (or the last one expired).
+ * - quote → an open quote exists but hasn't been accepted (no invoice yet).
+ * - invoice → the quote is accepted and an invoice is awaiting payment.
+ */
+export type BundleFlowStatus = "none" | "quote" | "invoice";
+
+export interface BundleFlowState {
+ status: BundleFlowStatus;
+ /** The underlying quote row, or null when {@code status === "none"}. */
+ latest: LatestBundleQuote | null;
+ /** First load (or a refresh) is in flight. */
+ loading: boolean;
+ /** Re-read the latest quote — call after the checkout modal closes so the CTA reflects new state. */
+ refresh: () => void;
+}
+
+/**
+ * Page-level probe for the prepaid-bundle flow, so the billing page can render the
+ * right CTA on load — "View quote" once a quote exists, "Pay invoice to complete"
+ * once it's accepted — instead of always restarting the activation fork. The heavy
+ * hydration (sizing, re-accept) still lives in {@code BundleCheckoutModal}; this
+ * only classifies the latest quote so the entry point can name the resume action.
+ *
+ * Effectively leader-scoped: {@code payg_get_latest_bundle_quote} 403s for
+ * non-leaders, which (like an unconfigured backend) we treat as "none". Only
+ * meaningful for a free team — a paid invoice flips the team to subscribed. Pass
+ * {@code enabled: false} to skip the read entirely (non-leaders, no team).
+ */
+export function useBundleFlowState(
+ teamId: number | null | undefined,
+ enabled = true,
+): BundleFlowState {
+ const [latest, setLatest] = useState<LatestBundleQuote | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [tick, setTick] = useState(0);
+ const refresh = useCallback(() => setTick((t) => t + 1), []);
+
+ useEffect(() => {
+ if (!enabled || teamId == null) {
+ setLatest(null);
+ setLoading(false);
+ return;
+ }
+ let cancelled = false;
+ setLoading(true);
+ getLatestBundleQuote(teamId)
+ .then((q) => {
+ if (!cancelled) setLatest(q);
+ })
+ .catch(() => {
+ // No backend / not a leader / transient — fall back to "none" rather than
+ // block the page. The modal is the source of truth once it opens.
+ if (!cancelled) setLatest(null);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [teamId, enabled, tick]);
+
+ const status: BundleFlowStatus =
+ latest == null ? "none" : latest.stripeRef ? "invoice" : "quote";
+
+ return { status, latest, loading, refresh };
+}
diff --git a/frontend/editor/src/proprietary/billing/format.test.ts b/frontend/editor/src/proprietary/billing/format.test.ts
new file mode 100644
index 0000000000..314c606080
--- /dev/null
+++ b/frontend/editor/src/proprietary/billing/format.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect } from "vitest";
+import {
+ estimateMonthlyVolumeFromUsers,
+ provisionMonthlyVolume,
+ bundlePoolCredits,
+ bundleListMinor,
+ bundlePriceMinor,
+ computeBundleQuote,
+} from "@app/billing";
+
+/**
+ * The run-based prepaid brain must mirror the marketing calculator (users → volume,
+ * ~3× provisioning, size-folded run pool, 12-for-10) so the buyer sees the number the
+ * server charges. The pool is the Stripe line quantity + the credited pool, in the
+ * same size-scaled runs the meter charges on consumption.
+ */
+describe("prepaid bundle brain", () => {
+ it("estimates monthly volume from users (× 80/user, clean step)", () => {
+ expect(estimateMonthlyVolumeFromUsers(25)).toBe(2000); // 25 × 80
+ expect(estimateMonthlyVolumeFromUsers(300)).toBe(24000); // ≥20k → 500 step
+ expect(estimateMonthlyVolumeFromUsers(0)).toBe(0);
+ });
+
+ it("provisions ~3× above expected, rounded up to a clean magnitude", () => {
+ expect(provisionMonthlyVolume(1000)).toBe(5000); // target 3000 → 5×1000
+ expect(provisionMonthlyVolume(2000)).toBe(10000); // target 6000 → 10×1000
+ expect(provisionMonthlyVolume(0)).toBe(0);
+ });
+
+ it("sizes the pool in size-folded runs (volume × policies × pipelines × size × 12)", () => {
+ // 10,000/mo × Governed(4 policies) × None(×1) × Standard(×1.2) × 12.
+ expect(bundlePoolCredits(10000, 4, 1, 1.2)).toBe(576_000);
+ // Size ×1 → 10,000 × 4 × 1 × 12.
+ expect(bundlePoolCredits(10000, 4, 1, 1.0)).toBe(480_000);
+ // Pipelines multiply runs like policies do.
+ expect(bundlePoolCredits(10000, 4, 2, 1.0)).toBe(960_000);
+ });
+
+ it("zeroes the pool for non-positive inputs", () => {
+ expect(bundlePoolCredits(0, 4, 1, 1.2)).toBe(0);
+ expect(bundlePoolCredits(10000, 0, 1, 1.2)).toBe(0);
+ expect(bundlePoolCredits(10000, 4, 0, 1.2)).toBe(0);
+ });
+
+ it("computes an end-to-end quote from users + finer settings", () => {
+ const q = computeBundleQuote({
+ users: 25,
+ posturePolicies: 4,
+ sizeMult: 1.2,
+ pipelineMult: 1,
+ ratePerRunMinor: 1,
+ });
+ expect(q.expectedMonthlyVolume).toBe(2000);
+ expect(q.provisionedMonthlyVolume).toBe(10000);
+ expect(q.poolCredits).toBe(576_000);
+ expect(q.listMinor).toBe(576_000); // 576k credits × 1¢
+ expect(q.priceMinor).toBe(480_000); // × 10/12
+ expect(q.savingsMinor).toBe(96_000);
+ expect(q.overEnterprise).toBe(false);
+ });
+
+ it("flags enterprise scale on EXPECTED (not provisioned) runs/yr over the ceiling", () => {
+ const q = computeBundleQuote({
+ users: 3000,
+ posturePolicies: 7,
+ sizeMult: 2.0,
+ pipelineMult: 10,
+ ratePerRunMinor: 1,
+ });
+ // expected 240k/mo × 7 × 10 × 12 ≫ 1M runs/yr.
+ expect(q.overEnterprise).toBe(true);
+ });
+
+ it("hides money when the rate is unknown", () => {
+ const q = computeBundleQuote({
+ users: 25,
+ posturePolicies: 4,
+ sizeMult: 1.2,
+ pipelineMult: 1,
+ ratePerRunMinor: null,
+ });
+ expect(q.poolCredits).toBe(576_000);
+ expect(q.listMinor).toBeNull();
+ expect(q.priceMinor).toBeNull();
+ expect(q.savingsMinor).toBeNull();
+ });
+
+ it("applies the 12-for-10 discount at the per-run rate", () => {
+ // 120k credits × 2 minor = 240,000 list; × 10/12 = 200,000 paid.
+ expect(bundleListMinor(120_000, 2)).toBe(240_000);
+ expect(bundlePriceMinor(120_000, 2)).toBe(200_000);
+ });
+
+ it("rounds sub-cent rates to the minor unit (HALF_UP)", () => {
+ // 100k × 0.5 = 50,000 list; × 10/12 = 41,666.67 → 41,667.
+ expect(bundleListMinor(100_000, 0.5)).toBe(50_000);
+ expect(bundlePriceMinor(100_000, 0.5)).toBe(41_667);
+ });
+
+ it("returns null money when the rate is unknown or non-positive", () => {
+ expect(bundleListMinor(120_000, null)).toBeNull();
+ expect(bundlePriceMinor(120_000, null)).toBeNull();
+ expect(bundlePriceMinor(120_000, 0)).toBeNull();
+ });
+});
diff --git a/frontend/editor/src/proprietary/billing/format.ts b/frontend/editor/src/proprietary/billing/format.ts
index 194a9bd686..2a5f406cc0 100644
--- a/frontend/editor/src/proprietary/billing/format.ts
+++ b/frontend/editor/src/proprietary/billing/format.ts
@@ -88,6 +88,204 @@ export function formatPeriodDate(
}
}
+// ─── Prepaid bundle pricing (run-based brain) ───────────────────────────────
+
+/**
+ * "12 months for the price of 10" — months granted vs paid. Mirrors the Stripe
+ * coupon (10/12 off), so the calculator's live estimate matches the amount charged.
+ */
+export const PREPAID_MONTHS_GRANTED = 12;
+export const PREPAID_MONTHS_PAID = 10;
+
+/**
+ * People-driven traffic estimate: one Stirling user runs ≈ this many PDFs a month
+ * (WBR telemetry). The self-serve prepay flow sizes the year from USERS and derives
+ * volume from this rate rather than asking the buyer to guess a PDF count.
+ */
+export const PDFS_PER_USER_MONTH = 80;
+
+/**
+ * Above this many EXPECTED runs/yr the self-serve prepay flow hands off to the
+ * enterprise quote — committed-volume pricing is negotiated, never self-served.
+ */
+export const BUNDLE_SELF_SERVE_RUN_CEILING_YR = 1_000_000;
+
+/**
+ * Governance posture as a policy-run count — the intensity fed to the pricing brain
+ * (a PDF through N policies is N runs). Replaces the retired ×1.4/2.4/4.0 posture
+ * multiplier: the policy count IS the multiplier now.
+ */
+export const BUNDLE_POLICY_POSTURES = [
+ { id: "essentials", policies: 2 },
+ { id: "governed", policies: 4 },
+ { id: "regulated", policies: 7 },
+] as const;
+
+/** File-size tier — the data multiplier folded into the pool (a bigger PDF draws more). */
+export const BUNDLE_SIZE_TIERS = [
+ { id: "compact", mult: 1.0 },
+ { id: "standard", mult: 1.2 },
+ { id: "heavy", mult: 2.0 },
+] as const;
+
+/** Pipeline intensity — pipelines multiply runs per PDF exactly like policies do. */
+export const BUNDLE_PIPELINE_TIERS = [
+ { id: "none", mult: 1 },
+ { id: "standard", mult: 2 },
+ { id: "advanced", mult: 10 },
+] as const;
+
+/**
+ * Estimated monthly people-driven PDF volume for a team of {@code users}
+ * ({@code users ×} {@link PDFS_PER_USER_MONTH}, rounded to a clean step); zero for a
+ * non-positive team size.
+ */
+export function estimateMonthlyVolumeFromUsers(users: number): number {
+ if (users <= 0) return 0;
+ const raw = users * PDFS_PER_USER_MONTH;
+ const step = raw >= 20000 ? 500 : 100;
+ return Math.max(step, Math.round(raw / step) * step);
+}
+
+/**
+ * Provisioned monthly PDF capacity for an {@code expectedMonthly} volume: ~3× above
+ * expected (buyers compare a plan to a stock, not a flow), rounded up to a clean
+ * 1/2/2.5/5/10 magnitude. Renewals re-size to observed usage, so generous
+ * provisioning stays fair.
+ */
+export function provisionMonthlyVolume(expectedMonthly: number): number {
+ if (expectedMonthly <= 0) return 0;
+ const target = expectedMonthly * 3;
+ const mag = Math.pow(10, Math.floor(Math.log10(target)));
+ const steps = [1, 2, 2.5, 5, 10];
+ for (const s of steps) if (s * mag >= target) return Math.round(s * mag);
+ return Math.round(10 * mag);
+}
+
+/**
+ * Prepaid pool size in run-credits for a provisioned monthly PDF volume at a given
+ * posture (policy runs/PDF), pipeline intensity, and file-size tier, over the term.
+ * The pool is denominated in the SAME size-scaled runs the meter charges on
+ * consumption, so buying and spending are one currency; each credit is the list run
+ * rate. Size folds in as extra credits.
+ */
+export function bundlePoolCredits(
+ provisionedMonthlyVolume: number,
+ posturePolicies: number,
+ pipelineMult: number,
+ sizeMult: number,
+ monthsGranted: number = PREPAID_MONTHS_GRANTED,
+): number {
+ if (
+ provisionedMonthlyVolume <= 0 ||
+ posturePolicies <= 0 ||
+ pipelineMult <= 0 ||
+ sizeMult <= 0
+ )
+ return 0;
+ const runsPerMonth =
+ provisionedMonthlyVolume * posturePolicies * pipelineMult;
+ return Math.round(runsPerMonth * sizeMult) * monthsGranted;
+}
+
+/** Undiscounted "worth" of a pool in minor units (units × rate); null when the rate is unknown. */
+export function bundleListMinor(
+ units: number,
+ ratePerUnitMinor: number | null | undefined,
+): number | null {
+ const rate =
+ ratePerUnitMinor != null && ratePerUnitMinor > 0 ? ratePerUnitMinor : null;
+ return rate != null ? Math.round(units * rate) : null;
+}
+
+/**
+ * Discounted price of a prepaid pool in minor units: units × rate × paid/granted.
+ * Mirror of the Stripe coupon. Null when the rate is unknown (the caller hides the
+ * figure and falls back to the server total).
+ */
+export function bundlePriceMinor(
+ units: number,
+ ratePerUnitMinor: number | null | undefined,
+ monthsPaid: number = PREPAID_MONTHS_PAID,
+ monthsGranted: number = PREPAID_MONTHS_GRANTED,
+): number | null {
+ const rate =
+ ratePerUnitMinor != null && ratePerUnitMinor > 0 ? ratePerUnitMinor : null;
+ return rate != null
+ ? Math.round((units * rate * monthsPaid) / monthsGranted)
+ : null;
+}
+
+/** Inputs to {@link computeBundleQuote} — team size + the finer-setting multipliers. */
+export interface BundleQuoteInput {
+ /** Team size — the primary sizing input; volume + pool derive from it. */
+ users: number;
+ /** Governance posture as a policy-run count (2 / 4 / 7). */
+ posturePolicies: number;
+ /** File-size tier multiplier (1.0 / 1.2 / 2.0). */
+ sizeMult: number;
+ /** Pipeline intensity multiplier (1 / 2 / 10). */
+ pipelineMult: number;
+ /** Per-run list rate in minor units; null when unresolved (price is hidden). */
+ ratePerRunMinor: number | null | undefined;
+}
+
+/** The derived breakdown {@link computeBundleQuote} returns. */
+export interface BundleQuoteBreakdown {
+ /** People-driven monthly volume estimated from users (pre-provisioning). */
+ expectedMonthlyVolume: number;
+ /** Provisioned monthly PDF capacity (~3× expected) — the "handles X/mo" headline. */
+ provisionedMonthlyVolume: number;
+ /** Size-folded runs the pool represents = Stripe line quantity + credited pool. */
+ poolCredits: number;
+ listMinor: number | null;
+ priceMinor: number | null;
+ savingsMinor: number | null;
+ /** EXPECTED runs/yr exceed the self-serve ceiling → route to the enterprise quote. */
+ overEnterprise: boolean;
+}
+
+/**
+ * The one self-serve prepay pricing brain: team size + finer settings → the pool,
+ * price, and enterprise-ladder flag. Volume is derived from users (never asked) and
+ * provisioned ~3× above expected; the pool is size-folded runs — the Stripe line
+ * quantity AND the credited pool, in the same currency the meter charges on
+ * consumption. Mirrors the marketing calculator so the buyer sees the number the
+ * server charges.
+ */
+export function computeBundleQuote(
+ input: BundleQuoteInput,
+): BundleQuoteBreakdown {
+ const { users, posturePolicies, sizeMult, pipelineMult, ratePerRunMinor } =
+ input;
+ const expectedMonthlyVolume = estimateMonthlyVolumeFromUsers(users);
+ const provisionedMonthlyVolume = provisionMonthlyVolume(
+ expectedMonthlyVolume,
+ );
+ const poolCredits = bundlePoolCredits(
+ provisionedMonthlyVolume,
+ posturePolicies,
+ pipelineMult,
+ sizeMult,
+ );
+ const listMinor = bundleListMinor(poolCredits, ratePerRunMinor);
+ const priceMinor = bundlePriceMinor(poolCredits, ratePerRunMinor);
+ const savingsMinor =
+ listMinor != null && priceMinor != null ? listMinor - priceMinor : null;
+ const expectedRunsYr =
+ Math.round(expectedMonthlyVolume * posturePolicies * pipelineMult) * 12;
+ const overEnterprise = expectedRunsYr > BUNDLE_SELF_SERVE_RUN_CEILING_YR;
+ return {
+ expectedMonthlyVolume,
+ provisionedMonthlyVolume,
+ poolCredits,
+ listMinor,
+ priceMinor,
+ savingsMinor,
+ overEnterprise,
+ };
+}
+
export type MeterState = "FULL" | "WARNED" | "DEGRADED";
/** Warn (≥80%) / degrade (≥100%) band for a usage meter; mirrors the BE thresholds. */
diff --git a/frontend/editor/src/proprietary/billing/index.ts b/frontend/editor/src/proprietary/billing/index.ts
index 228458ca9b..687adec541 100644
--- a/frontend/editor/src/proprietary/billing/index.ts
+++ b/frontend/editor/src/proprietary/billing/index.ts
@@ -14,6 +14,21 @@ export {
docCapForMoney,
formatPeriodDate,
meterState,
+ PREPAID_MONTHS_GRANTED,
+ PREPAID_MONTHS_PAID,
+ PDFS_PER_USER_MONTH,
+ BUNDLE_SELF_SERVE_RUN_CEILING_YR,
+ BUNDLE_POLICY_POSTURES,
+ BUNDLE_SIZE_TIERS,
+ BUNDLE_PIPELINE_TIERS,
+ estimateMonthlyVolumeFromUsers,
+ provisionMonthlyVolume,
+ bundlePoolCredits,
+ bundleListMinor,
+ bundlePriceMinor,
+ computeBundleQuote,
+ type BundleQuoteInput,
+ type BundleQuoteBreakdown,
type MeterState,
} from "@app/billing/format";
export { MeterBar } from "@app/billing/MeterBar";
diff --git a/frontend/editor/src/proprietary/billing/types.ts b/frontend/editor/src/proprietary/billing/types.ts
index 46fd228f73..1fd2fbea9c 100644
--- a/frontend/editor/src/proprietary/billing/types.ts
+++ b/frontend/editor/src/proprietary/billing/types.ts
@@ -76,6 +76,14 @@ export interface Wallet {
uniquePdfsThisPeriod: number;
/** Input files on charges where the size multiplier applied (units billed &gt; input files). */
sizeMultiplierPdfsThisPeriod: number;
+ /** "prepaid" while prepaid-bundle units remain (drawn ahead of the meter), else "payg". */
+ billingMode: "prepaid" | "payg";
+ /** Prepaid units still available across the team's in-term bundles; 0 = none/exhausted. */
+ prepaidUnitsRemaining: number;
+ /** Total capacity of in-term prepaid bundles — the "X of Y used" denominator; 0 = no bundle. */
+ prepaidUnitsTotal: number;
+ /** Soonest bundle term-end (ISO yyyy-mm-dd) for the countdown; null when no bundle. */
+ prepaidExpiresAt: string | null;
/** Populated for the leader view; empty for members / single-seat tenants. */
members: WalletMember[];
recent: WalletActivityRow[];
diff --git a/frontend/editor/src/saas/components/shared/FreeLimitReachedModal.test.tsx b/frontend/editor/src/saas/components/shared/FreeLimitReachedModal.test.tsx
index d70d807b25..1565f88d9a 100644
--- a/frontend/editor/src/saas/components/shared/FreeLimitReachedModal.test.tsx
+++ b/frontend/editor/src/saas/components/shared/FreeLimitReachedModal.test.tsx
@@ -31,6 +31,10 @@ const wallet: Wallet = {
docsProcessedThisPeriod: 0,
uniquePdfsThisPeriod: 0,
sizeMultiplierPdfsThisPeriod: 0,
+ billingMode: "payg",
+ prepaidUnitsRemaining: 0,
+ prepaidUnitsTotal: 0,
+ prepaidExpiresAt: null,
members: [],
recent: [],
};
diff --git a/frontend/editor/src/saas/hooks/walletDevPreview.ts b/frontend/editor/src/saas/hooks/walletDevPreview.ts
index 1529058f15..216e9fb536 100644
--- a/frontend/editor/src/saas/hooks/walletDevPreview.ts
+++ b/frontend/editor/src/saas/hooks/walletDevPreview.ts
@@ -72,6 +72,12 @@ function buildDevPreviewWallet(role: WalletRole): Wallet {
docsProcessedThisPeriod: 50,
uniquePdfsThisPeriod: 48,
sizeMultiplierPdfsThisPeriod: 8,
+ // Illustrative prepaid bundle so the /dev/payg-preview route can design the
+ // prepaid-capacity card + banner (drawn ahead of the meter, outside the cap).
+ billingMode: "prepaid",
+ prepaidUnitsRemaining: 78_000,
+ prepaidUnitsTotal: 120_000,
+ prepaidExpiresAt: "2027-03-01",
categoryDocs: { api: 18, ai: 14, automation: 18 },
// Wave 1 backend (PR #6574) returns a per-category breakdown so the
// hero panel can split AI / automation / API. Use realistic but