import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ KwpProjectDomainError: class KwpProjectDomainError extends Error { readonly code: string; constructor(code: string) { super(code); this.code = code; } }, auditEvent: vi.fn(), logActivity: vi.fn(), publishOutboxEvent: vi.fn(), buildWorkflowTriggerOutboxEvent: vi.fn((input) => input), transaction: vi.fn(), runKwpResourceSession: vi.fn(), loadKwpBoundProject: vi.fn(), publishKwpContactSearch: vi.fn(), publishKwpProjectSearch: vi.fn(), bindingFindFirst: vi.fn(), bindingFindMany: vi.fn(), bindingUpdate: vi.fn(), bindingUpdateMany: vi.fn(), capabilityFindUnique: vi.fn(), routingFindUnique: vi.fn(), stageFindFirst: vi.fn(), stageChangeCreate: vi.fn(), runCreate: vi.fn(), runUpdateMany: vi.fn(), itemCreate: vi.fn(), projectUpdateMany: vi.fn(), getRlsExecutionContext: vi.fn(), resourceSearch: vi.fn(), resourceLoadProjectDetails: vi.fn(), events: [] as string[], })); vi.mock("@hivegrid/activity", () => ({ logActivity: mocks.logActivity })); vi.mock("@hivegrid/db/client.server", () => ({ getDbClient: () => ({ $transaction: mocks.transaction, appSyncRun: { updateMany: mocks.runUpdateMany }, }), })); vi.mock("@hivegrid/db/outbox", () => ({ publishOutboxEvent: mocks.publishOutboxEvent })); vi.mock("@hivegrid/db/rls-context.server", () => ({ getRlsExecutionContext: mocks.getRlsExecutionContext, })); vi.mock("@hivegrid/foundation", () => ({ auditEvent: mocks.auditEvent })); vi.mock("@hivegrid/queue", () => ({ buildWorkflowTriggerOutboxEvent: mocks.buildWorkflowTriggerOutboxEvent })); vi.mock("./project-domain.server.js", () => ({ KwpProjectDomainError: mocks.KwpProjectDomainError, loadKwpBoundProject: mocks.loadKwpBoundProject, publishKwpContactSearch: mocks.publishKwpContactSearch, publishKwpProjectSearch: mocks.publishKwpProjectSearch, syncKwpPrimaryContactChannels: vi.fn(), })); vi.mock("./resource-client.server.js", () => ({ runKwpResourceSession: mocks.runKwpResourceSession, })); import { syncKwpProjectBinding } from "./project-sync.server.js"; const now = new Date("2026-07-23T13:00:00.000Z"); const project = { id: "project-1", tenantId: "tenant-1", projektNummer: "P-00042", projektname: "Local", pipelineId: "pipeline-1", stageId: "stage-1", startDatum: null, auftragsvolumen: null, wonAt: null, lostAt: null, updatedAt: new Date("2026-07-23T12:00:00.000Z"), }; const binding = { id: "binding-1", tenantId: "tenant-1", dataConnectionId: "connection-1", externalId: "KWP-4711", localId: "project-1", revision: 7, fingerprint: "old", missingSince: null, }; const tx = { appEntityBinding: { findFirst: mocks.bindingFindFirst, findMany: mocks.bindingFindMany, update: mocks.bindingUpdate, updateMany: mocks.bindingUpdateMany, }, kwpCapabilityState: { findUnique: mocks.capabilityFindUnique }, kwpProjectRouting: { findUnique: mocks.routingFindUnique }, pipelineStage: { findFirst: mocks.stageFindFirst }, appSyncRun: { create: mocks.runCreate }, appSyncItem: { create: mocks.itemCreate }, projekt: { updateMany: mocks.projectUpdateMany }, projektStageChange: { create: mocks.stageChangeCreate }, }; beforeEach(() => { vi.clearAllMocks(); mocks.events.length = 0; mocks.getRlsExecutionContext.mockReturnValue({ tenantId: "tenant-1" }); mocks.transaction.mockImplementation(async (callback) => { mocks.events.push("tx:start"); const result = await callback(tx); mocks.events.push("tx:end"); return result; }); mocks.bindingFindFirst.mockResolvedValue(binding); mocks.bindingFindMany.mockResolvedValue([]); mocks.bindingUpdateMany.mockResolvedValue({ count: 1 }); mocks.bindingUpdate.mockResolvedValue({}); mocks.capabilityFindUnique.mockResolvedValue({ status: "active" }); mocks.routingFindUnique.mockResolvedValue({ pipelineId: "pipeline-2", stageId: "stage-2", }); mocks.stageFindFirst.mockResolvedValue({ id: "stage-2", name: "In Arbeit", stageKind: "neutral", }); mocks.stageChangeCreate.mockResolvedValue({ id: "change-1" }); mocks.loadKwpBoundProject.mockResolvedValue(project); mocks.runCreate.mockResolvedValue({ id: "run-1" }); mocks.runUpdateMany.mockResolvedValue({ count: 1 }); mocks.itemCreate.mockResolvedValue({ id: "item-1" }); mocks.auditEvent.mockResolvedValue(undefined); mocks.logActivity.mockResolvedValue(undefined); mocks.resourceSearch.mockResolvedValue([]); mocks.resourceLoadProjectDetails.mockResolvedValue({ externalProjectNumber: "KWP-4711", name: "KWP Project", startDate: "2026-07-01T00:00:00.000Z", orderValue: 42_500, }); mocks.runKwpResourceSession.mockImplementation(async (_input, callback) => { mocks.events.push("provider"); return callback({ searchProjects: mocks.resourceSearch, loadProjectDetails: mocks.resourceLoadProjectDetails, loadAddressDetails: vi.fn(), }); }); }); describe("KWP three-phase project sync", () => { it("does provider I/O between short transactions and marks a missing project without deleting local data", async () => { const result = await syncKwpProjectBinding({ bindingId: "binding-1", now }); expect(result).toEqual({ runId: "run-1", state: "missing", projectId: "project-1", stageChanged: false, }); expect(mocks.events).toEqual([ "tx:start", "tx:end", "provider", "tx:start", "tx:end", ]); expect(mocks.bindingUpdateMany).toHaveBeenCalledWith({ where: { id: "binding-1", tenantId: "tenant-1", revision: 7, state: { in: ["active", "missing"] }, }, data: { state: "missing", revision: { increment: 1 }, missingSince: now, }, }); expect(mocks.projectUpdateMany).not.toHaveBeenCalled(); expect(mocks.itemCreate).toHaveBeenCalledWith({ data: expect.objectContaining({ operation: "skipped", status: "skipped" }), }); expect(mocks.runUpdateMany).toHaveBeenLastCalledWith(expect.objectContaining({ data: expect.objectContaining({ status: "completed", itemsSucceeded: 1 }), })); }); it("records a failed run but performs no local partial mutation on network failure", async () => { mocks.runKwpResourceSession.mockImplementationOnce(async () => { mocks.events.push("provider"); throw new Error("provider unavailable"); }); await expect(syncKwpProjectBinding({ bindingId: "binding-1", now })) .rejects.toThrow("provider unavailable"); expect(mocks.bindingUpdateMany).not.toHaveBeenCalled(); expect(mocks.projectUpdateMany).not.toHaveBeenCalled(); expect(mocks.itemCreate).not.toHaveBeenCalled(); expect(mocks.runUpdateMany).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ status: "failed", itemsFailed: 1 }), })); }); it("atomically reconciles a later stage change and emits the existing event with source=kwp", async () => { mocks.resourceSearch.mockResolvedValueOnce([{ externalProjectNumber: "KWP-4711", name: "KWP Project", projectAddressCode: null, invoiceAddressCode: null, clientAddressCode: null, status: 8, statusLabel: "Erhalten", }]); mocks.projectUpdateMany.mockResolvedValue({ count: 1 }); mocks.loadKwpBoundProject .mockResolvedValueOnce(project) .mockResolvedValueOnce(project) .mockResolvedValueOnce({ ...project, projektname: "KWP Project", pipelineId: "pipeline-2", stageId: "stage-2", startDatum: new Date("2026-07-01T00:00:00.000Z"), auftragsvolumen: 42_500, updatedAt: new Date("2026-07-23T13:00:00.000Z"), }); await expect(syncKwpProjectBinding({ bindingId: "binding-1", now })).resolves.toEqual({ runId: "run-1", state: "synced", projectId: "project-1", stageChanged: true, }); expect(mocks.events).toEqual(["tx:start", "tx:end", "provider", "tx:start", "tx:end"]); expect(mocks.projectUpdateMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ id: "project-1", tenantId: "tenant-1", updatedAt: project.updatedAt, }), data: expect.objectContaining({ projektname: "KWP Project", pipelineId: "pipeline-2", stageId: "stage-2", }), })); expect(mocks.buildWorkflowTriggerOutboxEvent).toHaveBeenCalledWith(expect.objectContaining({ event: "project.stage_changed", data: expect.objectContaining({ projectId: "project-1", fromStageId: "stage-1", toStageId: "stage-2", source: "kwp", }), })); expect(mocks.publishOutboxEvent).toHaveBeenCalledOnce(); expect(mocks.publishKwpProjectSearch).toHaveBeenCalledOnce(); }); it("quarantines an unknown status without mutating the project", async () => { mocks.resourceSearch.mockResolvedValueOnce([{ externalProjectNumber: "KWP-4711", name: "KWP Project", projectAddressCode: null, invoiceAddressCode: null, clientAddressCode: null, status: 99, statusLabel: "Unbekannt", }]); mocks.routingFindUnique.mockResolvedValueOnce(null); await expect(syncKwpProjectBinding({ bindingId: "binding-1", now })).resolves.toEqual({ runId: "run-1", state: "quarantined", projectId: "project-1", stageChanged: false, }); expect(mocks.projectUpdateMany).not.toHaveBeenCalled(); expect(mocks.publishOutboxEvent).not.toHaveBeenCalled(); expect(mocks.bindingUpdateMany).not.toHaveBeenCalled(); }); });