import type { Prisma, PrismaClient } from '@prisma/client'; import { logger } from '../lib/logger.js'; export interface ActivityLogInput { actorId: string; action: string; entityType: string; entityId?: string | null; details?: Record | null; } /** * Best-effort audit write — a failure must never break the main request. * Errors are reported to the app logger only. * `details` always includes the actor's ID (merged under `actorId`). */ export async function logActivity(prisma: PrismaClient, input: ActivityLogInput) { try { await prisma.activityLog.create({ data: { actorId: input.actorId, action: input.action, entityType: input.entityType, entityId: input.entityId ?? null, details: { actorId: input.actorId, ...(input.details ?? {}) } as Prisma.InputJsonValue, }, }); } catch (e) { logger.error( { err: e, action: input.action, actorId: input.actorId }, 'Failed to write activity log', ); } } export interface ActivityLogFilters { action?: string; userId?: string; /** Inclusive ISO date (YYYY-MM-DD). */ from?: string; /** Inclusive ISO date (YYYY-MM-DD). */ to?: string; limit: number; offset: number; } export interface ActivityLogActor { id: string; email: string; firstName: string | null; lastName: string | null; } export interface ActivityLogEntry { id: string; action: string; entityType: string; entityId: string | null; details: Record | null; createdAt: Date; actor: ActivityLogActor; } export async function listActivityLogs(prisma: PrismaClient, filters: ActivityLogFilters) { const where: Prisma.ActivityLogWhereInput = { ...(filters.action ? { action: filters.action } : {}), ...(filters.userId ? { actorId: filters.userId } : {}), // Granice dat w strefie serwera (jak reszta systemu), nie w UTC. createdAt: filters.from || filters.to ? { ...(filters.from ? { gte: new Date(`${filters.from}T00:00:00`) } : {}), ...(filters.to ? { lte: new Date(`${filters.to}T23:59:59.999`) } : {}), } : undefined, }; const [logs, total] = await Promise.all([ prisma.activityLog.findMany({ where, include: { actor: { select: { id: true, email: true, firstName: true, lastName: true } }, }, orderBy: { createdAt: 'desc' }, take: filters.limit, skip: filters.offset, }), prisma.activityLog.count({ where }), ]); return { logs, total }; }