import { getDbClient } from "./client.server.js"; import type { AuditEvent, Prisma } from "../generated/prisma/client/client.js"; /** * AK-P3 — read-path for the Audit-Viewer (`/admin/audit`). * * The write-path (`createAuditEvent`) and the export-path * (`audit-export.helpers.server`) already exist; this module adds the missing * paginated list query the viewer needs. It is a thin wrapper over Prisma so * the route stays free of direct `findMany` calls and the filters are applied * against the existing `(tenantId|action|outcome, createdAt)` indexes. */ export type AuditEventListParams = { where?: Prisma.AuditEventWhereInput; take?: number; skip?: number; }; export type AuditEventListResult = { rows: AuditEvent[]; total: number; take: number; skip: number; }; export const AUDIT_VIEWER_DEFAULT_PAGE_SIZE = 25; export const AUDIT_VIEWER_MAX_PAGE_SIZE = 100; function clampPageSize(take: number | undefined): number { if (!Number.isFinite(take) || !take || take < 1) return AUDIT_VIEWER_DEFAULT_PAGE_SIZE; return Math.min(Math.trunc(take), AUDIT_VIEWER_MAX_PAGE_SIZE); } /** * Lists audit events newest-first with server-side filters + pagination. * Returns the page rows plus the total count for the same filter so the route * can build pagination metadata. */ export async function listAuditEvents(params: AuditEventListParams = {}): Promise { const db = getDbClient(); const where = params.where ?? {}; const take = clampPageSize(params.take); const skip = Number.isFinite(params.skip) && params.skip && params.skip > 0 ? Math.trunc(params.skip) : 0; const [rows, total] = await Promise.all([ db.auditEvent.findMany({ where, orderBy: { createdAt: "desc" }, take, skip }), db.auditEvent.count({ where }), ]); return { rows, total, take, skip }; }