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 reporting workspaces and downloads within their current reader

pulse-triage[bot]fd6e641d745c
diff --git a/docs/release-control/v6/internal/subsystems/organization-settings.md b/docs/release-control/v6/internal/subsystems/organization-settings.md
index a9e6bc2cb6..b669061f14 100644
--- a/docs/release-control/v6/internal/subsystems/organization-settings.md
+++ b/docs/release-control/v6/internal/subsystems/organization-settings.md
@@ -626,3 +626,33 @@ must not dispatch into the default or a new organisation or automatically replay
a refusal. Endpoint paths, encoded principal keys, JSON payloads, authentication
and server permission checks are unchanged. `api/__tests__/rbac.test.ts` and
`UserAccessReaderLifetime.test.tsx` pin forwarding and the consuming lifecycle.
+
+
+### Reporting workspaces belong to the current reader
+
+The existing Data & Reports panel keys its whole workspace, resource-picker
+searches and lazy schedule editor to the current organisation, authenticated
+principal, non-secret credential hint/sorted scope set, reporting-read admission
+and reporting entitlement/readiness. An equal security-status refresh preserves
+the reader's drafts. A changed reader withdraws schedules, recipients, selections,
+searches, titles and local feedback; restoring access requires fresh reads and
+never revives the old editor.
+
+Every reporting request retains its original `expectedOrgID`, abort signal and
+`retry: false`. Disposal and current-reader checks suppress late catalog/list/
+mutation results, follow-up requests, feedback and downloads, including a response
+whose blob finishes after withdrawal. Aborting a client does not undo a server
+write or recall an already downloaded file. Backend permission/scope checks,
+report generation, scheduled delivery and retention policy are unchanged; the
+client fingerprint is not a new authorisation grant or a write-capability promise.
+
+Schedule actions require an accepted current inventory and current row identity,
+are mutually excluded, and recheck admission after a confirmation. Failed or
+malformed reads are unknown, not an empty schedule directory; Refresh explicitly
+retries them. Refused saves retain the editor for deliberate retry, with feedback
+inside this reader rather than global toasts or duplicate raw console output.
+Registered `ReportingPanel.reader.test.tsx`, `useReportingPanelState.test.ts`,
+`ReportingPanel.test.tsx` and `settingsPanelRegistryContext.test.ts` cover lifetime,
+late body completion, same-reader refresh, refused-save retry, malformed inventory,
+confirmation, route props and existing reporting/delivery behaviour. Actual App
+Settings/API-client/browser proof remains required for the consuming surface.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 31e77eb569..c1e107f86a 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -4147,3 +4147,33 @@ earlier raw object; that current-read object remains usable for the same live
ID. A later full read, context withdrawal or deletion invalidates the old
confirmation. The registered sequential scope-edit/revoke consumer regression
and earlier-read rejection test cover both sides without ID-only admission.
+
+
+### Reporting drafts and downloads cannot outlive their reader
+
+The existing Data & Reports panel keys its whole workspace, resource-picker
+searches and lazy schedule editor to the current organisation, authenticated
+principal, non-secret credential hint/sorted scope set, reporting-read admission
+and reporting entitlement/readiness. An equal security-status refresh preserves
+the reader's drafts. A changed reader withdraws schedules, recipients, selections,
+searches, titles and local feedback; restoring access requires fresh reads and
+never revives the old editor.
+
+Every reporting request retains its original `expectedOrgID`, abort signal and
+`retry: false`. Disposal and current-reader checks suppress late catalog/list/
+mutation results, follow-up requests, feedback and downloads, including a response
+whose blob finishes after withdrawal. Aborting a client does not undo a server
+write or recall an already downloaded file. Backend permission/scope checks,
+report generation, scheduled delivery and retention policy are unchanged; the
+client fingerprint is not a new authorisation grant or a write-capability promise.
+
+Schedule actions require an accepted current inventory and current row identity,
+are mutually excluded, and recheck admission after a confirmation. Failed or
+malformed reads are unknown, not an empty schedule directory; Refresh explicitly
+retries them. Refused saves retain the editor for deliberate retry, with feedback
+inside this reader rather than global toasts or duplicate raw console output.
+Registered `ReportingPanel.reader.test.tsx`, `useReportingPanelState.test.ts`,
+`ReportingPanel.test.tsx` and `settingsPanelRegistryContext.test.ts` cover lifetime,
+late body completion, same-reader refresh, refused-save retry, malformed inventory,
+confirmation, route props and existing reporting/delivery behaviour. Actual App
+Settings/API-client/browser proof remains required for the consuming surface.
diff --git a/frontend-modern/src/components/Settings/ReportingPanel.tsx b/frontend-modern/src/components/Settings/ReportingPanel.tsx
index ccff4e5f54..75a4e5befd 100644
--- a/frontend-modern/src/components/Settings/ReportingPanel.tsx
+++ b/frontend-modern/src/components/Settings/ReportingPanel.tsx
@@ -1,4 +1,7 @@
-import { For, Show, Suspense, lazy } from 'solid-js';
+import { For, Show, Suspense, createMemo, createSignal, lazy, onCleanup } from 'solid-js';
+import { getOrgID } from '@/utils/apiClient';
+import { eventBus } from '@/stores/events';
+import { hasFeature, runtimeCapabilitiesLoaded } from '@/stores/license';
import FileText from 'lucide-solid/icons/file-text';
import Download from 'lucide-solid/icons/download';
import BarChart from 'lucide-solid/icons/bar-chart';
@@ -37,9 +40,66 @@ const REPORTING_FORMAT_ICONS: Record<ReportingFormat, typeof FileText> = {
const ReportScheduleEditor = lazy(() => import('./ReportScheduleEditor'));
-export function ReportingPanel() {
- const state = useReportingPanelState();
+export interface ReportingPanelProps {
+ currentUser?: string;
+ accessKey?: string;
+ canRead?: boolean;
+}
+
+export function ReportingPanel(props: ReportingPanelProps) {
+ const [org, setOrg] = createSignal(getOrgID() || 'default');
+ const unsubscribe = eventBus.on('org_switched', () => setOrg(getOrgID() || 'default'));
+ onCleanup(unsubscribe);
+ // Key the whole workspace, including picker searches and lazy editors, by the
+ // actual reader facts. A copied security status is not a new reader.
+ const reader = createMemo(
+ (previous?: {
+ org: string;
+ user?: string;
+ access?: string;
+ read: boolean;
+ enabled: boolean;
+ resolved: boolean;
+ }) => {
+ org(); // Also refresh when the organization event has no capability delta.
+ const next = {
+ org: getOrgID() || 'default',
+ user: props.currentUser,
+ access: props.accessKey,
+ read: props.canRead !== false,
+ enabled: hasFeature('advanced_reporting'),
+ resolved: runtimeCapabilitiesLoaded(),
+ };
+ return previous &&
+ Object.keys(next).every(
+ (key) => next[key as keyof typeof next] === previous[key as keyof typeof next],
+ )
+ ? previous
+ : next;
+ },
+ );
+ return (
+ <Show
+ when={reader().read}
+ fallback={
+ <OperationsPanel title="Reporting">
+ <p class="p-4 text-sm text-muted">Reporting is not available to this session.</p>
+ </OperationsPanel>
+ }
+ >
+ <Show when={reader()} keyed>
+ {(accepted) => <ReportingWorkspace isCurrentReader={() => reader() === accepted} />}
+ </Show>
+ </Show>
+ );
+}
+
+function ReportingWorkspace(props: { isCurrentReader: () => boolean }) {
+ const state = useReportingPanelState(props.isCurrentReader);
const {
+ actionError,
+ successNotice,
+ canEditSchedules,
deleteReportSchedule,
deletingScheduleID,
exportingInventory,
@@ -120,6 +180,16 @@ export function ReportingPanel() {
return (
<div class="space-y-6">
+ <Show when={actionError()}>
+ <p role="alert" class="text-sm text-warning">
+ {actionError()}
+ </p>
+ </Show>
+ <Show when={successNotice()}>
+ <p role="status" class="text-sm text-success">
+ {successNotice()}
+ </p>
+ </Show>
<Show when={reportingCatalogLoading() && !catalogReady()}>
<OperationsPanel title="Reporting" description="Loading reporting surfaces...">
<div class="p-4 sm:p-6">
@@ -300,7 +370,13 @@ export function ReportingPanel() {
<RefreshCw size={16} />
Refresh
</Button>
- <Button variant="primary" size="sm" class="gap-2" onClick={startCreateSchedule}>
+ <Button
+ variant="primary"
+ size="sm"
+ class="gap-2"
+ disabled={!canEditSchedules()}
+ onClick={startCreateSchedule}
+ >
<Plus size={16} />
Create schedule
</Button>
@@ -330,6 +406,7 @@ export function ReportingPanel() {
variant="secondary"
size="sm"
class="gap-2"
+ disabled={!canEditSchedules()}
onClick={startCreateSchedule}
>
<Plus size={16} />
@@ -366,6 +443,7 @@ export function ReportingPanel() {
<input
type="checkbox"
class="h-4 w-4"
+ disabled={!canEditSchedules()}
checked={schedule.enabled}
aria-label={`Enable ${schedule.name}`}
onChange={() => toggleReportSchedule(schedule)}
@@ -379,7 +457,9 @@ export function ReportingPanel() {
aria-label={`${reportScheduleRunActionLabel(schedule)} ${schedule.name} now`}
isLoading={runningScheduleID() === schedule.id}
disabled={
- runningScheduleID() !== '' || schedule.last_run_status === 'running'
+ !canEditSchedules() ||
+ runningScheduleID() !== '' ||
+ schedule.last_run_status === 'running'
}
onClick={() => runReportScheduleNow(schedule)}
>
@@ -476,6 +556,7 @@ export function ReportingPanel() {
size="sm"
class="min-h-11 gap-2"
aria-label={`Edit ${schedule.name}`}
+ disabled={!canEditSchedules()}
onClick={() => startEditSchedule(schedule)}
>
<Pencil size={15} />
@@ -487,7 +568,7 @@ export function ReportingPanel() {
class="min-h-11 gap-2"
aria-label={`Delete ${schedule.name}`}
isLoading={deletingScheduleID() === schedule.id}
- disabled={deletingScheduleID() !== ''}
+ disabled={!canEditSchedules() || deletingScheduleID() !== ''}
onClick={() => deleteReportSchedule(schedule)}
>
<Trash2 size={15} />
diff --git a/frontend-modern/src/components/Settings/__tests__/ReportingPanel.reader.test.tsx b/frontend-modern/src/components/Settings/__tests__/ReportingPanel.reader.test.tsx
new file mode 100644
index 0000000000..d23c2ce1e4
--- /dev/null
+++ b/frontend-modern/src/components/Settings/__tests__/ReportingPanel.reader.test.tsx
@@ -0,0 +1,293 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, fireEvent, render, screen, waitFor } from '@solidjs/testing-library';
+import { createSignal, type Accessor, type Setter } from 'solid-js';
+import { ReportingPanel, type ReportingPanelProps } from '../ReportingPanel';
+import { buildLegacyReportingCatalogFallback } from '../reportingCatalogModel';
+import { eventBus } from '@/stores/events';
+
+let org = 'default';
+let enabled: Accessor<boolean>;
+let setEnabled: Setter<boolean>;
+const api = vi.fn();
+vi.mock('@/utils/apiClient', async () => ({
+ ...(await vi.importActual<typeof import('@/utils/apiClient')>('@/utils/apiClient')),
+ getOrgID: () => org,
+ apiFetch: (...args: unknown[]) => api(...args),
+}));
+vi.mock('@/stores/license', () => ({
+ hasFeature: () => enabled(),
+ runtimeCapabilitiesLoaded: () => true,
+ loadRuntimeCapabilities: vi.fn(),
+}));
+vi.mock('@/stores/licenseCommercial', () => ({
+ getUpgradeActionDestination: () => ({ href: '/pricing', external: false }),
+}));
+vi.mock('@/stores/sessionPresentationPolicy', () => ({
+ presentationPolicyHidesUpgradePrompts: () => true,
+}));
+vi.mock('../ResourcePicker', () => ({
+ ResourcePicker: () => <input aria-label="Fixture resource search" />,
+}));
+
+const catalog = {
+ ...buildLegacyReportingCatalogFallback(),
+ vmInventoryExport: {
+ id: 'vm_inventory',
+ title: 'VM Inventory Export',
+ description: 'Current inventory',
+ format: 'csv',
+ exportEndpoint: '/api/admin/reports/inventory/vms/export',
+ filenamePrefix: 'vm-inventory',
+ filenameDateStyle: 'utc_yyyymmdd',
+ columns: [{ key: 'name', label: 'Name', description: 'VM name' }],
+ },
+};
+const schedule = (name = 'North private report') => ({
+ id: 'reused-id',
+ name,
+ enabled: false,
+ kind: 'vm_inventory',
+ format: 'csv',
+ cadence: { type: 'monthly', time: '09:00', timezone: 'UTC' },
+ scope: { resources: [], tags: [] },
+ delivery: {
+ method: 'email',
+ attach: true,
+ save_to_disk: true,
+ },
+});
+const json = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status });
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { resolve, promise };
+}
+function mount() {
+ const [props, setProps] = createSignal<ReportingPanelProps>({
+ currentUser: 'operator-a',
+ canRead: true,
+ });
+ const view = render(() => <ReportingPanel {...props()} />);
+ return { ...view, setProps };
+}
+async function ready() {
+ await screen.findByText('North private report', { exact: true });
+}
+async function draft() {
+ await fireEvent.click(screen.getAllByRole('button', { name: 'Create schedule' })[0]);
+ await screen.findByRole('textbox', { name: 'Schedule name' });
+ await fireEvent.input(screen.getByRole('textbox', { name: 'Schedule name' }), {
+ target: { value: 'Private draft' },
+ });
+ await fireEvent.input(screen.getByRole('textbox', { name: 'Report Title' }), {
+ target: { value: 'Private title' },
+ });
+}
+beforeEach(() => {
+ org = 'default';
+ [enabled, setEnabled] = createSignal(true);
+ api.mockReset();
+ api.mockImplementation((url: string) =>
+ Promise.resolve(json(url.endsWith('/schedules') ? { schedules: [schedule()] } : catalog)),
+ );
+});
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe('Reporting reader lifetime', () => {
+ it('keeps equal-reader drafts but destroys them on a principal change', async () => {
+ const view = mount();
+ await ready();
+ await draft();
+ const search = screen.getAllByLabelText('Fixture resource search')[0];
+ await fireEvent.input(search, { target: { value: 'Private search' } });
+ const count = api.mock.calls.length;
+ view.setProps({ currentUser: 'operator-a', canRead: true });
+ expect(screen.getByRole('textbox', { name: 'Schedule name' })).toHaveValue('Private draft');
+ expect(search).toHaveValue('Private search');
+ expect(api).toHaveBeenCalledTimes(count);
+ view.setProps({ currentUser: 'operator-b', canRead: true });
+ await ready();
+ expect(screen.queryByRole('textbox', { name: 'Schedule name' })).not.toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: 'Report Title' })).toHaveValue('');
+ expect(screen.getByLabelText('Fixture resource search')).toHaveValue('');
+ });
+
+ it('withdraws a changed credential or scope context even for the same principal', async () => {
+ const view = mount();
+ await ready();
+ await draft();
+ view.setProps({ currentUser: 'operator-a', canRead: true, accessKey: 'replacement-scopes' });
+ await ready();
+ expect(screen.queryByRole('textbox', { name: 'Schedule name' })).not.toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: 'Report Title' })).toHaveValue('');
+ });
+
+ it('retains a refused save for deliberate retry and keeps feedback inside its reader', async () => {
+ api.mockImplementation((url: string, init: RequestInit) =>
+ Promise.resolve(
+ init?.method === 'POST'
+ ? json({ error: 'Synthetic report save refused' }, 403)
+ : json(url.endsWith('/schedules') ? { schedules: [schedule()] } : catalog),
+ ),
+ );
+ const view = mount();
+ await ready();
+ await draft();
+ await fireEvent.change(screen.getByRole('combobox', { name: 'Report type' }), {
+ target: { value: 'vm_inventory' },
+ });
+ await fireEvent.click(screen.getByRole('button', { name: 'Save schedule' }));
+ await screen.findByRole('alert');
+ expect(screen.getByRole('textbox', { name: 'Schedule name' })).toHaveValue('Private draft');
+ expect(api.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1);
+ await fireEvent.click(screen.getByRole('button', { name: 'Save schedule' }));
+ await waitFor(() =>
+ expect(api.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(2),
+ );
+ view.setProps({ currentUser: 'operator-b', canRead: true });
+ await ready();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('withdraws read access and entitlement without reviving the old editor', async () => {
+ const view = mount();
+ await ready();
+ await draft();
+ view.setProps({ currentUser: 'operator-a', canRead: false });
+ expect(screen.queryByText('North private report')).not.toBeInTheDocument();
+ expect(screen.queryByRole('textbox', { name: 'Schedule name' })).not.toBeInTheDocument();
+ const count = api.mock.calls.length;
+ document.dispatchEvent(new Event('visibilitychange'));
+ expect(api).toHaveBeenCalledTimes(count);
+ view.setProps({ currentUser: 'operator-a', canRead: true });
+ await ready();
+ await draft();
+ setEnabled(false);
+ await waitFor(() =>
+ expect(screen.queryByRole('textbox', { name: 'Schedule name' })).not.toBeInTheDocument(),
+ );
+ expect(screen.queryByText('North private report')).not.toBeInTheDocument();
+ setEnabled(true);
+ await ready();
+ expect(screen.getByRole('textbox', { name: 'Report Title' })).toHaveValue('');
+ });
+
+ it('rejects an old organisation read, even when an id is reused', async () => {
+ const old = deferred<Response>();
+ api.mockImplementation((url: string) =>
+ url.endsWith('/schedules') ? old.promise : Promise.resolve(json(catalog)),
+ );
+ mount();
+ await screen.findByText('Loading report schedules...');
+ api.mockImplementation((url: string) =>
+ Promise.resolve(
+ json(url.endsWith('/schedules') ? { schedules: [schedule('South report')] } : catalog),
+ ),
+ );
+ org = 'other';
+ eventBus.emit('org_switched', org);
+ await screen.findByText('South report');
+ old.resolve(json({ schedules: [schedule()] }));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(screen.queryByText('North private report')).not.toBeInTheDocument();
+ expect(screen.getByText('South report')).toBeInTheDocument();
+ expect(
+ api.mock.calls.every(
+ ([, init]) =>
+ init.retry === false && init.expectedOrgID && init.signal instanceof AbortSignal,
+ ),
+ ).toBe(true);
+ });
+
+ it('does not publish a late saved response or close the next reader draft', async () => {
+ const pending = deferred<Response>();
+ api.mockImplementation((url: string, init: RequestInit) =>
+ init?.method === 'POST'
+ ? pending.promise
+ : Promise.resolve(json(url.endsWith('/schedules') ? { schedules: [schedule()] } : catalog)),
+ );
+ const view = mount();
+ await ready();
+ await draft();
+ // Inventory reports need no explicit resource selection.
+ await fireEvent.change(screen.getByRole('combobox', { name: 'Report type' }), {
+ target: { value: 'vm_inventory' },
+ });
+ await fireEvent.click(screen.getByRole('button', { name: 'Save schedule' }));
+ await waitFor(() =>
+ expect(api.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1),
+ );
+ const options = api.mock.calls.find(([, init]) => init?.method === 'POST')![1];
+ view.setProps({ currentUser: 'operator-b', canRead: true });
+ await ready();
+ await draft();
+ expect(options.signal.aborted).toBe(true);
+ pending.resolve(json(schedule('Old saved response')));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(screen.getByRole('textbox', { name: 'Schedule name' })).toHaveValue('Private draft');
+ expect(screen.queryByText('Old saved response')).not.toBeInTheDocument();
+ expect(screen.queryByText('Report schedule saved')).not.toBeInTheDocument();
+ });
+
+ it('does not download a body that completes after the workspace is withdrawn', async () => {
+ const pending = deferred<Blob>();
+ const response = new Response('synthetic');
+ vi.spyOn(response, 'blob').mockReturnValue(pending.promise);
+ api.mockImplementation((url: string) =>
+ Promise.resolve(
+ url.includes('/export')
+ ? response
+ : json(url.endsWith('/schedules') ? { schedules: [schedule()] } : catalog),
+ ),
+ );
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click');
+ const view = mount();
+ await ready();
+ await fireEvent.click(screen.getByRole('button', { name: 'Export VM Inventory' }));
+ await waitFor(() => expect(response.blob).toHaveBeenCalledOnce());
+ view.setProps({ currentUser: 'operator-b', canRead: true });
+ await ready();
+ pending.resolve(new Blob(['PRIVATE SYNTHETIC BODY']));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(click).not.toHaveBeenCalled();
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(screen.queryByText('VM inventory exported')).not.toBeInTheDocument();
+ });
+
+ it('keeps a malformed or refused schedule read unknown and offers explicit refresh', async () => {
+ api.mockImplementation((url: string) =>
+ Promise.resolve(json(url.endsWith('/schedules') ? {} : catalog)),
+ );
+ mount();
+ await screen.findByText('Report schedules are unavailable. Refresh to try again.');
+ expect(screen.queryByText('No scheduled reports are configured yet.')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Create schedule' })).toBeDisabled();
+ api.mockImplementation((url: string) =>
+ Promise.resolve(json(url.endsWith('/schedules') ? { schedules: [] } : catalog)),
+ );
+ await fireEvent.click(screen.getByRole('button', { name: 'Refresh' }));
+ await screen.findByText('No scheduled reports are configured yet.');
+ expect(screen.getAllByRole('button', { name: 'Create schedule' })[0]).toBeEnabled();
+ });
+
+ it('revalidates the reader after a delete confirmation and never changes another organisation', async () => {
+ mount();
+ await ready();
+ vi.spyOn(window, 'confirm').mockImplementation(() => {
+ org = 'other';
+ return true;
+ });
+ await fireEvent.click(screen.getByLabelText('Details for North private report'));
+ await fireEvent.click(screen.getByRole('button', { name: 'Delete North private report' }));
+ expect(api.mock.calls.some(([, init]) => init?.method === 'DELETE')).toBe(false);
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx
index ff179be36f..1c907165c8 100644
--- a/frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/ReportingPanel.test.tsx
@@ -74,6 +74,9 @@ const baseCatalog = {
function buildState(overrides: Record<string, unknown> = {}) {
return {
+ actionError: () => '',
+ successNotice: () => '',
+ canEditSchedules: () => true,
closeScheduleForm: vi.fn(),
deleteReportSchedule: vi.fn(),
deletingScheduleID: () => '',
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
index 6a5617547a..23e5d901a8 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsPanelRegistryContext.test.ts
@@ -150,6 +150,58 @@ describe('buildSettingsPanelRegistryContext', () => {
expect(context.getOrganizationSharingPanelProps()).toMatchObject({ currentUser: undefined });
expect(context.getApiAccessPanelProps()).toMatchObject({ currentUser: undefined });
});
+ it('binds Reporting to the live reader and explicit read capability', () => {
+ const [status, setStatus] = createSignal<SecurityStatus | null>(null);
+ const context = buildSettingsPanelRegistryContext({
+ ...buildParams(null),
+ securityStatus: status,
+ });
+ expect(context.getReportingPanelProps()).toEqual({
+ currentUser: undefined,
+ accessKey: '[null,null]',
+ canRead: false,
+ });
+ setStatus({
+ currentUsername: 'report-reader',
+ settingsCapabilities: { reportingRead: true },
+ } as SecurityStatus);
+ expect(context.getReportingPanelProps()).toEqual({
+ currentUser: 'report-reader',
+ accessKey: '[null,null]',
+ canRead: true,
+ });
+ setStatus({
+ currentUsername: '',
+ settingsCapabilities: { reportingRead: false },
+ } as SecurityStatus);
+ expect(context.getReportingPanelProps()).toEqual({
+ currentUser: '',
+ accessKey: '[null,null]',
+ canRead: false,
+ });
+ });
+ it('normalizes Reporting scope order without hiding credential or scope changes', () => {
+ const [status, setStatus] = createSignal<SecurityStatus | null>({
+ currentUsername: 'operator',
+ apiTokenHint: 'hint-a',
+ tokenScopes: ['settings:write', 'settings:read'],
+ } as SecurityStatus);
+ const context = buildSettingsPanelRegistryContext({
+ ...buildParams(null),
+ securityStatus: status,
+ });
+ const key = context.getReportingPanelProps().accessKey;
+ setStatus({ ...status(), tokenScopes: ['settings:read', 'settings:write'] } as SecurityStatus);
+ expect(context.getReportingPanelProps().accessKey).toBe(key);
+ setStatus({ ...status(), tokenScopes: ['settings:read'] } as SecurityStatus);
+ expect(context.getReportingPanelProps().accessKey).not.toBe(key);
+ setStatus({
+ ...status(),
+ apiTokenHint: 'hint-b',
+ tokenScopes: ['settings:read', 'settings:write'],
+ } as SecurityStatus);
+ expect(context.getReportingPanelProps().accessKey).not.toBe(key);
+ });
it('binds audit webhooks to the live principal and explicit read/write capabilities', () => {
const [status, setStatus] = createSignal<SecurityStatus | null>(null);
const context = buildSettingsPanelRegistryContext({
diff --git a/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts b/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
index ad8813d059..b1d525cb75 100644
--- a/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/useReportingPanelState.test.ts
@@ -204,7 +204,7 @@ describe('useReportingPanelState', () => {
const createElement = vi.spyOn(document, 'createElement');
try {
await hookState.handleExportVMInventory();
- expect(showWarningMock).toHaveBeenCalledExactlyOnceWith(message);
+ expect(hookState.actionError()).toBe(message);
expect(showSuccessMock).not.toHaveBeenCalled();
expect(createElement).not.toHaveBeenCalledWith('a');
expect(hookState.exportingInventory()).toBe(false);
@@ -221,7 +221,14 @@ describe('useReportingPanelState', () => {
expect(loadRuntimeLicenseStatusMock).toHaveBeenCalledOnce();
expect(loadCommercialLicenseStatusMock).not.toHaveBeenCalled();
- expect(apiFetchMock).toHaveBeenCalledWith('/api/admin/reports/catalog');
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/admin/reports/catalog',
+ expect.objectContaining({
+ expectedOrgID: 'default',
+ retry: false,
+ signal: expect.any(AbortSignal),
+ }),
+ );
expect(hookState.reportingCatalog()?.performanceReport.defaultFormat).toBe('csv');
expect(hookState.format()).toBe('csv');
expect(hookState.range()).toBe('7d');
@@ -235,7 +242,14 @@ describe('useReportingPanelState', () => {
await settleMountLoads(hookState);
- expect(apiFetchMock).toHaveBeenCalledWith('/api/admin/reports/catalog');
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/admin/reports/catalog',
+ expect.objectContaining({
+ expectedOrgID: 'default',
+ retry: false,
+ signal: expect.any(AbortSignal),
+ }),
+ );
expect(hookState.reportingCatalog()?.title).toBe('Detailed Reporting');
expect(hookState.reportingCatalog()?.lockedState.title).toBe('Advanced Reporting');
expect(hookState.isLocked()).toBe(true);
@@ -290,7 +304,14 @@ describe('useReportingPanelState', () => {
expect(loadRuntimeLicenseStatusMock).toHaveBeenCalledOnce();
expect(loadCommercialLicenseStatusMock).not.toHaveBeenCalled();
- expect(apiFetchMock).toHaveBeenCalledWith('/api/admin/reports/catalog');
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/admin/reports/catalog',
+ expect.objectContaining({
+ expectedOrgID: 'default',
+ retry: false,
+ signal: expect.any(AbortSignal),
+ }),
+ );
expect(hookState.reportingCatalog()?.title).toBe('Detailed Reporting');
expect(hookState.isLocked()).toBe(false);
expect(hookState.isReportingEnabled()).toBe(false);
@@ -638,7 +659,7 @@ describe('useReportingPanelState', () => {
hookState.updateScheduleForm({ name: 'Monthly clients' });
await hookState.saveReportSchedule();
- expect(showWarningMock).toHaveBeenCalledWith('Select resources or enter at least one tag');
+ expect(hookState.actionError()).toBe('Select resources or enter at least one tag');
expect(
apiFetchMock.mock.calls.some(
([, init]) => (init as RequestInit | undefined)?.method === 'POST',
@@ -670,22 +691,31 @@ describe('useReportingPanelState', () => {
});
const { hookState, dispose } = mountHook();
await settleMountLoads(hookState);
- await hookState.runReportScheduleNow(failed);
+ await hookState.runReportScheduleNow(hookState.reportSchedules()[0]);
expect(apiFetchMock).toHaveBeenCalledWith(
'/api/admin/reports/schedules/weekly/run?retry=true',
- { method: 'POST' },
+ expect.objectContaining({ method: 'POST', expectedOrgID: 'default', retry: false }),
);
- expect(showWarningMock).toHaveBeenCalledWith(failed.last_error);
+ expect(hookState.actionError()).toBe(failed.last_error);
expect(hookState.reportSchedules()[0].last_run_status).toBe('failed');
dispose();
});
it('requires deliberate confirmation before retrying uncertain acceptance', async () => {
const confirm = vi.spyOn(window, 'confirm').mockReturnValue(false);
+ apiFetchMock.mockImplementation((url: string) =>
+ Promise.resolve(
+ jsonResponse(
+ url.endsWith('/schedules')
+ ? { schedules: [deliverySchedule('unconfirmed')] }
+ : catalogPayload,
+ ),
+ ),
+ );
const { hookState, dispose } = mountHook();
await settleMountLoads(hookState);
apiFetchMock.mockClear();
- await hookState.runReportScheduleNow(deliverySchedule('unconfirmed'));
+ await hookState.runReportScheduleNow(hookState.reportSchedules()[0]);
expect(confirm).toHaveBeenCalledWith(expect.stringContaining('risk of a duplicate'));
expect(apiFetchMock).not.toHaveBeenCalled();
confirm.mockRestore();
@@ -706,7 +736,10 @@ describe('useReportingPanelState', () => {
apiFetchMock.mockClear();
document.dispatchEvent(new Event('visibilitychange'));
await vi.waitFor(() =>
- expect(apiFetchMock).toHaveBeenCalledWith('/api/admin/reports/schedules'),
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ '/api/admin/reports/schedules',
+ expect.objectContaining({ retry: false }),
+ ),
);
await settleMountLoads(hookState);
dispose();
@@ -758,7 +791,7 @@ describe('useReportingPanelState', () => {
await settleMountLoads(hookState);
await hookState.toggleReportSchedule(hookState.reportSchedules()[0]);
expect(hookState.reportSchedules()[0].enabled).toBe(false);
- expect(showSuccessMock).toHaveBeenCalledWith('Report schedule disabled');
+ expect(hookState.successNotice()).toBe('Report schedule disabled');
dispose();
});
});
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
index 28dc86812c..ce83174af0 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistry.ts
@@ -10,6 +10,7 @@ import type { APIAccessPanel as APIAccessPanelType } from './APIAccessPanel';
import type { SecurityOverviewPanel as SecurityOverviewPanelType } from './SecurityOverviewPanel';
import type { SecurityAuthPanel as SecurityAuthPanelType } from './SecurityAuthPanel';
import type { RelaySettingsPanel as RelaySettingsPanelType } from './RelaySettingsPanel';
+import type { ReportingPanel as ReportingPanelType } from './ReportingPanel';
import type { AuditWebhookPanel as AuditWebhookPanelType } from './AuditWebhookPanel';
import type { RolesPanel as RolesPanelType } from './RolesPanel';
import type { UserAssignmentsPanel as UserAssignmentsPanelType } from './UserAssignmentsPanel';
@@ -45,6 +46,7 @@ export interface SettingsPanelRegistryContext {
getSecurityOverviewPanelProps: () => Parameters<typeof SecurityOverviewPanelType>[0];
getSecurityAuthPanelProps: () => Parameters<typeof SecurityAuthPanelType>[0];
getRelayPanelProps: () => Parameters<typeof RelaySettingsPanelType>[0];
+ getReportingPanelProps: () => Parameters<typeof ReportingPanelType>[0];
getAuditWebhookPanelProps: () => Parameters<typeof AuditWebhookPanelType>[0];
getRolesPanelProps: () => Parameters<typeof RolesPanelType>[0];
getUserAssignmentsPanelProps: () => Parameters<typeof UserAssignmentsPanelType>[0];
@@ -96,6 +98,7 @@ export const createSettingsPanelRegistry = (
},
'support-reporting': {
component: SETTINGS_PANEL_REGISTRY_LOADERS.ReportingPanel,
+ getProps: context.getReportingPanelProps,
},
'support-logs': {
component: SETTINGS_PANEL_REGISTRY_LOADERS.SystemLogsPanel,
diff --git a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
index 091b075ae6..67f9e6bd58 100644
--- a/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
+++ b/frontend-modern/src/components/Settings/settingsPanelRegistryContext.tsx
@@ -124,6 +124,15 @@ export function buildSettingsPanelRegistryContext(
getRelayPanelProps: () => ({
canManage: settingsCapabilities()?.relayWrite === true,
}),
+ getReportingPanelProps: () => ({
+ currentUser: currentUser(),
+ // Non-secret identity facts only; equal scope sets keep the same workspace.
+ accessKey: JSON.stringify([
+ params.securityStatus()?.apiTokenHint,
+ params.securityStatus()?.tokenScopes?.slice().sort(),
+ ]),
+ canRead: settingsCapabilities()?.reportingRead === true,
+ }),
getAuditWebhookPanelProps: () => ({
currentUser: currentUser(),
canRead: settingsCapabilities()?.auditWebhooksRead === true,
diff --git a/frontend-modern/src/components/Settings/useReportingPanelState.ts b/frontend-modern/src/components/Settings/useReportingPanelState.ts
index 80b01ab128..1b5b588b35 100644
--- a/frontend-modern/src/components/Settings/useReportingPanelState.ts
+++ b/frontend-modern/src/components/Settings/useReportingPanelState.ts
@@ -1,7 +1,6 @@
import { createEffect, createSignal, onMount, onCleanup, untrack } from 'solid-js';
import { createStore, reconcile, unwrap } from 'solid-js/store';
-import { apiErrorFromResponse, apiFetch } from '@/utils/apiClient';
-import { showSuccess, showWarning } from '@/utils/toast';
+import { apiErrorFromResponse, apiFetch, getOrgID } from '@/utils/apiClient';
import { aiAvailabilityStore } from '@/stores/aiAvailability';
import type { SelectedResource } from '@/components/Settings/ResourcePicker';
import { hasFeature, runtimeCapabilitiesLoaded } from '@/stores/license';
@@ -45,7 +44,52 @@ import {
type ReportScheduleKind,
} from '@/components/Settings/reportingSchedulesModel';
-export const useReportingPanelState = () => {
+export const useReportingPanelState = (isCurrentReader: () => boolean = () => true) => {
+ const org = getOrgID() || 'default';
+ let disposed = false;
+ const controller = new AbortController();
+ const isActive = () => !disposed && isCurrentReader() && (getOrgID() || 'default') === org;
+ const assertActive = () => {
+ if (!isActive()) throw new Error('Reporting reader changed');
+ };
+ const fetchForReader = async (...[url, init]: Parameters<typeof apiFetch>) => {
+ assertActive();
+ const response = await apiFetch(url, {
+ ...init,
+ expectedOrgID: org,
+ retry: false,
+ signal: controller.signal,
+ });
+ assertActive();
+ return response;
+ };
+ const readJSON = async (response: Response) => {
+ const body = await response.json();
+ assertActive();
+ return body;
+ };
+ const [actionError, setActionError] = createSignal('');
+ const [successNotice, setSuccessNotice] = createSignal('');
+ const showWarning = (message: string) => {
+ if (isActive()) {
+ setSuccessNotice('');
+ setActionError(message);
+ }
+ };
+ const showSuccess = (message: string) => {
+ if (isActive()) {
+ setActionError('');
+ setSuccessNotice(message);
+ }
+ };
+ const clearFeedback = () => {
+ setActionError('');
+ setSuccessNotice('');
+ };
+ onCleanup(() => {
+ disposed = true;
+ controller.abort();
+ });
const [selectedResources, setSelectedResources] = createSignal<SelectedResource[]>([]);
const [metricType, setMetricType] = createSignal('');
const [format, setFormat] = createSignal<ReportingFormat | null>(null);
@@ -81,6 +125,7 @@ export const useReportingPanelState = () => {
const [savingSchedule, setSavingSchedule] = createSignal(false);
const [runningScheduleID, setRunningScheduleID] = createSignal('');
const [deletingScheduleID, setDeletingScheduleID] = createSignal('');
+ const [updatingSchedule, setUpdatingSchedule] = createSignal(false);
const reportingFeatureId = () => reportingCatalog()?.id ?? '';
const showUpgradePrompts = () => !presentationPolicyHidesUpgradePrompts();
@@ -98,7 +143,7 @@ export const useReportingPanelState = () => {
});
const loadReportingCatalog = async () => {
- if (reportingCatalogLoading()) {
+ if (!isActive() || reportingCatalogLoading()) {
return;
}
@@ -107,7 +152,7 @@ export const useReportingPanelState = () => {
setReportingCatalogError('');
try {
const request = buildReportingCatalogRequest();
- const response = await apiFetch(request.url);
+ const response = await fetchForReader(request.url);
if (!response.ok) {
if (response.status === 404) {
setReportingCatalog(buildLegacyReportingCatalogFallback());
@@ -116,14 +161,14 @@ export const useReportingPanelState = () => {
throw await apiErrorFromResponse(response, getReportingCatalogErrorMessage());
}
- setReportingCatalog(parseReportingCatalog(await response.json()));
+ setReportingCatalog(parseReportingCatalog(await readJSON(response)));
} catch (error) {
- console.error('Reporting catalog error:', error);
+ if (!isActive()) return;
setReportingCatalogError(
error instanceof Error ? error.message : getReportingCatalogErrorMessage(),
);
} finally {
- setReportingCatalogLoading(false);
+ if (isActive()) setReportingCatalogLoading(false);
}
};
@@ -135,24 +180,48 @@ export const useReportingPanelState = () => {
void loadReportingCatalog();
});
- const loadReportSchedules = async () => {
- if (reportSchedulesLoading()) return;
+ const loadReportSchedules = async (afterMutation = false) => {
+ if (
+ !afterMutation &&
+ (savingSchedule() || updatingSchedule() || runningScheduleID() || deletingScheduleID())
+ )
+ return;
+ if (!isActive() || reportSchedulesLoading()) return;
setReportSchedulesAttempted(true);
setReportSchedulesLoading(true);
setReportSchedulesError('');
try {
- const response = await apiFetch('/api/admin/reports/schedules');
+ const response = await fetchForReader('/api/admin/reports/schedules');
if (!response.ok) {
throw await apiErrorFromResponse(response, 'Failed to load report schedules');
}
- setReportSchedules(parseReportSchedulesResponse(await response.json()));
+ const body = await readJSON(response);
+ // A malformed response is unknown, never evidence of an empty directory.
+ if (
+ !body ||
+ !('schedules' in body) ||
+ (body.schedules !== null &&
+ (!Array.isArray(body.schedules) ||
+ body.schedules.some(
+ (schedule: ReportSchedule) =>
+ !schedule ||
+ typeof schedule.id !== 'string' ||
+ !schedule.id ||
+ typeof schedule.name !== 'string',
+ ) ||
+ new Set(body.schedules.map((schedule: ReportSchedule) => schedule.id)).size !==
+ body.schedules.length))
+ ) {
+ throw new Error('Report schedules are unavailable. Refresh to try again.');
+ }
+ setReportSchedules(parseReportSchedulesResponse(body));
} catch (error) {
- console.error('Report schedules error:', error);
+ if (!isActive()) return;
setReportSchedulesError(
error instanceof Error ? error.message : 'Failed to load report schedules',
);
} finally {
- setReportSchedulesLoading(false);
+ if (isActive()) setReportSchedulesLoading(false);
}
};
@@ -199,8 +268,22 @@ export const useReportingPanelState = () => {
}
});
+ const canEditSchedules = () =>
+ isActive() &&
+ isReportingEnabled() &&
+ reportSchedulesAttempted() &&
+ !reportSchedulesLoading() &&
+ !reportSchedulesError() &&
+ !savingSchedule() &&
+ !updatingSchedule() &&
+ !runningScheduleID() &&
+ !deletingScheduleID();
+ const isCurrentSchedule = (schedule: ReportSchedule) =>
+ reportSchedules().some((current) => unwrap(current) === unwrap(schedule));
+
const downloadResponseBlob = async (filename: string, response: Response) => {
const blob = await response.blob();
+ assertActive();
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
@@ -208,13 +291,18 @@ export const useReportingPanelState = () => {
response.headers.get('Content-Disposition'),
filename,
);
- document.body.appendChild(anchor);
- anchor.click();
- window.URL.revokeObjectURL(url);
- document.body.removeChild(anchor);
+ try {
+ document.body.appendChild(anchor);
+ anchor.click();
+ } finally {
+ window.URL.revokeObjectURL(url);
+ anchor.remove();
+ }
};
const handleGenerate = async () => {
+ if (!isActive() || !isReportingEnabled() || generating()) return;
+ clearFeedback();
const resources = selectedResources();
if (resources.length === 0) {
showWarning(getReportingGenerateSelectionRequiredMessage());
@@ -244,7 +332,7 @@ export const useReportingPanelState = () => {
performanceReport,
);
- const response = await apiFetch(request.request.url, request.request.init);
+ const response = await fetchForReader(request.request.url, request.request.init);
if (!response.ok) {
throw await apiErrorFromResponse(response, getReportingGenerateErrorMessage());
}
@@ -253,15 +341,16 @@ export const useReportingPanelState = () => {
showSuccess(getReportingGenerateSuccessMessage());
} catch (error) {
- console.error('Report generation error:', error);
+ if (!isActive()) return;
showWarning(error instanceof Error ? error.message : getReportingGenerateErrorMessage());
} finally {
- setGenerating(false);
+ if (isActive()) setGenerating(false);
}
};
const handleExportVMInventory = async () => {
- if (exportingInventory()) return;
+ if (!isActive() || !isReportingEnabled() || exportingInventory()) return;
+ clearFeedback();
setExportingInventory(true);
try {
@@ -270,7 +359,7 @@ export const useReportingPanelState = () => {
throw new Error(getReportingInventoryExportErrorMessage());
}
const request = buildVMInventoryExportRequest(new Date(), inventoryDefinition);
- const response = await apiFetch(request.request.url);
+ const response = await fetchForReader(request.request.url);
if (!response.ok) {
throw await apiErrorFromResponse(response, getReportingInventoryExportErrorMessage());
}
@@ -278,12 +367,12 @@ export const useReportingPanelState = () => {
await downloadResponseBlob(request.filename, response);
showSuccess(getReportingInventoryExportSuccessMessage());
} catch (error) {
- console.error('VM inventory export error:', error);
+ if (!isActive()) return;
showWarning(
error instanceof Error ? error.message : getReportingInventoryExportErrorMessage(),
);
} finally {
- setExportingInventory(false);
+ if (isActive()) setExportingInventory(false);
}
};
@@ -310,12 +399,16 @@ export const useReportingPanelState = () => {
};
const startCreateSchedule = () => {
+ if (!canEditSchedules()) return;
+ clearFeedback();
setScheduleForm(DEFAULT_REPORT_SCHEDULE_FORM());
setScheduleResources([]);
setScheduleFormOpen(true);
};
const startEditSchedule = (schedule: ReportSchedule) => {
+ if (!canEditSchedules() || !isCurrentSchedule(schedule)) return;
+ clearFeedback();
const normalized = normalizeReportSchedule(schedule);
setScheduleForm(scheduleToForm(normalized));
setScheduleResources(scheduleToSelectedResources(normalized));
@@ -329,7 +422,8 @@ export const useReportingPanelState = () => {
};
const saveReportSchedule = async () => {
- if (savingSchedule()) return;
+ if (!canEditSchedules() || !scheduleFormOpen()) return;
+ clearFeedback();
const form = scheduleForm();
const payload = buildReportSchedulePayload(form, scheduleResources());
if (!payload.name) {
@@ -348,7 +442,7 @@ export const useReportingPanelState = () => {
setSavingSchedule(true);
try {
const isUpdate = form.id !== '';
- const response = await apiFetch(
+ const response = await fetchForReader(
isUpdate
? `/api/admin/reports/schedules/${encodeURIComponent(form.id)}`
: '/api/admin/reports/schedules',
@@ -361,7 +455,7 @@ export const useReportingPanelState = () => {
if (!response.ok) {
throw await apiErrorFromResponse(response, 'Failed to save report schedule');
}
- const saved = normalizeReportSchedule(await response.json());
+ const saved = normalizeReportSchedule(await readJSON(response));
setReportSchedules((current) => {
const index = current.findIndex((schedule) => schedule.id === saved.id);
if (index < 0) return [...current, saved];
@@ -370,13 +464,13 @@ export const useReportingPanelState = () => {
return next;
});
closeScheduleForm();
- await loadReportSchedules();
+ await loadReportSchedules(true);
showSuccess('Report schedule saved');
} catch (error) {
- console.error('Save report schedule error:', error);
+ if (!isActive()) return;
showWarning(error instanceof Error ? error.message : 'Failed to save report schedule');
} finally {
- setSavingSchedule(false);
+ if (isActive()) setSavingSchedule(false);
}
};
@@ -384,7 +478,7 @@ export const useReportingPanelState = () => {
const normalized = normalizeReportSchedule(schedule);
const payload = { ...normalized };
delete payload.delivery_check;
- const response = await apiFetch(
+ const response = await fetchForReader(
`/api/admin/reports/schedules/${encodeURIComponent(normalized.id)}`,
{
method: 'PUT',
@@ -395,26 +489,32 @@ export const useReportingPanelState = () => {
if (!response.ok) {
throw await apiErrorFromResponse(response, 'Failed to update report schedule');
}
- const saved = normalizeReportSchedule(await response.json());
+ const saved = normalizeReportSchedule(await readJSON(response));
setReportSchedules((current) =>
current.map((candidate) => (candidate.id === saved.id ? saved : candidate)),
);
- await loadReportSchedules();
+ await loadReportSchedules(true);
};
const toggleReportSchedule = async (schedule: ReportSchedule) => {
+ if (!canEditSchedules() || !isCurrentSchedule(schedule)) return;
+ clearFeedback();
const enabled = !schedule.enabled;
+ setUpdatingSchedule(true);
try {
await updateReportSchedule({ ...schedule, enabled });
showSuccess(enabled ? 'Report schedule enabled' : 'Report schedule disabled');
} catch (error) {
- console.error('Toggle report schedule error:', error);
+ if (!isActive()) return;
showWarning(error instanceof Error ? error.message : 'Failed to update report schedule');
+ } finally {
+ if (isActive()) setUpdatingSchedule(false);
}
};
const runReportScheduleNow = async (schedule: ReportSchedule) => {
- if (runningScheduleID()) return;
+ if (!canEditSchedules() || !isCurrentSchedule(schedule) || runningScheduleID()) return;
+ clearFeedback();
if (
schedule.last_run_status === 'unconfirmed' &&
!window.confirm(
@@ -422,10 +522,11 @@ export const useReportingPanelState = () => {
)
)
return;
+ if (!canEditSchedules() || !isCurrentSchedule(schedule)) return;
const retry = reportScheduleNeedsRetry(schedule);
setRunningScheduleID(schedule.id);
try {
- const response = await apiFetch(
+ const response = await fetchForReader(
`/api/admin/reports/schedules/${encodeURIComponent(schedule.id)}/run${retry ? '?retry=true' : ''}`,
{ method: 'POST' },
);
@@ -433,13 +534,14 @@ export const useReportingPanelState = () => {
.clone()
.json()
.catch(() => null);
+ assertActive();
if (body?.schedule) {
const updated = normalizeReportSchedule(body.schedule);
setReportSchedules((current) =>
current.map((candidate) => (candidate.id === updated.id ? updated : candidate)),
);
}
- await loadReportSchedules();
+ await loadReportSchedules(true);
if (!response.ok) {
if (body?.schedule) {
showWarning(body.schedule.last_error || reportScheduleLastRunLabel(body.schedule));
@@ -457,20 +559,22 @@ export const useReportingPanelState = () => {
body?.schedule ? reportScheduleLastRunLabel(body.schedule) : 'Report schedule ran',
);
} catch (error) {
- console.error('Run report schedule error:', error);
+ if (!isActive()) return;
showWarning(error instanceof Error ? error.message : 'Failed to run report schedule');
- await loadReportSchedules();
+ await loadReportSchedules(true);
} finally {
- setRunningScheduleID('');
+ if (isActive()) setRunningScheduleID('');
}
};
const deleteReportSchedule = async (schedule: ReportSchedule) => {
- if (deletingScheduleID()) return;
+ if (!canEditSchedules() || !isCurrentSchedule(schedule) || deletingScheduleID()) return;
+ clearFeedback();
if (!window.confirm(`Delete ${schedule.name}?`)) return;
+ if (!canEditSchedules() || !isCurrentSchedule(schedule)) return;
setDeletingScheduleID(schedule.id);
try {
- const response = await apiFetch(
+ const response = await fetchForReader(
`/api/admin/reports/schedules/${encodeURIComponent(schedule.id)}`,
{
method: 'DELETE',
@@ -482,14 +586,17 @@ export const useReportingPanelState = () => {
setReportSchedules((current) => current.filter((candidate) => candidate.id !== schedule.id));
showSuccess('Report schedule deleted');
} catch (error) {
- console.error('Delete report schedule error:', error);
+ if (!isActive()) return;
showWarning(error instanceof Error ? error.message : 'Failed to delete report schedule');
} finally {
- setDeletingScheduleID('');
+ if (isActive()) setDeletingScheduleID('');
}
};
return {
+ actionError,
+ successNotice,
+ canEditSchedules,
closeScheduleForm,
deleteReportSchedule,
deletingScheduleID,
@@ -510,13 +617,13 @@ export const useReportingPanelState = () => {
reportingCatalogError,
reportingCatalogLoading,
reloadReportingCatalog: () => {
- if (reportingCatalogLoading()) {
+ if (!isActive() || reportingCatalogLoading()) {
return;
}
void loadReportingCatalog();
},
reloadReportSchedules: () => {
- if (reportSchedulesLoading()) return;
+ if (!isActive() || reportSchedulesLoading()) return;
void loadReportSchedules();
},
runReportScheduleNow,