import { createAdminAuditLog, listAdminAuditLogs } from '../../repositories/admin-audit-log-repo.js' import { nowIso } from '../../utils/time.js' export function writeAdminAuditLog(session, payload = {}) { if (!session?.userId) { return null } return createAdminAuditLog({ actorUserId: session.userId, actorUsername: session.username, actorRole: session.role, action: String(payload.action || '').trim(), targetType: String(payload.targetType || '').trim() || 'unknown', targetId: String(payload.targetId || '').trim(), payloadJson: JSON.stringify(payload.data || {}), createdAt: nowIso(), }) } export function getAdminAuditLogs(query = {}) { const page = normalizePage(query.page) const pageSize = normalizePageSize(query.pageSize) const { items, total } = listAdminAuditLogs({ page, pageSize, actorUsername: String(query.actorUsername || '').trim(), action: String(query.action || '').trim(), targetType: String(query.targetType || '').trim(), dateFrom: normalizeDateQuery(query.dateFrom), dateTo: normalizeDateQuery(query.dateTo, true), }) return { items: items.map((item) => ({ logId: item.id, actorUserId: item.actor_user_id, actorUsername: item.actor_username, actorRole: item.actor_role, action: item.action, targetType: item.target_type, targetId: item.target_id, payload: safeParseJson(item.payload_json), createdAt: item.created_at, })), pagination: { page, pageSize, total }, } } function normalizePage(rawValue) { const parsed = Number(rawValue) return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1 } function normalizePageSize(rawValue) { const parsed = Number(rawValue) if (!Number.isFinite(parsed) || parsed <= 0) { return 20 } return Math.min(100, Math.floor(parsed)) } function normalizeDateQuery(rawValue, endOfDay = false) { const normalized = String(rawValue || '').trim() if (!normalized) { return '' } if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) { return endOfDay ? `${normalized}T23:59:59.999Z` : `${normalized}T00:00:00.000Z` } return normalized } function safeParseJson(value) { try { return JSON.parse(String(value || '{}')) } catch { return {} } }