Skip to content

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

Share Team capacity through daily instance sync (#8053)

ConnorYoh63483d759410
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.java
index b03358fc16..51c644caad 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
@@ -296,16 +296,40 @@ public class AccountLinkClient {
long apiUnits,
long aiUnits,
long automationUnits) {
+ return reportUsage(
+ deviceId,
+ deviceSecret,
+ syncSeq,
+ periodStart,
+ apiUnits,
+ aiUnits,
+ automationUnits,
+ null);
+ }
+
+ /** A null period sends only deployment seats, without changing usage counters. */
+ public InstanceEntitlement reportUsage(
+ String deviceId,
+ String deviceSecret,
+ long syncSeq,
+ LocalDateTime periodStart,
+ long apiUnits,
+ long aiUnits,
+ long automationUnits,
+ Integer seatCount) {
HttpResponse<String> response;
try {
ObjectNode root = mapper.createObjectNode();
root.put("syncSeq", syncSeq);
// Explicit ISO-8601 string so it round-trips regardless of the mapper's time config.
- root.put("periodStart", periodStart.toString());
- ObjectNode units = root.putObject("cumulativeUnits");
- units.put("api", apiUnits);
- units.put("ai", aiUnits);
- units.put("automation", automationUnits);
+ if (seatCount != null) root.put("seatCount", seatCount);
+ if (periodStart != null) {
+ root.put("periodStart", periodStart.toString());
+ ObjectNode units = root.putObject("cumulativeUnits");
+ units.put("api", apiUnits);
+ units.put("ai", aiUnits);
+ units.put("automation", automationUnits);
+ }
String body = mapper.writeValueAsString(root);
HttpRequest request =
HttpRequest.newBuilder()
@@ -359,7 +383,10 @@ public class AccountLinkClient {
parseDateTime(root, "periodEnd"),
licensedUsers,
root.path("automationStepLimit").asInt(0),
- root.path("prepaidRemainingUnits").asLong(0));
+ root.path("prepaidRemainingUnits").asLong(0),
+ root.hasNonNull("fleetUserLimit")
+ ? Math.max(0, root.get("fleetUserLimit").asInt())
+ : null);
}
/** 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/AccountLinkController.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java
index fd487665aa..d7fb31fa42 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/AccountLinkController.java
@@ -42,7 +42,6 @@ public class AccountLinkController {
private final ConnectService connectService;
private final LocalUsageService localUsageService;
private final FreeTierUsageService freeTierUsageService;
- // Present only when metering is on (its own flag); absent → /sync-now reports 409.
private final ObjectProvider<UsageSyncService> syncServiceProvider;
public AccountLinkController(
@@ -102,11 +101,23 @@ public class AccountLinkController {
}
}
- /** Called by the callback page with the nonce it found in the fragment. */
+ /** Finishes the link, then reports seats after the credential transaction has committed. */
@PostMapping("/connect/complete")
public ResponseEntity<ConnectService.ConnectStatus> connectComplete(
@RequestBody(required = false) ConnectCompleteRequest req) {
- return ResponseEntity.ok(connectService.complete(req != null ? req.nonce() : null));
+ ConnectService.ConnectStatus result =
+ connectService.complete(req != null ? req.nonce() : null);
+ if (result.phase() == ConnectService.Phase.LINKED) {
+ UsageSyncService sync = syncServiceProvider.getIfAvailable();
+ if (sync != null) {
+ try {
+ sync.syncNow();
+ } catch (RuntimeException e) {
+ log.warn("Initial account-link sync failed; the scheduled sync will retry", e);
+ }
+ }
+ }
+ return ResponseEntity.ok(result);
}
/** Everything we know about where the admin's browser is, for the callback. */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java
index a14b812df7..6ec212dfa9 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredential.java
@@ -58,6 +58,9 @@ public class DeviceCredential implements Serializable {
columnDefinition = "boolean not null default false")
private boolean entitlementRevoked;
+ @Column(name = "fleet_user_limit")
+ private Integer fleetUserLimit;
+
@Column(name = "linked_at", nullable = false)
private LocalDateTime linkedAt;
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java
index 9c3261b6c1..c37b0b9cf1 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialRepository.java
@@ -12,8 +12,9 @@ public interface DeviceCredentialRepository extends JpaRepository<DeviceCredenti
/** Updates only the current device, so an old response cannot refresh a replacement link. */
@Modifying(clearAutomatically = true)
@Query(
- "update DeviceCredential c set c.lastEntitlementSuccessAt = :at, c.entitlementRevoked = :revoked where c.deviceId = :deviceId and (c.lastEntitlementSuccessAt is null or c.lastEntitlementSuccessAt <= :at)")
- int recordEntitlementContact(String deviceId, Instant at, boolean revoked);
+ "update DeviceCredential c set c.lastEntitlementSuccessAt = :at, c.entitlementRevoked = :revoked, c.fleetUserLimit = :fleetUserLimit where c.deviceId = :deviceId and (c.lastEntitlementSuccessAt is null or c.lastEntitlementSuccessAt <= :at)")
+ int recordEntitlementContact(
+ String deviceId, Instant at, boolean revoked, Integer fleetUserLimit);
/** The singleton credential, if this instance has linked. */
default Optional<DeviceCredential> findCredential() {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java
index d5a12a59e1..ec0451769e 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/DeviceCredentialStore.java
@@ -51,13 +51,15 @@ public class DeviceCredentialStore {
cred.setLinkedAt(LocalDateTime.now());
cred.setLastEntitlementSuccessAt(null);
cred.setEntitlementRevoked(false);
+ cred.setFleetUserLimit(null);
repo.save(cred);
}
/** Commits successful contact independently of the caller's work or transaction rollback. */
@Transactional(propagation = Propagation.REQUIRES_NEW)
- public void recordEntitlementContact(String deviceId, Instant at, boolean revoked) {
- repo.recordEntitlementContact(deviceId, at, revoked);
+ public void recordEntitlementContact(
+ String deviceId, Instant at, boolean revoked, Integer fleetUserLimit) {
+ repo.recordEntitlementContact(deviceId, at, revoked, revoked ? null : fleetUserLimit);
}
/** Unlinks this instance locally (idempotent). */
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java
index 777c91df8f..370235a0b2 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/EntitlementCache.java
@@ -157,10 +157,27 @@ public class EntitlementCache {
private Snapshot successfulSnapshot(String deviceId, InstanceEntitlement entitlement) {
Instant now = clock.instant();
credentialStore.recordEntitlementContact(
- deviceId, now, entitlement.state() == EntitlementState.REVOKED);
+ deviceId,
+ now,
+ entitlement.state() == EntitlementState.REVOKED,
+ entitlement.fleetUserLimit());
return new Snapshot(entitlement, now, now, false);
}
+ /** The current device's persisted allowance is usable only within its offline grace. */
+ public Integer fleetUserLimit() {
+ if (isGraceExpired()) return null;
+ var credential = credentialStore.get();
+ if (credential.isEmpty() || credential.get().isEntitlementRevoked()) return null;
+ if (Objects.equals(snapshotDeviceId, credential.get().getDeviceId())
+ && snapshot.entitlement() != null) {
+ return snapshot.entitlement().state() == EntitlementState.REVOKED
+ ? null
+ : snapshot.entitlement().fleetUserLimit();
+ }
+ return credential.get().getFleetUserLimit();
+ }
+
/** Applies across restarts and independently of metering or the presence of cached data. */
public boolean isGraceExpired() {
ConnectionStatus status = connectionStatus();
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.java
index 2d4fcfe21e..26825bc8ff 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
@@ -35,7 +35,61 @@ public record InstanceEntitlement(
LocalDateTime periodEnd,
Integer licensedUsers,
int automationStepLimit,
- long prepaidRemainingUnits) {
+ long prepaidRemainingUnits,
+ Integer fleetUserLimit) {
+
+ public InstanceEntitlement(
+ boolean subscribed,
+ long freeRemainingUnits,
+ long periodSpendUnits,
+ Long periodCapUnits,
+ EntitlementState state,
+ UnitCalcPolicy unitCalcPolicy,
+ LocalDateTime periodStart,
+ LocalDateTime periodEnd,
+ Integer licensedUsers,
+ int automationStepLimit,
+ long prepaidRemainingUnits) {
+ this(
+ subscribed,
+ freeRemainingUnits,
+ periodSpendUnits,
+ periodCapUnits,
+ state,
+ unitCalcPolicy,
+ periodStart,
+ periodEnd,
+ licensedUsers,
+ automationStepLimit,
+ prepaidRemainingUnits,
+ null);
+ }
+
+ public InstanceEntitlement(
+ boolean subscribed,
+ long freeRemainingUnits,
+ long periodSpendUnits,
+ Long periodCapUnits,
+ EntitlementState state,
+ UnitCalcPolicy unitCalcPolicy,
+ LocalDateTime periodStart,
+ LocalDateTime periodEnd,
+ Integer licensedUsers,
+ int automationStepLimit) {
+ this(
+ subscribed,
+ freeRemainingUnits,
+ periodSpendUnits,
+ periodCapUnits,
+ state,
+ unitCalcPolicy,
+ periodStart,
+ periodEnd,
+ licensedUsers,
+ automationStepLimit,
+ 0L,
+ null);
+ }
public InstanceEntitlement {
automationStepLimit = BillingStepLimit.resolve(automationStepLimit);
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageSyncService.java b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageSyncService.java
index a8e3a921ac..57859b4fe6 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageSyncService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/accountlink/UsageSyncService.java
@@ -6,6 +6,7 @@ import java.util.EnumMap;
import java.util.List;
import java.util.Optional;
+import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Profile;
@@ -17,6 +18,8 @@ import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import stirling.software.proprietary.billing.BillingCategory;
+import stirling.software.proprietary.security.service.UserService;
+import stirling.software.proprietary.service.UserLicenseSettingsService;
/**
* Daily usage sender for combined billing. Reports each period's cumulative per-category usage to
@@ -32,8 +35,9 @@ import stirling.software.proprietary.billing.BillingCategory;
@Service
@Profile("!saas")
@ConditionalOnProperty(
- name = "stirling.billing.account-link.metering.enabled",
- havingValue = "true")
+ name = "stirling.billing.account-link.enabled",
+ havingValue = "true",
+ matchIfMissing = true)
public class UsageSyncService implements SchedulingConfigurer {
// First run waits out startup churn; then every interval.
@@ -46,6 +50,8 @@ public class UsageSyncService implements SchedulingConfigurer {
private final EntitlementCache entitlementCache;
private final AccountLinkProperties properties;
private final ApplicationEventPublisher events;
+ private final ObjectProvider<UserService> users;
+ private final UserLicenseSettingsService licenseSettings;
public UsageSyncService(
UsageCounterRepository counters,
@@ -54,7 +60,9 @@ public class UsageSyncService implements SchedulingConfigurer {
AccountLinkClient client,
EntitlementCache entitlementCache,
AccountLinkProperties properties,
- ApplicationEventPublisher events) {
+ ApplicationEventPublisher events,
+ ObjectProvider<UserService> users,
+ UserLicenseSettingsService licenseSettings) {
this.counters = counters;
this.syncState = syncState;
this.credentialStore = credentialStore;
@@ -62,6 +70,8 @@ public class UsageSyncService implements SchedulingConfigurer {
this.entitlementCache = entitlementCache;
this.properties = properties;
this.events = events;
+ this.users = users;
+ this.licenseSettings = licenseSettings;
}
/**
@@ -86,40 +96,49 @@ public class UsageSyncService implements SchedulingConfigurer {
/**
* Reports every period with unsynced usage and refreshes the cached entitlement from the reply.
- * Single daily caller (non-reentrant {@code fixedDelay}), so no internal locking. No-op when
- * unlinked or when nothing is pending.
+ * Serializes link, manual and scheduled calls to preserve report sequence ordering. Also
+ * reports seats when no credits are pending; no-op when unlinked.
*/
- public void syncNow() {
+ public synchronized void syncNow() {
Optional<DeviceCredential> cred = credentialStore.get();
if (cred.isEmpty()) {
return; // not linked
}
- List<LocalDateTime> periods = counters.findPeriodsWithUnsyncedUsage();
- if (periods.isEmpty()) {
- // Nothing to report, but a sync is also our cue to pick up an out-of-band entitlement
- // change (e.g. the admin just subscribed) that otherwise wouldn't surface until the
- // cache TTL lapses. Force an immediate refresh so the gate reflects the new plan now.
- entitlementCache.invalidate();
- entitlementCache.current();
- events.publishEvent(new EntitlementRefreshedEvent());
- return;
- }
+ UserService localUsers = users.getIfAvailable();
+ if (localUsers == null) return;
+ int seatCount =
+ licenseSettings.hasLicenseKeyPaidTier()
+ ? 0
+ : Math.toIntExact(localUsers.getTotalUsersCount());
+ List<LocalDateTime> periods =
+ properties.getMetering().isEnabled()
+ ? counters.findPeriodsWithUnsyncedUsage()
+ : List.of();
InstanceEntitlement latest = null;
try {
+ if (periods.isEmpty()) {
+ latest =
+ client.reportUsage(
+ cred.get().getDeviceId(),
+ cred.get().getDeviceSecret(),
+ 0,
+ null,
+ 0,
+ 0,
+ 0,
+ seatCount);
+ }
for (LocalDateTime period : periods) {
- InstanceEntitlement fresh = syncPeriod(cred.get(), period);
+ InstanceEntitlement fresh = syncPeriod(cred.get(), period, seatCount);
if (fresh != null) {
latest = fresh;
}
}
} catch (AccountLinkClient.RevokedException e) {
- // Authoritative deny — stop reporting; the entitlement cache blocks billable work on
- // its
- // own next refresh, so we don't synthesise the blocked state here.
- log.info(
- "Usage sync denied (HTTP {}); credential revoked/invalid — gate blocks on next"
- + " refresh",
- e.status());
+ entitlementCache.accept(
+ cred.get().getDeviceId(),
+ new InstanceEntitlement(false, 0, 0, 0L, EntitlementState.REVOKED));
+ events.publishEvent(new EntitlementRefreshedEvent());
return;
}
// Adopt the freshest entitlement the sync returned, saving the cache a redundant fetch.
@@ -132,7 +151,8 @@ public class UsageSyncService implements SchedulingConfigurer {
}
/** Reports one period; returns the fresh entitlement, or null on a transport/server failure. */
- private InstanceEntitlement syncPeriod(DeviceCredential cred, LocalDateTime period) {
+ private InstanceEntitlement syncPeriod(
+ DeviceCredential cred, LocalDateTime period, int seatCount) {
EnumMap<BillingCategory, Long> cumulative = new EnumMap<>(BillingCategory.class);
for (UsageCounter c : counters.findByPeriodStart(period)) {
BillingCategory cat = c.billingCategory();
@@ -150,7 +170,8 @@ public class UsageSyncService implements SchedulingConfigurer {
period,
cumulative.getOrDefault(BillingCategory.API, 0L),
cumulative.getOrDefault(BillingCategory.AI, 0L),
- cumulative.getOrDefault(BillingCategory.AUTOMATION, 0L));
+ cumulative.getOrDefault(BillingCategory.AUTOMATION, 0L),
+ seatCount);
if (fresh == null) {
// Transport/server failure: leave the synced markers untouched. The burned seq is
// harmless (seqs need only be monotonic) and the delta bills on the next successful
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
index 622a919e3f..7ae07be5b4 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/service/UserService.java
@@ -656,9 +656,7 @@ public class UserService implements UserServiceInterface {
if (settings == null) {
return;
}
- // Resolve the cap before taking the lock. Only the count and the insert need serialising,
- // and once a linked instance takes its capacity from SaaS this call can refresh that over
- // the network -- a row lock must not be held across a round trip that may time out.
+ // Entitlement refresh may use the network; do it before taking the admission lock.
int max = settings.calculateMaxAllowedUsers();
// Serialise admission. The lock is held until saveUserCore's transaction commits, by which
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java
index 7b18312dfe..49845eecd3 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/UserLicenseSettingsService.java
@@ -308,27 +308,8 @@ public class UserLicenseSettingsService {
}
/**
- * Calculates the maximum allowed users based on grandfathering rules.
- *
- * <p>Logic:
- *
- * <ul>
- * <li>Grandfathered limit = max(5, existing user count at V1→V2 migration)
- * <li>No license, not linked: Uses grandfathered limit only
- * <li>No license, linked: max(grandfathered limit, the linked team's allowance)
- * <li>SERVER license (maxUsers=0): Unlimited users (Integer.MAX_VALUE)
- * <li>ENTERPRISE license (maxUsers>0): License seats only (NO grandfathering added)
- * </ul>
- *
- * <p>IMPORTANT: Paid licenses REPLACE the limit, they don't add to grandfathering. A linked
- * team's allowance does not: linking is monotonic, so it can only raise the ceiling.
- *
- * <p>The branch is chosen by whether a licence <i>key</i> is installed, never by the effective
- * tier. A Team plan bought in the cloud promotes the effective tier to SERVER without carrying
- * a {@code premium.maxUsers}, so branching on the effective tier would read the stored 0 as
- * "SERVER licence, unlimited" and hand a customer who bought 100 users no limit at all.
- *
- * @return Maximum number of users allowed (Integer.MAX_VALUE for unlimited)
+ * Installed licenses keep their own capacity. Linked deployments use the fleet allowance while
+ * the existing offline grace is valid, then fall back to their grandfathered free limit.
*/
public int calculateMaxAllowedUsers() {
validateSettingsIntegrity();
@@ -347,6 +328,12 @@ public class UserLicenseSettingsService {
// whatever it granted, and a customer worse off under it can simply remove it.
if (!hasLicenseKeyPaidTier()) {
Integer fromSaas = linkedTeamAllowance();
+ EntitlementCache cache = entitlementCache.getIfAvailable();
+ Integer fleetLimit = cache == null ? null : cache.fleetUserLimit();
+ if (fleetLimit != null
+ && cache != null
+ && !cache.isGraceExpired()
+ && cache.linkedDeviceId() != null) return fleetLimit;
if (fromSaas != null) {
// Floored at the grandfathered limit, so linking can only raise the ceiling.
// Otherwise a solo cloud account, whose team the instance binds to before any
@@ -696,7 +683,8 @@ public class UserLicenseSettingsService {
* is also SERVER when the promotion comes from a cloud Team plan, and that plan states its
* capacity in the entitlement, not in {@code premium.maxUsers}.
*/
- private boolean hasLicenseKeyPaidTier() {
+ /** Whether installed license capacity is independent of the linked Team subscription. */
+ public boolean hasLicenseKeyPaidTier() {
LicenseKeyChecker checker = licenseKeyChecker.getIfAvailable();
if (checker == null) {
return false;
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkAuthorizationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkAuthorizationTest.java
index ada639e884..e3ea0d2217 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkAuthorizationTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkAuthorizationTest.java
@@ -82,6 +82,8 @@ class AccountLinkAuthorizationTest {
when(ownerService.isCurrentUser(any())).thenReturn(true);
controller.connectStart(null, new MockHttpServletRequest());
controller.connectReauth(null, new MockHttpServletRequest());
+ when(connectService.complete("nonce"))
+ .thenReturn(ConnectService.ConnectStatus.of(ConnectService.Phase.LINKED));
controller.connectComplete(new AccountLinkController.ConnectCompleteRequest("nonce"));
controller.unlink();
controller.recheck();
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
index 9f4ba86ea9..06d03f9546 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkClientTest.java
@@ -317,4 +317,18 @@ class AccountLinkClientTest {
client.reportUsage(
"dev-1", "sec-1", 1L, LocalDateTime.of(2026, 6, 1, 0, 0), 1, 0, 0));
}
+
+ @Test
+ void dailySeatHeartbeatParsesLocalAllowance() throws Exception {
+ var reply = response(200, "{\"state\":\"OK\",\"licensedUsers\":100,\"fleetUserLimit\":17}");
+ when(httpClient.send(any(), any(HttpResponse.BodyHandler.class))).thenReturn(reply);
+ var result = client.reportUsage("dev-1", "sec-1", 0, null, 0, 0, 0, 7);
+ assertNotNull(result);
+ assertEquals(100, result.licensedUsers());
+ assertEquals(17, result.fleetUserLimit());
+ var request = ArgumentCaptor.forClass(HttpRequest.class);
+ org.mockito.Mockito.verify(httpClient)
+ .send(request.capture(), any(HttpResponse.BodyHandler.class));
+ assertEquals("/api/v1/instance/sync", request.getValue().uri().getPath());
+ }
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java
index 6498bfc341..934aa45386 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/AccountLinkControllerTest.java
@@ -2,6 +2,8 @@ package stirling.software.proprietary.accountlink;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -12,6 +14,8 @@ import java.time.LocalDateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -89,6 +93,63 @@ class AccountLinkControllerTest {
return new org.springframework.mock.web.MockHttpServletRequest();
}
+ @Test
+ void connectComplete_reportsSeatsAfterTheLinkCommits() {
+ var linked = new ConnectService.ConnectStatus(ConnectService.Phase.LINKED, null, null, 42L);
+ when(connectService.complete("nonce")).thenReturn(linked);
+ when(syncProvider.getIfAvailable()).thenReturn(syncService);
+
+ var response =
+ controller.connectComplete(
+ new AccountLinkController.ConnectCompleteRequest("nonce"));
+
+ assertThat(response.getBody()).isEqualTo(linked);
+ var order = inOrder(connectService, syncService);
+ order.verify(connectService).complete("nonce");
+ order.verify(syncService).syncNow();
+ }
+
+ @ParameterizedTest
+ @EnumSource(
+ value = ConnectService.Phase.class,
+ names = "LINKED",
+ mode = EnumSource.Mode.EXCLUDE)
+ void connectComplete_doesNotSyncAnUnfinishedOrRejectedLink(ConnectService.Phase phase) {
+ when(connectService.complete("nonce")).thenReturn(ConnectService.ConnectStatus.of(phase));
+
+ controller.connectComplete(new AccountLinkController.ConnectCompleteRequest("nonce"));
+
+ verify(syncProvider, never()).getIfAvailable();
+ verify(syncService, never()).syncNow();
+ }
+
+ @Test
+ void connectComplete_keepsTheCommittedLinkWhenInitialSyncFails() {
+ var linked = new ConnectService.ConnectStatus(ConnectService.Phase.LINKED, null, null, 42L);
+ when(connectService.complete("nonce")).thenReturn(linked);
+ when(syncProvider.getIfAvailable()).thenReturn(syncService);
+ doThrow(new IllegalStateException("Sync unavailable")).when(syncService).syncNow();
+
+ var response =
+ controller.connectComplete(
+ new AccountLinkController.ConnectCompleteRequest("nonce"));
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ assertThat(response.getBody()).isEqualTo(linked);
+ }
+
+ @Test
+ void connectComplete_toleratesAnUnavailableSyncService() {
+ var linked = new ConnectService.ConnectStatus(ConnectService.Phase.LINKED, null, null, 42L);
+ when(connectService.complete("nonce")).thenReturn(linked);
+
+ var response =
+ controller.connectComplete(
+ new AccountLinkController.ConnectCompleteRequest("nonce"));
+
+ assertThat(response.getBody()).isEqualTo(linked);
+ }
+
@Test
void syncNow_triggersSyncWhenMeteringOn() {
when(syncProvider.getIfAvailable()).thenReturn(syncService);
@@ -116,8 +177,8 @@ class AccountLinkControllerTest {
}
@Test
- void syncNow_returns409WhenMeteringOff() {
- when(syncProvider.getIfAvailable()).thenReturn(null); // metering disabled → bean absent
+ void syncNow_returns409WhenSyncUnavailable() {
+ when(syncProvider.getIfAvailable()).thenReturn(null);
ResponseEntity<Void> resp = controller.syncNow();
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/DeviceEntitlementContactDbTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/DeviceEntitlementContactDbTest.java
index 4e9a18faaa..a72f35ca1e 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/DeviceEntitlementContactDbTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/DeviceEntitlementContactDbTest.java
@@ -23,20 +23,27 @@ class DeviceEntitlementContactDbTest {
device.setLinkedAt(LocalDateTime.of(2026, 9, 15, 0, 0));
repository.saveAndFlush(device);
Instant contact = Instant.parse("2026-09-15T10:00:00Z");
- assertThat(repository.recordEntitlementContact("current", contact, true)).isEqualTo(1);
+ assertThat(repository.recordEntitlementContact("current", contact, true, null))
+ .isEqualTo(1);
var restored = repository.findCredential().orElseThrow();
assertThat(restored.getLastEntitlementSuccessAt()).isEqualTo(contact);
assertThat(restored.isEntitlementRevoked()).isTrue();
+ assertThat(restored.getFleetUserLimit()).isNull();
assertThat(
repository.recordEntitlementContact(
- "old-device", contact.plusSeconds(20), false))
+ "old-device", contact.plusSeconds(20), false, 17))
.isZero();
- assertThat(repository.recordEntitlementContact("current", contact.minusSeconds(1), false))
+ assertThat(
+ repository.recordEntitlementContact(
+ "current", contact.minusSeconds(1), false, 17))
.isZero();
assertThat(repository.findCredential().orElseThrow().isEntitlementRevoked()).isTrue();
- assertThat(repository.recordEntitlementContact("current", contact.plusSeconds(1), false))
+ assertThat(
+ repository.recordEntitlementContact(
+ "current", contact.plusSeconds(1), false, 17))
.isEqualTo(1);
assertThat(repository.findCredential().orElseThrow().isEntitlementRevoked()).isFalse();
+ assertThat(repository.findCredential().orElseThrow().getFleetUserLimit()).isEqualTo(17);
}
@SpringBootConfiguration
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java
index c008d67470..5ae9bf98c1 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EnterpriseProcessingHttpIntegrationTest.java
@@ -1,13 +1,10 @@
package stirling.software.proprietary.accountlink;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
-import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -163,15 +160,7 @@ class EnterpriseProcessingHttpIntegrationTest {
assertThat(cloudCounters.count()).isZero();
verifyNoInteractions(cloud);
sync.syncNow();
- verify(cloud, never())
- .reportUsage(
- anyString(),
- anyString(),
- anyLong(),
- any(),
- anyLong(),
- anyLong(),
- anyLong());
+ verify(cloud).reportUsage("test-device", "test-secret", 0L, null, 0L, 0L, 0L, 0);
cloudCounters.saveAndFlush(new UsageCounter(period, "API", 7, period));
when(cloud.reportUsage(
@@ -181,11 +170,12 @@ class EnterpriseProcessingHttpIntegrationTest {
eq(period),
eq(7L),
eq(0L),
- eq(0L)))
+ eq(0L),
+ eq(0)))
.thenReturn(blocked);
sync.syncNow();
- verify(cloud).reportUsage("test-device", "test-secret", 1L, period, 7L, 0L, 0L);
+ verify(cloud).reportUsage("test-device", "test-secret", 1L, period, 7L, 0L, 0L, 0);
assertThat(cloudCounters.findByPeriodStart(period).getFirst().getLastSyncedUnits())
.isEqualTo(7);
assertLocalUsage(SPENT_GRANT + PDF_UNITS);
@@ -319,6 +309,19 @@ class EnterpriseProcessingHttpIntegrationTest {
PdfUaValidationService.class, FontEmbeddingService.class
})
static class TestApp {
+ @Bean
+ stirling.software.proprietary.security.service.UserService userService() {
+ return mock(stirling.software.proprietary.security.service.UserService.class);
+ }
+
+ @Bean
+ stirling.software.proprietary.service.UserLicenseSettingsService licenseSettingsService() {
+ var service =
+ mock(stirling.software.proprietary.service.UserLicenseSettingsService.class);
+ when(service.hasLicenseKeyPaidTier()).thenReturn(true);
+ return service;
+ }
+
@Bean
LicenseKeyChecker licenseKeyChecker() {
return mock(LicenseKeyChecker.class);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementOfflineTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementOfflineTest.java
index 2b175c8551..5f41408bfd 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementOfflineTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/EntitlementOfflineTest.java
@@ -23,11 +23,12 @@ class EntitlementOfflineTest {
doAnswer(
inv -> {
device.setLastEntitlementSuccessAt(inv.getArgument(1));
+ device.setFleetUserLimit(inv.getArgument(3));
device.setEntitlementRevoked(inv.getArgument(2));
return null;
})
.when(store)
- .recordEntitlementContact(eq("device"), any(), anyBoolean());
+ .recordEntitlementContact(eq("device"), any(), anyBoolean(), any());
var client = mock(AccountLinkClient.class);
when(client.fetchEntitlement("device", "secret"))
.thenThrow(new AccountLinkClient.RevokedException(401));
@@ -65,10 +66,11 @@ class EntitlementOfflineTest {
doAnswer(
inv -> {
device.setLastEntitlementSuccessAt(inv.getArgument(1));
+ device.setFleetUserLimit(inv.getArgument(3));
return null;
})
.when(store)
- .recordEntitlementContact(eq("device"), any(), anyBoolean());
+ .recordEntitlementContact(eq("device"), any(), anyBoolean(), any());
AccountLinkClient client = mock(AccountLinkClient.class);
AccountLinkProperties properties = new AccountLinkProperties();
InstanceEntitlement paid =
@@ -120,4 +122,32 @@ class EntitlementOfflineTest {
assertThat(cache.current()).isEmpty();
assertThat(cache.isGraceExpired()).isTrue();
}
+
+ @Test
+ void persistedFleetAllowanceSurvivesRestartButNotExpiryOrRevocation() {
+ Instant start = Instant.parse("2026-09-15T10:00:00Z");
+ Clock clock = mock(Clock.class);
+ when(clock.instant()).thenReturn(start);
+ var device = new DeviceCredential();
+ device.setDeviceId("device");
+ device.setDeviceSecret("secret");
+ device.setLastEntitlementSuccessAt(start);
+ device.setFleetUserLimit(17);
+ var store = mock(DeviceCredentialStore.class);
+ when(store.get()).thenReturn(Optional.of(device));
+ var client = mock(AccountLinkClient.class);
+ var cache = new EntitlementCache(store, client, new AccountLinkProperties(), clock);
+ assertThat(cache.current()).isEmpty();
+ assertThat(cache.fleetUserLimit()).isEqualTo(17);
+ when(clock.instant()).thenReturn(start.plus(Duration.ofDays(3)));
+ assertThat(cache.fleetUserLimit()).isNull();
+ cache.accept(
+ "device",
+ new InstanceEntitlement(
+ true, 0, 0, null, EntitlementState.OK, null, null, null, 100, 10, 0L, 23));
+ assertThat(cache.fleetUserLimit()).isEqualTo(23);
+ cache.accept(
+ "device", new InstanceEntitlement(false, 0, 0, null, EntitlementState.REVOKED));
+ assertThat(cache.fleetUserLimit()).isNull();
+ }
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageSyncServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageSyncServiceTest.java
index 374008db71..c13ce3fceb 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageSyncServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/accountlink/UsageSyncServiceTest.java
@@ -34,11 +34,23 @@ class UsageSyncServiceTest {
@Mock private ApplicationEventPublisher events;
+ @Mock
+ private org.springframework.beans.factory.ObjectProvider<
+ stirling.software.proprietary.security.service.UserService>
+ users;
+
+ @Mock private stirling.software.proprietary.security.service.UserService localUsers;
+ @Mock private stirling.software.proprietary.service.UserLicenseSettingsService licenseSettings;
+ private final AccountLinkProperties properties = new AccountLinkProperties();
+
private UsageSyncService service;
private final LocalDateTime period = LocalDateTime.of(2026, 6, 1, 0, 0);
@BeforeEach
void setUp() {
+ properties.getMetering().setEnabled(true);
+ org.mockito.Mockito.lenient().when(users.getIfAvailable()).thenReturn(localUsers);
+ org.mockito.Mockito.lenient().when(localUsers.getTotalUsersCount()).thenReturn(7L);
service =
new UsageSyncService(
counters,
@@ -46,8 +58,10 @@ class UsageSyncServiceTest {
credentialStore,
client,
entitlementCache,
- new AccountLinkProperties(),
- events);
+ properties,
+ events,
+ users,
+ licenseSettings);
}
@Test
@@ -62,7 +76,9 @@ class UsageSyncServiceTest {
client,
entitlementCache,
props,
- events);
+ events,
+ users,
+ licenseSettings);
ScheduledTaskRegistrar registrar = new ScheduledTaskRegistrar();
svc.configureTasks(registrar);
@@ -99,21 +115,33 @@ class UsageSyncServiceTest {
}
@Test
- void nothingPendingStillForcesEntitlementRefresh() {
+ void nothingPendingStillReportsSeatsAndRefreshesEntitlement() {
when(credentialStore.get()).thenReturn(Optional.of(credential()));
when(counters.findPeriodsWithUnsyncedUsage()).thenReturn(List.of());
+ var fresh = entitled();
+ when(client.reportUsage("dev-1", "sec-1", 0, null, 0, 0, 0, 7)).thenReturn(fresh);
+ service.syncNow();
+ verify(entitlementCache).accept("dev-1", fresh);
+ verify(events).publishEvent(any(EntitlementRefreshedEvent.class));
+ verifyNoInteractions(syncState);
+ }
+ @Test
+ void meteringDisabledStillReportsSeats() {
+ properties.getMetering().setEnabled(false);
+ when(credentialStore.get()).thenReturn(Optional.of(credential()));
service.syncNow();
+ verify(client).reportUsage("dev-1", "sec-1", 0, null, 0, 0, 0, 7);
+ verifyNoInteractions(counters);
+ }
- // No usage to report, so nothing is sent and no markers advance — but the sync still forces
- // an entitlement refresh so an out-of-band plan change (e.g. a just-completed subscription)
- // surfaces on the gate immediately instead of waiting out the entitlement-cache TTL.
- verifyNoInteractions(client);
- verify(syncState, never()).save(any());
- verify(entitlementCache, never()).accept(any(), any());
- verify(entitlementCache).invalidate();
- verify(entitlementCache).current();
- verify(events).publishEvent(any(EntitlementRefreshedEvent.class));
+ @Test
+ void installedPaidLicenseDoesNotConsumeTeamSeats() {
+ properties.getMetering().setEnabled(false);
+ when(credentialStore.get()).thenReturn(Optional.of(credential()));
+ when(licenseSettings.hasLicenseKeyPaidTier()).thenReturn(true);
+ service.syncNow();
+ verify(client).reportUsage("dev-1", "sec-1", 0, null, 0, 0, 0, 0);
}
@Test
@@ -128,14 +156,29 @@ class UsageSyncServiceTest {
when(syncState.findById(AccountLinkSyncState.SINGLETON_ID)).thenReturn(Optional.of(state));
InstanceEntitlement fresh = entitled();
when(client.reportUsage(
- eq("dev-1"), eq("sec-1"), eq(6L), eq(period), eq(12L), eq(4L), eq(0L)))
+ eq("dev-1"),
+ eq("sec-1"),
+ eq(6L),
+ eq(period),
+ eq(12L),
+ eq(4L),
+ eq(0L),
+ eq(7)))
.thenReturn(fresh);
service.syncNow();
// Seq advanced from 5 → 6 and the report carried the per-category cumulative.
verify(client)
- .reportUsage(eq("dev-1"), eq("sec-1"), eq(6L), eq(period), eq(12L), eq(4L), eq(0L));
+ .reportUsage(
+ eq("dev-1"),
+ eq("sec-1"),
+ eq(6L),
+ eq(period),
+ eq(12L),
+ eq(4L),
+ eq(0L),
+ eq(7));
// Only categories with usage are marked; AUTOMATION (0) is skipped.
verify(counters).markSynced(period, "API", 12L);
verify(counters).markSynced(period, "AI", 4L);
@@ -154,7 +197,8 @@ class UsageSyncServiceTest {
when(counters.findPeriodsWithUnsyncedUsage()).thenReturn(List.of(period));
when(counters.findByPeriodStart(period)).thenReturn(List.of(counter(period, "API", 12L)));
when(syncState.findById(AccountLinkSyncState.SINGLETON_ID)).thenReturn(Optional.of(state));
- when(client.reportUsage(any(), any(), anyLong(), any(), anyLong(), anyLong(), anyLong()))
+ when(client.reportUsage(
+ any(), any(), anyLong(), any(), anyLong(), anyLong(), anyLong(), eq(7)))
.thenReturn(null);
service.syncNow();
@@ -168,19 +212,25 @@ class UsageSyncServiceTest {
}
@Test
- void revokedAbortsWithoutMarkingOrAdoptingEntitlement() {
+ void revokedAbortsAndBlocksImmediately() {
AccountLinkSyncState state = new AccountLinkSyncState();
state.setId(AccountLinkSyncState.SINGLETON_ID);
when(credentialStore.get()).thenReturn(Optional.of(credential()));
when(counters.findPeriodsWithUnsyncedUsage()).thenReturn(List.of(period));
when(counters.findByPeriodStart(period)).thenReturn(List.of(counter(period, "API", 12L)));
when(syncState.findById(AccountLinkSyncState.SINGLETON_ID)).thenReturn(Optional.of(state));
- when(client.reportUsage(any(), any(), anyLong(), any(), anyLong(), anyLong(), anyLong()))
+ when(client.reportUsage(
+ any(), any(), anyLong(), any(), anyLong(), anyLong(), anyLong(), eq(7)))
.thenThrow(new AccountLinkClient.RevokedException(403));
service.syncNow();
verify(counters, never()).markSynced(any(), any(), anyLong());
- verify(entitlementCache, never()).accept(any(), any());
+ verify(entitlementCache)
+ .accept(
+ eq("dev-1"),
+ org.mockito.ArgumentMatchers.argThat(
+ value -> value.state() == EntitlementState.REVOKED));
+ verify(events).publishEvent(any(EntitlementRefreshedEvent.class));
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceMoreTest.java
index 9a0ffd94d8..13156dfe01 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceMoreTest.java
@@ -97,6 +97,7 @@ class UserLicenseSettingsServiceMoreTest {
private void cacheReturns(InstanceEntitlement entitlement) {
EntitlementCache cache = org.mockito.Mockito.mock(EntitlementCache.class);
when(cache.current()).thenReturn(Optional.ofNullable(entitlement));
+ when(cache.fleetUserLimit()).thenReturn(null);
when(cache.linkedDeviceId()).thenReturn("device-1");
when(entitlementCacheProvider.getIfAvailable()).thenReturn(cache);
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceTest.java
index 2a778c845c..4aa84a2a06 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/service/UserLicenseSettingsServiceTest.java
@@ -83,6 +83,7 @@ class UserLicenseSettingsServiceTest {
void offlineExpirySuspendsTeamAllowanceWithoutDestroyingItAndReconnectRestoresIt() {
EntitlementCache cache = org.mockito.Mockito.mock(EntitlementCache.class);
when(entitlementCacheProvider.getIfAvailable()).thenReturn(cache);
+ when(cache.fleetUserLimit()).thenReturn(null);
when(cache.linkedDeviceId()).thenReturn("device");
mockSettings.setLinkedTeamDeviceId("device");
mockSettings.setLinkedTeamUsers(300);
@@ -542,4 +543,67 @@ class UserLicenseSettingsServiceTest {
assertEquals(false, result, "SAML should be blocked when LicenseKeyChecker is unavailable");
}
+
+ @Test
+ void fleetAllowanceSurvivesOfflineRestartExpiresAndRecovers() {
+ EntitlementCache cache = org.mockito.Mockito.mock(EntitlementCache.class);
+ when(entitlementCacheProvider.getIfAvailable()).thenReturn(cache);
+ when(cache.linkedDeviceId()).thenReturn("device");
+ mockSettings.setLinkedTeamDeviceId("device");
+ mockSettings.setLinkedTeamUsers(300);
+ when(cache.fleetUserLimit()).thenReturn(17);
+ when(cache.current()).thenReturn(Optional.empty());
+ assertEquals(17, service.calculateMaxAllowedUsers());
+ when(cache.isGraceExpired()).thenReturn(true);
+ assertEquals(80, service.calculateMaxAllowedUsers());
+ assertEquals(17, cache.fleetUserLimit());
+ when(cache.isGraceExpired()).thenReturn(false);
+ when(cache.current())
+ .thenReturn(
+ Optional.of(
+ new stirling.software.proprietary.accountlink.InstanceEntitlement(
+ true,
+ 0,
+ 0,
+ null,
+ stirling.software.proprietary.accountlink.EntitlementState
+ .OK,
+ null,
+ null,
+ null,
+ 300,
+ 10,
+ 23)));
+ when(cache.fleetUserLimit()).thenReturn(23);
+ assertEquals(23, service.calculateMaxAllowedUsers());
+ assertEquals(300, mockSettings.getLinkedTeamUsers());
+ }
+
+ @Test
+ void revokedOrReplacedIdentityClearsFleetAllowance() {
+ EntitlementCache cache = org.mockito.Mockito.mock(EntitlementCache.class);
+ when(entitlementCacheProvider.getIfAvailable()).thenReturn(cache);
+ when(cache.linkedDeviceId()).thenReturn("device");
+ mockSettings.setLinkedTeamDeviceId("device");
+ mockSettings.setLinkedTeamUsers(300);
+ when(cache.fleetUserLimit()).thenReturn(17);
+ when(cache.current())
+ .thenReturn(
+ Optional.of(
+ new stirling.software.proprietary.accountlink.InstanceEntitlement(
+ false,
+ 0,
+ 0,
+ null,
+ stirling.software.proprietary.accountlink.EntitlementState
+ .REVOKED)));
+ when(cache.fleetUserLimit()).thenReturn(null);
+ assertEquals(80, service.calculateMaxAllowedUsers());
+
+ when(cache.fleetUserLimit()).thenReturn(17);
+ when(cache.linkedDeviceId()).thenReturn("other-device");
+ when(cache.current()).thenReturn(Optional.empty());
+ when(cache.fleetUserLimit()).thenReturn(null);
+ assertEquals(80, service.calculateMaxAllowedUsers());
+ }
}
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
index eeb39f107b..8f51ccb169 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/AccountLinkController.java
@@ -47,7 +47,9 @@ public class AccountLinkController {
String name,
String createdAt,
String lastSeenAt,
- boolean revoked) {}
+ boolean revoked,
+ Integer seatCount,
+ String seatsReportedAt) {}
@GetMapping("/instances")
@PreAuthorize("isAuthenticated()")
@@ -70,7 +72,11 @@ public class AccountLinkController {
i.getLastSeenAt() != null
? i.getLastSeenAt().toString()
: null,
- i.getRevokedAt() != null))
+ i.getRevokedAt() != null,
+ i.getSeatCount(),
+ i.getSeatsReportedAt() == null
+ ? null
+ : i.getSeatsReportedAt().toString()))
.toList();
return ResponseEntity.ok(rows);
}
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/FleetSeatService.java b/app/saas/src/main/java/stirling/software/saas/accountlink/FleetSeatService.java
new file mode 100644
index 0000000000..2e65eafb7a
--- /dev/null
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/FleetSeatService.java
@@ -0,0 +1,84 @@
+package stirling.software.saas.accountlink;
+
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+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 stirling.software.saas.repository.SaasTeamExtensionsRepository;
+
+/** Fleet capacity uses each active deployment's last report, including offline deployments. */
+@Service
+@Profile("saas")
+@RequiredArgsConstructor
+public class FleetSeatService {
+ private final LinkedInstanceRepository instances;
+ private final SaasTeamExtensionsRepository teams;
+
+ /**
+ * Reports are scoped to the authenticated device; unlinked devices cannot restore their count.
+ */
+ @Transactional
+ public void report(Long teamId, Long instanceId, int seats) {
+ if (seats < 0) throw new IllegalArgumentException("Seat count must be non-negative");
+ if (instances.reportSeats(teamId, instanceId, seats, OffsetDateTime.now(ZoneOffset.UTC))
+ != 1) throw new IllegalStateException("Linked instance is no longer active");
+ }
+
+ /** For an authenticated active deployment, excludes the required cloud owner from usage. */
+ @Transactional(readOnly = true)
+ public Integer allowance(Long teamId, Long instanceId) {
+ return teams.findByTeamId(teamId)
+ .map(
+ team -> {
+ long others = instances.otherDeploymentSeats(teamId, instanceId);
+ return (int)
+ Math.max(
+ 0L,
+ (long) team.getMaxSeats()
+ - Math.max(0, team.getSeatsUsed() - 1)
+ - others);
+ })
+ .orElse(null);
+ }
+
+ /** Seat sources for the owning team's billing view; null counts have never been reported. */
+ public record DeploymentSeats(
+ String deviceId, String name, Integer users, OffsetDateTime reportedAt) {}
+
+ /** The single required cloud owner is exempt only while the team has an active deployment. */
+ public record Breakdown(
+ int cloudUsers, int excludedOwners, List<DeploymentSeats> deployments) {}
+
+ /** Returns the team's active seat sources, or null when its capacity record is unavailable. */
+ @Transactional(readOnly = true)
+ public Breakdown breakdown(Long teamId) {
+ var deployments =
+ instances.findByTeamIdOrderByCreatedAtDesc(teamId).stream()
+ .filter(instance -> instance.getRevokedAt() == null)
+ .map(
+ instance ->
+ new DeploymentSeats(
+ instance.getDeviceId(),
+ instance.getName(),
+ instance.getSeatCount(),
+ instance.getSeatsReportedAt()))
+ .toList();
+ return teams.findByTeamId(teamId)
+ .map(
+ team -> {
+ int excluded =
+ deployments.isEmpty() ? 0 : Math.min(1, team.getSeatsUsed());
+ return new Breakdown(
+ Math.max(0, team.getSeatsUsed() - excluded),
+ excluded,
+ deployments);
+ })
+ .orElse(null);
+ }
+}
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.java
index 32915a4821..50a86814e7 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
@@ -64,6 +64,7 @@ public class InstanceController {
private final InstanceUsageIngestService usageIngestService;
private final LinkedInstanceRepository linkedInstanceRepository;
private final SaasTeamExtensionsRepository teamExtensionsRepository;
+ private final FleetSeatService fleetSeats;
public InstanceController(
EntitlementService entitlementService,
@@ -73,8 +74,10 @@ public class InstanceController {
InstanceUsageIngestService usageIngestService,
LinkedInstanceRepository linkedInstanceRepository,
SaasTeamExtensionsRepository teamExtensionsRepository,
- PrepaidBundleService prepaidBundleService) {
+ PrepaidBundleService prepaidBundleService,
+ FleetSeatService fleetSeats) {
this.prepaidBundleService = prepaidBundleService;
+ this.fleetSeats = fleetSeats;
this.entitlementService = entitlementService;
this.billingService = billingService;
this.accountLinkService = accountLinkService;
@@ -109,7 +112,8 @@ public class InstanceController {
LocalDateTime periodStart,
LocalDateTime periodEnd,
int automationStepLimit,
- long prepaidRemainingUnits) {}
+ long prepaidRemainingUnits,
+ Integer fleetUserLimit) {}
@GetMapping("/whoami")
@PreAuthorize("hasRole('LINKED_INSTANCE')")
@@ -148,12 +152,20 @@ public class InstanceController {
// it must reflect a just-changed subscription/cap at once (the flip is a DB-function write
// with no Java event to invalidate on).
entitlementService.invalidate(token.getTeamId());
- return ResponseEntity.ok(buildEntitlement(token.getTeamId()));
+ return ResponseEntity.ok(buildEntitlement(token.getTeamId(), token.getInstanceId()));
}
/** Body for {@code POST /sync}: the instance's cumulative units per category this period. */
public record UsageSyncRequest(
- long syncSeq, LocalDateTime periodStart, CategoryUnits cumulativeUnits) {
+ long syncSeq,
+ LocalDateTime periodStart,
+ CategoryUnits cumulativeUnits,
+ Integer seatCount) {
+ public UsageSyncRequest(
+ long syncSeq, LocalDateTime periodStart, CategoryUnits cumulativeUnits) {
+ this(syncSeq, periodStart, cumulativeUnits, null);
+ }
+
public record CategoryUnits(long api, long ai, long automation) {}
}
@@ -171,50 +183,58 @@ public class InstanceController {
if (!(auth instanceof LinkedInstanceAuthenticationToken token)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
- if (req == null || req.periodStart() == null || req.cumulativeUnits() == null) {
+ if (req == null
+ || (req.seatCount() != null && req.seatCount() < 0)
+ || (req.periodStart() == null) != (req.cumulativeUnits() == null)
+ || (req.periodStart() == null && req.seatCount() == null)) {
return ResponseEntity.badRequest().build();
}
Long teamId = token.getTeamId();
- // periodStart is the dedup/regression partition key, so bound a fabricated value to the
- // snapshot window (current or immediately-prior period, never future).
- EntitlementSnapshot snap = entitlementService.getSnapshot(teamId);
- LocalDateTime reported = req.periodStart();
- if (!reported.isBefore(snap.periodEnd())
- || reported.isBefore(snap.periodStart().minusMonths(1))) {
- log.warn(
- "Instance sync for team {} reported implausible periodStart {} (authoritative"
- + " {}..{}); rejecting.",
+ if (req.periodStart() != null) {
+ // periodStart is the dedup/regression partition key, so bound a fabricated value to the
+ // snapshot window (current or immediately-prior period, never future).
+ EntitlementSnapshot snap = entitlementService.getSnapshot(teamId);
+ LocalDateTime reported = req.periodStart();
+ if (!reported.isBefore(snap.periodEnd())
+ || reported.isBefore(snap.periodStart().minusMonths(1))) {
+ log.warn(
+ "Instance sync for team {} reported implausible periodStart {} (authoritative"
+ + " {}..{}); rejecting.",
+ teamId,
+ reported,
+ snap.periodStart(),
+ snap.periodEnd());
+ return ResponseEntity.badRequest().build();
+ }
+ // Attribute the charge to the admin who linked the instance (the device credential
+ // carries
+ // no user). Null is tolerated by the ingest service (it skips + retries next sync).
+ Long actorUserId =
+ linkedInstanceRepository
+ .findById(token.getInstanceId())
+ .map(LinkedInstance::getCreatedByUserId)
+ .orElse(null);
+ UsageSyncRequest.CategoryUnits c = req.cumulativeUnits();
+ usageIngestService.ingest(
teamId,
- reported,
- snap.periodStart(),
- snap.periodEnd());
- return ResponseEntity.badRequest().build();
+ actorUserId,
+ req.syncSeq(),
+ req.periodStart(),
+ Map.of(
+ BillingCategory.API, c.api(),
+ BillingCategory.AI, c.ai(),
+ BillingCategory.AUTOMATION, c.automation()));
}
- // Attribute the charge to the admin who linked the instance (the device credential carries
- // no user). Null is tolerated by the ingest service (it skips + retries next sync).
- Long actorUserId =
- linkedInstanceRepository
- .findById(token.getInstanceId())
- .map(LinkedInstance::getCreatedByUserId)
- .orElse(null);
- UsageSyncRequest.CategoryUnits c = req.cumulativeUnits();
- usageIngestService.ingest(
- teamId,
- actorUserId,
- req.syncSeq(),
- req.periodStart(),
- Map.of(
- BillingCategory.API, c.api(),
- BillingCategory.AI, c.ai(),
- BillingCategory.AUTOMATION, c.automation()));
+ if (req.seatCount() != null)
+ fleetSeats.report(teamId, token.getInstanceId(), req.seatCount());
// Drop the cache so the buildEntitlement below (and the portal's next read) reflect the
// just-charged delta + moved free-grant balance now, not after the TTL.
entitlementService.invalidate(teamId);
- return ResponseEntity.ok(buildEntitlement(teamId));
+ return ResponseEntity.ok(buildEntitlement(teamId, token.getInstanceId()));
}
/** The entitlement view shared by {@code GET /entitlement} and the {@code /sync} response. */
- private EntitlementResponse buildEntitlement(Long teamId) {
+ private EntitlementResponse buildEntitlement(Long teamId, Long instanceId) {
// Same composition the FE wallet uses: billing facts (subscription, free pool) from
// TeamBillingService, period spend/cap + state from the entitlement snapshot, plus the
// unit-calc policy + period the instance needs to meter locally.
@@ -236,7 +256,8 @@ public class InstanceController {
snap.periodStart(),
snap.periodEnd(),
policy.resolveStepLimit(JobSource.PIPELINE),
- prepaidBundleService.prepaidRemainingUnits(teamId));
+ prepaidBundleService.prepaidRemainingUnits(teamId),
+ fleetSeats.allowance(teamId, instanceId));
}
/**
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java
index e0e2f48986..3af131dba8 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstance.java
@@ -72,6 +72,12 @@ public class LinkedInstance {
@Column(name = "last_seen_at")
private LocalDateTime lastSeenAt;
+ @Column(name = "seat_count")
+ private Integer seatCount;
+
+ @Column(name = "seats_reported_at")
+ private java.time.OffsetDateTime seatsReportedAt;
+
/** NULL = active. Set on unlink/revoke; a revoked credential fails authentication. */
@Column(name = "revoked_at")
private LocalDateTime revokedAt;
diff --git a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java
index 384436976d..54a934938e 100644
--- a/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java
+++ b/app/saas/src/main/java/stirling/software/saas/accountlink/LinkedInstanceRepository.java
@@ -50,4 +50,19 @@ public interface LinkedInstanceRepository extends JpaRepository<LinkedInstance,
"UPDATE LinkedInstance li SET li.lastSeenAt = :now "
+ "WHERE li.instanceId = :instanceId AND li.revokedAt IS NULL")
int touchLastSeen(@Param("instanceId") Long instanceId, @Param("now") LocalDateTime now);
+
+ @Modifying
+ @Query(
+ "UPDATE LinkedInstance i SET i.seatCount = :seats, i.seatsReportedAt = :now "
+ + "WHERE i.instanceId = :instanceId AND i.teamId = :teamId AND i.revokedAt IS NULL")
+ int reportSeats(
+ @Param("teamId") Long teamId,
+ @Param("instanceId") Long instanceId,
+ @Param("seats") int seats,
+ @Param("now") java.time.OffsetDateTime now);
+
+ @Query(
+ "SELECT COALESCE(SUM(i.seatCount), 0) FROM LinkedInstance i "
+ + "WHERE i.teamId = :teamId AND i.instanceId <> :instanceId AND i.revokedAt IS NULL")
+ long otherDeploymentSeats(@Param("teamId") Long teamId, @Param("instanceId") Long instanceId);
}
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 27cca0fe97..23e7df301a 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
@@ -37,6 +37,7 @@ import stirling.software.proprietary.security.database.repository.UserRepository
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.proprietary.service.UserLicenseSettingsService;
+import stirling.software.saas.accountlink.FleetSeatService;
import stirling.software.saas.model.SaasTeamExtensions;
import stirling.software.saas.payg.api.WalletSnapshotResponse.ActivityRow;
import stirling.software.saas.payg.api.WalletSnapshotResponse.CategoryBreakdown;
@@ -114,6 +115,7 @@ public class PaygWalletController {
private final PrepaidBundleService prepaidBundleService;
private final UserTeamResolver userTeamResolver;
private final SaasTeamExtensionsRepository teamExtensionsRepository;
+ private final FleetSeatService fleetSeats;
public PaygWalletController(
EntitlementService entitlementService,
@@ -126,7 +128,9 @@ public class PaygWalletController {
UserRepository userRepository,
PrepaidBundleService prepaidBundleService,
UserTeamResolver userTeamResolver,
- SaasTeamExtensionsRepository teamExtensionsRepository) {
+ SaasTeamExtensionsRepository teamExtensionsRepository,
+ FleetSeatService fleetSeats) {
+ this.fleetSeats = fleetSeats;
this.entitlementService = Objects.requireNonNull(entitlementService, "entitlementService");
this.billingService = Objects.requireNonNull(billingService, "billingService");
this.memberRepo = Objects.requireNonNull(memberRepo, "memberRepo");
@@ -179,7 +183,7 @@ public class PaygWalletController {
String status = billing.subscribed() ? STATUS_SUBSCRIBED : STATUS_FREE;
WalletSnapshotResponse.ProcessorHolding processor =
new WalletSnapshotResponse.ProcessorHolding(billing.subscribed());
- WalletSnapshotResponse.TeamHolding team = teamHolding(teamId);
+ WalletSnapshotResponse.TeamHolding team = teamHolding(teamId, isLeader);
boolean noCap = billing.subscribed() && billing.capMoneyMinor() == null;
Integer capMajor =
@@ -271,14 +275,21 @@ public class PaygWalletController {
* The team's user-capacity holding. The cap is written from the Team subscription, so a team
* holds Team exactly when {@link SaasTeamExtensions#licensedUsers()} states one.
*/
- private WalletSnapshotResponse.TeamHolding teamHolding(Long teamId) {
- int usersInUse = Math.toIntExact(memberRepo.countByTeamId(teamId));
+ private WalletSnapshotResponse.TeamHolding teamHolding(Long teamId, boolean isLeader) {
+ Long fleetUsers = teamExtensionsRepository.fleetUsersInUse(teamId);
+ int usersInUse =
+ Math.toIntExact(fleetUsers == null ? memberRepo.countByTeamId(teamId) : fleetUsers);
Integer licensed =
teamExtensionsRepository
.findByTeamId(teamId)
.map(SaasTeamExtensions::licensedUsers)
.orElse(null);
- return new WalletSnapshotResponse.TeamHolding(licensed != null, licensed, usersInUse);
+ return new WalletSnapshotResponse.TeamHolding(
+ licensed != null,
+ licensed,
+ usersInUse,
+ fleetUsers != null,
+ isLeader ? fleetSeats.breakdown(teamId) : null);
}
/** Per-category size-scaled units + input-file counts for the same window. */
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 5a5aec97c8..0acf08d624 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
@@ -155,9 +155,23 @@ public record WalletSnapshotResponse(
* rather than meaning capacity is unknown.
* @param licensedUsers how many users the holding covers; {@code null} when the team has no
* user limit.
- * @param usersInUse team members occupying capacity right now.
+ * @param usersInUse counted cloud members plus deployment reports; linked teams exclude one
+ * required cloud owner.
*/
- public record TeamHolding(boolean held, Integer licensedUsers, int usersInUse) {}
+ public record TeamHolding(
+ boolean held,
+ Integer licensedUsers,
+ int usersInUse,
+ boolean fleet,
+ stirling.software.saas.accountlink.FleetSeatService.Breakdown breakdown) {
+ public TeamHolding(boolean held, Integer licensedUsers, int usersInUse, boolean fleet) {
+ this(held, licensedUsers, usersInUse, fleet, null);
+ }
+
+ public TeamHolding(boolean held, Integer licensedUsers, int usersInUse) {
+ this(held, licensedUsers, usersInUse, false);
+ }
+ }
/**
* The Processor holding: metered document automation beyond the free grant.
diff --git a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java
index f2ed734c9d..f90b2e52e6 100644
--- a/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java
+++ b/app/saas/src/main/java/stirling/software/saas/repository/SaasTeamExtensionsRepository.java
@@ -11,6 +11,13 @@ import stirling.software.saas.model.SaasTeamExtensions;
public interface SaasTeamExtensionsRepository extends JpaRepository<SaasTeamExtensions, Long> {
+ // A linked team needs one cloud owner even when everyone works on its self-hosted deployments.
+ String CLOUD_SEATS =
+ "GREATEST(e.seats_used - CASE WHEN EXISTS (SELECT 1 FROM stirling_pdf.linked_instance owner_link WHERE owner_link.team_id = e.team_id AND owner_link.revoked_at IS NULL) THEN 1 ELSE 0 END, 0)";
+ String FLEET_SEATS =
+ CLOUD_SEATS
+ + " + (SELECT COALESCE(SUM(i.seat_count), 0) FROM stirling_pdf.linked_instance i WHERE i.team_id = e.team_id AND i.revoked_at IS NULL)";
+
Optional<SaasTeamExtensions> findByTeamId(Long teamId);
/**
@@ -18,11 +25,30 @@ public interface SaasTeamExtensionsRepository extends JpaRepository<SaasTeamExte
*/
@Modifying
@Query(
- "UPDATE SaasTeamExtensions e SET e.seatsUsed = e.seatsUsed + 1 "
- + "WHERE e.teamId = :teamId AND "
- + "e.seatsUsed < e.maxSeats")
+ value =
+ "UPDATE stirling_pdf.saas_team_extensions e SET seats_used = seats_used + 1 "
+ + "WHERE team_id = :teamId AND "
+ + FLEET_SEATS
+ + " < max_seats",
+ nativeQuery = true)
int incrementSeatsUsed(@Param("teamId") Long teamId);
+ @Query(
+ value =
+ "SELECT "
+ + FLEET_SEATS
+ + " FROM stirling_pdf.saas_team_extensions e WHERE e.team_id=:teamId",
+ nativeQuery = true)
+ Long fleetUsersInUse(@Param("teamId") Long teamId);
+
+ @Query(
+ value =
+ "SELECT "
+ + FLEET_SEATS
+ + " < e.max_seats FROM stirling_pdf.saas_team_extensions e WHERE e.team_id=:teamId",
+ nativeQuery = true)
+ Boolean fleetHasAvailableSeats(@Param("teamId") Long teamId);
+
/** Atomic seat decrement. Floor at 0. Returns 1 on a real decrement, 0 if already at 0. */
@Modifying
@Query(
diff --git a/app/saas/src/main/java/stirling/software/saas/service/SaasTeamExtensionService.java b/app/saas/src/main/java/stirling/software/saas/service/SaasTeamExtensionService.java
index 3003454e72..97a531769b 100644
--- a/app/saas/src/main/java/stirling/software/saas/service/SaasTeamExtensionService.java
+++ b/app/saas/src/main/java/stirling/software/saas/service/SaasTeamExtensionService.java
@@ -13,8 +13,8 @@ import stirling.software.saas.model.SaasTeamExtensions;
import stirling.software.saas.repository.SaasTeamExtensionsRepository;
/**
- * Read/write access to {@link SaasTeamExtensions}. Reads return safe defaults (non-personal team,
- * seat fields zeroed) when no row exists; writes create the row lazily.
+ * Missing rows use display defaults, but cannot admit users without a persisted capacity record.
+ * Writes create the row lazily.
*/
@Service
@Profile("saas")
@@ -77,22 +77,15 @@ public class SaasTeamExtensionService {
.orElse(null);
}
- /** Whether the team has unused seats. See {@link SaasTeamExtensions#hasAvailableSeats()}. */
+ /**
+ * Checks shared fleet capacity; a missing record blocks admission, as does the atomic claim.
+ */
public boolean hasAvailableSeats(Team team) {
- return repository
- .findByTeamId(team.getId())
- .map(SaasTeamExtensions::hasAvailableSeats)
- .orElse(true);
+ return Boolean.TRUE.equals(repository.fleetHasAvailableSeats(team.getId()));
}
- /**
- * Whether the team accepts new invitations. See {@link SaasTeamExtensions#canInviteMembers()}.
- */
public boolean canInviteMembers(Team team) {
- return repository
- .findByTeamId(team.getId())
- .map(SaasTeamExtensions::canInviteMembers)
- .orElse(true);
+ return !isPersonal(team) && hasAvailableSeats(team);
}
/** Atomic seat increment with personal-team cap enforcement. */
diff --git a/app/saas/src/test/java/stirling/software/saas/accountlink/FleetSeatServiceTest.java b/app/saas/src/test/java/stirling/software/saas/accountlink/FleetSeatServiceTest.java
new file mode 100644
index 0000000000..f3bdba2bc4
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/accountlink/FleetSeatServiceTest.java
@@ -0,0 +1,79 @@
+package stirling.software.saas.accountlink;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.Optional;
+
+import org.junit.jupiter.api.Test;
+
+import stirling.software.saas.model.SaasTeamExtensions;
+import stirling.software.saas.repository.SaasTeamExtensionsRepository;
+
+class FleetSeatServiceTest {
+ private final LinkedInstanceRepository instances = mock(LinkedInstanceRepository.class);
+ private final SaasTeamExtensionsRepository teams = mock(SaasTeamExtensionsRepository.class);
+ private final FleetSeatService service = new FleetSeatService(instances, teams);
+
+ @Test
+ void allowanceSubtractsCloudAndOtherDeploymentsButNeverBecomesNegative() {
+ var team = new SaasTeamExtensions();
+ team.setMaxSeats(100);
+ team.setSeatsUsed(8);
+ when(teams.findByTeamId(42L)).thenReturn(Optional.of(team));
+ when(instances.otherDeploymentSeats(42L, 1L)).thenReturn(75L, 120L);
+ assertThat(service.allowance(42L, 1L)).isEqualTo(18);
+ assertThat(service.allowance(42L, 1L)).isZero();
+ }
+
+ @Test
+ void requiredCloudOwnerDoesNotConsumeTheLinkedServersFreeAllowance() {
+ var team = new SaasTeamExtensions();
+ team.setMaxSeats(5);
+ team.setSeatsUsed(1);
+ when(teams.findByTeamId(42L)).thenReturn(Optional.of(team));
+ assertThat(service.allowance(42L, 1L)).isEqualTo(5);
+ team.setSeatsUsed(0);
+ assertThat(service.allowance(42L, 1L)).isEqualTo(5);
+ }
+
+ @Test
+ void breakdownExemptsOneOwnerAndRetainsUnknownDeploymentCounts() {
+ var team = new SaasTeamExtensions();
+ team.setSeatsUsed(3);
+ when(teams.findByTeamId(42L)).thenReturn(Optional.of(team));
+ var unreported = new LinkedInstance();
+ unreported.setDeviceId("first");
+ unreported.setName("Office");
+ var reported = new LinkedInstance();
+ reported.setSeatCount(7);
+ reported.setDeviceId("second");
+ var revoked = new LinkedInstance();
+ revoked.setRevokedAt(LocalDateTime.now());
+ revoked.setSeatCount(99);
+ when(instances.findByTeamIdOrderByCreatedAtDesc(42L))
+ .thenReturn(List.of(unreported, reported, revoked));
+ var breakdown = service.breakdown(42L);
+ assertThat(breakdown.cloudUsers()).isEqualTo(2);
+ assertThat(breakdown.excludedOwners()).isEqualTo(1);
+ assertThat(breakdown.deployments()).hasSize(2);
+ assertThat(breakdown.deployments().getFirst().users()).isNull();
+ when(instances.findByTeamIdOrderByCreatedAtDesc(42L)).thenReturn(List.of(revoked));
+ assertThat(service.breakdown(42L).cloudUsers()).isEqualTo(3);
+ assertThat(service.breakdown(42L).excludedOwners()).isZero();
+ }
+
+ @Test
+ void reportStoresZeroAndCannotRestoreRevokedDeployments() {
+ when(instances.reportSeats(eq(42L), eq(1L), eq(0), any())).thenReturn(1, 0);
+ service.report(42L, 1L, 0);
+ assertThatThrownBy(() -> service.report(42L, 1L, 0))
+ .isInstanceOf(IllegalStateException.class);
+ assertThatThrownBy(() -> service.report(42L, 1L, -1))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+}
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.java
index 65220c9aee..bc351c23c4 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
@@ -61,6 +61,7 @@ class InstanceControllerTest {
@Mock private InstanceUsageIngestService usageIngestService;
@Mock private LinkedInstanceRepository linkedInstanceRepository;
@Mock private SaasTeamExtensionsRepository teamExtensionsRepository;
+ @Mock private FleetSeatService fleetSeats;
private InstanceController controller() {
return new InstanceController(
@@ -71,7 +72,8 @@ class InstanceControllerTest {
usageIngestService,
linkedInstanceRepository,
teamExtensionsRepository,
- Mockito.mock(PrepaidBundleService.class));
+ Mockito.mock(PrepaidBundleService.class),
+ fleetSeats);
}
private static PricingPolicy policy() {
@@ -341,4 +343,43 @@ class InstanceControllerTest {
start.plusMonths(1),
false);
}
+
+ @Test
+ void seatOnlySyncUsesAuthenticatedDeploymentWithoutBillingUsage() {
+ when(billingService.forTeam(42L)).thenReturn(freeBilling(500L));
+ when(entitlementService.getSnapshot(42L))
+ .thenReturn(snapshot(EntitlementState.FULL, 0L, null));
+ when(pricingPolicyService.getEffectivePolicy(42L)).thenReturn(policy());
+ when(fleetSeats.allowance(42L, 1L)).thenReturn(17);
+ var response =
+ controller()
+ .sync(
+ new LinkedInstanceAuthenticationToken(1L, 42L),
+ new InstanceController.UsageSyncRequest(0, null, null, 7));
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ assertThat(response.getBody().fleetUserLimit()).isEqualTo(17);
+ verify(fleetSeats).report(42L, 1L, 7);
+ verifyNoInteractions(usageIngestService);
+ }
+
+ @Test
+ void negativeSeatsAndPartialUsageAreRejected() {
+ var token = new LinkedInstanceAuthenticationToken(1L, 42L);
+ assertThat(
+ controller()
+ .sync(
+ token,
+ new InstanceController.UsageSyncRequest(0, null, null, -1))
+ .getStatusCode())
+ .isEqualTo(HttpStatus.BAD_REQUEST);
+ assertThat(
+ controller()
+ .sync(
+ token,
+ new InstanceController.UsageSyncRequest(
+ 0, LocalDateTime.now(), null, 7))
+ .getStatusCode())
+ .isEqualTo(HttpStatus.BAD_REQUEST);
+ verifyNoInteractions(fleetSeats, usageIngestService);
+ }
}
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 f6fb15b0e9..13d240e51f 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
@@ -36,6 +36,7 @@ import stirling.software.proprietary.security.database.repository.UserRepository
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.repository.TeamMembershipRepository;
import stirling.software.proprietary.service.UserLicenseSettingsService;
+import stirling.software.saas.accountlink.FleetSeatService;
import stirling.software.saas.model.SaasTeamExtensions;
import stirling.software.saas.payg.api.PaygWalletController.UpdateCapRequest;
import stirling.software.saas.payg.api.WalletSnapshotResponse.MemberRow;
@@ -76,6 +77,7 @@ class PaygWalletControllerTest {
@Mock private UserRepository userRepository;
@Mock private PrepaidBundleService prepaidBundleService;
@Mock private SaasTeamExtensionsRepository teamExtensionsRepository;
+ @Mock private FleetSeatService fleetSeats;
private PaygWalletController controller;
@@ -93,7 +95,8 @@ class PaygWalletControllerTest {
userRepository,
prepaidBundleService,
new UserTeamResolver(memberRepo),
- teamExtensionsRepository);
+ teamExtensionsRepository,
+ fleetSeats);
}
/**
@@ -165,7 +168,7 @@ class PaygWalletControllerTest {
user.setTeam(team);
when(memberRepo.findByTeamIdAndUserId(team.getId(), 60L))
.thenReturn(Optional.of(membership(team, user, TeamRole.MEMBER)));
- when(memberRepo.countByTeamId(60L)).thenReturn(3L);
+ when(teamExtensionsRepository.fleetUsersInUse(60L)).thenReturn(3L);
when(billingService.forTeam(60L)).thenReturn(freeBilling(500L));
when(entitlementService.getSnapshot(60L)).thenReturn(snapshot(0L, 500L));
stubEmptyLedgerReads(60L);
@@ -190,7 +193,7 @@ class PaygWalletControllerTest {
user.setTeam(team);
when(memberRepo.findByTeamIdAndUserId(team.getId(), 62L))
.thenReturn(Optional.of(membership(team, user, TeamRole.MEMBER)));
- when(memberRepo.countByTeamId(62L)).thenReturn(40L);
+ when(teamExtensionsRepository.fleetUsersInUse(62L)).thenReturn(40L);
SaasTeamExtensions ext = new SaasTeamExtensions();
ext.setMaxSeats(100);
when(teamExtensionsRepository.findByTeamId(62L)).thenReturn(Optional.of(ext));
@@ -220,7 +223,7 @@ class PaygWalletControllerTest {
user.setTeam(team);
when(memberRepo.findByTeamIdAndUserId(team.getId(), 63L))
.thenReturn(Optional.of(membership(team, user, TeamRole.MEMBER)));
- when(memberRepo.countByTeamId(63L)).thenReturn(2L);
+ when(teamExtensionsRepository.fleetUsersInUse(63L)).thenReturn(2L);
SaasTeamExtensions ext = new SaasTeamExtensions();
ext.setMaxSeats(UserLicenseSettingsService.DEFAULT_USER_LIMIT);
when(teamExtensionsRepository.findByTeamId(63L)).thenReturn(Optional.of(ext));
@@ -248,7 +251,7 @@ class PaygWalletControllerTest {
user.setTeam(team);
when(memberRepo.findByTeamIdAndUserId(team.getId(), 61L))
.thenReturn(Optional.of(membership(team, user, TeamRole.MEMBER)));
- when(memberRepo.countByTeamId(61L)).thenReturn(8L);
+ when(teamExtensionsRepository.fleetUsersInUse(61L)).thenReturn(8L);
when(billingService.forTeam(61L))
.thenReturn(subscribedBilling("sub_decoupled", 2500L, 1250L));
when(entitlementService.getSnapshot(61L)).thenReturn(snapshot(100L, 1250L));
diff --git a/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java b/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java
new file mode 100644
index 0000000000..27c775bf74
--- /dev/null
+++ b/app/saas/src/test/java/stirling/software/saas/repository/FleetSeatQueriesTest.java
@@ -0,0 +1,70 @@
+package stirling.software.saas.repository;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.data.jpa.repository.Query;
+
+class FleetSeatQueriesTest {
+ @Test
+ void ownerExemptionAgreesAcrossDisplayAvailabilityAndAtomicSeatClaims() throws Exception {
+ try (var db = DriverManager.getConnection("jdbc:h2:mem:fleetSeats;MODE=PostgreSQL")) {
+ try (var sql = db.createStatement()) {
+ sql.execute("CREATE SCHEMA stirling_pdf");
+ sql.execute(
+ "CREATE TABLE stirling_pdf.saas_team_extensions (team_id BIGINT PRIMARY KEY, seats_used INT, max_seats INT)");
+ sql.execute(
+ "CREATE TABLE stirling_pdf.linked_instance (team_id BIGINT, seat_count INT, revoked_at TIMESTAMP)");
+ sql.execute("INSERT INTO stirling_pdf.saas_team_extensions VALUES (1, 1, 5)");
+ assertThat(total(db)).isEqualTo(1);
+ sql.execute(
+ "INSERT INTO stirling_pdf.linked_instance VALUES (1, 4, NULL), (1, 0, NULL), (2, 99, NULL)");
+ assertThat(total(db)).isEqualTo(4);
+ assertThat(available(db)).isTrue();
+ assertThat(claim(db)).isEqualTo(1);
+ assertThat(total(db)).isEqualTo(5);
+ assertThat(available(db)).isFalse();
+ assertThat(claim(db)).isZero();
+ sql.execute(
+ "UPDATE stirling_pdf.linked_instance SET revoked_at=CURRENT_TIMESTAMP WHERE team_id=1");
+ assertThat(total(db)).isEqualTo(2);
+ sql.execute("UPDATE stirling_pdf.saas_team_extensions SET seats_used=0");
+ sql.execute("INSERT INTO stirling_pdf.linked_instance VALUES (1, NULL, NULL)");
+ assertThat(total(db)).isZero();
+ }
+ }
+ }
+
+ private static String query(String method) throws Exception {
+ return SaasTeamExtensionsRepository.class
+ .getMethod(method, Long.class)
+ .getAnnotation(Query.class)
+ .value()
+ .replace(":teamId", "1");
+ }
+
+ private static long total(Connection db) throws Exception {
+ try (var statement = db.createStatement();
+ var rows = statement.executeQuery(query("fleetUsersInUse"))) {
+ rows.next();
+ return rows.getLong(1);
+ }
+ }
+
+ private static boolean available(Connection db) throws Exception {
+ try (var statement = db.createStatement();
+ var rows = statement.executeQuery(query("fleetHasAvailableSeats"))) {
+ rows.next();
+ return rows.getBoolean(1);
+ }
+ }
+
+ private static int claim(Connection db) throws Exception {
+ try (var statement = db.createStatement()) {
+ return statement.executeUpdate(query("incrementSeatsUsed"));
+ }
+ }
+}
diff --git a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamExtensionServiceTest.java b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamExtensionServiceTest.java
index 8bb5bd7984..4ae5f20c4f 100644
--- a/app/saas/src/test/java/stirling/software/saas/service/SaasTeamExtensionServiceTest.java
+++ b/app/saas/src/test/java/stirling/software/saas/service/SaasTeamExtensionServiceTest.java
@@ -25,15 +25,6 @@ import stirling.software.proprietary.service.UserLicenseSettingsService;
import stirling.software.saas.model.SaasTeamExtensions;
import stirling.software.saas.repository.SaasTeamExtensionsRepository;
-/**
- * Unit tests for {@link SaasTeamExtensionService}.
- *
- * <p>The service is a thin read/write facade over {@link SaasTeamExtensionsRepository}. Reads
- * return safe defaults when no row exists (non-personal, STANDARD type, seatsUsed=0, maxSeats=the
- * free allowance, createdBy=null, hasAvailableSeats=true, canInviteMembers=true); writes create the
- * row lazily via {@code getOrCreate}. Pure delegation + Optional mapping, so everything is mocked
- * at the repository boundary.
- */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class SaasTeamExtensionServiceTest {
@@ -270,90 +261,35 @@ class SaasTeamExtensionServiceTest {
}
@Nested
- @DisplayName("hasAvailableSeats")
- class HasAvailableSeats {
-
- @Test
- @DisplayName("no row defaults to true (optimistic)")
- void noRow_true() {
- Team team = team();
- when(repository.findByTeamId(TEAM_ID)).thenReturn(Optional.empty());
-
- assertThat(service.hasAvailableSeats(team)).isTrue();
- }
-
- @Test
- @DisplayName("standard team cannot exceed purchased capacity")
- void standardTeam_overCap_false() {
- Team team = team();
- SaasTeamExtensions row = ext(team);
- row.setIsPersonal(false);
- row.setSeatsUsed(1000);
- row.setMaxSeats(1);
- when(repository.findByTeamId(TEAM_ID)).thenReturn(Optional.of(row));
-
- assertThat(service.hasAvailableSeats(team)).isFalse();
- }
-
- @Test
- @DisplayName("personal team with a free seat returns true")
- void personalTeam_underCap_true() {
- Team team = team();
- SaasTeamExtensions row = ext(team);
- row.setIsPersonal(true);
- row.setSeatsUsed(0);
- row.setMaxSeats(1);
- when(repository.findByTeamId(TEAM_ID)).thenReturn(Optional.of(row));
-
- assertThat(service.hasAvailableSeats(team)).isTrue();
- }
-
+ @DisplayName("fleet capacity")
+ class FleetCapacity {
@Test
- @DisplayName("personal team at its seat cap returns false (boundary)")
- void personalTeam_atCap_false() {
- Team team = team();
- SaasTeamExtensions row = ext(team);
- row.setIsPersonal(true);
- row.setSeatsUsed(1);
- row.setMaxSeats(1);
- when(repository.findByTeamId(TEAM_ID)).thenReturn(Optional.of(row));
-
- assertThat(service.hasAvailableSeats(team)).isFalse();
+ void unavailableSnapshot_blocksAdmissions() {
+ when(repository.fleetHasAvailableSeats(TEAM_ID)).thenReturn(null);
+ assertThat(service.hasAvailableSeats(team())).isFalse();
+ assertThat(service.canInviteMembers(team())).isFalse();
}
- }
-
- @Nested
- @DisplayName("canInviteMembers")
- class CanInviteMembers {
@Test
- @DisplayName("no row defaults to true")
- void noRow_true() {
- Team team = team();
- when(repository.findByTeamId(TEAM_ID)).thenReturn(Optional.empty());
-
- assertThat(service.canInviteMembers(team)).isTrue();
+ void cloudRoomDoesNotOverrideFleetExhaustion() {
+ when(repository.fleetHasAvailableSeats(TEAM_ID)).thenReturn(false);
+ assertThat(service.canInviteMembers(team())).isFalse();
}
@Test
- @DisplayName("standard team can invite")
- void standardTeam_true() {
- Team team = team();
- SaasTeamExtensions row = ext(team);
- row.setIsPersonal(false);
- when(repository.findByTeamId(TEAM_ID)).thenReturn(Optional.of(row));
-
- assertThat(service.canInviteMembers(team)).isTrue();
+ void fleetRoomAllowsStandardTeamInvitations() {
+ when(repository.fleetHasAvailableSeats(TEAM_ID)).thenReturn(true);
+ assertThat(service.hasAvailableSeats(team())).isTrue();
+ assertThat(service.canInviteMembers(team())).isTrue();
}
@Test
- @DisplayName("personal team can never invite")
- void personalTeam_false() {
+ void personalTeamStillRequiresConversion() {
Team team = team();
SaasTeamExtensions row = ext(team);
row.setIsPersonal(true);
when(repository.findByTeamId(TEAM_ID)).thenReturn(Optional.of(row));
-
+ when(repository.fleetHasAvailableSeats(TEAM_ID)).thenReturn(true);
assertThat(service.canInviteMembers(team)).isFalse();
}
}
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index e814dded7a..9b05e196da 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -7711,19 +7711,34 @@ low = "Running low"
[portal.billing.processor]
activate = "Switch on the Processor"
-factCapped = "{{pct}}% of {{cap}}"
factFree = "{{used}} of {{allowance}} used"
factNoCap = "no limit"
+freeRemaining = "Free credits remaining"
included = "Included in your license"
-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"
+noSpendLimit = "No spend limit"
+paidUsed = "Paid metered usage"
+percentUsed = "{{pct}}%"
raiseLimit = "Raise limit"
+remainingOf = "{{remaining}} of {{total}}"
rowName = "Processor"
+spendAgainstLimit = "{{spend}} of {{cap}} metered this cycle"
+
+[portal.billing.seats]
+awaitingSync = "Waiting for its daily sync; not yet included in the fleet total."
+breakdown = "Where users are counted"
+cloud = "Stirling Cloud"
+deployment = "Linked server"
+lastReported = "Reported {{date}}"
+live = "Live user count"
+notReported = "Not yet reported"
+ownerExcluded = "The required cloud team owner does not use a seat."
+thisServer = "This server"
[portal.billing.section]
cycle = "This cycle"
@@ -7801,6 +7816,7 @@ factNoLimit = "{{users}} users"
midFree = "The Team plan covers 100 users"
midFreeSelfHosted = "The free tier covers your first users"
midIncluded = "Included with your Team base"
+midLocalCapacity = "Capacity available to this server"
midPrice = "$99/mo per 100 users"
rowName = "Users"
@@ -11048,6 +11064,8 @@ removeError = "Couldn’t remove the connection. Try again."
renameError = "Couldn’t save the name. Try again."
retry = "Try again"
saveName = "Save name"
+seatsReported = "{{count}} Team seats · reported {{date}}. Offline deployments keep their seats until unlinked."
+seatsUnknown = "Waiting for this deployment to report its user count in the daily sync."
subtitle = "Manage the self-hosted servers connected to your team."
teamNote = "These instances share your team’s processing allowance."
title = "Connected instances"
diff --git a/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts b/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
index bb4e3cc000..26dbd836c8 100644
--- a/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/classification-heuristic-upload.spec.ts
@@ -75,21 +75,13 @@ test("a 10-file upload wave classifies every file into its group", async ({
].map((f) => path.join(FIXTURES, f)),
);
- // Group headers are collapsible buttons whose name carries the live member
- // count. Classification drains a few files per idle pass, and until a file's
- // verdict lands it is unclassified and counted under Other (see
- // fileSidebarGroupingLogic). Every count therefore climbs to a final value, so
- // the assertions must read the settled state, not a mid-drain snapshot.
const header = (name: string, count: number) =>
page.getByRole("button", { name: `${name} ${count}`, exact: true });
- // Other falls to its one terminal member (generic_notes.pdf) only after every
- // other file has classified out of it: the drain-complete signal to wait on.
+ // Unclassified files stay in Other until processing finishes; only generic notes remain.
await expect(header("Other", 1)).toBeVisible({ timeout: 150_000 });
- // Settled distribution. spanish_contrato.pdf is a Spanish lease agreement the
- // Spanish rules label as Legal, so nothing classifiable is stranded in Other -
- // only genuinely unlabellable generic prose belongs there.
+ // The Spanish lease is also classified as Legal.
await expect(header("Financial", 3)).toBeVisible();
await expect(header("HR", 3)).toBeVisible();
await expect(header("Legal", 3)).toBeVisible();
diff --git a/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts
index ff9e26c30a..3cb670e81b 100644
--- a/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts
@@ -500,13 +500,16 @@ test("a form apply reloads the new value and keeps the position", async ({
.first();
await expect(field).toBeVisible({ timeout: 20_000 });
await field.fill("updated value");
- await page.keyboard.press("Tab");
+ // Tab can start an asynchronous scroll to the next field in WebKit.
+ await field.blur();
// Filling can scroll the field into view, so the baseline is read once the
// edit is done, right before the apply.
const zoomBefore = await page.getByText(/%$/).first().textContent();
const pageTopBefore = await pageTopOf(page, 0);
- await page.getByRole("button", { name: "Apply Changes" }).first().click();
+ const apply = page.getByRole("button", { name: "Apply Changes" }).first();
+ await apply.click();
+ await expect(apply).toBeHidden({ timeout: 20_000 });
// The reloaded document carries the value the round trip produced, and the
// apply does not rescale the page or move the reader.
diff --git a/frontend/editor/src/portal/views/Usage.tsx b/frontend/editor/src/portal/views/Usage.tsx
index e3ffcc5bb1..c828a17d95 100644
--- a/frontend/editor/src/portal/views/Usage.tsx
+++ b/frontend/editor/src/portal/views/Usage.tsx
@@ -1,5 +1,6 @@
import { TeamSubscriptionChange } from "@app/billing/TeamSubscriptionChange";
import type { ServerPlan } from "@app/billing/serverPlan";
+import { fleetUsersInUse } from "@app/billing/fleetSeats";
import {
useCallback,
useEffect,
@@ -25,6 +26,7 @@ import {
triggerLocalSync,
type LocalUsage,
} from "@app/portal/api/link";
+import { useAccountLinkOptional } from "@app/portal/contexts/AccountLinkContext";
import { useStripePortal } from "@app/portal/hooks/useStripePortal";
import { usePortalSaasSession } from "@app/portal/hooks/usePortalSaasSession";
import { FreePlanView } from "@app/portal/components/billing/FreePlanView";
@@ -79,6 +81,7 @@ export function Usage({
renderLicenseSection,
}: UsageProps = {}) {
const { t } = useTranslation();
+ const accountLink = useAccountLinkOptional();
const { revision: sessionRevision, required } = usePortalSaasSession();
const [loadedWallet, setWallet] = useState<Wallet | null>(null);
const [sessionExpired, setSessionExpired] = useState(false);
@@ -259,8 +262,15 @@ export function Usage({
// Optional on purpose: a build that mounts no provider must lose the door, not the page.
const checkout = useCheckoutOptional();
const heldLimit = wallet?.team?.held ? wallet.team.licensedUsers : null;
- const usersInUse =
- localUsersInUse === undefined ? wallet?.team?.usersInUse : localUsersInUse;
+ const usersInUse = wallet?.team?.fleet
+ ? fleetUsersInUse(
+ wallet.team,
+ accountLink?.status?.deviceId,
+ localUsersInUse,
+ )
+ : localUsersInUse === undefined
+ ? wallet?.team?.usersInUse
+ : localUsersInUse;
const addCapacity = useCallback(() => {
// No email: the only one this instance holds is its local admin record, which is a Spring
// username and not an address the buyer owns. The checkout asks for one instead.
@@ -366,6 +376,8 @@ export function Usage({
return (
<BillingScreen
usersInUse={localUsersInUse}
+ userLimit={localUserLimit}
+ deviceId={accountLink?.status?.deviceId}
headerAction={
!needsRenewal && paying && wallet?.role === "leader" ? (
<Button
diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx
index ae07bd7170..203328c6c9 100644
--- a/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx
+++ b/frontend/editor/src/proprietary/billing/BillingScreen.test.tsx
@@ -14,6 +14,97 @@ vi.mock("react-i18next", () => ({
import { BillingScreen } from "@app/billing/BillingScreen";
import { freeWallet, subscribedWallet } from "@app/billing/walletFixtures";
+it.each([4, 0])(
+ "keeps standalone users against the enforced allowance of %i",
+ (limit) => {
+ render(
+ <BillingScreen
+ wallet={{
+ ...freeWallet,
+ team: {
+ held: false,
+ licensedUsers: null,
+ usersInUse: 1,
+ fleet: false,
+ },
+ }}
+ usersInUse={5}
+ userLimit={limit}
+ />,
+ );
+ expect(screen.getByText(`5 of ${limit} users`)).toBeInTheDocument();
+ expect(
+ screen.getByText("Capacity available to this server"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("1 of 5 users")).not.toBeInTheDocument();
+ },
+);
+
+it("shows shared fleet usage and full purchased capacity despite a smaller local allowance", () => {
+ render(
+ <BillingScreen
+ wallet={{
+ ...freeWallet,
+ team: { held: true, licensedUsers: 100, usersInUse: 83, fleet: true },
+ }}
+ usersInUse={7}
+ userLimit={17}
+ />,
+ );
+ expect(screen.getByText("83 of 100 users")).toBeInTheDocument();
+ expect(screen.queryByText("7 of 100 users")).not.toBeInTheDocument();
+ expect(
+ screen.queryByText("Capacity available to this server"),
+ ).not.toBeInTheDocument();
+});
+
+it.each([null, 3, 5])(
+ "replaces a local report of %s with live users in the fleet total",
+ (reported) => {
+ render(
+ <BillingScreen
+ wallet={{
+ ...freeWallet,
+ team: {
+ held: true,
+ licensedUsers: 100,
+ usersInUse: (reported ?? 0) + 2,
+ fleet: true,
+ breakdown: {
+ cloudUsers: 0,
+ excludedOwners: 1,
+ deployments: [
+ {
+ deviceId: "one",
+ name: "Server One",
+ users: reported,
+ reportedAt: null,
+ },
+ {
+ deviceId: "two",
+ name: "Server Two",
+ users: 2,
+ reportedAt: null,
+ },
+ ],
+ },
+ },
+ }}
+ deviceId="one"
+ usersInUse={5}
+ userLimit={98}
+ />,
+ );
+ expect(screen.getByText("7 of 100 users")).toBeInTheDocument();
+ expect(
+ screen.getByRole("img", { name: "Users: 7 of 100 users" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("7", { selector: ".billing-kv__value" }),
+ ).toBeInTheDocument();
+ },
+);
+
/**
* Units a linked instance has accrued that the cloud has not billed yet are real spend, and every
* figure on this screen counts them. Two totals disagreeing by an undisclosed amount is the bug
diff --git a/frontend/editor/src/proprietary/billing/BillingScreen.tsx b/frontend/editor/src/proprietary/billing/BillingScreen.tsx
index fddac322d8..ad240e6dd3 100644
--- a/frontend/editor/src/proprietary/billing/BillingScreen.tsx
+++ b/frontend/editor/src/proprietary/billing/BillingScreen.tsx
@@ -7,6 +7,7 @@ import { KvRow } from "@app/billing/KvRow";
import { TeamPlanRow } from "@app/billing/TeamPlanRow";
import { ProcessorPlanRow } from "@app/billing/ProcessorPlanRow";
import { estimatedBillWithPending } from "@app/billing/pendingUsage";
+import { fleetUsersInUse } from "@app/billing/fleetSeats";
import type { ServerPlan } from "@app/billing/serverPlan";
import type { Wallet } from "@app/billing/types";
import "@app/billing/billing-screen.css";
@@ -14,6 +15,10 @@ import "@app/billing/billing-screen.css";
export interface BillingScreenProps {
/** Host-specific occupied seats; null means unavailable, undefined uses the wallet. */
usersInUse?: number | null;
+ /** Standalone server allowance; linked fleets display the full Team capacity. */
+ userLimit?: number | null;
+ /** Identifies the deployment whose live roster overrides its last fleet report. */
+ deviceId?: string | null;
/** Host-authorized account actions beside the page title. */
headerAction?: ReactNode;
/**
@@ -89,6 +94,8 @@ function cycleDay(
*/
export function BillingScreen({
usersInUse,
+ userLimit,
+ deviceId,
headerAction,
wallet,
loading = false,
@@ -218,7 +225,9 @@ export function BillingScreen({
t(
"portal.billing.identity.team.chipIncluded",
"{{allowance}} included credits monthly",
- { allowance: wallet.freeAllowance.toLocaleString() },
+ {
+ allowance: wallet.freeAllowance.toLocaleString(),
+ },
),
],
};
@@ -246,9 +255,11 @@ export function BillingScreen({
const creditUnits = (wallet?.spendUnitsThisPeriod ?? 0) + pendingUnits;
const occupiedSeats = serverPlan
? serverPlan.usersInUse
- : usersInUse === undefined
- ? wallet?.team.usersInUse
- : usersInUse;
+ : wallet?.team.fleet
+ ? fleetUsersInUse(wallet.team, deviceId, usersInUse)
+ : usersInUse === undefined
+ ? wallet?.team.usersInUse
+ : usersInUse;
const showTeam = Boolean(
wallet &&
(wallet.team.held ||
@@ -343,6 +354,8 @@ export function BillingScreen({
{(showTeam || serverPlan) && (
<TeamPlanRow
usersInUse={usersInUse}
+ userLimit={userLimit}
+ deviceId={deviceId}
wallet={wallet}
selfHosted={selfHosted}
serverPlan={serverPlan}
diff --git a/frontend/editor/src/proprietary/billing/MeterRow.tsx b/frontend/editor/src/proprietary/billing/MeterRow.tsx
index 8c228df357..c3e13ad45b 100644
--- a/frontend/editor/src/proprietary/billing/MeterRow.tsx
+++ b/frontend/editor/src/proprietary/billing/MeterRow.tsx
@@ -1,4 +1,5 @@
import type { ReactNode } from "react";
+import { Tooltip } from "@app/ui/Tooltip";
export type MeterRowTone = "free" | "paid" | "warn";
@@ -22,6 +23,8 @@ export interface MeterRowProps {
onDoor?: () => void;
/** Tooltip on the middle line, for a fact that needs one qualifier and no more. */
midTitle?: string;
+ /** Breakdown available on hover, keyboard focus and touch. */
+ details?: ReactNode;
}
/**
@@ -40,10 +43,16 @@ export function MeterRow({
door,
onDoor,
midTitle,
+ details,
}: MeterRowProps) {
const cls = `billing-meter${tone === "paid" ? " billing-meter--paid" : tone === "warn" ? " billing-meter--warn" : ""}`;
- return (
- <div className={cls}>
+ const row = (
+ <div
+ className={cls}
+ tabIndex={details ? 0 : undefined}
+ role={details ? "group" : undefined}
+ aria-label={details ? name : undefined}
+ >
<span className="billing-meter__dot" aria-hidden />
<span className="billing-meter__name">{name}</span>
<span className="billing-meter__mid" title={midTitle}>
@@ -77,4 +86,11 @@ export function MeterRow({
)}
</div>
);
+ return details ? (
+ <Tooltip content={details} className="billing-meter-tooltip">
+ {row}
+ </Tooltip>
+ ) : (
+ row
+ );
}
diff --git a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx
index bc59d971a4..b70a751bae 100644
--- a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx
+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.test.tsx
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { fireEvent, render, screen, within } from "@testing-library/react";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
@@ -14,7 +14,6 @@ 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,
@@ -28,6 +27,30 @@ const on = (over: Partial<Wallet> = {}): Wallet => ({
});
describe("ProcessorPlanRow", () => {
+ it("shows remaining free credits and paid spend separately on focus", () => {
+ render(
+ <ProcessorPlanRow
+ wallet={on({
+ freeAllowance: 1000,
+ freeRemaining: 600,
+ estimatedBillMinor: 2500,
+ capUsd: 100,
+ noCap: false,
+ })}
+ pendingUnits={100}
+ />,
+ );
+ fireEvent.focus(screen.getByRole("group", { name: "Processor" }));
+ const tooltip = within(screen.getByRole("tooltip"));
+ expect(
+ tooltip.getByRole("progressbar", { name: "Free credits remaining" }),
+ ).toHaveAttribute("aria-valuenow", "50");
+ expect(
+ tooltip.getByRole("progressbar", { name: "Paid metered usage" }),
+ ).toHaveAttribute("aria-valuenow", "25");
+ expect(tooltip.getByText("500 of 1,000")).toBeInTheDocument();
+ expect(tooltip.getByText("$25.00 / $100")).toBeInTheDocument();
+ });
it("hides an absent included pool while retaining metered billing", () => {
render(
<ProcessorPlanRow wallet={on({ freeAllowance: 0, freeRemaining: 0 })} />,
@@ -49,7 +72,7 @@ describe("ProcessorPlanRow", () => {
screen.getByRole("button", { name: "Switch on the Processor" }),
).toBeInTheDocument();
});
- it("keeps the included pool visible when the metered limit is zero", () => {
+ it("shows only the Processor row when the metered limit is zero", () => {
render(
<ProcessorPlanRow
wallet={on({
@@ -61,10 +84,14 @@ describe("ProcessorPlanRow", () => {
})}
/>,
);
- expect(screen.getByText("100% of $0")).toBeInTheDocument();
- expect(screen.getByText("300 of 2,500 used")).toBeInTheDocument();
+ expect(screen.getByText("100%")).toBeInTheDocument();
+ expect(
+ screen.getByText("$0.00 of $0 metered this cycle"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("300 of 2,500 used")).not.toBeInTheDocument();
+ expect(screen.getAllByText("Processor")).toHaveLength(1);
});
- it("shows the actual Team allowance and its independent renewal while metering is on", () => {
+ it("does not add a separate included-credit row while metering is on", () => {
render(
<ProcessorPlanRow
wallet={on({
@@ -75,15 +102,9 @@ describe("ProcessorPlanRow", () => {
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();
+ expect(screen.queryByText("Included credits")).not.toBeInTheDocument();
+ expect(screen.queryByText("425 of 2,700 used")).not.toBeInTheDocument();
+ expect(screen.getAllByText("Processor")).toHaveLength(1);
});
it("sells while off: the grant drains towards the activation door", () => {
@@ -132,8 +153,10 @@ describe("ProcessorPlanRow", () => {
);
// 4500 minor is $45 against a $1,000 limit: 5%, not 450%.
- expect(screen.getByText("$45.00 metered this cycle")).toBeInTheDocument();
- expect(screen.getByText("5% of $1,000")).toBeInTheDocument();
+ expect(
+ screen.getByText("$45.00 of $1,000 metered this cycle"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("5%")).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Raise limit" }),
).toBeInTheDocument();
@@ -150,7 +173,7 @@ describe("ProcessorPlanRow", () => {
);
expect(screen.getByText("no limit")).toBeInTheDocument();
- expect(container.querySelectorAll(".billing-meter__fill")).toHaveLength(1);
+ expect(container.querySelectorAll(".billing-meter__fill")).toHaveLength(0);
});
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.tsx
index a6a1f2061e..172ebdfa40 100644
--- a/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx
+++ b/frontend/editor/src/proprietary/billing/ProcessorPlanRow.tsx
@@ -60,7 +60,7 @@ export function ProcessorPlanRow({
const rate = wallet.pricePerDocMinor;
const includedCredits = (() => {
- if (wallet.freeAllowance <= 0) return null;
+ if (wallet.processor.active || wallet.freeAllowance <= 0) return null;
const used = Math.min(
wallet.freeAllowance,
Math.max(0, wallet.freeAllowance - wallet.freeRemaining + pendingUnits),
@@ -87,11 +87,7 @@ export function ProcessorPlanRow({
return (
<MeterRow
- name={
- wallet.processor.active
- ? t("portal.billing.processor.includedCredits", "Included credits")
- : name
- }
+ name={name}
mid={
wallet.includedPeriodEnd
? t(
@@ -159,20 +155,30 @@ export function ProcessorPlanRow({
const mid =
spentMinor != null
- ? t(
- "portal.billing.processor.midMetered",
- "{{spend}} metered this cycle",
- {
- spend: formatMinor(spentMinor, wallet.currency),
- },
- )
+ ? capped
+ ? t(
+ "portal.billing.processor.spendAgainstLimit",
+ "{{spend}} of {{cap}} metered this cycle",
+ {
+ spend: formatMinor(spentMinor, wallet.currency),
+ cap: formatMoneyMajor(wallet.capUsd as number, wallet.currency),
+ },
+ )
+ : t(
+ "portal.billing.processor.midMetered",
+ "{{spend}} metered this cycle",
+ {
+ spend: formatMinor(spentMinor, wallet.currency),
+ },
+ )
: t("portal.billing.processor.midMeteredUnknown", "Metered this cycle");
const fact = capped
- ? t("portal.billing.processor.factCapped", "{{pct}}% of {{cap}}", {
- pct: Math.round(pct).toLocaleString(),
- cap: formatMoneyMajor(wallet.capUsd as number, wallet.currency),
- })
+ ? spentMinor == null
+ ? "—"
+ : t("portal.billing.processor.percentUsed", "{{pct}}%", {
+ pct: Math.round(pct).toLocaleString(),
+ })
: t("portal.billing.processor.factNoCap", "no limit");
const door =
@@ -180,28 +186,108 @@ export function ProcessorPlanRow({
(onGovern
? t("portal.billing.processor.raiseLimit", "Raise limit")
: undefined);
+ const freeRemaining = Math.min(
+ wallet.freeAllowance,
+ Math.max(0, wallet.freeRemaining - pendingUnits),
+ );
+ const freePct =
+ wallet.freeAllowance > 0 ? (freeRemaining / wallet.freeAllowance) * 100 : 0;
+ const freeLabel = t(
+ "portal.billing.processor.freeRemaining",
+ "Free credits remaining",
+ );
+ const paidLabel = t(
+ "portal.billing.processor.paidUsed",
+ "Paid metered usage",
+ );
+ const details = (
+ <div className="billing-breakdown">
+ <div>
+ <div className="billing-breakdown__row">
+ <span>{freeLabel}</span>
+ <strong>
+ {t(
+ "portal.billing.processor.remainingOf",
+ "{{remaining}} of {{total}}",
+ {
+ remaining: freeRemaining.toLocaleString(),
+ total: wallet.freeAllowance.toLocaleString(),
+ },
+ )}
+ </strong>
+ </div>
+ <span
+ className="billing-breakdown__bar"
+ role="progressbar"
+ aria-label={freeLabel}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={Math.round(freePct)}
+ >
+ <span
+ className="billing-breakdown__fill"
+ style={{ width: `${freePct}%` }}
+ />
+ </span>
+ </div>
+ <div>
+ <div className="billing-breakdown__row">
+ <span>{paidLabel}</span>
+ <strong>
+ {spentMinor == null
+ ? "—"
+ : formatMinor(spentMinor, wallet.currency)}
+ {capped
+ ? ` / ${formatMoneyMajor(wallet.capUsd as number, wallet.currency)}`
+ : ""}
+ </strong>
+ </div>
+ {capped ? (
+ <span
+ className="billing-breakdown__bar"
+ role="progressbar"
+ aria-label={paidLabel}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={
+ spentMinor == null
+ ? undefined
+ : Math.round(Math.min(100, Math.max(0, pct)))
+ }
+ >
+ <span
+ className="billing-breakdown__fill"
+ style={{ width: `${Math.min(100, Math.max(0, pct))}%` }}
+ />
+ </span>
+ ) : (
+ <small>
+ {t("portal.billing.processor.noSpendLimit", "No spend limit")}
+ </small>
+ )}
+ </div>
+ </div>
+ );
return (
- <>
- {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
- }
- />
- </>
+ <MeterRow
+ name={name}
+ mid={mid}
+ details={details}
+ 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/SeatBreakdown.test.tsx b/frontend/editor/src/proprietary/billing/SeatBreakdown.test.tsx
new file mode 100644
index 0000000000..c292f03e1e
--- /dev/null
+++ b/frontend/editor/src/proprietary/billing/SeatBreakdown.test.tsx
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { BillingScreen } from "@app/billing/BillingScreen";
+import { freeWallet } from "@app/billing/walletFixtures";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (_key: string, fallback?: string) => fallback ?? _key,
+ }),
+}));
+
+describe("seat breakdown", () => {
+ it("explains the exempt owner and substitutes the live local roster for its stale report", () => {
+ render(
+ <BillingScreen
+ wallet={{
+ ...freeWallet,
+ team: {
+ ...freeWallet.team,
+ fleet: true,
+ breakdown: {
+ cloudUsers: 0,
+ excludedOwners: 1,
+ deployments: [
+ {
+ deviceId: "here",
+ name: "Office",
+ users: 2,
+ reportedAt: "2026-09-18T09:00:00Z",
+ },
+ {
+ deviceId: "away",
+ name: "Remote office",
+ users: null,
+ reportedAt: null,
+ },
+ ],
+ },
+ },
+ }}
+ deviceId="here"
+ usersInUse={5}
+ userLimit={5}
+ />,
+ );
+ fireEvent.focus(screen.getByRole("group", { name: "Users" }));
+ const tooltip = within(screen.getByRole("tooltip"));
+ expect(
+ tooltip.getByText("The required cloud team owner does not use a seat."),
+ ).toBeInTheDocument();
+ expect(tooltip.getByText("This server")).toBeInTheDocument();
+ expect(tooltip.getByText("5")).toBeInTheDocument();
+ expect(tooltip.queryByText("2")).not.toBeInTheDocument();
+ expect(tooltip.getByText("Remote office")).toBeInTheDocument();
+ expect(tooltip.getByText("Not yet reported")).toBeInTheDocument();
+ expect(
+ tooltip.getByText(
+ "Waiting for its daily sync; not yet included in the fleet total.",
+ ),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/editor/src/proprietary/billing/SeatBreakdown.tsx b/frontend/editor/src/proprietary/billing/SeatBreakdown.tsx
new file mode 100644
index 0000000000..be0b6844b8
--- /dev/null
+++ b/frontend/editor/src/proprietary/billing/SeatBreakdown.tsx
@@ -0,0 +1,72 @@
+import { useTranslation } from "react-i18next";
+import type { TeamHolding } from "@app/billing/types";
+
+/** Shows report freshness; only this deployment can substitute a live local count. */
+export function SeatBreakdown({
+ breakdown,
+ deviceId,
+ localUsers,
+}: {
+ breakdown: NonNullable<TeamHolding["breakdown"]>;
+ deviceId?: string | null;
+ localUsers?: number | null;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="billing-breakdown">
+ <strong>
+ {t("portal.billing.seats.breakdown", "Where users are counted")}
+ </strong>
+ <div className="billing-breakdown__row">
+ <span>{t("portal.billing.seats.cloud", "Stirling Cloud")}</span>
+ <strong>{breakdown.cloudUsers.toLocaleString()}</strong>
+ </div>
+ {breakdown.excludedOwners > 0 && (
+ <small>
+ {t(
+ "portal.billing.seats.ownerExcluded",
+ "The required cloud team owner does not use a seat.",
+ )}
+ </small>
+ )}
+ {breakdown.deployments.map((deployment) => {
+ const current = deployment.deviceId === deviceId;
+ const live = current && localUsers != null;
+ const count = live ? localUsers : deployment.users;
+ return (
+ <div key={deployment.deviceId}>
+ <div className="billing-breakdown__row">
+ <span>
+ {current
+ ? t("portal.billing.seats.thisServer", "This server")
+ : deployment.name ||
+ t("portal.billing.seats.deployment", "Linked server")}
+ </span>
+ <strong>
+ {count == null
+ ? t("portal.billing.seats.notReported", "Not yet reported")
+ : count.toLocaleString()}
+ </strong>
+ </div>
+ <small>
+ {live
+ ? t("portal.billing.seats.live", "Live user count")
+ : deployment.reportedAt
+ ? t(
+ "portal.billing.seats.lastReported",
+ "Reported {{date}}",
+ {
+ date: new Date(deployment.reportedAt).toLocaleString(),
+ },
+ )
+ : t(
+ "portal.billing.seats.awaitingSync",
+ "Waiting for its daily sync; not yet included in the fleet total.",
+ )}
+ </small>
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx
index c63d4ced02..a2f926b8a1 100644
--- a/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx
+++ b/frontend/editor/src/proprietary/billing/TeamPlanRow.tsx
@@ -2,6 +2,8 @@ import { useTranslation } from "react-i18next";
import { MeterRow } from "@app/billing/MeterRow";
import type { ServerPlan } from "@app/billing/serverPlan";
import type { Wallet } from "@app/billing/types";
+import { SeatBreakdown } from "@app/billing/SeatBreakdown";
+import { fleetUsersInUse } from "@app/billing/fleetSeats";
/**
* The Team product, as a row: users against the capacity the plan covers.
@@ -18,6 +20,8 @@ export function TeamPlanRow({
serverPlan,
onAddCapacity,
usersInUse: occupiedSeats,
+ userLimit,
+ deviceId,
}: {
wallet: Wallet | null;
serverPlan?: ServerPlan;
@@ -25,8 +29,11 @@ export function TeamPlanRow({
selfHosted?: boolean;
/** Leader-only: the door that sells Team capacity. Omit for members. */
onAddCapacity?: () => void;
- /** Undefined uses cloud membership; null hides an unavailable local count. */
+ /** Live local roster replaces this deployment's report in the fleet total. */
usersInUse?: number | null;
+ /** Used only for standalone servers; linked fleets show the full plan capacity. */
+ userLimit?: number | null;
+ deviceId?: string | null;
}) {
const { t } = useTranslation();
if (serverPlan) {
@@ -71,36 +78,54 @@ export function TeamPlanRow({
}
if (!wallet) return null;
const { held, licensedUsers } = wallet.team;
- const usersInUse =
- occupiedSeats === undefined ? wallet.team.usersInUse : occupiedSeats;
+ const usersInUse = wallet.team.fleet
+ ? fleetUsersInUse(wallet.team, deviceId, occupiedSeats)
+ : occupiedSeats === undefined
+ ? wallet.team.usersInUse
+ : occupiedSeats;
const processorActive = Boolean(wallet.processor?.active);
- const mid = !held
- ? selfHosted
+ const mid =
+ !wallet.team.fleet && userLimit !== undefined
? t(
- "portal.billing.team.midFreeSelfHosted",
- "The free tier covers your first users",
+ "portal.billing.team.midLocalCapacity",
+ "Capacity available to this server",
)
- : t("portal.billing.team.midFree", "The Team plan covers 100 users")
- : processorActive
- ? t("portal.billing.team.midIncluded", "Included with your Team base")
- : t("portal.billing.team.midPrice", "$99/mo per 100 users");
+ : !held
+ ? selfHosted
+ ? t(
+ "portal.billing.team.midFreeSelfHosted",
+ "The free tier covers your first users",
+ )
+ : t("portal.billing.team.midFree", "The Team plan covers 100 users")
+ : processorActive
+ ? t("portal.billing.team.midIncluded", "Included with your Team base")
+ : t("portal.billing.team.midPrice", "$99/mo per 100 users");
const door = onAddCapacity
? t("portal.billing.team.addCapacity", "Add capacity")
: undefined;
const name = t("portal.billing.team.rowName", "Users");
+ const details = wallet.team.breakdown ? (
+ <SeatBreakdown
+ breakdown={wallet.team.breakdown}
+ deviceId={deviceId}
+ localUsers={occupiedSeats}
+ />
+ ) : undefined;
- // One number in charge at a time: the server's free allowance until a plan is held, the
- // plan's own limit after.
- const limit = held
- ? licensedUsers
- : (licensedUsers ?? wallet.freeUserAllowance ?? null);
+ const limit =
+ !wallet.team.fleet && userLimit !== undefined
+ ? userLimit
+ : held
+ ? licensedUsers
+ : (licensedUsers ?? wallet.freeUserAllowance ?? null);
if (usersInUse == null) {
return (
<MeterRow
name={name}
+ details={details}
mid={mid}
showTrack={false}
tone={held ? "paid" : "free"}
@@ -117,11 +142,11 @@ export function TeamPlanRow({
);
}
- // A non-positive limit is an absent one, not a full meter: nothing to divide by either way.
- if (limit == null || limit <= 0) {
+ if (limit == null) {
return (
<MeterRow
name={name}
+ details={details}
mid={mid}
showTrack={false}
tone={held ? "paid" : "free"}
@@ -134,13 +159,15 @@ export function TeamPlanRow({
);
}
- const pct = (usersInUse / limit) * 100;
+ const pct =
+ limit === 0 ? (usersInUse > 0 ? 100 : 0) : (usersInUse / limit) * 100;
// A free tier filling up is the product working, not a warning, so amber is for paid capacity.
const tone = held ? (pct >= 90 ? "warn" : "paid") : "free";
return (
<MeterRow
name={name}
+ details={details}
mid={mid}
pct={pct}
tone={tone}
diff --git a/frontend/editor/src/proprietary/billing/billing-screen.css b/frontend/editor/src/proprietary/billing/billing-screen.css
index ac5eb0c05b..6c42bafb89 100644
--- a/frontend/editor/src/proprietary/billing/billing-screen.css
+++ b/frontend/editor/src/proprietary/billing/billing-screen.css
@@ -243,6 +243,41 @@
text-align: right;
}
+.billing-meter-tooltip {
+ display: block;
+}
+
+.billing-breakdown {
+ display: grid;
+ gap: 0.625rem;
+ min-width: min(16rem, 70vw);
+}
+
+.billing-breakdown__row {
+ display: flex;
+ justify-content: space-between;
+ gap: 1rem;
+}
+
+.billing-breakdown small {
+ color: var(--c-text-muted);
+}
+
+.billing-breakdown__bar {
+ display: block;
+ height: 0.375rem;
+ margin-top: 0.375rem;
+ overflow: hidden;
+ background: var(--c-surface-sunken);
+ border-radius: 0.25rem;
+}
+
+.billing-breakdown__fill {
+ display: block;
+ height: 100%;
+ background: var(--c-primary);
+}
+
.billing-meter__door {
flex-shrink: 0;
width: 10.625rem;
diff --git a/frontend/editor/src/proprietary/billing/fleetSeats.ts b/frontend/editor/src/proprietary/billing/fleetSeats.ts
new file mode 100644
index 0000000000..27a5a1144b
--- /dev/null
+++ b/frontend/editor/src/proprietary/billing/fleetSeats.ts
@@ -0,0 +1,18 @@
+import type { TeamHolding } from "@app/billing/types";
+
+/** Replaces this deployment's last report with its live roster, without counting it twice. */
+export function fleetUsersInUse(
+ team: TeamHolding,
+ deviceId?: string | null,
+ localUsers?: number | null,
+): number {
+ if (!team.breakdown) return team.usersInUse;
+ return team.breakdown.deployments.reduce(
+ (total, deployment) =>
+ total +
+ (deployment.deviceId === deviceId && localUsers != null
+ ? localUsers
+ : (deployment.users ?? 0)),
+ team.breakdown.cloudUsers,
+ );
+}
diff --git a/frontend/editor/src/proprietary/billing/types.ts b/frontend/editor/src/proprietary/billing/types.ts
index b70c5c38cb..44e2c16b5f 100644
--- a/frontend/editor/src/proprietary/billing/types.ts
+++ b/frontend/editor/src/proprietary/billing/types.ts
@@ -46,6 +46,17 @@ export interface TeamHolding {
licensedUsers: number | null;
/** Members occupying capacity right now — the capacity meter's numerator. */
usersInUse: number;
+ fleet?: boolean;
+ breakdown?: {
+ cloudUsers: number;
+ excludedOwners: number;
+ deployments: {
+ deviceId: string;
+ name: string | null;
+ users: number | null;
+ reportedAt: string | null;
+ }[];
+ } | null;
}
/** The Processor holding: metered automation beyond the free grant. */
diff --git a/frontend/editor/src/proprietary/components/settings/ConnectedInstanceRow.tsx b/frontend/editor/src/proprietary/components/settings/ConnectedInstanceRow.tsx
index a2f82d6bac..9d725a05d4 100644
--- a/frontend/editor/src/proprietary/components/settings/ConnectedInstanceRow.tsx
+++ b/frontend/editor/src/proprietary/components/settings/ConnectedInstanceRow.tsx
@@ -99,6 +99,23 @@ export function ConnectedInstanceRow({
)}
</p>
)}
+ {!instance.revoked && (
+ <p>
+ {instance.seatCount == null
+ ? t(
+ "settings.connectedInstances.seatsUnknown",
+ "Waiting for this deployment to report its user count in the daily sync.",
+ )
+ : t(
+ "settings.connectedInstances.seatsReported",
+ "{{count}} Team seats · reported {{date}}. Offline deployments keep their seats until unlinked.",
+ {
+ count: instance.seatCount,
+ date: formatDate(instance.seatsReportedAt ?? null),
+ },
+ )}
+ </p>
+ )}
<details className="account-connection__details">
<summary>
{t("settings.connectedInstances.details", "Details")}
diff --git a/frontend/editor/src/proprietary/types/linkedInstance.ts b/frontend/editor/src/proprietary/types/linkedInstance.ts
index 813d85cee7..dc7f612eec 100644
--- a/frontend/editor/src/proprietary/types/linkedInstance.ts
+++ b/frontend/editor/src/proprietary/types/linkedInstance.ts
@@ -7,4 +7,6 @@ export interface LinkedInstanceRow {
/** Last credential-authenticated contact with Stirling; not a heartbeat or online status. */
lastSeenAt: string | null;
revoked: boolean;
+ seatCount?: number | null;
+ seatsReportedAt?: string | null;
}