#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Support shared monthly Team credits in billing and linked instances (#8039)
ConnorYohffca42e5dd41
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.javaindex 3418efd965..b03358fc16 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkClient.java@@ -358,7 +358,8 @@ public class AccountLinkClient {parseDateTime(root, "periodStart"),parseDateTime(root, "periodEnd"),licensedUsers,- root.path("automationStepLimit").asInt(0));+ root.path("automationStepLimit").asInt(0),+ root.path("prepaidRemainingUnits").asLong(0));}/** Parses the nested unit-calc policy; null if absent or any knob is invalid (e.g. zero). */diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.javaindex 2956fad057..2d4fcfe21e 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlement.java@@ -34,7 +34,8 @@ public record InstanceEntitlement(LocalDateTime periodStart,LocalDateTime periodEnd,Integer licensedUsers,- int automationStepLimit) {+ int automationStepLimit,+ long prepaidRemainingUnits) {public InstanceEntitlement {automationStepLimit = BillingStepLimit.resolve(automationStepLimit);@@ -61,7 +62,8 @@ public record InstanceEntitlement(periodStart,periodEnd,licensedUsers,- BillingStepLimit.resolve(null));+ BillingStepLimit.resolve(null),+ 0L);}/** Gate-only view with no metering config — used by the revoked sentinel and gate tests. */diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.javaindex a2d3367633..71d87bf8c2 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/InstanceEntitlementGate.java@@ -128,6 +128,11 @@ public class InstanceEntitlementGate {if (e.state() == EntitlementState.OVER_LIMIT || e.state() == EntitlementState.REVOKED) {return false;}+ long pendingAfterIncluded = Math.max(0, pendingUnsyncedUnits - e.freeRemainingUnits());+ if (e.freeRemainingUnits() > Math.max(0, pendingUnsyncedUnits)+ || e.prepaidRemainingUnits() > pendingAfterIncluded) {+ return true;+ }if (e.subscribed()) {if (e.periodCapUnits() == null) {return true; // uncapped subscription@@ -135,7 +140,7 @@ public class InstanceEntitlementGate {// Project the cap the way the grant is projected: synced paid spend plus the paid part// of local usage not yet synced (free grant is consumed first, so only the excess// bills) — stops at the cap in real time instead of overshooting until the next sync.- long pendingPaid = Math.max(0, pendingUnsyncedUnits - e.freeRemainingUnits());+ long pendingPaid = Math.max(0, pendingAfterIncluded - e.prepaidRemainingUnits());return e.periodSpendUnits() + pendingPaid < e.periodCapUnits();}// Unsubscribed: free pool must cover SaaS-charged usage (in freeRemainingUnits) plus localdiff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.javaindex edfe8c2068..812dfb8b06 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementGateTest.java@@ -32,6 +32,35 @@ class InstanceEntitlementGateTest {@Mock private LocalUsageService localUsageService;@Mock private FreeTierUsageService freeTierUsageService;+ @Test+ void includedAndPrepaidCreditsRemainUsableAtZeroMeteredCap() {+ InstanceEntitlement e =+ new InstanceEntitlement(+ true, 20, 0, 0L, EntitlementState.OK, null, null, null, null, 0, 10);+ assertTrue(+ InstanceEntitlementGate.decide(true, true, true, Optional.of(e), false, 19, 0)+ .allowed());+ assertTrue(+ InstanceEntitlementGate.decide(true, true, true, Optional.of(e), false, 29, 0)+ .allowed());+ assertFalse(+ InstanceEntitlementGate.decide(true, true, true, Optional.of(e), false, 30, 0)+ .allowed());+ }++ @Test+ void prepaidCreditsDoNotRequireProcessorSubscription() {+ InstanceEntitlement e =+ new InstanceEntitlement(+ false, 0, 0, null, EntitlementState.OK, null, null, null, null, 0, 10);+ assertTrue(+ InstanceEntitlementGate.decide(true, true, true, Optional.of(e), false, 9, 0)+ .allowed());+ assertFalse(+ InstanceEntitlementGate.decide(true, true, true, Optional.of(e), false, 10, 0)+ .allowed());+ }+private static FreeTierUsageService.FreeTierBalance grant(long remaining) {LocalDateTime start = LocalDateTime.of(2026, 9, 1, 0, 0);return new FreeTierUsageService.FreeTierBalance(diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.javaindex 2d56bbd8d2..03b1d0bec5 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/InstanceEntitlementInterceptorTest.java@@ -408,7 +408,8 @@ class InstanceEntitlementInterceptorTest {period,period.plusMonths(1),null,- 20)));+ 20,+ 0L)));InstanceEntitlementInterceptor interceptor = interceptor();for (int step = 0; step < 3; step++) {diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.javaindex 4825fb96ee..126fc1bd70 100644--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/PolicyAutomationBillingDbTest.java@@ -199,7 +199,8 @@ class PolicyAutomationBillingDbTest {PERIOD,PERIOD.plusMonths(1),null,- stepLimit)));+ stepLimit,+ 0L)));List<Resource> inputs =IntStream.range(0, inputCount).mapToObj(diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.javaindex 2f9e6a851f..32915a4821 100644--- a/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/InstanceController.java@@ -24,6 +24,7 @@ import stirling.software.proprietary.billing.UnitCalcPolicy;import stirling.software.saas.model.SaasTeamExtensions;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.instance.InstanceUsageIngestService;@@ -55,6 +56,7 @@ import stirling.software.saas.repository.SaasTeamExtensionsRepository;@ConditionalOnProperty(name = "stirling.billing.account-link.enabled", havingValue = "true")public class InstanceController {+ private final PrepaidBundleService prepaidBundleService;private final EntitlementService entitlementService;private final TeamBillingService billingService;private final AccountLinkService accountLinkService;@@ -70,7 +72,9 @@ public class InstanceController {PricingPolicyService pricingPolicyService,InstanceUsageIngestService usageIngestService,LinkedInstanceRepository linkedInstanceRepository,- SaasTeamExtensionsRepository teamExtensionsRepository) {+ SaasTeamExtensionsRepository teamExtensionsRepository,+ PrepaidBundleService prepaidBundleService) {+ this.prepaidBundleService = prepaidBundleService;this.entitlementService = entitlementService;this.billingService = billingService;this.accountLinkService = accountLinkService;@@ -104,7 +108,8 @@ public class InstanceController {UnitCalcPolicy unitCalcPolicy,LocalDateTime periodStart,LocalDateTime periodEnd,- int automationStepLimit) {}+ int automationStepLimit,+ long prepaidRemainingUnits) {}@GetMapping("/whoami")@PreAuthorize("hasRole('LINKED_INSTANCE')")@@ -230,7 +235,8 @@ public class InstanceController {policy.getFileUnitCap()),snap.periodStart(),snap.periodEnd(),- policy.resolveStepLimit(JobSource.PIPELINE));+ policy.resolveStepLimit(JobSource.PIPELINE),+ prepaidBundleService.prepaidRemainingUnits(teamId));}/**diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.java b/app/saas/src/main/java/stirling/software/saas/payg/api/PaygWalletController.javaindex 203213dadd..2acad55f41 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@@ -252,7 +252,13 @@ public class PaygWalletController {prepaidTotal,prepaidExpiresAt,billingMode,- bundleRatePerCreditMinor);+ bundleRatePerCreditMinor,+ billing.includedPeriodStart() == null+ ? null+ : billing.includedPeriodStart().toLocalDate().toString(),+ billing.includedPeriodEnd() == null+ ? null+ : billing.includedPeriodEnd().toLocalDate().toString());return ResponseEntity.ok(body);}@@ -530,6 +536,8 @@ public class PaygWalletController {0L,null,BILLING_MODE_PAYG,+ null,+ null,null);}}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.java b/app/saas/src/main/java/stirling/software/saas/payg/api/WalletSnapshotResponse.javaindex 4c67f32255..5a5aec97c8 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@@ -100,7 +100,9 @@ public record WalletSnapshotResponse(long prepaidUnitsTotal,String prepaidExpiresAt,String billingMode,- BigDecimal bundleRatePerCreditMinor) {+ BigDecimal bundleRatePerCreditMinor,+ String includedPeriodStart,+ String includedPeriodEnd) {// Prepaid usage bundles, aggregated across the team's in-term pools (drawn ahead of the meter,// outside the spend cap):diff --git a/app/saas/src/main/java/stirling/software/saas/payg/billing/IncludedAllowance.java b/app/saas/src/main/java/stirling/software/saas/payg/billing/IncludedAllowance.javanew file mode 100644index 0000000000..6d73d115d2--- /dev/null+++ b/app/saas/src/main/java/stirling/software/saas/payg/billing/IncludedAllowance.java@@ -0,0 +1,43 @@+package stirling.software.saas.payg.billing;++import java.time.LocalDateTime;+import java.time.YearMonth;++import stirling.software.saas.payg.policy.PaygTeamExtensions;++/**+ * Monthly included credits, independent of the metered subscription's billing window. Renewal and+ * upgrade semantics must match the SaaS database's {@code refresh_team_included_credits} function.+ */+public record IncludedAllowance(+ LocalDateTime start, LocalDateTime end, long granted, long remaining) {++ /** Preserves issued credits on downgrade and applies only the difference on upgrade. */+ public static IncludedAllowance resolve(+ PaygTeamExtensions ext, long target, LocalDateTime now) {+ target = Math.max(0, target);+ LocalDateTime start = ext.getFreeUnitsPeriodStart();+ LocalDateTime end = ext.getFreeUnitsPeriodEnd();+ if (end == null && start != null) {+ end = start.plusMonths(1);+ }+ if (start == null || end == null || !now.isBefore(end)) {+ start = YearMonth.from(now).atDay(1).atStartOfDay();+ return new IncludedAllowance(start, start.plusMonths(1), target, target);+ }+ long issued = ext.getFreeUnitsGranted() == null ? target : ext.getFreeUnitsGranted();+ long granted = Math.max(issued, target);+ long remaining =+ Math.max(0, ext.getFreeUnitsRemaining() == null ? 0 : ext.getFreeUnitsRemaining());+ return new IncludedAllowance(+ start, end, granted, Math.min(granted, remaining + granted - issued));+ }++ /** Caller must hold the team's row lock and persist the entity in the same transaction. */+ public void store(PaygTeamExtensions ext, long balance) {+ ext.setFreeUnitsPeriodStart(start);+ ext.setFreeUnitsPeriodEnd(end);+ ext.setFreeUnitsGranted(granted);+ ext.setFreeUnitsRemaining(balance);+ }+}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/billing/TeamBillingContext.java b/app/saas/src/main/java/stirling/software/saas/payg/billing/TeamBillingContext.javaindex e880e6450c..0cd839ba38 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/billing/TeamBillingContext.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/billing/TeamBillingContext.java@@ -5,19 +5,19 @@ import java.time.LocalDateTime;/*** One team's billing facts, composed by {@link TeamBillingService}. The free grant and the spending- * cap are separate pools measured over one window.+ * cap have independent renewal windows.** @param subscribed team has a live PAYG subscription — i.e. {@code payg_subscription_id} is set.* Cleared by {@code payg_unlink_subscription} on cancellation, so a cancelled team reads false.* @param subscriptionId {@code payg_team_extensions.payg_subscription_id}; null when free* @param periodStart inclusive start of the billing window — the Stripe subscription's current- * period when subscribed, calendar month otherwise. Also the period the free grant resets on.+ * period when subscribed, calendar month otherwise.* @param periodEnd exclusive end of the billing window- * @param freeGrantUnits the team's free grant size per period (policy {@code free_tier_units}); the- * denominator for "used X of N free"+ * @param freeGrantUnits included credits issued for this term; upgrades increase it and downgrades+ * take effect at renewal* @param freeRemainingUnits free documents still available in this period ({@code- * payg_team_extensions.free_units_remaining}, via {@code- * TeamBillingService.remainingForPeriod}). 0 = exhausted.+ * payg_team_extensions.free_units_remaining}, via {@code IncludedAllowance.resolve}). 0 =+ * exhausted.* @param perDocMinor paid per-document rate in minor units of {@link #currency()}; null when the* rate can't be resolved (free team, price row unsynced) — display "unknown", never substitute* @param currency lower-case ISO 4217 of the subscription's Price; null when unknown@@ -36,4 +36,6 @@ public record TeamBillingContext(BigDecimal perDocMinor,String currency,Long capMoneyMinor,- Long monthlyCapDocUnits) {}+ Long monthlyCapDocUnits,+ LocalDateTime includedPeriodStart,+ LocalDateTime includedPeriodEnd) {}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/billing/TeamBillingService.java b/app/saas/src/main/java/stirling/software/saas/payg/billing/TeamBillingService.javaindex 97643786e4..ce533b68c2 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/billing/TeamBillingService.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/billing/TeamBillingService.java@@ -4,6 +4,7 @@ import java.math.BigDecimal;import java.math.RoundingMode;import java.time.Duration;import java.time.LocalDateTime;+import java.time.ZoneOffset;import java.util.Objects;import java.util.Optional;@@ -30,8 +31,7 @@ import stirling.software.saas.payg.wallet.WalletPolicy;* entitlement hot path and the wallet endpoint read from here, so what the customer sees is what* the guard enforces.*- * <p>The free grant and the spending cap are separate pools measured over one window: the Stripe- * subscription period when subscribed, the calendar month otherwise.+ * <p>Included credits renew monthly in UTC, independently of the Stripe metered billing window.** <p>Cached per team for {@value #CACHE_TTL_SECONDS}s. {@code EntitlementService.invalidate}* cascades into {@link #invalidate(Long)} so both caches drop together on cap edits / webhooks.@@ -133,18 +133,12 @@ public class TeamBillingService {billing.map(b -> new LocalDateTime[] {b.periodStart(), b.periodEnd()}).orElseGet(TeamBillingService::calendarMonthWindow);- long freeGrant = resolveGrant(teamId);- // The reset is persisted lazily by the charge pipeline, so the raw counter still reads as- // last period's for a team that has run nothing since the boundary.- long freeRemaining =+ long freeGrant = resolveGrant(teamId, extOpt.orElse(null));+ Optional<IncludedAllowance> allowance =extOpt.map(- ext ->- remainingForPeriod(- ext.getFreeUnitsPeriodStart(),- ext.getFreeUnitsRemaining(),- freeGrant,- window[0]))- .orElse(0L);+ ext ->+ IncludedAllowance.resolve(+ ext, freeGrant, LocalDateTime.now(ZoneOffset.UTC)));BigDecimal perDocMinor = billing.map(SubscriptionBilling::perDocMinor).orElse(null);String currency = billing.map(SubscriptionBilling::currency).orElse(null);@@ -174,18 +168,33 @@ public class TeamBillingService {subscriptionId,window[0],window[1],- freeGrant,- freeRemaining,+ allowance.map(IncludedAllowance::granted).orElse(0L),+ allowance.map(IncludedAllowance::remaining).orElse(0L),perDocMinor,currency,capMoneyMinor,- monthlyCapDocUnits);+ monthlyCapDocUnits,+ allowance.map(IncludedAllowance::start).orElse(null),+ allowance.map(IncludedAllowance::end).orElse(null));}- private long resolveGrant(Long teamId) {+ /** Resolves the target for the locked row, so webhook changes bypass the balance cache. */+ public long resolveGrant(Long teamId, PaygTeamExtensions ext) {try {PricingPolicy policy = pricingPolicyService.getEffectivePolicy(teamId);Long grant = policy.getFreeTierUnits();+ if (ext != null && Boolean.TRUE.equals(ext.getTeamCreditsEligible())) {+ grant = policy.getTeamIncludedUnits();+ if (grant == null) {+ grant = pricingPolicyService.getEffectivePolicy(null).getTeamIncludedUnits();+ }+ if (grant == null) {+ log.warn(+ "Team included-credit allowance missing for team {}; using its free-tier allowance",+ teamId);+ grant = policy.getFreeTierUnits();+ }+ }return grant == null ? 0L : grant;} catch (RuntimeException e) {log.warn("No effective pricing policy for team {}: {}", teamId, e.getMessage());@@ -276,34 +285,12 @@ public class TeamBillingService {.orElse(null);}- /**- * The team's free balance for the period starting at {@code currentPeriodStart}: a full grant- * when the counter is stale, the counter otherwise. Shared with the decrement in {@code- * JobChargeService} so displayed and enforced balances cannot diverge.- */- public static long remainingForPeriod(- LocalDateTime stampedPeriodStart,- Long storedRemaining,- long grant,- LocalDateTime currentPeriodStart) {- if (isStale(stampedPeriodStart, currentPeriodStart)) {- return Math.max(0L, grant);- }- return storedRemaining == null ? 0L : Math.max(0L, storedRemaining);- }-- public static boolean isStale(- LocalDateTime stampedPeriodStart, LocalDateTime currentPeriodStart) {- return currentPeriodStart != null- && (stampedPeriodStart == null || stampedPeriodStart.isBefore(currentPeriodStart));- }-/*** Inclusive-start / exclusive-end window for the calendar month — the monthly billing window* used when there's no Stripe subscription period to anchor on.*/static LocalDateTime[] calendarMonthWindow() {- return calendarMonthWindow(LocalDateTime.now());+ return calendarMonthWindow(LocalDateTime.now(ZoneOffset.UTC));}/** Test seam — accepts a clock value so tests don't race the calendar boundary. */diff --git a/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.java b/app/saas/src/main/java/stirling/software/saas/payg/charge/JobChargeService.javaindex 3438e60ca6..85cb4cfa44 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@@ -3,6 +3,7 @@ package stirling.software.saas.payg.charge;import java.io.IOException;import java.nio.file.Path;import java.time.LocalDateTime;+import java.time.ZoneOffset;import java.util.List;import java.util.Objects;import java.util.Optional;@@ -17,7 +18,7 @@ import org.springframework.web.multipart.MultipartFile;import lombok.extern.slf4j.Slf4j;-import stirling.software.saas.payg.billing.TeamBillingContext;+import stirling.software.saas.payg.billing.IncludedAllowance;import stirling.software.saas.payg.billing.TeamBillingService;import stirling.software.saas.payg.bundle.PrepaidBundleService;import stirling.software.saas.payg.docs.DocumentClassifier;@@ -135,11 +136,19 @@ public class JobChargeService {int units = computeUnits(inputs, policy);job.setDocUnits(units);- int freeUsed = consumeFreeGrant(ctx, units);+ FreeGrantDraw freeDraw = consumeFreeGrant(ctx, units);+ int freeUsed = freeDraw.units();// Prepaid bundle is the tier between the free grant and the meter (free → prepaid →// metered); draw only what the free grant didn't cover.int bundleUsed = drawBundle(ctx, units - freeUsed);- recordShadowRow(ctx, job.getId(), policy.getId(), units, freeUsed, bundleUsed);+ recordShadowRow(+ ctx,+ job.getId(),+ policy.getId(),+ units,+ freeUsed,+ bundleUsed,+ freeDraw.periodStart());// doc_count + fingerprint were set on the fresh job by JobService.openFresh; carry them// onto the ledger DEBIT so usage analytics query one table. Bundle-drawn units are netted// out of the ledger amount so they never count against the spend cap (they're prepaid, not@@ -192,9 +201,17 @@ public class JobChargeService {ctx.runId());ProcessingJob job = jobService.open(jobCtx, chargeUnits);- int freeUsed = consumeFreeGrant(ctx, chargeUnits);+ FreeGrantDraw freeDraw = consumeFreeGrant(ctx, chargeUnits);+ int freeUsed = freeDraw.units();int bundleUsed = drawBundle(ctx, chargeUnits - freeUsed);- recordShadowRow(ctx, job.getId(), policy.getId(), chargeUnits, freeUsed, bundleUsed);+ recordShadowRow(+ ctx,+ job.getId(),+ policy.getId(),+ chargeUnits,+ freeUsed,+ bundleUsed,+ freeDraw.periodStart());recordLedgerDebit(ctx,job.getId(),@@ -210,68 +227,54 @@ public class JobChargeService {return job.getId();}- /**- * Units of {@code units} drawn from the team's grant for the current period; the remainder is- * metered to Stripe. The grant is a soft floor, so the job crossing the boundary takes what is- * left and bills the rest.- *- * <p>Also the only writer of the period reset. Both happen under {@code openProcess}'s row- * lock, against the balance on the locked row rather than the cached context, so concurrent- * same-team charges cannot both claim the last free unit.- */- private int consumeFreeGrant(ChargeContext ctx, int units) {+ private record FreeGrantDraw(int units, LocalDateTime periodStart) {}++ private FreeGrantDraw consumeFreeGrant(ChargeContext ctx, int units) {BillingCategory category = ctx.billingCategory();if (category == null || category == BillingCategory.BYPASSED || ctx.ownerTeamId() == null) {- return 0;+ return new FreeGrantDraw(0, null);}Optional<PaygTeamExtensions> extOpt =teamExtensionsRepository.findByIdForUpdate(ctx.ownerTeamId());if (extOpt.isEmpty()) {- return 0;+ return new FreeGrantDraw(0, null);}PaygTeamExtensions ext = extOpt.get();- TeamBillingContext billing = teamBillingService.forTeam(ctx.ownerTeamId());- LocalDateTime periodStart = billing.periodStart();- boolean periodRolled =- TeamBillingService.isStale(ext.getFreeUnitsPeriodStart(), periodStart);- long remaining =- TeamBillingService.remainingForPeriod(- ext.getFreeUnitsPeriodStart(),- ext.getFreeUnitsRemaining(),- billing.freeGrantUnits(),- periodStart);- int freeUsed = (int) Math.min(units, Math.max(0L, remaining));- if (periodRolled || freeUsed > 0) {- // A roll-over writes even when nothing is drawn, so the stamp stops reading as stale.- ext.setFreeUnitsRemaining(remaining - freeUsed);- ext.setFreeUnitsPeriodStart(periodStart);- teamExtensionsRepository.save(ext);- }- return freeUsed;+ IncludedAllowance allowance =+ IncludedAllowance.resolve(+ ext,+ teamBillingService.resolveGrant(ctx.ownerTeamId(), ext),+ LocalDateTime.now(ZoneOffset.UTC));+ int freeUsed = (int) Math.min(units, allowance.remaining());+ allowance.store(ext, allowance.remaining() - freeUsed);+ teamExtensionsRepository.save(ext);+ return new FreeGrantDraw(freeUsed, allowance.start());}- /**- * Return {@code units} to the team's free grant, capped at one period's grant. The cap only- * bites when a refund lands after its charge's period ended, where the balance has already- * reset and adding the old units would over-credit the team. Locks rather than incrementing- * blindly because the cap applies against the balance as it stands.- */- private void restoreFreeGrant(Long teamId, int units) {+ /** Restores a failed charge only within the included-credit term that funded it. */+ private void restoreFreeGrant(+ Long teamId, int units, LocalDateTime chargedAt, LocalDateTime chargedPeriod) {Optional<PaygTeamExtensions> extOpt = teamExtensionsRepository.findByIdForUpdate(teamId);if (extOpt.isEmpty()) {return;}PaygTeamExtensions ext = extOpt.get();- TeamBillingContext billing = teamBillingService.forTeam(teamId);- long grant = billing.freeGrantUnits();- long remaining =- TeamBillingService.remainingForPeriod(- ext.getFreeUnitsPeriodStart(),- ext.getFreeUnitsRemaining(),- grant,- billing.periodStart());- ext.setFreeUnitsRemaining(Math.min(grant, remaining + Math.max(0, units)));- ext.setFreeUnitsPeriodStart(billing.periodStart());+ IncludedAllowance allowance =+ IncludedAllowance.resolve(+ ext,+ teamBillingService.resolveGrant(teamId, ext),+ LocalDateTime.now(ZoneOffset.UTC));+ boolean sameTerm =+ chargedPeriod != null+ ? chargedPeriod.equals(allowance.start())+ : chargedAt != null+ && !chargedAt.isBefore(allowance.start())+ && chargedAt.isBefore(allowance.end());+ if (!sameTerm) {+ return;+ }+ allowance.store(+ ext, Math.min(allowance.granted(), allowance.remaining() + Math.max(0, units)));teamExtensionsRepository.save(ext);}@@ -376,7 +379,8 @@ public class JobChargeService {Long policyId,int units,int freeUnitsConsumed,- int bundleUnitsConsumed) {+ int bundleUnitsConsumed,+ LocalDateTime includedPeriodStart) {PaygShadowCharge row = new PaygShadowCharge();row.setTeamId(ctx.ownerTeamId());row.setJobId(jobId);@@ -385,6 +389,7 @@ public class JobChargeService {// 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.setIncludedPeriodStart(includedPeriodStart);row.setBundleUnitsConsumed(bundleUnitsConsumed);// No legacy comparison: the legacy credit engine has been removed, so diff stays at 0.row.setLegacyCreditsCharged(0);@@ -447,7 +452,11 @@ public class JobChargeService {int freeConsumed =row.getFreeUnitsConsumed() == null ? 0 : row.getFreeUnitsConsumed();if (freeConsumed > 0 && row.getTeamId() != null) {- restoreFreeGrant(row.getTeamId(), freeConsumed);+ restoreFreeGrant(+ row.getTeamId(),+ freeConsumed,+ row.getOccurredAt(),+ row.getIncludedPeriodStart());}// Return the prepaid units this job drew to the team's pools (best-effort — see// PrepaidBundleService.restore).diff --git a/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementService.java b/app/saas/src/main/java/stirling/software/saas/payg/entitlement/EntitlementService.javaindex 2ff2d8f613..49eca53f37 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@@ -23,14 +23,15 @@ import stirling.software.saas.payg.cap.CapEvaluator;import stirling.software.saas.payg.cap.CapEvaluator.Evaluation;import stirling.software.saas.payg.model.EntitlementState;import stirling.software.saas.payg.model.FeatureSet;-import stirling.software.saas.payg.repository.WalletLedgerRepository;+import stirling.software.saas.payg.repository.PaygShadowChargeRepository;import stirling.software.saas.payg.repository.WalletPolicyRepository;import stirling.software.saas.payg.wallet.WalletPolicy;/*** Hot-path entitlement lookup. Returns the {@link EntitlementSnapshot} for a team: the billing* facts (window, free allowance, document cap) come from {@link TeamBillingService}; this service- * layers the period spend (ledger SUM over that window) and the warn/degrade evaluation on top.+ * layers metered spend (excluding included and prepaid units) and the warn/degrade evaluation on+ * top.** <p>Backed by a per-team Caffeine cache with {@value #CACHE_TTL_SECONDS}s TTL and {@value* #CACHE_MAX_SIZE}-entry cap. The TTL is the correctness floor — a cap change becomes visible on@@ -51,7 +52,7 @@ public class EntitlementService {private final TeamBillingService teamBillingService;private final WalletPolicyRepository walletPolicyRepository;- private final WalletLedgerRepository ledgerRepository;+ private final PaygShadowChargeRepository shadowRepository;private final PrepaidBundleService prepaidBundleService;private final Cache<Long, EntitlementSnapshot> snapshotCache;@@ -59,12 +60,12 @@ public class EntitlementService {public EntitlementService(TeamBillingService teamBillingService,WalletPolicyRepository walletPolicyRepository,- WalletLedgerRepository ledgerRepository,+ PaygShadowChargeRepository shadowRepository,PrepaidBundleService prepaidBundleService) {this.teamBillingService = Objects.requireNonNull(teamBillingService, "teamBillingService");this.walletPolicyRepository =Objects.requireNonNull(walletPolicyRepository, "walletPolicyRepository");- this.ledgerRepository = Objects.requireNonNull(ledgerRepository, "ledgerRepository");+ this.shadowRepository = Objects.requireNonNull(shadowRepository, "shadowRepository");this.prepaidBundleService =Objects.requireNonNull(prepaidBundleService, "prepaidBundleService");this.snapshotCache =@@ -77,7 +78,7 @@ public class EntitlementService {/*** Returns the entitlement snapshot for {@code teamId}. Caches per-team for {@value- * #CACHE_TTL_SECONDS}s — burst requests share a single SUM query against the ledger.+ * #CACHE_TTL_SECONDS}s — burst requests share a single query over charged usage.** <p>{@code null} teamId throws — the guard short-circuits team-less requests upstream so a* null reach here is a programming error.@@ -133,25 +134,13 @@ public class EntitlementService {Long snapshotCap;if (billing.subscribed()) {- // Subscribed: gate on the monthly spending cap. Spend = this period's net billable- // documents (DEBIT minus REFUND so a refunded job doesn't read as spent). The free- // grant doesn't gate a paying team — it only reduced what they were metered.- long signedNet = ledgerRepository.sumPeriodNetBillable(teamId, periodStart, periodEnd);- long periodSpend = signedNet < 0 ? -signedNet : 0L;+ long periodSpend =+ Math.max(0, shadowRepository.sumPaidUnits(teamId, periodStart, periodEnd));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) {+ && (billing.freeRemainingUnits() > 0L+ || prepaidBundleService.prepaidRemainingUnits(teamId) > 0L)) {eval = fullyEntitledOnPrepaid();}snapshotSpend = periodSpend;diff --git a/app/saas/src/main/java/stirling/software/saas/payg/policy/PaygTeamExtensions.java b/app/saas/src/main/java/stirling/software/saas/payg/policy/PaygTeamExtensions.javaindex 11fb2fc2e7..60ed5b1a26 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/policy/PaygTeamExtensions.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/policy/PaygTeamExtensions.java@@ -79,15 +79,20 @@ public class PaygTeamExtensions implements Serializable {@Column(name = "free_units_remaining", nullable = false)private Long freeUnitsRemaining = 0L;- /**- * The billing period {@link #freeUnitsRemaining} was last reset for, always a {@code- * TeamBillingContext.periodStart}. {@code null} or older than the current period start means- * the counter is stale and reads as a full grant. Written only by the app, which owns the- * period rule.- */+ /** Inclusive UTC start of the included-credit term, independent of Processor billing. */@Column(name = "free_units_period_start")private LocalDateTime freeUnitsPeriodStart;+ @Column(name = "free_units_period_end")+ private LocalDateTime freeUnitsPeriodEnd;++ @Column(name = "free_units_granted")+ private Long freeUnitsGranted;++ /** Projected by the Team subscription webhook; seat quantity does not multiply credits. */+ @Column(name = "team_credits_eligible", insertable = false, updatable = false)+ private Boolean teamCreditsEligible = false;+@CreationTimestamp@Column(name = "created_at", updatable = false)private LocalDateTime createdAt;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.javaindex da67729962..5e668e89d8 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@@ -82,6 +82,10 @@ public class PricingPolicy implements Serializable {@Column(name = "free_tier_units", nullable = false)private Long freeTierUnits = 0L;+ /** Null inherits the default policy's Team allowance. */+ @Column(name = "team_included_units")+ private Long teamIncludedUnits;+/*** Max tool steps allowed in one process before it splits, keyed by the caller's {@link* JobSource}. Self-hosted teams typically get a higher limit via a per-team policy override.diff --git a/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicyService.java b/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicyService.javaindex 0fd7bb45d1..8e7991eaeb 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicyService.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/policy/PricingPolicyService.java@@ -159,6 +159,13 @@ public class PricingPolicyService {if (Boolean.TRUE.equals(target.getIsDefault())) {return target;}+ if (target.getTeamIncludedUnits() == null) {+ target.setTeamIncludedUnits(+ policyRepository+ .findFirstByIsDefaultTrue()+ .map(PricingPolicy::getTeamIncludedUnits)+ .orElse(0L));+ }policyRepository.clearDefaultFlag();target.setIsDefault(true);PricingPolicy saved = policyRepository.save(target);diff --git a/app/saas/src/main/java/stirling/software/saas/payg/policy/admin/PolicyDtos.java b/app/saas/src/main/java/stirling/software/saas/payg/policy/admin/PolicyDtos.javaindex 0069b84dc6..fefbb99e3b 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/policy/admin/PolicyDtos.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/policy/admin/PolicyDtos.java@@ -33,7 +33,8 @@ final class PolicyDtos {Boolean isDefault,String notes,String createdBy,- LocalDateTime createdAt) {+ LocalDateTime createdAt,+ Long teamIncludedUnits) {static PolicyResponse from(PricingPolicy p) {return new PolicyResponse(@@ -53,7 +54,8 @@ final class PolicyDtos {p.getIsDefault(),p.getNotes(),p.getCreatedBy(),- p.getCreatedAt());+ p.getCreatedAt(),+ p.getTeamIncludedUnits());}}@@ -72,7 +74,35 @@ final class PolicyDtos {Map<JobSource, Integer> stepLimits,Set<String> stripePriceIds,String notes,- String createdBy) {}+ String createdBy,+ Long teamIncludedUnits) {+ CreatePolicyRequest(+ String version,+ LocalDateTime effectiveFrom,+ LocalDateTime effectiveTo,+ Integer docPagesPerUnit,+ Long docBytesPerUnit,+ Integer minChargeUnits,+ Integer fileUnitCap,+ Map<JobSource, Integer> stepLimits,+ Set<String> stripePriceIds,+ String notes,+ String createdBy) {+ this(+ version,+ effectiveFrom,+ effectiveTo,+ docPagesPerUnit,+ docBytesPerUnit,+ minChargeUnits,+ fileUnitCap,+ stepLimits,+ stripePriceIds,+ notes,+ createdBy,+ null);+ }+ }/*** Inbound payload for {@code PUT /teams/{teamId}/policy-override}. {@code policyId = null}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/policy/admin/PricingPolicyAdminController.java b/app/saas/src/main/java/stirling/software/saas/payg/policy/admin/PricingPolicyAdminController.javaindex 0ed2bb417f..fea6562ccf 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/policy/admin/PricingPolicyAdminController.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/policy/admin/PricingPolicyAdminController.java@@ -161,6 +161,10 @@ public class PricingPolicyAdminController {p.setIsDefault(false);p.setNotes(req.notes());p.setCreatedBy(req.createdBy());+ if (req.teamIncludedUnits() != null && req.teamIncludedUnits() < 0) {+ throw new IllegalArgumentException("teamIncludedUnits must not be negative.");+ }+ p.setTeamIncludedUnits(req.teamIncludedUnits());return p;}diff --git a/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygShadowChargeRepository.java b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygShadowChargeRepository.javaindex 341dd6a54c..436440f21e 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygShadowChargeRepository.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/repository/PaygShadowChargeRepository.java@@ -30,12 +30,12 @@ public interface PaygShadowChargeRepository extends JpaRepository<PaygShadowChar/*** Paid (Stripe-metered) documents for a team in a period: {@code SUM(payg_units −- * free_units_consumed)} over CHARGED rows. This is exactly what was reported to Stripe in the- * window, so the wallet's "estimated bill so far" is the metered total × rate. REFUNDED rows- * are excluded.+ * free_units_consumed − bundle_units_consumed)} over CHARGED rows. This is exactly what was+ * reported to Stripe in the window, so the wallet's "estimated bill so far" is the metered+ * total × rate. REFUNDED rows are excluded.*/@Query(- "SELECT COALESCE(SUM(s.paygUnits - s.freeUnitsConsumed), 0) FROM PaygShadowCharge s"+ "SELECT COALESCE(SUM(s.paygUnits - s.freeUnitsConsumed - s.bundleUnitsConsumed), 0) FROM PaygShadowCharge s"+ " WHERE s.teamId = :teamId"+ " AND s.status = stirling.software.saas.payg.model.ShadowChargeStatus.CHARGED"+ " AND s.occurredAt >= :from AND s.occurredAt < :to")diff --git a/app/saas/src/main/java/stirling/software/saas/payg/repository/WalletLedgerRepository.java b/app/saas/src/main/java/stirling/software/saas/payg/repository/WalletLedgerRepository.javaindex c5f320fcb1..f94c97b7f5 100644--- a/app/saas/src/main/java/stirling/software/saas/payg/repository/WalletLedgerRepository.java+++ b/app/saas/src/main/java/stirling/software/saas/payg/repository/WalletLedgerRepository.java@@ -83,24 +83,6 @@ public interface WalletLedgerRepository extends JpaRepository<WalletLedgerEntry,@Param("periodStart") LocalDateTime periodStart,@Param("periodEnd") LocalDateTime periodEnd);- /**- * Net signed period balance over billable entries (DEBIT negative + REFUND positive). Negate- * for positive spend. Unlike {@link #sumPeriodAmount} (DEBIT only) this nets refunds, so a- * refunded job no longer reads as spent — the headline period-spend figure for the subscribed- * monthly bill + cap.- */- @Query(- "SELECT COALESCE(SUM(e.amountUnits), 0) FROM WalletLedgerEntry e"- + " WHERE e.teamId = :teamId"- + " AND e.entryType IN (stirling.software.saas.payg.model.LedgerEntryType.DEBIT,"- + " stirling.software.saas.payg.model.LedgerEntryType.REFUND)"- + " AND e.occurredAt >= :periodStart"- + " AND e.occurredAt < :periodEnd")- long sumPeriodNetBillable(- @Param("teamId") Long teamId,- @Param("periodStart") LocalDateTime periodStart,- @Param("periodEnd") LocalDateTime periodEnd);-/** Per-member period spend (only when the member has a sub-cap configured). */@Query("SELECT COALESCE(SUM(e.amountUnits), 0) FROM WalletLedgerEntry e"diff --git a/app/saas/src/main/java/stirling/software/saas/payg/shadow/PaygShadowCharge.java b/app/saas/src/main/java/stirling/software/saas/payg/shadow/PaygShadowCharge.javaindex ee95c09908..1881666827 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,10 @@ public class PaygShadowCharge implements Serializable {@Column(name = "free_units_consumed", nullable = false)private Integer freeUnitsConsumed = 0;+ /** The term that funded this charge, so a late refund cannot replenish another month. */+ @Column(name = "included_period_start")+ private LocalDateTime includedPeriodStart;+/*** 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)diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceControllerTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceControllerTest.javaindex dbb58ab31b..65220c9aee 100644--- a/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceControllerTest.java+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/InstanceControllerTest.java@@ -19,6 +19,7 @@ import org.junit.jupiter.params.provider.NullSource;import org.junit.jupiter.params.provider.ValueSource;import org.mockito.ArgumentCaptor;import org.mockito.Mock;+import org.mockito.Mockito;import org.mockito.junit.jupiter.MockitoExtension;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;@@ -32,6 +33,7 @@ import stirling.software.saas.accountlink.InstanceController.EntitlementResponseimport stirling.software.saas.model.SaasTeamExtensions;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.instance.InstanceUsageIngestService;@@ -68,7 +70,8 @@ class InstanceControllerTest {pricingPolicyService,usageIngestService,linkedInstanceRepository,- teamExtensionsRepository);+ teamExtensionsRepository,+ Mockito.mock(PrepaidBundleService.class));}private static PricingPolicy policy() {@@ -291,7 +294,9 @@ class InstanceControllerTest {null,null,null,- null);+ null,+ start,+ start.plusMonths(1));}private static TeamBillingContext subscribedBilling(String subId, long freeRemaining) {@@ -306,7 +311,9 @@ class InstanceControllerTest {BigDecimal.valueOf(2),"usd",2500L,- 1250L);+ 1250L,+ start,+ start.plusMonths(1));}private static EntitlementSnapshot snapshot(EntitlementState state, long spend, Long cap) {diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/PaygWalletControllerTest.javaindex 4905cc18eb..ddc80d39ca 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@@ -112,7 +112,9 @@ class PaygWalletControllerTest {null,null,null,- null);+ null,+ start,+ start.plusMonths(1));}/**@@ -133,7 +135,9 @@ class PaygWalletControllerTest {BigDecimal.valueOf(2),"usd",capMoneyMinor,- monthlyCapDocUnits);+ monthlyCapDocUnits,+ start,+ start.plusMonths(1));}private void stubEmptyLedgerReads(long teamId) {diff --git a/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.java b/app/saas/src/test/java/stirling/software/saas/payg/api/WalletSnapshotResponseTest.javaindex 5309eeebff..14fc62803a 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@@ -47,7 +47,9 @@ class WalletSnapshotResponseTest {/* prepaidUnitsTotal= */ 120_000L,/* prepaidExpiresAt= */ "2027-06-01",/* billingMode= */ "prepaid",- /* bundleRatePerCreditMinor= */ new BigDecimal("1"));+ /* bundleRatePerCreditMinor= */ new BigDecimal("1"),+ null,+ null);}@Test@@ -132,6 +134,8 @@ class WalletSnapshotResponseTest {0L,null,"payg",+ null,+ null,null);assertThat(free.billableLimit()).isNull();diff --git a/app/saas/src/test/java/stirling/software/saas/payg/billing/IncludedAllowanceTest.java b/app/saas/src/test/java/stirling/software/saas/payg/billing/IncludedAllowanceTest.javanew file mode 100644index 0000000000..74ef17d336--- /dev/null+++ b/app/saas/src/test/java/stirling/software/saas/payg/billing/IncludedAllowanceTest.java@@ -0,0 +1,64 @@+package stirling.software.saas.payg.billing;++import static org.assertj.core.api.Assertions.assertThat;++import java.time.LocalDateTime;++import org.junit.jupiter.api.Test;++import stirling.software.saas.payg.policy.PaygTeamExtensions;++class IncludedAllowanceTest {+ private final LocalDateTime now = LocalDateTime.of(2026, 9, 16, 12, 0);++ @Test+ void upgradeIsTotalAllowanceAndCannotBeClaimedTwice() {+ PaygTeamExtensions ext = current(1000, 700);+ IncludedAllowance upgraded = IncludedAllowance.resolve(ext, 2500, now);+ assertThat(upgraded.remaining()).isEqualTo(2200);+ upgraded.store(ext, upgraded.remaining() - 10);+ assertThat(IncludedAllowance.resolve(ext, 2500, now).remaining()).isEqualTo(2190);+ assertThat(IncludedAllowance.resolve(ext, 1000, now).remaining()).isEqualTo(2190);+ }++ @Test+ void downgradeTakesEffectAtNextMonthWithNoRollover() {+ PaygTeamExtensions ext = current(2500, 2200);+ IncludedAllowance renewed = IncludedAllowance.resolve(ext, 1000, now.plusMonths(1));+ assertThat(renewed.granted()).isEqualTo(1000);+ assertThat(renewed.remaining()).isEqualTo(1000);+ assertThat(renewed.start()).isEqualTo(LocalDateTime.of(2026, 10, 1, 0, 0));+ }++ @Test+ void annualTeamRenewsMonthlyAndSkipsUnusedMonths() {+ PaygTeamExtensions ext = current(2500, 0);+ IncludedAllowance renewed = IncludedAllowance.resolve(ext, 2500, now.plusMonths(8));+ assertThat(renewed.remaining()).isEqualTo(2500);+ assertThat(renewed.end()).isEqualTo(LocalDateTime.of(2027, 6, 1, 0, 0));+ }++ @Test+ void migratedMidMonthTermIsHonoredUntilItsEnd() {+ PaygTeamExtensions ext = current(1000, 700);+ ext.setFreeUnitsPeriodStart(now.minusDays(5));+ ext.setFreeUnitsPeriodEnd(now.minusDays(5).plusMonths(1));+ assertThat(IncludedAllowance.resolve(ext, 1000, now.plusDays(16)).remaining())+ .isEqualTo(700);+ assertThat(IncludedAllowance.resolve(ext, 1000, now.plusMonths(1)).remaining())+ .isEqualTo(1000);+ IncludedAllowance firstCalendarTerm =+ IncludedAllowance.resolve(ext, 1000, ext.getFreeUnitsPeriodEnd());+ assertThat(firstCalendarTerm.start()).isEqualTo(LocalDateTime.of(2026, 10, 1, 0, 0));+ assertThat(firstCalendarTerm.end()).isEqualTo(LocalDateTime.of(2026, 11, 1, 0, 0));+ }++ private PaygTeamExtensions current(long granted, long remaining) {+ PaygTeamExtensions ext = new PaygTeamExtensions();+ ext.setFreeUnitsGranted(granted);+ ext.setFreeUnitsRemaining(remaining);+ ext.setFreeUnitsPeriodStart(LocalDateTime.of(2026, 9, 1, 0, 0));+ ext.setFreeUnitsPeriodEnd(LocalDateTime.of(2026, 10, 1, 0, 0));+ return ext;+ }+}diff --git a/app/saas/src/test/java/stirling/software/saas/payg/billing/TeamBillingServiceMoreTest.java b/app/saas/src/test/java/stirling/software/saas/payg/billing/TeamBillingServiceMoreTest.javaindex 2214c4f38a..51ef2d301e 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/billing/TeamBillingServiceMoreTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/billing/TeamBillingServiceMoreTest.java@@ -11,6 +11,7 @@ import static org.mockito.Mockito.when;import java.math.BigDecimal;import java.time.LocalDateTime;import java.time.YearMonth;+import java.time.ZoneOffset;import java.util.Optional;import org.junit.jupiter.api.BeforeEach;@@ -19,6 +20,7 @@ import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;+import org.mockito.Mockito;import org.mockito.junit.jupiter.MockitoExtension;import stirling.software.saas.payg.policy.PaygTeamExtensions;@@ -69,7 +71,7 @@ class TeamBillingServiceMoreTest {}private void stubGrant(long grant) {- PricingPolicy policy = org.mockito.Mockito.mock(PricingPolicy.class);+ PricingPolicy policy = Mockito.mock(PricingPolicy.class);lenient().when(policy.getFreeTierUnits()).thenReturn(grant);lenient().when(pricingPolicyService.getEffectivePolicy(TEAM_ID)).thenReturn(policy);}@@ -190,8 +192,8 @@ class TeamBillingServiceMoreTest {// Window is the calendar month.LocalDateTime[] expected =new LocalDateTime[] {- YearMonth.now().atDay(1).atStartOfDay(),- YearMonth.now().plusMonths(1).atDay(1).atStartOfDay()+ YearMonth.now(ZoneOffset.UTC).atDay(1).atStartOfDay(),+ YearMonth.now(ZoneOffset.UTC).plusMonths(1).atDay(1).atStartOfDay()};assertThat(ctx.periodStart()).isEqualTo(expected[0]);assertThat(ctx.periodEnd()).isEqualTo(expected[1]);@@ -229,7 +231,7 @@ class TeamBillingServiceMoreTest {}@Test- @DisplayName("missing extension row yields zero free remaining")+ @DisplayName("missing extension row has no included pool")void noExtensionRow_zeroFreeRemaining() {stubGrant(500L);when(extensionsRepository.findById(TEAM_ID)).thenReturn(Optional.empty());@@ -238,7 +240,7 @@ class TeamBillingServiceMoreTest {TeamBillingContext ctx = service.forTeam(TEAM_ID);- assertThat(ctx.freeGrantUnits()).isEqualTo(500L);+ assertThat(ctx.freeGrantUnits()).isZero();assertThat(ctx.freeRemainingUnits()).isZero();assertThat(ctx.subscriptionId()).isNull();}@@ -299,7 +301,9 @@ class TeamBillingServiceMoreTest {rate,"usd",null,- null);+ null,+ LocalDateTime.now(),+ LocalDateTime.now());}@Test@@ -357,8 +361,9 @@ class TeamBillingServiceMoreTest {@DisplayName("no-arg overload anchors on the current month")void noArgOverload() {LocalDateTime[] window = TeamBillingService.calendarMonthWindow();- assertThat(window[0]).isEqualTo(YearMonth.now().atDay(1).atStartOfDay());- assertThat(window[1]).isEqualTo(YearMonth.now().plusMonths(1).atDay(1).atStartOfDay());+ assertThat(window[0]).isEqualTo(YearMonth.now(ZoneOffset.UTC).atDay(1).atStartOfDay());+ assertThat(window[1])+ .isEqualTo(YearMonth.now(ZoneOffset.UTC).plusMonths(1).atDay(1).atStartOfDay());}}@@ -417,14 +422,13 @@ class TeamBillingServiceMoreTest {}@Test- @DisplayName("the grant resets on the Stripe window, not the calendar month")- void subscribedGrantFollowsTheStripeWindow() {+ @DisplayName("advancing the Stripe window does not replenish included credits")+ void subscribedGrantIsIndependentOfStripeWindow() {stubGrant(GRANT);- // Stamped for the calendar month, but this team's period is Stripe-anchored and starts- // mid-month, so the stamp belongs to the previous period and the grant resets.- LocalDateTime stripeStart = LocalDateTime.of(2026, 6, 10, 0, 0);+ LocalDateTime includedStart = TeamBillingService.calendarMonthWindow()[0];+ LocalDateTime stripeStart = includedStart.plusDays(9);when(extensionsRepository.findById(TEAM_ID))- .thenReturn(Optional.of(subscribedRow(LocalDateTime.of(2026, 6, 1, 0, 0))));+ .thenReturn(Optional.of(subscribedRow(includedStart)));when(subscriptionDao.findBilling("sub_1")).thenReturn(Optional.of(@@ -439,7 +443,8 @@ class TeamBillingServiceMoreTest {TeamBillingContext ctx = service.forTeam(TEAM_ID);assertThat(ctx.periodStart()).isEqualTo(stripeStart);- assertThat(ctx.freeRemainingUnits()).isEqualTo(GRANT);+ assertThat(ctx.includedPeriodStart()).isEqualTo(includedStart);+ assertThat(ctx.freeRemainingUnits()).isZero();}private PaygTeamExtensions subscribedRow(LocalDateTime stamp) {@@ -448,45 +453,4 @@ class TeamBillingServiceMoreTest {return e;}}-- @Nested- @DisplayName("remainingForPeriod")- class RemainingForPeriodRule {-- private final LocalDateTime period = LocalDateTime.of(2026, 8, 1, 0, 0);-- @Test- @DisplayName("stale stamp yields the full grant; current stamp yields the stored balance")- void staleVersusCurrent() {- assertThat(- TeamBillingService.remainingForPeriod(- period.minusMonths(1), 0L, 500L, period))- .isEqualTo(500L);- assertThat(TeamBillingService.remainingForPeriod(period, 0L, 500L, period)).isZero();- assertThat(TeamBillingService.remainingForPeriod(period, 42L, 500L, period))- .isEqualTo(42L);- }-- @Test- @DisplayName("a stamp in the future is never read as another grant")- void futureStampKeepsTheStoredBalance() {- assertThat(TeamBillingService.remainingForPeriod(period.plusDays(1), 7L, 500L, period))- .isEqualTo(7L);- }-- @Test- @DisplayName("null stored balance and negative values floor at zero")- void nullAndNegativeBalances() {- assertThat(TeamBillingService.remainingForPeriod(period, null, 500L, period)).isZero();- assertThat(TeamBillingService.remainingForPeriod(period, -5L, 500L, period)).isZero();- assertThat(TeamBillingService.remainingForPeriod(null, 0L, -1L, period)).isZero();- }-- @Test- @DisplayName("an unknown current period leaves the counter alone")- void nullCurrentPeriod() {- assertThat(TeamBillingService.isStale(null, null)).isFalse();- assertThat(TeamBillingService.remainingForPeriod(null, 3L, 500L, null)).isEqualTo(3L);- }- }}diff --git a/app/saas/src/test/java/stirling/software/saas/payg/billing/TeamBillingServiceTest.java b/app/saas/src/test/java/stirling/software/saas/payg/billing/TeamBillingServiceTest.javaindex 5bc3fd2d1e..5897b7c4ef 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/billing/TeamBillingServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/billing/TeamBillingServiceTest.java@@ -3,6 +3,7 @@ package stirling.software.saas.payg.billing;import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.Mockito.when;+import java.time.LocalDateTime;import java.util.Optional;import org.junit.jupiter.api.BeforeEach;@@ -38,6 +39,45 @@ class TeamBillingServiceTest {private StripeSubscriptionDao subscriptionDao;private TeamBillingService service;+ @Test+ void missingTeamAllowanceFallsBackToFreePolicyButExplicitZeroIsRespected() {+ PricingPolicy policy = new PricingPolicy();+ policy.setFreeTierUnits(1000L);+ when(pricingPolicyService.getEffectivePolicy(TEAM_ID)).thenReturn(policy);+ when(pricingPolicyService.getEffectivePolicy(null)).thenReturn(policy);+ PaygTeamExtensions ext = new PaygTeamExtensions();+ ext.setTeamCreditsEligible(true);+ assertThat(service.resolveGrant(TEAM_ID, ext)).isEqualTo(1000L);+ policy.setTeamIncludedUnits(0L);+ assertThat(service.resolveGrant(TEAM_ID, ext)).isZero();+ }++ @Test+ void teamAllowanceComesFromPolicyAndSurvivesProcessorChanges() {+ PaygTeamExtensions ext = new PaygTeamExtensions();+ ext.setTeamId(TEAM_ID);+ ext.setTeamCreditsEligible(true);+ ext.setFreeUnitsGranted(1000L);+ ext.setFreeUnitsRemaining(700L);+ LocalDateTime start = TeamBillingService.calendarMonthWindow()[0];+ ext.setFreeUnitsPeriodStart(start);+ ext.setFreeUnitsPeriodEnd(start.plusMonths(1));+ PricingPolicy policy = new PricingPolicy();+ policy.setFreeTierUnits(1000L);+ policy.setTeamIncludedUnits(2700L);+ when(extensionsRepository.findById(TEAM_ID)).thenReturn(Optional.of(ext));+ when(pricingPolicyService.getEffectivePolicy(TEAM_ID)).thenReturn(policy);+ TeamBillingContext first = service.forTeam(TEAM_ID);+ assertThat(first.freeGrantUnits()).isEqualTo(2700);+ assertThat(first.freeRemainingUnits()).isEqualTo(2400);+ ext.setPaygSubscriptionId("sub_processor");+ service.invalidate(TEAM_ID);+ TeamBillingContext second = service.forTeam(TEAM_ID);+ assertThat(second.freeRemainingUnits()).isEqualTo(2400);+ assertThat(second.includedPeriodStart()).isEqualTo(first.includedPeriodStart());+ assertThat(second.includedPeriodEnd()).isEqualTo(start.plusMonths(1));+ }+@BeforeEachvoid setUp() {extensionsRepository = Mockito.mock(PaygTeamExtensionsRepository.class);@@ -119,5 +159,8 @@ class TeamBillingServiceTest {assertThat(ctx.subscribed()).isFalse();assertThat(ctx.subscriptionId()).isNull();+ assertThat(ctx.freeGrantUnits()).isZero();+ assertThat(ctx.freeRemainingUnits()).isZero();+ assertThat(ctx.includedPeriodEnd()).isNull();}}diff --git a/app/saas/src/test/java/stirling/software/saas/payg/charge/JobChargeServiceTest.java b/app/saas/src/test/java/stirling/software/saas/payg/charge/JobChargeServiceTest.javaindex e637c167ad..97d88842d2 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@@ -14,6 +14,8 @@ import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.time.LocalDateTime;+import java.time.YearMonth;+import java.time.ZoneOffset;import java.util.HashMap;import java.util.List;import java.util.Map;@@ -77,7 +79,8 @@ class JobChargeServiceTest {private TeamBillingService teamBillingService;private JobChargeService service;- private static final LocalDateTime PERIOD_START = LocalDateTime.of(2026, 8, 1, 0, 0);+ private static final LocalDateTime PERIOD_START =+ YearMonth.now(ZoneOffset.UTC).atDay(1).atStartOfDay();private static final long GRANT = 500L;@@ -99,6 +102,7 @@ class JobChargeServiceTest {// close, so the meter tests just set free_units_consumed on the shadow row directly.teamBillingService = Mockito.mock(TeamBillingService.class);when(teamBillingService.forTeam(Mockito.anyLong())).thenReturn(billingContext(GRANT));+ when(teamBillingService.resolveGrant(Mockito.anyLong(), any())).thenReturn(GRANT);service =new JobChargeService(jobService,@@ -124,7 +128,9 @@ class JobChargeServiceTest {null,null,null,- null);+ null,+ PERIOD_START,+ PERIOD_START.plusMonths(1));}@AfterEach@@ -470,6 +476,7 @@ class JobChargeServiceTest {void openProcess_zeroGrantRollover_stampsWithoutDrawing(@TempDir Path tmp) throws IOException {// A zero grant still advances the stamp, or every later charge re-evaluates a stale row.when(teamBillingService.forTeam(100L)).thenReturn(billingContext(0L));+ when(teamBillingService.resolveGrant(Mockito.eq(100L), any())).thenReturn(0L);PricingPolicy policy = stubPolicy(1, Map.of(JobSource.WEB, 10));when(policyService.getEffectivePolicy(100L)).thenReturn(policy);ProcessingJob newJob = openJob(UUID.randomUUID());@@ -528,9 +535,8 @@ class JobChargeServiceTest {}@Test- void openProcess_exhaustedGrant_storesZeroFreeAndLeavesCounterUntouched(@TempDir Path tmp)+ void openProcess_exhaustedGrant_storesZeroFreeAndPersistsTerm(@TempDir Path tmp)throws IOException {- // Grant already at 0 → nothing free, full units bill, counter not re-saved.PricingPolicy policy = stubPolicy(1, Map.of(JobSource.WEB, 10));when(policyService.getEffectivePolicy(100L)).thenReturn(policy);ProcessingJob newJob = openJob(UUID.randomUUID());@@ -553,7 +559,8 @@ class JobChargeServiceTest {ArgumentCaptor<PaygShadowCharge> captor = ArgumentCaptor.forClass(PaygShadowCharge.class);verify(shadowRepo).save(captor.capture());assertThat(captor.getValue().getFreeUnitsConsumed()).isZero();- verify(teamExtRepo, never()).save(any());+ verify(teamExtRepo).save(ext);+ assertThat(ext.getFreeUnitsGranted()).isEqualTo(GRANT);}@Test@@ -671,6 +678,8 @@ class JobChargeServiceTest {// charge time. The refund must hand exactly those free units back to the team's counter.UUID jobId = UUID.randomUUID();PaygShadowCharge row = chargedShadowRow(jobId, 100L, 10, 3, BillingCategory.API);+ row.setIncludedPeriodStart(PERIOD_START);+ row.setOccurredAt(PERIOD_START.plusMonths(1));when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.of(row));when(jobRepo.findById(jobId)).thenReturn(Optional.of(openJob(jobId)));PaygTeamExtensions ext = new PaygTeamExtensions();@@ -687,21 +696,23 @@ class JobChargeServiceTest {@Testvoid markFirstStepFailed_refundAfterPeriodTurned_doesNotExceedTheGrant() {- // The charge's period is over and the grant already reset, so the restore is capped.UUID jobId = UUID.randomUUID();PaygShadowCharge row = chargedShadowRow(jobId, 100L, 10, 3, BillingCategory.API);+ row.setOccurredAt(PERIOD_START.minusDays(1));+ row.setIncludedPeriodStart(PERIOD_START.minusMonths(1));when(shadowRepo.findFirstByJobIdOrderByIdAsc(jobId)).thenReturn(Optional.of(row));when(jobRepo.findById(jobId)).thenReturn(Optional.of(openJob(jobId)));PaygTeamExtensions ext = new PaygTeamExtensions();ext.setTeamId(100L);- ext.setFreeUnitsRemaining(0L);- ext.setFreeUnitsPeriodStart(PERIOD_START.minusMonths(1));+ ext.setFreeUnitsRemaining(100L);+ ext.setFreeUnitsPeriodStart(PERIOD_START);when(teamExtRepo.findByIdForUpdate(100L)).thenReturn(Optional.of(ext));service.markFirstStepFailed(jobId, "first-step-5xx:503");- assertThat(ext.getFreeUnitsRemaining()).isEqualTo(GRANT);+ assertThat(ext.getFreeUnitsRemaining()).isEqualTo(100L);assertThat(ext.getFreeUnitsPeriodStart()).isEqualTo(PERIOD_START);+ verify(teamExtRepo, never()).save(any());}@Test@@ -1172,6 +1183,7 @@ class JobChargeServiceTest {row.setTeamId(teamId);row.setPaygUnits(units);row.setFreeUnitsConsumed(freeUnitsConsumed);+ row.setOccurredAt(PERIOD_START.plusDays(1));row.setStatus(ShadowChargeStatus.CHARGED);row.setBillingCategory(category);return row;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.javaindex 0e6f2e2d56..8b2dc90c62 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@@ -21,7 +21,7 @@ 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;-import stirling.software.saas.payg.repository.WalletLedgerRepository;+import stirling.software.saas.payg.repository.PaygShadowChargeRepository;import stirling.software.saas.payg.repository.WalletPolicyRepository;import stirling.software.saas.payg.wallet.WalletPolicy;@@ -34,8 +34,7 @@ import stirling.software.saas.payg.wallet.WalletPolicy;* remaining}, both read straight from the billing context (no ledger query). Exhausted grant* (remaining ≤ 0) → DEGRADED.* <li><b>Subscribed</b> — gated by the monthly money-derived doc cap. Spend = this period's net- * billable units ({@link WalletLedgerRepository#sumPeriodNetBillable} negated, refunds- * netted).+ * metered units ({@link PaygShadowChargeRepository#sumPaidUnits}, excluding refunded jobs).* </ul>** Also covers cache hit/miss + the invalidate cascade.@@ -47,15 +46,35 @@ class EntitlementServiceTest {private TeamBillingService billingService;private WalletPolicyRepository walletPolicyRepo;- private WalletLedgerRepository ledgerRepo;+ private PaygShadowChargeRepository ledgerRepo;private PrepaidBundleService prepaidBundleService;private EntitlementService service;+ @Test+ void zeroMeteredCapDoesNotBlockIncludedTeamCredits() {+ stubBilling(+ 42L,+ new TeamBillingContext(+ true,+ "sub",+ PERIOD_START,+ PERIOD_END,+ 2500,+ 2200,+ null,+ null,+ 0L,+ 0L,+ PERIOD_START,+ PERIOD_END));+ assertThat(service.getSnapshot(42L).state()).isEqualTo(EntitlementState.FULL);+ }+@BeforeEachvoid setUp() {billingService = Mockito.mock(TeamBillingService.class);walletPolicyRepo = Mockito.mock(WalletPolicyRepository.class);- ledgerRepo = Mockito.mock(WalletLedgerRepository.class);+ ledgerRepo = Mockito.mock(PaygShadowChargeRepository.class);prepaidBundleService = Mockito.mock(PrepaidBundleService.class);service =new EntitlementService(@@ -90,7 +109,7 @@ class EntitlementServiceTest {stubBilling(42L, subscribedContext(2000L));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.of(walletPolicyThresholds(FeatureSet.MINIMAL)));- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(-500L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(500L);EntitlementSnapshot snap = service.getSnapshot(42L);@@ -101,10 +120,9 @@ class EntitlementServiceTest {@Testvoid subscribedTeam_refundsNetAgainstSpend() {- // Net billable = debits − refunds. A −300 net (e.g. 500 debited, 200 refunded) → 300 spend.stubBilling(42L, subscribedContext(2000L));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(-300L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(300L);EntitlementSnapshot snap = service.getSnapshot(42L);@@ -115,14 +133,14 @@ class EntitlementServiceTest {void spendWindow_comesFromBillingContextNotCalendarMonth() {stubBilling(42L, subscribedContext(2000L));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(0L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(0L);EntitlementSnapshot snap = service.getSnapshot(42L);// The subscription-anchored window flows through to both the snapshot and the SUM query.assertThat(snap.periodStart()).isEqualTo(PERIOD_START);assertThat(snap.periodEnd()).isEqualTo(PERIOD_END);- verify(ledgerRepo).sumPeriodNetBillable(eq(42L), eq(PERIOD_START), eq(PERIOD_END));+ verify(ledgerRepo).sumPaidUnits(eq(42L), eq(PERIOD_START), eq(PERIOD_END));}@Test@@ -198,7 +216,7 @@ class EntitlementServiceTest {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(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(1000L);when(prepaidBundleService.prepaidRemainingUnits(42L)).thenReturn(5000L);EntitlementSnapshot snap = service.getSnapshot(42L);@@ -226,7 +244,7 @@ class EntitlementServiceTest {stubBilling(42L, subscribedContext(1000L));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.of(walletPolicyThresholds(FeatureSet.MINIMAL)));- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(-1000L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(1000L);when(prepaidBundleService.prepaidRemainingUnits(42L)).thenReturn(0L);EntitlementSnapshot snap = service.getSnapshot(42L);@@ -245,7 +263,7 @@ class EntitlementServiceTest {stubBilling(42L, subscribedContext(1000L));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.of(walletPolicyThresholds(FeatureSet.MINIMAL)));- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(-250L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(250L);EntitlementSnapshot snap = service.getSnapshot(42L);@@ -271,7 +289,7 @@ class EntitlementServiceTest {void uncappedSubscribedTeam_nullCapNeverDegrades() {stubBilling(42L, subscribedContext(null));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(-1_000_000L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(1_000_000L);EntitlementSnapshot snap = service.getSnapshot(42L);@@ -280,11 +298,10 @@ class EntitlementServiceTest {}@Test- void positiveNetBillable_treatedAsZeroSpend() {- // Subscribed defensive: if refunds exceed debits (positive net), spend clamps to zero.+ void negativeMeteredSpend_treatedAsZeroSpend() {stubBilling(42L, subscribedContext(100L));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(50L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(-50L);EntitlementSnapshot snap = service.getSnapshot(42L);@@ -296,14 +313,14 @@ class EntitlementServiceTest {void cacheHit_secondCallSkipsLedgerLookup() {stubBilling(42L, subscribedContext(500L));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(0L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(0L);service.getSnapshot(42L);service.getSnapshot(42L);service.getSnapshot(42L);// Only one underlying ledger SUM despite 3 calls — second + third hit the cache.- verify(ledgerRepo, times(1)).sumPeriodNetBillable(eq(42L), any(), any());+ verify(ledgerRepo, times(1)).sumPaidUnits(eq(42L), any(), any());assertThat(service.cacheSize()).isEqualTo(1);}@@ -311,13 +328,13 @@ class EntitlementServiceTest {void invalidate_dropsCacheAndCascadesToBillingService() {stubBilling(42L, subscribedContext(500L));when(walletPolicyRepo.findByTeamId(42L)).thenReturn(Optional.empty());- when(ledgerRepo.sumPeriodNetBillable(eq(42L), any(), any())).thenReturn(0L);+ when(ledgerRepo.sumPaidUnits(eq(42L), any(), any())).thenReturn(0L);service.getSnapshot(42L);service.invalidate(42L);service.getSnapshot(42L);- verify(ledgerRepo, times(2)).sumPeriodNetBillable(eq(42L), any(), any());+ verify(ledgerRepo, times(2)).sumPaidUnits(eq(42L), any(), any());// Window/cap facts must recompute together with the spend.verify(billingService).invalidate(42L);}@@ -326,14 +343,14 @@ class EntitlementServiceTest {void invalidate_otherTeamLeavesEntryAlone() {when(billingService.forTeam(any())).thenReturn(subscribedContext(500L));when(walletPolicyRepo.findByTeamId(any())).thenReturn(Optional.empty());- when(ledgerRepo.sumPeriodNetBillable(any(), any(), any())).thenReturn(0L);+ when(ledgerRepo.sumPaidUnits(any(), any(), any())).thenReturn(0L);service.getSnapshot(42L);service.invalidate(99L);service.getSnapshot(42L);// Only one fetch for team 42 — 99 invalidate didn't touch its entry.- verify(ledgerRepo, times(1)).sumPeriodNetBillable(eq(42L), any(), any());+ verify(ledgerRepo, times(1)).sumPaidUnits(eq(42L), any(), any());}@Test@@ -351,7 +368,18 @@ class EntitlementServiceTest {/** Unsubscribed team: gated by the one-time grant (size + remaining); no monthly cap. */private static TeamBillingContext freeContext(long grant, long remaining) {return new TeamBillingContext(- false, null, PERIOD_START, PERIOD_END, grant, remaining, null, null, null, null);+ false,+ null,+ PERIOD_START,+ PERIOD_END,+ grant,+ remaining,+ null,+ null,+ null,+ null,+ PERIOD_START,+ PERIOD_END);}/**@@ -369,7 +397,9 @@ class EntitlementServiceTest {java.math.BigDecimal.valueOf(2),"usd",monthlyCapDocUnits == null ? null : monthlyCapDocUnits * 2,- monthlyCapDocUnits);+ monthlyCapDocUnits,+ PERIOD_START,+ PERIOD_END);}private static WalletPolicy walletPolicyThresholds(FeatureSet degradedSet) {diff --git a/app/saas/src/test/java/stirling/software/saas/payg/policy/PricingPolicyServiceTest.java b/app/saas/src/test/java/stirling/software/saas/payg/policy/PricingPolicyServiceTest.javaindex 3c552d205a..d3daf80296 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/policy/PricingPolicyServiceTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/policy/PricingPolicyServiceTest.java@@ -201,10 +201,13 @@ class PricingPolicyServiceTest {PricingPolicy promoted = policy(2L, "v1-enterprise", true);when(policyRepo.findById(2L)).thenReturn(Optional.of(overridePolicy));when(policyRepo.save(any(PricingPolicy.class))).thenReturn(promoted);+ defaultPolicy.setTeamIncludedUnits(2700L);+ when(policyRepo.findFirstByIsDefaultTrue()).thenReturn(Optional.of(defaultPolicy));PricingPolicy result = service.setDefault(2L);verify(policyRepo).clearDefaultFlag();+ assertThat(overridePolicy.getTeamIncludedUnits()).isEqualTo(2700L);assertThat(result.getIsDefault()).isTrue();verify(events, atLeastOnce()).publishEvent(any(PolicyChangedEvent.class));}diff --git a/app/saas/src/test/java/stirling/software/saas/payg/policy/admin/PricingPolicyAdminControllerTest.java b/app/saas/src/test/java/stirling/software/saas/payg/policy/admin/PricingPolicyAdminControllerTest.javaindex 3216361919..fa5bfb00f6 100644--- a/app/saas/src/test/java/stirling/software/saas/payg/policy/admin/PricingPolicyAdminControllerTest.java+++ b/app/saas/src/test/java/stirling/software/saas/payg/policy/admin/PricingPolicyAdminControllerTest.java@@ -86,7 +86,8 @@ class PricingPolicyAdminControllerTest {null,null,"notes",- "[email protected]");+ "[email protected]",+ 2700L);PricingPolicy saved = policy(99L, "v2", false);ArgumentCaptor<PricingPolicy> draft = ArgumentCaptor.forClass(PricingPolicy.class);when(service.create(draft.capture())).thenReturn(saved);@@ -96,6 +97,7 @@ class PricingPolicyAdminControllerTest {assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.CREATED);assertThat(((PolicyResponse) resp.getBody()).policyId()).isEqualTo(99L);assertThat(draft.getValue().getVersion()).isEqualTo("v2");+ assertThat(draft.getValue().getTeamIncludedUnits()).isEqualTo(2700L);// Controller must never let isDefault=true through to the service — setDefault is the// only path for promotion.assertThat(draft.getValue().getIsDefault()).isFalse();diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 67244a90f1..a501a4d9c0 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -7570,6 +7570,7 @@ subNoRate = "Team base plus metered processing"[portal.billing.identity.team]chipFleet = "Fleet control"+chipIncluded = "{{allowance}} included credits monthly"chipSso = "SSO"name = "Team"sub = "Up to {{users}} users"@@ -7722,13 +7723,15 @@ low = "Running low"[portal.billing.processor]activate = "Switch on the Processor"-capTooltip = "Pauses PDF processing at your spend limit."factCapped = "{{pct}}% of {{cap}}"factFree = "{{used}} of {{allowance}} used"factNoCap = "no limit"included = "Included in your license"-midFree = "{{rate}} per credit · {{allowance}} free every month"-midFreeNoRate = "{{allowance}} free every month"+includedCredits = "Included credits"+includedRenewal = "{{summary}} · Renews {{date}}"+meteredCapTooltip = "Pauses metered processing at your spend limit."+midIncluded = "{{rate}} per credit · {{allowance}} included every month"+midIncludedNoRate = "{{allowance}} included every month"midMetered = "{{spend}} metered this cycle"midMeteredUnknown = "Metered this cycle"raiseLimit = "Raise limit"diff --git a/frontend/editor/src/cloud/hooks/useWallet.ts b/frontend/editor/src/cloud/hooks/useWallet.tsindex 2c28073a6d..38b80ac05a 100644--- a/frontend/editor/src/cloud/hooks/useWallet.ts+++ b/frontend/editor/src/cloud/hooks/useWallet.ts@@ -135,6 +135,8 @@ function reuseIfEqual(prev: Wallet | null, next: Wallet): Wallet {prev.billableLimit !== next.billableLimit ||prev.freeAllowance !== next.freeAllowance ||prev.freeRemaining !== next.freeRemaining ||+ prev.includedPeriodStart !== next.includedPeriodStart ||+ prev.includedPeriodEnd !== next.includedPeriodEnd ||prev.pricePerDocMinor !== next.pricePerDocMinor ||prev.bundleRatePerCreditMinor !== next.bundleRatePerCreditMinor ||prev.currency !== next.currency ||diff --git a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsxindex 389a6b8996..ae3ad1aa07 100644--- a/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx+++ b/frontend/editor/src/portal/components/billing/FreeTierPlanView.test.tsx@@ -90,7 +90,7 @@ describe("FreeTierPlanView", () => {expect(await screen.findByText("120 of 500 used")).toBeInTheDocument();// No rate is known locally, so the row quotes the allowance rather than a price.- expect(screen.getByText("500 free every month")).toBeInTheDocument();+ expect(screen.getByText("500 included every month")).toBeInTheDocument();});it("reads only the instance's own ledger for the meter", async () => {diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.tsxindex 49cc9b5a0d..00e11bd504 100644--- a/frontend/editor/src/proprietary/billing/BillingScreen.tsx+++ b/frontend/editor/src/proprietary/billing/BillingScreen.tsx@@ -210,6 +210,11 @@ export function BillingScreen({chips: [t("portal.billing.identity.team.chipSso", "SSO"),t("portal.billing.identity.team.chipFleet", "Fleet control"),+ t(+ "portal.billing.identity.team.chipIncluded",+ "{{allowance}} included credits monthly",+ { allowance: wallet.freeAllowance.toLocaleString() },+ ),],};}diff --git a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsxindex 8073e0b873..bc59d971a4 100644--- a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx@@ -14,6 +14,7 @@ vi.mock("react-i18next", () => ({import { ProcessorPlanRow } from "@app/billing/ProcessorPlanRow";import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";import type { Wallet } from "@app/billing/types";+import { formatPeriodDate } from "@app/billing/format";const off = (over: Partial<Wallet> = {}): Wallet => ({...freeWallet,@@ -27,6 +28,64 @@ const on = (over: Partial<Wallet> = {}): Wallet => ({});describe("ProcessorPlanRow", () => {+ it("hides an absent included pool while retaining metered billing", () => {+ render(+ <ProcessorPlanRow wallet={on({ freeAllowance: 0, freeRemaining: 0 })} />,+ );+ expect(screen.queryByText("Included credits")).not.toBeInTheDocument();+ expect(screen.queryByText("0 of 0 used")).not.toBeInTheDocument();+ expect(screen.getByText("Processor")).toBeInTheDocument();+ });++ it("keeps activation available when there is no included pool", () => {+ render(+ <ProcessorPlanRow+ wallet={off({ freeAllowance: 0, freeRemaining: 0 })}+ onActivate={() => {}}+ />,+ );+ expect(screen.queryByText("0 of 0 used")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Switch on the Processor" }),+ ).toBeInTheDocument();+ });+ it("keeps the included pool visible when the metered limit is zero", () => {+ render(+ <ProcessorPlanRow+ wallet={on({+ capUsd: 0,+ noCap: false,+ estimatedBillMinor: 0,+ freeAllowance: 2500,+ freeRemaining: 2200,+ })}+ />,+ );+ expect(screen.getByText("100% of $0")).toBeInTheDocument();+ expect(screen.getByText("300 of 2,500 used")).toBeInTheDocument();+ });+ it("shows the actual Team allowance and its independent renewal while metering is on", () => {+ render(+ <ProcessorPlanRow+ wallet={on({+ freeAllowance: 2700,+ freeRemaining: 2300,+ includedPeriodEnd: "2026-10-01",+ })}+ pendingUnits={25}+ />,+ );+ expect(screen.getByText("Included credits")).toBeInTheDocument();+ expect(screen.getByText("425 of 2,700 used")).toBeInTheDocument();+ expect(+ screen.getByText(+ (text) =>+ text.includes("2,700 included every month") &&+ text.includes(`Renews ${formatPeriodDate("2026-10-01")}`),+ ),+ ).toBeInTheDocument();+ });+it("sells while off: the grant drains towards the activation door", () => {render(<ProcessorPlanRow@@ -91,7 +150,7 @@ describe("ProcessorPlanRow", () => {);expect(screen.getByText("no limit")).toBeInTheDocument();- expect(container.querySelector(".billing-meter__fill")).toBeNull();+ expect(container.querySelectorAll(".billing-meter__fill")).toHaveLength(1);});it("lets a prepaid team's door be relabelled without changing the row", () => {diff --git a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsxindex bf6166fd58..a6a1f2061e 100644--- a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx@@ -1,6 +1,10 @@import type { ReactNode } from "react";import { useTranslation } from "react-i18next";-import { formatMinor, formatMoneyMajor } from "@app/billing/format";+import {+ formatMinor,+ formatMoneyMajor,+ formatPeriodDate,+} from "@app/billing/format";import { MeterRow } from "@app/billing/MeterRow";import { estimatedBillWithPending } from "@app/billing/pendingUsage";import type { Wallet } from "@app/billing/types";@@ -55,7 +59,8 @@ export function ProcessorPlanRow({if (!wallet) return null;const rate = wallet.pricePerDocMinor;- if (!wallet.processor.active) {+ const includedCredits = (() => {+ if (wallet.freeAllowance <= 0) return null;const used = Math.min(wallet.freeAllowance,Math.max(0, wallet.freeAllowance - wallet.freeRemaining + pendingUnits),@@ -65,16 +70,16 @@ export function ProcessorPlanRow({const mid =rate != null? t(- "portal.billing.processor.midFree",- "{{rate}} per credit · {{allowance}} free every month",+ "portal.billing.processor.midIncluded",+ "{{rate}} per credit · {{allowance}} included every month",{rate: formatMinor(rate, wallet.currency),allowance: wallet.freeAllowance.toLocaleString(),},): t(- "portal.billing.processor.midFreeNoRate",- "{{allowance}} free every month",+ "portal.billing.processor.midIncludedNoRate",+ "{{allowance}} included every month",{allowance: wallet.freeAllowance.toLocaleString(),},@@ -82,8 +87,23 @@ export function ProcessorPlanRow({return (<MeterRow- name={name}- mid={mid}+ name={+ wallet.processor.active+ ? t("portal.billing.processor.includedCredits", "Included credits")+ : name+ }+ mid={+ wallet.includedPeriodEnd+ ? t(+ "portal.billing.processor.includedRenewal",+ "{{summary}} · Renews {{date}}",+ {+ summary: mid,+ date: formatPeriodDate(wallet.includedPeriodEnd),+ },+ )+ : mid+ }pct={pct}tone="free"fact={t(@@ -95,15 +115,36 @@ export function ProcessorPlanRow({},)}door={- onActivate+ !wallet.processor.active && onActivate? (activateLabel ??t("portal.billing.processor.activate", "Switch on the Processor")): undefined}- onDoor={onActivate}+ onDoor={!wallet.processor.active ? onActivate : undefined}/>);- }+ })();+ if (!wallet.processor.active)+ return (+ includedCredits ?? (+ <MeterRow+ name={name}+ mid=""+ fact=""+ showTrack={false}+ door={+ onActivate+ ? (activateLabel ??+ t(+ "portal.billing.processor.activate",+ "Switch on the Processor",+ ))+ : undefined+ }+ onDoor={onActivate}+ />+ )+ );const spentMinor = estimatedBillWithPending(wallet, pendingUnits);const capped = !wallet.noCap && wallet.capUsd != null;@@ -111,7 +152,9 @@ export function ProcessorPlanRow({const spentMajor = spentMinor != null ? spentMinor / 100 : null;const pct =capped && spentMajor != null- ? (spentMajor / (wallet.capUsd as number)) * 100+ ? wallet.capUsd === 0+ ? 100+ : (spentMajor / (wallet.capUsd as number)) * 100: 0;const mid =@@ -139,23 +182,26 @@ export function ProcessorPlanRow({: undefined);return (- <MeterRow- name={name}- mid={mid}- pct={pct}- tone={capped && pct >= 90 ? "warn" : "paid"}- showTrack={capped}- fact={fact}- door={onGovern ? door : undefined}- onDoor={onGovern}- midTitle={- capped- ? t(- "portal.billing.processor.capTooltip",- "Pauses PDF processing at your spend limit.",- )- : undefined- }- />+ <>+ {includedCredits}+ <MeterRow+ name={name}+ mid={mid}+ pct={pct}+ tone={capped && pct >= 90 ? "warn" : "paid"}+ showTrack={capped}+ fact={fact}+ door={onGovern ? door : undefined}+ onDoor={onGovern}+ midTitle={+ capped+ ? t(+ "portal.billing.processor.meteredCapTooltip",+ "Pauses metered processing at your spend limit.",+ )+ : undefined+ }+ />+ </>);}diff --git a/frontend/editor/src/proprietary/billing/types.ts b/frontend/editor/src/proprietary/billing/types.tsindex 5e9df435b6..b70c5c38cb 100644--- a/frontend/editor/src/proprietary/billing/types.ts+++ b/frontend/editor/src/proprietary/billing/types.ts@@ -70,6 +70,9 @@ export interface Wallet {/** ISO yyyy-mm-dd. Stripe period when subscribed; calendar month when free. */billingPeriodStart: string;billingPeriodEnd: string;+ /** Independent monthly included-credit term; absent on older servers. */+ includedPeriodStart?: string | null;+ includedPeriodEnd?: string | null;/** Free grant used this period (free teams) or documents processed this period (subscribed). */billableUsed: number;/** Document ceiling for the window; null when subscribed-uncapped. */