Files

166 lines
6.3 KiB
TypeScript

/**
* AK-P3 — Audit-Viewer (`/admin/audit`).
*
* Permission-gated (`admin_identity.audit.read`), server-side filtered list over the
* tamper-evident `AuditEvent` table (NOT the legacy `Log` model used by
* `/admin/audit-trails`). The loader builds the AuditListVM once (persisted
* summaryText + field-by-field beforeDiff/afterDiff since the AK-P3 core schema
* extension; derived summary + metadata fallback for legacy rows) and the route
* renders the interim `<AuditListPage vm actions />` screen (AD-28).
*/
import type { LoaderFunctionArgs, MetaFunction } from "react-router";
import { useLoaderData, useNavigate } from "react-router";
import { listAuditEvents, AUDIT_VIEWER_DEFAULT_PAGE_SIZE } from "@hivegrid/db/audit-events-query.server";
import { buildAuditListVM, type AuditListVM, type AuditListFilterState } from "@hivegrid/view-models";
import { useTranslation } from "react-i18next";
import { AuditListPage, type AuditListQuery } from "~/components/screens/audit/AuditListPage";
import { AdminPageHeader } from "~/components/screens/admin/AdminPageHeader";
import { Button } from "~/ui/components/Button";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
type LoaderData = {
title: string;
vm: AuditListVM;
};
export function parseFilters(url: URL): AuditListFilterState {
const get = (k: string) => url.searchParams.get(k)?.trim() || null;
const from = get("from");
const to = get("to");
return {
from: from && ISO_DATE.test(from) ? from : null,
to: to && ISO_DATE.test(to) ? to : null,
tenantId: get("tenantId"),
actorType: get("actorType"),
actorId: get("actorId"),
action: get("action"),
outcome: get("outcome"),
targetType: get("targetType"),
targetId: get("targetId"),
};
}
export function buildWhere(filters: AuditListFilterState): Record<string, unknown> {
const where: Record<string, unknown> = {};
if (filters.tenantId) where.tenantId = filters.tenantId;
if (filters.actorType) where.actorType = filters.actorType;
if (filters.actorId) where.actorId = filters.actorId;
if (filters.outcome) where.outcome = filters.outcome;
if (filters.targetType) where.targetType = filters.targetType;
if (filters.targetId) where.targetId = filters.targetId;
if (filters.action) where.action = { contains: filters.action, mode: "insensitive" };
if (filters.from || filters.to) {
const range: Record<string, Date> = {};
if (filters.from) range.gte = new Date(`${filters.from}T00:00:00.000Z`);
if (filters.to) {
const upper = new Date(`${filters.to}T00:00:00.000Z`);
upper.setUTCDate(upper.getUTCDate() + 1);
range.lt = upper;
}
where.createdAt = range;
}
return where;
}
export const loader = async ({ request }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const url = new URL(request.url);
const filters = parseFilters(url);
const pageRaw = Number.parseInt(url.searchParams.get("page") ?? "1", 10);
const page = Number.isFinite(pageRaw) && pageRaw > 0 ? pageRaw : 1;
const pageSize = AUDIT_VIEWER_DEFAULT_PAGE_SIZE;
// listAuditEvents lives in @hivegrid/db so the route stays free of findMany.
const { rows, total, take } = await runAsAdminIdentity(request, "admin_identity.audit.read", () =>
listAuditEvents({
where: buildWhere(filters),
take: pageSize,
skip: pageSize * (page - 1),
})
);
const vm = buildAuditListVM({
rows: rows.map((row) => ({
id: row.id,
createdAtIso: row.createdAt.toISOString(),
tenantId: row.tenantId,
actorType: row.actorType,
actorName: row.actorDisplayName ?? null,
actorEmail: row.actorEmail,
actorId: row.actorId,
action: row.action,
targetType: row.targetType,
targetId: row.targetId,
outcome: row.outcome,
hasMetadata: row.metadata != null,
metadata: row.metadata,
beforeDiff: row.beforeDiff,
afterDiff: row.afterDiff,
summaryText: row.summaryText,
})),
filter: filters,
pagination: { page, pageSize: take, total, totalPages: Math.max(1, Math.ceil(total / take)) },
canExport: true,
});
const data: LoaderData = {
title: `${t("settings:audit.viewer.title")} | ${process.env.APP_NAME}`,
vm,
};
return data;
};
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
export default function AuditViewerRoute() {
const { vm } = useLoaderData<LoaderData>();
const navigate = useNavigate();
const { t } = useTranslation(["settings", "translations"]);
function onApply(query: AuditListQuery) {
const params = new URLSearchParams();
if (query.from) params.set("from", query.from);
if (query.to) params.set("to", query.to);
if (query.tenantId) params.set("tenantId", query.tenantId);
if (query.actorType) params.set("actorType", query.actorType);
if (query.actorId) params.set("actorId", query.actorId);
if (query.action) params.set("action", query.action);
if (query.outcome) params.set("outcome", query.outcome);
if (query.targetType) params.set("targetType", query.targetType);
if (query.targetId) params.set("targetId", query.targetId);
if (query.page > 1) params.set("page", String(query.page));
navigate({ search: params.toString() ? `?${params.toString()}` : "" });
}
// Canonical admin-host link (host-aware alias, e.g. /audit-export) — matches
// how every other admin surface links internally.
const exportHref = adminPath("audit-export", { mode: "host-aware" });
const canExport = vm.status === "ready" && Boolean(vm.data?.canExport);
return (
<div className="flex w-full flex-col">
<AdminPageHeader
title={t("settings:audit.viewer.title")}
description={t("settings:audit.viewer.subtitle")}
actions={
canExport ? (
<a href={exportHref} className="no-underline" data-ui-id="ui.audit.list.export">
<Button variant="secondary">{t("settings:audit.viewer.exportLink")}</Button>
</a>
) : null
}
/>
<AuditListPage vm={vm} exportHref={exportHref} actions={{ onApply }} hideHeader />
</div>
);
}
export function ErrorBoundary() {
return <ServerError />;
}