339 lines
14 KiB
TypeScript
339 lines
14 KiB
TypeScript
import { DescriptionItem, DescriptionList } from "@govoplan/core-webui";
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { Search } from "lucide-react";
|
|
import {
|
|
AdminPageLayout,
|
|
adminErrorMessage,
|
|
Button,
|
|
DataGrid,
|
|
Dialog,
|
|
DocumentationHelpLink,
|
|
formatAdminDateTime as formatDateTime,
|
|
hasScope,
|
|
i18nMessage,
|
|
mergeDeltaRows,
|
|
TableActionGroup,
|
|
useDeltaWatermarks,
|
|
type ApiSettings,
|
|
type AuthInfo,
|
|
type DataGridColumn,
|
|
type DataGridQueryState
|
|
} from "@govoplan/core-webui";
|
|
import {
|
|
downloadAuditEvidenceBundle,
|
|
exportAuditEvidenceBundle,
|
|
fetchAdminAudit,
|
|
fetchAdminAuditDelta,
|
|
type AuditAdminItem,
|
|
type AuditSortBy
|
|
} from "../../api/audit";
|
|
|
|
type Props = {
|
|
settings: ApiSettings;
|
|
auth: AuthInfo;
|
|
systemMode?: boolean;
|
|
};
|
|
type AuditDetailRow = {
|
|
id: string;
|
|
field: string;
|
|
value: string;
|
|
};
|
|
|
|
const I18N = {
|
|
actionLabel: "i18n:govoplan-audit.action.f1a20801",
|
|
actions: "i18n:govoplan-audit.actions.f1a20802",
|
|
actor: "i18n:govoplan-audit.actor.f1a20803",
|
|
close: "i18n:govoplan-audit.close.f1a20804",
|
|
details: "i18n:govoplan-audit.details.f1a20805",
|
|
eventDetails: "i18n:govoplan-audit.audit_event_details.f1a20806",
|
|
exportEvidence: "i18n:govoplan-audit.export_page_evidence.f1a20822",
|
|
exportingEvidence: "i18n:govoplan-audit.audit_evidence_export_is_in_progress.f1a20823",
|
|
inspect: "i18n:govoplan-audit.inspect_audit_event.f1a20807",
|
|
loading: "i18n:govoplan-audit.audit_evidence_is_loading.f1a20808",
|
|
noDetails: "i18n:govoplan-audit.no_additional_details_were_recorded.f1a20809",
|
|
noRecords: "i18n:govoplan-audit.no_audit_records_match_the_current_scope_and_filters.f1a20810",
|
|
object: "i18n:govoplan-audit.object.f1a20811",
|
|
reload: "i18n:govoplan-audit.reload_audit_evidence.f1a20812",
|
|
scopeLabel: "i18n:govoplan-audit.scope.f1a20813",
|
|
system: "i18n:govoplan-audit.system.f1a20814",
|
|
systemAudit: "i18n:govoplan-audit.system_audit.f1a20815",
|
|
systemDescription: "i18n:govoplan-audit.system_level_administrative_history_showing_value0_value1_of_value2.f1a20816",
|
|
tenantAudit: "i18n:govoplan-audit.tenant_audit.f1a20817",
|
|
tenantContext: "i18n:govoplan-audit.tenant_context.f1a20818",
|
|
tenantDescription: "i18n:govoplan-audit.tenant_level_administrative_history_showing_value0_value1_of_value2.f1a20819",
|
|
time: "i18n:govoplan-audit.time.f1a20820",
|
|
value: "i18n:govoplan-audit.value.f1a20821"
|
|
} as const;
|
|
|
|
const DEFAULT_QUERY: DataGridQueryState = {
|
|
sort: { columnId: "time", direction: "desc" },
|
|
filters: {}
|
|
};
|
|
|
|
export default function AdminAuditPanel({ settings, auth, systemMode = false }: Props) {
|
|
const [items, setItems] = useState<AuditAdminItem[]>([]);
|
|
const itemsRef = useRef<AuditAdminItem[]>([]);
|
|
const pageItemsRef = useRef<Record<string, AuditAdminItem[]>>({});
|
|
const pageCursorsRef = useRef<Record<number, string | null>>({ 1: null });
|
|
const { getDeltaWatermark, setDeltaWatermark, resetDeltaWatermark } = useDeltaWatermarks();
|
|
const [total, setTotal] = useState(0);
|
|
const [page, setPage] = useState(1);
|
|
const [pageSize, setPageSize] = useState(10);
|
|
const [query, setQuery] = useState<DataGridQueryState>(DEFAULT_QUERY);
|
|
const [selected, setSelected] = useState<AuditAdminItem | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState("");
|
|
const [reloadToken, setReloadToken] = useState(0);
|
|
const [exporting, setExporting] = useState(false);
|
|
const tenantId = (auth.active_tenant ?? auth.tenant).id;
|
|
const canExport = hasScope(
|
|
auth,
|
|
systemMode ? "audit:system_evidence:export" : "audit:evidence:export"
|
|
);
|
|
|
|
const load = useCallback(async () => {
|
|
setLoading(true);
|
|
setError("");
|
|
try {
|
|
const sortColumn = query.sort?.columnId;
|
|
const sortBy = sortColumn && ["time", "actor", "action", "object", "tenant"].includes(sortColumn)
|
|
? sortColumn as AuditSortBy
|
|
: "time";
|
|
const sortDirection = query.sort?.direction ?? "desc";
|
|
const filters = query.filters;
|
|
const pageCursor = page === 1 ? null : pageCursorsRef.current[page];
|
|
const deltaMode = page === 1 || pageCursor !== undefined;
|
|
const requestOptions = {
|
|
scope: systemMode ? "system" as const : "tenant" as const,
|
|
page,
|
|
pageSize,
|
|
cursor: pageCursor,
|
|
sortBy,
|
|
sortDirection,
|
|
filters
|
|
};
|
|
const deltaKey = `audit:${systemMode ? "system" : "tenant"}:${tenantId}:${pageSize}:${page}:${pageCursor ?? "root"}:${JSON.stringify({ sortBy, sortDirection, filters })}`;
|
|
const response = deltaMode
|
|
? await fetchAdminAuditDelta(settings, { ...requestOptions, since: getDeltaWatermark(deltaKey) })
|
|
: await fetchAdminAudit(settings, requestOptions);
|
|
const baseItems = pageItemsRef.current[deltaKey] ?? [];
|
|
const nextItems = "full" in response && !response.full
|
|
? mergeDeltaRows(baseItems, response.items, response.deleted, (item) => item.id, { sort: compareAuditEvents(sortBy, sortDirection) }).slice(0, pageSize)
|
|
: response.items;
|
|
pageItemsRef.current[deltaKey] = nextItems;
|
|
itemsRef.current = nextItems;
|
|
setItems(nextItems);
|
|
setTotal(response.total);
|
|
if (!deltaMode && response.page !== page) setPage(response.page);
|
|
if (response.cursor !== undefined) pageCursorsRef.current[page] = response.cursor ?? null;
|
|
if (response.next_cursor !== undefined) {
|
|
if (response.next_cursor) pageCursorsRef.current[page + 1] = response.next_cursor;
|
|
else delete pageCursorsRef.current[page + 1];
|
|
}
|
|
if ("full" in response && !response.full && page === 1 && (response.items.length > 0 || response.deleted.length > 0)) {
|
|
pageCursorsRef.current = { 1: null };
|
|
}
|
|
if ("watermark" in response) setDeltaWatermark(deltaKey, response.watermark);
|
|
if (!deltaMode) resetDeltaWatermark(deltaKey);
|
|
} catch (err) {
|
|
setError(adminErrorMessage(err));
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [settings.accessToken, settings.apiBaseUrl, settings.apiKey, systemMode, tenantId, page, pageSize, query, reloadToken, getDeltaWatermark, setDeltaWatermark, resetDeltaWatermark]);
|
|
|
|
useEffect(() => {
|
|
itemsRef.current = [];
|
|
pageItemsRef.current = {};
|
|
pageCursorsRef.current = { 1: null };
|
|
resetDeltaWatermark();
|
|
}, [settings.accessToken, settings.apiBaseUrl, settings.apiKey, systemMode, tenantId, pageSize, query, resetDeltaWatermark]);
|
|
|
|
useEffect(() => { void load(); }, [load]);
|
|
|
|
const handleQueryChange = useCallback((next: DataGridQueryState) => {
|
|
setQuery((current) => {
|
|
if (JSON.stringify(current) === JSON.stringify(next)) return current;
|
|
setPage(1);
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
const exportPageEvidence = useCallback(async () => {
|
|
setExporting(true);
|
|
setError("");
|
|
try {
|
|
const created = await exportAuditEvidenceBundle(settings, {
|
|
scope: systemMode ? "system" : "tenant",
|
|
tenant_id: systemMode ? null : tenantId,
|
|
record_ids: items.map((item) => item.id),
|
|
max_records: Math.max(1, items.length),
|
|
sign: false
|
|
});
|
|
const downloaded = await downloadAuditEvidenceBundle(settings, created.id);
|
|
downloadJson(
|
|
downloaded.bundle,
|
|
`govoplan-audit-evidence-${created.id}.json`
|
|
);
|
|
} catch (err) {
|
|
setError(adminErrorMessage(err));
|
|
} finally {
|
|
setExporting(false);
|
|
}
|
|
}, [items, settings, systemMode, tenantId]);
|
|
|
|
const columns = useMemo<DataGridColumn<AuditAdminItem>[]>(() => [
|
|
{ id: "time", header: I18N.time, width: 190, minWidth: 150, maxWidth: 260, resizable: true, sticky: "start", sortable: true, filterable: true, filterType: "date", value: (row) => row.created_at, render: (row) => formatDateTime(row.created_at) },
|
|
{ id: "actor", header: I18N.actor, width: 220, minWidth: 170, maxWidth: 360, resizable: true, sortable: true, filterable: true, value: (row) => row.actor_email || "System", render: (row) => row.actor_email || I18N.system },
|
|
{ id: "action", header: I18N.actionLabel, width: 250, minWidth: 170, maxWidth: 420, resizable: true, sortable: true, filterable: true, value: (row) => row.action },
|
|
{ id: "object", header: I18N.object, width: 300, minWidth: 180, maxWidth: 640, resizable: true, fill: true, sortable: true, filterable: true, value: (row) => `${row.object_type || "-"} ${row.object_id || ""}`.trim() },
|
|
...(systemMode ? [{ id: "tenant", header: I18N.tenantContext, width: 190, minWidth: 150, maxWidth: 300, resizable: true, sortable: true, filterable: true, value: (row: AuditAdminItem) => row.tenant_id || "-" }] : []),
|
|
{ id: "actions", header: I18N.actions, width: 70, sticky: "end", resizable: false, align: "right", render: (row) => <TableActionGroup actions={[{ id: "inspect", label: I18N.inspect, icon: <Search aria-hidden="true" size={16} />, onClick: () => setSelected(row) }]} /> }
|
|
], [systemMode]);
|
|
|
|
const detailColumns = useMemo<DataGridColumn<AuditDetailRow>[]>(() => [
|
|
{ id: "field", header: I18N.details, minWidth: 180, resizable: true, value: (row) => row.field },
|
|
{ id: "value", header: I18N.value, minWidth: 260, resizable: true, fill: true, value: (row) => row.value }
|
|
], []);
|
|
const detailRows = useMemo(() => auditDetailRows(selected?.details ?? {}), [selected]);
|
|
|
|
const firstShown = total === 0 ? 0 : (page - 1) * pageSize + 1;
|
|
const lastShown = Math.min(total, page * pageSize);
|
|
const pageDescription = i18nMessage(
|
|
systemMode ? I18N.systemDescription : I18N.tenantDescription,
|
|
{ value0: firstShown, value1: lastShown, value2: total }
|
|
);
|
|
|
|
return (
|
|
<>
|
|
<AdminPageLayout
|
|
title={systemMode ? I18N.systemAudit : I18N.tenantAudit}
|
|
description={pageDescription}
|
|
loading={loading}
|
|
error={error}
|
|
actions={(
|
|
<>
|
|
{canExport && (
|
|
<Button
|
|
onClick={() => { void exportPageEvidence(); }}
|
|
disabled={loading || exporting || items.length === 0}
|
|
disabledReason={exporting ? I18N.exportingEvidence : undefined}>
|
|
{I18N.exportEvidence}
|
|
</Button>
|
|
)}
|
|
<DocumentationHelpLink
|
|
reference={{
|
|
topicId: "audit.read-authorized-evidence",
|
|
documentationType: "user"
|
|
}} />
|
|
<Button
|
|
onClick={() => setReloadToken((value) => value + 1)}
|
|
disabled={loading}
|
|
disabledReason={loading ? I18N.loading : undefined}>
|
|
{I18N.reload}
|
|
</Button>
|
|
</>
|
|
)}>
|
|
<div className="admin-table-surface">
|
|
<DataGrid
|
|
id={systemMode ? "admin-system-audit-v6" : "admin-tenant-audit-v6"}
|
|
rows={items}
|
|
columns={columns}
|
|
initialFit="container"
|
|
getRowKey={(row) => row.id}
|
|
emptyText={I18N.noRecords}
|
|
className="admin-audit-grid"
|
|
initialSort={{ columnId: "time", direction: "desc" }}
|
|
pagination={{
|
|
mode: "server",
|
|
page,
|
|
pageSize,
|
|
totalRows: total,
|
|
pageSizeOptions: [10, 25, 50, 100, 250],
|
|
disabled: loading,
|
|
onPageChange: setPage,
|
|
onPageSizeChange: (next) => { setPageSize(next); setPage(1); }
|
|
}}
|
|
onQueryChange={handleQueryChange}
|
|
/>
|
|
</div>
|
|
</AdminPageLayout>
|
|
<Dialog variant="administration" size="wide"
|
|
open={Boolean(selected)}
|
|
title={I18N.eventDetails}
|
|
onClose={() => setSelected(null)}
|
|
className=""
|
|
footer={<Button onClick={() => setSelected(null)}>{I18N.close}</Button>}>
|
|
{selected && (
|
|
<>
|
|
<DescriptionList>
|
|
<DescriptionItem term={<>{I18N.scopeLabel}</>}>{selected.scope}</DescriptionItem>
|
|
<DescriptionItem term={<>{I18N.actionLabel}</>}>{selected.action}</DescriptionItem>
|
|
<DescriptionItem term={<>{I18N.actor}</>}>{selected.actor_email || I18N.system}</DescriptionItem>
|
|
<DescriptionItem term={<>{I18N.object}</>}>{selected.object_type || "-"} {selected.object_id || ""}</DescriptionItem>
|
|
<DescriptionItem term={<>{I18N.tenantContext}</>}>{selected.tenant_id || "-"}</DescriptionItem>
|
|
<DescriptionItem term={<>{I18N.time}</>}>{formatDateTime(selected.created_at)}</DescriptionItem>
|
|
</DescriptionList>
|
|
{detailRows.length ? (
|
|
<DataGrid
|
|
id="admin-audit-event-details-grid"
|
|
rows={detailRows}
|
|
columns={detailColumns}
|
|
getRowKey={(row) => row.id}
|
|
initialFit="container" />
|
|
) : <p className="muted">{I18N.noDetails}</p>}
|
|
</>
|
|
)}
|
|
</Dialog>
|
|
</>
|
|
);
|
|
}
|
|
|
|
function downloadJson(value: unknown, filename: string): void {
|
|
const blob = new Blob([`${JSON.stringify(value, null, 2)}\n`], { type: "application/json" });
|
|
const url = URL.createObjectURL(blob);
|
|
const anchor = document.createElement("a");
|
|
anchor.href = url;
|
|
anchor.download = filename;
|
|
anchor.click();
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
|
|
function auditDetailRows(details: Record<string, unknown>): AuditDetailRow[] {
|
|
return Object.entries(details)
|
|
.sort(([left], [right]) => left.localeCompare(right))
|
|
.map(([field, value]) => ({
|
|
id: field,
|
|
field,
|
|
value: auditDetailValue(value)
|
|
}));
|
|
}
|
|
|
|
function auditDetailValue(value: unknown): string {
|
|
if (value === null || value === undefined) return "-";
|
|
if (typeof value === "string") return value;
|
|
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
function compareAuditEvents(sortBy: AuditSortBy, sortDirection: "asc" | "desc"): (left: AuditAdminItem, right: AuditAdminItem) => number {
|
|
return (left, right) => {
|
|
const primary = compareAuditValues(auditSortValue(left, sortBy), auditSortValue(right, sortBy));
|
|
const directed = sortDirection === "asc" ? primary : -primary;
|
|
return directed || right.id.localeCompare(left.id);
|
|
};
|
|
}
|
|
|
|
function auditSortValue(item: AuditAdminItem, sortBy: AuditSortBy): string | number {
|
|
if (sortBy === "time") return new Date(item.created_at).getTime();
|
|
if (sortBy === "actor") return item.actor_email || "System";
|
|
if (sortBy === "action") return item.action;
|
|
if (sortBy === "object") return `${item.object_type || ""} ${item.object_id || ""}`;
|
|
return item.tenant_id || "";
|
|
}
|
|
|
|
function compareAuditValues(left: string | number, right: string | number): number {
|
|
if (typeof left === "number" && typeof right === "number") return left - right;
|
|
return String(left).localeCompare(String(right));
|
|
}
|