Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Keep Billing Admin changes tied to confirmed reads

pulse-triage[bot]6422ee529c75
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 71fcd28268..788ca30edb 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -21,6 +21,21 @@
## Purpose
+### Billing Admin cancellation and non-replayed writes
+
+`frontend-modern/src/api/billingAdmin.ts` accepts an optional cancellation signal
+for the global hosted organization inventory, per-organization billing read and
+subscription PUT. Existing session preference, encoded organization path and
+`skipOrgContext` are unchanged: the platform-admin endpoints still use default
+request context, not the UI's selected tenant. Idempotent reads retain the
+existing client fallback policy. Subscription writes set `retry: false`, so an
+unconfirmed response does not replay after CSRF refresh, rate limiting or token
+fallback; the client rechecks cancellation after CSRF preparation before dispatch.
+A pending abort does not claim a server-side rollback. Existing server-side
+administration, organization and capability checks remain authoritative.
+API unit and real-client transport tests cover option propagation, headers,
+encoded targets, non-retry responses and cancellation during CSRF preparation.
+
### Selected organization detail and billing request lifetimes
The existing organization `update` client optionally accepts the same
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 6110786061..8e33000750 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -15,6 +15,36 @@
## Purpose
+### Billing Admin reads and changes use an accepted global snapshot
+
+Hosted Billing Admin remains a platform-administration surface, not an
+organization-selected read. Its existing hosted/multitenant/demo and server
+permission boundaries stay in place. A refresh, capability/presentation
+withdrawal, read-only transition or disposal invalidates the inventory and row
+requests, aborts pending transport and removes retained billing details. Late
+successes, failures and spinner completions cannot change a newer snapshot.
+The six-worker billing prefetch runs once per accepted inventory; failures are
+not rescheduled by sibling completions. Opaque organization IDs are own keys,
+not object-prototype entries.
+
+Only a successful, well-formed inventory can assert emptiness. Failed inventory
+reads show a fixed inline error, not old rows or an empty-list claim. Failed or
+malformed billing rows show unavailable data and deliberate read-only recovery,
+not a trial/customer default or a permanent JSON loading placeholder. Subscription
+controls require the current accepted row and a non-read-only session; they
+never fetch missing billing data as an implicit prelude to writing.
+
+A subscription change preserves the saved plan and other billing fields, admits
+one in-flight write per row and is never automatically repeated. Refresh,
+withdrawal and disposal abort its transport, including after CSRF preparation.
+Cancellation is not server rollback. A failed, malformed or mismatched response
+withdraws the row snapshot and says the change is unconfirmed until an explicit
+reload. Obsolete completions produce no success or failure toast in a later view.
+Normal-suite BillingAdminPanel/ReadLifetimes and billingAdmin transport tests pin
+these boundaries. Desktop and phone browser evidence uses the actual panel,
+grid, client and capability stores with synthetic HTTP responses; no installed
+billing, provider mutation or original administrator recovery is claimed.
+
### Organization billing reads are a selected snapshot, not fallback plan data
The existing Billing & Usage panel displays plan and member figures only after
diff --git a/frontend-modern/src/api/__tests__/billingAdmin.test.ts b/frontend-modern/src/api/__tests__/billingAdmin.test.ts
index cc0edb7e56..8f74922aab 100644
--- a/frontend-modern/src/api/__tests__/billingAdmin.test.ts
+++ b/frontend-modern/src/api/__tests__/billingAdmin.test.ts
@@ -92,4 +92,31 @@ describe('BillingAdminAPI', () => {
expect(result).toEqual(mockState);
});
});
+ it('forwards cancellation for all operations and makes writes non-retrying', async () => {
+ const signal = new AbortController().signal;
+ await BillingAdminAPI.listOrganizations({ signal });
+ await BillingAdminAPI.getBillingState('org/one', { signal });
+ const state: BillingState = { subscription_state: 'active', capabilities: [], limits: {} };
+ await BillingAdminAPI.putBillingState('org/one', state, { signal });
+ expect(apiFetchJSON).toHaveBeenNthCalledWith(
+ 1,
+ '/api/hosted/organizations',
+ expect.objectContaining({ signal, preferSessionAuth: true, skipOrgContext: true }),
+ );
+ expect(apiFetchJSON).toHaveBeenNthCalledWith(
+ 2,
+ '/api/admin/orgs/org%2Fone/billing-state',
+ expect.objectContaining({ signal, preferSessionAuth: true, skipOrgContext: true }),
+ );
+ expect(apiFetchJSON).toHaveBeenNthCalledWith(
+ 3,
+ '/api/admin/orgs/org%2Fone/billing-state',
+ expect.objectContaining({
+ signal,
+ retry: false,
+ preferSessionAuth: true,
+ skipOrgContext: true,
+ }),
+ );
+ });
});
diff --git a/frontend-modern/src/api/__tests__/billingAdmin.transport.test.ts b/frontend-modern/src/api/__tests__/billingAdmin.transport.test.ts
new file mode 100644
index 0000000000..441b4c89ff
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/billingAdmin.transport.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { BillingState } from '../billingAdmin';
+
+const fetchMock = vi.fn();
+let api: typeof import('../billingAdmin');
+let client: typeof import('@/utils/apiClient');
+const state: BillingState = {
+ subscription_state: 'suspended',
+ capabilities: ['multi_tenant'],
+ limits: { max_nodes: 30 },
+};
+
+beforeEach(async () => {
+ vi.resetModules();
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+ document.cookie = 'pulse_csrf=; Max-Age=0; Path=/';
+ sessionStorage.clear();
+ client = await import('@/utils/apiClient');
+ api = await import('../billingAdmin');
+ client.setApiToken('synthetic-stored-token');
+ client.setOrgID('selected-tenant');
+});
+afterEach(() => {
+ client.clearAuth();
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+});
+
+describe('Billing Admin real transport', () => {
+ it('keeps global reads session-preferred and cancellable, without using the selected tenant', async () => {
+ const signal = new AbortController().signal;
+ fetchMock.mockResolvedValueOnce(new Response('[]', { status: 200 }));
+ await api.BillingAdminAPI.listOrganizations({ signal });
+ expect(fetchMock.mock.calls[0][1]).toMatchObject({
+ signal,
+ credentials: 'include',
+ headers: { 'X-Pulse-Org-ID': 'default' },
+ });
+ expect(fetchMock.mock.calls[0][1].headers['X-API-Token']).toBeUndefined();
+ expect(client.getOrgID()).toBe('selected-tenant');
+ });
+
+ it.each([403, 429, 503])(
+ 'does not automatically repeat a subscription PUT after HTTP %i',
+ async (status) => {
+ fetchMock.mockResolvedValueOnce(
+ new Response('{}', {
+ status,
+ headers: { 'X-CSRF-Token': 'synthetic-new-csrf', 'Retry-After': '0' },
+ }),
+ );
+ await expect(api.BillingAdminAPI.putBillingState('org/one', state)).rejects.toMatchObject({
+ status,
+ });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0][0]).toBe('/api/admin/orgs/org%2Fone/billing-state');
+ expect(fetchMock.mock.calls[0][1]).toMatchObject({
+ method: 'PUT',
+ body: JSON.stringify(state),
+ headers: { 'X-Pulse-Org-ID': 'default' },
+ });
+ expect(fetchMock.mock.calls[0][1].headers['X-API-Token']).toBeUndefined();
+ },
+ );
+
+ it('does not dispatch a withdrawn subscription change after CSRF preparation completes', async () => {
+ vi.stubEnv('MODE', 'production');
+ let resolve!: (value: Response) => void;
+ fetchMock.mockImplementationOnce(
+ () =>
+ new Promise<Response>((yes) => {
+ resolve = yes;
+ }),
+ );
+ const controller = new AbortController();
+ const writing = api.BillingAdminAPI.putBillingState('org-a', state, {
+ signal: controller.signal,
+ });
+ const result = expect(writing).rejects.toMatchObject({ name: 'AbortError' });
+ expect(fetchMock.mock.calls[0][0]).toBe('/api/health');
+ controller.abort();
+ resolve(new Response('{}', { status: 200 }));
+ await result;
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend-modern/src/api/billingAdmin.ts b/frontend-modern/src/api/billingAdmin.ts
index d8e4a61012..bab110abe5 100644
--- a/frontend-modern/src/api/billingAdmin.ts
+++ b/frontend-modern/src/api/billingAdmin.ts
@@ -22,24 +22,34 @@ export interface BillingState {
stripe_price_id?: string;
}
+interface BillingAdminRequestOptions {
+ signal?: AbortSignal;
+}
+
export const BillingAdminAPI = {
- listOrganizations: () =>
+ listOrganizations: (options?: BillingAdminRequestOptions) =>
apiFetchJSON<HostedOrganizationSummary[]>('/api/hosted/organizations', {
preferSessionAuth: true,
skipOrgContext: true,
+ ...options,
}),
- getBillingState: (orgID: string) =>
+ getBillingState: (orgID: string, options?: BillingAdminRequestOptions) =>
apiFetchJSON<BillingState>(`/api/admin/orgs/${encodeURIComponent(orgID)}/billing-state`, {
preferSessionAuth: true,
skipOrgContext: true,
+ ...options,
}),
- putBillingState: (orgID: string, payload: BillingState) =>
+ putBillingState: (orgID: string, payload: BillingState, options?: BillingAdminRequestOptions) =>
apiFetchJSON<BillingState>(`/api/admin/orgs/${encodeURIComponent(orgID)}/billing-state`, {
method: 'PUT',
body: JSON.stringify(payload),
preferSessionAuth: true,
skipOrgContext: true,
+ ...options,
+ // A failed response does not establish whether a subscription changed.
+ // Also recheck cancellation after the client's CSRF preparation wait.
+ retry: false,
}),
};
diff --git a/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx b/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx
index 563945193e..f470713035 100644
--- a/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx
+++ b/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx
@@ -1,4 +1,4 @@
-import type { Component } from 'solid-js';
+import { Show, type Component } from 'solid-js';
import { Button } from '@/components/shared/Button';
import { PulseDataGrid } from '@/components/shared/PulseDataGrid';
import {
@@ -13,6 +13,8 @@ import type { BillingStateCache } from './useBillingAdminPanelState';
interface BillingAdminOrganizationsTableProps {
billingByOrgID: BillingStateCache;
billingLoadingByOrgID: Record<string, boolean>;
+ billingErrorByOrgID: Record<string, string>;
+ canManageBilling: boolean;
expandedOrgID: string | null;
isLoading: boolean;
orgs: HostedOrganizationSummary[];
@@ -31,152 +33,185 @@ const stripeCustomerCell = (state?: BillingState) => {
export const BillingAdminOrganizationsTable: Component<BillingAdminOrganizationsTableProps> = (
props,
-) => (
- <PulseDataGrid
- data={props.orgs}
- isLoading={props.isLoading}
- emptyState={BILLING_ADMIN_EMPTY_STATE}
- desktopMinWidth="920px"
- columns={[
- {
- key: 'organization',
- label: 'Organization',
- render: (org) => {
- const orgID = (org.org_id || '').trim();
- return (
- <button
- type="button"
- class="text-left w-full"
- onClick={() => {
- props.onToggleOrganization(orgID);
- }}
- >
- <div class="font-medium text-base-content">{org.display_name || org.org_id}</div>
- <div class="text-xs text-muted">
- <span class="font-mono">{org.org_id}</span>
- {getBillingAdminOrganizationBadges(org).map((badge) => (
- <span class={`ml-2 rounded-sm px-1.5 py-0.5 ${badge.badgeClass}`}>
- {badge.label}
- </span>
- ))}
+) => {
+ const unreadLabel = (orgID: string) =>
+ props.billingLoadingByOrgID[orgID] ? 'Loading' : 'Unavailable';
+ const actionsDisabled = (orgID: string) =>
+ !props.canManageBilling ||
+ !props.billingByOrgID[orgID] ||
+ !!props.billingErrorByOrgID[orgID] ||
+ props.savingByOrgID[orgID] ||
+ props.billingLoadingByOrgID[orgID];
+ return (
+ <PulseDataGrid
+ data={props.orgs}
+ isLoading={props.isLoading}
+ emptyState={BILLING_ADMIN_EMPTY_STATE}
+ desktopMinWidth="920px"
+ columns={[
+ {
+ key: 'organization',
+ label: 'Organization',
+ render: (org) => {
+ const orgID = (org.org_id || '').trim();
+ return (
+ <button
+ type="button"
+ class="text-left w-full"
+ onClick={() => {
+ props.onToggleOrganization(orgID);
+ }}
+ >
+ <div class="font-medium text-base-content">{org.display_name || org.org_id}</div>
+ <div class="text-xs text-muted">
+ <span class="font-mono">{org.org_id}</span>
+ {getBillingAdminOrganizationBadges(org).map((badge) => (
+ <span class={`ml-2 rounded-sm px-1.5 py-0.5 ${badge.badgeClass}`}>
+ {badge.label}
+ </span>
+ ))}
+ </div>
+ </button>
+ );
+ },
+ },
+ {
+ key: 'owner',
+ label: 'Owner',
+ hiddenOnMobile: true,
+ render: (org) => (
+ <span class="font-mono text-xs text-base-content">{org.owner_user_id || 'N/A'}</span>
+ ),
+ },
+ {
+ key: 'subscription',
+ label: 'Subscription',
+ render: (org) => {
+ const billing = props.billingByOrgID[(org.org_id || '').trim()];
+ const orgID = (org.org_id || '').trim();
+ return (
+ <div class="space-y-2">
+ <span class="font-mono text-xs text-base-content">
+ {billing
+ ? getLicenseSubscriptionStatusPresentation(billing.subscription_state).label
+ : unreadLabel(orgID)}
+ </span>
+ <Show when={props.billingErrorByOrgID[orgID]}>
+ <p role="alert" class="max-w-xs text-xs text-red-700 dark:text-red-300">
+ {props.billingErrorByOrgID[orgID]}
+ </p>
+ <Button
+ variant="secondary"
+ size="xs"
+ aria-label={`Reload billing for ${org.display_name || orgID}`}
+ onClick={() => props.onReloadOrganization(orgID)}
+ disabled={props.billingLoadingByOrgID[orgID] || props.savingByOrgID[orgID]}
+ >
+ Reload billing
+ </Button>
+ </Show>
</div>
- </button>
- );
+ );
+ },
},
- },
- {
- key: 'owner',
- label: 'Owner',
- hiddenOnMobile: true,
- render: (org) => (
- <span class="font-mono text-xs text-base-content">{org.owner_user_id || 'N/A'}</span>
- ),
- },
- {
- key: 'subscription',
- label: 'Subscription',
- render: (org) => {
- const billing = props.billingByOrgID[(org.org_id || '').trim()];
- return (
- <span class="font-mono text-xs text-base-content">
- {getLicenseSubscriptionStatusPresentation(billing?.subscription_state).label}
- </span>
- );
+ {
+ key: 'trial',
+ label: 'Trial',
+ hiddenOnMobile: true,
+ render: (org) => {
+ const billing = props.billingByOrgID[(org.org_id || '').trim()];
+ return (
+ <span class="text-xs text-base-content">
+ {billing ? getBillingAdminTrialStatus(billing) : unreadLabel(org.org_id)}
+ </span>
+ );
+ },
},
- },
- {
- key: 'trial',
- label: 'Trial',
- hiddenOnMobile: true,
- render: (org) => {
- const billing = props.billingByOrgID[(org.org_id || '').trim()];
- return (
- <span class="text-xs text-base-content">{getBillingAdminTrialStatus(billing)}</span>
- );
+ {
+ key: 'stripeCustomer',
+ label: 'Stripe Customer',
+ hiddenOnMobile: true,
+ render: (org) => {
+ const billing = props.billingByOrgID[(org.org_id || '').trim()];
+ const cellValue = billing ? stripeCustomerCell(billing) : unreadLabel(org.org_id);
+ return (
+ <span class="font-mono text-xs text-base-content" title={cellValue}>
+ {cellValue}
+ </span>
+ );
+ },
},
- },
- {
- key: 'stripeCustomer',
- label: 'Stripe Customer',
- hiddenOnMobile: true,
- render: (org) => {
- const billing = props.billingByOrgID[(org.org_id || '').trim()];
- const cellValue = stripeCustomerCell(billing);
- return (
- <span class="font-mono text-xs text-base-content" title={cellValue}>
- {cellValue}
- </span>
- );
+ {
+ key: 'actions',
+ label: 'Actions',
+ align: 'right',
+ render: (org) => {
+ const orgID = (org.org_id || '').trim();
+ const billing = props.billingByOrgID[orgID];
+ const currentSubState = (billing?.subscription_state || '').toLowerCase() || 'unknown';
+ return (
+ <div class="inline-flex flex-col sm:flex-row sm:items-center gap-2">
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => {
+ props.onSuspendOrganization(orgID);
+ }}
+ disabled={actionsDisabled(orgID) || currentSubState === 'suspended'}
+ >
+ Suspend Org
+ </Button>
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={() => {
+ props.onActivateOrganization(orgID);
+ }}
+ disabled={actionsDisabled(orgID) || currentSubState === 'active'}
+ >
+ Activate Org
+ </Button>
+ </div>
+ );
+ },
},
- },
- {
- key: 'actions',
- label: 'Actions',
- align: 'right',
- render: (org) => {
- const orgID = (org.org_id || '').trim();
- const billing = props.billingByOrgID[orgID];
- const currentSubState = (billing?.subscription_state || '').toLowerCase() || 'unknown';
- return (
- <div class="inline-flex flex-col sm:flex-row sm:items-center gap-2">
- <Button
- variant="secondary"
- size="sm"
- onClick={() => {
- props.onSuspendOrganization(orgID);
- }}
- disabled={
- props.savingByOrgID[orgID] ||
- props.billingLoadingByOrgID[orgID] ||
- currentSubState === 'suspended'
- }
- >
- Suspend Org
- </Button>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => {
- props.onActivateOrganization(orgID);
- }}
- disabled={
- props.savingByOrgID[orgID] ||
- props.billingLoadingByOrgID[orgID] ||
- currentSubState === 'active'
+ ]}
+ keyExtractor={(org) => org.org_id}
+ isRowExpanded={(org) => props.expandedOrgID === (org.org_id || '').trim()}
+ expandedRender={(org) => {
+ const orgID = (org.org_id || '').trim();
+ return (
+ <div class="px-3 pb-3 bg-surface-alt">
+ <div class="rounded-md border border-border bg-surface-alt p-3">
+ <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-2">
+ <div class="text-xs font-semibold text-muted">Billing state JSON</div>
+ <Button
+ variant="secondary"
+ size="xs"
+ disabled={props.billingLoadingByOrgID[orgID] || props.savingByOrgID[orgID]}
+ onClick={() => {
+ props.onReloadOrganization(orgID);
+ }}
+ >
+ Reload
+ </Button>
+ </div>
+ <Show
+ when={props.billingByOrgID[orgID]}
+ fallback={
+ <p role="status" class="text-sm text-muted">
+ {props.billingErrorByOrgID[orgID] || 'Loading billing state...'}
+ </p>
}
>
- Activate Org
- </Button>
+ <pre class="text-xs overflow-x-auto whitespace-pre-wrap break-words font-mono text-base-content">
+ {JSON.stringify(props.billingByOrgID[orgID], null, 2)}
+ </pre>
+ </Show>
</div>
- );
- },
- },
- ]}
- keyExtractor={(org) => org.org_id}
- isRowExpanded={(org) => props.expandedOrgID === (org.org_id || '').trim()}
- expandedRender={(org) => {
- const orgID = (org.org_id || '').trim();
- return (
- <div class="px-3 pb-3 bg-surface-alt">
- <div class="rounded-md border border-border bg-surface-alt p-3">
- <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-2">
- <div class="text-xs font-semibold text-muted">Billing state JSON</div>
- <Button
- variant="secondary"
- size="xs"
- onClick={() => {
- props.onReloadOrganization(orgID);
- }}
- >
- Reload
- </Button>
- </div>
- <pre class="text-xs overflow-x-auto whitespace-pre-wrap font-mono text-base-content">
- {JSON.stringify(props.billingByOrgID[orgID] ?? { loading: true }, null, 2)}
- </pre>
</div>
- </div>
- );
- }}
- />
-);
+ );
+ }}
+ />
+ );
+};
diff --git a/frontend-modern/src/components/Settings/BillingAdminPanel.tsx b/frontend-modern/src/components/Settings/BillingAdminPanel.tsx
index f83ab057d6..227de2370d 100644
--- a/frontend-modern/src/components/Settings/BillingAdminPanel.tsx
+++ b/frontend-modern/src/components/Settings/BillingAdminPanel.tsx
@@ -38,33 +38,40 @@ export const BillingAdminPanel: Component = () => {
bodyClass="space-y-4"
>
<Show when={state.orgsError()}>
- <div class="rounded-md border border-red-200 dark:border-red-900/25 bg-red-50 dark:bg-red-900/25 p-3 text-sm text-red-800 dark:text-red-200">
+ <div
+ role="alert"
+ class="rounded-md border border-red-200 dark:border-red-900/25 bg-red-50 dark:bg-red-900/25 p-3 text-sm text-red-800 dark:text-red-200"
+ >
{state.orgsError()}
</div>
</Show>
- <div class="mt-4">
- <BillingAdminOrganizationsTable
- orgs={state.orgs()}
- isLoading={state.loadingOrgs()}
- billingByOrgID={state.billingByOrgID()}
- billingLoadingByOrgID={state.billingLoadingByOrgID()}
- savingByOrgID={state.savingByOrgID()}
- expandedOrgID={state.expandedOrgID()}
- onToggleOrganization={(orgID) => {
- void state.toggleExpandedOrganization(orgID);
- }}
- onSuspendOrganization={(orgID) => {
- void state.updateSubscriptionState(orgID, 'suspended');
- }}
- onActivateOrganization={(orgID) => {
- void state.updateSubscriptionState(orgID, 'active');
- }}
- onReloadOrganization={(orgID) => {
- void state.reloadOrganization(orgID);
- }}
- />
- </div>
+ <Show when={!state.orgsError()}>
+ <div class="mt-4" aria-busy={state.loadingOrgs()}>
+ <BillingAdminOrganizationsTable
+ orgs={state.orgs()}
+ isLoading={state.loadingOrgs()}
+ billingByOrgID={state.billingByOrgID()}
+ billingLoadingByOrgID={state.billingLoadingByOrgID()}
+ billingErrorByOrgID={state.billingErrorByOrgID()}
+ canManageBilling={state.canManageBilling()}
+ savingByOrgID={state.savingByOrgID()}
+ expandedOrgID={state.expandedOrgID()}
+ onToggleOrganization={(orgID) => {
+ void state.toggleExpandedOrganization(orgID);
+ }}
+ onSuspendOrganization={(orgID) => {
+ void state.updateSubscriptionState(orgID, 'suspended');
+ }}
+ onActivateOrganization={(orgID) => {
+ void state.updateSubscriptionState(orgID, 'active');
+ }}
+ onReloadOrganization={(orgID) => {
+ void state.reloadOrganization(orgID);
+ }}
+ />
+ </div>
+ </Show>
</SettingsPanel>
</Show>
);
diff --git a/frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx
index 8dd5831f94..849dd36016 100644
--- a/frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx
@@ -34,6 +34,7 @@ vi.mock('@/stores/notifications', () => ({
}));
vi.mock('@/stores/sessionPresentationPolicy', () => ({
+ presentationPolicyIsReadOnly: () => false,
presentationPolicyHidesOrganizationSurfaces: (...args: unknown[]) =>
presentationPolicyHidesOrganizationSurfacesMock(...args),
}));
diff --git a/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx b/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx
new file mode 100644
index 0000000000..bf495cd998
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx
@@ -0,0 +1,437 @@
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { BillingAdminPanel } from '../BillingAdminPanel';
+import {
+ BILLING_ADMIN_READ_ERROR,
+ BILLING_ADMIN_UNCONFIRMED_CHANGE,
+ useBillingAdminPanelState,
+} from '../useBillingAdminPanelState';
+import type { BillingState } from '@/api/billingAdmin';
+
+const mocks = vi.hoisted(() => ({
+ list: vi.fn(),
+ get: vi.fn(),
+ put: vi.fn(),
+ success: vi.fn(),
+ error: vi.fn(),
+ log: vi.fn(),
+ hosted: vi.fn(),
+ multi: vi.fn(),
+ hidden: vi.fn(),
+ readOnly: vi.fn(),
+}));
+vi.mock('@/api/billingAdmin', () => ({
+ BillingAdminAPI: {
+ listOrganizations: mocks.list,
+ getBillingState: mocks.get,
+ putBillingState: mocks.put,
+ },
+}));
+vi.mock('@/stores/license', () => ({
+ isHostedModeEnabled: mocks.hosted,
+ isMultiTenantEnabled: mocks.multi,
+}));
+vi.mock('@/stores/sessionPresentationPolicy', () => ({
+ presentationPolicyHidesOrganizationSurfaces: mocks.hidden,
+ presentationPolicyIsReadOnly: mocks.readOnly,
+}));
+vi.mock('@/stores/notifications', () => ({
+ notificationStore: { success: mocks.success, error: mocks.error },
+}));
+vi.mock('@/utils/logger', () => ({ logger: { error: mocks.log } }));
+
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<T>((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+};
+const org = (id = 'org-a') => ({
+ org_id: id,
+ display_name: `Organization ${id}`,
+ owner_user_id: 'owner',
+ created_at: '2026-01-01',
+ suspended: false,
+ soft_deleted: false,
+});
+const billing = (name = 'active'): BillingState => ({
+ subscription_state: name,
+ capabilities: ['multi_tenant'],
+ limits: { max_nodes: 20 },
+ meters_enabled: [],
+});
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+const signalAt = (mock: typeof mocks.list, call = 0, position = 0) =>
+ (mock.mock.calls[call][position] as { signal: AbortSignal }).signal;
+const mountState = () => {
+ let state!: ReturnType<typeof useBillingAdminPanelState>;
+ const view = render(() => {
+ state = useBillingAdminPanelState();
+ return null;
+ });
+ return { state, unmount: view.unmount };
+};
+let setHosted!: (v: boolean) => void;
+let setMulti!: (v: boolean) => void;
+let setHidden!: (v: boolean) => void;
+let setReadOnly!: (v: boolean) => void;
+
+beforeEach(() => {
+ Object.values(mocks).forEach((mock) => mock.mockReset());
+ const [hosted, hostedSetter] = createSignal(true);
+ setHosted = hostedSetter;
+ const [multi, multiSetter] = createSignal(true);
+ setMulti = multiSetter;
+ const [hidden, hiddenSetter] = createSignal(false);
+ setHidden = hiddenSetter;
+ const [readOnly, readOnlySetter] = createSignal(false);
+ setReadOnly = readOnlySetter;
+ mocks.hosted.mockImplementation(hosted);
+ mocks.multi.mockImplementation(multi);
+ mocks.hidden.mockImplementation(hidden);
+ mocks.readOnly.mockImplementation(readOnly);
+ mocks.list.mockResolvedValue([org()]);
+ mocks.get.mockResolvedValue(billing());
+ mocks.put.mockImplementation(async (_id, payload) => payload);
+});
+afterEach(cleanup);
+
+describe('Billing Admin accepted inventory and billing reads', () => {
+ it('disables both actions until the actual row read succeeds', async () => {
+ const pending = deferred<BillingState>();
+ mocks.get.mockReturnValueOnce(pending.promise);
+ render(() => <BillingAdminPanel />);
+ await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(1));
+ expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Activate Org' })).toBeDisabled();
+ expect(screen.queryByText('N/A')).not.toBeInTheDocument();
+ pending.resolve(billing());
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeEnabled());
+ });
+
+ it('removes the former inventory on refresh and distinguishes failure from an empty inventory', async () => {
+ render(() => <BillingAdminPanel />);
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeEnabled());
+ const pending = deferred<unknown>();
+ mocks.list.mockReturnValueOnce(pending.promise);
+ await fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
+ expect(screen.queryByText('Organization org-a')).not.toBeInTheDocument();
+ pending.reject(new Error('SYNTHETIC PRIVATE BACKEND DETAIL'));
+ await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Failed to load'));
+ expect(screen.queryByText(/No organizations/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/SYNTHETIC PRIVATE/)).not.toBeInTheDocument();
+ expect(mocks.error).not.toHaveBeenCalled();
+ mocks.list.mockResolvedValueOnce([]);
+ await fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
+ await waitFor(() => expect(screen.getByText(/No organizations/)).toBeInTheDocument());
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(mocks.get).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ null,
+ {},
+ [org(), org()],
+ [{ ...org(), org_id: ' ' }],
+ [{ ...org(), org_id: ' org-a' }],
+ ])('does not turn malformed inventory %j into usable rows', async (data) => {
+ mocks.list.mockResolvedValueOnce(data);
+ const { state } = mountState();
+ await settle();
+ expect(state.orgsError()).toBeTruthy();
+ expect(state.orgs()).toEqual([]);
+ expect(mocks.get).not.toHaveBeenCalled();
+ });
+
+ it('keeps a failed row unavailable without automatic retries as other rows finish, and offers a read-only reload', async () => {
+ const other = deferred<BillingState>();
+ mocks.list.mockResolvedValue([org(), org('org-b')]);
+ mocks.get
+ .mockRejectedValueOnce(new Error('SYNTHETIC PRIVATE BILLING DETAIL'))
+ .mockReturnValueOnce(other.promise)
+ .mockResolvedValue(billing());
+ render(() => <BillingAdminPanel />);
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent(BILLING_ADMIN_READ_ERROR),
+ );
+ other.resolve(billing());
+ await settle();
+ await settle();
+ expect(mocks.get).toHaveBeenCalledTimes(2);
+ expect(screen.queryByText(/SYNTHETIC PRIVATE/)).not.toBeInTheDocument();
+ await fireEvent.click(screen.getByRole('button', { name: /Organization org-a/ }));
+ expect(screen.getByRole('status')).toHaveTextContent(BILLING_ADMIN_READ_ERROR);
+ expect(screen.queryByText(/"loading": true/)).not.toBeInTheDocument();
+ const before = mocks.put.mock.calls.length;
+ await fireEvent.click(
+ screen.getByRole('button', { name: 'Reload billing for Organization org-a' }),
+ );
+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument());
+ expect(mocks.get).toHaveBeenCalledTimes(3);
+ expect(mocks.put).toHaveBeenCalledTimes(before);
+ });
+
+ it.each([
+ null,
+ {},
+ { ...billing(), capabilities: null },
+ { ...billing(), limits: [] },
+ { ...billing(), limits: { users: NaN } },
+ { ...billing(), meters_enabled: 'all' },
+ { ...billing(), subscription_state: '' },
+ ])('rejects malformed billing %j rather than enabling a write', async (data) => {
+ mocks.get.mockResolvedValueOnce(data);
+ const { state } = mountState();
+ await settle();
+ expect(state.billingErrorByOrgID()['org-a']).toBe(BILLING_ADMIN_READ_ERROR);
+ expect(state.billingByOrgID()['org-a']).toBeUndefined();
+ await state.updateSubscriptionState('org-a', 'suspended');
+ expect(mocks.put).not.toHaveBeenCalled();
+ expect(mocks.get).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['success', 'failure'])(
+ 'ignores an obsolete row reload %s without ending its replacement spinner',
+ async (outcome) => {
+ const old = deferred<BillingState>();
+ const current = deferred<BillingState>();
+ mocks.get.mockReturnValueOnce(old.promise).mockReturnValueOnce(current.promise);
+ const { state } = mountState();
+ await settle();
+ const reload = state.reloadOrganization('org-a');
+ expect(signalAt(mocks.get, 0, 1).aborted).toBe(true);
+ if (outcome === 'success') old.resolve(billing('obsolete'));
+ else old.reject(new Error('obsolete'));
+ await settle();
+ expect(state.billingLoadingByOrgID()['org-a']).toBe(true);
+ expect(state.billingByOrgID()['org-a']).toBeUndefined();
+ expect(state.billingErrorByOrgID()['org-a']).toBeUndefined();
+ expect(mocks.log).not.toHaveBeenCalled();
+ current.resolve(billing('trialing'));
+ await reload;
+ expect(state.billingByOrgID()['org-a']?.subscription_state).toBe('trialing');
+ },
+ );
+
+ it('ignores obsolete list success and failure across repeated refreshes', async () => {
+ const first = deferred<ReturnType<typeof org>[]>();
+ const second = deferred<ReturnType<typeof org>[]>();
+ mocks.list
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise)
+ .mockResolvedValueOnce([org('current')]);
+ const { state } = mountState();
+ const middle = state.refreshOrganizations();
+ await state.refreshOrganizations();
+ expect(signalAt(mocks.list, 0).aborted).toBe(true);
+ expect(signalAt(mocks.list, 1).aborted).toBe(true);
+ first.resolve([org('obsolete')]);
+ second.reject(new Error('obsolete'));
+ await middle;
+ await settle();
+ expect(state.orgs().map((o) => o.org_id)).toEqual(['current']);
+ expect(state.orgsError()).toBeNull();
+ expect(mocks.log).not.toHaveBeenCalled();
+ expect(mocks.get.mock.calls.map((c) => c[0])).toEqual(['current']);
+ });
+
+ it('does not let a previous inventory billing completion overwrite a new row with the same ID', async () => {
+ const old = deferred<BillingState>();
+ const current = deferred<BillingState>();
+ mocks.get.mockReturnValueOnce(old.promise).mockReturnValueOnce(current.promise);
+ const { state } = mountState();
+ await settle();
+ const refreshing = state.refreshOrganizations();
+ await settle();
+ current.resolve(billing('trialing'));
+ await refreshing;
+ old.resolve(billing('obsolete'));
+ await settle();
+ expect(state.billingByOrgID()['org-a']?.subscription_state).toBe('trialing');
+ expect(signalAt(mocks.get, 0, 1).aborted).toBe(true);
+ });
+
+ it.each(['hosted', 'multi', 'hidden'])(
+ 'clears and invalidates %s withdrawal, then reads afresh on re-entry',
+ async (kind) => {
+ const old = deferred<ReturnType<typeof org>[]>();
+ mocks.list.mockReturnValueOnce(old.promise);
+ const { state } = mountState();
+ const withdraw = () =>
+ kind === 'hosted' ? setHosted(false) : kind === 'multi' ? setMulti(false) : setHidden(true);
+ const restore = () =>
+ kind === 'hosted' ? setHosted(true) : kind === 'multi' ? setMulti(true) : setHidden(false);
+ withdraw();
+ await settle();
+ expect(state.orgs()).toEqual([]);
+ expect(state.hostedEnabled()).toBe(false);
+ expect(signalAt(mocks.list).aborted).toBe(true);
+ restore();
+ await settle();
+ old.resolve([org('obsolete')]);
+ await settle();
+ expect(state.orgs().map((o) => o.org_id)).toEqual(['org-a']);
+ expect(mocks.get.mock.calls.map((c) => c[0])).toEqual(['org-a']);
+ },
+ );
+
+ it('bounds prefetch to six concurrent reads and stops the old pool from admitting queued rows', async () => {
+ mocks.list.mockResolvedValue(Array.from({ length: 10 }, (_, i) => org(`org-${i}`)));
+ const pending = Array.from({ length: 6 }, () => deferred<BillingState>());
+ let n = 0;
+ mocks.get.mockImplementation(() => pending[n++].promise);
+ const { state } = mountState();
+ await settle();
+ expect(mocks.get).toHaveBeenCalledTimes(6);
+ setHosted(false);
+ await settle();
+ pending.forEach((p) => p.resolve(billing()));
+ await settle();
+ await settle();
+ expect(mocks.get).toHaveBeenCalledTimes(6);
+ expect(state.orgs()).toEqual([]);
+ mocks.get.mock.calls.forEach((_c, i) => expect(signalAt(mocks.get, i, 1).aborted).toBe(true));
+ });
+
+ it('disposal aborts reads, clears retained snapshots, and ignores later errors without notifications', async () => {
+ const pending = deferred<BillingState>();
+ mocks.get.mockReturnValueOnce(pending.promise);
+ const { state, unmount } = mountState();
+ await settle();
+ unmount();
+ expect(signalAt(mocks.get, 0, 1).aborted).toBe(true);
+ pending.reject(new Error('late'));
+ await settle();
+ expect(state.orgs()).toEqual([]);
+ expect(state.billingByOrgID()).toEqual({});
+ expect(mocks.log).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ await state.refreshOrganizations();
+ expect(mocks.list).toHaveBeenCalledTimes(1);
+ });
+
+ it('disposal while listing cannot launch a billing read', async () => {
+ const pending = deferred<ReturnType<typeof org>[]>();
+ mocks.list.mockReturnValueOnce(pending.promise);
+ const { unmount } = mountState();
+ unmount();
+ pending.resolve([org()]);
+ await settle();
+ expect(mocks.get).not.toHaveBeenCalled();
+ expect(signalAt(mocks.list).aborted).toBe(true);
+ });
+
+ it('keeps opaque organization IDs separate from object prototypes', async () => {
+ mocks.list.mockResolvedValue(['__proto__', 'constructor', 'toString'].map(org));
+ const { state } = mountState();
+ await settle();
+ expect(mocks.get).toHaveBeenCalledTimes(3);
+ for (const id of ['__proto__', 'constructor', 'toString'])
+ expect(state.billingByOrgID()[id]?.subscription_state).toBe('active');
+ await state.updateSubscriptionState('__proto__', 'suspended');
+ expect(mocks.put.mock.calls[0][0]).toBe('__proto__');
+ expect(Object.prototype).not.toHaveProperty('subscription_state');
+ });
+});
+
+describe('Billing Admin writes require the current accepted snapshot', () => {
+ it('does not fetch or write implicitly for an unread or unknown organization', async () => {
+ const pending = deferred<BillingState>();
+ mocks.get.mockReturnValueOnce(pending.promise);
+ const { state } = mountState();
+ await settle();
+ await state.updateSubscriptionState('org-a', 'suspended');
+ await state.updateSubscriptionState('foreign', 'active');
+ expect(mocks.get).toHaveBeenCalledTimes(1);
+ expect(mocks.put).not.toHaveBeenCalled();
+ pending.resolve(billing());
+ });
+
+ it('deduplicates writes, preserves all saved billing fields and refuses a row reload while saving', async () => {
+ const current = {
+ ...billing(),
+ plan_version: 'cloud_power',
+ trial_started_at: 10,
+ trial_ends_at: 20,
+ stripe_customer_id: 'cus_fixture',
+ stripe_subscription_id: 'sub_fixture',
+ stripe_price_id: 'price_fixture',
+ };
+ mocks.get.mockResolvedValueOnce(current);
+ const pending = deferred<BillingState>();
+ mocks.put.mockReturnValueOnce(pending.promise);
+ const { state } = mountState();
+ await settle();
+ const writing = state.updateSubscriptionState('org-a', 'suspended');
+ await state.updateSubscriptionState('org-a', 'suspended');
+ await state.reloadOrganization('org-a');
+ expect(mocks.put).toHaveBeenCalledTimes(1);
+ expect(mocks.get).toHaveBeenCalledTimes(1);
+ expect(mocks.put.mock.calls[0][1]).toEqual({ ...current, subscription_state: 'suspended' });
+ pending.resolve({ ...current, subscription_state: 'suspended' });
+ await writing;
+ expect(state.savingByOrgID()['org-a']).toBe(false);
+ expect(mocks.success).toHaveBeenCalledTimes(1);
+ await state.updateSubscriptionState('org-a', 'suspended');
+ expect(mocks.put).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['rejected', 'malformed', 'mismatched'])(
+ 'withdraws the snapshot after an unconfirmed %s update without retrying or claiming rollback',
+ async (kind) => {
+ if (kind === 'rejected')
+ mocks.put.mockRejectedValueOnce(new Error('SYNTHETIC PRIVATE UPDATE DETAIL'));
+ else mocks.put.mockResolvedValueOnce(kind === 'mismatched' ? billing('active') : {});
+ const { state } = mountState();
+ await settle();
+ await state.updateSubscriptionState('org-a', 'suspended');
+ expect(state.billingByOrgID()['org-a']).toBeUndefined();
+ expect(state.billingErrorByOrgID()['org-a']).toBe(BILLING_ADMIN_UNCONFIRMED_CHANGE);
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ await state.updateSubscriptionState('org-a', 'active');
+ expect(mocks.put).toHaveBeenCalledTimes(1);
+ expect(mocks.get).toHaveBeenCalledTimes(1);
+ mocks.get.mockResolvedValueOnce(billing('suspended'));
+ await state.reloadOrganization('org-a');
+ expect(state.billingErrorByOrgID()['org-a']).toBeUndefined();
+ expect(state.billingByOrgID()['org-a']?.subscription_state).toBe('suspended');
+ },
+ );
+
+ it.each(['refresh', 'read-only', 'dispose'])(
+ 'invalidates a pending write on %s without applying its completion to the new snapshot',
+ async (kind) => {
+ const pending = deferred<BillingState>();
+ mocks.put.mockReturnValueOnce(pending.promise);
+ const { state, unmount } = mountState();
+ await settle();
+ const writing = state.updateSubscriptionState('org-a', 'suspended');
+ if (kind === 'refresh') {
+ mocks.list.mockResolvedValueOnce([org('org-b')]);
+ await state.refreshOrganizations();
+ } else if (kind === 'read-only') {
+ setReadOnly(true);
+ await settle();
+ } else unmount();
+ expect(signalAt(mocks.put, 0, 2).aborted).toBe(true);
+ pending.resolve(billing('suspended'));
+ await writing;
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ if (kind === 'dispose') expect(state.billingByOrgID()['org-a']).toBeUndefined();
+ else if (kind === 'refresh') {
+ expect(state.billingByOrgID()['org-a']).toBeUndefined();
+ await state.updateSubscriptionState('org-a', 'suspended');
+ } else {
+ expect(state.billingByOrgID()['org-a']?.subscription_state).toBe('active');
+ await state.updateSubscriptionState('org-a', 'suspended');
+ }
+ expect(mocks.put).toHaveBeenCalledTimes(1);
+ },
+ );
+});
diff --git a/frontend-modern/src/components/Settings/useBillingAdminPanelState.ts b/frontend-modern/src/components/Settings/useBillingAdminPanelState.ts
index bfd812a25c..a70e77048a 100644
--- a/frontend-modern/src/components/Settings/useBillingAdminPanelState.ts
+++ b/frontend-modern/src/components/Settings/useBillingAdminPanelState.ts
@@ -1,4 +1,4 @@
-import { createEffect, createMemo, createSignal } from 'solid-js';
+import { batch, createEffect, createMemo, createSignal, on, onCleanup } from 'solid-js';
import {
BillingAdminAPI,
type BillingState,
@@ -6,12 +6,49 @@ import {
} from '@/api/billingAdmin';
import { isHostedModeEnabled, isMultiTenantEnabled } from '@/stores/license';
import { notificationStore } from '@/stores/notifications';
-import { presentationPolicyHidesOrganizationSurfaces } from '@/stores/sessionPresentationPolicy';
+import {
+ presentationPolicyHidesOrganizationSurfaces,
+ presentationPolicyIsReadOnly,
+} from '@/stores/sessionPresentationPolicy';
import { logger } from '@/utils/logger';
import { getBillingAdminStateUpdateSuccessMessage } from '@/utils/licensePresentation';
-import { getOrganizationSettingsLoadErrorMessage as getOrganizationSettingsPanelLoadErrorMessage } from '@/utils/organizationSettingsPresentation';
+import { getOrganizationSettingsLoadErrorMessage } from '@/utils/organizationSettingsPresentation';
export type BillingStateCache = Record<string, BillingState | undefined>;
+const emptyRecord = <T>(): Record<string, T> => Object.create(null);
+const withEntry = <T>(entries: Record<string, T>, key: string, value: T): Record<string, T> =>
+ Object.assign(emptyRecord<T>(), entries, { [key]: value });
+export const BILLING_ADMIN_READ_ERROR =
+ 'Billing state is unavailable. Reload it before making changes.';
+export const BILLING_ADMIN_UNCONFIRMED_CHANGE =
+ 'The subscription change could not be confirmed. Reload billing state before making another change.';
+
+const isBillingState = (value: unknown): value is BillingState => {
+ if (!value || typeof value !== 'object') return false;
+ const state = value as BillingState;
+ const isStringArray = (items: unknown) =>
+ Array.isArray(items) && items.every((item) => typeof item === 'string');
+ return (
+ typeof state.subscription_state === 'string' &&
+ state.subscription_state.trim().length > 0 &&
+ isStringArray(state.capabilities) &&
+ !!state.limits &&
+ typeof state.limits === 'object' &&
+ !Array.isArray(state.limits) &&
+ Object.values(state.limits).every(
+ (limit) => typeof limit === 'number' && Number.isFinite(limit),
+ ) &&
+ (state.meters_enabled === undefined || isStringArray(state.meters_enabled)) &&
+ ['plan_version', 'stripe_customer_id', 'stripe_subscription_id', 'stripe_price_id'].every(
+ (key) =>
+ state[key as keyof BillingState] === undefined ||
+ typeof state[key as keyof BillingState] === 'string',
+ ) &&
+ [state.trial_started_at, state.trial_ends_at].every(
+ (time) => time == null || (typeof time === 'number' && Number.isFinite(time)),
+ )
+ );
+};
async function promisePool<T>(items: T[], concurrency: number, fn: (item: T) => Promise<void>) {
if (items.length === 0) return;
@@ -32,12 +69,18 @@ export function useBillingAdminPanelState() {
const [orgs, setOrgs] = createSignal<HostedOrganizationSummary[]>([]);
const [loadingOrgs, setLoadingOrgs] = createSignal(false);
const [orgsError, setOrgsError] = createSignal<string | null>(null);
- const [billingByOrgID, setBillingByOrgID] = createSignal<BillingStateCache>({});
- const [billingLoadingByOrgID, setBillingLoadingByOrgID] = createSignal<Record<string, boolean>>(
- {},
- );
- const [savingByOrgID, setSavingByOrgID] = createSignal<Record<string, boolean>>({});
+ const [billingByOrgID, setBillingByOrgID] = createSignal<BillingStateCache>(emptyRecord());
+ const [billingLoadingByOrgID, setBillingLoadingByOrgID] =
+ createSignal<Record<string, boolean>>(emptyRecord());
+ const [billingErrorByOrgID, setBillingErrorByOrgID] =
+ createSignal<Record<string, string>>(emptyRecord());
+ const [savingByOrgID, setSavingByOrgID] = createSignal<Record<string, boolean>>(emptyRecord());
const [expandedOrgID, setExpandedOrgID] = createSignal<string | null>(null);
+ let generation = 0;
+ let disposed = false;
+ let listController: AbortController | undefined;
+ const billingReads = new Map<string, AbortController>();
+ const billingWrites = new Map<string, AbortController>();
const hostedEnabled = createMemo(
() =>
@@ -45,118 +88,206 @@ export function useBillingAdminPanelState() {
isHostedModeEnabled() &&
!presentationPolicyHidesOrganizationSurfaces(),
);
+ const canManageBilling = () => hostedEnabled() && !presentationPolicyIsReadOnly();
+ const isCurrent = (request: number) => !disposed && request === generation && hostedEnabled();
+ const hasCurrentOrganization = (orgID: string) =>
+ !loadingOrgs() && !orgsError() && orgs().some((org) => org.org_id === orgID);
- const setBillingLoading = (orgID: string, value: boolean) => {
- setBillingLoadingByOrgID((prev) => ({ ...prev, [orgID]: value }));
+ const invalidateRequests = () => {
+ generation += 1;
+ listController?.abort();
+ listController = undefined;
+ for (const controller of billingReads.values()) controller.abort();
+ for (const controller of billingWrites.values()) controller.abort();
+ billingReads.clear();
+ billingWrites.clear();
};
- const setSaving = (orgID: string, value: boolean) => {
- setSavingByOrgID((prev) => ({ ...prev, [orgID]: value }));
+ const clearSnapshot = () => {
+ setOrgs([]);
+ setOrgsError(null);
+ setBillingByOrgID(emptyRecord());
+ setBillingLoadingByOrgID(emptyRecord());
+ setBillingErrorByOrgID(emptyRecord());
+ setSavingByOrgID(emptyRecord());
+ setExpandedOrgID(null);
};
- const loadOrganizations = async () => {
- setLoadingOrgs(true);
- setOrgsError(null);
+ const ensureBillingState = async (orgID: string, request = generation) => {
+ if (
+ !isCurrent(request) ||
+ !hasCurrentOrganization(orgID) ||
+ billingByOrgID()[orgID] ||
+ billingReads.has(orgID) ||
+ billingWrites.has(orgID) ||
+ billingErrorByOrgID()[orgID]
+ )
+ return;
+
+ const controller = new AbortController();
+ billingReads.set(orgID, controller);
+ const readIsCurrent = () =>
+ isCurrent(request) && hasCurrentOrganization(orgID) && billingReads.get(orgID) === controller;
+ setBillingLoadingByOrgID((prev) => withEntry(prev, orgID, true));
try {
- const next = await BillingAdminAPI.listOrganizations();
- setOrgs(next ?? []);
+ const state = await BillingAdminAPI.getBillingState(orgID, { signal: controller.signal });
+ if (!readIsCurrent()) return;
+ if (!isBillingState(state)) throw new Error('Billing state returned invalid data');
+ setBillingByOrgID((prev) => withEntry(prev, orgID, state));
} catch (err) {
- logger.error('Failed to list hosted organizations', err);
- const msg = err instanceof Error ? err.message : '';
- const errorMessage = getOrganizationSettingsPanelLoadErrorMessage(msg, 'billing-admin');
- setOrgsError(errorMessage);
- notificationStore.error(errorMessage);
+ if (!readIsCurrent()) return;
+ logger.error('Failed to fetch billing state', { orgID, err });
+ setBillingErrorByOrgID((prev) => withEntry(prev, orgID, BILLING_ADMIN_READ_ERROR));
} finally {
- setLoadingOrgs(false);
+ if (readIsCurrent()) {
+ billingReads.delete(orgID);
+ setBillingLoadingByOrgID((prev) => withEntry(prev, orgID, false));
+ }
}
};
- const ensureBillingState = async (orgID: string): Promise<BillingState | null> => {
- const cached = billingByOrgID()[orgID];
- if (cached) return cached;
-
- if (billingLoadingByOrgID()[orgID]) {
- return null;
- }
+ const refreshOrganizations = async () => {
+ if (disposed) return;
+ invalidateRequests();
+ const request = generation;
+ batch(() => {
+ clearSnapshot();
+ setLoadingOrgs(hostedEnabled());
+ });
+ if (!hostedEnabled()) return;
- setBillingLoading(orgID, true);
+ const controller = new AbortController();
+ listController = controller;
+ let next: HostedOrganizationSummary[];
try {
- const state = await BillingAdminAPI.getBillingState(orgID);
- setBillingByOrgID((prev) => ({ ...prev, [orgID]: state }));
- return state;
+ next = await BillingAdminAPI.listOrganizations({ signal: controller.signal });
+ if (!isCurrent(request)) return;
+ if (
+ !Array.isArray(next) ||
+ next.some(
+ (org) =>
+ !org ||
+ typeof org.org_id !== 'string' ||
+ !org.org_id.trim() ||
+ org.org_id !== org.org_id.trim(),
+ ) ||
+ new Set(next.map((org) => org.org_id)).size !== next.length
+ )
+ throw new Error('Hosted organizations returned invalid data');
+ setOrgs(next);
} catch (err) {
- logger.error('Failed to fetch billing state', { orgID, err });
- return null;
+ if (!isCurrent(request)) return;
+ logger.error('Failed to list hosted organizations', err);
+ setOrgsError(getOrganizationSettingsLoadErrorMessage('', 'billing-admin'));
+ return;
} finally {
- setBillingLoading(orgID, false);
+ if (isCurrent(request)) {
+ listController = undefined;
+ setLoadingOrgs(false);
+ }
}
+
+ // One bounded prefetch per accepted inventory, not a reactive retry loop.
+ // Invalidation also prevents the old pool from admitting its queued rows.
+ await promisePool(next, 6, async (org) => {
+ await ensureBillingState(org.org_id, request);
+ });
};
const updateSubscriptionState = async (orgID: string, nextState: 'suspended' | 'active') => {
- setSaving(orgID, true);
+ const request = generation;
+ const current = billingByOrgID()[orgID];
+ if (
+ !isCurrent(request) ||
+ !canManageBilling() ||
+ !hasCurrentOrganization(orgID) ||
+ !current ||
+ billingReads.has(orgID) ||
+ billingWrites.has(orgID) ||
+ billingErrorByOrgID()[orgID] ||
+ current.subscription_state.toLowerCase() === nextState
+ )
+ return;
+
+ const controller = new AbortController();
+ billingWrites.set(orgID, controller);
+ const writeIsCurrent = () =>
+ isCurrent(request) &&
+ canManageBilling() &&
+ hasCurrentOrganization(orgID) &&
+ billingWrites.get(orgID) === controller;
+ setSavingByOrgID((prev) => withEntry(prev, orgID, true));
try {
- const current =
- (await ensureBillingState(orgID)) ?? (await BillingAdminAPI.getBillingState(orgID));
const planVersion = current.plan_version?.trim() || undefined;
const payload: BillingState = {
...current,
subscription_state: nextState,
- capabilities: Array.isArray(current.capabilities) ? current.capabilities : [],
- limits: current.limits ?? {},
- meters_enabled: Array.isArray(current.meters_enabled) ? current.meters_enabled : [],
...(planVersion ? { plan_version: planVersion } : {}),
};
-
- const saved = await BillingAdminAPI.putBillingState(orgID, payload);
- setBillingByOrgID((prev) => ({ ...prev, [orgID]: saved }));
+ const saved = await BillingAdminAPI.putBillingState(orgID, payload, {
+ signal: controller.signal,
+ });
+ if (!writeIsCurrent()) return;
+ if (!isBillingState(saved) || saved.subscription_state.toLowerCase() !== nextState) {
+ throw new Error('Billing update did not confirm the requested subscription state');
+ }
+ setBillingByOrgID((prev) => withEntry(prev, orgID, saved));
notificationStore.success(getBillingAdminStateUpdateSuccessMessage(nextState), 2500);
} catch (err) {
+ if (!writeIsCurrent()) return;
logger.error('Failed to update billing state', { orgID, err });
- const msg = err instanceof Error ? err.message : 'Failed to update billing state';
- notificationStore.error(msg);
+ batch(() => {
+ setBillingByOrgID((prev) => withEntry(prev, orgID, undefined));
+ setBillingErrorByOrgID((prev) => withEntry(prev, orgID, BILLING_ADMIN_UNCONFIRMED_CHANGE));
+ });
} finally {
- setSaving(orgID, false);
+ if (writeIsCurrent()) {
+ billingWrites.delete(orgID);
+ setSavingByOrgID((prev) => withEntry(prev, orgID, false));
+ }
}
};
- const refreshOrganizations = async () => {
- setBillingByOrgID({});
- setExpandedOrgID(null);
- await loadOrganizations();
- };
-
const toggleExpandedOrganization = async (orgID: string) => {
- if (!orgID) return;
- setExpandedOrgID((prev) => (prev === orgID ? null : orgID));
- await ensureBillingState(orgID);
+ if (!isCurrent(generation) || !hasCurrentOrganization(orgID)) return;
+ const opening = expandedOrgID() !== orgID;
+ setExpandedOrgID(opening ? orgID : null);
+ if (opening) await ensureBillingState(orgID);
};
const reloadOrganization = async (orgID: string) => {
- if (!orgID) return;
- setBillingByOrgID((prev) => ({ ...prev, [orgID]: undefined }));
+ if (!isCurrent(generation) || !hasCurrentOrganization(orgID) || billingWrites.has(orgID))
+ return;
+ billingReads.get(orgID)?.abort();
+ billingReads.delete(orgID);
+ batch(() => {
+ setBillingByOrgID((prev) => withEntry(prev, orgID, undefined));
+ setBillingErrorByOrgID((prev) => {
+ const next = Object.assign(emptyRecord<string>(), prev);
+ delete next[orgID];
+ return next;
+ });
+ });
await ensureBillingState(orgID);
};
- createEffect(() => {
- if (!hostedEnabled()) return;
- void loadOrganizations();
- });
-
- createEffect(() => {
- const list = orgs();
- if (!hostedEnabled() || loadingOrgs() || list.length === 0) return;
-
- const missing = list.map((o) => o.org_id).filter((id) => id && !billingByOrgID()[id]);
- if (missing.length === 0) return;
-
- void promisePool(missing, 6, async (orgID) => {
- await ensureBillingState(orgID);
+ createEffect(
+ on([hostedEnabled, presentationPolicyIsReadOnly], () => void refreshOrganizations()),
+ );
+ onCleanup(() => {
+ disposed = true;
+ invalidateRequests();
+ batch(() => {
+ clearSnapshot();
+ setLoadingOrgs(false);
});
});
return {
billingByOrgID,
+ billingErrorByOrgID,
billingLoadingByOrgID,
+ canManageBilling,
expandedOrgID,
hostedEnabled,
loadingOrgs,