import { beforeEach, describe, expect, it, vi } from "vitest"; const publishOutboxEventMock = vi.fn(async () => ({ id: "outbox_1" })); vi.mock("@toolctrl/db/outbox", () => ({ publishOutboxEvent: (...args: unknown[]) => publishOutboxEventMock(...args), })); vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({ default: { sendToRoles: vi.fn(), }, })); vi.mock("~/utils/db.server", () => ({ db: { $transaction: vi.fn(), }, })); vi.mock("~/utils/url.server", () => ({ getAbsoluteApiUrl: vi.fn(() => "https://app.example.test/api"), getBaseURL: vi.fn(() => "https://app.example.test"), })); vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ adminPath: vi.fn((path: string) => `/admin/${path}`), appPath: vi.fn((path: string) => `/app/${path}`), })); vi.mock("../../db/eventWebhookAttempts.db.server", () => ({ createEventWebhookAttempt: vi.fn(), updateEventWebhookAttempt: vi.fn(), })); import EventsService from "./EventsService"; describe("EventsService workflow outbox producer", () => { beforeEach(() => { publishOutboxEventMock.mockClear(); }); it("records the application event before publishing the workflow outbox event in the same transaction", async () => { const createdEvent = { id: "evt_1", name: "row.created", tenantId: "tenant_1", userId: "user_1", data: JSON.stringify({ id: "row_1", title: "Acme deal", row: { id: "row_1" }, entity: { id: "entity_1", name: "Deal", slug: "deals", title: "Deals" }, visibility: "tenant", user: { id: "user_1", email: "owner@example.test" }, }), description: "New Deal: Acme deal, by owner@example.test", createdAt: new Date("2026-05-27T10:00:00.000Z"), }; const tx = { event: { create: vi.fn(async () => createdEvent), }, }; const payload = { id: "row_1", title: "Acme deal", row: { id: "row_1" }, entity: { id: "entity_1", name: "Deal", slug: "deals", title: "Deals" }, visibility: "tenant", user: { id: "user_1", email: "owner@example.test" }, }; const result = await EventsService.createInTransaction(tx as never, { event: "row.created", tenantId: "tenant_1", userId: "user_1", data: payload, }); expect(result.item).toBe(createdEvent); expect(tx.event.create).toHaveBeenCalledWith({ data: { name: "row.created", tenantId: "tenant_1", userId: "user_1", data: JSON.stringify(payload), description: "New Deal: Acme deal, by owner@example.test", }, }); expect(publishOutboxEventMock).toHaveBeenCalledWith(tx, { tenantId: "tenant_1", type: "workflow.trigger.event", payload: { event: "row.created", data: payload, userId: "user_1", }, dispatchKey: "workflow-trigger:evt_1", }); expect(tx.event.create.mock.invocationCallOrder[0]).toBeLessThan(publishOutboxEventMock.mock.invocationCallOrder[0]); }); });