import { beforeEach, describe, expect, it, vi } from "vitest"; import { syncInternalCalendarEventsForTenant, type CalendarWorkerClient } from "./calendar-worker-tasks.server.js"; const mocks = vi.hoisted(() => { class MockGoogleCalendarError extends Error { readonly code: string; readonly httpStatus?: number; readonly fullResyncRequired: boolean; constructor(code: string, httpStatus?: number) { super(code); this.name = "GoogleCalendarError"; this.code = code; this.httpStatus = httpStatus; this.fullResyncRequired = httpStatus === 410; } } return { MockGoogleCalendarError, createNotificationDelivery: vi.fn(async () => ({})), insertEvent: vi.fn(), patchEvent: vi.fn(), }; }); vi.mock("./google/googleCalendarApi.js", () => ({ deleteEvent: vi.fn(async () => undefined), GoogleCalendarError: mocks.MockGoogleCalendarError, insertEvent: mocks.insertEvent, listEvents: vi.fn(), patchEvent: mocks.patchEvent, refreshAccessToken: vi.fn(), resolveGoogleOAuthConfig: vi.fn(() => ({ clientId: "id", clientSecret: "secret", redirectUri: "https://app.example.test/callback" })), watchCalendar: vi.fn(), })); vi.mock("@hivegrid/db/crypto/tenant-envelope.server", () => ({ decryptTenantField: vi.fn(async (_tenantId: string, ciphertext: string) => (ciphertext.includes("refresh") ? "refresh-token" : "access-token")), encryptTenantField: vi.fn(async (_tenantId: string, value: string) => `sealed:${value}`), })); vi.mock("@hivegrid/db/notifications.server", () => ({ createNotificationDelivery: mocks.createNotificationDelivery, })); function createClient(options: { mapping?: Record | null; patchConflict?: boolean; eventCount?: number } = {}) { const now = new Date("2026-06-30T10:00:00.000Z"); const connection = { id: "conn_1", tenantId: "tenant_1", userId: "user_1", oauthRefreshTokenCiphertext: "sealed-refresh", oauthAccessTokenCiphertext: "sealed-access", oauthAccessTokenExpiresAt: new Date("2026-06-30T11:00:00.000Z"), webhookSubscriptionId: null, webhookSubscriptionExpiresAt: null, syncDirection: "bidirectional" as const, status: "active" as const, }; const event = { id: "event_1", updatedAt: now, tenantId: "tenant_1", userId: "user_1", title: "Kundentermin", description: null, location: null, startsAt: new Date("2026-07-01T08:00:00.000Z"), endsAt: new Date("2026-07-01T09:00:00.000Z"), isAllDay: false, timeZone: "Europe/Berlin", attendees: [], versionToken: 1, archivedAt: null, }; const events = Array.from({ length: options.eventCount ?? 1 }, (_, index) => ({ ...event, id: `event_${index + 1}`, })); const mapping = options.mapping ?? null; const client = { calendarConnection: { findMany: vi.fn(async () => [connection]), findFirst: vi.fn(async () => connection), updateMany: vi.fn(async () => ({ count: 1 })), update: vi.fn(async () => ({})), }, calendarEvent: { findMany: vi.fn(async () => events), upsert: vi.fn(async () => ({})), }, calendarEventMapping: { findMany: vi.fn(async () => (mapping ? [mapping] : [])), create: vi.fn(async ({ data }) => ({ id: "mapping_1", ...data })), update: vi.fn(async ({ data }) => ({ id: "mapping_1", ...data })), deleteMany: vi.fn(async () => ({ count: 1 })), }, calendarSyncCursor: { findFirst: vi.fn(async () => null), upsert: vi.fn(async () => ({})), updateMany: vi.fn(async () => ({ count: 1 })), }, calendarWebhookEvent: { findMany: vi.fn(async () => []), updateMany: vi.fn(async () => ({ count: 1 })), update: vi.fn(async () => ({})), }, calendarConflict: { create: vi.fn(async () => ({})), }, }; if (options.patchConflict) { mocks.patchEvent.mockRejectedValueOnce(new mocks.MockGoogleCalendarError("rate_limit_exceeded", 412)); } return client as unknown as CalendarWorkerClient & typeof client; } describe("calendar worker write sync", () => { beforeEach(() => { vi.clearAllMocks(); mocks.insertEvent.mockResolvedValue({ id: "google_event_1", etag: "etag_1" }); mocks.patchEvent.mockResolvedValue({ id: "google_event_1", etag: "etag_2" }); }); it("creates an external event and mapping for a new HiveGrid event", async () => { const client = createClient(); const result = await syncInternalCalendarEventsForTenant(client, "tenant_1", { now: new Date("2026-06-30T10:00:00.000Z") }); expect(result).toMatchObject({ scanned: 1, created: 1, updated: 0, conflicts: 0, failed: 0 }); expect(client.calendarConnection.findFirst).not.toHaveBeenCalled(); expect(client.calendarEventMapping.findMany).toHaveBeenCalledOnce(); expect(mocks.insertEvent).toHaveBeenCalledWith("access-token", "primary", expect.objectContaining({ summary: "Kundentermin" })); expect(client.calendarEventMapping.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ internalEventId: "event_1", externalEventId: "google_event_1", lastKnownExternalEtag: "etag_1", lastKnownInternalVersionToken: 1, }), }), ); }); it("loads mappings for a full event batch with one database query", async () => { const client = createClient({ eventCount: 50 }); const result = await syncInternalCalendarEventsForTenant(client, "tenant_1", { now: new Date("2026-06-30T10:00:00.000Z"), take: 50 }); expect(result).toMatchObject({ scanned: 50, created: 50, updated: 0, failed: 0 }); expect(client.calendarConnection.findFirst).not.toHaveBeenCalled(); expect(client.calendarEventMapping.findMany).toHaveBeenCalledOnce(); expect(mocks.insertEvent).toHaveBeenCalledTimes(50); }); it("logs and notifies a Last-Write-Wins conflict on provider etag mismatch", async () => { const client = createClient({ mapping: { id: "mapping_1", internalEventId: "event_1", externalEventId: "google_event_1", externalCalendarId: "primary", connectionId: "conn_1", lastSyncedAt: new Date("2026-06-30T09:00:00.000Z"), lastKnownExternalEtag: "old-etag", lastKnownInternalVersionToken: 0, }, patchConflict: true, }); const result = await syncInternalCalendarEventsForTenant(client, "tenant_1", { now: new Date("2026-06-30T10:00:00.000Z") }); expect(result).toMatchObject({ scanned: 1, created: 0, updated: 0, conflicts: 1, failed: 0 }); expect(client.calendarConflict.create).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ connectionId: "conn_1", internalEventId: "event_1", externalEventId: "google_event_1", resolution: "external_won", descriptionText: "calendar.conflict.externalWon", }), }), ); expect(mocks.createNotificationDelivery).toHaveBeenCalledWith(expect.objectContaining({ userId: "user_1", messageKey: "calendar.conflict.externalWon" })); }); });