import { getDbClient } from "@hivegrid/db/client.server"; import type { Prisma } from "@hivegrid/db/prisma-browser"; import type { LogActivityInput } from "./types.js"; /** * Minimal write surface `logActivity` needs. Satisfied by the full Prisma client * AND by interactive-transaction clients, so callers can append an activity inside * the same transaction as the action that triggered it. */ export type ActivityWriteClient = { activity: { create: (args: { data: Prisma.ActivityUncheckedCreateInput }) => Promise<{ id: string }>; }; }; export type LogActivityOptions = { /** Transaction/client to write through. Defaults to the shared db singleton. */ client?: ActivityWriteClient; }; /** * Append a user-facing activity to the central `Activity` stream (M045 / DoD #14). * * This is NOT the audit log — the tamper-evident `AuditEvent` (M001) is written * separately (auto via Prisma middleware). `logActivity` records the human-readable, * per-entity timeline shown to tenant users. */ export async function logActivity(input: LogActivityInput, options: LogActivityOptions = {}): Promise<{ id: string }> { if (!input.tenantId) { throw new Error("logActivity: tenantId is required"); } if (!input.subjectId) { throw new Error("logActivity: subjectId is required"); } if (!input.summaryText || input.summaryText.trim().length === 0) { throw new Error("logActivity: summaryText (Klartext-Zusammenfassung) is required"); } const client = options.client ?? (getDbClient() as unknown as ActivityWriteClient); return client.activity.create({ data: { tenantId: input.tenantId, actorUserId: input.actorUserId ?? null, actorKind: input.actorKind, activityType: input.activityType, subjectType: input.subjectType, subjectId: input.subjectId, summaryText: input.summaryText, relatedEntityRefs: input.relatedEntityRefs ? (input.relatedEntityRefs as unknown as Prisma.InputJsonValue) : undefined, metadata: input.metadata ? (input.metadata as Prisma.InputJsonValue) : undefined, }, }); }