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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * chore: remove unnecessary comment from zod-utils.ts Co-Authored-By: Volnei Munhoz <[email protected]> * feat: add Sentry metrics telemetry and fix null assertions in CalendarSyncService Co-Authored-By: Volnei Munhoz <[email protected]> * fix: use dynamic import for getRegularBookingService to avoid RAQB import in server context Co-Authored-By: Volnei Munhoz <[email protected]> * fix: use dynamic import for findTeamMembersMatchingAttributeLogic to avoid RAQB import in server context Co-Authored-By: Volnei Munhoz <[email protected]> * 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 <[email protected]> Co-authored-by: Keith Williams <[email protected]> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
This commit is contained in:
6 files changed
+1880
-45
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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<ReturnType<BookingRepository["findBookingByUidWithEventType"]>>
|
||||
>;
|
||||
|
||||
type RescheduleBookingData = CreateRegularBookingData & {
|
||||
responses: Record<string, unknown>;
|
||||
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<string, unknown> => {
|
||||
const rawResponses = booking.responses;
|
||||
if (rawResponses && typeof rawResponses === "object" && !Array.isArray(rawResponses)) {
|
||||
return rawResponses as Record<string, unknown>;
|
||||
}
|
||||
|
||||
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<string, unknown> => {
|
||||
const baseResponses = extractBookingResponses(booking);
|
||||
const overrides: Record<string, unknown> = {};
|
||||
|
||||
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();
|
||||
};
|
||||
+1048
File diff suppressed because it is too large.
Load diff
+511
@@ -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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
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: "[email protected]",
|
||||
};
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user