From 5242e419d966533683ff7b40cbe976d572b90240 Mon Sep 17 00:00:00 2001 From: Volnei Munhoz Date: Thu, 26 Feb 2026 13:12:52 -0300 Subject: [PATCH] feat: Calendar Sync (#24124) * feat: calendar cache and sync - wip * Add env.example * refactor on CalendarCacheEventService * remove test console.log * Fix type checks errors * chore: remove pt comment * add route.ts * chore: fix tests * Improve cache impl * chore: update recurring event id * chore: small improvements * calendar cache improvements * Fix remove dynamic imports * Add cleanup stale cache * Fix tests * add event update * type fixes * feat: add comprehensive tests for new calendar subscription API routes - Add tests for /api/cron/calendar-subscriptions-cleanup route (9 tests) - Add tests for /api/cron/calendar-subscriptions route (10 tests) - Add tests for /api/webhooks/calendar-subscription/[provider] route (11 tests) - Add missing feature flags for calendar-subscription-cache and calendar-subscription-sync - All 30 tests pass with comprehensive coverage of authentication, feature flags, error handling, and service instantiation Tests cover: - Authentication scenarios (API key validation, Bearer tokens, query parameters) - Feature flag combinations (cache/sync enabled/disabled states) - Success and error handling (including non-Error exceptions) - Service instantiation with proper dependency injection - Provider validation for webhook endpoints Co-Authored-By: Volnei Munhoz * feat: add comprehensive tests for calendar subscription services, repositories, and adapters - Add unit tests for CalendarSubscriptionService with subscription, webhook, and event processing - Add unit tests for CalendarCacheEventService with cache operations and cleanup - Add unit tests for CalendarSyncService with Cal.com event filtering and booking operations - Add unit tests for CalendarCacheEventRepository with CRUD operations - Add unit tests for SelectedCalendarRepository with calendar selection management - Add unit tests for GoogleCalendarSubscriptionAdapter with subscription and event fetching - Add unit tests for Office365CalendarSubscriptionAdapter with placeholder implementation - Add unit tests for AdaptersFactory with provider management and adapter creation - Fix lint issues by removing explicit 'any' type casting and unused variables - All tests follow Cal.com conventions using Vitest framework with proper mocking Co-Authored-By: Volnei Munhoz * fix: improve calendar-subscriptions-cleanup test performance by adding missing mocks - Add comprehensive mocks for defaultResponderForAppDir, logger, performance monitoring, and Sentry - Fix slow test execution (933ms -> <100ms) caused by missing dependency mocks - Ensure consistent test performance across different environments Co-Authored-By: Volnei Munhoz * Fix tests * Fix tests * type fix * Fix coderabbit comments * Fix types * Fix test * Update apps/web/app/api/cron/calendar-subscriptions/route.ts Co-authored-by: Alex van Andel * Fixes by first review * feat: add database migrations for calendar cache and sync fields - Add CalendarCacheEventStatus enum with confirmed, tentative, cancelled values - Add new fields to SelectedCalendar: channelId, channelKind, channelResourceId, channelResourceUri, channelExpiration, syncSubscribedAt, syncToken, syncedAt, syncErrorAt, syncErrorCount - Create CalendarCacheEvent table with foreign key to SelectedCalendar - Add necessary indexes and constraints for performance and data integrity Fixes database schema issues causing e2e test failures with 'column does not exist' errors. Co-Authored-By: Volnei Munhoz * only google-calendar for now * docs: add Calendar Cache and Sync feature documentation - Add comprehensive feature overview and motivation - Document feature flags with SQL examples - Include SQL examples for enabling features for users and teams - Reference technical documentation files Addresses PR #23876 documentation requirements Co-Authored-By: Volnei Munhoz * docs: update calendar subscription README with comprehensive documentation - Undo incorrect changes to main README.md - Update packages/features/calendar-subscription/README.md with: - Feature overview and motivation - Environment variables section - Complete feature flags documentation with SQL examples - SQL examples for enabling features for users and teams - Detailed architecture documentation Addresses PR #23876 documentation requirements Co-Authored-By: Volnei Munhoz * fix docs * Fix test to available calendars * Fix test to available calendars * add migration and sync boilerplate * fix typo * remove double log * sync boilerplate * remove console.log * only subscribe for google calendar * adjust for 3 months fetch * only subscribe for teams that have feature enabled * adjust tests * chore: safe increment error count Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * calendar sync * test: add comprehensive tests for CalendarSyncService - Add comprehensive test coverage for CalendarSyncService methods - Test handleEvents, cancelBooking, and rescheduleBooking functionality - Cover edge cases like missing UIDs, malformed UIDs, and error handling - Fix dynamic import usage in CalendarSyncService to use .default - Remove invalid properties from handleNewBooking call to fix type errors Co-Authored-By: Volnei Munhoz * fix: add skipCalendarSyncTaskCreation flag to handleCancelBooking to prevent infinite loops - Add skipCalendarSyncTaskCreation field to bookingCancelSchema in zod-utils.ts - Update handleCancelBooking to skip EventManager.cancelEvent when flag is true - Update CalendarSyncService.cancelBooking to pass skipCalendarSyncTaskCreation: true - Update CalendarSyncService.rescheduleBooking to pass skipCalendarSyncTaskCreation: true - Update tests to verify the flags are passed correctly This prevents infinite loops when calendar events are cancelled/rescheduled from external calendars (Google/Office365) which trigger webhooks to Cal.com, which would otherwise try to update the external calendar again. Co-Authored-By: Volnei Munhoz * refactor: rename flag to skipCalendarSyncTaskCancellation and use static imports - Rename skipCalendarSyncTaskCreation to skipCalendarSyncTaskCancellation in handleCancelBooking - Convert dynamic imports to static imports in CalendarSyncService - Update tests to use vi.hoisted for proper mock hoisting with static imports Co-Authored-By: Volnei Munhoz * feat: add error handling and static import for handleNewBooking - Create index.ts entry point for handleNewBooking directory - Add try-catch error handling to cancelBooking and rescheduleBooking - Log errors but don't block calendar sync operations - Update tests to verify errors are caught and logged, not thrown Co-Authored-By: Volnei Munhoz * refactor: use RegularBookingService directly and fix safeStringify usage - Remove handleNewBooking/index.ts and call getRegularBookingService().createBooking() directly in CalendarSyncService - Fix safeStringify usage: apply to error itself, not wrapper object - Update tests to mock getRegularBookingService instead of handleNewBooking Addresses PR comments from Volnei and Cubic-dev-ai Co-Authored-By: Volnei Munhoz * fix: restore handleNewBooking/index.ts and fix bookingData structure for calendar sync - Restore handleNewBooking/index.ts as entry point for static imports - Fix CalendarSyncService.rescheduleBooking to use correct bookingData structure with required fields (eventTypeId, start, end, timeZone, language, metadata) - Use rescheduleUid to indicate this is a reschedule operation - Fix safeStringify usage in error logging (wrap only the error, not the whole object) - Update tests to match new bookingData structure Co-Authored-By: Volnei Munhoz * refactor: address PR comments - use RegularBookingService directly, remove unnecessary flags, fix booking reference update - Remove handleNewBooking/index.ts wrapper and use getRegularBookingService().createBooking() directly in CalendarSyncService - Remove allRemainingBookings and cancelSubsequentBookings flags from cancelBooking (only cancel the specific booking, not the entire series) - Move bookingReference update outside skipCalendarSyncTaskCancellation block for data consistency - Update tests to match new implementation Co-Authored-By: Volnei Munhoz * chore: remove unnecessary comment from zod-utils.ts Co-Authored-By: Volnei Munhoz * feat: add Sentry metrics telemetry and fix null assertions in CalendarSyncService Co-Authored-By: Volnei Munhoz * fix: use dynamic import for getRegularBookingService to avoid RAQB import in server context Co-Authored-By: Volnei Munhoz * fix: use dynamic import for findTeamMembersMatchingAttributeLogic to avoid RAQB import in server context Co-Authored-By: Volnei Munhoz * improve booking update * add more tests and edge cases * fix: add required actionSource and Sentry mocks to calendar sync Add actionSource: "SYSTEM" to handleCancelBooking call after it became required, and mock @sentry/nextjs in test files. --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Alex van Andel Co-authored-by: Keith Williams Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- .../bookings/lib/handleCancelBooking.ts | 61 +- .../lib/sync/CalendarSyncService.ts | 298 ++++- .../CalendarSyncService.integration.test.ts | 1048 +++++++++++++++++ .../__tests__/CalendarSyncService.test.ts | 511 ++++++++ packages/features/users/lib/getRoutedUsers.ts | 6 +- packages/prisma/zod-utils.ts | 1 + 6 files changed, 1880 insertions(+), 45 deletions(-) create mode 100644 packages/features/calendar-subscription/lib/sync/__tests__/CalendarSyncService.integration.test.ts create mode 100644 packages/features/calendar-subscription/lib/sync/__tests__/CalendarSyncService.test.ts diff --git a/packages/features/bookings/lib/handleCancelBooking.ts b/packages/features/bookings/lib/handleCancelBooking.ts index 9273cabf41..d186daf858 100644 --- a/packages/features/bookings/lib/handleCancelBooking.ts +++ b/packages/features/bookings/lib/handleCancelBooking.ts @@ -166,6 +166,7 @@ async function handler(input: CancelBookingInput, dependencies?: Dependencies) { cancelSubsequentBookings, internalNote, skipCancellationReasonValidation = false, + skipCalendarSyncTaskCancellation = false, } = bookingCancelInput.parse(body); const bookingToDelete = await getBookingToDelete(id, uid); const { @@ -630,36 +631,46 @@ async function handler(input: CancelBookingInput, dependencies?: Dependencies) { allRemainingBookings ); - try { - const bookingToDeleteEventTypeMetadataParsed = eventTypeMetaDataSchemaWithTypedApps.safeParse( - bookingToDelete.eventType?.metadata || null - ); - - if (!bookingToDeleteEventTypeMetadataParsed.success) { - log.error( - `Error parsing metadata`, - safeStringify({ error: bookingToDeleteEventTypeMetadataParsed?.error }) + // Skip calendar event deletion when cancellation comes from a calendar subscription webhook + // to avoid infinite loops (Google/Office365 → Cal.com → Google/Office365 → ...) + if (!skipCalendarSyncTaskCancellation) { + try { + const bookingToDeleteEventTypeMetadataParsed = eventTypeMetaDataSchemaWithTypedApps.safeParse( + bookingToDelete.eventType?.metadata || null ); - throw new Error("Error parsing metadata"); + + if (!bookingToDeleteEventTypeMetadataParsed.success) { + log.error( + `Error parsing metadata`, + safeStringify({ error: bookingToDeleteEventTypeMetadataParsed?.error }) + ); + throw new Error("Error parsing metadata"); + } + + const bookingToDeleteEventTypeMetadata = bookingToDeleteEventTypeMetadataParsed.data; + + const credentials = await getAllCredentialsIncludeServiceAccountKey(bookingToDelete.user, { + ...bookingToDelete.eventType, + metadata: bookingToDeleteEventTypeMetadata, + }); + + const eventManager = new EventManager( + { ...bookingToDelete.user, credentials }, + bookingToDeleteEventTypeMetadata?.apps + ); + + await eventManager.cancelEvent(evt, bookingToDelete.references, isBookingInRecurringSeries); + } catch (error) { + log.error(`Error deleting integrations`, safeStringify({ error })); } + } - const bookingToDeleteEventTypeMetadata = bookingToDeleteEventTypeMetadataParsed.data; - - const credentials = await getAllCredentialsIncludeServiceAccountKey(bookingToDelete.user, { - ...bookingToDelete.eventType, - metadata: bookingToDeleteEventTypeMetadata, - }); - - const eventManager = new EventManager( - { ...bookingToDelete.user, credentials }, - bookingToDeleteEventTypeMetadata?.apps - ); - - await eventManager.cancelEvent(evt, bookingToDelete.references, isBookingInRecurringSeries); - + // Always mark booking references as deleted for data consistency + // (even when skipCalendarSyncTaskCancellation is true, since the external event is already deleted) + try { await bookingReferenceRepository.updateManyByBookingId(bookingToDelete.id, { deleted: true }); } catch (error) { - log.error(`Error deleting integrations`, safeStringify({ error })); + log.error(`Error marking booking references as deleted`, safeStringify({ error })); } try { diff --git a/packages/features/calendar-subscription/lib/sync/CalendarSyncService.ts b/packages/features/calendar-subscription/lib/sync/CalendarSyncService.ts index 2a2aff77f3..73139a53d7 100644 --- a/packages/features/calendar-subscription/lib/sync/CalendarSyncService.ts +++ b/packages/features/calendar-subscription/lib/sync/CalendarSyncService.ts @@ -1,7 +1,12 @@ -import { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository"; +import type { CreateRegularBookingData } from "@calcom/features/bookings/lib/dto/types"; +import { IdempotencyKeyService } from "@calcom/lib/idempotencyKey/idempotencyKeyService"; +import handleCancelBooking from "@calcom/features/bookings/lib/handleCancelBooking"; +import type { BookingRepository } from "@calcom/features/bookings/repositories/BookingRepository"; import type { CalendarSubscriptionEventItem } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionPort.interface"; import logger from "@calcom/lib/logger"; +import { safeStringify } from "@calcom/lib/safeStringify"; import type { SelectedCalendar } from "@calcom/prisma/client"; +import { metrics } from "@sentry/nextjs"; const log = logger.getSubLogger({ prefix: ["CalendarSyncService"] }); @@ -31,10 +36,23 @@ export class CalendarSyncService { countEvents: calendarSubscriptionEvents.length, }); + metrics.count("calendar.sync.handleEvents.calls", 1, { + attributes: { + integration: selectedCalendar.integration, + }, + }); + // only process cal.com calendar events const calEvents = calendarSubscriptionEvents.filter((e) => e.iCalUID?.toLowerCase()?.endsWith("@cal.com") ); + + metrics.distribution("calendar.sync.handleEvents.events_count", calEvents.length, { + attributes: { + integration: selectedCalendar.integration, + }, + }); + if (calEvents.length === 0) { log.debug("handleEvents: no calendar events to process"); return; @@ -45,9 +63,9 @@ export class CalendarSyncService { await Promise.all( calEvents.map((e) => { if (e.status === "cancelled") { - return this.cancelBooking(e); + return this.cancelBooking(e, selectedCalendar.userId); } else { - return this.rescheduleBooking(e); + return this.rescheduleBooking(e, selectedCalendar.userId); } }) ); @@ -58,41 +76,283 @@ export class CalendarSyncService { * @param event * @returns */ - async cancelBooking(event: CalendarSubscriptionEventItem) { + async cancelBooking(event: CalendarSubscriptionEventItem, calendarUserId: number) { + const startTime = performance.now(); log.debug("cancelBooking", { event }); const [bookingUid] = event.iCalUID?.split("@") ?? [undefined]; if (!bookingUid) { - log.debug("Unable to sync, booking not found"); + log.debug("Unable to sync, booking UID not found in iCalUID"); return; } - const booking = await this.deps.bookingRepository.findBookingByUidWithEventType({ bookingUid }); - if (!booking) { - log.debug("Unable to sync, booking not found"); - return; - } + try { + const booking = await this.deps.bookingRepository.findBookingByUidWithEventType({ bookingUid }); + if (!booking) { + log.debug("Unable to sync, booking not found in database", { bookingUid }); + return; + } - // todo handle cancel booking + if (booking.userId !== calendarUserId) { + log.debug("Skipping sync, calendar owner is not the booking host", { + bookingUid, + calendarUserId, + bookingUserId: booking.userId, + }); + metrics.count("calendar.sync.cancelBooking.calls", 1, { + attributes: { status: "skipped", reason: "not_booking_host" }, + }); + return; + } + + if (!booking.userId || !booking.userPrimaryEmail) { + log.warn("Unable to sync cancellation, booking missing required user data", { + bookingUid, + hasUserId: !!booking.userId, + hasUserPrimaryEmail: !!booking.userPrimaryEmail, + }); + metrics.count("calendar.sync.cancelBooking.calls", 1, { + attributes: { status: "skipped", reason: "missing_user_data" }, + }); + return; + } + + await handleCancelBooking({ + userId: booking.userId, + actionSource: "SYSTEM", + bookingData: { + uid: booking.uid, + cancellationReason: "Cancelled on user's calendar", + cancelledBy: booking.userPrimaryEmail, + // Skip calendar event deletion to avoid infinite loops + // (Google/Office365 → Cal.com → Google/Office365 → ...) + skipCalendarSyncTaskCancellation: true, + }, + }); + log.info("Successfully cancelled booking from calendar sync", { bookingUid }); + + metrics.count("calendar.sync.cancelBooking.calls", 1, { + attributes: { status: "success" }, + }); + metrics.distribution("calendar.sync.cancelBooking.duration_ms", performance.now() - startTime, { + attributes: { status: "success" }, + }); + } catch (error) { + log.error("Failed to cancel booking from calendar sync", { bookingUid, error: safeStringify(error) }); + + metrics.count("calendar.sync.cancelBooking.calls", 1, { + attributes: { status: "error" }, + }); + metrics.distribution("calendar.sync.cancelBooking.duration_ms", performance.now() - startTime, { + attributes: { status: "error" }, + }); + } } /** * Reschedule a booking * @param event */ - async rescheduleBooking(event: CalendarSubscriptionEventItem) { + async rescheduleBooking(event: CalendarSubscriptionEventItem, calendarUserId: number) { + const startTime = performance.now(); log.debug("rescheduleBooking", { event }); const [bookingUid] = event.iCalUID?.split("@") ?? [undefined]; if (!bookingUid) { - log.debug("Unable to sync, booking not found"); + log.debug("Unable to sync, booking UID not found in iCalUID"); return; } - const booking = await this.deps.bookingRepository.findBookingByUidWithEventType({ bookingUid }); - if (!booking) { - log.debug("Unable to sync, booking not found"); - return; - } + try { + const booking = await this.deps.bookingRepository.findBookingByUidWithEventType({ bookingUid }); + if (!booking) { + log.debug("Unable to sync, booking not found in database", { bookingUid }); + return; + } - // todo handle update booking + if (booking.userId !== calendarUserId) { + log.debug("Skipping sync, calendar owner is not the booking host", { + bookingUid, + calendarUserId, + bookingUserId: booking.userId, + }); + metrics.count("calendar.sync.rescheduleBooking.calls", 1, { + attributes: { status: "skipped", reason: "not_booking_host" }, + }); + return; + } + + if (!booking.eventTypeId) { + log.warn("Unable to sync reschedule, booking missing eventTypeId", { bookingUid }); + metrics.count("calendar.sync.rescheduleBooking.calls", 1, { + attributes: { status: "skipped", reason: "missing_event_type_id" }, + }); + return; + } + + if (!hasStartTimeChanged(booking, event)) { + log.debug("Skipping reschedule, start time has not changed", { bookingUid }); + metrics.count("calendar.sync.rescheduleBooking.calls", 1, { + attributes: { status: "skipped", reason: "no_time_change" }, + }); + return; + } + + // Dynamic import to avoid loading the entire booking service chain at module evaluation time + // This prevents react-awesome-query-builder from being loaded in server-side contexts + const { getRegularBookingService } = await import( + "@calcom/features/bookings/di/RegularBookingService.container" + ); + const regularBookingService = getRegularBookingService(); + await regularBookingService.createBooking({ + bookingData: buildRescheduleBookingData(booking, event), + bookingMeta: { + // Skip calendar event creation to avoid infinite loops + // (Google/Office365 → Cal.com → Google/Office365 → ...) + skipCalendarSyncTaskCreation: true, + skipAvailabilityCheck: true, + skipEventLimitsCheck: true, + }, + }); + log.info("Successfully rescheduled booking from calendar sync", { bookingUid }); + + metrics.count("calendar.sync.rescheduleBooking.calls", 1, { + attributes: { status: "success" }, + }); + metrics.distribution("calendar.sync.rescheduleBooking.duration_ms", performance.now() - startTime, { + attributes: { status: "success" }, + }); + } catch (error) { + log.error("Failed to reschedule booking from calendar sync", { + bookingUid, + error: safeStringify(error), + }); + + metrics.count("calendar.sync.rescheduleBooking.calls", 1, { + attributes: { status: "error" }, + }); + metrics.distribution("calendar.sync.rescheduleBooking.duration_ms", performance.now() - startTime, { + attributes: { status: "error" }, + }); + } } } + +export type BookingWithEventType = NonNullable< + Awaited> +>; + +type RescheduleBookingData = CreateRegularBookingData & { + responses: Record; + idempotencyKey: string; +}; + +export const buildRescheduleBookingData = ( + booking: BookingWithEventType, + event: CalendarSubscriptionEventItem +): RescheduleBookingData => { + const fallbackStart = booking.startTime.toISOString(); + const start = event.start?.toISOString() ?? fallbackStart; + + // Keep the original booking duration — external calendar controls "when", Cal.com controls "how long" + const originalDurationMs = booking.endTime.getTime() - booking.startTime.getTime(); + const end = new Date(new Date(start).getTime() + originalDurationMs).toISOString(); + + return { + eventTypeId: booking.eventTypeId!, + start, + end, + timeZone: event.timeZone ?? "UTC", + language: "en", + metadata: buildMetadataFromCalendarEvent(event), + rescheduleUid: booking.uid, + idempotencyKey: IdempotencyKeyService.generate({ + startTime: new Date(start), + endTime: new Date(end), + userId: booking.userId ?? undefined, + reassignedById: null, + }), + responses: mergeBookingResponsesWithEventData(booking, event), + }; +}; + +export const extractBookingResponses = (booking: BookingWithEventType): Record => { + const rawResponses = booking.responses; + if (rawResponses && typeof rawResponses === "object" && !Array.isArray(rawResponses)) { + return rawResponses as Record; + } + + const fallbackLocation = booking.location ?? ""; + + return { + name: booking.title, + email: booking.userPrimaryEmail ?? "", + guests: [], + notes: booking.description ?? "", + smsReminderNumber: booking.smsReminderNumber ?? undefined, + location: fallbackLocation + ? { + label: fallbackLocation, + value: fallbackLocation, + optionValue: fallbackLocation, + } + : undefined, + }; +}; + +export const mergeBookingResponsesWithEventData = ( + booking: BookingWithEventType, + event: CalendarSubscriptionEventItem +): Record => { + const baseResponses = extractBookingResponses(booking); + const overrides: Record = {}; + + if (event.summary) { + overrides.title = event.summary; + } + + if (event.description) { + overrides.notes = event.description; + } + + if (event.location) { + overrides.location = { + value: event.location, + label: event.location, + optionValue: event.location, + }; + } + + return { + ...baseResponses, + ...overrides, + }; +}; + +export const buildMetadataFromCalendarEvent = (event: CalendarSubscriptionEventItem) => { + const payload = { + summary: event.summary ?? null, + description: event.description ?? null, + location: event.location ?? null, + busy: event.busy ?? null, + status: event.status ?? null, + isAllDay: event.isAllDay ?? null, + timeZone: event.timeZone ?? null, + recurringEventId: event.recurringEventId ?? null, + originalStartDate: event.originalStartDate?.toISOString() ?? null, + createdAt: event.createdAt?.toISOString() ?? null, + updatedAt: event.updatedAt?.toISOString() ?? null, + etag: event.etag ?? null, + kind: event.kind ?? null, + }; + + return { + calendarSubscriptionEvent: JSON.stringify(payload), + }; +}; + +export const hasStartTimeChanged = ( + booking: BookingWithEventType, + event: CalendarSubscriptionEventItem +): boolean => { + if (!event.start) return false; + return event.start.getTime() !== booking.startTime.getTime(); +}; diff --git a/packages/features/calendar-subscription/lib/sync/__tests__/CalendarSyncService.integration.test.ts b/packages/features/calendar-subscription/lib/sync/__tests__/CalendarSyncService.integration.test.ts new file mode 100644 index 0000000000..ccf2b6d03b --- /dev/null +++ b/packages/features/calendar-subscription/lib/sync/__tests__/CalendarSyncService.integration.test.ts @@ -0,0 +1,1048 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; + +import type { CalendarSubscriptionEventItem } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionPort.interface"; +import type { BookingRepository } from "@calcom/lib/server/repository/booking"; +import type { SelectedCalendar } from "@calcom/prisma/client"; + +import { + type BookingWithEventType, + CalendarSyncService, + buildMetadataFromCalendarEvent, + buildRescheduleBookingData, + extractBookingResponses, + hasStartTimeChanged, + mergeBookingResponsesWithEventData, +} from "../CalendarSyncService"; + +const { mockHandleCancelBooking, mockCreateBooking } = vi.hoisted(() => ({ + mockHandleCancelBooking: vi.fn().mockResolvedValue(undefined), + mockCreateBooking: vi.fn().mockResolvedValue(undefined), +})); + +vi.mock("@calcom/features/bookings/lib/handleCancelBooking", () => ({ + default: mockHandleCancelBooking, +})); + +vi.mock("@calcom/features/bookings/di/RegularBookingService.container", () => ({ + getRegularBookingService: () => ({ + createBooking: mockCreateBooking, + }), +})); + +vi.mock("@calcom/lib/idempotencyKey/idempotencyKeyService", () => ({ + IdempotencyKeyService: { + generate: vi.fn(() => "test-idempotency-key"), + }, +})); + +vi.mock("@sentry/nextjs", () => ({ + metrics: { + count: vi.fn(), + distribution: vi.fn(), + }, +})); + +const makeBooking = (overrides: Partial = {}): BookingWithEventType => + ({ + id: 1, + uid: "booking-uid-123", + userId: 42, + userPrimaryEmail: "user@example.com", + startTime: new Date("2024-01-15T10:00:00Z"), + endTime: new Date("2024-01-15T11:00:00Z"), + title: "Team Standup", + description: "Daily standup meeting", + location: "https://meet.google.com/abc", + smsReminderNumber: null, + responses: { + name: "John Doe", + email: "john@example.com", + notes: "Daily standup meeting", + location: { + value: "https://meet.google.com/abc", + label: "Google Meet", + optionValue: "https://meet.google.com/abc", + }, + }, + eventTypeId: 10, + eventType: { id: 10, title: "Standup", length: 60 }, + ...overrides, + }) as unknown as BookingWithEventType; + +const makeEvent = (overrides: Partial = {}): CalendarSubscriptionEventItem => ({ + id: "gcal-event-1", + iCalUID: "booking-uid-123@cal.com", + start: new Date("2024-01-15T14:00:00Z"), + end: new Date("2024-01-15T15:00:00Z"), + busy: true, + summary: "Team Standup", + description: "Daily standup meeting", + location: "https://meet.google.com/abc", + status: "confirmed", + isAllDay: false, + timeZone: "America/New_York", + recurringEventId: null, + originalStartDate: null, + createdAt: new Date("2024-01-10T00:00:00Z"), + updatedAt: new Date("2024-01-15T09:00:00Z"), + etag: '"etag-123"', + kind: "calendar#event", + ...overrides, +}); + +const mockSelectedCalendar: SelectedCalendar = { + id: "sc-1", + userId: 42, + credentialId: 1, + integration: "google_calendar", + externalId: "user@gmail.com", + eventTypeId: null, + delegationCredentialId: null, + domainWideDelegationCredentialId: null, + googleChannelId: null, + googleChannelKind: null, + googleChannelResourceId: null, + googleChannelResourceUri: null, + googleChannelExpiration: null, + error: null, + lastErrorAt: null, + watchAttempts: 0, + maxAttempts: 3, + unwatchAttempts: 0, + createdAt: new Date(), + updatedAt: new Date(), + channelId: "channel-1", + channelKind: "web_hook", + channelResourceId: "resource-1", + channelResourceUri: "https://example.com/webhook", + channelExpiration: new Date(Date.now() + 86400000), + syncSubscribedAt: new Date(), + syncToken: "sync-token-1", + syncedAt: new Date(), + syncErrorAt: null, + syncErrorCount: 0, +}; + +// ─── Helper function tests (pure, no mocks needed) ─────────────────────────── + +describe("buildRescheduleBookingData", () => { + test("preserves original 60-min duration when event is moved", () => { + const booking = makeBooking(); + const event = makeEvent({ + start: new Date("2024-01-15T14:00:00Z"), + end: new Date("2024-01-15T15:00:00Z"), + }); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.start).toBe("2024-01-15T14:00:00.000Z"); + expect(result.end).toBe("2024-01-15T15:00:00.000Z"); + }); + + test("preserves original 30-min duration when event is stretched to 90min externally", () => { + const booking = makeBooking({ + startTime: new Date("2024-01-15T10:00:00Z"), + endTime: new Date("2024-01-15T10:30:00Z"), + }); + const event = makeEvent({ + start: new Date("2024-01-15T14:00:00Z"), + end: new Date("2024-01-15T15:30:00Z"), // 90min in external calendar + }); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.start).toBe("2024-01-15T14:00:00.000Z"); + expect(result.end).toBe("2024-01-15T14:30:00.000Z"); // 30min preserved, NOT 15:30 + }); + + test("preserves original 2-hour duration when event is shortened externally", () => { + const booking = makeBooking({ + startTime: new Date("2024-01-15T10:00:00Z"), + endTime: new Date("2024-01-15T12:00:00Z"), + }); + const event = makeEvent({ + start: new Date("2024-01-15T14:00:00Z"), + end: new Date("2024-01-15T14:30:00Z"), // shortened to 30min + }); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.start).toBe("2024-01-15T14:00:00.000Z"); + expect(result.end).toBe("2024-01-15T16:00:00.000Z"); // 2h preserved + }); + + test("falls back to booking start when event start is null", () => { + const booking = makeBooking(); + const event = makeEvent({ start: null }); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.start).toBe("2024-01-15T10:00:00.000Z"); + expect(result.end).toBe("2024-01-15T11:00:00.000Z"); + }); + + test("uses event timezone, falls back to UTC", () => { + const booking = makeBooking(); + + const withTz = buildRescheduleBookingData(booking, makeEvent({ timeZone: "Europe/London" })); + expect(withTz.timeZone).toBe("Europe/London"); + + const withoutTz = buildRescheduleBookingData(booking, makeEvent({ timeZone: null })); + expect(withoutTz.timeZone).toBe("UTC"); + }); + + test("sets rescheduleUid to original booking uid", () => { + const booking = makeBooking({ uid: "original-uid-abc" }); + const event = makeEvent(); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.rescheduleUid).toBe("original-uid-abc"); + }); + + test("sets eventTypeId from booking", () => { + const booking = makeBooking({ eventTypeId: 99 }); + const event = makeEvent(); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.eventTypeId).toBe(99); + }); + + test("handles cross-day rescheduling correctly", () => { + const booking = makeBooking({ + startTime: new Date("2024-01-15T23:00:00Z"), + endTime: new Date("2024-01-16T00:30:00Z"), // 90min crossing midnight + }); + const event = makeEvent({ + start: new Date("2024-01-20T22:00:00Z"), + end: new Date("2024-01-20T23:00:00Z"), + }); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.start).toBe("2024-01-20T22:00:00.000Z"); + expect(result.end).toBe("2024-01-20T23:30:00.000Z"); // 90min preserved, crosses midnight + }); +}); + +describe("extractBookingResponses", () => { + test("returns existing responses when present as object", () => { + const booking = makeBooking({ + responses: { name: "Jane", email: "jane@test.com", custom: "value" }, + }); + + const result = extractBookingResponses(booking); + + expect(result).toEqual({ name: "Jane", email: "jane@test.com", custom: "value" }); + }); + + test("builds fallback responses when responses is null", () => { + const booking = makeBooking({ + responses: null, + title: "My Booking", + userPrimaryEmail: "user@test.com", + description: "Some notes", + smsReminderNumber: "+5511999999999", + location: "Zoom", + }); + + const result = extractBookingResponses(booking); + + expect(result).toEqual({ + name: "My Booking", + email: "user@test.com", + guests: [], + notes: "Some notes", + smsReminderNumber: "+5511999999999", + location: { + label: "Zoom", + value: "Zoom", + optionValue: "Zoom", + }, + }); + }); + + test("builds fallback responses when responses is an array (invalid shape)", () => { + const booking = makeBooking({ responses: ["invalid"] as unknown as null }); + + const result = extractBookingResponses(booking); + + expect(result).toHaveProperty("name"); + expect(result).toHaveProperty("email"); + expect(result).toHaveProperty("guests"); + }); + + test("omits location from fallback when booking has no location", () => { + const booking = makeBooking({ responses: null, location: null }); + + const result = extractBookingResponses(booking); + + expect(result.location).toBeUndefined(); + }); + + test("handles empty string location", () => { + const booking = makeBooking({ responses: null, location: "" }); + + const result = extractBookingResponses(booking); + + expect(result.location).toBeUndefined(); + }); + + test("handles null userPrimaryEmail in fallback", () => { + const booking = makeBooking({ responses: null, userPrimaryEmail: null }); + + const result = extractBookingResponses(booking); + + expect(result.email).toBe(""); + }); + + test("handles null description in fallback", () => { + const booking = makeBooking({ responses: null, description: null }); + + const result = extractBookingResponses(booking); + + expect(result.notes).toBe(""); + }); +}); + +describe("mergeBookingResponsesWithEventData", () => { + test("overrides title, notes, and location from event", () => { + const booking = makeBooking({ + responses: { name: "John", email: "john@test.com", notes: "old notes" }, + }); + const event = makeEvent({ + summary: "New Title", + description: "New notes", + location: "New Location", + }); + + const result = mergeBookingResponsesWithEventData(booking, event); + + expect(result.name).toBe("John"); // preserved from booking + expect(result.email).toBe("john@test.com"); // preserved from booking + expect(result.title).toBe("New Title"); // from event + expect(result.notes).toBe("New notes"); // overridden by event + expect(result.location).toEqual({ + value: "New Location", + label: "New Location", + optionValue: "New Location", + }); + }); + + test("does not override when event fields are null/empty", () => { + const booking = makeBooking({ + responses: { name: "John", notes: "Original notes", location: { value: "Original" } }, + }); + const event = makeEvent({ + summary: null, + description: null, + location: null, + }); + + const result = mergeBookingResponsesWithEventData(booking, event); + + expect(result.title).toBeUndefined(); + expect(result.notes).toBe("Original notes"); + expect(result.location).toEqual({ value: "Original" }); + }); + + test("partially overrides — only summary changed", () => { + const booking = makeBooking({ + responses: { name: "John", notes: "Keep this" }, + }); + const event = makeEvent({ + summary: "Changed Title", + description: null, + location: null, + }); + + const result = mergeBookingResponsesWithEventData(booking, event); + + expect(result.title).toBe("Changed Title"); + expect(result.notes).toBe("Keep this"); // not overridden + }); +}); + +describe("buildMetadataFromCalendarEvent", () => { + test("serializes all event fields into calendarSubscriptionEvent", () => { + const event = makeEvent(); + + const result = buildMetadataFromCalendarEvent(event); + + expect(result).toHaveProperty("calendarSubscriptionEvent"); + const parsed = JSON.parse(result.calendarSubscriptionEvent); + expect(parsed.summary).toBe("Team Standup"); + expect(parsed.description).toBe("Daily standup meeting"); + expect(parsed.location).toBe("https://meet.google.com/abc"); + expect(parsed.busy).toBe(true); + expect(parsed.status).toBe("confirmed"); + expect(parsed.isAllDay).toBe(false); + expect(parsed.timeZone).toBe("America/New_York"); + expect(parsed.etag).toBe('"etag-123"'); + expect(parsed.kind).toBe("calendar#event"); + }); + + test("handles all-null optional fields", () => { + const event = makeEvent({ + summary: null, + description: null, + location: null, + busy: null, + status: null, + isAllDay: null, + timeZone: null, + recurringEventId: null, + originalStartDate: null, + createdAt: null, + updatedAt: null, + etag: null, + kind: null, + }); + + const result = buildMetadataFromCalendarEvent(event); + const parsed = JSON.parse(result.calendarSubscriptionEvent); + + Object.values(parsed).forEach((value) => { + expect(value).toBeNull(); + }); + }); + + test("serializes dates as ISO strings", () => { + const event = makeEvent({ + originalStartDate: new Date("2024-01-15T10:00:00Z"), + createdAt: new Date("2024-01-10T00:00:00Z"), + updatedAt: new Date("2024-01-15T09:00:00Z"), + }); + + const result = buildMetadataFromCalendarEvent(event); + const parsed = JSON.parse(result.calendarSubscriptionEvent); + + expect(parsed.originalStartDate).toBe("2024-01-15T10:00:00.000Z"); + expect(parsed.createdAt).toBe("2024-01-10T00:00:00.000Z"); + expect(parsed.updatedAt).toBe("2024-01-15T09:00:00.000Z"); + }); +}); + +// ─── Change detection ───────────────────────────────────────────────────────── + +describe("hasStartTimeChanged", () => { + test("returns true when event start differs from booking start", () => { + const booking = makeBooking({ startTime: new Date("2024-01-15T10:00:00Z") }); + const event = makeEvent({ start: new Date("2024-01-15T14:00:00Z") }); + + expect(hasStartTimeChanged(booking, event)).toBe(true); + }); + + test("returns false when event start equals booking start", () => { + const booking = makeBooking({ startTime: new Date("2024-01-15T10:00:00Z") }); + const event = makeEvent({ start: new Date("2024-01-15T10:00:00Z") }); + + expect(hasStartTimeChanged(booking, event)).toBe(false); + }); + + test("returns false when event start is null", () => { + const booking = makeBooking({ startTime: new Date("2024-01-15T10:00:00Z") }); + const event = makeEvent({ start: null }); + + expect(hasStartTimeChanged(booking, event)).toBe(false); + }); + + test("detects 1-second difference", () => { + const booking = makeBooking({ startTime: new Date("2024-01-15T10:00:00Z") }); + const event = makeEvent({ start: new Date("2024-01-15T10:00:01Z") }); + + expect(hasStartTimeChanged(booking, event)).toBe(true); + }); + + test("same timestamp in different timezone representations is equal", () => { + const booking = makeBooking({ startTime: new Date("2024-01-15T10:00:00Z") }); + // Same instant, different representation + const event = makeEvent({ start: new Date("2024-01-15T07:00:00-03:00") }); + + expect(hasStartTimeChanged(booking, event)).toBe(false); + }); +}); + +describe("CalendarSyncService - skip reschedule when no time change", () => { + let service: CalendarSyncService; + let mockBookingRepository: BookingRepository; + + beforeEach(() => { + mockBookingRepository = { + findBookingByUidWithEventType: vi.fn(), + } as unknown as BookingRepository; + + service = new CalendarSyncService({ + bookingRepository: mockBookingRepository, + }); + + vi.clearAllMocks(); + }); + + test("skips reschedule when start time has not changed (e.g. RSVP update)", async () => { + const booking = makeBooking({ + startTime: new Date("2024-01-15T10:00:00Z"), + endTime: new Date("2024-01-15T11:00:00Z"), + }); + const event = makeEvent({ + start: new Date("2024-01-15T10:00:00Z"), + end: new Date("2024-01-15T11:00:00Z"), + status: "confirmed", + }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); + + test("proceeds with reschedule when start time has changed", async () => { + const booking = makeBooking({ + startTime: new Date("2024-01-15T10:00:00Z"), + endTime: new Date("2024-01-15T11:00:00Z"), + }); + const event = makeEvent({ + start: new Date("2024-01-15T14:00:00Z"), + end: new Date("2024-01-15T15:00:00Z"), + }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + expect(mockCreateBooking).toHaveBeenCalled(); + }); + + test("skips reschedule when event start is null", async () => { + const booking = makeBooking(); + const event = makeEvent({ start: null }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); +}); + +// ─── iCalUID parsing edge cases ─────────────────────────────────────────────── + +describe("iCalUID parsing", () => { + let service: CalendarSyncService; + let mockBookingRepository: BookingRepository; + + beforeEach(() => { + mockBookingRepository = { + findBookingByUidWithEventType: vi.fn(), + } as unknown as BookingRepository; + + service = new CalendarSyncService({ + bookingRepository: mockBookingRepository, + }); + + vi.clearAllMocks(); + }); + + test("iCalUID with multiple @ signs: only first part is used as bookingUid", async () => { + const event = makeEvent({ iCalUID: "uid-part@extra@cal.com", status: "cancelled" }); + const booking = makeBooking({ uid: "uid-part" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.cancelBooking(event, mockSelectedCalendar.userId); + + // split("@") → ["uid-part", "extra", "cal.com"], first element is "uid-part" + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "uid-part", + }); + expect(mockHandleCancelBooking).toHaveBeenCalled(); + }); + + test("iCalUID with UUID format works correctly", async () => { + const uuid = "550e8400-e29b-41d4-a716-446655440000"; + const event = makeEvent({ iCalUID: `${uuid}@cal.com` }); + const booking = makeBooking({ uid: uuid }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: uuid, + }); + }); + + test("iCalUID with no @ sign: entire string becomes bookingUid", async () => { + const event = makeEvent({ iCalUID: "no-at-sign" }); + const booking = makeBooking({ uid: "no-at-sign" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + // split("@") → ["no-at-sign"], first element is "no-at-sign" + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "no-at-sign", + }); + }); + + test("iCalUID that is just '@' results in empty bookingUid and returns early", async () => { + const event = makeEvent({ iCalUID: "@" }); + + await service.cancelBooking(event, mockSelectedCalendar.userId); + + // split("@") → ["", ""], first element is "" which is falsy + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + }); + + test("undefined iCalUID returns early", async () => { + const event = makeEvent({ iCalUID: undefined as unknown as null }); + + await service.cancelBooking(event, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + }); +}); + +// ─── Zero/negative duration edge cases ──────────────────────────────────────── + +describe("buildRescheduleBookingData - duration edge cases", () => { + test("booking with zero duration: end equals start", () => { + const booking = makeBooking({ + startTime: new Date("2024-01-15T10:00:00Z"), + endTime: new Date("2024-01-15T10:00:00Z"), // zero duration + }); + const event = makeEvent({ + start: new Date("2024-01-20T14:00:00Z"), + }); + + const result = buildRescheduleBookingData(booking, event); + + // 0ms duration preserved: end === start + expect(result.start).toBe("2024-01-20T14:00:00.000Z"); + expect(result.end).toBe("2024-01-20T14:00:00.000Z"); + }); + + test("booking with very short duration (1 minute)", () => { + const booking = makeBooking({ + startTime: new Date("2024-01-15T10:00:00Z"), + endTime: new Date("2024-01-15T10:01:00Z"), + }); + const event = makeEvent({ + start: new Date("2024-01-20T14:00:00Z"), + }); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.start).toBe("2024-01-20T14:00:00.000Z"); + expect(result.end).toBe("2024-01-20T14:01:00.000Z"); + }); + + test("booking with very long duration (8 hours)", () => { + const booking = makeBooking({ + startTime: new Date("2024-01-15T09:00:00Z"), + endTime: new Date("2024-01-15T17:00:00Z"), + }); + const event = makeEvent({ + start: new Date("2024-01-20T08:00:00Z"), + }); + + const result = buildRescheduleBookingData(booking, event); + + expect(result.start).toBe("2024-01-20T08:00:00.000Z"); + expect(result.end).toBe("2024-01-20T16:00:00.000Z"); // 8h preserved + }); +}); + +// ─── End-to-end data flow: event fields → createBooking ─────────────────────── + +describe("CalendarSyncService - booking data updated from external event", () => { + let service: CalendarSyncService; + let mockBookingRepository: BookingRepository; + + beforeEach(() => { + mockBookingRepository = { + findBookingByUidWithEventType: vi.fn(), + } as unknown as BookingRepository; + + service = new CalendarSyncService({ + bookingRepository: mockBookingRepository, + }); + + vi.clearAllMocks(); + }); + + test("summary from external event overrides title in responses", async () => { + const booking = makeBooking({ + responses: { name: "John Doe", email: "john@test.com", notes: "Original" }, + }); + const event = makeEvent({ summary: "New Meeting Title" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + const call = mockCreateBooking.mock.calls[0][0]; + expect(call.bookingData.responses.title).toBe("New Meeting Title"); + expect(call.bookingData.responses.name).toBe("John Doe"); // preserved + }); + + test("description from external event overrides notes in responses", async () => { + const booking = makeBooking({ + responses: { name: "John Doe", email: "john@test.com", notes: "Original notes" }, + }); + const event = makeEvent({ description: "Updated meeting agenda" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + const call = mockCreateBooking.mock.calls[0][0]; + expect(call.bookingData.responses.notes).toBe("Updated meeting agenda"); + }); + + test("location from external event overrides location in responses", async () => { + const booking = makeBooking({ + responses: { + name: "John Doe", + location: { value: "Old Room", label: "Old Room", optionValue: "Old Room" }, + }, + }); + const event = makeEvent({ location: "https://zoom.us/j/123" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + const call = mockCreateBooking.mock.calls[0][0]; + expect(call.bookingData.responses.location).toEqual({ + value: "https://zoom.us/j/123", + label: "https://zoom.us/j/123", + optionValue: "https://zoom.us/j/123", + }); + }); + + test("null fields from external event do NOT override booking responses", async () => { + const booking = makeBooking({ + responses: { + name: "John Doe", + email: "john@test.com", + notes: "Keep these notes", + location: { value: "Room A", label: "Room A", optionValue: "Room A" }, + }, + }); + const event = makeEvent({ summary: null, description: null, location: null }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + const call = mockCreateBooking.mock.calls[0][0]; + expect(call.bookingData.responses.notes).toBe("Keep these notes"); + expect(call.bookingData.responses.location).toEqual({ + value: "Room A", + label: "Room A", + optionValue: "Room A", + }); + expect(call.bookingData.responses.title).toBeUndefined(); // no override + }); + + test("all fields updated simultaneously from external event", async () => { + const booking = makeBooking({ + responses: { + name: "John Doe", + email: "john@test.com", + notes: "Old notes", + location: { value: "Old", label: "Old", optionValue: "Old" }, + guests: ["guest@test.com"], + }, + }); + const event = makeEvent({ + summary: "Renamed Meeting", + description: "New agenda for Q1", + location: "Conference Room B", + }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + const call = mockCreateBooking.mock.calls[0][0]; + const responses = call.bookingData.responses; + + // Overridden by event + expect(responses.title).toBe("Renamed Meeting"); + expect(responses.notes).toBe("New agenda for Q1"); + expect(responses.location).toEqual({ + value: "Conference Room B", + label: "Conference Room B", + optionValue: "Conference Room B", + }); + + // Preserved from booking + expect(responses.name).toBe("John Doe"); + expect(responses.email).toBe("john@test.com"); + expect(responses.guests).toEqual(["guest@test.com"]); + }); + + test("external event data is stored in metadata as calendarSubscriptionEvent", async () => { + const booking = makeBooking(); + const event = makeEvent({ + summary: "Sync Test", + description: "From Google", + location: "Virtual", + status: "confirmed", + timeZone: "America/Sao_Paulo", + }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + const call = mockCreateBooking.mock.calls[0][0]; + const raw = call.bookingData.metadata.calendarSubscriptionEvent; + expect(typeof raw).toBe("string"); + + const parsed = JSON.parse(raw); + expect(parsed.summary).toBe("Sync Test"); + expect(parsed.description).toBe("From Google"); + expect(parsed.location).toBe("Virtual"); + expect(parsed.status).toBe("confirmed"); + expect(parsed.timeZone).toBe("America/Sao_Paulo"); + }); + + test("booking without existing responses uses fallback with event overrides", async () => { + const booking = makeBooking({ + responses: null, + title: "Original Title", + userPrimaryEmail: "user@company.com", + description: "Original description", + location: "Original Location", + }); + const event = makeEvent({ + summary: "Calendar Title", + description: "Calendar description", + location: "Calendar Location", + }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + const call = mockCreateBooking.mock.calls[0][0]; + const responses = call.bookingData.responses; + + // Fallback fields from booking + expect(responses.name).toBe("Original Title"); + expect(responses.email).toBe("user@company.com"); + expect(responses.guests).toEqual([]); + + // Overridden by event + expect(responses.title).toBe("Calendar Title"); + expect(responses.notes).toBe("Calendar description"); + expect(responses.location).toEqual({ + value: "Calendar Location", + label: "Calendar Location", + optionValue: "Calendar Location", + }); + }); +}); + +// ─── Service-level integration tests ────────────────────────────────────────── + +describe("CalendarSyncService - error isolation", () => { + let service: CalendarSyncService; + let mockBookingRepository: BookingRepository; + + beforeEach(() => { + mockBookingRepository = { + findBookingByUidWithEventType: vi.fn(), + } as unknown as BookingRepository; + + service = new CalendarSyncService({ + bookingRepository: mockBookingRepository, + }); + + vi.clearAllMocks(); + }); + + test("handleEvents: failure in one event does not block others", async () => { + const cancelEvent = makeEvent({ iCalUID: "cancel-uid@cal.com", status: "cancelled" }); + const rescheduleEvent = makeEvent({ + iCalUID: "reschedule-uid@cal.com", + status: "confirmed", + start: new Date("2024-01-20T14:00:00Z"), + }); + + const cancelBooking = makeBooking({ uid: "cancel-uid" }); + const rescheduleBooking = makeBooking({ uid: "reschedule-uid" }); + + mockBookingRepository.findBookingByUidWithEventType = vi + .fn() + .mockImplementation(({ bookingUid }: { bookingUid: string }) => { + if (bookingUid === "cancel-uid") return Promise.resolve(cancelBooking); + if (bookingUid === "reschedule-uid") return Promise.resolve(rescheduleBooking); + return Promise.resolve(null); + }); + + // Cancel fails, but reschedule should still work + mockHandleCancelBooking.mockRejectedValue(new Error("Cancel service down")); + + await service.handleEvents(mockSelectedCalendar, [cancelEvent, rescheduleEvent]); + + expect(mockHandleCancelBooking).toHaveBeenCalled(); + expect(mockCreateBooking).toHaveBeenCalled(); + }); + + test("handleEvents: DB error on one event does not block others", async () => { + const event1 = makeEvent({ iCalUID: "uid-1@cal.com", status: "confirmed" }); + const event2 = makeEvent({ iCalUID: "uid-2@cal.com", status: "confirmed" }); + + let callCount = 0; + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockImplementation(() => { + callCount++; + if (callCount === 1) return Promise.reject(new Error("DB timeout")); + return Promise.resolve(makeBooking({ uid: "uid-2" })); + }); + + await service.handleEvents(mockSelectedCalendar, [event1, event2]); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledTimes(2); + expect(mockCreateBooking).toHaveBeenCalledTimes(1); + }); + + test("cancelBooking: passes correct data to handleCancelBooking", async () => { + const booking = makeBooking({ + uid: "my-booking-uid", + userId: 99, + userPrimaryEmail: "admin@company.com", + }); + const event = makeEvent({ iCalUID: "my-booking-uid@cal.com", status: "cancelled" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.cancelBooking(event, 99); + + expect(mockHandleCancelBooking).toHaveBeenCalledWith({ + userId: 99, + actionSource: "SYSTEM", + bookingData: { + uid: "my-booking-uid", + cancellationReason: "Cancelled on user's calendar", + cancelledBy: "admin@company.com", + skipCalendarSyncTaskCancellation: true, + }, + }); + }); + + test("rescheduleBooking: passes correct bookingMeta flags", async () => { + const booking = makeBooking(); + const event = makeEvent({ + start: new Date("2024-01-20T14:00:00Z"), + end: new Date("2024-01-20T15:00:00Z"), + }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + expect(mockCreateBooking).toHaveBeenCalledWith( + expect.objectContaining({ + bookingMeta: { + skipCalendarSyncTaskCreation: true, + skipAvailabilityCheck: true, + skipEventLimitsCheck: true, + }, + }) + ); + }); + + test("rescheduleBooking: skips booking without eventTypeId", async () => { + const booking = makeBooking({ eventTypeId: null }); + const event = makeEvent(); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); + + test("cancelBooking: skips when calendar owner is not the booking host", async () => { + const booking = makeBooking({ uid: "booking-uid-123", userId: 99 }); + const event = makeEvent({ iCalUID: "booking-uid-123@cal.com", status: "cancelled" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + // calendarUserId (42) !== booking.userId (99) → skip + await service.cancelBooking(event, mockSelectedCalendar.userId); + + expect(mockHandleCancelBooking).not.toHaveBeenCalled(); + }); + + test("rescheduleBooking: skips when calendar owner is not the booking host", async () => { + const booking = makeBooking({ uid: "booking-uid-123", userId: 99 }); + const event = makeEvent({ + iCalUID: "booking-uid-123@cal.com", + start: new Date("2024-01-20T14:00:00Z"), + }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + // calendarUserId (42) !== booking.userId (99) → skip + await service.rescheduleBooking(event, mockSelectedCalendar.userId); + + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); + + test("cancelBooking: skips booking without userId", async () => { + const booking = makeBooking({ userId: null }); + const event = makeEvent({ iCalUID: "booking-uid-123@cal.com", status: "cancelled" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.cancelBooking(event, mockSelectedCalendar.userId); + + expect(mockHandleCancelBooking).not.toHaveBeenCalled(); + }); + + test("cancelBooking: skips booking without userPrimaryEmail", async () => { + const booking = makeBooking({ userPrimaryEmail: null }); + const event = makeEvent({ iCalUID: "booking-uid-123@cal.com", status: "cancelled" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(booking); + + await service.cancelBooking(event, mockSelectedCalendar.userId); + + expect(mockHandleCancelBooking).not.toHaveBeenCalled(); + }); + + test("handleEvents: correctly routes cancelled vs non-cancelled events", async () => { + const cancelledEvent = makeEvent({ iCalUID: "uid-a@cal.com", status: "cancelled" }); + const confirmedEvent = makeEvent({ iCalUID: "uid-b@cal.com", status: "confirmed" }); + + const bookingA = makeBooking({ uid: "uid-a" }); + const bookingB = makeBooking({ uid: "uid-b" }); + + mockBookingRepository.findBookingByUidWithEventType = vi + .fn() + .mockImplementation(({ bookingUid }: { bookingUid: string }) => { + if (bookingUid === "uid-a") return Promise.resolve(bookingA); + if (bookingUid === "uid-b") return Promise.resolve(bookingB); + return Promise.resolve(null); + }); + + await service.handleEvents(mockSelectedCalendar, [cancelledEvent, confirmedEvent]); + + // "cancelled" → cancelBooking, "confirmed" → rescheduleBooking + expect(mockHandleCancelBooking).toHaveBeenCalledTimes(1); + expect(mockCreateBooking).toHaveBeenCalledTimes(1); + }); + + test("handleEvents: non-cancelled statuses (tentative, confirmed) all route to reschedule", async () => { + const tentativeEvent = makeEvent({ iCalUID: "uid-t@cal.com", status: "tentative" }); + const bookingT = makeBooking({ uid: "uid-t" }); + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(bookingT); + + await service.handleEvents(mockSelectedCalendar, [tentativeEvent]); + + expect(mockHandleCancelBooking).not.toHaveBeenCalled(); + expect(mockCreateBooking).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/features/calendar-subscription/lib/sync/__tests__/CalendarSyncService.test.ts b/packages/features/calendar-subscription/lib/sync/__tests__/CalendarSyncService.test.ts new file mode 100644 index 0000000000..ea3b46cbee --- /dev/null +++ b/packages/features/calendar-subscription/lib/sync/__tests__/CalendarSyncService.test.ts @@ -0,0 +1,511 @@ +import { beforeEach, describe, expect, test, vi } from "vitest"; + +import type { CalendarSubscriptionEventItem } from "@calcom/features/calendar-subscription/lib/CalendarSubscriptionPort.interface"; +import type { BookingRepository } from "@calcom/lib/server/repository/booking"; +import type { SelectedCalendar } from "@calcom/prisma/client"; + +import { CalendarSyncService } from "../CalendarSyncService"; + +const { mockHandleCancelBooking, mockCreateBooking } = vi.hoisted(() => ({ + mockHandleCancelBooking: vi.fn().mockResolvedValue(undefined), + mockCreateBooking: vi.fn().mockResolvedValue(undefined), +})); + +vi.mock("@calcom/features/bookings/lib/handleCancelBooking", () => ({ + default: mockHandleCancelBooking, +})); + +vi.mock("@calcom/features/bookings/di/RegularBookingService.container", () => ({ + getRegularBookingService: () => ({ + createBooking: mockCreateBooking, + }), +})); + +vi.mock("@calcom/lib/idempotencyKey/idempotencyKeyService", () => ({ + IdempotencyKeyService: { + generate: vi.fn(() => "test-idempotency-key"), + }, +})); + +vi.mock("@sentry/nextjs", () => ({ + metrics: { + count: vi.fn(), + distribution: vi.fn(), + }, +})); + +const mockSelectedCalendar: SelectedCalendar = { + id: "test-calendar-id", + userId: 1, + credentialId: 1, + integration: "google_calendar", + externalId: "test@example.com", + eventTypeId: null, + delegationCredentialId: null, + domainWideDelegationCredentialId: null, + googleChannelId: null, + googleChannelKind: null, + googleChannelResourceId: null, + googleChannelResourceUri: null, + googleChannelExpiration: null, + error: null, + lastErrorAt: null, + watchAttempts: 0, + maxAttempts: 3, + unwatchAttempts: 0, + createdAt: new Date(), + updatedAt: new Date(), + channelId: "test-channel-id", + channelKind: "web_hook", + channelResourceId: "test-resource-id", + channelResourceUri: "test-resource-uri", + channelExpiration: new Date(Date.now() + 86400000), + syncSubscribedAt: new Date(), + syncToken: "test-sync-token", + syncedAt: new Date(), + syncErrorAt: null, + syncErrorCount: 0, +}; + +const mockBooking = { + id: 1, + uid: "test-booking-uid", + userId: 1, + userPrimaryEmail: "user@example.com", + startTime: new Date("2023-12-01T10:00:00Z"), + endTime: new Date("2023-12-01T11:00:00Z"), + title: "Test Booking", + description: "Initial notes", + location: "Test Location", + smsReminderNumber: "+123456789", + responses: { + name: "John Doe", + email: "john@example.com", + notes: "Initial notes", + location: { + value: "Test Location", + label: "Test Location", + optionValue: "Test Location", + }, + }, + eventTypeId: 1, + eventType: { + id: 1, + title: "Test Event Type", + }, +}; + +const mockCalComEvent: CalendarSubscriptionEventItem = { + id: "event-1", + iCalUID: "test-booking-uid@cal.com", + start: new Date("2023-12-01T10:00:00Z"), + end: new Date("2023-12-01T11:00:00Z"), + busy: true, + summary: "Test Event", + description: "Test Description", + location: "Test Location", + status: "confirmed", + isAllDay: false, + timeZone: "UTC", + recurringEventId: null, + originalStartDate: null, + createdAt: new Date(), + updatedAt: new Date(), + etag: "test-etag", + kind: "calendar#event", +}; + +const mockNonCalComEvent: CalendarSubscriptionEventItem = { + id: "event-2", + iCalUID: "external-event@external.com", + start: new Date("2023-12-01T12:00:00Z"), + end: new Date("2023-12-01T13:00:00Z"), + busy: true, + summary: "External Event", + description: "External Description", + location: "External Location", + status: "confirmed", + isAllDay: false, + timeZone: "UTC", + recurringEventId: null, + originalStartDate: null, + createdAt: new Date(), + updatedAt: new Date(), + etag: "test-etag", + kind: "calendar#event", +}; + +const mockCancelledEvent: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + id: "event-3", + iCalUID: "cancelled-booking-uid@cal.com", + status: "cancelled", +}; + +describe("CalendarSyncService", () => { + let service: CalendarSyncService; + let mockBookingRepository: BookingRepository; + + beforeEach(() => { + mockBookingRepository = { + findBookingByUidWithEventType: vi.fn(), + } as unknown as BookingRepository; + + service = new CalendarSyncService({ + bookingRepository: mockBookingRepository, + }); + + vi.clearAllMocks(); + }); + + describe("handleEvents", () => { + test("should process only Cal.com events", async () => { + const events = [mockCalComEvent, mockNonCalComEvent, mockCancelledEvent]; + + mockBookingRepository.findBookingByUidWithEventType = vi + .fn() + .mockResolvedValueOnce(mockBooking) + .mockResolvedValueOnce(mockBooking); + + await service.handleEvents(mockSelectedCalendar, events); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledTimes(2); + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "test-booking-uid", + }); + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "cancelled-booking-uid", + }); + }); + + test("should return early when no Cal.com events", async () => { + const events = [mockNonCalComEvent]; + + await service.handleEvents(mockSelectedCalendar, events); + + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + }); + + test("should return early when no events", async () => { + await service.handleEvents(mockSelectedCalendar, []); + + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + }); + + test("should handle mixed case iCalUID", async () => { + const eventWithMixedCase: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + iCalUID: "test-booking-uid@CAL.COM", + }; + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(mockBooking); + + await service.handleEvents(mockSelectedCalendar, [eventWithMixedCase]); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "test-booking-uid", + }); + }); + + test("should handle events with null iCalUID", async () => { + const eventWithNullUID: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + iCalUID: null, + }; + + await service.handleEvents(mockSelectedCalendar, [eventWithNullUID]); + + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + }); + }); + + describe("cancelBooking", () => { + test("should successfully cancel a booking", async () => { + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(mockBooking); + + await service.cancelBooking(mockCancelledEvent, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "cancelled-booking-uid", + }); + + expect(mockHandleCancelBooking).toHaveBeenCalledWith({ + userId: mockBooking.userId, + actionSource: "SYSTEM", + bookingData: { + uid: mockBooking.uid, + cancellationReason: "Cancelled on user's calendar", + cancelledBy: mockBooking.userPrimaryEmail, + skipCalendarSyncTaskCancellation: true, + }, + }); + }); + + test("should return early when booking UID is missing", async () => { + const eventWithoutUID: CalendarSubscriptionEventItem = { + ...mockCancelledEvent, + iCalUID: null, + }; + + await service.cancelBooking(eventWithoutUID, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + expect(mockHandleCancelBooking).not.toHaveBeenCalled(); + }); + + test("should return early when booking UID is malformed", async () => { + const eventWithMalformedUID: CalendarSubscriptionEventItem = { + ...mockCancelledEvent, + iCalUID: "@cal.com", + }; + + await service.cancelBooking(eventWithMalformedUID, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + expect(mockHandleCancelBooking).not.toHaveBeenCalled(); + }); + + test("should return early when booking is not found", async () => { + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(null); + + await service.cancelBooking(mockCancelledEvent, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "cancelled-booking-uid", + }); + expect(mockHandleCancelBooking).not.toHaveBeenCalled(); + }); + + test("should handle cancellation errors gracefully without throwing", async () => { + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(mockBooking); + mockHandleCancelBooking.mockRejectedValue(new Error("Cancellation failed")); + + // Should not throw - errors are caught and logged + await expect(service.cancelBooking(mockCancelledEvent, mockSelectedCalendar.userId)).resolves.not.toThrow(); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalled(); + expect(mockHandleCancelBooking).toHaveBeenCalled(); + }); + + test("should handle database errors gracefully without throwing", async () => { + mockBookingRepository.findBookingByUidWithEventType = vi + .fn() + .mockRejectedValue(new Error("DB connection failed")); + + await expect(service.cancelBooking(mockCancelledEvent, mockSelectedCalendar.userId)).resolves.not.toThrow(); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalled(); + expect(mockHandleCancelBooking).not.toHaveBeenCalled(); + }); + }); + + describe("rescheduleBooking", () => { + test("should successfully reschedule a booking preserving original duration", async () => { + const updatedEvent: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + start: new Date("2023-12-01T14:00:00Z"), + end: new Date("2023-12-01T15:00:00Z"), + summary: "Updated summary", + description: "Updated description", + location: "Updated location", + }; + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(mockBooking); + + await service.rescheduleBooking(updatedEvent, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "test-booking-uid", + }); + + // Original booking is 10:00-11:00 (60min). New start is 14:00, so end should be 15:00 (60min preserved). + expect(mockCreateBooking).toHaveBeenCalledWith({ + bookingData: { + eventTypeId: mockBooking.eventTypeId, + start: "2023-12-01T14:00:00.000Z", + end: "2023-12-01T15:00:00.000Z", + timeZone: "UTC", + language: "en", + metadata: expect.objectContaining({ + calendarSubscriptionEvent: expect.any(String), + }), + rescheduleUid: mockBooking.uid, + idempotencyKey: expect.any(String), + responses: expect.objectContaining({ + title: "Updated summary", + notes: "Updated description", + location: { + label: "Updated location", + optionValue: "Updated location", + value: "Updated location", + }, + }), + }, + bookingMeta: { + skipCalendarSyncTaskCreation: true, + skipAvailabilityCheck: true, + skipEventLimitsCheck: true, + }, + }); + const lastCall = mockCreateBooking.mock.calls.at(-1)!; + const parsedMetadataUpdated = JSON.parse( + lastCall[0].bookingData.metadata.calendarSubscriptionEvent as string + ); + expect(parsedMetadataUpdated).toEqual( + expect.objectContaining({ + summary: "Updated summary", + description: "Updated description", + location: "Updated location", + }) + ); + }); + + test("should preserve original duration when external event has different duration", async () => { + const stretchedEvent: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + start: new Date("2023-12-01T14:00:00Z"), + end: new Date("2023-12-01T15:30:00Z"), // 90min, but original booking is 60min + }; + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(mockBooking); + + await service.rescheduleBooking(stretchedEvent, mockSelectedCalendar.userId); + + // Original booking is 60min. External event is 90min. Duration should stay 60min. + expect(mockCreateBooking).toHaveBeenCalledWith( + expect.objectContaining({ + bookingData: expect.objectContaining({ + start: "2023-12-01T14:00:00.000Z", + end: "2023-12-01T15:00:00.000Z", // 14:00 + 60min = 15:00, NOT 15:30 + }), + }) + ); + }); + + test("should skip reschedule when event times are null (no change detected)", async () => { + const eventWithNullTimes: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + start: null, + end: null, + }; + + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(mockBooking); + + await service.rescheduleBooking(eventWithNullTimes, mockSelectedCalendar.userId); + + // Null start means no change detected, reschedule is skipped + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); + + test("should build fallback responses when booking responses are missing", async () => { + const bookingWithoutResponses = { + ...mockBooking, + responses: null, + }; + const eventWithDifferentStart: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + start: new Date("2023-12-01T14:00:00Z"), + end: new Date("2023-12-01T15:00:00Z"), + }; + mockBookingRepository.findBookingByUidWithEventType = vi + .fn() + .mockResolvedValue(bookingWithoutResponses); + + await service.rescheduleBooking(eventWithDifferentStart, mockSelectedCalendar.userId); + + expect(mockCreateBooking).toHaveBeenCalledWith({ + bookingData: expect.objectContaining({ + responses: expect.objectContaining({ + name: bookingWithoutResponses.title, + email: bookingWithoutResponses.userPrimaryEmail, + guests: [], + notes: mockCalComEvent.description, + smsReminderNumber: bookingWithoutResponses.smsReminderNumber, + location: { + label: mockCalComEvent.location, + value: mockCalComEvent.location, + optionValue: mockCalComEvent.location, + }, + title: mockCalComEvent.summary, + }), + metadata: expect.objectContaining({ + calendarSubscriptionEvent: expect.any(String), + }), + idempotencyKey: expect.any(String), + }), + bookingMeta: { + skipCalendarSyncTaskCreation: true, + skipAvailabilityCheck: true, + skipEventLimitsCheck: true, + }, + }); + const baseCall = mockCreateBooking.mock.calls.at(-1)!; + const parsedMetadataBase = JSON.parse( + baseCall[0].bookingData.metadata.calendarSubscriptionEvent as string + ); + expect(parsedMetadataBase.summary).toEqual(mockCalComEvent.summary); + }); + + test("should return early when booking UID is missing", async () => { + const eventWithoutUID: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + iCalUID: null, + }; + + await service.rescheduleBooking(eventWithoutUID, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); + + test("should return early when booking UID is malformed", async () => { + const eventWithMalformedUID: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + iCalUID: "@cal.com", + }; + + await service.rescheduleBooking(eventWithMalformedUID, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).not.toHaveBeenCalled(); + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); + + test("should return early when booking is not found", async () => { + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(null); + + await service.rescheduleBooking(mockCalComEvent, mockSelectedCalendar.userId); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalledWith({ + bookingUid: "test-booking-uid", + }); + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); + + test("should handle rescheduling errors gracefully without throwing", async () => { + const eventWithDifferentStart: CalendarSubscriptionEventItem = { + ...mockCalComEvent, + start: new Date("2023-12-01T14:00:00Z"), + end: new Date("2023-12-01T15:00:00Z"), + }; + mockBookingRepository.findBookingByUidWithEventType = vi.fn().mockResolvedValue(mockBooking); + mockCreateBooking.mockRejectedValue(new Error("Rescheduling failed")); + + // Should not throw - errors are caught and logged + await expect(service.rescheduleBooking(eventWithDifferentStart, mockSelectedCalendar.userId)).resolves.not.toThrow(); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalled(); + expect(mockCreateBooking).toHaveBeenCalled(); + }); + + test("should handle database errors gracefully without throwing", async () => { + mockBookingRepository.findBookingByUidWithEventType = vi + .fn() + .mockRejectedValue(new Error("DB connection failed")); + + await expect(service.rescheduleBooking(mockCalComEvent, mockSelectedCalendar.userId)).resolves.not.toThrow(); + + expect(mockBookingRepository.findBookingByUidWithEventType).toHaveBeenCalled(); + expect(mockCreateBooking).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/features/users/lib/getRoutedUsers.ts b/packages/features/users/lib/getRoutedUsers.ts index db30dbe001..e2b0003974 100644 --- a/packages/features/users/lib/getRoutedUsers.ts +++ b/packages/features/users/lib/getRoutedUsers.ts @@ -1,5 +1,4 @@ import { enrichHostsWithDelegationCredentials } from "@calcom/app-store/delegationCredential"; -import { findTeamMembersMatchingAttributeLogic } from "@calcom/features/routing-forms/lib/findTeamMembersMatchingAttributeLogic"; import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId"; import logger from "@calcom/lib/logger"; import type { AttributesQueryValue } from "@calcom/lib/raqb/types"; @@ -52,6 +51,11 @@ async function findMatchingTeamMembersIdsForEventRRSegment(eventType: EventType) return null; } + // Dynamic import to avoid loading react-awesome-query-builder at module evaluation time + const { findTeamMembersMatchingAttributeLogic } = await import( + "@calcom/features/routing-forms/lib/findTeamMembersMatchingAttributeLogic" + ); + const { teamMembersMatchingAttributeLogic } = await findTeamMembersMatchingAttributeLogic({ attributesQueryValue: eventType.rrSegmentQueryValue ?? null, teamId: eventType.team.id, diff --git a/packages/prisma/zod-utils.ts b/packages/prisma/zod-utils.ts index 1d5b23f8aa..1690666d62 100644 --- a/packages/prisma/zod-utils.ts +++ b/packages/prisma/zod-utils.ts @@ -396,6 +396,7 @@ export const bookingCancelSchema = z.object({ cancelSubsequentBookings: z.boolean().optional(), cancellationReason: z.string().optional(), skipCancellationReasonValidation: z.boolean().optional(), + skipCalendarSyncTaskCancellation: z.boolean().optional(), seatReferenceUid: z.string().optional(), cancelledBy: z.string().email({ message: "Invalid email" }).optional(), internalNote: z