feat: admin audit log (recording, storage, Audit log screen) #21
No files matched your search
@@ -67,7 +67,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
|
||||
|
||||
## 4. Portal
|
||||
|
||||
- [ ] 4.1 `/audit-log` list and `/audit-log/[id]` detail, with a proxy, a service and i18n keys (design decision 9).
|
||||
- [x] 4.1 `/audit-log` list and `/audit-log/[id]` detail, with a proxy, a service and i18n keys (design decision 9).
|
||||
- Tests first:
|
||||
- rows and filters go into the query;
|
||||
- the detail shows a before/after table and a field-name list;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import * as route from "./route";
|
||||
|
||||
const { GET } = route;
|
||||
const req = (url: string) => new Request(url) as unknown as Parameters<typeof GET>[0];
|
||||
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("/api/audit-log/[[...path]]", () => {
|
||||
it("is GET only", () => {
|
||||
expect(Object.keys(route).filter((k) => /^(GET|POST|PUT|PATCH|DELETE)$/.test(k))).toEqual(["GET"]);
|
||||
});
|
||||
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await GET(req("http://localhost/api/audit-log"), ctx())).status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses dot segments", async () => {
|
||||
expect((await GET(req("http://localhost/api/audit-log/.."), ctx([".."]))).status).toBe(400);
|
||||
expect((await GET(req("http://localhost/api/audit-log/."), ctx(["."]))).status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards the query to the list", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
|
||||
const res = await GET(req("http://localhost/api/audit-log?actor=a&page=0&size=20"), ctx());
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log?actor=a&page=0&size=20", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("forwards one event by encoded id", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: "a/b" } });
|
||||
await GET(req("http://localhost/api/audit-log/a%2Fb"), ctx(["a/b"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log/a%2Fb", { token: "jwt" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// Read-only proxy for /api/admin/audit-log[/<id>]; mobile-api owns the BO_AUDIT_LOG guard. Audit events are never writable from the portal, so GET is the only method.
|
||||
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||
const target = `/api/admin/audit-log${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
|
||||
const result = await callMobileApi<unknown>(target, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getAuditEvent: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/auditLog")>()),
|
||||
getAuditEvent: mocks.getAuditEvent,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", () => ({ useParams: () => ({ id: "e2" }) }));
|
||||
|
||||
import AuditEventPage from "./page";
|
||||
|
||||
const EVENT = {
|
||||
id: 2, companyId: 1, occurredAt: "2026-11-30T15:52:00.5", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE",
|
||||
httpMethod: "PUT", pathTemplate: "/api/admin/users/{id}", targetId: "42", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null as string | null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getAuditEvent.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("AuditEventPage", () => {
|
||||
it("gates on BO_AUDIT_LOG", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<AuditEventPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.getAuditEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a before/after table for put-style changes", async () => {
|
||||
const changes = JSON.stringify({
|
||||
roles: { before: ["A"], after: ["A", "B"] },
|
||||
enabled: { before: false, after: true },
|
||||
lockout: { before: { status: "Y", value: 5 }, after: null },
|
||||
});
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes });
|
||||
render(<AuditEventPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("columnheader").map((h) => h.textContent)).toEqual(["Field", "Before", "After"]);
|
||||
const rows = within(table).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("rolesAA, B");
|
||||
expect(rows[1]).toHaveTextContent("enabledfalsetrue");
|
||||
expect(rows[2]).toHaveTextContent("lockoutstatus: Y, value: 5—");
|
||||
expect(screen.getByText("sales1")).toBeInTheDocument();
|
||||
expect(screen.getByText("/api/admin/users/{id}", { exact: false })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders module grants with a dash before and joined codes after", async () => {
|
||||
const changes = JSON.stringify({
|
||||
modulesAdded: { before: null, after: ["BO_USERS", "BO_LEADS"] },
|
||||
modulesRemoved: { before: null, after: ["BO_EVENTS"] },
|
||||
});
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes });
|
||||
render(<AuditEventPage />);
|
||||
const rows = within(await screen.findByRole("table")).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("modulesAdded—BO_USERS, BO_LEADS");
|
||||
expect(rows[1]).toHaveTextContent("modulesRemoved—BO_EVENTS");
|
||||
});
|
||||
|
||||
it("lists field names only for {fields: [...]}", async () => {
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes: JSON.stringify({ fields: ["phone", "notes"] }) });
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("phone")).toBeInTheDocument();
|
||||
expect(screen.getByText("notes")).toBeInTheDocument();
|
||||
expect(screen.getByText("Values are not recorded for these fields.")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("table")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows unparsable changes as plain text", async () => {
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes: "not json {" });
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("not json {")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a message when the event is not found", async () => {
|
||||
mocks.getAuditEvent.mockRejectedValue(new ApiError("NOT_FOUND", 404));
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("Audit event not found")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Back to audit log" })).toHaveAttribute("href", "/audit-log");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { formatEmailDate } from "@/app/lib/services/adminEmails";
|
||||
import { getAuditEvent, type AuditEvent } from "@/app/lib/services/auditLog";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
type Parsed = { kind: "fields"; fields: string[] } | { kind: "diff"; rows: [string, unknown, unknown][] } | { kind: "text"; text: string };
|
||||
|
||||
function parseChanges(raw: string): Parsed {
|
||||
try {
|
||||
const obj: unknown = JSON.parse(raw);
|
||||
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
||||
const rec = obj as Record<string, unknown>;
|
||||
if (Array.isArray(rec.fields)) return { kind: "fields", fields: rec.fields.map(String) };
|
||||
const rows = Object.entries(rec).map(([k, v]): [string, unknown, unknown] => {
|
||||
const c = (v ?? {}) as { before?: unknown; after?: unknown };
|
||||
return [k, c.before, c.after];
|
||||
});
|
||||
return { kind: "diff", rows };
|
||||
}
|
||||
} catch { /* shown as plain text below */ }
|
||||
return { kind: "text", text: raw };
|
||||
}
|
||||
|
||||
const show = (v: unknown): string => {
|
||||
if (v === null || v === undefined) return "—";
|
||||
if (Array.isArray(v)) return v.map(show).join(", ");
|
||||
if (typeof v === "object") return Object.entries(v).map(([k, x]) => `${k}: ${show(x)}`).join(", ");
|
||||
return String(v);
|
||||
};
|
||||
|
||||
function Changes({ raw }: { raw: string | null }) {
|
||||
const t = useT();
|
||||
const parsed = useMemo(() => (raw ? parseChanges(raw) : null), [raw]);
|
||||
if (!parsed) return <p className="text-sm text-muted-foreground">{t("AuditNoChanges")}</p>;
|
||||
if (parsed.kind === "text") return <pre className="overflow-x-auto whitespace-pre-wrap break-all text-sm">{parsed.text}</pre>;
|
||||
if (parsed.kind === "fields") {
|
||||
return (
|
||||
<div className="space-y-2 text-sm">
|
||||
<ul className="list-disc pl-5">{parsed.fields.map((f) => <li key={f}>{f}</li>)}</ul>
|
||||
<p className="text-muted-foreground">{t("AuditFieldsOnly")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("AuditField")}</TableHead>
|
||||
<TableHead>{t("AuditBefore")}</TableHead>
|
||||
<TableHead>{t("AuditAfter")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{parsed.rows.map(([field, before, after]) => (
|
||||
<TableRow key={field}>
|
||||
<TableCell className="font-medium">{field}</TableCell>
|
||||
<TableCell className="break-words whitespace-normal">{show(before)}</TableCell>
|
||||
<TableCell className="break-words whitespace-normal">{show(after)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
|
||||
function AuditEventContent() {
|
||||
const t = useT();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [event, setEvent] = useState<AuditEvent | null>(null);
|
||||
const [error, setError] = useState<"notFound" | "failed" | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- clears the previous event/error before the id-triggered fetch below.
|
||||
setEvent(null);
|
||||
setError(null);
|
||||
getAuditEvent(id)
|
||||
.then((e) => { if (!cancelled) setEvent(e); })
|
||||
.catch((err: unknown) => { if (!cancelled) setError(err instanceof ApiError && err.status === 404 ? "notFound" : "failed"); });
|
||||
return () => { cancelled = true; };
|
||||
}, [id]);
|
||||
|
||||
const back = <Link href="/audit-log" className="mt-4 inline-block text-primary underline-offset-4 hover:underline">{t("AuditBack")}</Link>;
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
{error === "notFound" ? <EmptyState title={t("AuditNotFound")} /> : <ErrorState message={t("AuditLoadFailed")} className="mb-4" />}
|
||||
{back}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!event) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title={event.action} />
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-sm">
|
||||
<dt className="text-muted-foreground">{t("LsTime")}</dt>
|
||||
<dd>{formatEmailDate(event.occurredAt)}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditWho")}</dt>
|
||||
<dd className="break-all">{event.actor}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditModule")}</dt>
|
||||
<dd>{event.module ? t(event.module) : "—"}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditAction")}</dt>
|
||||
<dd>{event.action}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditRequest")}</dt>
|
||||
<dd className="break-all">{event.httpMethod} {event.pathTemplate}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditTarget")}</dt>
|
||||
<dd className="break-all">{event.targetId ?? "—"}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditOutcome")}</dt>
|
||||
<dd><Badge variant={event.outcome === "SUCCESS" ? "positive" : "negative"}>{event.outcome} {event.httpStatus}</Badge></dd>
|
||||
<dt className="text-muted-foreground">{t("LsIp")}</dt>
|
||||
<dd>{event.clientIp ?? "—"}</dd>
|
||||
</dl>
|
||||
<section className="space-y-2">
|
||||
<h2 className="text-base font-semibold">{t("AuditChanges")}</h2>
|
||||
<Changes raw={event.changes} />
|
||||
</section>
|
||||
{back}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuditEventPage() {
|
||||
return (
|
||||
<RequireModule pathname="/audit-log">
|
||||
<AuditEventContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ searchAuditLog: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/auditLog")>()),
|
||||
searchAuditLog: mocks.searchAuditLog,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import AuditLogPage from "./page";
|
||||
|
||||
const EVENTS = [
|
||||
{ id: 2, companyId: 1, occurredAt: "2026-11-30T15:52:00.5", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/api/admin/users/{id}", targetId: "42", outcome: "FAILURE", httpStatus: 403, clientIp: "10.0.0.5", changes: null },
|
||||
{ id: 1, companyId: 1, occurredAt: "2026-11-29T09:05:00", actor: "admin", module: null, action: "LEAD_EXPORT", httpMethod: "GET", pathTemplate: "/api/admin/leads/export", targetId: null, outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.6", changes: null },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/audit-log");
|
||||
mocks.searchAuditLog.mockReset().mockResolvedValue({ items: EVENTS, total: 2 });
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("AuditLogPage", () => {
|
||||
it("renders NotAuthorized without BO_AUDIT_LOG", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<AuditLogPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.searchAuditLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lists rows with module label, outcome badge with status, and a link to the detail", async () => {
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
const rows = within(table).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("30/11/2026 15:52");
|
||||
expect(rows[0]).toHaveTextContent("sales1");
|
||||
expect(rows[0]).toHaveTextContent("Users");
|
||||
expect(rows[0]).toHaveTextContent("USER_UPDATE");
|
||||
expect(rows[0]).toHaveTextContent("FAILURE 403");
|
||||
expect(rows[0]).toHaveTextContent("10.0.0.5");
|
||||
expect(within(rows[0]).getByRole("link", { name: "USER_UPDATE" })).toHaveAttribute("href", "/audit-log/2");
|
||||
expect(rows[1]).toHaveTextContent("SUCCESS 200");
|
||||
});
|
||||
|
||||
it("labels lead modules and offers them in the module filter, without BO_AUDIT_LOG", async () => {
|
||||
mocks.searchAuditLog.mockResolvedValue({ items: [{ ...EVENTS[1], module: "BO_LEADS_EXPORT" }], total: 1 });
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("row")[1]).toHaveTextContent("Lead export");
|
||||
await userEvent.click(screen.getByRole("combobox", { name: "Module" }));
|
||||
expect(await screen.findByRole("option", { name: "Lead editing" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("option", { name: "Lead export" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("option", { name: "Audit log" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a dash for a null module", async () => {
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("row")[2]).toHaveTextContent("admin—LEAD_EXPORT");
|
||||
});
|
||||
|
||||
it("puts the filters in the query", async () => {
|
||||
memoryRouter.reset("/audit-log", "outcome=FAILURE&from=2026-11-01&module=BO_USERS");
|
||||
render(<AuditLogPage />);
|
||||
await screen.findByRole("table");
|
||||
expect(mocks.searchAuditLog).toHaveBeenCalledWith(expect.objectContaining({ outcome: "FAILURE", from: "2026-11-01", module: "BO_USERS", page: 1, pageSize: 20 }));
|
||||
await userEvent.type(screen.getByRole("searchbox", { name: "Who" }), "sales");
|
||||
await waitFor(() => expect(mocks.searchAuditLog).toHaveBeenLastCalledWith(expect.objectContaining({ actor: "sales", outcome: "FAILURE" })));
|
||||
});
|
||||
|
||||
it("shows an empty state and an error state", async () => {
|
||||
mocks.searchAuditLog.mockResolvedValue({ items: [], total: 0 });
|
||||
const { unmount } = render(<AuditLogPage />);
|
||||
expect(await screen.findByText("No audit events found")).toBeInTheDocument();
|
||||
unmount();
|
||||
mocks.searchAuditLog.mockRejectedValue(new Error("x"));
|
||||
render(<AuditLogPage />);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the audit log");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
||||
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { ROUTE_MODULES } from "@/app/lib/routeModules";
|
||||
import { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails";
|
||||
import { searchAuditLog, type AuditEvent } from "@/app/lib/services/auditLog";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const DEFAULTS = { actor: "", module: "", action: "", outcome: "", from: "", to: "" };
|
||||
// The backend stores the handler's @AdminModule code, so the filter lists those: the route modules plus the lead edit/export codes. Audit-log reads are never recorded.
|
||||
const MODULES = [...Object.values(ROUTE_MODULES).filter((m) => m !== "BO_AUDIT_LOG"), "BO_LEADS_EDIT", "BO_LEADS_EXPORT"];
|
||||
|
||||
function AuditLogContent() {
|
||||
const t = useT();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const [data, setData] = useState<{ items: AuditEvent[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
|
||||
setLoading(true);
|
||||
setFailed(false);
|
||||
searchAuditLog({ ...filters, page, pageSize })
|
||||
.then((result) => { if (!cancelled) setData(result); })
|
||||
.catch(() => { if (!cancelled) setFailed(true); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
}, [filters, page, reloadKey, pageSize]);
|
||||
|
||||
const moduleOptions = useMemo(() => MODULES.map((m) => ({ value: m, label: t(m) })), [t]);
|
||||
const outcomeOptions = useMemo(() => [{ value: "SUCCESS", label: t("AuditSuccess") }, { value: "FAILURE", label: t("AuditFailure") }], [t]);
|
||||
const cut = (text: string | null | undefined, max = "max-w-40") => <span className={`block truncate ${max}`} title={text ?? undefined}>{text}</span>;
|
||||
const columns = useMemo<ColumnDef<AuditEvent, unknown>[]>(
|
||||
() => [
|
||||
{ id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => <span className="whitespace-nowrap">{formatDate(row.original.occurredAt)}</span> },
|
||||
{ id: "actor", header: t("AuditWho"), enableSorting: false, cell: ({ row }) => cut(row.original.actor, "max-w-32") },
|
||||
{ id: "module", header: t("AuditModule"), enableSorting: false, cell: ({ row }) => (row.original.module ? t(row.original.module) : "—") },
|
||||
{
|
||||
id: "action",
|
||||
header: t("AuditAction"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Link href={`/audit-log/${row.original.id}`} title={row.original.action} className="block max-w-48 truncate font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
||||
{row.original.action}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{ id: "target", header: t("AuditTarget"), enableSorting: false, cell: ({ row }) => cut(row.original.targetId, "max-w-28") },
|
||||
{
|
||||
id: "outcome",
|
||||
header: t("AuditOutcome"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.outcome === "SUCCESS" ? "positive" : "negative"}>{row.original.outcome} {row.original.httpStatus}</Badge>
|
||||
),
|
||||
},
|
||||
{ accessorKey: "clientIp", header: t("LsIp"), enableSorting: false },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
{failed && <ErrorState message={t("AuditLoadFailed")} onRetry={refetch} className="mb-4" />}
|
||||
<FilterPanel activeCount={activeCount} onClear={clear}>
|
||||
<FilterField label={t("AuditWho")}>
|
||||
<FilterSearch className="w-full" aria-label={t("AuditWho")} value={filters.actor} onChange={(actor) => set({ actor })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditModule")}>
|
||||
<FilterSelect className="w-full" aria-label={t("AuditModule")} allLabel={t("AuditAllModules")} options={moduleOptions} value={filters.module} onChange={(module) => set({ module })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditAction")}>
|
||||
<FilterSearch className="w-full" aria-label={t("AuditAction")} value={filters.action} onChange={(action) => set({ action })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditOutcome")}>
|
||||
<FilterSelect className="w-full" aria-label={t("AuditOutcome")} allLabel={t("AuditAllOutcomes")} options={outcomeOptions} value={filters.outcome} onChange={(outcome) => set({ outcome })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsFrom")}>
|
||||
<DatePicker aria-label={t("LsFrom")} value={filters.from} onChange={(from) => set({ from })} max={filters.to || undefined} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsTo")}>
|
||||
<DatePicker aria-label={t("LsTo")} value={filters.to} onChange={(to) => set({ to })} min={filters.from || undefined} />
|
||||
</FilterField>
|
||||
</FilterPanel>
|
||||
<DataTable
|
||||
label={t("BO_AUDIT_LOG")}
|
||||
columns={columns}
|
||||
data={data.items}
|
||||
total={data.total}
|
||||
page={page}
|
||||
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
||||
tableRef={tableRef}
|
||||
onPageChange={setPage}
|
||||
isLoading={loading}
|
||||
rowKey={(r) => String(r.id)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("AuditNoMatch") : t("AuditNoEvents")} />}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuditLogPage() {
|
||||
return (
|
||||
<RequireModule pathname="/audit-log">
|
||||
<AuditLogContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -373,6 +373,30 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LsRulesSaved: "Password rules saved.",
|
||||
LsSettingsLoadFailed: "Failed to load the settings",
|
||||
LsSaveFailed: "Failed to save",
|
||||
BO_AUDIT_LOG: "Audit log",
|
||||
BO_LEADS_EDIT: "Lead editing",
|
||||
BO_LEADS_EXPORT: "Lead export",
|
||||
AuditWho: "Who",
|
||||
AuditModule: "Module",
|
||||
AuditAction: "Action",
|
||||
AuditTarget: "Target",
|
||||
AuditOutcome: "Outcome",
|
||||
AuditAllModules: "All modules",
|
||||
AuditAllOutcomes: "All outcomes",
|
||||
AuditSuccess: "Success",
|
||||
AuditFailure: "Failure",
|
||||
AuditNoEvents: "No audit events found",
|
||||
AuditNoMatch: "No audit events match your filters",
|
||||
AuditLoadFailed: "Failed to load the audit log",
|
||||
AuditNotFound: "Audit event not found",
|
||||
AuditBack: "Back to audit log",
|
||||
AuditRequest: "Request",
|
||||
AuditChanges: "Changes",
|
||||
AuditNoChanges: "No changes recorded.",
|
||||
AuditField: "Field",
|
||||
AuditBefore: "Before",
|
||||
AuditAfter: "After",
|
||||
AuditFieldsOnly: "Values are not recorded for these fields.",
|
||||
PwdRule_INPUT_LENGTH_MIN: "Minimum length",
|
||||
PwdRule_INPUT_LENGTH_MAX: "Maximum length",
|
||||
PwdRule_ALPHABET_LENGTH_MIN: "Minimum letters",
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("routeModules", () => {
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users"]);
|
||||
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
|
||||
expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/leads": "BO_LEADS",
|
||||
"/emails": "BO_EMAILS",
|
||||
"/login-security": "BO_LOGIN_SECURITY",
|
||||
"/audit-log": "BO_AUDIT_LOG",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import { getAuditEvent, searchAuditLog } from "./auditLog";
|
||||
|
||||
beforeEach(() => mocks.apiGet.mockReset());
|
||||
|
||||
describe("auditLog service", () => {
|
||||
it("searchAuditLog sends only non-empty filters with a 0-based page", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [{ id: "e1" }], totalElements: 9 });
|
||||
const out = await searchAuditLog({ actor: "admin", module: "", action: "USER_UPDATE", outcome: "FAILURE", from: "2026-11-01", to: "", page: 2, pageSize: 10 });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/audit-log?actor=admin&action=USER_UPDATE&outcome=FAILURE&from=2026-11-01&page=1&size=10");
|
||||
expect(out).toEqual({ items: [{ id: "e1" }], total: 9 });
|
||||
});
|
||||
|
||||
it("searchAuditLog tolerates an empty body", async () => {
|
||||
mocks.apiGet.mockResolvedValue(null);
|
||||
expect(await searchAuditLog({ page: 1, pageSize: 10 })).toEqual({ items: [], total: 0 });
|
||||
});
|
||||
|
||||
it("getAuditEvent GETs one event by encoded id", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ id: "a/b" });
|
||||
await getAuditEvent("a/b");
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/audit-log/a%2Fb");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { apiGet } from "@/app/lib/clientApi";
|
||||
|
||||
export interface AuditEvent {
|
||||
id: number;
|
||||
companyId: number;
|
||||
/** Server-local ISO datetime, e.g. "2026-11-30T15:52:00.5". */
|
||||
occurredAt: string;
|
||||
actor: string;
|
||||
module: string | null;
|
||||
action: string;
|
||||
httpMethod: string;
|
||||
pathTemplate: string;
|
||||
targetId: string | null;
|
||||
outcome: "SUCCESS" | "FAILURE";
|
||||
httpStatus: number;
|
||||
clientIp: string | null;
|
||||
/** JSON string: {"<field>": {before, after}} or {"fields": [...]}; null when nothing was recorded. */
|
||||
changes: string | null;
|
||||
}
|
||||
|
||||
export interface AuditLogParams {
|
||||
actor?: string;
|
||||
module?: string;
|
||||
action?: string;
|
||||
outcome?: string;
|
||||
/** "yyyy-MM-dd". */
|
||||
from?: string;
|
||||
to?: string;
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
const BASE = "/api/audit-log";
|
||||
|
||||
export async function searchAuditLog(params: AuditLogParams): Promise<{ items: AuditEvent[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of ["actor", "module", "action", "outcome", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: AuditEvent[]; totalElements?: number } | null>(`${BASE}?${qs}`);
|
||||
const items = Array.isArray(raw?.content) ? raw.content : [];
|
||||
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
|
||||
}
|
||||
|
||||
export const getAuditEvent = (id: string) => apiGet<AuditEvent>(`${BASE}/${encodeURIComponent(id)}`);
|
||||
Reference in new issue
Block a user