import { describe, expect, it, vi } from "vitest"; import type { Prisma } from "@hivegrid/db/prisma-browser"; import { logActivity, type ActivityWriteClient } from "./logActivity.server.js"; import type { LogActivityInput } from "./types.js"; function makeMockClient() { const create = vi.fn<(args: { data: Prisma.ActivityUncheckedCreateInput }) => Promise<{ id: string }>>(() => Promise.resolve({ id: "act_1" }) ); const client: ActivityWriteClient = { activity: { create } }; return { client, create }; } const base: LogActivityInput = { tenantId: "t1", actorUserId: "u1", actorKind: "user", activityType: "note_added", subjectType: "contact", subjectId: "c1", summaryText: "Notiz hinzugefügt", }; describe("logActivity", () => { it("writes a tenant-scoped activity row with mapped fields through the given client", async () => { const { client, create } = makeMockClient(); const result = await logActivity(base, { client }); expect(result).toEqual({ id: "act_1" }); expect(create).toHaveBeenCalledTimes(1); expect(create.mock.calls[0]?.[0].data).toMatchObject({ tenantId: "t1", actorUserId: "u1", actorKind: "user", activityType: "note_added", subjectType: "contact", subjectId: "c1", summaryText: "Notiz hinzugefügt", }); }); it("passes relatedEntityRefs and metadata through as JSON", async () => { const { client, create } = makeMockClient(); await logActivity( { ...base, relatedEntityRefs: [{ type: "company", id: "co1" }], metadata: { from: "neu", to: "kontaktiert" } }, { client } ); const data = create.mock.calls[0]?.[0].data; expect(data?.relatedEntityRefs).toEqual([{ type: "company", id: "co1" }]); expect(data?.metadata).toEqual({ from: "neu", to: "kontaktiert" }); }); it("defaults a missing actorUserId to null (system/automation actors)", async () => { const { client, create } = makeMockClient(); await logActivity({ ...base, actorUserId: undefined, actorKind: "system" }, { client }); expect(create.mock.calls[0]?.[0].data.actorUserId).toBeNull(); }); it("accepts the canonical missed-call activity type", async () => { const { client, create } = makeMockClient(); await logActivity({ ...base, activityType: "call_missed" }, { client }); expect(create.mock.calls[0]?.[0].data.activityType).toBe("call_missed"); }); it("requires tenantId, subjectId and a non-empty summaryText", async () => { const { client } = makeMockClient(); await expect(logActivity({ ...base, tenantId: "" }, { client })).rejects.toThrow("tenantId"); await expect(logActivity({ ...base, subjectId: "" }, { client })).rejects.toThrow("subjectId"); await expect(logActivity({ ...base, summaryText: " " }, { client })).rejects.toThrow("summaryText"); }); });