refactor: circular deps between app store and lib [4] (#23829)
* mv team queries to features from lib * update imports * same * wip * move event manager test * calendar manager to features from lib * update imports * update imports * fix * mv getEventTypeById * fix * fix * remove * fix type check error * fix tests * fix tests * fix
This commit is contained in:
1 parent
3b471f0e25
commit
b3a28dca25
90 files changed
+134
-112
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries/teams";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Team, User, OrganizationSettings } from "@calcom/prisma/client";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries/teams";
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Team, OrganizationSettings } from "@calcom/prisma/client";
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
import { prisma } from "@calcom/prisma/__mocks__/prisma";
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
import { symmetricDecrypt } from "@calcom/lib/crypto";
|
||||
import type { DestinationCalendar } from "@calcom/prisma/client";
|
||||
import type { CredentialForCalendarService } from "@calcom/types/Credential";
|
||||
|
||||
import EventManager from "./EventManager";
|
||||
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma,
|
||||
}));
|
||||
|
||||
vi.mock("@calcom/lib/crypto", () => ({
|
||||
symmetricDecrypt: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedSymmetricDecrypt = vi.mocked(symmetricDecrypt);
|
||||
|
||||
function buildCalDAVCredential(data: {
|
||||
id: number;
|
||||
key: string;
|
||||
userId?: number;
|
||||
}): CredentialForCalendarService {
|
||||
return {
|
||||
id: data.id,
|
||||
type: "caldav_calendar",
|
||||
key: data.key,
|
||||
userId: data.userId || 1,
|
||||
user: { email: "[email protected]" },
|
||||
teamId: null,
|
||||
appId: "caldav-calendar",
|
||||
invalid: false,
|
||||
delegatedTo: null,
|
||||
delegationCredentialId: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildDestinationCalendar(data: {
|
||||
id: number;
|
||||
integration: string;
|
||||
externalId: string | null;
|
||||
}): DestinationCalendar {
|
||||
return {
|
||||
id: data.id,
|
||||
integration: data.integration,
|
||||
externalId: data.externalId || "",
|
||||
userId: 1,
|
||||
eventTypeId: null,
|
||||
credentialId: null,
|
||||
primaryEmail: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
delegationCredentialId: null,
|
||||
domainWideDelegationCredentialId: null,
|
||||
};
|
||||
}
|
||||
|
||||
describe("EventManager CalDAV credential validation", () => {
|
||||
let eventManager: EventManager;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
eventManager = new EventManager({
|
||||
credentials: [],
|
||||
destinationCalendar: null,
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractServerUrlFromCredential", () => {
|
||||
it("should extract server URL from valid CalDAV credential", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "https://caldav.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromCredential(credential);
|
||||
expect(result).toBe("https://caldav.example.com");
|
||||
expect(mockedSymmetricDecrypt).toHaveBeenCalledWith(
|
||||
"encrypted_key",
|
||||
process.env.CALENDSO_ENCRYPTION_KEY || ""
|
||||
);
|
||||
});
|
||||
|
||||
it("should return null for non-CalDAV credential", () => {
|
||||
const credential = {
|
||||
...buildCalDAVCredential({ id: 1, key: "encrypted_key" }),
|
||||
type: "google_calendar",
|
||||
} as CredentialForCalendarService;
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromCredential(credential);
|
||||
expect(result).toBeNull();
|
||||
expect(mockedSymmetricDecrypt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should return null when decryption fails", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "invalid_key",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockImplementation(() => {
|
||||
throw new Error("Decryption failed");
|
||||
});
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromCredential(credential);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null when decrypted data has no URL", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromCredential(credential);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null when URL is invalid", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "invalid-url",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromCredential(credential);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle URLs with different ports", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "https://caldav.example.com:8443/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromCredential(credential);
|
||||
expect(result).toBe("https://caldav.example.com:8443");
|
||||
});
|
||||
|
||||
it("should handle HTTP URLs", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "http://caldav.internal.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromCredential(credential);
|
||||
expect(result).toBe("http://caldav.internal.com");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractServerUrlFromDestination", () => {
|
||||
it("should extract server URL from CalDAV destination calendar", () => {
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "https://caldav.example.com/dav/calendars/user/calendar1/",
|
||||
});
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromDestination(destination);
|
||||
expect(result).toBe("https://caldav.example.com");
|
||||
});
|
||||
|
||||
it("should return null for non-CalDAV destination", () => {
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
});
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromDestination(destination);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null when externalId is null", () => {
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: null,
|
||||
});
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromDestination(destination);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null when externalId is invalid URL", () => {
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "invalid-url",
|
||||
});
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromDestination(destination);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should handle URLs with different ports", () => {
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "https://caldav.example.com:8443/dav/calendars/user/calendar1/",
|
||||
});
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromDestination(destination);
|
||||
expect(result).toBe("https://caldav.example.com:8443");
|
||||
});
|
||||
|
||||
it("should handle HTTP URLs", () => {
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "http://caldav.internal.com/dav/calendars/user/calendar1/",
|
||||
});
|
||||
|
||||
const result = (eventManager as any).extractServerUrlFromDestination(destination);
|
||||
expect(result).toBe("http://caldav.internal.com");
|
||||
});
|
||||
});
|
||||
|
||||
describe("credentialMatchesDestination", () => {
|
||||
it("should return true for matching CalDAV server URLs", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "https://caldav.example.com/dav/calendars/user/calendar1/",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "https://caldav.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for non-matching CalDAV server URLs", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "https://different.example.com/dav/calendars/user/calendar1/",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "https://caldav.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should return true for non-CalDAV credentials", () => {
|
||||
const credential = {
|
||||
...buildCalDAVCredential({ id: 1, key: "encrypted_key" }),
|
||||
type: "google_calendar",
|
||||
} as CredentialForCalendarService;
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
});
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(true);
|
||||
expect(symmetricDecrypt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should return true when credential is CalDAV but destination is not", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
});
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(true);
|
||||
expect(symmetricDecrypt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should return false when credential URL extraction fails", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "invalid_key",
|
||||
});
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "https://caldav.example.com/dav/calendars/user/calendar1/",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockImplementation(() => {
|
||||
throw new Error("Decryption failed");
|
||||
});
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when destination URL extraction fails", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "invalid-url",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "https://caldav.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle URLs with different paths but same server", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "https://caldav.example.com/different/path/calendar1/",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "https://caldav.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle URLs with different ports as non-matching", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "https://caldav.example.com:8443/dav/calendars/user/calendar1/",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "https://caldav.example.com:9443/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle HTTP vs HTTPS as non-matching", () => {
|
||||
const credential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_key",
|
||||
});
|
||||
|
||||
const destination = buildDestinationCalendar({
|
||||
id: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: "https://caldav.example.com/dav/calendars/user/calendar1/",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "http://caldav.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const result = (eventManager as any).credentialMatchesDestination(credential, destination);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -17,7 +17,7 @@ import {
|
||||
} from "@calcom/features/webhooks/lib/scheduleTrigger";
|
||||
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
|
||||
import type { EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
|
||||
import EventManager from "@calcom/lib/EventManager";
|
||||
import EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
|
||||
|
||||
@@ -11,8 +11,8 @@ import { scheduleTrigger } from "@calcom/features/webhooks/lib/scheduleTrigger";
|
||||
import sendPayload from "@calcom/features/webhooks/lib/sendOrSchedulePayload";
|
||||
import type { EventPayloadType, EventTypeInfo } from "@calcom/features/webhooks/lib/sendPayload";
|
||||
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
|
||||
import type { EventManagerUser } from "@calcom/lib/EventManager";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/lib/EventManager";
|
||||
import type { EventManagerUser } from "@calcom/features/bookings/lib/EventManager";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
||||
import { getTeamIdFromEventType } from "@calcom/lib/getTeamIdFromEventType";
|
||||
|
||||
@@ -36,7 +36,7 @@ import {
|
||||
scheduleTrigger,
|
||||
} from "@calcom/features/webhooks/lib/scheduleTrigger";
|
||||
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/lib/EventManager";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
|
||||
import { handleAnalyticsEvents } from "@calcom/lib/analyticsManager/handleAnalyticsEvents";
|
||||
import { groupHostsByGroupId } from "@calcom/lib/bookings/hostGroupUtils";
|
||||
import { shouldIgnoreContactOwner } from "@calcom/lib/bookings/routing/utils";
|
||||
|
||||
+1
-1
@@ -783,7 +783,7 @@ describe("Round Robin handleNewBooking", () => {
|
||||
describe("Seated Round Robin Event", () => {
|
||||
test("For second seat booking, organizer remains the same with no team members included", async () => {
|
||||
const handleNewBooking = getNewBookingHandler();
|
||||
const EventManager = (await import("@calcom/lib/EventManager")).default;
|
||||
const EventManager = (await import("@calcom/features/bookings/lib/EventManager")).default;
|
||||
|
||||
const eventManagerSpy = vi.spyOn(EventManager.prototype, "updateCalendarAttendees");
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
allowDisablingAttendeeConfirmationEmails,
|
||||
allowDisablingHostConfirmationEmails,
|
||||
} from "@calcom/features/ee/workflows/lib/allowDisablingStandardEmails";
|
||||
import EventManager from "@calcom/lib/EventManager";
|
||||
import EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
import { cloneDeep } from "lodash";
|
||||
|
||||
import { sendRescheduledSeatEmailAndSMS } from "@calcom/emails";
|
||||
import type EventManager from "@calcom/lib/EventManager";
|
||||
import type EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Person, CalendarEvent } from "@calcom/types/Calendar";
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { cloneDeep } from "lodash";
|
||||
import { uuid } from "short-uuid";
|
||||
|
||||
import { sendRescheduledEmailsAndSMS } from "@calcom/emails";
|
||||
import type EventManager from "@calcom/lib/EventManager";
|
||||
import type EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
import { cloneDeep } from "lodash";
|
||||
|
||||
import { sendRescheduledEmailsAndSMS } from "@calcom/emails";
|
||||
import type EventManager from "@calcom/lib/EventManager";
|
||||
import type EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { AdditionalInformation, AppsStatus } from "@calcom/types/Calendar";
|
||||
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import type EventManager from "@calcom/lib/EventManager";
|
||||
import type EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
|
||||
import type { createLoggerWithEventDetails } from "../../../handleNewBooking/logger";
|
||||
import type {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { refreshCredentials } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/refreshCredentials";
|
||||
import EventManager from "@calcom/lib/EventManager";
|
||||
import EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
import { prisma } from "@calcom/prisma/__mocks__/prisma";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { getCalendarCredentials, deduplicateCredentialsBasedOnSelectedCalendars } from "./CalendarManager";
|
||||
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma,
|
||||
}));
|
||||
|
||||
function buildCredential(data: {
|
||||
type: string;
|
||||
appId: string;
|
||||
id: number;
|
||||
delegatedToId: string | null;
|
||||
user: { email: string } | null;
|
||||
}) {
|
||||
return {
|
||||
...data,
|
||||
teamId: null,
|
||||
invalid: false,
|
||||
key: { access_token: "DONT_MATTER" },
|
||||
userId: 10000,
|
||||
delegatedTo: {
|
||||
serviceAccountKey: {
|
||||
client_email: "DONT_MATTER",
|
||||
tenant_id: "DONT_MATTER",
|
||||
client_id: "DONT_MATTER",
|
||||
private_key: "DONT_MATTER",
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("CalendarManager tests", () => {
|
||||
describe("fn: getCalendarCredentials", () => {
|
||||
it("should only return credentials for calendar apps", async () => {
|
||||
const googleCalendarCredentials = {
|
||||
id: "1",
|
||||
appId: "google-calendar",
|
||||
type: "google_calendar",
|
||||
userId: "3",
|
||||
key: {
|
||||
access_token: "google_calendar_key",
|
||||
},
|
||||
invalid: false,
|
||||
delegatedTo: null,
|
||||
};
|
||||
|
||||
const credentials = [
|
||||
googleCalendarCredentials,
|
||||
{
|
||||
id: "2",
|
||||
appId: "office365-video",
|
||||
type: "office365_video",
|
||||
userId: "4",
|
||||
key: {
|
||||
access_token: "office365_video_key",
|
||||
},
|
||||
invalid: false,
|
||||
},
|
||||
];
|
||||
|
||||
const calendarCredentials = getCalendarCredentials(credentials);
|
||||
expect(calendarCredentials).toHaveLength(1);
|
||||
expect(calendarCredentials[0].credential).toEqual(googleCalendarCredentials);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fn: deduplicateCredentialsBasedOnSelectedCalendars", () => {
|
||||
it("should remove a regular credential for which a delegation credential exists i.e. both are fetching events for same externalId", () => {
|
||||
const calcomUser = {
|
||||
email: "[email protected]",
|
||||
};
|
||||
|
||||
const externalIdSameAsCalcomUserEmail = calcomUser.email;
|
||||
const externalIdDifferentFromCalcomUserEmail = "[email protected]";
|
||||
|
||||
// Delegation Credential(Calendar)
|
||||
const delegationCredentialCalendarForCalcomEmail = buildCredential({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: -1,
|
||||
delegatedToId: "45fa8f04-e891-417b-98e1-abf48e8ae18a",
|
||||
user: calcomUser,
|
||||
});
|
||||
|
||||
// Delegation Credential(Conferencing)
|
||||
const delegationCredentialConferencingForCalcomEmail = buildCredential({
|
||||
type: "google_video",
|
||||
appId: "google-meet",
|
||||
id: -1,
|
||||
delegatedToId: "45fa8f04-e891-417b-98e1-abf48e8ae18a",
|
||||
user: calcomUser,
|
||||
});
|
||||
|
||||
// Regular Credential for [email protected]
|
||||
const regularCredentialForCalcomEmail = buildCredential({
|
||||
id: 2,
|
||||
appId: "google-calendar",
|
||||
type: "google_calendar",
|
||||
delegatedToId: null,
|
||||
user: calcomUser,
|
||||
});
|
||||
|
||||
// Regular Credential for [email protected]
|
||||
const regularCredentialForSomeOtherEmail = buildCredential({
|
||||
id: 3,
|
||||
appId: "google-calendar",
|
||||
type: "google_calendar",
|
||||
delegatedToId: null,
|
||||
user: calcomUser,
|
||||
});
|
||||
|
||||
const credentials = [
|
||||
delegationCredentialCalendarForCalcomEmail,
|
||||
delegationCredentialConferencingForCalcomEmail,
|
||||
// This one is duplicate
|
||||
regularCredentialForCalcomEmail,
|
||||
// Regular Credential for [email protected]
|
||||
regularCredentialForSomeOtherEmail,
|
||||
];
|
||||
|
||||
const selectedCalendars = [
|
||||
{
|
||||
id: "62f4f3b7-c65b-4199-8052-25b91ee25ff2",
|
||||
userId: 23,
|
||||
integration: "google_calendar",
|
||||
externalId: externalIdDifferentFromCalcomUserEmail,
|
||||
credentialId: regularCredentialForSomeOtherEmail.id,
|
||||
delegationCredentialId: null,
|
||||
eventTypeId: null,
|
||||
},
|
||||
{
|
||||
id: "418e1bd0-7bde-4ea6-b03a-b2b6de6af497",
|
||||
userId: 23,
|
||||
integration: "google_calendar",
|
||||
externalId: externalIdSameAsCalcomUserEmail,
|
||||
credentialId: regularCredentialForCalcomEmail.id,
|
||||
delegationCredentialId: null,
|
||||
eventTypeId: null,
|
||||
},
|
||||
];
|
||||
|
||||
const uniqueCredentials = deduplicateCredentialsBasedOnSelectedCalendars({
|
||||
credentials,
|
||||
selectedCalendars,
|
||||
});
|
||||
expect(uniqueCredentials).toHaveLength(3);
|
||||
expect(uniqueCredentials).toEqual([
|
||||
delegationCredentialCalendarForCalcomEmail,
|
||||
delegationCredentialConferencingForCalcomEmail,
|
||||
regularCredentialForSomeOtherEmail,
|
||||
]);
|
||||
});
|
||||
|
||||
it("should not remove a regular credential for which a delegation credential exists i.e. both are fetching events for same externalId if integration is different", () => {
|
||||
const calcomUser = {
|
||||
email: "[email protected]",
|
||||
};
|
||||
|
||||
const externalIdSameAsCalcomUserEmail = calcomUser.email;
|
||||
const externalIdDifferentFromCalcomUserEmail = "[email protected]";
|
||||
|
||||
// Delegation Credential(Calendar) - wrong integration type
|
||||
const delegationCredentialCalendarForCalcomEmail = buildCredential({
|
||||
type: "google_calendar_wrong_type",
|
||||
appId: "google-calendar",
|
||||
id: -1,
|
||||
delegatedToId: "45fa8f04-e891-417b-98e1-abf48e8ae18a",
|
||||
user: calcomUser,
|
||||
});
|
||||
|
||||
// Delegation Credential(Conferencing)
|
||||
const delegationCredentialConferencingForCalcomEmail = buildCredential({
|
||||
type: "google_video",
|
||||
appId: "google-meet",
|
||||
id: -1,
|
||||
delegatedToId: "45fa8f04-e891-417b-98e1-abf48e8ae18a",
|
||||
user: calcomUser,
|
||||
});
|
||||
|
||||
// Regular Credential for [email protected]
|
||||
const regularCredentialForCalcomEmail = buildCredential({
|
||||
id: 2,
|
||||
appId: "google-calendar",
|
||||
type: "google_calendar",
|
||||
delegatedToId: null,
|
||||
user: calcomUser,
|
||||
});
|
||||
|
||||
// Regular Credential for [email protected]
|
||||
const regularCredentialForSomeOtherEmail = buildCredential({
|
||||
id: 3,
|
||||
appId: "google-calendar",
|
||||
type: "google_calendar",
|
||||
delegatedToId: null,
|
||||
user: calcomUser,
|
||||
});
|
||||
|
||||
const credentials = [
|
||||
delegationCredentialCalendarForCalcomEmail,
|
||||
delegationCredentialConferencingForCalcomEmail,
|
||||
// This one won't be removed as integration is different
|
||||
regularCredentialForCalcomEmail,
|
||||
// Regular Credential for [email protected]
|
||||
regularCredentialForSomeOtherEmail,
|
||||
];
|
||||
|
||||
const selectedCalendars = [
|
||||
{
|
||||
id: "62f4f3b7-c65b-4199-8052-25b91ee25ff2",
|
||||
userId: 23,
|
||||
integration: "google_calendar",
|
||||
externalId: externalIdDifferentFromCalcomUserEmail,
|
||||
credentialId: regularCredentialForSomeOtherEmail.id,
|
||||
delegationCredentialId: null,
|
||||
eventTypeId: null,
|
||||
},
|
||||
{
|
||||
id: "418e1bd0-7bde-4ea6-b03a-b2b6de6af497",
|
||||
userId: 23,
|
||||
integration: "google_calendar",
|
||||
externalId: externalIdSameAsCalcomUserEmail,
|
||||
credentialId: regularCredentialForCalcomEmail.id,
|
||||
delegationCredentialId: null,
|
||||
eventTypeId: null,
|
||||
},
|
||||
];
|
||||
|
||||
const uniqueCredentials = deduplicateCredentialsBasedOnSelectedCalendars({
|
||||
credentials,
|
||||
selectedCalendars,
|
||||
});
|
||||
expect(uniqueCredentials).toHaveLength(4);
|
||||
expect(uniqueCredentials).toEqual([
|
||||
delegationCredentialCalendarForCalcomEmail,
|
||||
delegationCredentialConferencingForCalcomEmail,
|
||||
regularCredentialForCalcomEmail,
|
||||
regularCredentialForSomeOtherEmail,
|
||||
]);
|
||||
});
|
||||
|
||||
it("should return empty array when credentials array is empty", () => {
|
||||
const selectedCalendars = [
|
||||
{
|
||||
id: "calendar-1",
|
||||
userId: 23,
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
credentialId: 1,
|
||||
delegationCredentialId: null,
|
||||
eventTypeId: null,
|
||||
},
|
||||
];
|
||||
|
||||
const uniqueCredentials = deduplicateCredentialsBasedOnSelectedCalendars({
|
||||
credentials: [],
|
||||
selectedCalendars,
|
||||
});
|
||||
expect(uniqueCredentials).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should return original credentials when user email is not present", () => {
|
||||
const credentialsWithoutUserEmail = [
|
||||
buildCredential({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: 1,
|
||||
delegatedToId: null,
|
||||
user: null,
|
||||
}),
|
||||
buildCredential({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: -1,
|
||||
delegatedToId: "delegation-1",
|
||||
user: null,
|
||||
}),
|
||||
];
|
||||
|
||||
const selectedCalendars = [
|
||||
{
|
||||
id: "calendar-1",
|
||||
userId: 23,
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
credentialId: 1,
|
||||
delegationCredentialId: null,
|
||||
eventTypeId: null,
|
||||
},
|
||||
];
|
||||
|
||||
const uniqueCredentials = deduplicateCredentialsBasedOnSelectedCalendars({
|
||||
credentials: credentialsWithoutUserEmail,
|
||||
selectedCalendars,
|
||||
});
|
||||
expect(uniqueCredentials).toEqual(credentialsWithoutUserEmail);
|
||||
});
|
||||
|
||||
it("should return original credentials when no delegation credentials exist", () => {
|
||||
const regularCredentials = [
|
||||
buildCredential({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: 1,
|
||||
delegatedToId: null,
|
||||
user: { email: "[email protected]" },
|
||||
}),
|
||||
buildCredential({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: 2,
|
||||
delegatedToId: null,
|
||||
user: { email: "[email protected]" },
|
||||
}),
|
||||
];
|
||||
|
||||
const selectedCalendars = [
|
||||
{
|
||||
id: "calendar-1",
|
||||
userId: 23,
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]",
|
||||
credentialId: 1,
|
||||
delegationCredentialId: null,
|
||||
eventTypeId: null,
|
||||
},
|
||||
];
|
||||
|
||||
const uniqueCredentials = deduplicateCredentialsBasedOnSelectedCalendars({
|
||||
credentials: regularCredentials,
|
||||
selectedCalendars,
|
||||
});
|
||||
expect(uniqueCredentials).toEqual(regularCredentials);
|
||||
});
|
||||
|
||||
it("should return original credentials when no matching selected calendars exist", () => {
|
||||
const credentials = [
|
||||
buildCredential({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: 1,
|
||||
delegatedToId: "delegation-1",
|
||||
user: { email: "[email protected]" },
|
||||
}),
|
||||
buildCredential({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: 2,
|
||||
delegatedToId: null,
|
||||
user: { email: "[email protected]" },
|
||||
}),
|
||||
];
|
||||
|
||||
const selectedCalendars = [
|
||||
{
|
||||
id: "calendar-1",
|
||||
userId: 23,
|
||||
integration: "google_calendar",
|
||||
externalId: "[email protected]", // Different email than the credentials
|
||||
credentialId: 1,
|
||||
delegationCredentialId: null,
|
||||
eventTypeId: null,
|
||||
},
|
||||
];
|
||||
|
||||
const uniqueCredentials = deduplicateCredentialsBasedOnSelectedCalendars({
|
||||
credentials,
|
||||
selectedCalendars,
|
||||
});
|
||||
expect(uniqueCredentials).toEqual(credentials);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,520 @@
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { sortBy } from "lodash";
|
||||
|
||||
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import { MeetLocationType } from "@calcom/app-store/locations";
|
||||
import getApps from "@calcom/app-store/utils";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getUid } from "@calcom/lib/CalEventParser";
|
||||
import { getRichDescription } from "@calcom/lib/CalEventParser";
|
||||
import { CalendarAppDelegationCredentialError } from "@calcom/lib/CalendarAppError";
|
||||
import { ORGANIZER_EMAIL_EXEMPT_DOMAINS } from "@calcom/lib/constants";
|
||||
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential/clientAndServer";
|
||||
import { formatCalEvent } from "@calcom/lib/formatCalendarEvent";
|
||||
import getCalendarsEvents from "@calcom/lib/getCalendarsEvents";
|
||||
import { getCalendarsEventsWithTimezones } from "@calcom/lib/getCalendarsEvents";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getPiiFreeCalendarEvent, getPiiFreeCredential } from "@calcom/lib/piiFreeData";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import type {
|
||||
CalendarEvent,
|
||||
CalendarServiceEvent,
|
||||
EventBusyDate,
|
||||
IntegrationCalendar,
|
||||
NewCalendarEventType,
|
||||
SelectedCalendar,
|
||||
} from "@calcom/types/Calendar";
|
||||
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
|
||||
import type { EventResult } from "@calcom/types/EventManager";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["CalendarManager"] });
|
||||
|
||||
export const getCalendarCredentials = (credentials: Array<CredentialForCalendarService>) => {
|
||||
const calendarCredentials = getApps(credentials, true)
|
||||
.filter((app) => app.type.endsWith("_calendar"))
|
||||
.flatMap((app) => {
|
||||
const credentials = app.credentials.flatMap((credential) => {
|
||||
const calendar = () => getCalendar(credential);
|
||||
return app.variant === "calendar" ? [{ integration: app, credential, calendar }] : [];
|
||||
});
|
||||
|
||||
return credentials.length ? credentials : [];
|
||||
});
|
||||
|
||||
return calendarCredentials;
|
||||
};
|
||||
|
||||
export const getCalendarCredentialsWithoutDelegation = (credentials: CredentialPayload[]) => {
|
||||
return getCalendarCredentials(buildNonDelegationCredentials(credentials));
|
||||
};
|
||||
|
||||
export const getConnectedCalendars = async (
|
||||
calendarCredentials: ReturnType<typeof getCalendarCredentials>,
|
||||
selectedCalendars: { externalId: string }[],
|
||||
destinationCalendarExternalId?: string
|
||||
) => {
|
||||
let destinationCalendar: IntegrationCalendar | undefined;
|
||||
const connectedCalendars = await Promise.all(
|
||||
calendarCredentials.map(async (item) => {
|
||||
try {
|
||||
const { integration, credential } = item;
|
||||
const safeToSendIntegration = cleanIntegrationKeys(integration);
|
||||
const calendar = await item.calendar;
|
||||
// Don't leak credentials to the client
|
||||
const credentialId = credential.id;
|
||||
const delegationCredentialId = credential.delegatedToId ?? null;
|
||||
if (!calendar) {
|
||||
return {
|
||||
integration: safeToSendIntegration,
|
||||
credentialId,
|
||||
delegationCredentialId,
|
||||
};
|
||||
}
|
||||
const calendarInstance = await calendar();
|
||||
if (!calendarInstance) {
|
||||
return {
|
||||
integration: safeToSendIntegration,
|
||||
credentialId,
|
||||
delegationCredentialId,
|
||||
error: {
|
||||
message: "Could not get calendar instance",
|
||||
},
|
||||
};
|
||||
}
|
||||
const cals = await calendarInstance.listCalendars();
|
||||
const calendars = sortBy(
|
||||
cals.map((cal: IntegrationCalendar) => {
|
||||
if (cal.externalId === destinationCalendarExternalId) destinationCalendar = cal;
|
||||
return {
|
||||
...cal,
|
||||
readOnly: cal.readOnly || false,
|
||||
primary: cal.primary || null,
|
||||
isSelected: selectedCalendars.some((selected) => selected.externalId === cal.externalId),
|
||||
credentialId,
|
||||
delegationCredentialId,
|
||||
};
|
||||
}),
|
||||
["primary"]
|
||||
);
|
||||
const primary = calendars.find((item) => item.primary) ?? calendars.find((cal) => cal !== undefined);
|
||||
if (!primary) {
|
||||
return {
|
||||
integration: safeToSendIntegration,
|
||||
credentialId,
|
||||
error: {
|
||||
message: "No primary calendar found",
|
||||
},
|
||||
};
|
||||
}
|
||||
// HACK https://github.com/calcom/cal.com/pull/7644/files#r1131508414
|
||||
if (destinationCalendar && !Object.isFrozen(destinationCalendar)) {
|
||||
destinationCalendar.primaryEmail = primary.email;
|
||||
destinationCalendar.integrationTitle = integration.title;
|
||||
destinationCalendar = Object.freeze(destinationCalendar);
|
||||
}
|
||||
|
||||
return {
|
||||
integration: safeToSendIntegration,
|
||||
credentialId,
|
||||
delegationCredentialId,
|
||||
primary,
|
||||
calendars,
|
||||
};
|
||||
} catch (error) {
|
||||
let errorMessage = "Could not get connected calendars";
|
||||
|
||||
// Here you can expect for specific errors
|
||||
if (error instanceof Error) {
|
||||
if (error.message === "invalid_grant") {
|
||||
errorMessage = "Access token expired or revoked";
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof CalendarAppDelegationCredentialError) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
log.error("getConnectedCalendars failed", safeStringify(error), safeStringify({ item }));
|
||||
|
||||
return {
|
||||
integration: cleanIntegrationKeys(item.integration),
|
||||
credentialId: item.credential.id,
|
||||
delegationCredentialId: item.credential.delegatedToId,
|
||||
error: {
|
||||
message: errorMessage,
|
||||
},
|
||||
};
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
return { connectedCalendars, destinationCalendar };
|
||||
};
|
||||
|
||||
/**
|
||||
* Important function to prevent leaking credentials to the client
|
||||
* @param appIntegration
|
||||
* @returns App
|
||||
*/
|
||||
const cleanIntegrationKeys = (
|
||||
appIntegration: Awaited<ReturnType<typeof getCalendarCredentials>>[number]["integration"] & {
|
||||
credentials?: Array<CredentialPayload>;
|
||||
credential: CredentialPayload;
|
||||
}
|
||||
) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { credentials, credential, ...rest } = appIntegration;
|
||||
return rest;
|
||||
};
|
||||
|
||||
/**
|
||||
* This function deduplicates credentials based on selected calendars
|
||||
* It removes regular credentials for which corresponding delegation credentials exist which can be identified only associating them with selected calendars
|
||||
*
|
||||
* This is important to prevent unnecessary/duplicate calls to calendar APIs
|
||||
*/
|
||||
export const deduplicateCredentialsBasedOnSelectedCalendars = ({
|
||||
credentials,
|
||||
selectedCalendars,
|
||||
}: {
|
||||
credentials: CredentialForCalendarService[];
|
||||
selectedCalendars: SelectedCalendar[];
|
||||
}) => {
|
||||
// Only proceed if we have credentials
|
||||
if (credentials.length === 0) {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
// Get the user email from the first credential
|
||||
const userEmail = credentials[0].user?.email;
|
||||
|
||||
// If no email, we can't identify which credential is duplicate
|
||||
if (!userEmail) {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
// Check if there are delegation credentials for the same integration types
|
||||
const delegationCredentials = credentials.filter((credential) => credential.delegatedToId);
|
||||
|
||||
// Find all selected calendars with externalId matching the user's email and having a regular credential
|
||||
const selectedCalendarsWithUserEmailConnectedWithRegularCredential = selectedCalendars.filter(
|
||||
(calendar) => calendar.externalId === userEmail && calendar.credentialId && calendar.credentialId > 0
|
||||
);
|
||||
|
||||
// If no delegation credentials or no regular credentials connected selected calendars, return original credentials
|
||||
if (
|
||||
delegationCredentials.length === 0 ||
|
||||
selectedCalendarsWithUserEmailConnectedWithRegularCredential.length === 0
|
||||
) {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
const deduplicatedCredentials = [...credentials];
|
||||
|
||||
// For each selected calendar with user email, check if a delegation credential exists for the same integration.
|
||||
// If yes, we remove such a regular credential as that is a duplicate
|
||||
const credentialIdsToRemove = selectedCalendarsWithUserEmailConnectedWithRegularCredential
|
||||
.filter((calendar) =>
|
||||
delegationCredentials.some((credential) => credential.type === calendar.integration)
|
||||
)
|
||||
.map((calendar) => calendar.credentialId);
|
||||
|
||||
// Remove the regular credentials that are now handled by delegation credentials
|
||||
return deduplicatedCredentials.filter((credential) => !credentialIdsToRemove.includes(credential.id));
|
||||
};
|
||||
|
||||
export const getBusyCalendarTimes = async (
|
||||
/**
|
||||
* withCredentials can possibly have duplicate credential in case DelegationCredential is enabled.
|
||||
* There is no way to deduplicate that at the moment because a `credential` doesn't directly know to which external_id(or email it is connected to).
|
||||
* So, there could be multiple credentials for the same user.
|
||||
* 1. Delegated Credential - that fetches events for [email protected]
|
||||
* 2. Regular Credential - that fetches events for [email protected]
|
||||
*
|
||||
*/
|
||||
withCredentials: CredentialForCalendarService[],
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: SelectedCalendar[],
|
||||
shouldServeCache?: boolean,
|
||||
includeTimeZone?: boolean
|
||||
) => {
|
||||
let results: (EventBusyDate & { timeZone?: string })[][] = [];
|
||||
|
||||
const deduplicatedCredentials = deduplicateCredentialsBasedOnSelectedCalendars({
|
||||
credentials: withCredentials,
|
||||
selectedCalendars,
|
||||
});
|
||||
|
||||
if (deduplicatedCredentials.length !== withCredentials.length) {
|
||||
log.info(
|
||||
"Deduplicated credentials and removed",
|
||||
withCredentials.length - deduplicatedCredentials.length,
|
||||
"duplicates. Total number of credentials now is",
|
||||
deduplicatedCredentials.length
|
||||
);
|
||||
}
|
||||
|
||||
// const months = getMonths(dateFrom, dateTo);
|
||||
// Subtract 11 hours from the start date to avoid problems in UTC- time zones.
|
||||
const startDate = dayjs(dateFrom).subtract(11, "hours").format();
|
||||
// Add 14 hours from the start date to avoid problems in UTC+ time zones.
|
||||
const endDate = dayjs(dateTo).add(14, "hours").format();
|
||||
try {
|
||||
if (includeTimeZone) {
|
||||
results = await getCalendarsEventsWithTimezones(
|
||||
deduplicatedCredentials,
|
||||
startDate,
|
||||
endDate,
|
||||
selectedCalendars
|
||||
);
|
||||
} else {
|
||||
results = await getCalendarsEvents(
|
||||
deduplicatedCredentials,
|
||||
startDate,
|
||||
endDate,
|
||||
selectedCalendars,
|
||||
shouldServeCache
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
log.warn(`Error getting calendar availability`, {
|
||||
selectedCalendarIds: selectedCalendars.map((calendar) => calendar.externalId),
|
||||
error: safeStringify(e),
|
||||
});
|
||||
return { success: false, data: [{ start: startDate, end: endDate, source: "error-placeholder" }] };
|
||||
}
|
||||
return { success: true, data: results.reduce((acc, availability) => acc.concat(availability), []) };
|
||||
};
|
||||
|
||||
export const createEvent = async (
|
||||
credential: CredentialForCalendarService,
|
||||
originalEvent: CalendarEvent,
|
||||
externalId?: string
|
||||
): Promise<EventResult<NewCalendarEventType>> => {
|
||||
// Some calendar libraries may edit the original event so let's clone it
|
||||
const formattedEvent = formatCalEvent(originalEvent);
|
||||
const uid: string = getUid(formattedEvent);
|
||||
const calendar = await getCalendar(credential);
|
||||
let success = true;
|
||||
let calError: string | undefined = undefined;
|
||||
|
||||
log.debug(
|
||||
"Creating calendar event",
|
||||
safeStringify({
|
||||
calEvent: getPiiFreeCalendarEvent(formattedEvent),
|
||||
})
|
||||
);
|
||||
// Check if the disabledNotes flag is set to true
|
||||
if (formattedEvent.hideCalendarNotes) {
|
||||
formattedEvent.additionalNotes = "Notes have been hidden by the organizer"; // TODO: i18n this string?
|
||||
}
|
||||
|
||||
const calEvent = processEvent(formattedEvent);
|
||||
|
||||
const externalCalendarIdWhenDelegationCredentialIsChosen = credential.delegatedToId
|
||||
? externalId
|
||||
: undefined;
|
||||
|
||||
// TODO: Surface success/error messages coming from apps to improve end user visibility
|
||||
const creationResult = calendar
|
||||
? await calendar
|
||||
// Ideally we should pass externalId always, but let's start with DelegationCredential case first as in that case, CalendarService need to handle a special case for DelegationCredential to determine the selectedCalendar.
|
||||
// Such logic shouldn't exist in CalendarService as it would be same for all calendar apps.
|
||||
.createEvent(calEvent, credential.id, externalCalendarIdWhenDelegationCredentialIsChosen)
|
||||
.catch(async (error: { code: number; calError: string }) => {
|
||||
success = false;
|
||||
/**
|
||||
* There is a time when selectedCalendar externalId doesn't match witch certain credential
|
||||
* so google returns 404.
|
||||
* */
|
||||
if (error?.code === 404) {
|
||||
return undefined;
|
||||
}
|
||||
if (error?.calError) {
|
||||
calError = error.calError;
|
||||
}
|
||||
log.error(
|
||||
"createEvent failed",
|
||||
safeStringify(error),
|
||||
safeStringify({ calEvent: getPiiFreeCalendarEvent(calEvent) })
|
||||
);
|
||||
// @TODO: This code will be off till we can investigate an error with it
|
||||
//https://github.com/calcom/cal.com/issues/3949
|
||||
// await sendBrokenIntegrationEmail(calEvent, "calendar");
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
if (!creationResult) {
|
||||
logger.error(
|
||||
"createEvent failed",
|
||||
safeStringify({
|
||||
success,
|
||||
uid,
|
||||
creationResult,
|
||||
originalEvent: getPiiFreeCalendarEvent(calEvent),
|
||||
calError,
|
||||
})
|
||||
);
|
||||
}
|
||||
log.debug(
|
||||
"Created calendar event",
|
||||
safeStringify({
|
||||
calEvent: getPiiFreeCalendarEvent(calEvent),
|
||||
creationResult,
|
||||
})
|
||||
);
|
||||
return {
|
||||
appName: credential.appId || "",
|
||||
type: credential.type,
|
||||
success,
|
||||
uid,
|
||||
iCalUID: creationResult?.iCalUID || undefined,
|
||||
createdEvent: creationResult,
|
||||
originalEvent: calEvent,
|
||||
calError,
|
||||
calWarnings: creationResult?.additionalInfo?.calWarnings || [],
|
||||
externalId,
|
||||
credentialId: credential.id,
|
||||
delegatedToId: credential.delegatedToId ?? undefined,
|
||||
};
|
||||
};
|
||||
|
||||
export const updateEvent = async (
|
||||
credential: CredentialForCalendarService,
|
||||
rawCalEvent: CalendarEvent,
|
||||
bookingRefUid: string | null,
|
||||
externalCalendarId: string | null
|
||||
): Promise<EventResult<NewCalendarEventType>> => {
|
||||
const formattedEvent = formatCalEvent(rawCalEvent);
|
||||
const calEvent = processEvent(formattedEvent);
|
||||
const uid = getUid(calEvent);
|
||||
const calendar = await getCalendar(credential);
|
||||
let success = false;
|
||||
let calError: string | undefined = undefined;
|
||||
let calWarnings: string[] | undefined = [];
|
||||
log.debug(
|
||||
"Updating calendar event",
|
||||
safeStringify({
|
||||
bookingRefUid,
|
||||
calEvent: getPiiFreeCalendarEvent(calEvent),
|
||||
})
|
||||
);
|
||||
if (bookingRefUid === "") {
|
||||
log.error(
|
||||
"updateEvent failed",
|
||||
"bookingRefUid is empty",
|
||||
safeStringify({ calEvent: getPiiFreeCalendarEvent(calEvent) })
|
||||
);
|
||||
}
|
||||
const updatedResult: NewCalendarEventType | NewCalendarEventType[] | undefined =
|
||||
calendar && bookingRefUid
|
||||
? await calendar
|
||||
.updateEvent(bookingRefUid, calEvent, externalCalendarId)
|
||||
.then((event: NewCalendarEventType | NewCalendarEventType[]) => {
|
||||
success = true;
|
||||
return event;
|
||||
})
|
||||
.catch(async (e: { calError: string }) => {
|
||||
// @TODO: This code will be off till we can investigate an error with it
|
||||
// @see https://github.com/calcom/cal.com/issues/3949
|
||||
// await sendBrokenIntegrationEmail(calEvent, "calendar");
|
||||
log.error(
|
||||
"updateEvent failed",
|
||||
safeStringify({ e, calEvent: getPiiFreeCalendarEvent(calEvent) })
|
||||
);
|
||||
if (e?.calError) {
|
||||
calError = e.calError;
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (!updatedResult) {
|
||||
logger.error(
|
||||
"updateEvent failed",
|
||||
safeStringify({
|
||||
success,
|
||||
bookingRefUid,
|
||||
credential: getPiiFreeCredential(credential),
|
||||
originalEvent: getPiiFreeCalendarEvent(calEvent),
|
||||
calError,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (Array.isArray(updatedResult)) {
|
||||
calWarnings = updatedResult.flatMap((res) => res.additionalInfo?.calWarnings ?? []);
|
||||
} else {
|
||||
calWarnings = updatedResult?.additionalInfo?.calWarnings || [];
|
||||
}
|
||||
|
||||
return {
|
||||
appName: credential.appId || "",
|
||||
type: credential.type,
|
||||
success,
|
||||
uid,
|
||||
updatedEvent: updatedResult,
|
||||
originalEvent: calEvent,
|
||||
calError,
|
||||
calWarnings,
|
||||
};
|
||||
};
|
||||
|
||||
export const deleteEvent = async ({
|
||||
credential,
|
||||
bookingRefUid,
|
||||
event,
|
||||
externalCalendarId,
|
||||
}: {
|
||||
credential: CredentialForCalendarService;
|
||||
bookingRefUid: string;
|
||||
event: CalendarEvent;
|
||||
externalCalendarId?: string | null;
|
||||
}): Promise<unknown> => {
|
||||
const calendar = await getCalendar(credential);
|
||||
log.debug(
|
||||
"Deleting calendar event",
|
||||
safeStringify({
|
||||
bookingRefUid,
|
||||
event: getPiiFreeCalendarEvent(event),
|
||||
})
|
||||
);
|
||||
if (calendar) {
|
||||
return calendar.deleteEvent(bookingRefUid, event, externalCalendarId);
|
||||
} else {
|
||||
log.error(
|
||||
"Could not do deleteEvent - No calendar adapter found",
|
||||
safeStringify({
|
||||
credential: getPiiFreeCredential(credential),
|
||||
event,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return Promise.resolve({});
|
||||
};
|
||||
|
||||
/**
|
||||
* Process the calendar event by generating description and removing attendees if needed
|
||||
*/
|
||||
const processEvent = (calEvent: CalendarEvent): CalendarServiceEvent => {
|
||||
// Generate the calendar event description
|
||||
const calendarEvent: CalendarServiceEvent = {
|
||||
...calEvent,
|
||||
calendarDescription: getRichDescription(calEvent),
|
||||
};
|
||||
|
||||
const isMeetLocationType = calEvent.location === MeetLocationType;
|
||||
|
||||
// Determine if the calendar event should include attendees
|
||||
const isOrganizerExempt = ORGANIZER_EMAIL_EXEMPT_DOMAINS?.split(",")
|
||||
.filter((domain) => domain.trim() !== "")
|
||||
.some((domain) => calEvent.organizer.email.toLowerCase().endsWith(domain.toLowerCase()));
|
||||
|
||||
if (calEvent.hideOrganizerEmail && !isOrganizerExempt && !isMeetLocationType) {
|
||||
calendarEvent.attendees = [];
|
||||
}
|
||||
|
||||
return calendarEvent;
|
||||
};
|
||||
@@ -14,7 +14,7 @@ import { deleteWebhookScheduledTriggers } from "@calcom/features/webhooks/lib/sc
|
||||
import { buildNonDelegationCredential } from "@calcom/lib/delegationCredential/server";
|
||||
import { isPrismaObjOrUndefined } from "@calcom/lib/isPrismaObj";
|
||||
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
|
||||
import { DailyLocationType } from "@calcom/lib/location";
|
||||
import { DailyLocationType } from "@calcom/app-store/locations";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { bookingMinimalSelect, prisma } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { DirectorySyncEvent, Group } from "@boxyhq/saml-jackson";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { addNewMembersToEventTypes } from "@calcom/lib/server/queries/teams";
|
||||
import { addNewMembersToEventTypes } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -12,7 +12,7 @@ import { getBooking } from "@calcom/features/bookings/lib/payment/getBooking";
|
||||
import stripe from "@calcom/features/ee/payments/server/stripe";
|
||||
import { getPlatformParams } from "@calcom/features/platform-oauth-client/get-platform-params";
|
||||
import { PlatformOAuthClientRepository } from "@calcom/features/platform-oauth-client/platform-oauth-client.repository";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/lib/EventManager";
|
||||
import EventManager, { placeholderCreatedEvent } from "@calcom/features/bookings/lib/EventManager";
|
||||
import { IS_PRODUCTION } from "@calcom/lib/constants";
|
||||
import { getErrorFromUnknown } from "@calcom/lib/errors";
|
||||
import { HttpError as HttpCode } from "@calcom/lib/http-error";
|
||||
|
||||
@@ -4,8 +4,8 @@ import { getAllCredentialsIncludeServiceAccountKey } from "@calcom/features/book
|
||||
import type { EventType } from "@calcom/features/bookings/lib/getAllCredentialsForUsersOnEvent/getAllCredentials";
|
||||
import { getVideoCallDetails } from "@calcom/features/bookings/lib/handleNewBooking/getVideoCallDetails";
|
||||
import { getVideoCallUrlFromCalEvent } from "@calcom/lib/CalEventParser";
|
||||
import EventManager from "@calcom/lib/EventManager";
|
||||
import type { EventManagerInitParams } from "@calcom/lib/EventManager";
|
||||
import EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import type { EventManagerInitParams } from "@calcom/features/bookings/lib/EventManager";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { BookingReferenceRepository } from "@calcom/lib/server/repository/bookingReference";
|
||||
|
||||
@@ -22,7 +22,7 @@ import { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import { SchedulingType, BookingStatus, WorkflowMethods } from "@calcom/prisma/enums";
|
||||
import { test } from "@calcom/web/test/fixtures/fixtures";
|
||||
|
||||
vi.mock("@calcom/lib/EventManager");
|
||||
vi.mock("@calcom/features/bookings/lib/EventManager");
|
||||
vi.mock("@calcom/app-store/utils", () => ({
|
||||
getAppFromSlug: vi.fn(),
|
||||
}));
|
||||
@@ -177,7 +177,7 @@ type ConferenceResult = {
|
||||
};
|
||||
|
||||
const mockEventManagerReschedule = async (config?: MockEventManagerConfig) => {
|
||||
const EventManager = (await import("@calcom/lib/EventManager")).default;
|
||||
const EventManager = (await import("@calcom/features/bookings/lib/EventManager")).default;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const spy = vi.spyOn(EventManager.prototype as any, "reschedule");
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
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 EventManager from "@calcom/lib/EventManager";
|
||||
import EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import { SENDER_NAME } from "@calcom/lib/constants";
|
||||
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/lib/delegationCredential/server";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
|
||||
@@ -21,7 +21,7 @@ import { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import { SchedulingType, BookingStatus, WorkflowMethods } from "@calcom/prisma/enums";
|
||||
import { test } from "@calcom/web/test/fixtures/fixtures";
|
||||
|
||||
vi.mock("@calcom/lib/EventManager");
|
||||
vi.mock("@calcom/features/bookings/lib/EventManager");
|
||||
|
||||
const testDestinationCalendar = {
|
||||
integration: "test-calendar",
|
||||
@@ -61,7 +61,7 @@ describe("roundRobinReassignment test", () => {
|
||||
|
||||
test("reassign new round robin organizer", async ({ emails }) => {
|
||||
const roundRobinReassignment = (await import("./roundRobinReassignment")).default;
|
||||
const EventManager = (await import("@calcom/lib/EventManager")).default;
|
||||
const EventManager = (await import("@calcom/features/bookings/lib/EventManager")).default;
|
||||
|
||||
const eventManagerSpy = vi.spyOn(EventManager.prototype as any, "reschedule");
|
||||
eventManagerSpy.mockResolvedValue({ referencesToCreate: [] });
|
||||
@@ -194,7 +194,7 @@ describe("roundRobinReassignment test", () => {
|
||||
// TODO: add fixed hosts test
|
||||
test("Reassign round robin host with fixed host as organizer", async () => {
|
||||
const roundRobinReassignment = (await import("./roundRobinReassignment")).default;
|
||||
const EventManager = (await import("@calcom/lib/EventManager")).default;
|
||||
const EventManager = (await import("@calcom/features/bookings/lib/EventManager")).default;
|
||||
|
||||
const eventManagerSpy = vi.spyOn(EventManager.prototype as any, "reschedule");
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ import AssignmentReasonRecorder, {
|
||||
RRReassignmentType,
|
||||
} from "@calcom/features/ee/round-robin/assignmentReason/AssignmentReasonRecorder";
|
||||
import { getEventName } from "@calcom/features/eventtypes/lib/eventNaming";
|
||||
import EventManager from "@calcom/lib/EventManager";
|
||||
import EventManager from "@calcom/features/bookings/lib/EventManager";
|
||||
import {
|
||||
enrichHostsWithDelegationCredentials,
|
||||
enrichUserWithDelegationCredentialsIncludeServiceAccountKey,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { SAMLSSORecord, OIDCSSORecord } from "@boxyhq/saml-jackson";
|
||||
|
||||
import { HOSTED_CAL_FEATURES } from "@calcom/lib/constants";
|
||||
import { isTeamAdmin } from "@calcom/lib/server/queries/teams";
|
||||
import { isTeamAdmin } from "@calcom/features/ee/teams/lib/queries";
|
||||
|
||||
export const samlDatabaseUrl = process.env.SAML_DATABASE_URL || "";
|
||||
export const isSAMLLoginEnabled = samlDatabaseUrl.length > 0;
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import type { ParsedUrlQuery } from "querystring";
|
||||
|
||||
/* eslint-disable */
|
||||
import { getCRMContactOwnerForRRLeadSkip } from "@calcom/app-store/_utils/CRMRoundRobinSkip";
|
||||
import {
|
||||
ROUTING_FORM_RESPONSE_ID_QUERY_STRING,
|
||||
ROUTING_FORM_QUEUED_RESPONSE_ID_QUERY_STRING,
|
||||
} from "@calcom/app-store/routing-forms/lib/constants";
|
||||
import { enabledAppSlugs } from "@calcom/app-store/routing-forms/lib/enabledApps";
|
||||
import type { AttributeRoutingConfig, LocalRoute } from "@calcom/app-store/routing-forms/types/types";
|
||||
import { zodRoutes as routesSchema } from "@calcom/app-store/routing-forms/zod";
|
||||
|
||||
/* eslint-enable */
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { RoutingFormResponseRepository } from "@calcom/lib/server/repository/formResponse";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getTeamMemberEmailFromCrm"] });
|
||||
|
||||
interface EventData {
|
||||
id: number;
|
||||
isInstantEvent: boolean;
|
||||
schedulingType: SchedulingType | null;
|
||||
metadata: Prisma.JsonValue | null;
|
||||
length: number;
|
||||
}
|
||||
|
||||
const returnNullValue = { email: null, recordType: null, crmAppSlug: null, recordId: null };
|
||||
|
||||
async function findUserByEmailWhoIsAHostOfEventType({
|
||||
email,
|
||||
eventTypeId,
|
||||
}: {
|
||||
email: string;
|
||||
eventTypeId: number;
|
||||
}) {
|
||||
return prisma.user.findFirst({
|
||||
where: {
|
||||
email,
|
||||
hosts: { some: { eventTypeId } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Returns the form response id or the queued response id */
|
||||
function getRoutingFormResponseIdFromQuery(query: ParsedUrlQuery) {
|
||||
const routingFormResponseIdAsNumber = Number(query[ROUTING_FORM_RESPONSE_ID_QUERY_STRING]);
|
||||
const routingFormResponseId = isNaN(routingFormResponseIdAsNumber) ? null : routingFormResponseIdAsNumber;
|
||||
|
||||
if (routingFormResponseId) return { routingFormResponseId, queuedFormResponseId: null };
|
||||
|
||||
const queuedFormResponseId = query[ROUTING_FORM_QUEUED_RESPONSE_ID_QUERY_STRING];
|
||||
if (queuedFormResponseId && typeof queuedFormResponseId === "string")
|
||||
return { queuedFormResponseId, routingFormResponseId: null };
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async function getAttributeRoutingConfig(
|
||||
data:
|
||||
| {
|
||||
routingFormResponseId?: number | null;
|
||||
queuedFormResponseId?: string | null;
|
||||
eventTypeId: number;
|
||||
}
|
||||
| {
|
||||
route: Pick<LocalRoute, "attributeRoutingConfig">;
|
||||
}
|
||||
) {
|
||||
if ("route" in data) {
|
||||
return data.route.attributeRoutingConfig ?? null;
|
||||
}
|
||||
const { routingFormResponseId, queuedFormResponseId } = data;
|
||||
const routingFormResponseRepository = new RoutingFormResponseRepository(prisma);
|
||||
|
||||
const routingFormResponseQuery = routingFormResponseId
|
||||
? await routingFormResponseRepository.findFormResponseIncludeForm({ routingFormResponseId })
|
||||
: queuedFormResponseId
|
||||
? await routingFormResponseRepository.findQueuedFormResponseIncludeForm({ queuedFormResponseId })
|
||||
: null;
|
||||
|
||||
if (!routingFormResponseQuery || !routingFormResponseQuery?.form.routes) return null;
|
||||
const parsedRoutes = routesSchema.safeParse(routingFormResponseQuery?.form.routes);
|
||||
|
||||
if (!parsedRoutes.success || !parsedRoutes.data) return null;
|
||||
|
||||
// Find the route with the attributeRoutingConfig
|
||||
const route = parsedRoutes.data.find((route) => {
|
||||
if ("action" in route) {
|
||||
return route.id === routingFormResponseQuery.chosenRouteId;
|
||||
}
|
||||
});
|
||||
|
||||
if (!route || !("attributeRoutingConfig" in route)) return null;
|
||||
// Get attributeRoutingConfig for the form
|
||||
const attributeRoutingConfig = route.attributeRoutingConfig;
|
||||
|
||||
if (!attributeRoutingConfig) return null;
|
||||
return attributeRoutingConfig;
|
||||
}
|
||||
|
||||
function getEnabledRoutingFormAppSlugFromQuery(query: ParsedUrlQuery) {
|
||||
// Determine if a routing form enabled app is in the query. Then pass it to the proper handler
|
||||
// Routing form apps will have the format cal.appSlug
|
||||
let enabledRoutingFormApp;
|
||||
|
||||
for (const key of Object.keys(query)) {
|
||||
const keySplit = key.split(".");
|
||||
|
||||
const appSlug = keySplit[1];
|
||||
|
||||
if (enabledAppSlugs.includes(appSlug)) {
|
||||
enabledRoutingFormApp = appSlug;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return enabledRoutingFormApp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses the owner of the contact directly from CRM
|
||||
*/
|
||||
async function getOwnerEmailFromCrm(
|
||||
eventData: EventData,
|
||||
email: string
|
||||
): Promise<{
|
||||
email: string | null;
|
||||
recordType: string | null;
|
||||
crmAppSlug: string | null;
|
||||
recordId: string | null;
|
||||
}> {
|
||||
const crmContactOwner = await getCRMContactOwnerForRRLeadSkip(email, eventData.metadata);
|
||||
|
||||
if (!crmContactOwner?.email) return returnNullValue;
|
||||
log.info(
|
||||
"[getOwnerEmailFromCrm] crmContactOwner",
|
||||
safeStringify({
|
||||
contactOwnerEmail: crmContactOwner.email,
|
||||
recordType: crmContactOwner.recordType,
|
||||
email,
|
||||
eventTypeId: eventData.id,
|
||||
})
|
||||
);
|
||||
// Determine if the contactOwner is a part of the event type
|
||||
const contactOwnerQuery = await findUserByEmailWhoIsAHostOfEventType({
|
||||
email: crmContactOwner.email,
|
||||
eventTypeId: eventData.id,
|
||||
});
|
||||
if (!contactOwnerQuery) {
|
||||
log.info(
|
||||
"[getOwnerEmailFromCrm] contactOwner not found as host, not considering it",
|
||||
safeStringify({ contactOwnerEmail: crmContactOwner.email, email, eventTypeId: eventData.id })
|
||||
);
|
||||
return returnNullValue;
|
||||
}
|
||||
return crmContactOwner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles custom lookup field logic
|
||||
*/
|
||||
async function getTeamMemberEmailUsingRoutingFormHandler({
|
||||
bookerEmail,
|
||||
eventTypeId,
|
||||
attributeRoutingConfig,
|
||||
crmAppSlug,
|
||||
}: {
|
||||
bookerEmail: string;
|
||||
eventTypeId: number;
|
||||
attributeRoutingConfig: AttributeRoutingConfig | null;
|
||||
crmAppSlug: string;
|
||||
}) {
|
||||
const nullReturnValue = { email: null, skipContactOwner: false, recordType: "", recordId: "" };
|
||||
|
||||
if (!attributeRoutingConfig) return nullReturnValue;
|
||||
|
||||
// If the skipContactOwner is enabled then don't return an team member email
|
||||
if (attributeRoutingConfig.skipContactOwner) return { ...nullReturnValue, skipContactOwner: true };
|
||||
|
||||
const appBookingFormHandler = (await import("@calcom/app-store/routing-forms/appBookingFormHandler"))
|
||||
.default;
|
||||
const appHandler = appBookingFormHandler[crmAppSlug];
|
||||
if (!appHandler) return nullReturnValue;
|
||||
|
||||
const {
|
||||
email: userEmail,
|
||||
recordType,
|
||||
recordId,
|
||||
} = await appHandler(bookerEmail, attributeRoutingConfig, eventTypeId);
|
||||
|
||||
if (!userEmail) return nullReturnValue;
|
||||
|
||||
// Determine if the user is a part of the event type
|
||||
const userQuery = await findUserByEmailWhoIsAHostOfEventType({ email: userEmail, eventTypeId });
|
||||
|
||||
if (!userQuery) return nullReturnValue;
|
||||
|
||||
return { ...nullReturnValue, email: userEmail, recordType, recordId };
|
||||
}
|
||||
|
||||
async function getTeamMemberEmailForResponseOrContact({
|
||||
bookerEmail,
|
||||
eventData,
|
||||
routingFormResponseId,
|
||||
queuedFormResponseId,
|
||||
chosenRoute,
|
||||
crmAppSlug,
|
||||
}: {
|
||||
bookerEmail: string;
|
||||
eventData: EventData;
|
||||
routingFormResponseId?: number | null;
|
||||
queuedFormResponseId?: string | null;
|
||||
/**
|
||||
* If provided, we won't go look for the route from DB.
|
||||
*/
|
||||
chosenRoute?: LocalRoute;
|
||||
crmAppSlug?: string;
|
||||
}): Promise<{
|
||||
email: string | null;
|
||||
recordType: string | null;
|
||||
crmAppSlug: string | null;
|
||||
recordId: string | null;
|
||||
}> {
|
||||
const eventTypeId = eventData.id;
|
||||
if (eventData.schedulingType !== SchedulingType.ROUND_ROBIN) return returnNullValue;
|
||||
|
||||
const attributeRoutingConfigGetterData =
|
||||
routingFormResponseId || queuedFormResponseId
|
||||
? { routingFormResponseId, queuedFormResponseId, eventTypeId }
|
||||
: chosenRoute
|
||||
? { route: chosenRoute }
|
||||
: null;
|
||||
|
||||
// If we have found crmAppSlug, it means that the CRM App in the routing-form will handle the logic
|
||||
if (attributeRoutingConfigGetterData && crmAppSlug) {
|
||||
log.debug(
|
||||
"Using CRM App handler in routing-forms",
|
||||
safeStringify({ attributeRoutingConfigGetterData, crmAppSlug })
|
||||
);
|
||||
const attributeRoutingConfig = await getAttributeRoutingConfig(attributeRoutingConfigGetterData);
|
||||
const { email, skipContactOwner, recordType, recordId } = await getTeamMemberEmailUsingRoutingFormHandler(
|
||||
{
|
||||
bookerEmail,
|
||||
eventTypeId,
|
||||
attributeRoutingConfig,
|
||||
crmAppSlug,
|
||||
}
|
||||
);
|
||||
|
||||
if (skipContactOwner) return returnNullValue;
|
||||
if (email) return { email, recordType, crmAppSlug, recordId };
|
||||
} else {
|
||||
log.debug("Getting the contact owner email from CRM");
|
||||
return await getOwnerEmailFromCrm(eventData, bookerEmail);
|
||||
}
|
||||
|
||||
return returnNullValue;
|
||||
}
|
||||
|
||||
export async function getTeamMemberEmailForResponseOrContactUsingUrlQuery({
|
||||
query,
|
||||
eventData,
|
||||
chosenRoute,
|
||||
}: {
|
||||
query: ParsedUrlQuery;
|
||||
eventData: EventData;
|
||||
chosenRoute?: LocalRoute;
|
||||
}): Promise<{
|
||||
email: string | null;
|
||||
recordType: string | null;
|
||||
crmAppSlug: string | null;
|
||||
recordId: string | null;
|
||||
}> {
|
||||
// Without email no lookup is possible
|
||||
if (!query.email || typeof query.email !== "string") {
|
||||
return returnNullValue;
|
||||
}
|
||||
|
||||
log.debug("getTeamMemberEmailForResponseOrContactUsingUrlQuery", safeStringify({ query }));
|
||||
|
||||
const crmAppSlug = getEnabledRoutingFormAppSlugFromQuery(query);
|
||||
|
||||
const routingFormResponseIdAndQueuedFormResponseId = getRoutingFormResponseIdFromQuery(query);
|
||||
|
||||
return await getTeamMemberEmailForResponseOrContact({
|
||||
bookerEmail: query.email,
|
||||
eventData,
|
||||
chosenRoute,
|
||||
crmAppSlug,
|
||||
...(routingFormResponseIdAndQueuedFormResponseId
|
||||
? { ...routingFormResponseIdAndQueuedFormResponseId }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,673 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { getAppFromSlug } from "@calcom/app-store/utils";
|
||||
import { DATABASE_CHUNK_SIZE } from "@calcom/lib/constants";
|
||||
import { getBookerBaseUrlSync } from "@calcom/lib/getBookerUrl/client";
|
||||
import { parseBookingLimit } from "@calcom/lib/intervalLimits/isBookingLimits";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTeam, getOrg } from "@calcom/lib/server/repository/team";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { baseEventTypeSelect } from "@calcom/prisma/selects";
|
||||
import {
|
||||
EventTypeMetaDataSchema,
|
||||
allManagedEventTypeProps,
|
||||
unlockedManagedEventTypeProps,
|
||||
eventTypeLocations,
|
||||
} from "@calcom/prisma/zod-utils";
|
||||
import { EventTypeSchema } from "@calcom/prisma/zod/modelSchema/EventTypeSchema";
|
||||
|
||||
export type TeamWithMembers = Awaited<ReturnType<typeof getTeamWithMembers>>;
|
||||
|
||||
export async function getTeamWithMembers(args: {
|
||||
id?: number;
|
||||
slug?: string;
|
||||
userId?: number;
|
||||
orgSlug?: string | null;
|
||||
isTeamView?: boolean;
|
||||
currentOrg?: Pick<Team, "id"> | null;
|
||||
/**
|
||||
* If true, means that you are fetching an organization and not a team
|
||||
*/
|
||||
isOrgView?: boolean;
|
||||
}) {
|
||||
const { id, slug, currentOrg: _currentOrg, userId, orgSlug, isTeamView, isOrgView } = args;
|
||||
|
||||
// This should improve performance saving already app data found.
|
||||
const appDataMap = new Map();
|
||||
const userSelect = {
|
||||
username: true,
|
||||
email: true,
|
||||
name: true,
|
||||
avatarUrl: true,
|
||||
id: true,
|
||||
bio: true,
|
||||
teams: {
|
||||
select: {
|
||||
team: {
|
||||
select: {
|
||||
slug: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
credentials: {
|
||||
select: {
|
||||
app: {
|
||||
select: {
|
||||
slug: true,
|
||||
categories: true,
|
||||
},
|
||||
},
|
||||
destinationCalendars: {
|
||||
select: {
|
||||
externalId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} satisfies Prisma.UserSelect;
|
||||
let lookupBy;
|
||||
|
||||
if (id) {
|
||||
lookupBy = { id, havingMemberWithId: userId };
|
||||
} else if (slug) {
|
||||
lookupBy = { slug, havingMemberWithId: userId };
|
||||
} else {
|
||||
throw new Error("Must provide either id or slug");
|
||||
}
|
||||
|
||||
const arg = {
|
||||
lookupBy,
|
||||
forOrgWithSlug: orgSlug ?? null,
|
||||
isOrg: !!isOrgView,
|
||||
teamSelect: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
isOrganization: true,
|
||||
logoUrl: true,
|
||||
bio: true,
|
||||
hideBranding: true,
|
||||
hideBookATeamMember: true,
|
||||
isPrivate: true,
|
||||
metadata: true,
|
||||
parent: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
isPrivate: true,
|
||||
isOrganization: true,
|
||||
logoUrl: true,
|
||||
metadata: true,
|
||||
organizationSettings: {
|
||||
select: {
|
||||
allowSEOIndexing: true,
|
||||
orgProfileRedirectsToVerifiedDomain: true,
|
||||
orgAutoAcceptEmail: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
parentId: true,
|
||||
children: {
|
||||
select: {
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
members: {
|
||||
select: {
|
||||
accepted: true,
|
||||
role: true,
|
||||
disableImpersonation: true,
|
||||
user: {
|
||||
select: userSelect,
|
||||
},
|
||||
},
|
||||
},
|
||||
theme: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
eventTypes: {
|
||||
where: {
|
||||
hidden: false,
|
||||
schedulingType: {
|
||||
not: SchedulingType.MANAGED,
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
] as Prisma.EventTypeOrderByWithRelationInput[],
|
||||
select: {
|
||||
hosts: {
|
||||
select: {
|
||||
user: {
|
||||
select: userSelect,
|
||||
},
|
||||
},
|
||||
},
|
||||
metadata: true,
|
||||
...baseEventTypeSelect,
|
||||
},
|
||||
},
|
||||
inviteTokens: {
|
||||
select: {
|
||||
token: true,
|
||||
expires: true,
|
||||
expiresInDays: true,
|
||||
identifier: true,
|
||||
},
|
||||
},
|
||||
organizationSettings: {
|
||||
select: {
|
||||
allowSEOIndexing: true,
|
||||
orgProfileRedirectsToVerifiedDomain: true,
|
||||
orgAutoAcceptEmail: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
const teamOrOrg = isOrgView ? await getOrg(arg) : await getTeam(arg);
|
||||
|
||||
if (!teamOrOrg) return null;
|
||||
|
||||
const teamOrOrgMemberships = [];
|
||||
const userRepo = new UserRepository(prisma);
|
||||
for (const membership of teamOrOrg.members) {
|
||||
teamOrOrgMemberships.push({
|
||||
...membership,
|
||||
user: await userRepo.enrichUserWithItsProfile({
|
||||
user: membership.user,
|
||||
}),
|
||||
});
|
||||
}
|
||||
const members = teamOrOrgMemberships.map((m) => {
|
||||
const { credentials, profile, ...restUser } = m.user;
|
||||
return {
|
||||
...restUser,
|
||||
username: profile?.username ?? restUser.username,
|
||||
role: m.role,
|
||||
profile: profile,
|
||||
organizationId: profile?.organizationId ?? null,
|
||||
organization: profile?.organization,
|
||||
accepted: m.accepted,
|
||||
disableImpersonation: m.disableImpersonation,
|
||||
subteams: orgSlug
|
||||
? m.user.teams
|
||||
.filter((membership) => membership.team.id !== teamOrOrg.id)
|
||||
.map((membership) => membership.team.slug)
|
||||
: null,
|
||||
bookerUrl: getBookerBaseUrlSync(profile?.organization?.slug || ""),
|
||||
connectedApps: !isTeamView
|
||||
? credentials?.map((cred) => {
|
||||
const appSlug = cred.app?.slug;
|
||||
let appData = appDataMap.get(appSlug);
|
||||
|
||||
if (!appData) {
|
||||
appData = getAppFromSlug(appSlug);
|
||||
appDataMap.set(appSlug, appData);
|
||||
}
|
||||
|
||||
const isCalendar = cred?.app?.categories?.includes("calendar") ?? false;
|
||||
const externalId = isCalendar ? cred.destinationCalendars?.[0]?.externalId : null;
|
||||
return {
|
||||
name: appData?.name ?? null,
|
||||
logo: appData?.logo ?? null,
|
||||
app: cred.app,
|
||||
externalId: externalId ?? null,
|
||||
};
|
||||
})
|
||||
: null,
|
||||
};
|
||||
});
|
||||
|
||||
const eventTypesWithUsersUserProfile = [];
|
||||
for (const eventType of teamOrOrg.eventTypes) {
|
||||
const usersWithUserProfile = [];
|
||||
for (const { user } of eventType.hosts) {
|
||||
usersWithUserProfile.push(
|
||||
await userRepo.enrichUserWithItsProfile({
|
||||
user,
|
||||
})
|
||||
);
|
||||
}
|
||||
eventTypesWithUsersUserProfile.push({
|
||||
...eventType,
|
||||
users: usersWithUserProfile,
|
||||
});
|
||||
}
|
||||
const eventTypes = eventTypesWithUsersUserProfile.map((eventType) => ({
|
||||
...eventType,
|
||||
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
|
||||
}));
|
||||
|
||||
// Don't leak invite tokens to the frontend
|
||||
const { inviteTokens, ...teamWithoutInviteTokens } = teamOrOrg;
|
||||
|
||||
// Don't leak stripe payment ids
|
||||
const teamMetadata = teamOrOrg.metadata;
|
||||
const {
|
||||
paymentId: _,
|
||||
subscriptionId: __,
|
||||
subscriptionItemId: ___,
|
||||
...restTeamMetadata
|
||||
} = teamMetadata || {};
|
||||
|
||||
return {
|
||||
...teamWithoutInviteTokens,
|
||||
...(teamWithoutInviteTokens.logoUrl ? { logo: teamWithoutInviteTokens.logoUrl } : {}),
|
||||
/** To prevent breaking we only return non-email attached token here, if we have one */
|
||||
inviteToken: inviteTokens.find(
|
||||
(token) =>
|
||||
token.identifier === `invite-link-for-teamId-${teamOrOrg.id}` &&
|
||||
token.expires > new Date(new Date().setHours(24))
|
||||
),
|
||||
metadata: restTeamMetadata,
|
||||
eventTypes: !isOrgView ? eventTypes : null,
|
||||
members,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getTeamWithoutMembers(args: {
|
||||
id?: number;
|
||||
slug?: string;
|
||||
userId?: number;
|
||||
orgSlug?: string | null;
|
||||
/**
|
||||
* If true, means that you are fetching an organization and not a team
|
||||
*/
|
||||
isOrgView?: boolean;
|
||||
}) {
|
||||
const { id, slug, userId, orgSlug, isOrgView } = args;
|
||||
|
||||
let lookupBy;
|
||||
|
||||
if (id) {
|
||||
lookupBy = { id, havingMemberWithId: userId };
|
||||
} else if (slug) {
|
||||
lookupBy = { slug, havingMemberWithId: userId };
|
||||
} else {
|
||||
throw new Error("Must provide either id or slug");
|
||||
}
|
||||
|
||||
const arg = {
|
||||
lookupBy,
|
||||
forOrgWithSlug: orgSlug ?? null,
|
||||
isOrg: !!isOrgView,
|
||||
teamSelect: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
isOrganization: true,
|
||||
logoUrl: true,
|
||||
bio: true,
|
||||
hideBranding: true,
|
||||
hideBookATeamMember: true,
|
||||
hideTeamProfileLink: true,
|
||||
isPrivate: true,
|
||||
metadata: true,
|
||||
bookingLimits: true,
|
||||
rrResetInterval: true,
|
||||
rrTimestampBasis: true,
|
||||
includeManagedEventsInLimits: true,
|
||||
parent: {
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
isPrivate: true,
|
||||
isOrganization: true,
|
||||
logoUrl: true,
|
||||
metadata: true,
|
||||
},
|
||||
},
|
||||
parentId: true,
|
||||
children: {
|
||||
select: {
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
theme: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
inviteTokens: {
|
||||
select: {
|
||||
token: true,
|
||||
expires: true,
|
||||
expiresInDays: true,
|
||||
identifier: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
const teamOrOrg = isOrgView ? await getOrg(arg) : await getTeam(arg);
|
||||
|
||||
if (!teamOrOrg) return null;
|
||||
|
||||
// Don't leak invite tokens to the frontend
|
||||
const { inviteTokens, ...teamWithoutInviteTokens } = teamOrOrg;
|
||||
|
||||
// Don't leak stripe payment ids
|
||||
const teamMetadata = teamOrOrg.metadata;
|
||||
const {
|
||||
paymentId: _,
|
||||
subscriptionId: __,
|
||||
subscriptionItemId: ___,
|
||||
...restTeamMetadata
|
||||
} = teamMetadata || {};
|
||||
|
||||
return {
|
||||
...teamWithoutInviteTokens,
|
||||
...(teamWithoutInviteTokens.logoUrl ? { logo: teamWithoutInviteTokens.logoUrl } : {}),
|
||||
/** To prevent breaking we only return non-email attached token here, if we have one */
|
||||
inviteToken: inviteTokens.find(
|
||||
(token) =>
|
||||
token.identifier === `invite-link-for-teamId-${teamOrOrg.id}` &&
|
||||
token.expires > new Date(new Date().setHours(24))
|
||||
),
|
||||
metadata: restTeamMetadata,
|
||||
bookingLimits: parseBookingLimit(teamOrOrg.bookingLimits),
|
||||
};
|
||||
}
|
||||
|
||||
// also returns team
|
||||
export async function isTeamAdmin(userId: number, teamId: number) {
|
||||
const team = await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId,
|
||||
accepted: true,
|
||||
OR: [{ role: "ADMIN" }, { role: "OWNER" }],
|
||||
},
|
||||
include: {
|
||||
team: {
|
||||
select: {
|
||||
metadata: true,
|
||||
parentId: true,
|
||||
isOrganization: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!team) return false;
|
||||
return team;
|
||||
}
|
||||
|
||||
export async function isTeamOwner(userId: number, teamId: number) {
|
||||
return !!(await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId,
|
||||
accepted: true,
|
||||
role: "OWNER",
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export async function isTeamMember(userId: number, teamId: number) {
|
||||
return !!(await prisma.membership.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
teamId,
|
||||
accepted: true,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function generateNewChildEventTypeDataForDB({
|
||||
eventType,
|
||||
userId,
|
||||
includeWorkflow = true,
|
||||
includeUserConnect = true,
|
||||
}: {
|
||||
eventType: Omit<
|
||||
Prisma.EventTypeGetPayload<{ select: typeof allManagedEventTypeProps & { id: true } }>,
|
||||
"locations"
|
||||
> & { locations: Prisma.JsonValue | null };
|
||||
userId: number;
|
||||
includeWorkflow?: boolean;
|
||||
includeUserConnect?: boolean;
|
||||
}) {
|
||||
const allManagedEventTypePropsZod = EventTypeSchema.pick(allManagedEventTypeProps).extend({
|
||||
bookingFields: EventTypeSchema.shape.bookingFields.nullish(),
|
||||
locations: z
|
||||
.preprocess((val: unknown) => (val === null ? undefined : val), eventTypeLocations)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const managedEventTypeValues = allManagedEventTypePropsZod
|
||||
.omit(unlockedManagedEventTypeProps)
|
||||
.parse(eventType);
|
||||
|
||||
// Define the values for unlocked properties to use on creation, not updation
|
||||
const unlockedEventTypeValues = allManagedEventTypePropsZod
|
||||
.pick(unlockedManagedEventTypeProps)
|
||||
.parse(eventType);
|
||||
|
||||
// Calculate if there are new workflows for which assigned members will get too
|
||||
const currentWorkflowIds = Array.isArray(eventType.workflows)
|
||||
? eventType.workflows.map((wf) => wf.workflowId)
|
||||
: [];
|
||||
|
||||
return {
|
||||
...managedEventTypeValues,
|
||||
...unlockedEventTypeValues,
|
||||
bookingLimits: (managedEventTypeValues.bookingLimits as unknown as Prisma.InputJsonObject) ?? undefined,
|
||||
recurringEvent: (managedEventTypeValues.recurringEvent as unknown as Prisma.InputJsonValue) ?? undefined,
|
||||
metadata: (managedEventTypeValues.metadata as Prisma.InputJsonValue) ?? undefined,
|
||||
bookingFields: (managedEventTypeValues.bookingFields as Prisma.InputJsonValue) ?? undefined,
|
||||
durationLimits: (managedEventTypeValues.durationLimits as Prisma.InputJsonValue) ?? undefined,
|
||||
eventTypeColor: (managedEventTypeValues.eventTypeColor as Prisma.InputJsonValue) ?? undefined,
|
||||
rrSegmentQueryValue: (managedEventTypeValues.rrSegmentQueryValue as Prisma.InputJsonValue) ?? undefined,
|
||||
onlyShowFirstAvailableSlot: managedEventTypeValues.onlyShowFirstAvailableSlot ?? false,
|
||||
userId,
|
||||
...(includeUserConnect && {
|
||||
users: {
|
||||
connect: [{ id: userId }],
|
||||
},
|
||||
}),
|
||||
parentId: eventType.id,
|
||||
hidden: false,
|
||||
...(includeWorkflow && {
|
||||
workflows: currentWorkflowIds && {
|
||||
create: currentWorkflowIds.map((wfId) => ({ workflowId: wfId })),
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async function getEventTypesToAddNewMembers(teamId: number) {
|
||||
return await prisma.eventType.findMany({
|
||||
where: {
|
||||
team: { id: teamId },
|
||||
assignAllTeamMembers: true,
|
||||
},
|
||||
select: {
|
||||
...allManagedEventTypeProps,
|
||||
id: true,
|
||||
schedulingType: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateNewTeamMemberEventTypes(userId: number, teamId: number) {
|
||||
const eventTypesToAdd = await getEventTypesToAddNewMembers(teamId);
|
||||
|
||||
eventTypesToAdd.length > 0 &&
|
||||
(await prisma.$transaction(
|
||||
eventTypesToAdd.map((eventType) => {
|
||||
if (eventType.schedulingType === "MANAGED") {
|
||||
return prisma.eventType.create({
|
||||
data: generateNewChildEventTypeDataForDB({
|
||||
eventType,
|
||||
userId,
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
return prisma.eventType.update({
|
||||
where: { id: eventType.id },
|
||||
data: { hosts: { create: [{ userId, isFixed: eventType.schedulingType === "COLLECTIVE" }] } },
|
||||
});
|
||||
}
|
||||
})
|
||||
));
|
||||
}
|
||||
|
||||
export async function addNewMembersToEventTypes({ userIds, teamId }: { userIds: number[]; teamId: number }) {
|
||||
const log = logger.getSubLogger({
|
||||
prefix: ["addNewMembersToEventTypes"],
|
||||
});
|
||||
|
||||
const eventTypesToAdd = await getEventTypesToAddNewMembers(teamId);
|
||||
|
||||
const managedEventTypes = eventTypesToAdd.filter((eventType) => eventType.schedulingType === "MANAGED");
|
||||
const teamEventTypes = eventTypesToAdd.filter((eventType) => eventType.schedulingType !== "MANAGED");
|
||||
|
||||
await Promise.allSettled([
|
||||
prisma.eventType
|
||||
.createMany({
|
||||
data: managedEventTypes
|
||||
.map((eventType) =>
|
||||
userIds.map((userId) =>
|
||||
generateNewChildEventTypeDataForDB({
|
||||
eventType,
|
||||
userId,
|
||||
includeWorkflow: false,
|
||||
includeUserConnect: false,
|
||||
})
|
||||
)
|
||||
)
|
||||
.flat(),
|
||||
skipDuplicates: true,
|
||||
})
|
||||
.catch((error) => {
|
||||
log.error(
|
||||
`Failed to add new members to managed event types`,
|
||||
safeStringify({
|
||||
teamId,
|
||||
error,
|
||||
})
|
||||
);
|
||||
}),
|
||||
prisma.host
|
||||
.createMany({
|
||||
data: teamEventTypes
|
||||
.map((eventType) => {
|
||||
return userIds.map((userId) => {
|
||||
return {
|
||||
userId,
|
||||
eventTypeId: eventType.id,
|
||||
isFixed: eventType.schedulingType === "COLLECTIVE",
|
||||
};
|
||||
});
|
||||
})
|
||||
.flat(),
|
||||
skipDuplicates: true,
|
||||
})
|
||||
.catch((error) => {
|
||||
log.error(
|
||||
`Failed to add new members as hosts`,
|
||||
safeStringify({
|
||||
teamId,
|
||||
error,
|
||||
})
|
||||
);
|
||||
}),
|
||||
]);
|
||||
|
||||
// Connect to users and workflows
|
||||
const createdChildrenEventTypes = await prisma.eventType.findMany({
|
||||
where: {
|
||||
userId: {
|
||||
in: userIds,
|
||||
},
|
||||
parent: {
|
||||
id: {
|
||||
in: managedEventTypes.map((eventType) => eventType.id),
|
||||
},
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
workflows: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (createdChildrenEventTypes.length > 0) {
|
||||
await Promise.allSettled([
|
||||
prisma.workflowsOnEventTypes
|
||||
.createMany({
|
||||
data: createdChildrenEventTypes
|
||||
.map((eventType) =>
|
||||
eventType.workflows.map((workflow) => ({
|
||||
eventTypeId: eventType.id,
|
||||
workflowId: workflow.id,
|
||||
}))
|
||||
)
|
||||
.flat(),
|
||||
skipDuplicates: true,
|
||||
})
|
||||
.catch((error) => {
|
||||
log.error(
|
||||
`Failed to connect new children event types to workflows`,
|
||||
safeStringify({
|
||||
teamId,
|
||||
error,
|
||||
})
|
||||
);
|
||||
}),
|
||||
]);
|
||||
// Connect children event types to users
|
||||
for (let i = 0; i < createdChildrenEventTypes.length; i += DATABASE_CHUNK_SIZE) {
|
||||
const childrenEventTypeBatch = createdChildrenEventTypes.slice(i, i + DATABASE_CHUNK_SIZE);
|
||||
|
||||
await Promise.allSettled([
|
||||
childrenEventTypeBatch.map((childEventType) => {
|
||||
if (!childEventType.userId) return;
|
||||
return prisma.eventType
|
||||
.update({
|
||||
where: {
|
||||
id: childEventType.id,
|
||||
},
|
||||
data: {
|
||||
users: {
|
||||
connect: [{ id: childEventType.userId }],
|
||||
},
|
||||
},
|
||||
})
|
||||
.catch((error) => {
|
||||
log.error(
|
||||
`Failed to connect new children event types to users`,
|
||||
safeStringify({
|
||||
teamId,
|
||||
childEventTypeId: childEventType.id,
|
||||
userId: childEventType.userId,
|
||||
error,
|
||||
})
|
||||
);
|
||||
});
|
||||
}),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
import prismock from "../../../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { mockNoTranslations } from "@calcom/web/test/utils/bookingScenario/bookingScenario";
|
||||
|
||||
import { describe, test, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
import { getRawEventType } from "./getEventTypeById";
|
||||
|
||||
vi.mock("@calcom/lib/server/i18n", () => ({
|
||||
getTranslation: (key: string) => () => key,
|
||||
}));
|
||||
|
||||
describe("getRawEventType", () => {
|
||||
beforeEach(() => {
|
||||
mockNoTranslations();
|
||||
});
|
||||
|
||||
describe("Regular user access", () => {
|
||||
test("should fetch event type when user owns it", async () => {
|
||||
const user = await prismock.user.create({
|
||||
data: {
|
||||
username: "testuser",
|
||||
email: "[email protected]",
|
||||
},
|
||||
});
|
||||
|
||||
const eventType = await prismock.eventType.create({
|
||||
data: {
|
||||
title: "Test Event Type",
|
||||
slug: "test-event",
|
||||
length: 30,
|
||||
userId: user.id,
|
||||
users: {
|
||||
connect: [{ id: user.id }],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await getRawEventType({
|
||||
userId: user.id,
|
||||
eventTypeId: eventType.id,
|
||||
isUserOrganizationAdmin: false,
|
||||
currentOrganizationId: null,
|
||||
prisma: prismock as any,
|
||||
});
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.id).toBe(eventType.id);
|
||||
expect(result?.title).toBe("Test Event Type");
|
||||
expect(result?.userId).toBe(user.id);
|
||||
});
|
||||
|
||||
test.skip("should return null when user doesn't have access to event type", async () => {
|
||||
// note(Lauris): test skipped because somehow when creating event type eventType.users includes otherUser
|
||||
const owner = await prismock.user.create({
|
||||
data: {
|
||||
username: "owner",
|
||||
email: "[email protected]",
|
||||
},
|
||||
});
|
||||
|
||||
const otherUser = await prismock.user.create({
|
||||
data: {
|
||||
username: "otheruser",
|
||||
email: "[email protected]",
|
||||
},
|
||||
});
|
||||
|
||||
const eventType = await prismock.eventType.create({
|
||||
data: {
|
||||
title: "Owner's Event Type",
|
||||
slug: "owner-event",
|
||||
length: 30,
|
||||
userId: owner.id,
|
||||
users: {
|
||||
connect: [{ id: owner.id }],
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
|
||||
await prismock.user.update({
|
||||
where: {
|
||||
id: otherUser.id,
|
||||
},
|
||||
data: {
|
||||
eventTypes: {
|
||||
disconnect: [{ id: eventType.id }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const result = await getRawEventType({
|
||||
userId: otherUser.id,
|
||||
eventTypeId: eventType.id,
|
||||
isUserOrganizationAdmin: false,
|
||||
currentOrganizationId: null,
|
||||
prisma: prismock as any,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Organization admin access", () => {
|
||||
test("should fetch team event type when user is org admin", async () => {
|
||||
const organization = await prismock.team.create({
|
||||
data: {
|
||||
id: 100,
|
||||
name: "Test Organization",
|
||||
slug: "test-org",
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
|
||||
const team = await prismock.team.create({
|
||||
data: {
|
||||
id: 200,
|
||||
name: "Test Team",
|
||||
slug: "test-team",
|
||||
parentId: organization.id,
|
||||
},
|
||||
});
|
||||
|
||||
const orgAdmin = await prismock.user.create({
|
||||
data: {
|
||||
username: "orgadmin",
|
||||
email: "[email protected]",
|
||||
organizationId: organization.id,
|
||||
},
|
||||
});
|
||||
|
||||
const eventType = await prismock.eventType.create({
|
||||
data: {
|
||||
title: "Team Event Type",
|
||||
slug: "team-event",
|
||||
length: 30,
|
||||
teamId: team.id,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await getRawEventType({
|
||||
userId: orgAdmin.id,
|
||||
eventTypeId: eventType.id,
|
||||
isUserOrganizationAdmin: true,
|
||||
currentOrganizationId: organization.id,
|
||||
prisma: prismock as any,
|
||||
});
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.id).toBe(eventType.id);
|
||||
expect(result?.title).toBe("Team Event Type");
|
||||
expect(result?.teamId).toBe(team.id);
|
||||
});
|
||||
|
||||
test("should fetch user event type when user is org admin and user belongs to org", async () => {
|
||||
const organization = await prismock.team.create({
|
||||
data: {
|
||||
id: 101,
|
||||
name: "Test Organization 2",
|
||||
slug: "test-org-2",
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
|
||||
const orgAdmin = await prismock.user.create({
|
||||
data: {
|
||||
username: "orgadmin2",
|
||||
email: "[email protected]",
|
||||
organizationId: organization.id,
|
||||
},
|
||||
});
|
||||
|
||||
const orgUser = await prismock.user.create({
|
||||
data: {
|
||||
username: "orguser",
|
||||
email: "[email protected]",
|
||||
organizationId: organization.id,
|
||||
profiles: {
|
||||
create: {
|
||||
organizationId: organization.id,
|
||||
uid: "orguser",
|
||||
username: "orguser",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const eventType = await prismock.eventType.create({
|
||||
data: {
|
||||
title: "Org User Event Type",
|
||||
slug: "org-user-event",
|
||||
length: 30,
|
||||
userId: orgUser.id,
|
||||
users: {
|
||||
connect: [{ id: orgUser.id }],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
users: true,
|
||||
owner: true,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await getRawEventType({
|
||||
userId: orgAdmin.id,
|
||||
eventTypeId: eventType.id,
|
||||
isUserOrganizationAdmin: true,
|
||||
currentOrganizationId: organization.id,
|
||||
prisma: prismock as any,
|
||||
});
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.id).toBe(eventType.id);
|
||||
expect(result?.title).toBe("Org User Event Type");
|
||||
expect(result?.userId).toBe(orgUser.id);
|
||||
});
|
||||
|
||||
test("should return null when org admin tries to access event type from different org", async () => {
|
||||
const org1 = await prismock.team.create({
|
||||
data: {
|
||||
id: 102,
|
||||
name: "Organization 1",
|
||||
slug: "org-1",
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
|
||||
const org2 = await prismock.team.create({
|
||||
data: {
|
||||
id: 103,
|
||||
name: "Organization 2",
|
||||
slug: "org-2",
|
||||
isOrganization: true,
|
||||
},
|
||||
});
|
||||
|
||||
const team1 = await prismock.team.create({
|
||||
data: {
|
||||
id: 201,
|
||||
name: "Team in Org 1",
|
||||
slug: "team-org-1",
|
||||
parentId: org1.id,
|
||||
},
|
||||
});
|
||||
|
||||
const org2Admin = await prismock.user.create({
|
||||
data: {
|
||||
username: "org2admin",
|
||||
email: "[email protected]",
|
||||
organizationId: org2.id,
|
||||
},
|
||||
});
|
||||
|
||||
const eventType = await prismock.eventType.create({
|
||||
data: {
|
||||
title: "Org 1 Team Event",
|
||||
slug: "org1-team-event",
|
||||
length: 30,
|
||||
teamId: team1.id,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
users: true,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await getRawEventType({
|
||||
userId: org2Admin.id,
|
||||
eventTypeId: eventType.id,
|
||||
isUserOrganizationAdmin: true,
|
||||
currentOrganizationId: org2.id,
|
||||
prisma: prismock as any,
|
||||
});
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
test("should fallback to regular user access when org admin flag is true but no organizationId", async () => {
|
||||
const user = await prismock.user.create({
|
||||
data: {
|
||||
username: "regularuser",
|
||||
email: "[email protected]",
|
||||
},
|
||||
});
|
||||
|
||||
const eventType = await prismock.eventType.create({
|
||||
data: {
|
||||
title: "Regular User Event",
|
||||
slug: "regular-user-event",
|
||||
length: 30,
|
||||
userId: user.id,
|
||||
users: {
|
||||
connect: [{ id: user.id }],
|
||||
},
|
||||
},
|
||||
include: {
|
||||
users: true,
|
||||
owner: true,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await getRawEventType({
|
||||
userId: user.id,
|
||||
eventTypeId: eventType.id,
|
||||
isUserOrganizationAdmin: true,
|
||||
currentOrganizationId: null,
|
||||
prisma: prismock as any,
|
||||
});
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.id).toBe(eventType.id);
|
||||
expect(result?.userId).toBe(user.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,289 @@
|
||||
//import "server-only";
|
||||
import { getLocationGroupedOptions } from "@calcom/app-store/server";
|
||||
import { getEventTypeAppData } from "@calcom/app-store/utils";
|
||||
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/getBookingFields";
|
||||
import { WEBSITE_URL } from "@calcom/lib/constants";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { getBookerBaseUrl } from "@calcom/lib/getBookerUrl/server";
|
||||
import { parseBookingLimit } from "@calcom/lib/intervalLimits/isBookingLimits";
|
||||
import { parseDurationLimit } from "@calcom/lib/intervalLimits/isDurationLimits";
|
||||
import { parseEventTypeColor } from "@calcom/lib/isEventTypeColor";
|
||||
import { parseRecurringEvent } from "@calcom/lib/isRecurringEvent";
|
||||
import type { LocationObject } from "@calcom/app-store/locations";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { SchedulingType, MembershipRole } from "@calcom/prisma/enums";
|
||||
import { customInputSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
|
||||
interface getEventTypeByIdProps {
|
||||
eventTypeId: number;
|
||||
userId: number;
|
||||
prisma: PrismaClient;
|
||||
isTrpcCall?: boolean;
|
||||
isUserOrganizationAdmin: boolean;
|
||||
currentOrganizationId: number | null;
|
||||
}
|
||||
|
||||
export type EventType = Awaited<ReturnType<typeof getEventTypeById>>;
|
||||
|
||||
export const getEventTypeById = async ({
|
||||
currentOrganizationId,
|
||||
eventTypeId,
|
||||
userId,
|
||||
prisma,
|
||||
isTrpcCall = false,
|
||||
isUserOrganizationAdmin,
|
||||
}: getEventTypeByIdProps) => {
|
||||
const userSelect = {
|
||||
name: true,
|
||||
avatarUrl: true,
|
||||
username: true,
|
||||
id: true,
|
||||
email: true,
|
||||
locale: true,
|
||||
defaultScheduleId: true,
|
||||
isPlatformManaged: true,
|
||||
timeZone: true,
|
||||
} satisfies Prisma.UserSelect;
|
||||
|
||||
const rawEventType = await getRawEventType({
|
||||
userId,
|
||||
eventTypeId,
|
||||
isUserOrganizationAdmin,
|
||||
currentOrganizationId,
|
||||
prisma,
|
||||
});
|
||||
|
||||
if (!rawEventType) {
|
||||
if (isTrpcCall) {
|
||||
throw new TRPCError({ code: "NOT_FOUND" });
|
||||
} else {
|
||||
throw new Error("Event type not found");
|
||||
}
|
||||
}
|
||||
|
||||
const { locations, metadata, ...restEventType } = rawEventType;
|
||||
const newMetadata = eventTypeMetaDataSchemaWithTypedApps.parse(metadata || {}) || {};
|
||||
const apps = newMetadata?.apps || {};
|
||||
const eventTypeWithParsedMetadata = { ...rawEventType, metadata: newMetadata };
|
||||
const userRepo = new UserRepository(prisma);
|
||||
const eventTeamMembershipsWithUserProfile = [];
|
||||
for (const eventTeamMembership of rawEventType.team?.members || []) {
|
||||
eventTeamMembershipsWithUserProfile.push({
|
||||
...eventTeamMembership,
|
||||
user: await userRepo.enrichUserWithItsProfile({
|
||||
user: eventTeamMembership.user,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const childrenWithUserProfile = [];
|
||||
for (const child of rawEventType.children || []) {
|
||||
childrenWithUserProfile.push({
|
||||
...child,
|
||||
owner: child.owner
|
||||
? await userRepo.enrichUserWithItsProfile({
|
||||
user: child.owner,
|
||||
})
|
||||
: null,
|
||||
});
|
||||
}
|
||||
|
||||
const eventTypeUsersWithUserProfile = [];
|
||||
for (const eventTypeUser of rawEventType.users) {
|
||||
eventTypeUsersWithUserProfile.push(
|
||||
await userRepo.enrichUserWithItsProfile({
|
||||
user: eventTypeUser,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
newMetadata.apps = {
|
||||
...apps,
|
||||
giphy: getEventTypeAppData(eventTypeWithParsedMetadata, "giphy", true),
|
||||
};
|
||||
|
||||
const parsedMetaData = newMetadata;
|
||||
|
||||
const parsedCustomInputs = (rawEventType.customInputs || []).map((input) => customInputSchema.parse(input));
|
||||
|
||||
const eventType = {
|
||||
...restEventType,
|
||||
schedule:
|
||||
rawEventType.schedule?.id ||
|
||||
(!rawEventType.team ? rawEventType.users[0]?.defaultScheduleId : null) ||
|
||||
null,
|
||||
restrictionScheduleId: rawEventType.restrictionScheduleId || null,
|
||||
restrictionScheduleName: rawEventType.restrictionSchedule?.name || null,
|
||||
useBookerTimezone: rawEventType.useBookerTimezone || false,
|
||||
instantMeetingSchedule: rawEventType.instantMeetingSchedule?.id || null,
|
||||
scheduleName: rawEventType.schedule?.name || null,
|
||||
recurringEvent: parseRecurringEvent(restEventType.recurringEvent),
|
||||
bookingLimits: parseBookingLimit(restEventType.bookingLimits),
|
||||
durationLimits: parseDurationLimit(restEventType.durationLimits),
|
||||
eventTypeColor: parseEventTypeColor(restEventType.eventTypeColor),
|
||||
locations: locations as unknown as LocationObject[],
|
||||
metadata: parsedMetaData,
|
||||
customInputs: parsedCustomInputs,
|
||||
users: rawEventType.users,
|
||||
bookerUrl: restEventType.team
|
||||
? await getBookerBaseUrl(restEventType.team.parentId)
|
||||
: restEventType.owner
|
||||
? await getBookerBaseUrl(currentOrganizationId)
|
||||
: WEBSITE_URL,
|
||||
children: childrenWithUserProfile.flatMap((ch) =>
|
||||
ch.owner !== null
|
||||
? {
|
||||
...ch,
|
||||
owner: {
|
||||
...ch.owner,
|
||||
avatar: getUserAvatarUrl(ch.owner),
|
||||
email: ch.owner.email,
|
||||
name: ch.owner.name ?? "",
|
||||
username: ch.owner.username ?? "",
|
||||
membership:
|
||||
restEventType.team?.members.find((tm) => tm.user.id === ch.owner?.id)?.role ||
|
||||
MembershipRole.MEMBER,
|
||||
},
|
||||
created: true,
|
||||
}
|
||||
: []
|
||||
),
|
||||
};
|
||||
|
||||
// backwards compat
|
||||
if (eventType.users.length === 0 && !eventType.team) {
|
||||
const fallbackUser = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
select: userSelect,
|
||||
});
|
||||
if (!fallbackUser) {
|
||||
if (isTrpcCall) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "The event type doesn't have user and no fallback user was found",
|
||||
});
|
||||
} else {
|
||||
throw Error("The event type doesn't have user and no fallback user was found");
|
||||
}
|
||||
}
|
||||
eventType.users.push(fallbackUser);
|
||||
}
|
||||
|
||||
const eventTypeUsers: ((typeof eventType.users)[number] & { avatar: string })[] =
|
||||
eventTypeUsersWithUserProfile.map((user) => ({
|
||||
...user,
|
||||
avatar: getUserAvatarUrl(user),
|
||||
}));
|
||||
|
||||
const currentUser = eventType.users.find((u) => u.id === userId);
|
||||
|
||||
const t = await getTranslation(currentUser?.locale ?? "en", "common");
|
||||
|
||||
if (!currentUser?.id && !eventType.teamId) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Could not find user or team",
|
||||
});
|
||||
}
|
||||
|
||||
const locationOptions = await getLocationGroupedOptions(
|
||||
eventType.teamId ? { teamId: eventType.teamId } : { userId },
|
||||
t
|
||||
);
|
||||
if (eventType.schedulingType === SchedulingType.MANAGED) {
|
||||
locationOptions.splice(0, 0, {
|
||||
label: t("default"),
|
||||
options: [
|
||||
{
|
||||
label: t("members_default_location"),
|
||||
value: "",
|
||||
icon: "/user-check.svg",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const isOrgTeamEvent = !!eventType?.teamId && !!eventType.team?.parentId;
|
||||
const eventTypeObject = Object.assign({}, eventType, {
|
||||
users: eventTypeUsers,
|
||||
periodStartDate: eventType.periodStartDate?.toString() ?? null,
|
||||
periodEndDate: eventType.periodEndDate?.toString() ?? null,
|
||||
bookingFields: getBookingFieldsWithSystemFields({ ...eventType, isOrgTeamEvent }),
|
||||
});
|
||||
|
||||
const isOrgEventType = !!eventTypeObject.team?.parentId;
|
||||
const teamMembers = eventTypeObject.team
|
||||
? eventTeamMembershipsWithUserProfile
|
||||
.filter((member) => member.accepted || isOrgEventType)
|
||||
.map((member) => {
|
||||
const user: typeof member.user & { avatar: string } = {
|
||||
...member.user,
|
||||
avatar: getUserAvatarUrl(member.user),
|
||||
};
|
||||
return {
|
||||
...user,
|
||||
profileId: user.profile.id,
|
||||
eventTypes: user.eventTypes.map((evTy) => evTy.slug),
|
||||
membership: member.role,
|
||||
};
|
||||
})
|
||||
: [];
|
||||
|
||||
// Find the current users membership so we can check role to enable/disable deletion.
|
||||
// Sets to null if no membership is found - this must mean we are in a none team event type
|
||||
const currentUserMembership = eventTypeObject.team?.members.find((el) => el.user.id === userId) ?? null;
|
||||
|
||||
let destinationCalendar = eventTypeObject.destinationCalendar;
|
||||
if (!destinationCalendar) {
|
||||
destinationCalendar = await prisma.destinationCalendar.findFirst({
|
||||
where: {
|
||||
userId: userId,
|
||||
eventTypeId: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const finalObj = {
|
||||
eventType: eventTypeObject,
|
||||
locationOptions,
|
||||
destinationCalendar,
|
||||
team: eventTypeObject.team || null,
|
||||
teamMembers,
|
||||
currentUserMembership,
|
||||
isUserOrganizationAdmin,
|
||||
};
|
||||
return finalObj;
|
||||
};
|
||||
|
||||
export async function getRawEventType({
|
||||
userId,
|
||||
eventTypeId,
|
||||
isUserOrganizationAdmin,
|
||||
currentOrganizationId,
|
||||
prisma,
|
||||
}: Omit<getEventTypeByIdProps, "isTrpcCall">) {
|
||||
const eventTypeRepo = new EventTypeRepository(prisma);
|
||||
|
||||
if (isUserOrganizationAdmin && currentOrganizationId) {
|
||||
return await eventTypeRepo.findByIdForOrgAdmin({
|
||||
id: eventTypeId,
|
||||
organizationId: currentOrganizationId,
|
||||
});
|
||||
}
|
||||
|
||||
return await eventTypeRepo.findById({
|
||||
id: eventTypeId,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
export default getEventTypeById;
|
||||
@@ -3,7 +3,7 @@ import { z } from "zod";
|
||||
import type { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
|
||||
import type { ChildrenEventType } from "@calcom/features/eventtypes/components/ChildrenEventTypeSelect";
|
||||
import type { IntervalLimit } from "@calcom/lib/intervalLimits/intervalLimitSchema";
|
||||
import type { EventLocationType } from "@calcom/lib/location";
|
||||
import type { EventLocationType } from "@calcom/app-store/locations";
|
||||
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
|
||||
import type { EventTypeTranslation } from "@calcom/prisma/client";
|
||||
import { type PeriodType, SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
|
||||
import { isOrganisationAdmin } from "@calcom/lib/server/queries/organisations";
|
||||
import { isTeamAdmin } from "@calcom/lib/server/queries/teams";
|
||||
import { isTeamAdmin } from "@calcom/features/ee/teams/lib/queries";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { selectOOOEntries } from "@calcom/app-store/zapier/api/subscriptions/lis
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
|
||||
import tasker from "@calcom/features/tasker";
|
||||
import { DailyLocationType, getHumanReadableLocationValue } from "@calcom/lib/location";
|
||||
import { DailyLocationType, getHumanReadableLocationValue } from "@calcom/app-store/locations";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
|
||||
Reference in new issue
Block a user