Files
cal.diy/packages/app-store/googlecalendar/lib/__tests__/CalendarService.test.ts
T
Keith WilliamsandDevin AI 3a8fe8c7af perf: convert services to factory functions and add TypeScript project references (#26117)
* perf(app-store): convert services to factory functions to narrow SDK type exports

This change converts CRM, Calendar, Payment, and Analytics services from
exporting classes to exporting factory functions that return interface types.
This prevents SDK types (HubSpot, Stripe, etc.) from leaking into the type
system when TypeScript emits .d.ts files.

Services modified:
- CRM: hubspot, salesforce, closecom, pipedrive-crm, zoho-bigin, zohocrm
- Calendar: all 13 calendar services
- Payment: stripe, paypal, alby, btcpayserver, hitpay, mock-payment-app
- Analytics: dub

Video adapters were audited and already use factory pattern.

WIP: Salesforce CRM service has a type error that needs fixing.
Co-Authored-By: [email protected] <[email protected]>

* fix(salesforce): add type assertion for appOptions in factory function

Co-Authored-By: [email protected] <[email protected]>

* fix: update remaining consumers to use factory functions

- getAnalytics.ts: call factory function instead of new
- getConnectedApps.ts: call factory function instead of new
- salesforce/CrmService.ts: fix type assertion with default value
- salesforce/routingForm/incompleteBookingAction.ts: use factory function
- salesforce/routingFormBookingFormHandler.ts: use factory function

Co-Authored-By: [email protected] <[email protected]>

* fix(salesforce): add SalesforceCRM interface for Salesforce-specific methods

- Create SalesforceCRM interface extending CRM with findUserEmailFromLookupField and incompleteBookingWriteToRecord methods
- Add createSalesforceCrmServiceWithSalesforceType factory function for internal Salesforce modules
- Update routing form files to use the new factory function with proper typing

Co-Authored-By: [email protected] <[email protected]>

* fix(salesforce): correct return type in SalesforceCRM interface

The findUserEmailFromLookupField method returns { email: string; recordType: RoutingReasons } | undefined,
not string | undefined. Updated the interface to match the actual implementation.

Co-Authored-By: [email protected] <[email protected]>

* fix: update all call sites to use factory functions

- Update calendar API add files to use factory functions (7 files)
- Update Google Calendar test files to use factory functions (3 files)
- Update Salesforce test files to use SalesforceCRM interface
- Add testMode parameter to createSalesforceCrmServiceWithSalesforceType
- Remove unused @ts-expect-error directive in bookingScenario.ts

Co-Authored-By: [email protected] <[email protected]>

* fix: add GoogleCalendar interface and update factory functions for service-specific methods

Co-Authored-By: [email protected] <[email protected]>

* fix: add type annotation to attendee parameter in google-calendar.e2e.ts

Co-Authored-By: [email protected] <[email protected]>

* fix: update selected-calendars/route.ts to use GoogleCalendar factory function

Co-Authored-By: [email protected] <[email protected]>

* fix: update remaining GoogleCalendarService call sites to use factory function

Co-Authored-By: [email protected] <[email protected]>

* fix: remove explicit type annotation in google-calendar.e2e.ts to fix type error

Co-Authored-By: [email protected] <[email protected]>

* fix: update test mocks to use factory function pattern for calendar and payment services

Co-Authored-By: [email protected] <[email protected]>

* fix: convert MockPaymentService to factory function in setupVitest.ts

Co-Authored-By: [email protected] <[email protected]>

* fix(api-v2): call calendar service factory functions instead of using new

Co-Authored-By: [email protected] <[email protected]>

* perf(trpc): add TypeScript project references to reduce build file count

- Add tsconfig.build.json to app-store with composite settings for declaration emit
- Add tsconfig.server.build.json to trpc with project references
- Add types and typesVersions to app-store package.json to redirect type resolution to dist-types
- Add build:types script to app-store for generating declarations
- Add dist-types to .gitignore

This reduces the tRPC build file count from 7,733 to 5,618 files (27% reduction)
by having TypeScript resolve to prebuilt .d.ts files instead of source files.

Co-Authored-By: [email protected] <[email protected]>

* fix(app-store): add fallback to typesVersions for CI compatibility

The typesVersions now prefers dist-types but falls back to source files
when dist-types don't exist. This fixes CI type-check failures while
still allowing the optimization when dist-types are built.

Co-Authored-By: [email protected] <[email protected]>

* Added build dependency for tRPC on app-store

* fix(app-store): exclude test directories from tsconfig.build.json

Exclude __tests__, __mocks__, and tests directories from the build
config to prevent test utility files (which import from outside rootDir)
from being included in the declaration emit.

Co-Authored-By: [email protected] <[email protected]>

* fix(turbo): add build:types task definition for app-store

Co-Authored-By: [email protected] <[email protected]>

* fix(turbo): remove circular build dependency between trpc and app-store

The build:types task for app-store transitively imports from @calcom/features,
which imports from @calcom/trpc. This creates a circular build dependency when
@calcom/trpc#build depends on @calcom/app-store#build:types.

Solution: Remove the turbo dependency. The typesVersions fallback pattern
['./dist-types/*', './*'] will use source files when dist-types/ doesn't exist,
and use prebuilt declarations when they do exist (for faster builds).

Also exclude dist-types from regular tsconfig.json to prevent 'Cannot write file'
errors when dist-types/ exists.

Co-Authored-By: [email protected] <[email protected]>

* refactor(app-store): rename dist-types to types for consistency

Rename the prebuilt TypeScript declarations folder from dist-types to types
to match the convention used by @calcom/trpc and other packages in the monorepo.

Updated files:
- tsconfig.build.json: declarationDir and exclude
- tsconfig.json: exclude
- package.json: typesVersions paths
- turbo.json: build:types outputs
- .gitignore: ignore path

Co-Authored-By: [email protected] <[email protected]>

* fix(api-v2): update ICS calendar test to mock factory function instead of class prototype

The IcsFeedCalendarService is now a factory function, not a class, so
jest.spyOn(IcsFeedCalendarService.prototype, 'listCalendars') no longer works.

Updated to use jest.spyOn(appStore, 'IcsFeedCalendarService').mockImplementation()
to mock the factory function return value instead.

Co-Authored-By: [email protected] <[email protected]>

* refactor(app-store): rename factory functions to Build* naming convention

- Rename Calendar factory functions from create*CalendarService to BuildCalendarService
- Rename CRM factory functions from create*CrmService to BuildCrmService
- Rename Payment factory functions from PaymentService to BuildPaymentService
- Rename Analytics factory function from createDubAnalyticsService to BuildAnalyticsService
- Update all index.ts re-exports to use new names
- Update all call sites throughout the codebase
- Update test mocks to use new factory function names

This makes it clear that these are factory functions, not class constructors.

Co-Authored-By: [email protected] <[email protected]>

* fix(app-store): update remaining CalendarService and PaymentService imports to Build* names

- Update api/add.ts files for applecalendar, caldavcalendar, exchange2013calendar, exchange2016calendar, exchangecalendar, ics-feedcalendar
- Update mock-payment-app index.ts to export BuildPaymentService
- Fix googlecalendar test import alias for createInMemoryDelegationCredentialForBuildCalendarService

Co-Authored-By: [email protected] <[email protected]>

* fix(tests): update payment service mocks to use BuildPaymentService

- Update setupVitest.ts to use BuildPaymentService instead of PaymentService
- Update handlePayment.test.ts mock to use BuildPaymentService

Co-Authored-By: [email protected] <[email protected]>

* refactor: address PR review comments - rename to Build* and remove unused code

Co-Authored-By: [email protected] <[email protected]>

* refactor: remove explanatory comments and fix indentation

Co-Authored-By: [email protected] <[email protected]>

* chore: update .gitignore to use *.tsbuildinfo pattern

Co-Authored-By: [email protected] <[email protected]>

* fix(api-v2): update IcsFeedCalendarService to BuildIcsFeedCalendarService in e2e test

Co-Authored-By: [email protected] <[email protected]>

* style: format CalendarService.test.ts

Co-Authored-By: [email protected] <[email protected]>

* Delete apps/ui-playground/next-env.d.ts

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-01-15 11:28:05 -03:00

806 lines
25 KiB
TypeScript

import oAuthManagerMock, {
defaultMockOAuthManager,
setFullMockOAuthManagerRequest,
} from "../../../tests/__mocks__/OAuthManager";
import "../__mocks__/features.repository";
import "../__mocks__/getGoogleAppKeys";
import {
calendarMock,
adminMock,
setLastCreatedJWT,
setCredentialsMock,
setLastCreatedOAuth2Client,
freebusyQueryMock,
calendarListMock,
} from "../__mocks__/googleapis";
import { expect, test, beforeEach, vi, describe } from "vitest";
import "vitest-fetch-mock";
import logger from "@calcom/lib/logger";
import { CredentialForCalendarServiceWithEmail } from "@calcom/types/Credential";
import BuildCalendarService, { createGoogleCalendarServiceWithGoogleType } from "../CalendarService";
import { createMockJWTInstance, createCredentialForCalendarService } from "./utils";
const log = logger.getSubLogger({ prefix: ["CalendarService.test"] });
beforeEach(() => {
vi.clearAllMocks();
setCredentialsMock.mockClear();
oAuthManagerMock.OAuthManager = defaultMockOAuthManager;
calendarMock.calendar_v3.Calendar.mockClear();
adminMock.admin_directory_v1.Admin.mockClear();
setLastCreatedJWT(null);
setLastCreatedOAuth2Client(null);
createMockJWTInstance({});
});
const mockCredential: CredentialForCalendarServiceWithEmail = {
id: 1,
userId: 1,
appId: "google-calendar",
type: "google_calendar",
key: {
access_token: "<INVALID_TOKEN>",
},
user: {
email: "[email protected]",
},
delegationCredentialId: null,
delegatedTo: null,
invalid: false,
teamId: null,
};
describe("getAvailability", () => {
test("returns availability for selected calendars", async () => {
const calendarService = BuildCalendarService(mockCredential);
setFullMockOAuthManagerRequest();
const mockedBusyTimes1 = [
{
start: "2024-01-01",
end: "2024-01-02",
},
];
const mockedBusyTimes2 = [
{
start: "2024-01-03",
end: "2024-01-04",
},
];
const mockedBusyTimes = [mockedBusyTimes1, mockedBusyTimes2];
calendarListMock.mockImplementation(() => {
return {
data: {
items: [
{
id: "[email protected]",
},
{
id: "[email protected]",
},
],
},
};
});
// Mock Once so that the getAvailability call doesn't accidentally reuse this mock result
freebusyQueryMock.mockImplementation(({ requestBody }: { requestBody: any }) => {
const calendarsObject: any = {};
requestBody.items.forEach((item: any, index: number) => {
calendarsObject[item.id] = {
busy: mockedBusyTimes[index],
};
});
return {
data: {
calendars: calendarsObject,
},
};
});
const availabilityWithPrimaryAsFallback = await calendarService.getAvailability({
dateFrom: "2024-01-01",
dateTo: "2024-01-02",
selectedCalendars: [],
mode: "slots",
fallbackToPrimary: true,
});
expect(availabilityWithPrimaryAsFallback).toEqual(mockedBusyTimes1);
const availabilityWithAllCalendarsAsFallback = await calendarService.getAvailability({
dateFrom: "2024-01-01",
dateTo: "2024-01-02",
selectedCalendars: [],
mode: "slots",
fallbackToPrimary: false,
});
expect(availabilityWithAllCalendarsAsFallback).toEqual([...mockedBusyTimes1, ...mockedBusyTimes2]);
});
});
describe("getPrimaryCalendar", () => {
test("should fetch primary calendar using 'primary' keyword", async () => {
const calendarService = createGoogleCalendarServiceWithGoogleType(mockCredential);
setFullMockOAuthManagerRequest();
const mockPrimaryCalendar = {
id: "[email protected]",
summary: "Primary Calendar",
description: "Primary calendar for [email protected]",
timeZone: "America/New_York",
};
const calendarsGetMock = vi.fn().mockResolvedValue({
data: mockPrimaryCalendar,
});
calendarMock.calendar_v3.Calendar().calendars.get = calendarsGetMock;
const result = await calendarService.getPrimaryCalendar();
expect(calendarsGetMock).toHaveBeenCalledTimes(1);
expect(calendarsGetMock).toHaveBeenCalledWith({
calendarId: "primary",
});
expect(result).toEqual(mockPrimaryCalendar);
});
});
describe("Date Optimization Benchmarks", () => {
test("native Date calculations should be significantly faster than dayjs while producing identical results", async () => {
const dayjs = (await import("@calcom/dayjs")).default;
const testCases = [
{
dateFrom: "2024-01-01T00:00:00Z",
dateTo: "2024-01-31T00:00:00Z",
name: "30 days",
expectedDiff: 30,
},
{
dateFrom: "2024-01-01T00:00:00Z",
dateTo: "2024-03-31T00:00:00Z",
name: "90 days (API limit)",
expectedDiff: 90,
},
{
dateFrom: "2024-01-01T00:00:00Z",
dateTo: "2024-07-01T00:00:00Z",
name: "182 days (chunking required)",
expectedDiff: 182,
},
];
const iterations = 1000; // Reduced for test performance
for (const testCase of testCases) {
log.info(`Testing ${testCase.name}...`);
// Test correctness first
const dayjsDiff = dayjs(testCase.dateTo).diff(dayjs(testCase.dateFrom), "days");
const nativeDiff = Math.floor(
(new Date(testCase.dateTo).getTime() - new Date(testCase.dateFrom).getTime()) / (1000 * 60 * 60 * 24)
);
// Verify identical results
expect(nativeDiff).toBe(dayjsDiff);
expect(nativeDiff).toBe(testCase.expectedDiff);
// Performance test - dayjs approach
const dayjsStart = performance.now();
for (let i = 0; i < iterations; i++) {
const start = dayjs(testCase.dateFrom);
const end = dayjs(testCase.dateTo);
const diff = end.diff(start, "days");
}
const dayjsTime = performance.now() - dayjsStart;
// Performance test - native Date approach
const nativeStart = performance.now();
for (let i = 0; i < iterations; i++) {
const start = new Date(testCase.dateFrom);
const end = new Date(testCase.dateTo);
const diff = Math.floor((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
}
const nativeTime = performance.now() - nativeStart;
const speedupRatio = dayjsTime / nativeTime;
log.info(
`${testCase.name} - Dayjs: ${dayjsTime.toFixed(2)}ms, Native: ${nativeTime.toFixed(
2
)}ms, Speedup: ${speedupRatio.toFixed(1)}x`
);
if (!process.env.CI) {
const minSpeedup = 5; // Assert significant performance improvement (at least 5x faster)
expect(speedupRatio).toBeGreaterThan(minSpeedup);
}
}
});
test("chunking logic should produce identical results between dayjs and native Date implementations", async () => {
const dayjs = (await import("@calcom/dayjs")).default;
const testCases = [
{
dateFrom: "2024-01-01T00:00:00Z",
dateTo: "2024-04-01T00:00:00Z", // 91 days - requires chunking
name: "91 days (minimal chunking)",
},
{
dateFrom: "2024-01-01T00:00:00Z",
dateTo: "2024-07-01T00:00:00Z", // 182 days - multiple chunks
name: "182 days (multiple chunks)",
},
];
for (const testCase of testCases) {
const fromDate = new Date(testCase.dateFrom);
const toDate = new Date(testCase.dateTo);
const diff = Math.floor((toDate.getTime() - fromDate.getTime()) / (1000 * 60 * 60 * 24));
// Only test cases that require chunking (> 90 days)
if (diff <= 90) continue;
// OLD WAY (dayjs-based chunking)
const originalStartDate = dayjs(testCase.dateFrom);
const originalEndDate = dayjs(testCase.dateTo);
const loopsNumber = Math.ceil(diff / 90);
let startDate = originalStartDate;
let endDate = originalStartDate.add(90, "days");
const oldChunks = [];
for (let i = 0; i < loopsNumber; i++) {
if (endDate.isAfter(originalEndDate)) endDate = originalEndDate;
oldChunks.push({
start: startDate.toISOString(),
end: endDate.toISOString(),
});
startDate = endDate.add(1, "minutes");
endDate = startDate.add(90, "days");
}
// NEW WAY (native Date-based chunking)
let currentStartTime = fromDate.getTime();
const originalEndTime = toDate.getTime();
const ninetyDaysMs = 90 * 24 * 60 * 60 * 1000;
const oneMinuteMs = 60 * 1000;
const newChunks = [];
for (let i = 0; i < loopsNumber; i++) {
let currentEndTime = currentStartTime + ninetyDaysMs;
if (currentEndTime > originalEndTime) {
currentEndTime = originalEndTime;
}
newChunks.push({
start: new Date(currentStartTime).toISOString(),
end: new Date(currentEndTime).toISOString(),
});
currentStartTime = currentEndTime + oneMinuteMs;
}
// Verify identical chunking results
expect(newChunks).toHaveLength(oldChunks.length);
for (let i = 0; i < oldChunks.length; i++) {
expect(newChunks[i].start).toBe(oldChunks[i].start);
expect(newChunks[i].end).toBe(oldChunks[i].end);
}
log.info(`${testCase.name} - Generated ${newChunks.length} identical chunks`);
}
});
test("date parsing should be consistent between dayjs and native Date for all expected input formats", async () => {
const dayjs = (await import("@calcom/dayjs")).default;
// Test various date formats that Google Calendar API might return
const testDates = [
"2024-01-01T00:00:00Z", // UTC
"2024-01-01T12:30:45.123Z", // UTC with milliseconds
"2024-01-01T00:00:00-08:00", // Timezone offset
"2024-01-01T00:00:00+05:30", // Positive timezone offset
"2024-12-31T23:59:59Z", // End of year
"2024-02-29T12:00:00Z", // Leap year date
];
for (const dateString of testDates) {
const dayjsTime = dayjs(dateString).valueOf();
const nativeTime = new Date(dateString).getTime();
expect(nativeTime).toBe(dayjsTime);
// Also verify ISO string output consistency
const dayjsISO = dayjs(dateString).toISOString();
const nativeISO = new Date(dateString).toISOString();
expect(nativeISO).toBe(dayjsISO);
log.debug(`Date parsing verified: ${dateString} -> ${nativeTime}`);
}
});
test("fetchAvailabilityData should handle both single API call and chunked scenarios correctly", async () => {
const calendarService = BuildCalendarService(mockCredential);
setFullMockOAuthManagerRequest();
const mockBusyData = [
{ start: "2024-01-01T10:00:00Z", end: "2024-01-01T11:00:00Z" },
{ start: "2024-01-01T14:00:00Z", end: "2024-01-01T15:00:00Z" },
];
// Mock the getCacheOrFetchAvailability method to return consistent data
const getFreeBusyDataSpy = vi
.spyOn(calendarService as any, "getFreeBusyData")
.mockResolvedValue(mockBusyData.map((item) => ({ ...item, id: "[email protected]" })));
// Test single API call scenario (≤ 90 days)
const shortRangeResult = await (calendarService as any).fetchAvailabilityData(
["[email protected]"],
"2024-01-01T00:00:00Z",
"2024-01-31T00:00:00Z", // 30 days
false
);
expect(shortRangeResult).toEqual(mockBusyData);
expect(getFreeBusyDataSpy).toHaveBeenCalledTimes(1);
getFreeBusyDataSpy.mockClear();
// Test chunked scenario (> 90 days)
const longRangeResult = await (calendarService as any).fetchAvailabilityData(
["[email protected]"],
"2024-01-01T00:00:00Z",
"2024-07-01T00:00:00Z", // 182 days - should require chunking
false
);
// Should return concatenated results from multiple chunks
expect(longRangeResult.length).toBeGreaterThan(0);
expect(getFreeBusyDataSpy).toHaveBeenCalledTimes(3); // 182 days / 90 = ~2.02 -> 3 chunks
getFreeBusyDataSpy.mockRestore();
});
});
describe("createEvent", () => {
test("should create event with correct input/output format and handle all expected properties", async () => {
const calendarService = BuildCalendarService(mockCredential);
setFullMockOAuthManagerRequest();
// Mock Google Calendar API response
const mockGoogleEvent = {
id: "mock-event-id-123",
summary: "Test Meeting",
description: "Test meeting description",
start: {
dateTime: "2024-06-15T10:00:00Z",
timeZone: "UTC",
},
end: {
dateTime: "2024-06-15T11:00:00Z",
timeZone: "UTC",
},
attendees: [
{
email: "[email protected]",
displayName: "Test Organizer",
responseStatus: "accepted",
organizer: true,
},
{
email: "[email protected]",
displayName: "Test Attendee",
responseStatus: "accepted",
},
],
location: "Test Location",
iCalUID: "[email protected]",
recurrence: null,
};
// Mock calendar.events.insert
const eventsInsertMock = vi.fn().mockResolvedValue({
data: mockGoogleEvent,
});
calendarMock.calendar_v3.Calendar().events.insert = eventsInsertMock;
// Test input - simplified CalendarServiceEvent
const testCalEvent = {
type: "test-event-type",
uid: "cal-event-uid-123",
title: "Test Meeting",
startTime: "2024-06-15T10:00:00Z",
endTime: "2024-06-15T11:00:00Z",
organizer: {
id: 1,
name: "Test Organizer",
email: "[email protected]",
timeZone: "UTC",
language: {
translate: (...args: any[]) => args[0], // Mock translate function
locale: "en",
},
},
attendees: [
{
id: 2,
name: "Test Attendee",
email: "[email protected]",
timeZone: "UTC",
language: {
translate: (...args: any[]) => args[0], // Mock translate function
locale: "en",
},
},
],
location: "Test Location",
calendarDescription: "Test meeting description",
destinationCalendar: [
{
id: 1,
integration: "google_calendar",
externalId: "primary",
primaryEmail: null,
userId: mockCredential.userId,
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: 10,
},
],
iCalUID: "[email protected]",
conferenceData: undefined,
hideCalendarEventDetails: false,
seatsPerTimeSlot: null,
seatsShowAttendees: true,
};
// Call createEvent and verify result using inline snapshot
const result = await calendarService.createEvent(testCalEvent, mockCredential.id);
// Verify input processing - check that Google API was called with correct payload
expect(eventsInsertMock).toHaveBeenCalledTimes(1);
const insertCall = eventsInsertMock.mock.calls[0][0];
// Use inline snapshot for input validation
expect(insertCall).toMatchInlineSnapshot(`
{
"calendarId": "primary",
"conferenceDataVersion": 1,
"requestBody": {
"attendees": [
{
"displayName": "Test Organizer",
"email": "primary",
"id": "1",
"language": {
"locale": "en",
"translate": [Function],
},
"name": "Test Organizer",
"organizer": true,
"responseStatus": "accepted",
"timeZone": "UTC",
},
{
"email": "[email protected]",
"language": {
"locale": "en",
"translate": [Function],
},
"name": "Test Attendee",
"responseStatus": "accepted",
"timeZone": "UTC",
},
],
"description": "Test meeting description",
"end": {
"dateTime": "2024-06-15T11:00:00Z",
"timeZone": "UTC",
},
"guestsCanSeeOtherGuests": true,
"iCalUID": "[email protected]",
"location": "Test Location",
"reminders": {
"useDefault": true,
},
"start": {
"dateTime": "2024-06-15T10:00:00Z",
"timeZone": "UTC",
},
"summary": "Test Meeting",
},
"sendUpdates": "none",
}
`);
// Use inline snapshot for output validation
expect(result).toMatchInlineSnapshot(`
{
"additionalInfo": {
"hangoutLink": "",
},
"attendees": [
{
"displayName": "Test Organizer",
"email": "[email protected]",
"organizer": true,
"responseStatus": "accepted",
},
{
"displayName": "Test Attendee",
"email": "[email protected]",
"responseStatus": "accepted",
},
],
"description": "Test meeting description",
"end": {
"dateTime": "2024-06-15T11:00:00Z",
"timeZone": "UTC",
},
"iCalUID": "[email protected]",
"id": "mock-event-id-123",
"location": "Test Location",
"password": "",
"recurrence": null,
"start": {
"dateTime": "2024-06-15T10:00:00Z",
"timeZone": "UTC",
},
"summary": "Test Meeting",
"thirdPartyRecurringEventId": null,
"type": "google_calendar",
"uid": "",
"url": "",
}
`);
log.info("createEvent test passed - input/output formats verified");
});
test("should handle recurring events correctly", async () => {
const calendarService = BuildCalendarService(mockCredential);
setFullMockOAuthManagerRequest();
// Mock recurring event response
const mockRecurringEvent = {
id: "recurring-event-id",
summary: "Weekly Meeting",
recurrence: ["RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT=10"],
start: { dateTime: "2024-06-15T10:00:00Z", timeZone: "UTC" },
end: { dateTime: "2024-06-15T11:00:00Z", timeZone: "UTC" },
};
const mockFirstInstance = {
id: "recurring-event-id_20240615T100000Z",
summary: "Weekly Meeting",
start: { dateTime: "2024-06-15T10:00:00Z", timeZone: "UTC" },
end: { dateTime: "2024-06-15T11:00:00Z", timeZone: "UTC" },
};
calendarMock.calendar_v3.Calendar().events.insert = vi.fn().mockResolvedValue({
data: mockRecurringEvent,
});
calendarMock.calendar_v3.Calendar().events.instances = vi.fn().mockResolvedValue({
data: { items: [mockFirstInstance] },
});
const recurringCalEvent = {
type: "recurring-meeting",
title: "Weekly Meeting",
startTime: "2024-06-15T10:00:00Z",
endTime: "2024-06-15T11:00:00Z",
organizer: {
id: 1,
name: "Organizer",
email: "[email protected]",
timeZone: "UTC",
language: {
translate: (...args: any[]) => args[0], // Mock translate function
locale: "en",
},
},
attendees: [],
recurringEvent: {
freq: 2, // Weekly
interval: 1,
count: 10,
},
destinationCalendar: [
{
id: 1,
integration: "google_calendar",
externalId: "primary",
primaryEmail: null,
userId: mockCredential.userId,
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: 10,
},
],
calendarDescription: "Weekly team meeting",
};
const result = await calendarService.createEvent(recurringCalEvent, mockCredential.id);
// Use inline snapshot for recurring event result
expect(result).toMatchInlineSnapshot(`
{
"additionalInfo": {
"hangoutLink": "",
},
"end": {
"dateTime": "2024-06-15T11:00:00Z",
"timeZone": "UTC",
},
"iCalUID": undefined,
"id": "recurring-event-id_20240615T100000Z",
"password": "",
"start": {
"dateTime": "2024-06-15T10:00:00Z",
"timeZone": "UTC",
},
"summary": "Weekly Meeting",
"thirdPartyRecurringEventId": "recurring-event-id",
"type": "google_calendar",
"uid": "",
"url": "",
}
`);
// Verify recurrence rule was included in the request
const insertCall = calendarMock.calendar_v3.Calendar().events.insert.mock.calls[0][0];
expect(insertCall.requestBody.recurrence).toEqual(["RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT=10"]);
log.info("createEvent recurring event test passed");
});
test("should use default reminders when no custom reminder is configured", async () => {
const calendarService = BuildCalendarService(mockCredential);
setFullMockOAuthManagerRequest();
const mockGoogleEvent = {
id: "mock-event-default-reminder",
summary: "Test Meeting Default Reminder",
start: { dateTime: "2024-06-15T10:00:00Z", timeZone: "UTC" },
end: { dateTime: "2024-06-15T11:00:00Z", timeZone: "UTC" },
};
const eventsInsertMock = vi.fn().mockResolvedValue({
data: mockGoogleEvent,
});
calendarMock.calendar_v3.Calendar().events.insert = eventsInsertMock;
const testCalEvent = {
type: "test-event-type",
uid: "cal-event-uid-456",
title: "Test Meeting Default Reminder",
startTime: "2024-06-15T10:00:00Z",
endTime: "2024-06-15T11:00:00Z",
organizer: {
id: 1,
name: "Test Organizer",
email: "[email protected]",
timeZone: "UTC",
language: { translate: (...args: any[]) => args[0], locale: "en" },
},
attendees: [],
calendarDescription: "Test meeting description",
destinationCalendar: [
{
id: 1,
integration: "google_calendar",
externalId: "primary",
primaryEmail: null,
userId: mockCredential.userId,
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: null,
},
],
};
// Mock the getReminderDuration method to return null (no custom reminder configured)
vi.spyOn(calendarService as any, "getReminderDuration").mockResolvedValue(null);
await calendarService.createEvent(testCalEvent, mockCredential.id);
const insertCall = eventsInsertMock.mock.calls[0][0];
// When no custom reminder is configured, should use Google Calendar's default
expect(insertCall.requestBody.reminders).toEqual({
useDefault: true,
});
log.info("createEvent with default reminders test passed");
});
test("should handle 'just in time' reminder (0 minutes) correctly", async () => {
const calendarService = BuildCalendarService(mockCredential);
setFullMockOAuthManagerRequest();
// Mock the getReminderDuration method to return 0 (just in time)
vi.spyOn(calendarService as any, "getReminderDuration").mockResolvedValue(0);
const mockGoogleEvent = {
id: "mock-event-just-in-time",
summary: "Test Meeting Just In Time",
start: { dateTime: "2024-06-15T10:00:00Z", timeZone: "UTC" },
end: { dateTime: "2024-06-15T11:00:00Z", timeZone: "UTC" },
};
const eventsInsertMock = vi.fn().mockResolvedValue({
data: mockGoogleEvent,
});
calendarMock.calendar_v3.Calendar().events.insert = eventsInsertMock;
const testCalEvent = {
type: "test-event-type",
uid: "cal-event-uid-789",
title: "Test Meeting Just In Time",
startTime: "2024-06-15T10:00:00Z",
endTime: "2024-06-15T11:00:00Z",
organizer: {
id: 1,
name: "Test Organizer",
email: "[email protected]",
timeZone: "UTC",
language: { translate: (...args: any[]) => args[0], locale: "en" },
},
attendees: [],
calendarDescription: "Test meeting description",
destinationCalendar: [
{
id: 1,
integration: "google_calendar",
externalId: "primary",
primaryEmail: null,
userId: mockCredential.userId,
eventTypeId: null,
credentialId: mockCredential.id,
delegationCredentialId: null,
domainWideDelegationCredentialId: null,
createdAt: new Date("2024-06-15T11:00:00Z"),
updatedAt: new Date("2024-06-15T11:00:00Z"),
customCalendarReminder: 0,
},
],
};
await calendarService.createEvent(testCalEvent, mockCredential.id);
const insertCall = eventsInsertMock.mock.calls[0][0];
// When "just in time" (0 minutes) is configured, should override with 0-minute reminders
expect(insertCall.requestBody.reminders).toEqual({
useDefault: false,
overrides: [
{ method: "popup", minutes: 0 },
{ method: "email", minutes: 0 },
],
});
log.info("createEvent with just in time reminders test passed");
});
});