From 7fc3adfe0501dfb31ab4344da741e06af50d6af1 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 17:01:55 +0800 Subject: [PATCH] feat: admin portal Audit log list and detail Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- openspec/changes/add-admin-audit-log/tasks.md | 2 +- .../api/audit-log/[[...path]]/route.test.ts | 47 ++++++ .../app/api/audit-log/[[...path]]/route.ts | 18 +++ .../app/audit-log/[id]/page.test.tsx | 84 ++++++++++ .../app/audit-log/[id]/page.tsx | 150 ++++++++++++++++++ .../app/audit-log/page.test.tsx | 84 ++++++++++ solvway-admin-portal/app/audit-log/page.tsx | 126 +++++++++++++++ .../app/lib/i18n/defaultMessages.ts | 24 +++ .../app/lib/routeModules.test.ts | 2 +- solvway-admin-portal/app/lib/routeModules.ts | 1 + .../app/lib/services/auditLog.test.ts | 28 ++++ .../app/lib/services/auditLog.ts | 46 ++++++ 12 files changed, 610 insertions(+), 2 deletions(-) create mode 100644 solvway-admin-portal/app/api/audit-log/[[...path]]/route.test.ts create mode 100644 solvway-admin-portal/app/api/audit-log/[[...path]]/route.ts create mode 100644 solvway-admin-portal/app/audit-log/[id]/page.test.tsx create mode 100644 solvway-admin-portal/app/audit-log/[id]/page.tsx create mode 100644 solvway-admin-portal/app/audit-log/page.test.tsx create mode 100644 solvway-admin-portal/app/audit-log/page.tsx create mode 100644 solvway-admin-portal/app/lib/services/auditLog.test.ts create mode 100644 solvway-admin-portal/app/lib/services/auditLog.ts diff --git a/openspec/changes/add-admin-audit-log/tasks.md b/openspec/changes/add-admin-audit-log/tasks.md index 6747ef4..59b0e5c 100644 --- a/openspec/changes/add-admin-audit-log/tasks.md +++ b/openspec/changes/add-admin-audit-log/tasks.md @@ -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; diff --git a/solvway-admin-portal/app/api/audit-log/[[...path]]/route.test.ts b/solvway-admin-portal/app/api/audit-log/[[...path]]/route.test.ts new file mode 100644 index 0000000..577551b --- /dev/null +++ b/solvway-admin-portal/app/api/audit-log/[[...path]]/route.test.ts @@ -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[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" }); + }); +}); diff --git a/solvway-admin-portal/app/api/audit-log/[[...path]]/route.ts b/solvway-admin-portal/app/api/audit-log/[[...path]]/route.ts new file mode 100644 index 0000000..4dedbd4 --- /dev/null +++ b/solvway-admin-portal/app/api/audit-log/[[...path]]/route.ts @@ -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[/]; 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(target, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/audit-log/[id]/page.test.tsx b/solvway-admin-portal/app/audit-log/[id]/page.test.tsx new file mode 100644 index 0000000..adeb9f3 --- /dev/null +++ b/solvway-admin-portal/app/audit-log/[id]/page.test.tsx @@ -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()), + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + expect(await screen.findByText("Audit event not found")).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Back to audit log" })).toHaveAttribute("href", "/audit-log"); + }); +}); diff --git a/solvway-admin-portal/app/audit-log/[id]/page.tsx b/solvway-admin-portal/app/audit-log/[id]/page.tsx new file mode 100644 index 0000000..fea30fd --- /dev/null +++ b/solvway-admin-portal/app/audit-log/[id]/page.tsx @@ -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; + 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

{t("AuditNoChanges")}

; + if (parsed.kind === "text") return
{parsed.text}
; + if (parsed.kind === "fields") { + return ( +
+
    {parsed.fields.map((f) =>
  • {f}
  • )}
+

{t("AuditFieldsOnly")}

+
+ ); + } + return ( + + + + {t("AuditField")} + {t("AuditBefore")} + {t("AuditAfter")} + + + + {parsed.rows.map(([field, before, after]) => ( + + {field} + {show(before)} + {show(after)} + + ))} + +
+ ); +} + +function AuditEventContent() { + const t = useT(); + const { id } = useParams<{ id: string }>(); + const [event, setEvent] = useState(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 = {t("AuditBack")}; + + if (error) { + return ( + <> + + {error === "notFound" ? : } + {back} + + ); + } + if (!event) { + return ( + <> + + + + ); + } + + return ( +
+ +
+
{t("LsTime")}
+
{formatEmailDate(event.occurredAt)}
+
{t("AuditWho")}
+
{event.actor}
+
{t("AuditModule")}
+
{event.module ? t(event.module) : "—"}
+
{t("AuditAction")}
+
{event.action}
+
{t("AuditRequest")}
+
{event.httpMethod} {event.pathTemplate}
+
{t("AuditTarget")}
+
{event.targetId ?? "—"}
+
{t("AuditOutcome")}
+
{event.outcome} {event.httpStatus}
+
{t("LsIp")}
+
{event.clientIp ?? "—"}
+
+
+

{t("AuditChanges")}

+ +
+ {back} +
+ ); +} + +export default function AuditEventPage() { + return ( + + + + ); +} diff --git a/solvway-admin-portal/app/audit-log/page.test.tsx b/solvway-admin-portal/app/audit-log/page.test.tsx new file mode 100644 index 0000000..be33892 --- /dev/null +++ b/solvway-admin-portal/app/audit-log/page.test.tsx @@ -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()), + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + expect(await screen.findByText("No audit events found")).toBeInTheDocument(); + unmount(); + mocks.searchAuditLog.mockRejectedValue(new Error("x")); + render(); + expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the audit log"); + }); +}); diff --git a/solvway-admin-portal/app/audit-log/page.tsx b/solvway-admin-portal/app/audit-log/page.tsx new file mode 100644 index 0000000..8cd9839 --- /dev/null +++ b/solvway-admin-portal/app/audit-log/page.tsx @@ -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") => {text}; + const columns = useMemo[]>( + () => [ + { id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => {formatDate(row.original.occurredAt)} }, + { 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 }) => ( + + {row.original.action} + + ), + }, + { 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 }) => ( + {row.original.outcome} {row.original.httpStatus} + ), + }, + { accessorKey: "clientIp", header: t("LsIp"), enableSorting: false }, + ], + [t], + ); + + return ( + <> + + {failed && } + + + set({ actor })} /> + + + set({ module })} /> + + + set({ action })} /> + + + set({ outcome })} /> + + + set({ from })} max={filters.to || undefined} /> + + + set({ to })} min={filters.from || undefined} /> + + + String(r.id)} + empty={ 0 ? t("AuditNoMatch") : t("AuditNoEvents")} />} + /> + + ); +} + +export default function AuditLogPage() { + return ( + + + + ); +} diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index 1c7ba0a..26f5ff2 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -373,6 +373,30 @@ export const DEFAULT_MESSAGES: Record = { 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", diff --git a/solvway-admin-portal/app/lib/routeModules.test.ts b/solvway-admin-portal/app/lib/routeModules.test.ts index 3450412..1bda224 100644 --- a/solvway-admin-portal/app/lib/routeModules.test.ts +++ b/solvway-admin-portal/app/lib/routeModules.test.ts @@ -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"); }); diff --git a/solvway-admin-portal/app/lib/routeModules.ts b/solvway-admin-portal/app/lib/routeModules.ts index e6c7ba6..4495b64 100644 --- a/solvway-admin-portal/app/lib/routeModules.ts +++ b/solvway-admin-portal/app/lib/routeModules.ts @@ -11,6 +11,7 @@ export const ROUTE_MODULES: Record = { "/leads": "BO_LEADS", "/emails": "BO_EMAILS", "/login-security": "BO_LOGIN_SECURITY", + "/audit-log": "BO_AUDIT_LOG", }; export function requiredModuleFor(pathname: string): string | undefined { diff --git a/solvway-admin-portal/app/lib/services/auditLog.test.ts b/solvway-admin-portal/app/lib/services/auditLog.test.ts new file mode 100644 index 0000000..074a866 --- /dev/null +++ b/solvway-admin-portal/app/lib/services/auditLog.test.ts @@ -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"); + }); +}); diff --git a/solvway-admin-portal/app/lib/services/auditLog.ts b/solvway-admin-portal/app/lib/services/auditLog.ts new file mode 100644 index 0000000..68b6d71 --- /dev/null +++ b/solvway-admin-portal/app/lib/services/auditLog.ts @@ -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: {"": {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(`${BASE}/${encodeURIComponent(id)}`);