refactor: circular deps between app store and lib [1] (#23653)

* move dailyApiFetcher.ts to app store package

* update imports

* bookingLocationService

* revert

* move findFieldValueByIdentifier

* wip

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* move to features package

* update imports

* update imports

* move

* fix typechecks

* move getCalendarLinks

* mv event test
This commit is contained in:
Benny Joo authored and GitHub committed 2025-09-09 14:38:29 +00:00
1 parent 0fe775962f
commit d908403a99
39 files changed
+63 -55

No files matched your search

@@ -17,7 +17,7 @@ import {
sendAttendeeRequestEmailAndSMS,
} from "@calcom/emails";
import type { BookingType } from "@calcom/features/bookings/lib/handleNewBooking/originalRescheduledBookingUtils";
import type { EventNameObjectType } from "@calcom/lib/event";
import type { EventNameObjectType } from "@calcom/features/eventtypes/lib/eventNaming";
import { getPiiFreeCalendarEvent } from "@calcom/lib/piiFreeData";
import { safeStringify } from "@calcom/lib/safeStringify";
import { getTranslation } from "@calcom/lib/server/i18n";
@@ -0,0 +1,214 @@
import type { TFunction } from "i18next";
import { createEvent } from "ics";
import { RRule } from "rrule";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import dayjs from "@calcom/dayjs";
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
import { getCalendarLinks, CalendarLinkType } from "./getCalendarLinks";
// Mock dependencies
vi.mock("ics", () => ({
createEvent: vi.fn(),
}));
vi.mock("@calcom/lib/isRecurringEvent", () => ({
parseRecurringEvent: vi.fn(),
}));
describe("getCalendarLinks", () => {
// Mock data for tests
const mockStartTime = new Date("2023-01-15T10:00:00Z");
const mockEndTime = new Date("2023-01-15T11:00:00Z");
const mockDayjsStartTime = dayjs(mockStartTime);
const mockDayjsEndTime = dayjs(mockEndTime);
// Mock translation function
const mockT = ((key: string) => key) as TFunction;
// Mock createEvent implementation
const mockIcsValue = "BEGIN:VCALENDAR\nVERSION:2.0\nEND:VCALENDAR";
// Baseline mock objects that can be reused across tests
const baseMockBooking = {
startTime: mockStartTime,
endTime: mockEndTime,
location: "Test Location",
title: "Test Title",
responses: {},
metadata: {},
};
const baseMockEventType = {
recurringEvent: {},
description: "Test Description",
eventName: "Test Event",
isDynamic: false,
length: 60,
team: null,
users: [{ name: "Test User" }],
title: "Test Title",
};
beforeEach(() => {
// Reset mocks before each test
vi.resetAllMocks();
// Default mock implementations
(createEvent as jest.Mock).mockReturnValue({ value: mockIcsValue });
(parseRecurringEvent as jest.Mock).mockReturnValue(null);
});
afterEach(() => {
vi.clearAllMocks();
});
it("should return all calendar links", async () => {
const result = getCalendarLinks({ booking: baseMockBooking, eventType: baseMockEventType, t: mockT });
const googleLink = result.find((link) => link.id === CalendarLinkType.GOOGLE_CALENDAR);
const microsoftOfficeLink = result.find((link) => link.id === CalendarLinkType.MICROSOFT_OFFICE);
const microsoftOutlookLink = result.find((link) => link.id === CalendarLinkType.MICROSOFT_OUTLOOK);
const icsLink = result.find((link) => link.id === CalendarLinkType.ICS);
expect(result).toHaveLength(4);
expect(googleLink).toBeDefined();
expect(microsoftOfficeLink).toBeDefined();
expect(microsoftOutlookLink).toBeDefined();
expect(icsLink).toBeDefined();
(function verifyGoogleLink() {
expect(googleLink?.link).toContain("https://calendar.google.com/calendar/r/eventedit");
expect(googleLink?.link).toContain("dates=");
expect(googleLink?.link).toContain(
`${mockDayjsStartTime.utc().format("YYYYMMDDTHHmmss[Z]")}/${mockDayjsEndTime
.utc()
.format("YYYYMMDDTHHmmss[Z]")}`
);
expect(googleLink?.link).toContain(`details=${encodeURIComponent(baseMockEventType.description)}`);
})();
(function verifyMicrosoftOfficeLink() {
expect(microsoftOfficeLink?.link).toContain("https://outlook.office.com/calendar/0/deeplink/compose");
expect(microsoftOfficeLink?.link).toContain("enddt=");
expect(microsoftOfficeLink?.link).toContain("startdt=");
expect(microsoftOfficeLink?.link).toContain("body=Test%20Description");
})();
(function verifymicrosoftOutlookLink() {
expect(microsoftOutlookLink?.link).toContain("https://outlook.live.com/calendar/0/deeplink/compose");
expect(microsoftOutlookLink?.link).toContain("enddt=");
expect(microsoftOutlookLink?.link).toContain("startdt=");
expect(microsoftOutlookLink?.link).toContain("body=Test%20Description");
})();
(function verifyIcsLink() {
expect(icsLink).toBeDefined();
expect(icsLink?.link).toContain("data:text/calendar");
expect(icsLink?.link).toContain(encodeURIComponent(mockIcsValue));
expect(createEvent).toHaveBeenCalled();
expect(createEvent).toHaveBeenCalledWith(
expect.objectContaining({
description: baseMockEventType.description,
})
);
})();
});
it("should use videoCallUrl from metadata when available", async () => {
const videoCallUrl = "https://zoom.com/test";
const booking = {
...baseMockBooking,
metadata: { videoCallUrl },
};
const result = getCalendarLinks({ booking, eventType: baseMockEventType, t: mockT });
// Check that all links contain the videoCallUrl
const googleLink = result.find((link) => link.id === CalendarLinkType.GOOGLE_CALENDAR);
const microsoftOfficeLink = result.find((link) => link.id === CalendarLinkType.MICROSOFT_OFFICE);
const microsoftOutlookLink = result.find((link) => link.id === CalendarLinkType.MICROSOFT_OUTLOOK);
expect(googleLink?.link).toContain(`location=${encodeURIComponent(videoCallUrl)}`);
expect(microsoftOfficeLink?.link).toContain(`location=${encodeURIComponent(videoCallUrl)}`);
expect(microsoftOutlookLink?.link).toContain(`location=${encodeURIComponent(videoCallUrl)}`);
});
it("should handle custom title from dynamic event", async () => {
const customTitle = "Custom Dynamic Title";
const booking = {
...baseMockBooking,
responses: { title: customTitle, name: "Test Attendee" },
};
const eventType = {
...baseMockEventType,
isDynamic: true, // This makes it use the custom title
};
const result = getCalendarLinks({ booking, eventType, t: mockT });
const googleLink = result.find((link) => link.id === CalendarLinkType.GOOGLE_CALENDAR);
expect(googleLink?.link).toContain(`details=${encodeURIComponent(eventType.description)}`);
expect(googleLink?.link).toContain(`text=${customTitle}`);
// Check Office 365 link
const microsoftOfficeLink = result.find((link) => link.id === CalendarLinkType.MICROSOFT_OFFICE);
expect(microsoftOfficeLink?.link).toContain("body=Test%20Description");
expect(microsoftOfficeLink?.link).toContain(`subject=${customTitle}`);
// Check Outlook link
const microsoftOutlookLink = result.find((link) => link.id === CalendarLinkType.MICROSOFT_OUTLOOK);
expect(microsoftOutlookLink?.link).toContain("body=Test%20Description");
expect(microsoftOutlookLink?.link).toContain(`subject=${encodeURIComponent(customTitle)}`);
});
it("should handle recurring events - Only Google Calendar supports at the moment", async () => {
// Mock a recurring event rule
const mockRecurringRule = {
freq: 2, // WEEKLY
interval: 1,
count: 5,
};
(parseRecurringEvent as jest.Mock).mockReturnValue(mockRecurringRule);
const eventType = {
...baseMockEventType,
recurringEvent: { count: 5, freq: 2, interval: 1 },
};
const mockRRuleString = "FREQ=WEEKLY;INTERVAL=1;COUNT=5";
vi.spyOn(RRule.prototype, "toString").mockReturnValue(mockRRuleString);
const result = getCalendarLinks({ booking: baseMockBooking, eventType, t: mockT });
const googleLink = result.find((link) => link.id === "googleCalendar");
expect(googleLink).toBeDefined();
expect(googleLink?.link).toContain(`recur=${encodeURIComponent(mockRRuleString)}`);
});
it("should handle error in ICS generation", async () => {
// Mock createEvent to return an error
(createEvent as jest.Mock).mockReturnValue({ error: new Error("ICS generation failed") });
// Mock console.error to avoid test output noise
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined);
const result = getCalendarLinks({ booking: baseMockBooking, eventType: baseMockEventType, t: mockT });
const icsLink = result.find((link) => link.id === "ics");
expect(icsLink).toBeDefined();
expect(icsLink?.link).toBe("");
expect(consoleErrorSpy).toHaveBeenCalled();
// Verify createEvent was called with the correct description
expect(createEvent).toHaveBeenCalledWith(
expect.objectContaining({
description: baseMockEventType.description,
})
);
consoleErrorSpy.mockRestore();
});
});
@@ -0,0 +1,254 @@
import type { Prisma } from "@prisma/client";
import type { TFunction } from "i18next";
import { createEvent } from "ics";
import { RRule } from "rrule";
import type { z } from "zod";
import type { Dayjs } from "@calcom/dayjs";
import dayjs from "@calcom/dayjs";
import type { nameObjectSchema } from "@calcom/features/eventtypes/lib/eventNaming";
import { getEventName } from "@calcom/features/eventtypes/lib/eventNaming";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
import type { RecurringEvent } from "@calcom/types/Calendar";
type RecurringEventOrPrismaJsonObject = RecurringEvent | Prisma.JsonObject | null | undefined;
export const enum CalendarLinkType {
GOOGLE_CALENDAR = "googleCalendar",
MICROSOFT_OFFICE = "microsoftOffice",
MICROSOFT_OUTLOOK = "microsoftOutlook",
ICS = "ics",
}
const buildICalLink = ({
startTime,
endTime,
title,
description,
location,
}: {
startTime: Dayjs;
endTime: Dayjs;
title: string;
description: string | null;
location: string | null;
}) => {
const durationInMinutes = endTime.diff(startTime, "minutes");
const iCalEvent = createEvent({
start: [
startTime.toDate().getUTCFullYear(),
(startTime.toDate().getUTCMonth() as number) + 1,
startTime.toDate().getUTCDate(),
startTime.toDate().getUTCHours(),
startTime.toDate().getUTCMinutes(),
],
startInputType: "utc",
title,
duration: {
minutes: durationInMinutes,
},
...(description ? { description } : {}),
...(location ? { location } : {}),
});
if (iCalEvent.error) {
throw iCalEvent.error;
}
return `data:text/calendar,${encodeURIComponent(iCalEvent.value ? iCalEvent.value : false)}`;
};
const buildGoogleCalendarLink = ({
startTime,
endTime,
eventName,
eventDescription,
bookingLocation,
recurringEvent,
}: {
startTime: Dayjs;
endTime: Dayjs;
eventName: string;
eventDescription: string | null;
bookingLocation: string | null;
recurringEvent: RecurringEventOrPrismaJsonObject;
}) => {
const startTimeInUtcFormat = startTime.utc().format("YYYYMMDDTHHmmss[Z]");
const endTimeInUtcFormat = endTime.utc().format("YYYYMMDDTHHmmss[Z]");
const recurrence = recurringEvent ? encodeURIComponent(new RRule(recurringEvent).toString()) : "";
const location = bookingLocation ? encodeURIComponent(bookingLocation) : "";
const description = encodeURIComponent(eventDescription ?? "");
const googleCalendarLink = `https://calendar.google.com/calendar/r/eventedit?dates=${startTimeInUtcFormat}/${endTimeInUtcFormat}&text=${eventName}&details=${description}${
location ? `&location=${location}` : ""
}${recurrence ? `&recur=${recurrence}` : ""}`;
return googleCalendarLink;
};
const buildMicrosoftOfficeLink = ({
startTime,
endTime,
eventName,
eventDescription,
bookingLocation,
}: {
startTime: Dayjs;
endTime: Dayjs;
eventName: string;
eventDescription: string | null;
bookingLocation: string | null;
}) => {
const startTimeInUtcFormat = startTime.utc().format();
const endTimeInUtcFormat = endTime.utc().format();
const location = bookingLocation ? encodeURIComponent(bookingLocation) : "";
const description = encodeURIComponent(eventDescription ?? "");
// TODO: Why do we need to encode URI this href but not the google calendar link?
const microsoftOfficeLink = `https://outlook.office.com/calendar/0/deeplink/compose?body=${description}&enddt=${endTimeInUtcFormat}&path=%2Fcalendar%2Faction%2Fcompose&rru=addevent&startdt=${startTimeInUtcFormat}&subject=${eventName}${
location ? `&location=${location}` : ""
}`;
return microsoftOfficeLink;
};
const buildMicrosoftOutlookLink = ({
startTime,
endTime,
eventName,
eventDescription,
bookingLocation,
}: {
startTime: Dayjs;
endTime: Dayjs;
eventName: string;
eventDescription: string | null;
bookingLocation: string | null;
}) => {
const startTimeInUtcFormat = startTime.utc().format();
const endTimeInUtcFormat = endTime.utc().format();
const location = bookingLocation ? encodeURIComponent(bookingLocation) : "";
const microsoftOutlookLink =
encodeURI(
`https://outlook.live.com/calendar/0/deeplink/compose?body=${eventDescription}&enddt=${endTimeInUtcFormat}&path=%2Fcalendar%2Faction%2Fcompose&rru=addevent&startdt=${startTimeInUtcFormat}&subject=${eventName}`
) + (location ? `&location=${location}` : "");
return microsoftOutlookLink;
};
export const getCalendarLinks = ({
booking,
eventType,
t,
}: {
booking: {
startTime: Date;
endTime: Date;
location: string | null;
title: string;
responses: Prisma.JsonObject;
metadata: Prisma.JsonObject | null;
};
eventType: {
recurringEvent: RecurringEventOrPrismaJsonObject;
description?: string | null;
eventName?: string | null;
isDynamic: boolean;
length: number;
team?: {
name: string;
} | null;
users: {
name: string | null;
}[];
title: string;
};
t: TFunction;
}) => {
let evtName = eventType.eventName;
const videoCallUrl = bookingMetadataSchema.parse(booking?.metadata || {})?.videoCallUrl ?? null;
if (eventType.isDynamic && booking.responses.title) {
evtName = booking.responses.title as string;
}
const eventNameObject = {
attendeeName: booking.responses.name as z.infer<typeof nameObjectSchema> | string,
eventType: eventType.title,
eventName: evtName,
host: eventType.team?.name || eventType.users[0]?.name || "Nameless",
location: booking.location,
bookingFields: booking.responses,
eventDuration: dayjs(booking.endTime).diff(booking.startTime, "minutes"),
t,
};
// Create event name and description
const eventName = getEventName(eventNameObject, true);
const eventDescription = eventType.description || "";
// Calculate start and end times
const startTime = dayjs(booking.startTime);
const endTime = dayjs(booking.endTime);
const recurringEvent = eventType.recurringEvent;
const googleCalendarLink = buildGoogleCalendarLink({
startTime,
endTime,
eventName,
eventDescription,
bookingLocation: videoCallUrl ?? null,
recurringEvent,
});
const microsoftOfficeLink = buildMicrosoftOfficeLink({
startTime,
endTime,
eventName,
eventDescription,
bookingLocation: videoCallUrl,
});
const microsoftOutlookLink = buildMicrosoftOutlookLink({
startTime,
endTime,
eventName,
eventDescription,
bookingLocation: videoCallUrl,
});
// Generate ICS file link
let icsFileLink = "";
try {
icsFileLink = buildICalLink({
startTime,
endTime,
title: eventName,
description: eventDescription ?? null,
location: videoCallUrl ?? null,
});
} catch (error) {
console.error("Error generating ICS file", error);
}
return [
{
label: "Google Calendar",
id: CalendarLinkType.GOOGLE_CALENDAR,
link: googleCalendarLink,
},
{
label: "Microsoft Office",
id: CalendarLinkType.MICROSOFT_OFFICE,
link: microsoftOfficeLink,
},
{
label: "Microsoft Outlook",
id: CalendarLinkType.MICROSOFT_OUTLOOK,
link: microsoftOutlookLink,
},
{
label: "ICS",
id: CalendarLinkType.ICS,
link: icsFileLink,
},
];
};
@@ -23,6 +23,7 @@ import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhoo
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
import type { CacheService } from "@calcom/features/calendar-cache/lib/getShouldServeCache";
import AssignmentReasonRecorder from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
import { getEventName, updateHostInEventName } from "@calcom/features/eventtypes/lib/eventNaming";
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { getFullName } from "@calcom/features/form-builder/utils";
import { UsersRepository } from "@calcom/features/users/users.repository";
@@ -49,7 +50,6 @@ import { getCacheService } from "@calcom/lib/di/containers/Cache";
import { getLuckyUserService } from "@calcom/lib/di/containers/LuckyUser";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { getErrorFromUnknown } from "@calcom/lib/errors";
import { getEventName, updateHostInEventName } from "@calcom/lib/event";
import { extractBaseEmail } from "@calcom/lib/extract-base-email";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
@@ -0,0 +1,558 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { BookingLocationService } from "./bookingLocationService";
vi.mock("@calcom/app-store/utils", () => ({
getAppFromSlug: vi.fn(),
}));
vi.mock("@calcom/app-store/locations", async () => {
const actual = await vi.importActual("@calcom/app-store/locations");
return {
...actual,
OrganizerDefaultConferencingAppType: "conferencing",
CalVideoLocationType: "integrations:daily-video",
};
});
const { getAppFromSlug } = await import("@calcom/app-store/utils");
describe("BookingLocationService", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("getOrganizerDefaultConferencingAppLocation", () => {
describe("Dynamic conferencing apps", () => {
it("should return the app location type for a dynamic app like Google Meet", () => {
const mockMetadata = {
defaultConferencingApp: {
appSlug: "google-meet",
},
};
vi.mocked(getAppFromSlug).mockReturnValue({
appData: {
location: {
type: "integrations:google:meet",
},
},
} as any);
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: mockMetadata,
});
expect(result).toEqual({
conferencingAppLocationType: "integrations:google:meet",
isStaticLinkApp: false,
});
expect(getAppFromSlug).toHaveBeenCalledWith("google-meet");
});
it("should return the app location type for Zoom", () => {
const mockMetadata = {
defaultConferencingApp: {
appSlug: "zoom",
},
};
vi.mocked(getAppFromSlug).mockReturnValue({
appData: {
location: {
type: "integrations:zoom",
},
},
} as any);
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: mockMetadata,
});
expect(result).toEqual({
conferencingAppLocationType: "integrations:zoom",
isStaticLinkApp: false,
});
});
it("should return null when app is not found", () => {
const mockMetadata = {
defaultConferencingApp: {
appSlug: "unknown-app",
},
};
vi.mocked(getAppFromSlug).mockReturnValue(null);
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: mockMetadata,
});
expect(result).toBeNull();
});
});
describe("Static link apps", () => {
it("should return static link for apps with appLink", () => {
const mockMetadata = {
defaultConferencingApp: {
appSlug: "custom-video",
appLink: "https://custom-video.com/room123",
},
};
vi.mocked(getAppFromSlug).mockReturnValue({
appData: {
location: {
type: "integrations:custom-video",
},
},
} as any);
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: mockMetadata,
});
expect(result).toEqual({
conferencingAppLocationType: "integrations:custom-video",
isStaticLinkApp: true,
staticLink: "https://custom-video.com/room123",
});
});
});
describe("Fallback scenarios", () => {
it("should return null when no conferencing app is set", () => {
const mockMetadata = {};
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: mockMetadata,
});
expect(result).toBeNull();
expect(getAppFromSlug).not.toHaveBeenCalled();
});
it("should handle null metadata gracefully", () => {
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: null,
});
expect(result).toBeNull();
});
it("should handle undefined metadata gracefully", () => {
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: undefined,
});
expect(result).toBeNull();
});
});
describe("Invalid metadata parsing", () => {
it("should handle invalid metadata structure", () => {
const invalidMetadata = {
defaultConferencingApp: "not-an-object",
};
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: invalidMetadata,
});
expect(result).toBeNull();
});
it("should handle metadata with missing appSlug", () => {
const mockMetadata = {
defaultConferencingApp: {
appLink: "https://some-link.com",
},
};
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: mockMetadata,
});
expect(result).toBeNull();
});
});
describe("Edge cases", () => {
it("should handle app with no appData", () => {
const mockMetadata = {
defaultConferencingApp: {
appSlug: "app-without-data",
},
};
vi.mocked(getAppFromSlug).mockReturnValue({} as any);
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: mockMetadata,
});
expect(result).toBeNull();
});
it("should handle app with no location type", () => {
const mockMetadata = {
defaultConferencingApp: {
appSlug: "app-without-location-type",
},
};
vi.mocked(getAppFromSlug).mockReturnValue({
appData: {
location: {},
},
} as any);
const result = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: mockMetadata,
});
expect(result).toBeNull();
});
});
});
describe("getLocationForHost", () => {
it("should use organizer default when allowed and available", () => {
const mockHostMetadata = {
defaultConferencingApp: {
appSlug: "zoom",
},
};
vi.mocked(getAppFromSlug).mockReturnValue({
appData: {
location: {
type: "integrations:zoom",
},
},
} as any);
const result = BookingLocationService.getLocationForHost({
hostMetadata: mockHostMetadata,
eventTypeLocations: [{ type: "conferencing" }],
isTeamEventType: true,
});
expect(result).toEqual({
bookingLocation: "integrations:zoom",
requiresActualLink: true,
conferenceCredentialId: null,
});
});
it("should use static link when organizer default is a static link app", () => {
const mockHostMetadata = {
defaultConferencingApp: {
appSlug: "custom-video",
appLink: "https://custom-video.com/room123",
},
};
vi.mocked(getAppFromSlug).mockReturnValue({
appData: {
location: {
type: "integrations:custom-video",
},
},
} as any);
const result = BookingLocationService.getLocationForHost({
hostMetadata: mockHostMetadata,
eventTypeLocations: [{ type: "conferencing" }],
isTeamEventType: true,
});
expect(result).toEqual({
bookingLocation: "https://custom-video.com/room123",
requiresActualLink: false,
});
});
it("should fallback to first real location when organizer default not available", () => {
const mockHostMetadata = {};
const result = BookingLocationService.getLocationForHost({
hostMetadata: mockHostMetadata,
eventTypeLocations: [{ type: "conferencing" }, { type: "integrations:google:meet" }],
isTeamEventType: true,
});
expect(result).toEqual({
bookingLocation: "integrations:google:meet",
requiresActualLink: true,
conferenceCredentialId: null,
});
});
it("should default to Cal Video when no locations configured", () => {
const mockHostMetadata = {};
const result = BookingLocationService.getLocationForHost({
hostMetadata: mockHostMetadata,
eventTypeLocations: [{ type: "conferencing" }],
isTeamEventType: true,
});
expect(result).toEqual({
bookingLocation: "integrations:daily-video",
requiresActualLink: true,
conferenceCredentialId: null,
});
});
it("should not use organizer default for non-team and non-managed events", () => {
const mockHostMetadata = {
defaultConferencingApp: {
appSlug: "zoom",
},
};
vi.mocked(getAppFromSlug).mockReturnValue({
appData: {
location: {
type: "integrations:zoom",
},
},
} as any);
const result = BookingLocationService.getLocationForHost({
hostMetadata: mockHostMetadata,
eventTypeLocations: [{ type: "conferencing" }, { type: "integrations:google:meet" }],
isTeamEventType: false,
isManagedEventType: false,
});
expect(result).toEqual({
bookingLocation: "integrations:google:meet",
requiresActualLink: true,
conferenceCredentialId: null,
});
});
});
describe("getLocationDetailsFromType", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("Dynamic location types", () => {
it("should return location type with credential ID when present", () => {
const locationType = "integrations:zoom";
const eventTypeLocations = [
{ type: "integrations:zoom", credentialId: 123 },
{ type: "integrations:google:meet" },
];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "integrations:zoom",
conferenceCredentialId: 123,
});
});
it("should return location type without credential ID when not present", () => {
const locationType = "integrations:google:meet";
const eventTypeLocations = [{ type: "integrations:google:meet" }, { type: "integrations:zoom" }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "integrations:google:meet",
conferenceCredentialId: null,
});
});
it("should handle Cal Video location type", () => {
const locationType = "integrations:daily-video";
const eventTypeLocations = [{ type: "integrations:daily-video" }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "integrations:daily-video",
conferenceCredentialId: null,
});
});
});
describe("Static link values", () => {
it("should return static URL as-is without credential ID", () => {
const locationType = "https://zoom.us/j/123456789";
const eventTypeLocations = [{ type: "integrations:zoom", link: "https://zoom.us/j/123456789" }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "https://zoom.us/j/123456789",
conferenceCredentialId: null,
});
});
it("should handle custom static links", () => {
const locationType = "https://custom-video.com/room123";
const eventTypeLocations = [
{ type: "integrations:custom", link: "https://custom-video.com/room123" },
];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "https://custom-video.com/room123",
conferenceCredentialId: null,
});
});
});
describe("Edge cases", () => {
it("should handle empty event type locations", () => {
const locationType = "integrations:zoom";
const eventTypeLocations: any[] = [];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "integrations:zoom",
conferenceCredentialId: null,
});
});
it("should handle location type not in event type locations", () => {
const locationType = "integrations:teams";
const eventTypeLocations = [{ type: "integrations:zoom" }, { type: "integrations:google:meet" }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "integrations:teams",
conferenceCredentialId: null,
});
});
it("should handle multiple locations with same type but different credential IDs", () => {
const locationType = "integrations:zoom";
const eventTypeLocations = [
{ type: "integrations:zoom", credentialId: 123 },
{ type: "integrations:zoom", credentialId: 456 },
];
// getLocationValueForDB would pick the last matching one due to forEach
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "integrations:zoom",
conferenceCredentialId: 456,
});
});
it("should handle location with 0 as credential ID", () => {
const locationType = "integrations:zoom";
const eventTypeLocations = [{ type: "integrations:zoom", credentialId: 0 }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "integrations:zoom",
conferenceCredentialId: 0,
});
});
});
describe("Special location types", () => {
it("should handle phone location type", () => {
const locationType = "phone";
const eventTypeLocations = [{ type: "phone" }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "phone",
conferenceCredentialId: null,
});
});
it("should handle in-person location type", () => {
const locationType = "inPerson";
const eventTypeLocations = [{ type: "inPerson", address: "123 Main St" }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "123 Main St", // getLocationValueForDB returns the address for inPerson
conferenceCredentialId: null,
});
});
it("should handle attendee in-person location", () => {
const locationType = "attendeeInPerson";
const eventTypeLocations = [{ type: "attendeeInPerson" }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "attendeeInPerson",
conferenceCredentialId: null,
});
});
});
describe("Conferencing app location", () => {
it("should handle conferencing location type (organizer default)", () => {
const locationType = "conferencing";
const eventTypeLocations = [{ type: "conferencing" }];
const result = BookingLocationService.getLocationDetailsFromType({
locationType,
eventTypeLocations,
});
expect(result).toEqual({
bookingLocation: "conferencing",
conferenceCredentialId: null,
});
});
});
});
});
@@ -0,0 +1,247 @@
import { getLocationValueForDB, OrganizerDefaultConferencingAppType } from "@calcom/app-store/locations";
import { CalVideoLocationType, type LocationObject } from "@calcom/app-store/locations";
import { getAppFromSlug } from "@calcom/app-store/utils";
import { userMetadata as userMetadataSchema } from "@calcom/prisma/zod-utils";
type GetOrganizerDefaultConferencingAppLocationParams = {
organizerMetadata: unknown;
};
type GetOrganizerDefaultConferencingAppLocationResult = {
/**
* The conferencing app location type.
* It starts with 'integrations:' e.g. 'integrations:zoom' and it is defined in the app's config/metadata.ts file
*/
conferencingAppLocationType: string;
} & (
| {
isStaticLinkApp: true;
staticLink: string;
}
| {
isStaticLinkApp: false;
}
);
type GetLocationForHostParams = {
/**
* The new host's metadata containing their default conferencing app preferences
*/
hostMetadata: unknown;
/**
* The event type's configured locations
*/
eventTypeLocations: LocationObject[];
/**
* Whether this is a managed event type
*/
isManagedEventType?: boolean;
/**
* Whether this is a team event type
*/
isTeamEventType?: boolean;
};
type GetLocationForHostResult = {
/**
* The location string to be stored in the booking
*/
bookingLocation: string;
} & (
| {
requiresActualLink: false;
}
| {
requiresActualLink: true;
// Credential ID for generating the conferencing link. Set when:
// 1. The app supports team installation (concurrentMeetings: true)
// 2. The app is installed at team level (credential has teamId)
// 3. The event type is a team event that can use team credentials
conferenceCredentialId: number | null;
}
);
type GetLocationDetailsFromTypeParams = {
/**
* The location type or value to resolve
* @example "integrations:zoom" - A dynamic location type
* @example "https://example.com/meeting" - A static link value
* @example "integrations:daily" - Cal Video location type
*/
locationType: string;
/**
* The event type's configured locations that may contain credential IDs
*/
eventTypeLocations: LocationObject[];
};
type GetLocationDetailsFromTypeResult = {
/**
* The resolved location value for the database
*/
bookingLocation: string;
/**
* The conference credential ID if present in the location configuration
*/
conferenceCredentialId: number | null;
};
export class BookingLocationService {
/**
* Determines the booking location based on the Organizer's Default Conferencing App.
*
* Note that Organizer's Default Conferencing App is applicable only to Team Events. It gets also applicable to Children Managed Event Types(which are technically User Event Types) as well because the location is configured at Parent Managed Event Type(which is a Team Event Type)
*
* This function handles two types of conferencing apps:
* 1. Dynamic link apps (e.g., Google Meet, Zoom) - Generate a new link for each booking
* - These apps only have `appSlug` in organizerMetadata
* - The location is determined by the app's metadata (e.g., "integrations:google:meet")
*
* 2. Static link apps (e.g., Campfire)
* - These apps have `appLink`, as well as `appSlug` in organizerMetadata
* - The `appLink` is only used for managed or team event types
*
* @returns The location configuration or null if no valid conferencing app is found.
* Callers should handle the null case with their own fallback logic.
*/
static getOrganizerDefaultConferencingAppLocation({
organizerMetadata,
}: GetOrganizerDefaultConferencingAppLocationParams): GetOrganizerDefaultConferencingAppLocationResult | null {
// Parse the user metadata to extract conferencing app settings
const metadataParseResult = userMetadataSchema.safeParse(organizerMetadata);
const parsedMetadata = metadataParseResult.success ? metadataParseResult.data : undefined;
if (!parsedMetadata?.defaultConferencingApp?.appSlug) {
return null;
}
// Retrieve the app configuration from the app store
const app = getAppFromSlug(parsedMetadata.defaultConferencingApp.appSlug);
// Extract the location type from the app's metadata (e.g., "integrations:zoom")
const conferencingAppLocationType = app?.appData?.location?.type || null;
// If the app doesn't have a valid location type, return null
if (!conferencingAppLocationType) {
return null;
}
if (parsedMetadata.defaultConferencingApp.appLink) {
return {
conferencingAppLocationType,
isStaticLinkApp: true,
staticLink: parsedMetadata.defaultConferencingApp.appLink,
};
}
return {
conferencingAppLocationType,
isStaticLinkApp: false,
};
}
/**
* Determines the appropriate booking location based on the chosen host
*
* Logic:
* 1. If the event type includes OrganizerDefaultConferencingAppType in its locations,
* and the new host has a default conferencing app configured, use that.
* 2. Otherwise, use the first available location from the event type's configured locations.
*
*
* @returns The location configuration for the new host
*/
static getLocationForHost({
hostMetadata,
eventTypeLocations,
isManagedEventType = false,
isTeamEventType = false,
}: GetLocationForHostParams): GetLocationForHostResult {
// Check if the event type allows using the organizer's default conferencing app
const eventAllowsOrganizerDefault = eventTypeLocations.some(
(location) => location.type === OrganizerDefaultConferencingAppType
);
const isOrganizerDefaultAllowed = isTeamEventType || isManagedEventType;
if (eventAllowsOrganizerDefault && isOrganizerDefaultAllowed) {
const organizerDefaultLocation = BookingLocationService.getOrganizerDefaultConferencingAppLocation({
organizerMetadata: hostMetadata,
});
if (organizerDefaultLocation) {
if (organizerDefaultLocation.isStaticLinkApp) {
return {
requiresActualLink: false,
bookingLocation: organizerDefaultLocation.staticLink,
};
}
return {
requiresActualLink: true,
conferenceCredentialId: null,
bookingLocation: organizerDefaultLocation.conferencingAppLocationType,
};
}
}
// Fallback: Find the first real location (not OrganizerDefaultConferencingAppType)
const firstRealLocation = eventTypeLocations.find(
(location) => location.type !== OrganizerDefaultConferencingAppType
);
if (!firstRealLocation) {
// If no real locations are configured, default to Cal Video
return {
bookingLocation: CalVideoLocationType,
requiresActualLink: true,
conferenceCredentialId: null,
};
}
// Process the first real location through getLocationValueForDB to handle static links properly
const { bookingLocation, conferenceCredentialId } = BookingLocationService.getLocationDetailsFromType({
locationType: firstRealLocation.type,
eventTypeLocations,
});
return {
bookingLocation,
requiresActualLink: true,
conferenceCredentialId,
};
}
/**
* Extracts location details including conferenceCredentialId from a location type or value
*
* @param params - The location type/value and event type locations
* @returns The resolved booking location and conference credential ID if present
*
* @example
* // Dynamic location type with credential ID
* getLocationDetailsFromType({
* locationType: "integrations:zoom",
* eventTypeLocations: [{ type: "integrations:zoom", credentialId: 123 }]
* })
* // Returns: { bookingLocation: "integrations:zoom", conferenceCredentialId: 123 }
*
* @example
* // Static link value (already resolved)
* getLocationDetailsFromType({
* locationType: "https://zoom.us/j/123456789",
* eventTypeLocations: [{ type: "integrations:zoom", link: "https://zoom.us/j/123456789" }]
* })
* // Returns: { bookingLocation: "https://zoom.us/j/123456789", conferenceCredentialId: null }
*/
static getLocationDetailsFromType({
locationType,
eventTypeLocations,
}: GetLocationDetailsFromTypeParams): GetLocationDetailsFromTypeResult {
const { bookingLocation, conferenceCredentialId } = getLocationValueForDB(
locationType,
eventTypeLocations
);
return { bookingLocation, conferenceCredentialId: conferenceCredentialId ?? null };
}
}
@@ -13,21 +13,21 @@ import { getEventTypesFromDB } from "@calcom/features/bookings/lib/handleNewBook
import AssignmentReasonRecorder, {
RRReassignmentType,
} from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
import { BookingLocationService } from "@calcom/features/ee/round-robin/lib/bookingLocationService";
import {
scheduleEmailReminder,
deleteScheduledEmailReminder,
} from "@calcom/features/ee/workflows/lib/reminders/emailReminderManager";
import { scheduleWorkflowReminders } from "@calcom/features/ee/workflows/lib/reminders/reminderScheduler";
import { getEventName } from "@calcom/features/eventtypes/lib/eventNaming";
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
import { SENDER_NAME } from "@calcom/lib/constants";
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/lib/delegationCredential/server";
import { getEventName } from "@calcom/lib/event";
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
import { IdempotencyKeyService } from "@calcom/lib/idempotencyKey/idempotencyKeyService";
import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";
import logger from "@calcom/lib/logger";
import { getTranslation } from "@calcom/lib/server/i18n";
import { BookingLocationService } from "@calcom/lib/server/service/bookingLocationService";
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
import { prisma } from "@calcom/prisma";
import { WorkflowActions, WorkflowMethods, WorkflowTriggerEvents } from "@calcom/prisma/enums";
@@ -16,13 +16,13 @@ import type { IsFixedAwareUser } from "@calcom/features/bookings/lib/handleNewBo
import AssignmentReasonRecorder, {
RRReassignmentType,
} from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
import { getEventName } from "@calcom/features/eventtypes/lib/eventNaming";
import {
enrichHostsWithDelegationCredentials,
enrichUserWithDelegationCredentialsIncludeServiceAccountKey,
} from "@calcom/lib/delegationCredential/server";
import { getLuckyUserService } from "@calcom/lib/di/containers/LuckyUser";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { getEventName } from "@calcom/lib/event";
import { IdempotencyKeyService } from "@calcom/lib/idempotencyKey/idempotencyKeyService";
import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";
import logger from "@calcom/lib/logger";
@@ -4,9 +4,9 @@ import { FormProvider } from "react-hook-form";
import { useForm, useFormContext } from "react-hook-form";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import type { EventNameObjectType } from "@calcom/features/eventtypes/lib/eventNaming";
import { getEventName, validateCustomEventName } from "@calcom/features/eventtypes/lib/eventNaming";
import type { InputClassNames } from "@calcom/features/eventtypes/lib/types";
import type { EventNameObjectType } from "@calcom/lib/event";
import { getEventName, validateCustomEventName } from "@calcom/lib/event";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
@@ -20,6 +20,8 @@ import {
allowDisablingHostConfirmationEmails,
} from "@calcom/features/ee/workflows/lib/allowDisablingStandardEmails";
import { MultiplePrivateLinksController } from "@calcom/features/eventtypes/components";
import type { EventNameObjectType } from "@calcom/features/eventtypes/lib/eventNaming";
import { getEventName } from "@calcom/features/eventtypes/lib/eventNaming";
import type {
FormValues,
EventTypeSetupProps,
@@ -38,8 +40,6 @@ import {
APP_NAME,
MAX_SEATS_PER_TIME_SLOT,
} from "@calcom/lib/constants";
import type { EventNameObjectType } from "@calcom/lib/event";
import { getEventName } from "@calcom/lib/event";
import { generateHashedLink } from "@calcom/lib/generateHashedLink";
import { checkWCAGContrastColor } from "@calcom/lib/getBrandColours";
import { extractHostTimezone } from "@calcom/lib/hashedLinksUtils";
@@ -0,0 +1,551 @@
import type { TFunction } from "i18next";
import { describe, expect, it, vi } from "vitest";
import * as event from "./eventNaming";
import { updateHostInEventName } from "./eventNaming";
describe("event tests", () => {
describe("fn: getEventName", () => {
it("should return event_between_users message if no name", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("foo");
const lastCall = tFunc.mock.lastCall;
expect(lastCall).toEqual([
"event_between_users",
{
eventName: "example event type",
host: "example host",
attendeeName: "example attendee",
interpolation: {
escapeValue: false,
},
},
]);
});
it("should return event_between_users message if no name with team set", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
teamName: "example team name",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("foo");
const lastCall = tFunc.mock.lastCall;
expect(lastCall).toEqual([
"event_between_users",
{
eventName: "example event type",
host: "example team name",
attendeeName: "example attendee",
interpolation: {
escapeValue: false,
},
},
]);
});
it("should return event name if no vars used", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "example event name",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("example event name");
});
it("should support templating of event type", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "event type: {Event type title}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("event type: example event type");
});
it("should support templating of scheduler", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "scheduler: {Scheduler}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("scheduler: example attendee");
});
it("should support templating of organiser", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "organiser: {Organiser}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("organiser: example host");
});
it("should support templating of user", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "user: {USER}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("user: example attendee");
});
it("should support templating of attendee", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "attendee: {ATTENDEE}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("attendee: example attendee");
});
it("should support templating of host", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "host: {HOST}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("host: example host");
});
it("should support templating of attendee with host/attendee", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "host or attendee: {HOST/ATTENDEE}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("host or attendee: example attendee");
});
it("should support templating of host with host/attendee", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName(
{
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "host or attendee: {HOST/ATTENDEE}",
eventDuration: 15,
t: tFunc as TFunction,
},
true
);
expect(result).toBe("host or attendee: example host");
});
it("should support templating of custom booking fields", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "custom field: {customField}",
bookingFields: {
customField: "example custom field",
},
t: tFunc as TFunction,
});
expect(result).toBe("custom field: example custom field");
});
it("should support templating of custom booking fields with values", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "custom field: {customField}",
eventDuration: 15,
bookingFields: {
customField: {
value: "example custom field",
},
},
t: tFunc as TFunction,
});
expect(result).toBe("custom field: example custom field");
});
it("should support templating of custom booking fields with non-string values", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "custom field: {customField}",
eventDuration: 15,
bookingFields: {
customField: {
value: 808,
},
},
t: tFunc as TFunction,
});
expect(result).toBe("custom field: 808");
});
it("should support templating of custom booking fields with no value", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "custom field: {customField}",
eventDuration: 15,
bookingFields: {
customField: {
value: undefined,
},
},
t: tFunc as TFunction,
});
expect(result).toBe("custom field: ");
});
it("should support templating of location via {Location}", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
location: "attendeeInPerson",
eventName: "location: {Location}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("location: in_person_attendee_address");
});
it("should support templating of location via {LOCATION}", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
location: "attendeeInPerson",
eventName: "location: {LOCATION}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("location: in_person_attendee_address");
});
it("should strip location template if none set", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "location: {Location}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("location: ");
});
it("should strip location template if empty", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
location: "",
eventName: "location: {Location}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("location: ");
});
it("should template {Location} as passed location if unknown type", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
location: "unknownNonsense",
eventName: "location: {Location}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("location: unknownNonsense");
});
});
it("should support templating of event duration", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
eventName: "event duration: {Event duration}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("event duration: 15 mins");
});
it("should support templating of Scheduler first name", () => {
const tFunc = vi.fn(() => "foo");
const result = event.getEventName({
attendeeName: "example attendee",
eventType: "example event type",
host: "example host",
location: "attendeeInPerson",
eventName: "Scheduler first name: {Scheduler first name}",
eventDuration: 15,
t: tFunc as TFunction,
});
expect(result).toBe("Scheduler first name: example");
});
describe("fn: validateCustomEventName", () => {
it("should be valid when no variables used", () => {
expect(event.validateCustomEventName("foo")).toBe(true);
});
[
"Event type title",
"Organiser",
"Scheduler",
"Location",
"LOCATION",
"HOST/ATTENDEE",
"HOST",
"ATTENDEE",
"USER",
"Event duration",
].forEach((value) => {
it(`should support {${value}} variable`, () => {
expect(event.validateCustomEventName(`foo {${value}} bar`)).toBe(true);
expect(event.validateCustomEventName(`{${value}} bar`)).toBe(true);
expect(event.validateCustomEventName(`foo {${value}}`)).toBe(true);
});
});
it("should support booking field variables", () => {
expect(
event.validateCustomEventName("foo{customField}bar", {
customField: true,
})
).toBe(true);
});
it("should return variable when invalid variable used", () => {
expect(event.validateCustomEventName("foo{nonsenseField}bar")).toBe("{nonsenseField}");
});
});
describe("fn: updateHostInEventName", () => {
const oldHost = "John Doe";
const newHost = "Jane Smith";
it("should replace full host name with spaces", () => {
const eventName = "Meeting with John Doe";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Meeting with Jane Smith");
});
it("should replace full host name with dots", () => {
const eventName = "Meeting with John.Doe";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Meeting with Jane.Smith");
});
it("should replace full host name with hyphens", () => {
const eventName = "Meeting with John-Doe";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Meeting with Jane-Smith");
});
it("should replace full host name with underscores", () => {
const eventName = "Meeting with John_Doe";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Meeting with Jane_Smith");
});
it("should replace first name only", () => {
const eventName = "John's presentation";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Jane's presentation");
});
it("should replace first name at the beginning", () => {
const eventName = "John will present tomorrow";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Jane will present tomorrow");
});
it("should replace first name at the end", () => {
const eventName = "Presentation by John";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Presentation by Jane");
});
it("should handle different cases", () => {
const eventName = "meeting with john.doe";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("meeting with Jane.Smith");
});
it("should handle mixed cases", () => {
const eventName = "Meeting with JOHN DOE";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Meeting with Jane Smith");
});
it("should not replace partial matches", () => {
const eventName = "Meeting with Johnson";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Meeting with Johnson");
});
it("should handle empty event name", () => {
const result = updateHostInEventName("", oldHost, newHost);
expect(result).toBe("");
});
it("should handle event name without host", () => {
const eventName = "Team meeting";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("Team meeting");
});
it("should handle single word names", () => {
const eventName = "Meeting with John";
const result = updateHostInEventName(eventName, "John", "Jane");
expect(result).toBe("Meeting with Jane");
});
it("should handle names with multiple parts", () => {
const eventName = "Meeting with John van der Berg";
const result = updateHostInEventName(eventName, "John van der Berg", "Jane Smith");
expect(result).toBe("Meeting with Jane Smith");
});
it("should handle names with apostrophes", () => {
const eventName = "Meeting with John O'Connor";
const result = updateHostInEventName(eventName, "John O'Connor", "Jane Smith");
expect(result).toBe("Meeting with Jane Smith");
});
it("should handle names with special characters", () => {
const eventName = "Meeting with Jean-Pierre Dupont";
const result = updateHostInEventName(eventName, "Jean-Pierre Dupont", "Jane Smith");
expect(result).toBe("Meeting with Jane Smith");
});
it("should prioritize full name over first name", () => {
const eventName = "John.Doe and John are coming";
const result = updateHostInEventName(eventName, "John Doe", "Jane Smith");
expect(result).toBe("Jane.Smith and John are coming");
});
it("should only replace first match", () => {
const eventName = "John.Doe and John Doe meeting";
const result = updateHostInEventName(eventName, "John Doe", "Jane Smith");
expect(result).toBe("Jane.Smith and John Doe meeting");
});
it("should handle different new name structure", () => {
const eventName = "Meeting with John.Doe";
const result = updateHostInEventName(eventName, "John Doe", "Jane");
expect(result).toBe("Meeting with Jane");
});
it("should handle multiple occurrences with priority", () => {
const eventName = "John and John.Doe and John_Doe";
const result = updateHostInEventName(eventName, oldHost, newHost);
expect(result).toBe("John and Jane.Smith and John_Doe");
});
});
});
@@ -0,0 +1,204 @@
import type { TFunction } from "i18next";
import z from "zod";
import { guessEventLocationType } from "@calcom/app-store/locations";
import type { Prisma } from "@calcom/prisma/client";
export const nameObjectSchema = z.object({
firstName: z.string(),
lastName: z.string().optional(),
});
function parseName(name: z.infer<typeof nameObjectSchema> | string | undefined) {
if (typeof name === "string") return name;
else if (typeof name === "object" && nameObjectSchema.parse(name))
return `${name.firstName} ${name.lastName}`.trim();
else return "Nameless";
}
export type EventNameObjectType = {
attendeeName: z.infer<typeof nameObjectSchema> | string;
eventType: string;
eventName?: string | null;
teamName?: string | null;
host: string;
location?: string | null;
eventDuration: number;
bookingFields?: Prisma.JsonObject | null;
t: TFunction;
};
export function getEventName(eventNameObj: EventNameObjectType, forAttendeeView = false) {
const attendeeName = parseName(eventNameObj.attendeeName);
if (!eventNameObj.eventName)
return eventNameObj.t("event_between_users", {
eventName: eventNameObj.eventType,
host: eventNameObj.teamName || eventNameObj.host,
attendeeName,
interpolation: {
escapeValue: false,
},
});
let eventName = eventNameObj.eventName;
let locationString = eventNameObj.location || "";
if (eventNameObj.eventName.includes("{Location}") || eventNameObj.eventName.includes("{LOCATION}")) {
const eventLocationType = guessEventLocationType(eventNameObj.location);
if (eventLocationType) {
locationString = eventLocationType.label;
}
eventName = eventName.replace("{Location}", locationString);
eventName = eventName.replace("{LOCATION}", locationString);
}
let dynamicEventName = eventName
// Need this for compatibility with older event names
.replaceAll("{Event type title}", eventNameObj.eventType)
.replaceAll("{Scheduler}", attendeeName)
.replaceAll("{Organiser}", eventNameObj.host)
.replaceAll("{Organiser first name}", eventNameObj.host.split(" ")[0])
.replaceAll("{USER}", attendeeName)
.replaceAll("{ATTENDEE}", attendeeName)
.replaceAll("{HOST}", eventNameObj.host)
.replaceAll("{HOST/ATTENDEE}", forAttendeeView ? eventNameObj.host : attendeeName)
.replaceAll("{Event duration}", `${String(eventNameObj.eventDuration)} mins`)
.replaceAll(
"{Scheduler first name}",
attendeeName === eventNameObj.t("scheduler") ? "{Scheduler first name}" : attendeeName.split(" ")[0]
);
const { bookingFields } = eventNameObj || {};
const { name } = bookingFields || {};
if (name && typeof name === "object" && !Array.isArray(name) && typeof name.lastName === "string") {
dynamicEventName = dynamicEventName.replaceAll("{Scheduler last name}", name.lastName.toString());
}
const customInputvariables = dynamicEventName.match(/\{(.+?)}/g)?.map((variable) => {
return variable.replace("{", "").replace("}", "");
});
customInputvariables?.forEach((variable) => {
if (!eventNameObj.bookingFields) return;
const bookingFieldValue = eventNameObj.bookingFields[variable as keyof typeof eventNameObj.bookingFields];
if (bookingFieldValue) {
let fieldValue;
if (typeof bookingFieldValue === "object") {
if ("value" in bookingFieldValue) {
const valueAsString = bookingFieldValue.value?.toString();
fieldValue =
variable === "location"
? guessEventLocationType(valueAsString)?.label || valueAsString
: valueAsString;
} else if (variable === "name" && "firstName" in bookingFieldValue) {
const lastName = "lastName" in bookingFieldValue ? bookingFieldValue.lastName : "";
fieldValue = `${bookingFieldValue.firstName} ${lastName}`.trim();
}
} else {
fieldValue = bookingFieldValue.toString();
}
dynamicEventName = dynamicEventName.replace(`{${variable}}`, fieldValue || "");
} else {
dynamicEventName = dynamicEventName.replace(`{${variable}}`, "");
}
});
return dynamicEventName;
}
export function updateHostInEventName(eventName: string, oldHost: string, newHost: string) {
const oldParts = oldHost.trim().split(/\s+/);
const newParts = newHost.trim().split(/\s+/);
// Handle cases where names might have different number of parts
const oldFirst = oldParts[0];
const oldLast = oldParts.slice(1).join(" ");
const newFirst = newParts[0];
const newLast = newParts.slice(1).join(" ");
const formats = [
// Full name patterns (prioritize these first)
...(oldLast
? [
{
pattern: `${oldFirst}.${oldLast}`,
replacement: newLast ? `${newFirst}.${newLast}` : newFirst,
},
{
pattern: `${oldFirst}-${oldLast}`,
replacement: newLast ? `${newFirst}-${newLast}` : newFirst,
},
{
pattern: `${oldFirst}_${oldLast}`,
replacement: newLast ? `${newFirst}_${newLast}` : newFirst,
},
{
pattern: `${oldFirst} ${oldLast}`,
replacement: newLast ? `${newFirst} ${newLast}` : newFirst,
},
]
: []),
// First name only (last to avoid partial matches)
{
pattern: oldFirst,
replacement: newFirst,
},
];
let updatedEventName = eventName;
for (const { pattern, replacement } of formats) {
// Escape special regex characters in the pattern
const escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regex = new RegExp(`\\b${escapedPattern}\\b`, "gi");
if (regex.test(updatedEventName)) {
updatedEventName = updatedEventName.replace(regex, replacement);
return updatedEventName;
}
}
return updatedEventName;
}
export const validateCustomEventName = (value: string, bookingFields?: Prisma.JsonObject | null) => {
let customInputVariables: string[] = [];
if (bookingFields) {
customInputVariables = Object.keys(bookingFields).map((customInput) => {
return `{${customInput}}`;
});
}
const validVariables = customInputVariables.concat([
"{Event type title}",
"{Organiser}",
"{Scheduler}",
"{Location}",
"{Organiser first name}",
"{Scheduler first name}",
"{Scheduler last name}",
"{Event duration}",
//allowed for fallback reasons
"{LOCATION}",
"{HOST/ATTENDEE}",
"{HOST}",
"{ATTENDEE}",
"{USER}",
]);
const matches = value.match(/\{([^}]+)\}/g);
if (matches?.length) {
for (const item of matches) {
if (!validVariables.includes(item)) {
return item;
}
}
}
return true;
};
@@ -1,4 +1,4 @@
import { fetcher } from "@calcom/lib/dailyApiFetcher";
import { fetcher } from "@calcom/app-store/dailyvideo/lib/dailyApiFetcher";
import { triggerNoShowPayloadSchema } from "./schema";