From 6422ee529c75c03c8f3544aeba238b3f86e1b41b Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:16:32 +0000 Subject: [PATCH 01/10] Keep Billing Admin changes tied to confirmed reads Invalidate withdrawn inventory and billing reads, surface unavailable state and require a current snapshot before changing a subscription. Bound prefetches and writes, preserve saved billing fields and never repeat an unconfirmed update. Change-source: pulse-maintainer --- .../v6/internal/subsystems/api-contracts.md | 15 + .../v6/internal/subsystems/cloud-paid.md | 30 ++ .../src/api/__tests__/billingAdmin.test.ts | 27 ++ .../__tests__/billingAdmin.transport.test.ts | 87 ++++ frontend-modern/src/api/billingAdmin.ts | 16 +- .../BillingAdminOrganizationsTable.tsx | 317 +++++++------ .../components/Settings/BillingAdminPanel.tsx | 53 ++- .../__tests__/BillingAdminPanel.test.tsx | 1 + .../BillingAdminReadLifetimes.test.tsx | 437 ++++++++++++++++++ .../Settings/useBillingAdminPanelState.ts | 311 +++++++++---- 10 files changed, 1037 insertions(+), 257 deletions(-) create mode 100644 frontend-modern/src/api/__tests__/billingAdmin.transport.test.ts create mode 100644 frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx 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((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('/api/hosted/organizations', { preferSessionAuth: true, skipOrgContext: true, + ...options, }), - getBillingState: (orgID: string) => + getBillingState: (orgID: string, options?: BillingAdminRequestOptions) => apiFetchJSON(`/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(`/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; + billingErrorByOrgID: Record; + canManageBilling: boolean; expandedOrgID: string | null; isLoading: boolean; orgs: HostedOrganizationSummary[]; @@ -31,152 +33,185 @@ const stripeCustomerCell = (state?: BillingState) => { export const BillingAdminOrganizationsTable: Component = ( props, -) => ( - { - const orgID = (org.org_id || '').trim(); - return ( - + ); + }, + }, + { + key: 'owner', + label: 'Owner', + hiddenOnMobile: true, + render: (org) => ( + {org.owner_user_id || 'N/A'} + ), + }, + { + key: 'subscription', + label: 'Subscription', + render: (org) => { + const billing = props.billingByOrgID[(org.org_id || '').trim()]; + const orgID = (org.org_id || '').trim(); + return ( +
+ + {billing + ? getLicenseSubscriptionStatusPresentation(billing.subscription_state).label + : unreadLabel(orgID)} + + + + +
- - ); + ); + }, }, - }, - { - key: 'owner', - label: 'Owner', - hiddenOnMobile: true, - render: (org) => ( - {org.owner_user_id || 'N/A'} - ), - }, - { - key: 'subscription', - label: 'Subscription', - render: (org) => { - const billing = props.billingByOrgID[(org.org_id || '').trim()]; - return ( - - {getLicenseSubscriptionStatusPresentation(billing?.subscription_state).label} - - ); + { + key: 'trial', + label: 'Trial', + hiddenOnMobile: true, + render: (org) => { + const billing = props.billingByOrgID[(org.org_id || '').trim()]; + return ( + + {billing ? getBillingAdminTrialStatus(billing) : unreadLabel(org.org_id)} + + ); + }, }, - }, - { - key: 'trial', - label: 'Trial', - hiddenOnMobile: true, - render: (org) => { - const billing = props.billingByOrgID[(org.org_id || '').trim()]; - return ( - {getBillingAdminTrialStatus(billing)} - ); + { + 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 ( + + {cellValue} + + ); + }, }, - }, - { - key: 'stripeCustomer', - label: 'Stripe Customer', - hiddenOnMobile: true, - render: (org) => { - const billing = props.billingByOrgID[(org.org_id || '').trim()]; - const cellValue = stripeCustomerCell(billing); - return ( - - {cellValue} - - ); + { + 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 ( +
+ + +
+ ); + }, }, - }, - { - 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 ( -
- +
+ + {props.billingErrorByOrgID[orgID] || 'Loading billing state...'} +

} > - Suspend Org - - +
+                  {JSON.stringify(props.billingByOrgID[orgID], null, 2)}
+                
+
- ); - }, - }, - ]} - keyExtractor={(org) => org.org_id} - isRowExpanded={(org) => props.expandedOrgID === (org.org_id || '').trim()} - expandedRender={(org) => { - const orgID = (org.org_id || '').trim(); - return ( -
-
-
-
Billing state JSON
- -
-
-              {JSON.stringify(props.billingByOrgID[orgID] ?? { loading: true }, null, 2)}
-            
-
- ); - }} - /> -); + ); + }} + /> + ); +}; 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" > -
+ -
- { - void state.toggleExpandedOrganization(orgID); - }} - onSuspendOrganization={(orgID) => { - void state.updateSubscriptionState(orgID, 'suspended'); - }} - onActivateOrganization={(orgID) => { - void state.updateSubscriptionState(orgID, 'active'); - }} - onReloadOrganization={(orgID) => { - void state.reloadOrganization(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); + }} + /> +
+
); 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 = () => { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + const promise = new Promise((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; + 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(); + mocks.get.mockReturnValueOnce(pending.promise); + render(() => ); + 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(() => ); + await waitFor(() => expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeEnabled()); + const pending = deferred(); + 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(); + mocks.list.mockResolvedValue([org(), org('org-b')]); + mocks.get + .mockRejectedValueOnce(new Error('SYNTHETIC PRIVATE BILLING DETAIL')) + .mockReturnValueOnce(other.promise) + .mockResolvedValue(billing()); + render(() => ); + 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(); + const current = deferred(); + 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[]>(); + const second = deferred[]>(); + 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(); + const current = deferred(); + 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[]>(); + 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()); + 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(); + 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[]>(); + 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(); + 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(); + 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(); + 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; +const emptyRecord = (): Record => Object.create(null); +const withEntry = (entries: Record, key: string, value: T): Record => + Object.assign(emptyRecord(), 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(items: T[], concurrency: number, fn: (item: T) => Promise) { if (items.length === 0) return; @@ -32,12 +69,18 @@ export function useBillingAdminPanelState() { const [orgs, setOrgs] = createSignal([]); const [loadingOrgs, setLoadingOrgs] = createSignal(false); const [orgsError, setOrgsError] = createSignal(null); - const [billingByOrgID, setBillingByOrgID] = createSignal({}); - const [billingLoadingByOrgID, setBillingLoadingByOrgID] = createSignal>( - {}, - ); - const [savingByOrgID, setSavingByOrgID] = createSignal>({}); + const [billingByOrgID, setBillingByOrgID] = createSignal(emptyRecord()); + const [billingLoadingByOrgID, setBillingLoadingByOrgID] = + createSignal>(emptyRecord()); + const [billingErrorByOrgID, setBillingErrorByOrgID] = + createSignal>(emptyRecord()); + const [savingByOrgID, setSavingByOrgID] = createSignal>(emptyRecord()); const [expandedOrgID, setExpandedOrgID] = createSignal(null); + let generation = 0; + let disposed = false; + let listController: AbortController | undefined; + const billingReads = new Map(); + const billingWrites = new Map(); 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 loadOrganizations = async () => { - setLoadingOrgs(true); + const clearSnapshot = () => { + setOrgs([]); setOrgsError(null); - try { - const next = await BillingAdminAPI.listOrganizations(); - setOrgs(next ?? []); - } 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); - } finally { - setLoadingOrgs(false); - } + setBillingByOrgID(emptyRecord()); + setBillingLoadingByOrgID(emptyRecord()); + setBillingErrorByOrgID(emptyRecord()); + setSavingByOrgID(emptyRecord()); + setExpandedOrgID(null); }; - const ensureBillingState = async (orgID: string): Promise => { - const cached = billingByOrgID()[orgID]; - if (cached) return cached; + const ensureBillingState = async (orgID: string, request = generation) => { + if ( + !isCurrent(request) || + !hasCurrentOrganization(orgID) || + billingByOrgID()[orgID] || + billingReads.has(orgID) || + billingWrites.has(orgID) || + billingErrorByOrgID()[orgID] + ) + return; - if (billingLoadingByOrgID()[orgID]) { - return null; - } - - setBillingLoading(orgID, true); + 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 state = await BillingAdminAPI.getBillingState(orgID); - setBillingByOrgID((prev) => ({ ...prev, [orgID]: state })); - return state; + 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) { + if (!readIsCurrent()) return; logger.error('Failed to fetch billing state', { orgID, err }); - return null; + setBillingErrorByOrgID((prev) => withEntry(prev, orgID, BILLING_ADMIN_READ_ERROR)); } finally { - setBillingLoading(orgID, false); - } - }; - - const updateSubscriptionState = async (orgID: string, nextState: 'suspended' | 'active') => { - setSaving(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 })); - notificationStore.success(getBillingAdminStateUpdateSuccessMessage(nextState), 2500); - } catch (err) { - logger.error('Failed to update billing state', { orgID, err }); - const msg = err instanceof Error ? err.message : 'Failed to update billing state'; - notificationStore.error(msg); - } finally { - setSaving(orgID, false); + if (readIsCurrent()) { + billingReads.delete(orgID); + setBillingLoadingByOrgID((prev) => withEntry(prev, orgID, false)); + } } }; const refreshOrganizations = async () => { - setBillingByOrgID({}); - setExpandedOrgID(null); - await loadOrganizations(); + if (disposed) return; + invalidateRequests(); + const request = generation; + batch(() => { + clearSnapshot(); + setLoadingOrgs(hostedEnabled()); + }); + if (!hostedEnabled()) return; + + const controller = new AbortController(); + listController = controller; + let next: HostedOrganizationSummary[]; + try { + 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) { + if (!isCurrent(request)) return; + logger.error('Failed to list hosted organizations', err); + setOrgsError(getOrganizationSettingsLoadErrorMessage('', 'billing-admin')); + return; + } finally { + 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') => { + 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 planVersion = current.plan_version?.trim() || undefined; + const payload: BillingState = { + ...current, + subscription_state: nextState, + ...(planVersion ? { plan_version: planVersion } : {}), + }; + 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 }); + batch(() => { + setBillingByOrgID((prev) => withEntry(prev, orgID, undefined)); + setBillingErrorByOrgID((prev) => withEntry(prev, orgID, BILLING_ADMIN_UNCONFIRMED_CHANGE)); + }); + } finally { + if (writeIsCurrent()) { + billingWrites.delete(orgID); + setSavingByOrgID((prev) => withEntry(prev, orgID, false)); + } + } }; 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(), 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, From 7b37fa350b0f601361104fd4d4cdfa267a0ed053 Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:24:05 +0000 Subject: [PATCH 02/10] Keep optional Billing Admin cache entries typed explicitly Resolve the exact-source compiler errors without changing request behaviour. Make the owning panel assertions use its fixed error copy and unambiguous organization button. Contract-Neutral: Explicit generic arguments and test assertions only; no subsystem behaviour or API contract delta. Change-source: pulse-maintainer --- .../__tests__/BillingAdminReadLifetimes.test.tsx | 8 ++++++-- .../Settings/useBillingAdminPanelState.ts | 16 ++++++++-------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx b/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx index bf495cd998..8c396fed99 100644 --- a/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx @@ -121,7 +121,9 @@ describe('Billing Admin accepted inventory and billing reads', () => { 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')); + await waitFor(() => + expect(screen.getByRole('alert')).toHaveTextContent('Unable to load the organization list.'), + ); expect(screen.queryByText(/No organizations/)).not.toBeInTheDocument(); expect(screen.queryByText(/SYNTHETIC PRIVATE/)).not.toBeInTheDocument(); expect(mocks.error).not.toHaveBeenCalled(); @@ -163,7 +165,9 @@ describe('Billing Admin accepted inventory and billing reads', () => { await settle(); expect(mocks.get).toHaveBeenCalledTimes(2); expect(screen.queryByText(/SYNTHETIC PRIVATE/)).not.toBeInTheDocument(); - await fireEvent.click(screen.getByRole('button', { name: /Organization org-a/ })); + await fireEvent.click( + screen.getByRole('button', { name: 'Organization org-a org-a', exact: true }), + ); expect(screen.getByRole('status')).toHaveTextContent(BILLING_ADMIN_READ_ERROR); expect(screen.queryByText(/"loading": true/)).not.toBeInTheDocument(); const before = mocks.put.mock.calls.length; diff --git a/frontend-modern/src/components/Settings/useBillingAdminPanelState.ts b/frontend-modern/src/components/Settings/useBillingAdminPanelState.ts index a70e77048a..9e3fb5cfe9 100644 --- a/frontend-modern/src/components/Settings/useBillingAdminPanelState.ts +++ b/frontend-modern/src/components/Settings/useBillingAdminPanelState.ts @@ -106,10 +106,10 @@ export function useBillingAdminPanelState() { const clearSnapshot = () => { setOrgs([]); setOrgsError(null); - setBillingByOrgID(emptyRecord()); - setBillingLoadingByOrgID(emptyRecord()); - setBillingErrorByOrgID(emptyRecord()); - setSavingByOrgID(emptyRecord()); + setBillingByOrgID(emptyRecord()); + setBillingLoadingByOrgID(emptyRecord()); + setBillingErrorByOrgID(emptyRecord()); + setSavingByOrgID(emptyRecord()); setExpandedOrgID(null); }; @@ -133,7 +133,7 @@ export function useBillingAdminPanelState() { 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)); + setBillingByOrgID((prev) => withEntry(prev, orgID, state)); } catch (err) { if (!readIsCurrent()) return; logger.error('Failed to fetch billing state', { orgID, err }); @@ -231,13 +231,13 @@ export function useBillingAdminPanelState() { 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)); + 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 }); batch(() => { - setBillingByOrgID((prev) => withEntry(prev, orgID, undefined)); + setBillingByOrgID((prev) => withEntry(prev, orgID, undefined)); setBillingErrorByOrgID((prev) => withEntry(prev, orgID, BILLING_ADMIN_UNCONFIRMED_CHANGE)); }); } finally { @@ -261,7 +261,7 @@ export function useBillingAdminPanelState() { billingReads.get(orgID)?.abort(); billingReads.delete(orgID); batch(() => { - setBillingByOrgID((prev) => withEntry(prev, orgID, undefined)); + setBillingByOrgID((prev) => withEntry(prev, orgID, undefined)); setBillingErrorByOrgID((prev) => { const next = Object.assign(emptyRecord(), prev); delete next[orgID]; From 4b10ca579a323d1d8b8e37ac69c2cbc662816d59 Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:33:36 +0000 Subject: [PATCH 03/10] Use the supported exact-name query for Billing Admin tests Testing Library role queries already match a string name exactly. Remove the unsupported exact option without changing the asserted name or runtime. Change-source: pulse-maintainer --- .../Settings/__tests__/BillingAdminReadLifetimes.test.tsx | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx b/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx index 8c396fed99..4e8dc28bdf 100644 --- a/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/BillingAdminReadLifetimes.test.tsx @@ -165,9 +165,7 @@ describe('Billing Admin accepted inventory and billing reads', () => { await settle(); expect(mocks.get).toHaveBeenCalledTimes(2); expect(screen.queryByText(/SYNTHETIC PRIVATE/)).not.toBeInTheDocument(); - await fireEvent.click( - screen.getByRole('button', { name: 'Organization org-a org-a', exact: true }), - ); + await fireEvent.click(screen.getByRole('button', { name: 'Organization org-a 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; From ae608825fcef489d1098a060162b3f6ade75224e Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:43:57 +0000 Subject: [PATCH 04/10] Keep Billing Admin recovery and phone actions readable Override inherited table no-wrap for warnings and expanded JSON. Keep one mobile action set beside its subscription state instead of beyond the viewport, with a normal-suite action-target regression. Change-source: pulse-maintainer --- .../v6/internal/subsystems/cloud-paid.md | 7 +- .../BillingAdminOrganizationsTable.tsx | 69 ++++++++++--------- .../__tests__/BillingAdminPanel.test.tsx | 27 ++++++++ 3 files changed, 68 insertions(+), 35 deletions(-) diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md index 8e33000750..903443f74e 100644 --- a/docs/release-control/v6/internal/subsystems/cloud-paid.md +++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md @@ -40,8 +40,11 @@ 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, +On phones, one set of subscription actions stays in the subscription cell, beside +its accepted state and recovery control, rather than extending a separate column +off-screen. Error text and expanded JSON override inherited table no-wrap rules +so the warning, recovery and billing details remain readable. 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. diff --git a/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx b/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx index f470713035..32bd2c0e56 100644 --- a/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx +++ b/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx @@ -1,6 +1,7 @@ import { Show, type Component } from 'solid-js'; import { Button } from '@/components/shared/Button'; import { PulseDataGrid } from '@/components/shared/PulseDataGrid'; +import { useBreakpoint } from '@/hooks/useBreakpoint'; import { BILLING_ADMIN_EMPTY_STATE, getBillingAdminOrganizationBadges, @@ -34,6 +35,7 @@ const stripeCustomerCell = (state?: BillingState) => { export const BillingAdminOrganizationsTable: Component = ( props, ) => { + const { isMobile } = useBreakpoint(); const unreadLabel = (orgID: string) => props.billingLoadingByOrgID[orgID] ? 'Loading' : 'Unavailable'; const actionsDisabled = (orgID: string) => @@ -42,6 +44,30 @@ export const BillingAdminOrganizationsTable: Component { + const currentSubState = () => + (props.billingByOrgID[orgID]?.subscription_state || '').toLowerCase(); + return ( +
+ + +
+ ); + }; return ( { props.onToggleOrganization(orgID); }} @@ -97,7 +123,10 @@ export const BillingAdminOrganizationsTable: Component -
); }, @@ -144,36 +174,9 @@ export const BillingAdminOrganizationsTable: Component { - const orgID = (org.org_id || '').trim(); - const billing = props.billingByOrgID[orgID]; - const currentSubState = (billing?.subscription_state || '').toLowerCase() || 'unknown'; - return ( -
- - -
- ); - }, + render: (org) => {subscriptionActions(org.org_id)}, }, ]} keyExtractor={(org) => org.org_id} @@ -181,7 +184,7 @@ export const BillingAdminOrganizationsTable: Component { const orgID = (org.org_id || '').trim(); return ( -
+
Billing state JSON
@@ -204,7 +207,7 @@ export const BillingAdminOrganizationsTable: Component } > -
+                
                   {JSON.stringify(props.billingByOrgID[orgID], null, 2)}
                 
diff --git a/frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx index 849dd36016..a8ee90d34e 100644 --- a/frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx +++ b/frontend-modern/src/components/Settings/__tests__/BillingAdminPanel.test.tsx @@ -6,6 +6,7 @@ import billingAdminOrganizationsTableSource from '../BillingAdminOrganizationsTa import billingAdminPanelSource from '../BillingAdminPanel.tsx?raw'; import billingAdminPanelStateSource from '../useBillingAdminPanelState.ts?raw'; +const isMobileMock = vi.fn(); const listOrganizationsMock = vi.fn(); const getBillingStateMock = vi.fn(); const putBillingStateMock = vi.fn(); @@ -13,6 +14,10 @@ const successMock = vi.fn(); const errorMock = vi.fn(); const presentationPolicyHidesOrganizationSurfacesMock = vi.fn(); +vi.mock('@/hooks/useBreakpoint', () => ({ + useBreakpoint: () => ({ isMobile: () => isMobileMock() }), +})); + vi.mock('@/api/billingAdmin', () => ({ BillingAdminAPI: { listOrganizations: (...args: unknown[]) => listOrganizationsMock(...args), @@ -47,6 +52,7 @@ vi.mock('@/utils/logger', () => ({ describe('BillingAdminPanel', () => { beforeEach(() => { + isMobileMock.mockReset().mockReturnValue(false); listOrganizationsMock.mockReset(); getBillingStateMock.mockReset(); putBillingStateMock.mockReset(); @@ -179,4 +185,25 @@ describe('BillingAdminPanel', () => { expect(listOrganizationsMock).not.toHaveBeenCalled(); expect(getBillingStateMock).not.toHaveBeenCalled(); }); + it('keeps one set of mobile subscription actions beside their confirmed billing state', async () => { + isMobileMock.mockReturnValue(true); + getBillingStateMock.mockResolvedValue({ + capabilities: [], + limits: {}, + meters_enabled: [], + subscription_state: 'active', + }); + putBillingStateMock.mockImplementation(async (_orgID, payload) => payload); + render(() => ); + await waitFor(() => expect(screen.getByRole('button', { name: 'Suspend Org' })).toBeEnabled()); + expect(screen.getAllByRole('button', { name: 'Suspend Org' })).toHaveLength(1); + expect(screen.getAllByRole('button', { name: 'Activate Org' })).toHaveLength(1); + expect(screen.getByRole('button', { name: 'Suspend Org' }).closest('td')).toHaveTextContent( + 'Active', + ); + await fireEvent.click(screen.getByRole('button', { name: 'Suspend Org' })); + await waitFor(() => expect(putBillingStateMock).toHaveBeenCalledTimes(1)); + expect(putBillingStateMock.mock.calls[0][0]).toBe('org-1'); + expect(putBillingStateMock.mock.calls[0][1].subscription_state).toBe('suspended'); + }); }); From 057b6bab50df9824ff8a7f8475b7e8c1880b44b0 Mon Sep 17 00:00:00 2001 From: "pulse-triage[bot]" <249995291+pulse-triage[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:55:52 +0000 Subject: [PATCH 05/10] Stack mobile billing actions below read recovery The consuming WebKit bound check exposed an inline action group beside the reload control. Use a block-level flex group on phones, preserving the desktop inline layout. Contract-Neutral: Restores the already-contracted mobile action stacking and readable recovery; no API or subsystem contract delta. Change-source: pulse-maintainer --- .../src/components/Settings/BillingAdminOrganizationsTable.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx b/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx index 32bd2c0e56..f9b47c7b89 100644 --- a/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx +++ b/frontend-modern/src/components/Settings/BillingAdminOrganizationsTable.tsx @@ -48,7 +48,7 @@ export const BillingAdminOrganizationsTable: Component (props.billingByOrgID[orgID]?.subscription_state || '').toLowerCase(); return ( -
+