const prisma = require('../config/db'); // Fire-and-forget by design — a logging failure must never break the underlying admin // action, so this swallows its own errors rather than propagating them to the caller // (same posture as logSecurityEvent). async function logAdminAction({ actorId, actorRole, action, targetType, targetId, metadata, ip }) { try { await prisma.adminAuditLog.create({ data: { actorId: actorId || null, actorRole, action, targetType, targetId: targetId || null, metadata: metadata || undefined, ip: ip || null, }, }); } catch (e) { console.error('Failed to log admin action:', e?.message); } } const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/; const DAY_MS = 24 * 60 * 60 * 1000; // A date (YYYY-MM-DD) means midnight in the server's time zone (APP_TIMEZONE), not UTC. const startOf = (v) => new Date(DATE_ONLY.test(v) ? `${v}T00:00:00` : v); // The Prisma filter for the audit-log page. Dates (YYYY-MM-DD) are whole days, so `to` // includes that day. `search` matches the person (name or email), the target type or id, // or the IP. function auditLogWhere({ actorId, action, role, from, to, search } = {}) { const where = {}; if (actorId) where.actorId = actorId; if (action) where.action = action; if (role) where.actorRole = role; if (from || to) { where.createdAt = {}; if (from) where.createdAt.gte = startOf(from); if (to) { if (DATE_ONLY.test(to)) where.createdAt.lt = new Date(startOf(to).getTime() + DAY_MS); else where.createdAt.lte = new Date(to); } } const q = String(search || '').trim().slice(0, 100); if (q) { const contains = { contains: q, mode: 'insensitive' }; where.OR = [ { actor: { name: contains } }, { actor: { email: contains } }, { targetType: contains }, { targetId: { startsWith: q.replace(/^#/, '') } }, { ip: { startsWith: q } }, ]; } return where; } // Paginated listing for the admin audit-log page. async function getAdminAuditLog({ page = 1, limit = 50, ...filters } = {}) { const where = auditLogWhere(filters); const take = Math.min(Math.max(Number(limit) || 50, 1), 200); const skip = (Math.max(Number(page) || 1, 1) - 1) * take; const [rows, total] = await Promise.all([ prisma.adminAuditLog.findMany({ where, orderBy: { createdAt: 'desc' }, take, skip, include: { actor: { select: { id: true, name: true, email: true } } }, }), prisma.adminAuditLog.count({ where }), ]); return { rows, total, page: Math.max(Number(page) || 1, 1), limit: take }; } module.exports = { logAdminAction, getAdminAuditLog, auditLogWhere };