refactor: circular deps between app store and lib [6] (#23971)
* move delegation credential repository to features * mv credential repository to features * update imports * mv * fix * fix * fix * fix * fix * update imports * update imports * update eslint rule * fix * fix * mv getConnectedDestinationCalendars * fix import errors * mv getCalendarsEvents * remove getUsersCredentials * wip * revert eslint rule change for now * fix type checks * fix * format * cleanup * fix * fix * fix * fix * fix tests * migrate getUserAvailability * migrate * fix tests * fix type checks * fix * fix * migrate crmManager * update imports * migrate raqbUtils to appstore * migrate getLuckyUser to features * migrate findTeamMembersMatchingAttributeLogic to appstore * update imports * fix * fix * fix test * fix unit tests * fix * fix * add eslint config
This commit is contained in:
1 parent
445b307972
commit
bb68cd73ef
114 files changed
+263
-245
No files matched your search
@@ -1,205 +0,0 @@
|
||||
import { prisma } from "@calcom/prisma/__mocks__/prisma";
|
||||
|
||||
import type { Mock } from "vitest";
|
||||
import { describe, expect, it, vi, afterEach, beforeEach } from "vitest";
|
||||
|
||||
import { getLuckyUserService } from "@calcom/features/di/containers/LuckyUser";
|
||||
import { RRResetInterval, RRTimestampBasis } from "@calcom/prisma/enums";
|
||||
|
||||
import { filterHostsByLeadThreshold, errorCodes } from "./filterHostsByLeadThreshold";
|
||||
|
||||
vi.mock("@calcom/prisma", () => ({
|
||||
prisma,
|
||||
}));
|
||||
|
||||
const luckyUserService = getLuckyUserService();
|
||||
|
||||
// Mocking setup
|
||||
const prismaMock = {
|
||||
booking: {
|
||||
groupBy: vi.fn(), // Mock the groupBy method
|
||||
},
|
||||
};
|
||||
|
||||
// Use `vi.spyOn` to make `prisma.booking.groupBy` call the mock instead
|
||||
vi.spyOn(prismaMock.booking, "groupBy").mockImplementation(prismaMock.booking.groupBy);
|
||||
|
||||
// This variable will hold our mock function
|
||||
let getOrderedListOfLuckyUsersMock: Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
// Clear all mocks and spies before each test
|
||||
vi.clearAllMocks();
|
||||
// Spy on the real method and explicitly cast it as a Mock
|
||||
getOrderedListOfLuckyUsersMock = vi.spyOn(luckyUserService, "getOrderedListOfLuckyUsers") as Mock;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore all spies to their original implementation
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("filterHostByLeadThreshold", () => {
|
||||
it("skips filter if lead threshold is null", async () => {
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: false as const,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
expect(
|
||||
filterHostsByLeadThreshold({
|
||||
hosts,
|
||||
maxLeadThreshold: null,
|
||||
eventType: {
|
||||
id: 1,
|
||||
isRRWeightsEnabled: true,
|
||||
team: {
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
rrTimestampBasis: RRTimestampBasis.CREATED_AT,
|
||||
},
|
||||
includeNoShowInRRCalculation: false,
|
||||
},
|
||||
routingFormResponse: null,
|
||||
})
|
||||
).resolves.toStrictEqual(hosts);
|
||||
});
|
||||
|
||||
it("throws error when maxLeadThreshold = 0, 0 ahead makes no sense.", async () => {
|
||||
expect(
|
||||
filterHostsByLeadThreshold({
|
||||
hosts: [],
|
||||
maxLeadThreshold: 0,
|
||||
eventType: {
|
||||
id: 1,
|
||||
isRRWeightsEnabled: true,
|
||||
team: {
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
rrTimestampBasis: RRTimestampBasis.CREATED_AT,
|
||||
},
|
||||
includeNoShowInRRCalculation: false,
|
||||
},
|
||||
routingFormResponse: null,
|
||||
})
|
||||
).rejects.toThrow(errorCodes.MAX_LEAD_THRESHOLD_FALSY);
|
||||
});
|
||||
|
||||
it("correctly disqualifies a host when the lead offset is exceeding the threshold without weights", async () => {
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: false as const,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false as const,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 2,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
getOrderedListOfLuckyUsersMock.mockResolvedValue({
|
||||
perUserData: {
|
||||
bookingsCount: { 1: 10, 2: 6 },
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
filterHostsByLeadThreshold({
|
||||
hosts,
|
||||
maxLeadThreshold: 3,
|
||||
eventType: {
|
||||
id: 1,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
rrTimestampBasis: RRTimestampBasis.CREATED_AT,
|
||||
},
|
||||
includeNoShowInRRCalculation: false,
|
||||
},
|
||||
routingFormResponse: null,
|
||||
})
|
||||
).resolves.toStrictEqual([hosts[1]]); // host 1 (host[0]) disqualified
|
||||
});
|
||||
|
||||
it("correctly disqualifies a host when the lead offset is exceeding the threshold with weights", async () => {
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: false as const,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false as const,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 2,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false as const,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 3,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
getOrderedListOfLuckyUsersMock.mockResolvedValue({
|
||||
perUserData: {
|
||||
bookingsCount: { 1: 7, 2: 5, 3: 0 },
|
||||
weights: { 1: 100, 2: 50, 3: 20 },
|
||||
bookingShortfalls: { 1: 1, 2: -3, 3: 0 },
|
||||
calibrations: { 1: 1, 2: 2, 3: 1 },
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
filterHostsByLeadThreshold({
|
||||
hosts,
|
||||
maxLeadThreshold: 3,
|
||||
eventType: {
|
||||
id: 1,
|
||||
isRRWeightsEnabled: true,
|
||||
team: {
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
rrTimestampBasis: RRTimestampBasis.CREATED_AT,
|
||||
},
|
||||
includeNoShowInRRCalculation: false,
|
||||
},
|
||||
routingFormResponse: null,
|
||||
})
|
||||
).resolves.toStrictEqual([hosts[0], hosts[2]]); // host 2 (host[1]) disqualified
|
||||
});
|
||||
});
|
||||
@@ -1,167 +0,0 @@
|
||||
import { getLuckyUserService } from "@calcom/features/di/containers/LuckyUser";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { RRResetInterval, SelectedCalendar } from "@calcom/prisma/client";
|
||||
import { RRTimestampBasis } from "@calcom/prisma/enums";
|
||||
import type { CredentialForCalendarService } from "@calcom/types/Credential";
|
||||
|
||||
import type { LuckyUserService, RoutingFormResponse } from "../server/getLuckyUser";
|
||||
|
||||
export const errorCodes = {
|
||||
MAX_LEAD_THRESHOLD_FALSY: "Max lead threshold should be null or > 1, not 0.",
|
||||
} as const;
|
||||
|
||||
type BaseUser = {
|
||||
id: number;
|
||||
email: string;
|
||||
credentials: CredentialForCalendarService[];
|
||||
userLevelSelectedCalendars: SelectedCalendar[];
|
||||
} & Record<string, unknown>;
|
||||
|
||||
type BaseHost<User extends BaseUser> = {
|
||||
isFixed: boolean;
|
||||
createdAt: Date;
|
||||
priority?: number | null;
|
||||
weight?: number | null;
|
||||
weightAdjustment?: number | null;
|
||||
user: User;
|
||||
};
|
||||
|
||||
type PerUserData = Awaited<
|
||||
ReturnType<(typeof LuckyUserService.prototype)["getOrderedListOfLuckyUsers"]>
|
||||
>["perUserData"];
|
||||
type WeightedPerUserData = Omit<PerUserData, "weights" | "calibrations" | "bookingShortfalls"> & {
|
||||
weights: NonNullable<PerUserData["weights"]>;
|
||||
calibrations: NonNullable<PerUserData["calibrations"]>;
|
||||
bookingShortfalls: NonNullable<PerUserData["bookingShortfalls"]>;
|
||||
};
|
||||
|
||||
const log = logger.getSubLogger({ name: "filterHostsByLeadThreshold" });
|
||||
|
||||
function filterHostsByLeadThresholdWithWeights(perUserData: WeightedPerUserData, maxLeadThreshold: number) {
|
||||
const filteredUserIds: number[] = [];
|
||||
// negative shortfall means the host should receive negative bookings, so they are overbooked
|
||||
const maxShortfall = Math.max(...Object.values(perUserData.bookingShortfalls)); // least amount of bookings
|
||||
|
||||
for (const userIdStr in perUserData.bookingShortfalls) {
|
||||
const shortfall = perUserData.bookingShortfalls[userIdStr];
|
||||
// if user's shortfall is more than
|
||||
if (maxShortfall - shortfall > maxLeadThreshold) {
|
||||
log.debug(
|
||||
`Host ${userIdStr} has been filtered out because the amount of bookings made him exceed the thresholds. Shortfall: ${shortfall}, Max Shortfall: ${maxShortfall}`
|
||||
);
|
||||
} else {
|
||||
filteredUserIds.push(parseInt(userIdStr, 10));
|
||||
}
|
||||
}
|
||||
return filteredUserIds;
|
||||
}
|
||||
|
||||
function filterHostsByLeadThresholdWithoutWeights(perUserData: PerUserData, maxLeadThreshold: number) {
|
||||
const filteredUserIds: number[] = [];
|
||||
|
||||
const bookingsArray = Object.values(perUserData.bookingsCount);
|
||||
const minBookings = Math.min(...bookingsArray);
|
||||
|
||||
for (const userIdStr in perUserData.bookingsCount) {
|
||||
const bookingsCount = perUserData.bookingsCount[userIdStr];
|
||||
if (bookingsCount - minBookings > maxLeadThreshold) {
|
||||
log.debug(
|
||||
`Host ${userIdStr} has been filtered out because the given data made them exceed the thresholds. BookingsCount: ${bookingsCount}, MinBookings: ${minBookings}`
|
||||
);
|
||||
} else {
|
||||
filteredUserIds.push(parseInt(userIdStr, 10));
|
||||
log.debug(
|
||||
`Host Allowed ${userIdStr} has been filtered out because the given data made them exceed the thresholds. BookingsCount: ${bookingsCount}, MinBookings: ${minBookings}, MaxLeadThreshold: ${maxLeadThreshold}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return filteredUserIds;
|
||||
}
|
||||
|
||||
/*
|
||||
* Filter the hosts by lead threshold, disqualifying hosts that have exceeded the maximum
|
||||
*
|
||||
* NOTE: This function cleans up the leadOffset value so can't be used afterwards.
|
||||
*
|
||||
* @throws errorCodes.MAX_LEAD_THRESHOLD_FALSY
|
||||
*/
|
||||
export const filterHostsByLeadThreshold = async <T extends BaseHost<BaseUser>>({
|
||||
hosts,
|
||||
maxLeadThreshold,
|
||||
eventType,
|
||||
routingFormResponse,
|
||||
}: {
|
||||
hosts: T[];
|
||||
maxLeadThreshold: number | null;
|
||||
eventType: {
|
||||
id: number;
|
||||
isRRWeightsEnabled: boolean;
|
||||
team: {
|
||||
parentId?: number | null;
|
||||
rrResetInterval: RRResetInterval | null;
|
||||
rrTimestampBasis: RRTimestampBasis;
|
||||
} | null;
|
||||
includeNoShowInRRCalculation: boolean;
|
||||
};
|
||||
routingFormResponse: RoutingFormResponse | null;
|
||||
}) => {
|
||||
if (maxLeadThreshold === 0) {
|
||||
throw new Error(errorCodes.MAX_LEAD_THRESHOLD_FALSY);
|
||||
}
|
||||
if (
|
||||
maxLeadThreshold === null ||
|
||||
hosts.length < 1 ||
|
||||
(eventType.team?.rrTimestampBasis && eventType.team.rrTimestampBasis !== RRTimestampBasis.CREATED_AT)
|
||||
) {
|
||||
return hosts; // don't apply filter.
|
||||
}
|
||||
|
||||
// this needs the routing forms response too, because it needs to know what queue we are in
|
||||
const luckyUserService = getLuckyUserService();
|
||||
const orderedLuckyUsers = await luckyUserService.getOrderedListOfLuckyUsers({
|
||||
availableUsers: [
|
||||
{
|
||||
...hosts[0].user,
|
||||
weight: hosts[0].weight ?? null,
|
||||
priority: hosts[0].priority ?? null,
|
||||
},
|
||||
...hosts.slice(1).map((host) => ({
|
||||
...host.user,
|
||||
weight: host.weight ?? null,
|
||||
priority: host.priority ?? null,
|
||||
})),
|
||||
],
|
||||
eventType,
|
||||
allRRHosts: hosts,
|
||||
routingFormResponse,
|
||||
});
|
||||
|
||||
const perUserData = orderedLuckyUsers["perUserData"];
|
||||
|
||||
let filteredUserIds: number[];
|
||||
if (eventType.isRRWeightsEnabled) {
|
||||
// Check if any of the required data is null
|
||||
if (
|
||||
perUserData.calibrations === null ||
|
||||
perUserData.weights === null ||
|
||||
perUserData.bookingShortfalls === null
|
||||
) {
|
||||
throw new Error("Calibrations, weights, or booking shortfalls are null");
|
||||
}
|
||||
filteredUserIds = filterHostsByLeadThresholdWithWeights(
|
||||
{
|
||||
bookingsCount: perUserData.bookingsCount,
|
||||
bookingShortfalls: perUserData.bookingShortfalls,
|
||||
calibrations: perUserData.calibrations,
|
||||
weights: perUserData.weights,
|
||||
},
|
||||
maxLeadThreshold
|
||||
);
|
||||
} else {
|
||||
filteredUserIds = filterHostsByLeadThresholdWithoutWeights(perUserData, maxLeadThreshold);
|
||||
}
|
||||
|
||||
const filteredHosts = hosts.filter((host) => filteredUserIds.includes(host.user.id));
|
||||
return filteredHosts;
|
||||
};
|
||||
@@ -1,126 +0,0 @@
|
||||
import type { Mock } from "vitest";
|
||||
import { describe, expect, it, vi, afterEach } from "vitest";
|
||||
|
||||
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
|
||||
import { FilterHostsService } from "./filterHostsBySameRoundRobinHost";
|
||||
|
||||
const mockBookingRepo = {
|
||||
findOriginalRescheduledBookingUserId: vi.fn(),
|
||||
} as unknown as BookingRepository;
|
||||
|
||||
const filterHostsService = new FilterHostsService({
|
||||
bookingRepo: mockBookingRepo,
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
(mockBookingRepo.findOriginalRescheduledBookingUserId as Mock).mockClear();
|
||||
});
|
||||
|
||||
describe("FilterHostsService", () => {
|
||||
it("skips filter if rescheduleWithSameRoundRobinHost set to false", async () => {
|
||||
const hosts = [
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 1, email: "[email protected]" } },
|
||||
];
|
||||
expect(
|
||||
filterHostsService.filterHostsBySameRoundRobinHost({
|
||||
hosts,
|
||||
rescheduleUid: "some-uid",
|
||||
rescheduleWithSameRoundRobinHost: false,
|
||||
routedTeamMemberIds: null,
|
||||
})
|
||||
).resolves.toStrictEqual(hosts);
|
||||
});
|
||||
it("skips filter if rerouting", async () => {
|
||||
const hosts = [
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 1, email: "[email protected]" } },
|
||||
];
|
||||
expect(
|
||||
filterHostsService.filterHostsBySameRoundRobinHost({
|
||||
hosts,
|
||||
rescheduleUid: "some-uid",
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
routedTeamMemberIds: [23],
|
||||
})
|
||||
).resolves.toStrictEqual(hosts);
|
||||
});
|
||||
|
||||
it("correctly selects the same host if the filter applies and the host is in the RR users", async () => {
|
||||
(mockBookingRepo.findOriginalRescheduledBookingUserId as Mock).mockResolvedValue({ userId: 1 });
|
||||
|
||||
const hosts = [
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 1, email: "[email protected]" } },
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 2, email: "[email protected]" } },
|
||||
];
|
||||
expect(
|
||||
filterHostsService.filterHostsBySameRoundRobinHost({
|
||||
hosts,
|
||||
rescheduleUid: "some-uid",
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
routedTeamMemberIds: null,
|
||||
})
|
||||
).resolves.toStrictEqual([hosts[0]]);
|
||||
});
|
||||
|
||||
// Tests for bookings that have more than one host
|
||||
describe("Fixed hosts and round robin groups support", () => {
|
||||
it("should return organizer and attendee hosts", async () => {
|
||||
(mockBookingRepo.findOriginalRescheduledBookingUserId as Mock).mockResolvedValue({
|
||||
userId: 1,
|
||||
attendees: [
|
||||
{ email: "[email protected]" },
|
||||
{ email: "[email protected]" },
|
||||
{ email: "[email protected]" }, // Non-host attendee
|
||||
],
|
||||
});
|
||||
|
||||
const hosts = [
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 1, email: "[email protected]" } },
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 2, email: "[email protected]" } },
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 3, email: "[email protected]" } },
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 4, email: "[email protected]" } },
|
||||
];
|
||||
|
||||
const result = await filterHostsService.filterHostsBySameRoundRobinHost({
|
||||
hosts,
|
||||
rescheduleUid: "some-uid",
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
routedTeamMemberIds: null,
|
||||
});
|
||||
|
||||
// Should return organizer host (id: 1) and attendee hosts (ids: 2, 3)
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result).toEqual([
|
||||
expect.objectContaining({ user: { id: 1, email: "[email protected]" } }), // organizer
|
||||
expect.objectContaining({ user: { id: 2, email: "[email protected]" } }), // attendee
|
||||
expect.objectContaining({ user: { id: 3, email: "[email protected]" } }), // attendee
|
||||
]);
|
||||
});
|
||||
|
||||
it("should return only organizer host when no attendees match current hosts", async () => {
|
||||
(mockBookingRepo.findOriginalRescheduledBookingUserId as Mock).mockResolvedValue({
|
||||
userId: 1,
|
||||
attendees: [
|
||||
{ email: "[email protected]" }, // Non-host attendee
|
||||
{ email: "[email protected]" }, // Non-host attendee
|
||||
],
|
||||
});
|
||||
|
||||
const hosts = [
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 1, email: "[email protected]" } },
|
||||
{ isFixed: false as const, createdAt: new Date(), user: { id: 2, email: "[email protected]" } },
|
||||
];
|
||||
|
||||
const result = await filterHostsService.filterHostsBySameRoundRobinHost({
|
||||
hosts,
|
||||
rescheduleUid: "some-uid",
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
routedTeamMemberIds: null,
|
||||
});
|
||||
|
||||
// Should return only organizer host
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual(expect.objectContaining({ user: { id: 1, email: "[email protected]" } }));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,53 +0,0 @@
|
||||
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
|
||||
import { isRerouting } from "./routing/utils";
|
||||
|
||||
export interface IFilterHostsService {
|
||||
bookingRepo: BookingRepository;
|
||||
}
|
||||
|
||||
export class FilterHostsService {
|
||||
constructor(public readonly dependencies: IFilterHostsService) {}
|
||||
|
||||
async filterHostsBySameRoundRobinHost<
|
||||
T extends {
|
||||
isFixed: false; // ensure no fixed hosts are passed.
|
||||
user: { id: number; email: string };
|
||||
}
|
||||
>({
|
||||
hosts,
|
||||
rescheduleUid,
|
||||
rescheduleWithSameRoundRobinHost,
|
||||
routedTeamMemberIds,
|
||||
}: {
|
||||
hosts: T[];
|
||||
rescheduleUid: string | null;
|
||||
rescheduleWithSameRoundRobinHost: boolean;
|
||||
routedTeamMemberIds: number[] | null;
|
||||
}) {
|
||||
if (
|
||||
!rescheduleUid ||
|
||||
!rescheduleWithSameRoundRobinHost ||
|
||||
isRerouting({ rescheduleUid, routedTeamMemberIds })
|
||||
) {
|
||||
return hosts;
|
||||
}
|
||||
|
||||
const originalRescheduledBooking =
|
||||
await this.dependencies.bookingRepo.findOriginalRescheduledBookingUserId({
|
||||
rescheduleUid,
|
||||
});
|
||||
|
||||
if (!originalRescheduledBooking) {
|
||||
return hosts;
|
||||
}
|
||||
|
||||
const attendeeEmails = originalRescheduledBooking.attendees?.map((attendee) => attendee.email) || [];
|
||||
|
||||
return hosts.filter((host) => {
|
||||
const isOrganizer = host.user.id === originalRescheduledBooking.userId;
|
||||
const isAttendee = attendeeEmails.includes(host.user.email);
|
||||
return isOrganizer || isAttendee;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,691 +0,0 @@
|
||||
import prismaMock from "../../../tests/libs/__mocks__/prismaMock";
|
||||
|
||||
import { vi, it, describe, expect, afterEach } from "vitest";
|
||||
import type { Mock } from "vitest";
|
||||
|
||||
import { getQualifiedHostsService } from "@calcom/features/di/containers/QualifiedHosts";
|
||||
import { RRResetInterval, SchedulingType } from "@calcom/prisma/enums";
|
||||
|
||||
import { filterHostsByLeadThreshold } from "./filterHostsByLeadThreshold";
|
||||
import * as getRoutedUsers from "./getRoutedUsers";
|
||||
|
||||
// Mock the filterHostsByLeadThreshold function
|
||||
vi.mock("./filterHostsByLeadThreshold", () => {
|
||||
return {
|
||||
filterHostsByLeadThreshold: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
// Clear call history after each test
|
||||
afterEach(() => {
|
||||
(filterHostsByLeadThreshold as Mock).mockClear();
|
||||
});
|
||||
|
||||
const qualifiedHostsService = getQualifiedHostsService();
|
||||
describe("findQualifiedHostsWithDelegationCredentials", async () => {
|
||||
it("should return qualified hosts based on mock of filterHostsByLeadThreshold", async () => {
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: true,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 2,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
priority: undefined,
|
||||
weight: undefined,
|
||||
groupId: null,
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 1,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
priority: undefined,
|
||||
weight: undefined,
|
||||
groupId: null,
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: new Date(),
|
||||
user: {
|
||||
id: 3,
|
||||
email: "[email protected]",
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
priority: undefined,
|
||||
weight: undefined,
|
||||
groupId: null,
|
||||
},
|
||||
];
|
||||
|
||||
const rrHosts = hosts.filter((host) => !host.isFixed);
|
||||
const fixedHosts = hosts.filter((host) => host.isFixed);
|
||||
const rrHostsAfterFairness = [rrHosts[2]];
|
||||
|
||||
// Configure the mock return value
|
||||
(filterHostsByLeadThreshold as Mock).mockResolvedValue(rrHostsAfterFairness);
|
||||
|
||||
// Define the input for the test
|
||||
const eventType = {
|
||||
id: 1,
|
||||
hosts,
|
||||
users: [],
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
maxLeadThreshold: null,
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
assignAllTeamMembers: true,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
id: 1,
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
},
|
||||
};
|
||||
|
||||
// Call the function under test
|
||||
const result = await qualifiedHostsService.findQualifiedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
routedTeamMemberIds: [],
|
||||
rescheduleUid: null,
|
||||
contactOwnerEmail: null,
|
||||
routingFormResponse: null,
|
||||
});
|
||||
|
||||
// Verify the result
|
||||
expect(result).toStrictEqual({
|
||||
qualifiedRRHosts: rrHostsAfterFairness,
|
||||
fixedHosts,
|
||||
allFallbackRRHosts: rrHosts,
|
||||
});
|
||||
});
|
||||
|
||||
it("should return hosts after valid input with users", async () => {
|
||||
const users = [
|
||||
{
|
||||
email: "[email protected]",
|
||||
id: 1,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
{
|
||||
email: "[email protected]",
|
||||
id: 2,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
];
|
||||
|
||||
// Define the input for the test
|
||||
const eventType = {
|
||||
id: 1,
|
||||
hosts: [],
|
||||
users,
|
||||
schedulingType: null,
|
||||
maxLeadThreshold: null,
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
assignAllTeamMembers: true,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
id: 1,
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
},
|
||||
};
|
||||
|
||||
// Call the function under test
|
||||
const result = await qualifiedHostsService.findQualifiedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
routedTeamMemberIds: [],
|
||||
rescheduleUid: null,
|
||||
contactOwnerEmail: null,
|
||||
routingFormResponse: null,
|
||||
});
|
||||
|
||||
// Verify the result
|
||||
expect(result).toEqual({
|
||||
qualifiedRRHosts: [],
|
||||
fixedHosts: users.map((user) => ({
|
||||
user: user,
|
||||
isFixed: true,
|
||||
email: user.email,
|
||||
createdAt: null,
|
||||
})),
|
||||
});
|
||||
|
||||
expect(filterHostsByLeadThreshold).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should return only the crm contact owner match & other users + contact owner as fallback ", async () => {
|
||||
const oneYearAgo = new Date();
|
||||
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
|
||||
|
||||
const hosts = [
|
||||
{
|
||||
weight: 100,
|
||||
priority: 2,
|
||||
createdAt: oneYearAgo,
|
||||
isFixed: false,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 1,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
weight: 100,
|
||||
priority: 2,
|
||||
createdAt: oneYearAgo,
|
||||
isFixed: false,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 2,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
weight: 100,
|
||||
priority: 2,
|
||||
createdAt: oneYearAgo,
|
||||
isFixed: false,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 3,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
(filterHostsByLeadThreshold as Mock).mockResolvedValue(hosts);
|
||||
|
||||
// Define the input for the test
|
||||
const eventType = {
|
||||
id: 1,
|
||||
hosts,
|
||||
users: [],
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
maxLeadThreshold: null,
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
assignAllTeamMembers: true,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
id: 1,
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
},
|
||||
};
|
||||
|
||||
// Call the function under test
|
||||
const result = await qualifiedHostsService.findQualifiedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
routedTeamMemberIds: [],
|
||||
rescheduleUid: null,
|
||||
contactOwnerEmail: "[email protected]",
|
||||
routingFormResponse: null,
|
||||
});
|
||||
|
||||
// Verify the result
|
||||
expect(result).toEqual({
|
||||
qualifiedRRHosts: [
|
||||
{
|
||||
...hosts[0],
|
||||
},
|
||||
],
|
||||
allFallbackRRHosts: hosts,
|
||||
fixedHosts: [],
|
||||
});
|
||||
});
|
||||
|
||||
// it("should return only the crm contact owner match & other users + contact owner as fallback (with routing and segment filtering)", async () => {
|
||||
|
||||
// });
|
||||
|
||||
it("should return only routed members + contact owner as fallback for crm contact owner match", async () => {
|
||||
const oneYearAgo = new Date();
|
||||
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
|
||||
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 1,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 2,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 3,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
(filterHostsByLeadThreshold as Mock).mockResolvedValue([hosts[0], hosts[1]]);
|
||||
|
||||
// Define the input for the test
|
||||
const eventType = {
|
||||
id: 1,
|
||||
hosts,
|
||||
users: [],
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
maxLeadThreshold: null,
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
assignAllTeamMembers: true,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
id: 1,
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
},
|
||||
};
|
||||
|
||||
// Call the function under test
|
||||
const result = await qualifiedHostsService.findQualifiedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
routedTeamMemberIds: [1],
|
||||
rescheduleUid: null,
|
||||
contactOwnerEmail: "[email protected]",
|
||||
routingFormResponse: null,
|
||||
});
|
||||
|
||||
// Verify the result
|
||||
expect(result).toEqual({
|
||||
qualifiedRRHosts: [hosts[2]],
|
||||
allFallbackRRHosts: [hosts[0], hosts[2]],
|
||||
fixedHosts: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("if it's a reschedule with same host, it should only return this host and the fixed hosts", async () => {
|
||||
const oneYearAgo = new Date();
|
||||
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
|
||||
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 1,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 2,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: true,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 3,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const eventType = {
|
||||
id: 1,
|
||||
hosts,
|
||||
users: [],
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
maxLeadThreshold: null,
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
assignAllTeamMembers: true,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
id: 1,
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
},
|
||||
};
|
||||
prismaMock.booking.findFirst.mockResolvedValue({ userId: 2 });
|
||||
|
||||
const result = await qualifiedHostsService.findQualifiedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
routedTeamMemberIds: [],
|
||||
rescheduleUid: "recheduleUid",
|
||||
contactOwnerEmail: null,
|
||||
routingFormResponse: null,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
qualifiedRRHosts: [hosts[1]],
|
||||
fixedHosts: [hosts[2]],
|
||||
});
|
||||
});
|
||||
|
||||
it("should return early if segment matching results in only one host", async () => {
|
||||
const oneYearAgo = new Date();
|
||||
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
|
||||
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 1,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 2,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 3,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const eventType = {
|
||||
id: 1,
|
||||
hosts,
|
||||
users: [],
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
maxLeadThreshold: null,
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
assignAllTeamMembers: true,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
id: 1,
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
},
|
||||
};
|
||||
|
||||
const findMatchingHostsSpy = vi
|
||||
.spyOn(getRoutedUsers, "findMatchingHostsWithEventSegment")
|
||||
.mockImplementation(async () => [hosts[0]]);
|
||||
|
||||
// Call the function under test
|
||||
const result = await qualifiedHostsService.findQualifiedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
routedTeamMemberIds: [0, 1, 2],
|
||||
rescheduleUid: null,
|
||||
contactOwnerEmail: null,
|
||||
routingFormResponse: null,
|
||||
});
|
||||
|
||||
// Verify the result
|
||||
expect(result).toEqual({
|
||||
qualifiedRRHosts: [hosts[0]],
|
||||
fixedHosts: [],
|
||||
});
|
||||
|
||||
// Verify that findMatchingHostsWithEventSegment was called with correct parameters
|
||||
expect(findMatchingHostsSpy).toHaveBeenCalledWith({
|
||||
eventType,
|
||||
hosts: hosts.filter((host) => !host.isFixed), // Only round-robin hosts should be passed
|
||||
});
|
||||
|
||||
// Verify that filterHostsByLeadThreshold was not called since we returned early
|
||||
expect(filterHostsByLeadThreshold).not.toHaveBeenCalled();
|
||||
|
||||
// Verify that allFallbackRRHosts is not present in the result
|
||||
expect(result).not.toHaveProperty("allFallbackRRHosts");
|
||||
});
|
||||
|
||||
it("should filter for segment matching and routed team member ids", async () => {
|
||||
const oneYearAgo = new Date();
|
||||
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
|
||||
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 1,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 2,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 3,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const eventType = {
|
||||
id: 1,
|
||||
hosts,
|
||||
users: [],
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
maxLeadThreshold: null,
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
assignAllTeamMembers: true,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
id: 1,
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
},
|
||||
};
|
||||
|
||||
vi.spyOn(getRoutedUsers, "findMatchingHostsWithEventSegment").mockImplementation(async () => [
|
||||
hosts[0],
|
||||
hosts[1],
|
||||
]);
|
||||
|
||||
// Call the function under test
|
||||
const result = await qualifiedHostsService.findQualifiedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
routedTeamMemberIds: [2, 3],
|
||||
rescheduleUid: null,
|
||||
contactOwnerEmail: null,
|
||||
routingFormResponse: null,
|
||||
});
|
||||
|
||||
// Verify the result
|
||||
expect(result).toEqual({
|
||||
qualifiedRRHosts: [hosts[1]],
|
||||
fixedHosts: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("should filter for fairness and return fallback with segment filtering and routed team member ids", async () => {
|
||||
const oneYearAgo = new Date();
|
||||
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
|
||||
|
||||
const hosts = [
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 1,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 2,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 3,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
isFixed: false,
|
||||
createdAt: oneYearAgo,
|
||||
weight: undefined,
|
||||
priority: undefined,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
id: 3,
|
||||
credentials: [],
|
||||
userLevelSelectedCalendars: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const eventType = {
|
||||
id: 1,
|
||||
hosts,
|
||||
users: [],
|
||||
schedulingType: SchedulingType.ROUND_ROBIN,
|
||||
maxLeadThreshold: null,
|
||||
rescheduleWithSameRoundRobinHost: true,
|
||||
assignAllTeamMembers: true,
|
||||
assignRRMembersUsingSegment: false,
|
||||
rrSegmentQueryValue: null,
|
||||
isRRWeightsEnabled: false,
|
||||
team: {
|
||||
id: 1,
|
||||
parentId: null,
|
||||
rrResetInterval: RRResetInterval.MONTH,
|
||||
},
|
||||
};
|
||||
|
||||
vi.spyOn(getRoutedUsers, "findMatchingHostsWithEventSegment").mockImplementation(async () => [
|
||||
hosts[0],
|
||||
hosts[1],
|
||||
hosts[2],
|
||||
]);
|
||||
|
||||
const rrHostsAfterFairness = [hosts[2]];
|
||||
|
||||
// Configure the mock return value
|
||||
(filterHostsByLeadThreshold as Mock).mockResolvedValue(rrHostsAfterFairness);
|
||||
|
||||
// Call the function under test
|
||||
const result = await qualifiedHostsService.findQualifiedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
routedTeamMemberIds: [2, 3],
|
||||
rescheduleUid: null,
|
||||
contactOwnerEmail: null,
|
||||
routingFormResponse: null,
|
||||
});
|
||||
|
||||
// Verify the result
|
||||
expect(result).toEqual({
|
||||
qualifiedRRHosts: [hosts[2]],
|
||||
allFallbackRRHosts: [hosts[1], hosts[2]],
|
||||
fixedHosts: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,227 +0,0 @@
|
||||
import type { FilterHostsService } from "@calcom/lib/bookings/filterHostsBySameRoundRobinHost";
|
||||
import {
|
||||
findMatchingHostsWithEventSegment,
|
||||
getNormalizedHostsWithDelegationCredentials,
|
||||
} from "@calcom/lib/bookings/getRoutedUsers";
|
||||
import type { EventType } from "@calcom/lib/bookings/getRoutedUsers";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import type { SelectedCalendar } from "@calcom/prisma/client";
|
||||
import type { SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
|
||||
|
||||
import type { RoutingFormResponse } from "../server/getLuckyUser";
|
||||
import { filterHostsByLeadThreshold } from "./filterHostsByLeadThreshold";
|
||||
|
||||
export interface IQualifiedHostsService {
|
||||
bookingRepo: BookingRepository;
|
||||
filterHostsService: FilterHostsService;
|
||||
}
|
||||
|
||||
type Host<T> = {
|
||||
isFixed: boolean;
|
||||
createdAt: Date;
|
||||
priority?: number | null;
|
||||
weight?: number | null;
|
||||
groupId: string | null;
|
||||
} & {
|
||||
user: T;
|
||||
};
|
||||
|
||||
// In case we don't have any matching team members, we return all the RR hosts, as we always want the team event to be bookable.
|
||||
// Each filter is filtered down, but we never return 0-length.
|
||||
// TODO: We should notify about it to the organizer somehow.
|
||||
function applyFilterWithFallback<T>(currentValue: T[], newValue: T[]): T[] {
|
||||
return newValue.length > 0 ? newValue : currentValue;
|
||||
}
|
||||
|
||||
function getFallBackWithContactOwner<T extends { user: { id: number } }>(
|
||||
fallbackHosts: T[],
|
||||
contactOwner: T
|
||||
) {
|
||||
if (fallbackHosts.find((host) => host.user.id === contactOwner.user.id)) {
|
||||
return fallbackHosts;
|
||||
}
|
||||
|
||||
return [...fallbackHosts, contactOwner];
|
||||
}
|
||||
|
||||
const isRoundRobinHost = <T extends { isFixed: boolean }>(host: T): host is T & { isFixed: false } => {
|
||||
return host.isFixed === false;
|
||||
};
|
||||
|
||||
const isFixedHost = <T extends { isFixed: boolean }>(host: T): host is T & { isFixed: false } => {
|
||||
return host.isFixed;
|
||||
};
|
||||
|
||||
export class QualifiedHostsService {
|
||||
constructor(public readonly dependencies: IQualifiedHostsService) {}
|
||||
|
||||
async _findQualifiedHostsWithDelegationCredentials<
|
||||
T extends {
|
||||
email: string;
|
||||
id: number;
|
||||
credentials: CredentialPayload[];
|
||||
userLevelSelectedCalendars: SelectedCalendar[];
|
||||
} & Record<string, unknown>
|
||||
>({
|
||||
eventType,
|
||||
rescheduleUid,
|
||||
routedTeamMemberIds,
|
||||
contactOwnerEmail,
|
||||
routingFormResponse,
|
||||
}: {
|
||||
eventType: {
|
||||
id: number;
|
||||
maxLeadThreshold?: number | null;
|
||||
hosts?: Host<T>[];
|
||||
users: T[];
|
||||
schedulingType: SchedulingType | null;
|
||||
isRRWeightsEnabled: boolean;
|
||||
rescheduleWithSameRoundRobinHost: boolean;
|
||||
includeNoShowInRRCalculation: boolean;
|
||||
} & EventType;
|
||||
rescheduleUid: string | null;
|
||||
routedTeamMemberIds: number[];
|
||||
contactOwnerEmail: string | null;
|
||||
routingFormResponse: RoutingFormResponse | null;
|
||||
}): Promise<{
|
||||
qualifiedRRHosts: {
|
||||
isFixed: boolean;
|
||||
createdAt: Date | null;
|
||||
priority?: number | null;
|
||||
weight?: number | null;
|
||||
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
|
||||
}[];
|
||||
fixedHosts: {
|
||||
isFixed: boolean;
|
||||
createdAt: Date | null;
|
||||
priority?: number | null;
|
||||
weight?: number | null;
|
||||
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
|
||||
}[];
|
||||
// all hosts we want to fallback to including the qualifiedRRHosts (fairness + crm contact owner)
|
||||
allFallbackRRHosts?: {
|
||||
isFixed: boolean;
|
||||
createdAt: Date | null;
|
||||
priority?: number | null;
|
||||
weight?: number | null;
|
||||
user: Omit<T, "credentials"> & { credentials: CredentialForCalendarService[] };
|
||||
}[];
|
||||
}> {
|
||||
const { hosts: normalizedHosts, fallbackHosts: fallbackUsers } =
|
||||
await getNormalizedHostsWithDelegationCredentials({
|
||||
eventType,
|
||||
});
|
||||
// not a team event type, or some other reason - segment matching isn't necessary.
|
||||
if (!normalizedHosts) {
|
||||
const fixedHosts = fallbackUsers.filter(isFixedHost);
|
||||
const roundRobinHosts = fallbackUsers.filter(isRoundRobinHost);
|
||||
return { qualifiedRRHosts: roundRobinHosts, fixedHosts };
|
||||
}
|
||||
|
||||
const fixedHosts = normalizedHosts.filter(isFixedHost);
|
||||
const roundRobinHosts = normalizedHosts.filter(isRoundRobinHost);
|
||||
|
||||
// If it is rerouting, we should not force reschedule with same host.
|
||||
const hostsAfterRescheduleWithSameRoundRobinHost = applyFilterWithFallback(
|
||||
roundRobinHosts,
|
||||
await this.dependencies.filterHostsService.filterHostsBySameRoundRobinHost({
|
||||
hosts: roundRobinHosts,
|
||||
rescheduleUid,
|
||||
rescheduleWithSameRoundRobinHost: eventType.rescheduleWithSameRoundRobinHost,
|
||||
routedTeamMemberIds,
|
||||
})
|
||||
);
|
||||
|
||||
if (hostsAfterRescheduleWithSameRoundRobinHost.length === 1) {
|
||||
return {
|
||||
qualifiedRRHosts: hostsAfterRescheduleWithSameRoundRobinHost,
|
||||
fixedHosts,
|
||||
};
|
||||
}
|
||||
|
||||
const hostsAfterSegmentMatching = applyFilterWithFallback(
|
||||
hostsAfterRescheduleWithSameRoundRobinHost,
|
||||
(await findMatchingHostsWithEventSegment({
|
||||
eventType,
|
||||
hosts: hostsAfterRescheduleWithSameRoundRobinHost,
|
||||
})) as typeof hostsAfterRescheduleWithSameRoundRobinHost
|
||||
);
|
||||
|
||||
if (hostsAfterSegmentMatching.length === 1) {
|
||||
return {
|
||||
qualifiedRRHosts: hostsAfterSegmentMatching,
|
||||
fixedHosts,
|
||||
};
|
||||
}
|
||||
|
||||
//if segment matching doesn't return any hosts we fall back to all round robin hosts
|
||||
const officalRRHosts = hostsAfterSegmentMatching.length
|
||||
? hostsAfterSegmentMatching
|
||||
: hostsAfterRescheduleWithSameRoundRobinHost;
|
||||
|
||||
const hostsAfterContactOwnerMatching = applyFilterWithFallback(
|
||||
officalRRHosts,
|
||||
officalRRHosts.filter((host) => host.user.email === contactOwnerEmail)
|
||||
);
|
||||
|
||||
const hostsAfterRoutedTeamMemberIdsMatching = applyFilterWithFallback(
|
||||
officalRRHosts,
|
||||
officalRRHosts.filter((host) => routedTeamMemberIds.includes(host.user.id))
|
||||
);
|
||||
|
||||
if (hostsAfterRoutedTeamMemberIdsMatching.length === 1) {
|
||||
if (hostsAfterContactOwnerMatching.length === 1) {
|
||||
return {
|
||||
qualifiedRRHosts: hostsAfterContactOwnerMatching,
|
||||
allFallbackRRHosts: getFallBackWithContactOwner(
|
||||
hostsAfterRoutedTeamMemberIdsMatching,
|
||||
hostsAfterContactOwnerMatching[0]
|
||||
),
|
||||
fixedHosts,
|
||||
};
|
||||
}
|
||||
return {
|
||||
qualifiedRRHosts: hostsAfterRoutedTeamMemberIdsMatching,
|
||||
fixedHosts,
|
||||
};
|
||||
}
|
||||
|
||||
const hostsAfterFairnessMatching = applyFilterWithFallback(
|
||||
hostsAfterRoutedTeamMemberIdsMatching,
|
||||
await filterHostsByLeadThreshold({
|
||||
eventType,
|
||||
hosts: hostsAfterRoutedTeamMemberIdsMatching,
|
||||
maxLeadThreshold: eventType.maxLeadThreshold ?? null,
|
||||
routingFormResponse,
|
||||
})
|
||||
);
|
||||
|
||||
if (hostsAfterContactOwnerMatching.length === 1) {
|
||||
return {
|
||||
qualifiedRRHosts: hostsAfterContactOwnerMatching,
|
||||
allFallbackRRHosts: getFallBackWithContactOwner(
|
||||
hostsAfterFairnessMatching,
|
||||
hostsAfterContactOwnerMatching[0]
|
||||
),
|
||||
fixedHosts,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
qualifiedRRHosts: hostsAfterFairnessMatching,
|
||||
// only if fairness filtering is active
|
||||
allFallbackRRHosts:
|
||||
hostsAfterFairnessMatching.length !== hostsAfterRoutedTeamMemberIdsMatching.length
|
||||
? hostsAfterRoutedTeamMemberIdsMatching
|
||||
: undefined,
|
||||
fixedHosts,
|
||||
};
|
||||
}
|
||||
|
||||
findQualifiedHostsWithDelegationCredentials = withReporting(
|
||||
this._findQualifiedHostsWithDelegationCredentials.bind(this),
|
||||
"findQualifiedHostsWithDelegationCredentials"
|
||||
);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
import { getRoutedUsersWithContactOwnerAndFixedUsers } from "./getRoutedUsers";
|
||||
|
||||
vi.mock("@calcom/prisma", () => {
|
||||
return {
|
||||
default: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
describe("getRoutedUsersWithContactOwnerAndFixedUsers", () => {
|
||||
const users = [
|
||||
{ id: 1, email: "[email protected]", isFixed: false },
|
||||
{ id: 2, email: "[email protected]", isFixed: true },
|
||||
{ id: 3, email: "[email protected]", isFixed: false },
|
||||
{ id: 4, email: "[email protected]", isFixed: false },
|
||||
];
|
||||
|
||||
const usersWithoutFixedHosts = users.map((user) => ({ ...user, isFixed: false }));
|
||||
|
||||
it("should return all users when routedTeamMemberIds is null", () => {
|
||||
const result = getRoutedUsersWithContactOwnerAndFixedUsers({
|
||||
routedTeamMemberIds: null,
|
||||
users,
|
||||
contactOwnerEmail: "[email protected]",
|
||||
});
|
||||
expect(result).toEqual(users);
|
||||
});
|
||||
|
||||
it("should return all users when routedTeamMemberIds is empty - We don't want to enter a scenario where we have no team members to be booked", () => {
|
||||
const result = getRoutedUsersWithContactOwnerAndFixedUsers({
|
||||
routedTeamMemberIds: [],
|
||||
users,
|
||||
contactOwnerEmail: "[email protected]",
|
||||
});
|
||||
expect(result).toEqual(users);
|
||||
});
|
||||
|
||||
it("should filter users based on routedTeamMemberIds, isFixed, and contactOwnerEmail", () => {
|
||||
const result = getRoutedUsersWithContactOwnerAndFixedUsers({
|
||||
routedTeamMemberIds: [1, 3],
|
||||
users,
|
||||
contactOwnerEmail: "[email protected]",
|
||||
});
|
||||
expect(result).toEqual([
|
||||
{ id: 1, email: "[email protected]", isFixed: false },
|
||||
{ id: 2, email: "[email protected]", isFixed: true },
|
||||
{ id: 3, email: "[email protected]", isFixed: false },
|
||||
{ id: 4, email: "[email protected]", isFixed: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should return an empty array when neither fixed, nor routedTeamMemberIds, nor contactOwnerEmail match", () => {
|
||||
const result = getRoutedUsersWithContactOwnerAndFixedUsers({
|
||||
routedTeamMemberIds: [5],
|
||||
users: usersWithoutFixedHosts,
|
||||
contactOwnerEmail: "[email protected]",
|
||||
});
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return fixed hosts even if routedTeamMemberIds and contactOwnerEmail are invalid ", () => {
|
||||
const result = getRoutedUsersWithContactOwnerAndFixedUsers({
|
||||
routedTeamMemberIds: [5],
|
||||
users,
|
||||
contactOwnerEmail: "[email protected]",
|
||||
});
|
||||
expect(result).toEqual([{ id: 2, email: "[email protected]", isFixed: true }]);
|
||||
});
|
||||
});
|
||||
@@ -1,216 +0,0 @@
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { findTeamMembersMatchingAttributeLogic } from "@calcom/lib/raqb/findTeamMembersMatchingAttributeLogic";
|
||||
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import type { RRResetInterval } from "@calcom/prisma/client";
|
||||
import type { RRTimestampBasis } from "@calcom/prisma/enums";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import type { CredentialPayload } from "@calcom/types/Credential";
|
||||
|
||||
import { enrichHostsWithDelegationCredentials } from "../delegationCredential/server";
|
||||
import getOrgIdFromMemberOrTeamId from "../getOrgIdFromMemberOrTeamId";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[getRoutedUsers]"] });
|
||||
|
||||
export const getRoutedUsersWithContactOwnerAndFixedUsers = <
|
||||
T extends { id: number; isFixed?: boolean; email: string }
|
||||
>({
|
||||
routedTeamMemberIds,
|
||||
users,
|
||||
contactOwnerEmail,
|
||||
}: {
|
||||
routedTeamMemberIds: number[] | null;
|
||||
users: T[];
|
||||
contactOwnerEmail: string | null;
|
||||
}) => {
|
||||
// We don't want to enter a scenario where we have no team members to be booked
|
||||
// So, let's just fallback to regular flow if no routedTeamMemberIds are provided
|
||||
if (!routedTeamMemberIds || !routedTeamMemberIds.length) {
|
||||
return users;
|
||||
}
|
||||
|
||||
log.debug(
|
||||
"filtering users as per routedTeamMemberIds",
|
||||
safeStringify({ routedTeamMemberIds, contactOwnerEmail })
|
||||
);
|
||||
return users.filter(
|
||||
(user) => routedTeamMemberIds.includes(user.id) || user.isFixed || user.email === contactOwnerEmail
|
||||
);
|
||||
};
|
||||
|
||||
async function findMatchingTeamMembersIdsForEventRRSegment(eventType: EventType) {
|
||||
if (!eventType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isSegmentationDisabled = !eventType.assignAllTeamMembers || !eventType.assignRRMembersUsingSegment;
|
||||
|
||||
if (isSegmentationDisabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!eventType.team || !eventType.team.parentId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { teamMembersMatchingAttributeLogic } = await findTeamMembersMatchingAttributeLogic({
|
||||
attributesQueryValue: eventType.rrSegmentQueryValue ?? null,
|
||||
teamId: eventType.team.id,
|
||||
orgId: eventType.team.parentId,
|
||||
});
|
||||
if (!teamMembersMatchingAttributeLogic) {
|
||||
return teamMembersMatchingAttributeLogic;
|
||||
}
|
||||
return teamMembersMatchingAttributeLogic.map((member) => member.userId);
|
||||
}
|
||||
|
||||
type BaseUser = {
|
||||
id: number;
|
||||
email: string;
|
||||
};
|
||||
|
||||
type BaseHost<User extends BaseUser> = {
|
||||
isFixed: boolean;
|
||||
createdAt: Date;
|
||||
priority?: number | null;
|
||||
weight?: number | null;
|
||||
weightAdjustment?: number | null;
|
||||
user: User;
|
||||
groupId: string | null;
|
||||
};
|
||||
|
||||
export type EventType = {
|
||||
assignAllTeamMembers: boolean;
|
||||
assignRRMembersUsingSegment: boolean;
|
||||
rrSegmentQueryValue: AttributesQueryValue | null | undefined;
|
||||
team: {
|
||||
id: number;
|
||||
parentId: number | null;
|
||||
rrResetInterval: RRResetInterval | null;
|
||||
rrTimestampBasis: RRTimestampBasis;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export function getNormalizedHosts<User extends BaseUser, Host extends BaseHost<User>>({
|
||||
eventType,
|
||||
}: {
|
||||
eventType: {
|
||||
schedulingType: SchedulingType | null;
|
||||
hosts?: Host[];
|
||||
users: User[];
|
||||
};
|
||||
}) {
|
||||
if (eventType.hosts?.length && eventType.schedulingType) {
|
||||
return {
|
||||
hosts: eventType.hosts.map((host) => ({
|
||||
isFixed: host.isFixed,
|
||||
user: host.user,
|
||||
priority: host.priority,
|
||||
weight: host.weight,
|
||||
createdAt: host.createdAt,
|
||||
groupId: host.groupId,
|
||||
})),
|
||||
fallbackHosts: null,
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
hosts: null,
|
||||
fallbackHosts: eventType.users.map((user) => {
|
||||
return {
|
||||
isFixed: !eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE,
|
||||
email: user.email,
|
||||
user: user,
|
||||
createdAt: null,
|
||||
groupId: null,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
type BaseUserWithCredentialPayload = BaseUser & { credentials: CredentialPayload[] };
|
||||
export async function getNormalizedHostsWithDelegationCredentials<
|
||||
User extends BaseUserWithCredentialPayload,
|
||||
Host extends BaseHost<User>
|
||||
>({
|
||||
eventType,
|
||||
}: {
|
||||
eventType: {
|
||||
schedulingType: SchedulingType | null;
|
||||
hosts?: Host[];
|
||||
users: User[];
|
||||
teamId?: number;
|
||||
};
|
||||
}) {
|
||||
if (eventType.hosts?.length && eventType.schedulingType) {
|
||||
const hostsWithoutDelegationCredential = eventType.hosts.map((host) => ({
|
||||
isFixed: host.isFixed,
|
||||
user: host.user,
|
||||
priority: host.priority,
|
||||
weight: host.weight,
|
||||
createdAt: host.createdAt,
|
||||
groupId: host.groupId,
|
||||
}));
|
||||
const firstHost = hostsWithoutDelegationCredential[0];
|
||||
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
|
||||
memberId: firstHost?.user?.id ?? null,
|
||||
teamId: eventType.teamId,
|
||||
});
|
||||
const hostsEnrichedWithDelegationCredential = await enrichHostsWithDelegationCredentials({
|
||||
orgId: firstUserOrgId ?? null,
|
||||
hosts: hostsWithoutDelegationCredential ?? null,
|
||||
});
|
||||
return {
|
||||
hosts: hostsEnrichedWithDelegationCredential,
|
||||
fallbackHosts: null,
|
||||
};
|
||||
} else {
|
||||
const hostsWithoutDelegationCredential = eventType.users.map((user) => {
|
||||
return {
|
||||
isFixed: !eventType.schedulingType || eventType.schedulingType === SchedulingType.COLLECTIVE,
|
||||
email: user.email,
|
||||
user: user,
|
||||
createdAt: null,
|
||||
};
|
||||
});
|
||||
const firstHost = hostsWithoutDelegationCredential[0];
|
||||
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
|
||||
memberId: firstHost?.user?.id ?? null,
|
||||
teamId: eventType.teamId,
|
||||
});
|
||||
const hostsEnrichedWithDelegationCredential = await enrichHostsWithDelegationCredentials({
|
||||
orgId: firstUserOrgId ?? null,
|
||||
hosts: hostsWithoutDelegationCredential ?? null,
|
||||
});
|
||||
return {
|
||||
hosts: null,
|
||||
fallbackHosts: hostsEnrichedWithDelegationCredential,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// We don't allow fixed hosts when segment matching is enabled
|
||||
// If this ever changes, we need to update this function and return fixed hosts
|
||||
export async function findMatchingHostsWithEventSegment<User extends BaseUser>({
|
||||
eventType,
|
||||
hosts,
|
||||
}: {
|
||||
eventType: EventType;
|
||||
hosts: {
|
||||
isFixed: boolean;
|
||||
user: User;
|
||||
priority?: number | null;
|
||||
weight?: number | null;
|
||||
createdAt: Date | null;
|
||||
groupId: string | null;
|
||||
}[];
|
||||
}) {
|
||||
const matchingRRTeamMembers = await findMatchingTeamMembersIdsForEventRRSegment({
|
||||
...eventType,
|
||||
rrSegmentQueryValue: eventType.rrSegmentQueryValue ?? null,
|
||||
});
|
||||
const segmentedRoundRobinHosts = hosts.filter((host) => {
|
||||
if (!matchingRRTeamMembers) return true;
|
||||
return matchingRRTeamMembers.includes(host.user.id);
|
||||
});
|
||||
return segmentedRoundRobinHosts;
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
import { mockCrmApp } from "@calcom/web/test/utils/bookingScenario/bookingScenario";
|
||||
|
||||
import type { TFunction } from "i18next";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { getCrm } from "@calcom/app-store/_utils/getCrm";
|
||||
|
||||
import CrmManager from "./crmManager";
|
||||
|
||||
// vi.mock("@calcom/app-store/_utils/getCrm");
|
||||
|
||||
describe.skip("crmManager tests", () => {
|
||||
test("Set crmService if not set", async () => {
|
||||
const spy = vi.spyOn(CrmManager.prototype as any, "getCrmService");
|
||||
const crmManager = new CrmManager({
|
||||
id: 1,
|
||||
type: "credential_crm",
|
||||
key: {},
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
appId: "crm-app",
|
||||
invalid: false,
|
||||
user: { email: "[email protected]" },
|
||||
});
|
||||
expect(crmManager.crmService).toBe(null);
|
||||
|
||||
crmManager.getContacts(["[email protected]"]);
|
||||
|
||||
expect(spy).toBeCalledTimes(1);
|
||||
});
|
||||
describe("creating events", () => {
|
||||
test("If the contact exists, create the event", async () => {
|
||||
const tFunc = vi.fn(() => "foo");
|
||||
vi.spyOn(getCrm).mockReturnValue({
|
||||
getContacts: () => [
|
||||
{
|
||||
id: "contact-id",
|
||||
email: "[email protected]",
|
||||
},
|
||||
],
|
||||
createContacts: [{ id: "contact-id", email: "[email protected]" }],
|
||||
});
|
||||
// This mock is defaulting to non implemented mock return
|
||||
const mockedCrmApp = mockCrmApp("salesforce", {
|
||||
getContacts: [
|
||||
{
|
||||
id: "contact-id",
|
||||
email: "[email protected]",
|
||||
},
|
||||
],
|
||||
createContacts: [{ id: "contact-id", email: "[email protected]" }],
|
||||
});
|
||||
|
||||
const crmManager = new CrmManager({
|
||||
id: 1,
|
||||
type: "salesforce_crm",
|
||||
key: {
|
||||
clientId: "test-client-id",
|
||||
},
|
||||
userId: 1,
|
||||
teamId: null,
|
||||
appId: "salesforce",
|
||||
invalid: false,
|
||||
user: { email: "[email protected]" },
|
||||
});
|
||||
|
||||
crmManager.createEvent({
|
||||
title: "Test Meeting",
|
||||
type: "test-meeting",
|
||||
description: "Test Description",
|
||||
startTime: Date(),
|
||||
endTime: Date(),
|
||||
organizer: {
|
||||
email: "[email protected]",
|
||||
name: "Organizer",
|
||||
timeZone: "America/New_York",
|
||||
language: {
|
||||
locale: "en",
|
||||
translate: tFunc as TFunction,
|
||||
},
|
||||
},
|
||||
attendees: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
name: "Test",
|
||||
timeZone: "America/New_York",
|
||||
language: {
|
||||
locale: "en",
|
||||
translate: tFunc as TFunction,
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
console.log(mockedCrmApp);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,92 +0,0 @@
|
||||
import getCrm from "@calcom/app-store/_utils/getCrm";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { CalendarEvent, CalEventResponses } from "@calcom/types/Calendar";
|
||||
import type { CredentialPayload } from "@calcom/types/Credential";
|
||||
import type { CRM, ContactCreateInput } from "@calcom/types/CrmService";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["CrmManager"] });
|
||||
export default class CrmManager {
|
||||
crmService: CRM | null | undefined = null;
|
||||
credential: CredentialPayload;
|
||||
appOptions: any;
|
||||
constructor(credential: CredentialPayload, appOptions?: any) {
|
||||
this.credential = credential;
|
||||
this.appOptions = appOptions;
|
||||
}
|
||||
|
||||
private async getCrmService(credential: CredentialPayload) {
|
||||
if (this.crmService) return this.crmService;
|
||||
const crmService = await getCrm(credential, this.appOptions);
|
||||
this.crmService = crmService;
|
||||
|
||||
if (!this.crmService) {
|
||||
console.log("💀 Error initializing CRM service");
|
||||
log.error("CRM service initialization failed");
|
||||
}
|
||||
|
||||
return crmService;
|
||||
}
|
||||
|
||||
public async createEvent(event: CalendarEvent) {
|
||||
const crmService = await this.getCrmService(this.credential);
|
||||
if (!crmService) return;
|
||||
const { skipContactCreation = false, ignoreGuests = false } = crmService.getAppOptions() || {};
|
||||
const eventAttendees = ignoreGuests ? [event.attendees[0]] : event.attendees;
|
||||
// First see if the attendees already exist in the crm
|
||||
let contacts = (await this.getContacts({ emails: eventAttendees.map((a) => a.email) })) || [];
|
||||
// Ensure that all attendees are in the crm
|
||||
if (contacts.length == eventAttendees.length) {
|
||||
return await crmService.createEvent(event, contacts);
|
||||
}
|
||||
|
||||
if (skipContactCreation) return;
|
||||
const contactSet = new Set(contacts.map((c: { email: string }) => c.email));
|
||||
// Figure out which contacts to create
|
||||
const contactsToCreate = eventAttendees.filter((attendee) => !contactSet.has(attendee.email));
|
||||
const createdContacts = await this.createContacts(
|
||||
contactsToCreate,
|
||||
event.organizer?.email,
|
||||
event.responses
|
||||
);
|
||||
contacts = contacts.concat(createdContacts);
|
||||
return await crmService.createEvent(event, contacts);
|
||||
}
|
||||
|
||||
public async updateEvent(uid: string, event: CalendarEvent) {
|
||||
const crmService = await this.getCrmService(this.credential);
|
||||
return await crmService?.updateEvent(uid, event);
|
||||
}
|
||||
|
||||
public async deleteEvent(uid: string, event: CalendarEvent) {
|
||||
const crmService = await this.getCrmService(this.credential);
|
||||
return await crmService?.deleteEvent(uid, event);
|
||||
}
|
||||
|
||||
public async getContacts(params: {
|
||||
emails: string | string[];
|
||||
includeOwner?: boolean;
|
||||
forRoundRobinSkip?: boolean;
|
||||
}) {
|
||||
const crmService = await this.getCrmService(this.credential);
|
||||
const contacts = await crmService?.getContacts(params);
|
||||
return contacts;
|
||||
}
|
||||
|
||||
public async createContacts(
|
||||
contactsToCreate: ContactCreateInput[],
|
||||
organizerEmail?: string,
|
||||
calEventResponses?: CalEventResponses | null
|
||||
) {
|
||||
const crmService = await this.getCrmService(this.credential);
|
||||
const createdContacts =
|
||||
(await crmService?.createContacts(contactsToCreate, organizerEmail, calEventResponses)) || [];
|
||||
return createdContacts;
|
||||
}
|
||||
|
||||
public async handleAttendeeNoShow(bookingUid: string, attendees: { email: string; noShow: boolean }[]) {
|
||||
const crmService = await this.getCrmService(this.credential);
|
||||
if (crmService?.handleAttendeeNoShow) {
|
||||
await crmService.handleAttendeeNoShow(bookingUid, attendees);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { IOutOfOfficeData } from "@calcom/lib/getUserAvailability";
|
||||
import type { IOutOfOfficeData } from "@calcom/features/availability/lib/getUserAvailability";
|
||||
import type { Availability } from "@calcom/prisma/client";
|
||||
|
||||
export type DateRange = {
|
||||
|
||||
File renamed without changes.
@@ -1,620 +0,0 @@
|
||||
import { setupAndTeardown } from "@calcom/web/test/utils/bookingScenario/setupAndTeardown";
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
import { metadata as googleCalendarMetadata } from "@calcom/app-store/googlecalendar/_metadata";
|
||||
import { metadata as googleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
|
||||
import type { ServiceAccountKey } from "@calcom/lib/server/repository/delegationCredential";
|
||||
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
|
||||
import { OrganizationRepository } from "@calcom/lib/server/repository/organization";
|
||||
import { SMSLockState } from "@calcom/prisma/enums";
|
||||
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
|
||||
|
||||
import {
|
||||
buildAllCredentials,
|
||||
getDelegationCredentialOrRegularCredential,
|
||||
enrichUsersWithDelegationCredentials,
|
||||
enrichHostsWithDelegationCredentials,
|
||||
enrichUserWithDelegationCredentialsIncludeServiceAccountKey,
|
||||
enrichUserWithDelegationConferencingCredentialsWithoutOrgId,
|
||||
getAllDelegationCredentialsForUserIncludeServiceAccountKey,
|
||||
} from "./server";
|
||||
|
||||
// Mock OrganizationRepository
|
||||
vi.mock("@calcom/lib/server/repository/organization", () => ({
|
||||
OrganizationRepository: {
|
||||
findByMemberEmail: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock DelegationCredentialRepository
|
||||
vi.mock("@calcom/lib/server/repository/delegationCredential", () => ({
|
||||
DelegationCredentialRepository: {
|
||||
findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey: vi.fn(),
|
||||
findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockUser = {
|
||||
email: "[email protected]",
|
||||
id: 123,
|
||||
};
|
||||
|
||||
const mockServiceAccountKey: ServiceAccountKey = {
|
||||
client_email: "[email protected]",
|
||||
client_id: "123456789",
|
||||
private_key: "-----BEGIN PRIVATE KEY-----\nMIIE....\n-----END PRIVATE KEY-----\n",
|
||||
};
|
||||
|
||||
const mockWorkspacePlatform = {
|
||||
name: "Test Platform",
|
||||
slug: "google",
|
||||
};
|
||||
|
||||
const mockDelegationCredential = {
|
||||
id: "delegationCredential-1",
|
||||
enabled: true,
|
||||
domain: "example.com",
|
||||
organizationId: 1,
|
||||
serviceAccountKey: mockServiceAccountKey,
|
||||
workspacePlatform: mockWorkspacePlatform,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
// Mock organization data
|
||||
const mockOrganization = {
|
||||
id: 1,
|
||||
name: "Test Org",
|
||||
metadata: {},
|
||||
bio: null,
|
||||
timeZone: "UTC",
|
||||
weekStart: "Monday",
|
||||
hideBranding: false,
|
||||
theme: null,
|
||||
timeFormat: null,
|
||||
brandColor: null,
|
||||
darkBrandColor: null,
|
||||
createdAt: new Date(),
|
||||
includeManagedEventsInLimits: false,
|
||||
smsLockState: SMSLockState.LOCKED,
|
||||
smsLockReviewedByAdmin: false,
|
||||
slug: "test-org",
|
||||
logoUrl: null,
|
||||
bannerUrl: null,
|
||||
isPrivate: false,
|
||||
isOrganization: true,
|
||||
isOrganizationVerified: true,
|
||||
isOrganizationConfigured: true,
|
||||
isOrganizationAdminReviewed: true,
|
||||
orgAutoAcceptEmail: "example.com",
|
||||
orgProfileRedirectsToVerifiedDomain: false,
|
||||
allowSEOIndexing: true,
|
||||
calVideoLogo: null,
|
||||
appLogo: null,
|
||||
appIconLogo: null,
|
||||
hideBookATeamMember: false,
|
||||
hideTeam: false,
|
||||
hideCalendarNotes: false,
|
||||
eventTypeMatchParentTeam: false,
|
||||
lockEventTypeCreationForUsers: false,
|
||||
parentId: null,
|
||||
pendingPayment: false,
|
||||
isPlatform: false,
|
||||
createdByOAuthClientId: null,
|
||||
bookingLimits: null,
|
||||
};
|
||||
|
||||
// Credential Builders
|
||||
const buildDelegationCredential = (overrides = {}) => ({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: -1,
|
||||
delegatedToId: mockDelegationCredential.id,
|
||||
userId: mockUser.id,
|
||||
user: { email: mockUser.email },
|
||||
key: { access_token: "NOOP_UNUSED_DELEGATION_TOKEN" },
|
||||
invalid: false,
|
||||
teamId: null,
|
||||
team: null,
|
||||
// In-memory delegation credential has it set to null
|
||||
delegationCredentialId: mockDelegationCredential.id,
|
||||
delegatedTo: {
|
||||
serviceAccountKey: mockServiceAccountKey,
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const buildGoogleCalendarDelegationCredential = (overrides = {}) => ({
|
||||
...buildDelegationCredential({
|
||||
type: googleCalendarMetadata.type,
|
||||
appId: googleCalendarMetadata.slug,
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const buildDelegationCredentialGoogleMeetCredential = (overrides = {}) => ({
|
||||
...buildDelegationCredential({
|
||||
type: googleMeetMetadata.type,
|
||||
appId: googleMeetMetadata.slug,
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const buildRegularCredential = (overrides = {}): CredentialForCalendarService => ({
|
||||
type: "google_calendar",
|
||||
appId: "google-calendar",
|
||||
id: 1,
|
||||
userId: mockUser.id,
|
||||
user: { email: mockUser.email },
|
||||
key: JSON.stringify(mockServiceAccountKey),
|
||||
invalid: false,
|
||||
teamId: null,
|
||||
delegatedToId: null,
|
||||
delegatedTo: null,
|
||||
// Regular credentials have it set to null always
|
||||
delegationCredentialId: null,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const buildRegularGoogleCalendarCredential = (overrides = {}): CredentialPayload => ({
|
||||
...buildRegularCredential({
|
||||
appId: "google-calendar",
|
||||
type: "google_calendar",
|
||||
}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const buildMockWorkspacePlatform = (overrides: Partial<typeof mockWorkspacePlatform> = {}) => ({
|
||||
name: "Test Platform",
|
||||
slug: "google",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const buildMockDelegationCredential = (overrides: Partial<typeof mockDelegationCredential> = {}) => ({
|
||||
...mockDelegationCredential,
|
||||
workspacePlatform: buildMockWorkspacePlatform(overrides.workspacePlatform || {}),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("getAllDelegationCredentialsForUserIncludeServiceAccountKey", () => {
|
||||
setupAndTeardown();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(OrganizationRepository.findByMemberEmail).mockResolvedValue(mockOrganization);
|
||||
});
|
||||
|
||||
it("should return empty array when no DelegationCredential found", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(null);
|
||||
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return empty array when DelegationCredential is disabled", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
|
||||
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return credentials for enabled Google DelegationCredential", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential());
|
||||
const result = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({ user: mockUser });
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toEqual([
|
||||
buildGoogleCalendarDelegationCredential(),
|
||||
buildDelegationCredentialGoogleMeetCredential(),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAllCredentials", () => {
|
||||
const mockDelegationCredentialGoogleCalendarCred = buildGoogleCalendarDelegationCredential();
|
||||
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
|
||||
|
||||
it("should combine DelegationCredential and regular credentials", () => {
|
||||
const result = buildAllCredentials({
|
||||
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred],
|
||||
existingCredentials: [mockRegularGoogleCalendarCred],
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
|
||||
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
|
||||
});
|
||||
|
||||
it("should deduplicate DelegationCredential credentials with same delegatedToId and appId", () => {
|
||||
const duplicateDelegationCredential = buildGoogleCalendarDelegationCredential();
|
||||
const result = buildAllCredentials({
|
||||
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred, duplicateDelegationCredential],
|
||||
existingCredentials: [],
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual(mockDelegationCredentialGoogleCalendarCred);
|
||||
});
|
||||
|
||||
it("should keep DelegationCredential credentials with same delegatedToId but different appId", () => {
|
||||
const differentAppDelegationCredential = buildDelegationCredentialGoogleMeetCredential();
|
||||
const result = buildAllCredentials({
|
||||
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred, differentAppDelegationCredential],
|
||||
existingCredentials: [],
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
|
||||
expect(result).toContainEqual(differentAppDelegationCredential);
|
||||
});
|
||||
|
||||
it("should filter out DelegationCredential credentials from existingCredentials", () => {
|
||||
const delegatedCalendarCredential = buildRegularGoogleCalendarCredential({ id: -2 });
|
||||
const result = buildAllCredentials({
|
||||
delegationCredentials: [mockDelegationCredentialGoogleCalendarCred],
|
||||
existingCredentials: [mockRegularGoogleCalendarCred, delegatedCalendarCredential],
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toContainEqual(mockDelegationCredentialGoogleCalendarCred);
|
||||
expect(result).toContainEqual(mockRegularGoogleCalendarCred);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDelegationCredentialOrRegularCredential", () => {
|
||||
const mockDelegationCredentialGoogleCalendarCred = buildGoogleCalendarDelegationCredential();
|
||||
const mockRegularGoogleCalendarCred = buildRegularGoogleCalendarCredential();
|
||||
const credentials = [mockDelegationCredentialGoogleCalendarCred, mockRegularGoogleCalendarCred];
|
||||
|
||||
it("should find Delegation credential by delegationCredentialId", () => {
|
||||
const result = getDelegationCredentialOrRegularCredential({
|
||||
credentials,
|
||||
id: { credentialId: null, delegationCredentialId: mockDelegationCredential.id },
|
||||
});
|
||||
expect(result).toEqual(mockDelegationCredentialGoogleCalendarCred);
|
||||
});
|
||||
|
||||
it("should find regular credential by credentialId", () => {
|
||||
const result = getDelegationCredentialOrRegularCredential({
|
||||
credentials,
|
||||
id: { credentialId: mockRegularGoogleCalendarCred.id, delegationCredentialId: null },
|
||||
});
|
||||
expect(result).toEqual(mockRegularGoogleCalendarCred);
|
||||
});
|
||||
|
||||
it("should return null when no matching credential found", () => {
|
||||
const result = getDelegationCredentialOrRegularCredential({
|
||||
credentials,
|
||||
id: { credentialId: 999, delegationCredentialId: null },
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should not match null to null for delegatedToId", () => {
|
||||
const result = getDelegationCredentialOrRegularCredential({
|
||||
credentials,
|
||||
id: { credentialId: null, delegationCredentialId: null },
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("enrichUsersWithDelegationCredentials", () => {
|
||||
const mockUsers = [
|
||||
{
|
||||
...mockUser,
|
||||
credentials: [buildRegularGoogleCalendarCredential()],
|
||||
},
|
||||
{
|
||||
id: 456,
|
||||
email: "[email protected]",
|
||||
credentials: [buildRegularGoogleCalendarCredential({ id: 2 })],
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should return users as is when orgId is null", async () => {
|
||||
const result = await enrichUsersWithDelegationCredentials({
|
||||
orgId: null,
|
||||
users: mockUsers,
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
mockUsers.map((user) => ({
|
||||
...user,
|
||||
credentials: user.credentials.map((cred) => ({
|
||||
...cred,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
})),
|
||||
}))
|
||||
);
|
||||
});
|
||||
|
||||
it("should enrich users with DelegationCredential credentials when available", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential());
|
||||
|
||||
const result = await enrichUsersWithDelegationCredentials({
|
||||
orgId: 1,
|
||||
users: mockUsers,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
result.forEach((enrichedUser) => {
|
||||
expect(enrichedUser.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
|
||||
expect(enrichedUser.credentials).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: googleCalendarMetadata.type,
|
||||
appId: googleCalendarMetadata.slug,
|
||||
})
|
||||
);
|
||||
expect(enrichedUser.credentials).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: googleMeetMetadata.type,
|
||||
appId: googleMeetMetadata.slug,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
|
||||
|
||||
const result = await enrichUsersWithDelegationCredentials({
|
||||
orgId: 1,
|
||||
users: mockUsers,
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
mockUsers.map((user) => ({
|
||||
...user,
|
||||
credentials: user.credentials.map((cred) => ({
|
||||
...cred,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
})),
|
||||
}))
|
||||
);
|
||||
});
|
||||
|
||||
it("should return empty array when users is empty", async () => {
|
||||
const result = await enrichUsersWithDelegationCredentials({
|
||||
orgId: 1,
|
||||
users: [],
|
||||
});
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("enrichHostsWithDelegationCredentials", () => {
|
||||
const mockHosts = [
|
||||
{
|
||||
user: {
|
||||
...mockUser,
|
||||
credentials: [buildRegularGoogleCalendarCredential()],
|
||||
},
|
||||
metadata: { key: "value" },
|
||||
},
|
||||
{
|
||||
user: {
|
||||
id: 456,
|
||||
email: "[email protected]",
|
||||
credentials: [buildRegularGoogleCalendarCredential({ id: 2 })],
|
||||
},
|
||||
metadata: { key: "value2" },
|
||||
},
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should return hosts as is when orgId is null", async () => {
|
||||
const result = await enrichHostsWithDelegationCredentials({
|
||||
orgId: null,
|
||||
hosts: mockHosts,
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
mockHosts.map((host) => ({
|
||||
...host,
|
||||
user: {
|
||||
...host.user,
|
||||
credentials: host.user.credentials.map((cred) => ({
|
||||
...cred,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
})),
|
||||
},
|
||||
}))
|
||||
);
|
||||
});
|
||||
|
||||
it("should enrich hosts with DelegationCredential credentials when available", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential());
|
||||
|
||||
const result = await enrichHostsWithDelegationCredentials({
|
||||
orgId: 1,
|
||||
hosts: mockHosts,
|
||||
});
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
result.forEach((enrichedHost) => {
|
||||
expect(enrichedHost.metadata).toBeDefined(); // Preserve non-user data
|
||||
expect(enrichedHost.user.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
|
||||
expect(enrichedHost.user.credentials).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: googleCalendarMetadata.type,
|
||||
appId: googleCalendarMetadata.slug,
|
||||
})
|
||||
);
|
||||
expect(enrichedHost.user.credentials).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: googleMeetMetadata.type,
|
||||
appId: googleMeetMetadata.slug,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
|
||||
|
||||
const result = await enrichHostsWithDelegationCredentials({
|
||||
orgId: 1,
|
||||
hosts: mockHosts,
|
||||
});
|
||||
|
||||
expect(result).toEqual(
|
||||
mockHosts.map((host) => ({
|
||||
...host,
|
||||
user: {
|
||||
...host.user,
|
||||
credentials: host.user.credentials.map((cred) => ({
|
||||
...cred,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
})),
|
||||
},
|
||||
}))
|
||||
);
|
||||
});
|
||||
|
||||
it("should return empty array when hosts is empty", async () => {
|
||||
const result = await enrichHostsWithDelegationCredentials({
|
||||
orgId: 1,
|
||||
hosts: [],
|
||||
});
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("enrichUserWithDelegationCredentialsIncludeServiceAccountKey", () => {
|
||||
const mockUserWithCredentials = {
|
||||
...mockUser,
|
||||
credentials: [buildRegularGoogleCalendarCredential()],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should enrich user with DelegationCredential credentials when available", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential());
|
||||
|
||||
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user: mockUserWithCredentials,
|
||||
});
|
||||
|
||||
expect(result.credentials).toHaveLength(3); // 1 regular + 2 DelegationCredential (calendar + meet)
|
||||
expect(result.credentials).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: googleCalendarMetadata.type,
|
||||
appId: googleCalendarMetadata.slug,
|
||||
})
|
||||
);
|
||||
expect(result.credentials).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: googleMeetMetadata.type,
|
||||
appId: googleMeetMetadata.slug,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should not add DelegationCredential credentials when DelegationCredential is not found", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(null);
|
||||
|
||||
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user: mockUserWithCredentials,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
...mockUserWithCredentials,
|
||||
credentials: mockUserWithCredentials.credentials.map((cred) => ({
|
||||
...cred,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
it("should not add DelegationCredential credentials when DelegationCredential is disabled", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential({ enabled: false }));
|
||||
|
||||
const result = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user: mockUserWithCredentials,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
...mockUserWithCredentials,
|
||||
credentials: mockUserWithCredentials.credentials.map((cred) => ({
|
||||
...cred,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
})),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("enrichUserWithDelegationConferencingCredentialsWithoutOrgId", () => {
|
||||
const mockUserWithCredentials = {
|
||||
...mockUser,
|
||||
credentials: [buildRegularGoogleCalendarCredential()],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("should only return conferencing credentials", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(buildMockDelegationCredential());
|
||||
|
||||
const result = await enrichUserWithDelegationConferencingCredentialsWithoutOrgId({
|
||||
user: mockUserWithCredentials,
|
||||
});
|
||||
|
||||
expect(result.credentials).toHaveLength(1); // Only Google Meet
|
||||
expect(result.credentials[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
type: googleMeetMetadata.type,
|
||||
appId: googleMeetMetadata.slug,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("should return empty credentials array when no conferencing credentials found", async () => {
|
||||
vi.mocked(
|
||||
DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey
|
||||
).mockResolvedValue(null);
|
||||
|
||||
const result = await enrichUserWithDelegationConferencingCredentialsWithoutOrgId({
|
||||
user: mockUserWithCredentials,
|
||||
});
|
||||
|
||||
expect(result.credentials).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,682 +0,0 @@
|
||||
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import { metadata as googleCalendarMetadata } from "@calcom/app-store/googlecalendar/_metadata";
|
||||
import { metadata as googleMeetMetadata } from "@calcom/app-store/googlevideo/_metadata";
|
||||
import { metadata as office365CalendarMetaData } from "@calcom/app-store/office365calendar/_metadata";
|
||||
import { metadata as office365VideoMetaData } from "@calcom/app-store/office365video/_metadata";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { CredentialRepository } from "@calcom/lib/server/repository/credential";
|
||||
import type { ServiceAccountKey } from "@calcom/lib/server/repository/delegationCredential";
|
||||
import { DelegationCredentialRepository } from "@calcom/lib/server/repository/delegationCredential";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { SelectedCalendar } from "@calcom/prisma/client";
|
||||
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
|
||||
|
||||
import { UserRepository } from "../server/repository/user";
|
||||
import {
|
||||
buildNonDelegationCredential,
|
||||
buildNonDelegationCredentials,
|
||||
isDelegationCredential,
|
||||
} from "./clientAndServer";
|
||||
|
||||
export { buildNonDelegationCredentials, buildNonDelegationCredential } from "./clientAndServer";
|
||||
|
||||
const GOOGLE_WORKSPACE_SLUG = "google";
|
||||
const OFFICE365_WORKSPACE_SLUG = "office365";
|
||||
const WORKSPACE_PLATFORM_SLUGS = [GOOGLE_WORKSPACE_SLUG, OFFICE365_WORKSPACE_SLUG] as const;
|
||||
type WORKSPACE_PLATFORM_SLUGS_TYPE = (typeof WORKSPACE_PLATFORM_SLUGS)[number];
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["lib/delegationCredential/server"] });
|
||||
interface DelegationCredential {
|
||||
id: string;
|
||||
workspacePlatform: {
|
||||
slug: string;
|
||||
};
|
||||
serviceAccountKey: ServiceAccountKey | null;
|
||||
}
|
||||
|
||||
interface DelegationCredentialWithSensitiveServiceAccountKey extends DelegationCredential {
|
||||
serviceAccountKey: ServiceAccountKey;
|
||||
}
|
||||
|
||||
interface User {
|
||||
email: string;
|
||||
id: number;
|
||||
}
|
||||
|
||||
const isValidWorkspaceSlug = (slug: string) => {
|
||||
return WORKSPACE_PLATFORM_SLUGS.includes(slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE);
|
||||
};
|
||||
|
||||
const getDelegationCredentialAppMetadata = (
|
||||
slug: WORKSPACE_PLATFORM_SLUGS_TYPE,
|
||||
isConferencing?: boolean
|
||||
) => {
|
||||
switch (slug) {
|
||||
case GOOGLE_WORKSPACE_SLUG:
|
||||
return isConferencing
|
||||
? { type: googleMeetMetadata.type, appId: googleMeetMetadata.slug }
|
||||
: { type: googleCalendarMetadata.type, appId: googleCalendarMetadata.slug };
|
||||
|
||||
case OFFICE365_WORKSPACE_SLUG:
|
||||
return isConferencing
|
||||
? { type: office365VideoMetaData.type, appId: office365VideoMetaData.slug }
|
||||
: { type: office365CalendarMetaData.type, appId: office365CalendarMetaData.slug };
|
||||
|
||||
default:
|
||||
throw new Error("App metadata does not exist");
|
||||
}
|
||||
};
|
||||
|
||||
const _isConferencingCredential = (credential: CredentialPayload) => {
|
||||
return (
|
||||
credential.type.endsWith("_video") ||
|
||||
credential.type.endsWith("_conferencing") ||
|
||||
credential.type.endsWith("_messaging")
|
||||
);
|
||||
};
|
||||
|
||||
const _buildCommonUserCredential = ({
|
||||
delegationCredential,
|
||||
user,
|
||||
}: {
|
||||
delegationCredential: DelegationCredential;
|
||||
user: User;
|
||||
}) => {
|
||||
return {
|
||||
id: -1,
|
||||
delegatedToId: delegationCredential.id,
|
||||
userId: user.id,
|
||||
user: {
|
||||
email: user.email,
|
||||
},
|
||||
key: {
|
||||
access_token: "NOOP_UNUSED_DELEGATION_TOKEN",
|
||||
},
|
||||
invalid: false,
|
||||
teamId: null,
|
||||
team: null,
|
||||
delegationCredentialId: delegationCredential.id,
|
||||
delegatedTo: delegationCredential.serviceAccountKey
|
||||
? {
|
||||
serviceAccountKey: delegationCredential.serviceAccountKey,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
};
|
||||
|
||||
const _buildDelegatedCalendarCredential = ({
|
||||
delegationCredential,
|
||||
user,
|
||||
}: {
|
||||
delegationCredential: DelegationCredential;
|
||||
user: User;
|
||||
}) => {
|
||||
log.debug(
|
||||
"buildDelegationCredential",
|
||||
safeStringify({
|
||||
delegationCredential: {
|
||||
id: delegationCredential.id,
|
||||
},
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
},
|
||||
})
|
||||
);
|
||||
// TODO: Build for other platforms as well
|
||||
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
|
||||
log.warn(
|
||||
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
|
||||
delegationCredential.workspacePlatform.slug
|
||||
}`
|
||||
);
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
...getDelegationCredentialAppMetadata(
|
||||
delegationCredential.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE,
|
||||
false
|
||||
),
|
||||
..._buildCommonUserCredential({ delegationCredential, user }),
|
||||
};
|
||||
};
|
||||
|
||||
const _buildDelegatedCalendarCredentialWithServiceAccountKey = ({
|
||||
delegationCredential,
|
||||
user,
|
||||
}: {
|
||||
delegationCredential: DelegationCredentialWithSensitiveServiceAccountKey;
|
||||
user: User;
|
||||
}) => {
|
||||
const credential = _buildDelegatedCalendarCredential({ delegationCredential, user });
|
||||
if (!credential) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
...credential,
|
||||
delegatedTo: {
|
||||
serviceAccountKey: delegationCredential.serviceAccountKey,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const _buildDelegatedConferencingCredential = ({
|
||||
delegationCredential,
|
||||
user,
|
||||
}: {
|
||||
delegationCredential: DelegationCredential;
|
||||
user: User;
|
||||
}) => {
|
||||
// TODO: Build for other platforms as well
|
||||
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
|
||||
log.warn(
|
||||
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
|
||||
delegationCredential.workspacePlatform.slug
|
||||
}`
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...getDelegationCredentialAppMetadata(
|
||||
delegationCredential.workspacePlatform.slug as unknown as WORKSPACE_PLATFORM_SLUGS_TYPE,
|
||||
true
|
||||
),
|
||||
..._buildCommonUserCredential({ delegationCredential, user }),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets calendar as well as conferencing credentials(stored in-memory) for the user from the corresponding enabled DelegationCredential.
|
||||
*/
|
||||
export async function getAllDelegationCredentialsForUserIncludeServiceAccountKey({
|
||||
user,
|
||||
}: {
|
||||
user: { email: string; id: number };
|
||||
}) {
|
||||
log.debug("called with", safeStringify({ user }));
|
||||
// We access the repository without checking for feature flag here.
|
||||
// In case we need to disable the effects of DelegationCredential on credential we need to toggle DelegationCredential off from organization settings.
|
||||
// We could think of the teamFeatures flag to just disable the UI. The actual effect of DelegationCredential on credentials is disabled by toggling DelegationCredential off from UI
|
||||
const delegationCredential =
|
||||
await DelegationCredentialRepository.findUniqueByOrgMemberEmailIncludeSensitiveServiceAccountKey({
|
||||
email: user.email,
|
||||
});
|
||||
|
||||
if (!delegationCredential || !delegationCredential.enabled) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const delegationCredentials = [
|
||||
_buildDelegatedCalendarCredential({ delegationCredential, user }),
|
||||
_buildDelegatedConferencingCredential({ delegationCredential, user }),
|
||||
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
|
||||
|
||||
log.debug("Returned", safeStringify({ delegationCredentials }));
|
||||
return delegationCredentials;
|
||||
}
|
||||
|
||||
export async function getAllDelegationCredentialsForUser({ user }: { user: { email: string; id: number } }) {
|
||||
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
|
||||
user,
|
||||
});
|
||||
return delegationCredentials.map(({ delegatedTo: _1, ...rest }) => {
|
||||
return {
|
||||
...rest,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAllDelegatedCalendarCredentialsForUser({
|
||||
user,
|
||||
}: {
|
||||
user: { email: string; id: number };
|
||||
}) {
|
||||
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
|
||||
user,
|
||||
});
|
||||
const delegationCalendarCredentials = delegationCredentials.filter((credential) =>
|
||||
credential.type.endsWith("_calendar")
|
||||
);
|
||||
return buildAllCredentials({
|
||||
delegationCredentials: delegationCalendarCredentials,
|
||||
existingCredentials: [],
|
||||
});
|
||||
}
|
||||
|
||||
async function _getDelegationCredentialsMapPerUser({
|
||||
organizationId,
|
||||
users,
|
||||
}: {
|
||||
organizationId: number | null;
|
||||
users: User[];
|
||||
}) {
|
||||
const emptyMap = new Map<number, NonNullable<ReturnType<typeof _buildDelegatedCalendarCredential>>[]>();
|
||||
if (!organizationId) {
|
||||
return emptyMap;
|
||||
}
|
||||
// We assume that all users in an organization are from the same domain, so first one should be fine.
|
||||
// TODO: There could be multiple domains in an organization(if an organization is migrating maybe from one to another or for some other reason) and we should actually consider all of them, maybe group by domain.
|
||||
const userThatDeterminesDomain = users[0];
|
||||
if (!userThatDeterminesDomain) {
|
||||
return emptyMap;
|
||||
}
|
||||
const domain = userThatDeterminesDomain.email.split("@")[1];
|
||||
log.debug("called with", safeStringify({ users }));
|
||||
const delegationCredential =
|
||||
await DelegationCredentialRepository.findUniqueByOrganizationIdAndDomainIncludeSensitiveServiceAccountKey(
|
||||
{
|
||||
organizationId,
|
||||
domain,
|
||||
}
|
||||
);
|
||||
|
||||
if (!delegationCredential || !delegationCredential.enabled) {
|
||||
return emptyMap;
|
||||
}
|
||||
|
||||
const credentialsByUserId = new Map<
|
||||
number,
|
||||
NonNullable<ReturnType<typeof _buildDelegatedCalendarCredential>>[]
|
||||
>();
|
||||
|
||||
for (const user of users) {
|
||||
const delegationCredentials = [
|
||||
_buildDelegatedCalendarCredential({ delegationCredential, user }),
|
||||
_buildDelegatedConferencingCredential({ delegationCredential, user }),
|
||||
].filter((credential): credential is NonNullable<typeof credential> => credential !== null);
|
||||
|
||||
log.debug(
|
||||
"Returned for user",
|
||||
safeStringify({
|
||||
user,
|
||||
delegationCredentialIds:
|
||||
delegationCredentials?.map?.((delegationCredential) => delegationCredential?.delegatedToId) ?? [],
|
||||
})
|
||||
);
|
||||
credentialsByUserId.set(user.id, delegationCredentials);
|
||||
}
|
||||
|
||||
return credentialsByUserId;
|
||||
}
|
||||
|
||||
export async function checkIfSuccessfullyConfiguredInWorkspace({
|
||||
delegationCredential,
|
||||
user,
|
||||
}: {
|
||||
delegationCredential: DelegationCredentialWithSensitiveServiceAccountKey;
|
||||
user: User;
|
||||
}) {
|
||||
if (!isValidWorkspaceSlug(delegationCredential.workspacePlatform.slug)) {
|
||||
log.warn(
|
||||
`Only ${WORKSPACE_PLATFORM_SLUGS.toString()} Platforms are supported here, skipping ${
|
||||
delegationCredential.workspacePlatform.slug
|
||||
}`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
const credential = _buildDelegatedCalendarCredentialWithServiceAccountKey({
|
||||
delegationCredential,
|
||||
user,
|
||||
});
|
||||
|
||||
const calendar = await getCalendar(credential);
|
||||
|
||||
if (!calendar) {
|
||||
throw new Error("Google Calendar App not found");
|
||||
}
|
||||
return await calendar?.testDelegationCredentialSetup?.();
|
||||
}
|
||||
|
||||
export async function getAllDelegationCredentialsForUserByAppType({
|
||||
user,
|
||||
appType,
|
||||
}: {
|
||||
user: User;
|
||||
appType: string;
|
||||
}) {
|
||||
const delegationCredentials = await getAllDelegationCredentialsForUser({
|
||||
user,
|
||||
});
|
||||
return delegationCredentials.filter((credential) => credential.type === appType);
|
||||
}
|
||||
|
||||
export async function getAllDelegationCredentialsForUserByAppSlug({
|
||||
user,
|
||||
appSlug,
|
||||
}: {
|
||||
user: User;
|
||||
appSlug: string;
|
||||
}) {
|
||||
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
|
||||
user,
|
||||
});
|
||||
const appDelegationCredentials = delegationCredentials.filter((credential) => credential.appId === appSlug);
|
||||
return buildAllCredentials({
|
||||
delegationCredentials: appDelegationCredentials,
|
||||
existingCredentials: [],
|
||||
});
|
||||
}
|
||||
|
||||
type Host<TUser extends { id: number; email: string; credentials: CredentialPayload[] }> = {
|
||||
user: TUser;
|
||||
};
|
||||
|
||||
/**
|
||||
* Prepares credentials for use by CalendarService and EventManager
|
||||
* - Ensures no duplicate delegationCredentials caused by enrichment at possibly multiple places
|
||||
*/
|
||||
export const buildAllCredentials = ({
|
||||
delegationCredentials,
|
||||
existingCredentials,
|
||||
}: {
|
||||
delegationCredentials: CredentialForCalendarService[];
|
||||
existingCredentials: CredentialPayload[];
|
||||
}) => {
|
||||
const nonDelegationCredentials = existingCredentials.filter(
|
||||
(cred) => !isDelegationCredential({ credentialId: cred.id })
|
||||
);
|
||||
const allCredentials: CredentialForCalendarService[] = [
|
||||
...delegationCredentials,
|
||||
...buildNonDelegationCredentials(nonDelegationCredentials),
|
||||
];
|
||||
|
||||
const uniqueAllCredentials = allCredentials.reduce((acc, credential) => {
|
||||
if (!credential.delegatedToId) {
|
||||
// Regular credential go as is
|
||||
acc.push(credential);
|
||||
return acc;
|
||||
}
|
||||
const existingDelegationCredential = acc.find(
|
||||
(c) => c.delegatedToId === credential.delegatedToId && c.appId === credential.appId
|
||||
);
|
||||
if (!existingDelegationCredential) {
|
||||
acc.push(credential);
|
||||
}
|
||||
return acc;
|
||||
}, [] as typeof allCredentials);
|
||||
|
||||
return uniqueAllCredentials;
|
||||
};
|
||||
|
||||
export async function enrichUsersWithDelegationCredentials<
|
||||
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
|
||||
>({ orgId, users }: { orgId: number | null; users: TUser[] }) {
|
||||
const delegationCredentialsMap = await _getDelegationCredentialsMapPerUser({
|
||||
organizationId: orgId,
|
||||
users,
|
||||
});
|
||||
|
||||
const enrichedUsers = users.map((user) => {
|
||||
const { credentials, ...rest } = user;
|
||||
const enrichedCredentials = buildAllCredentials({
|
||||
delegationCredentials: delegationCredentialsMap.get(user.id) ?? [],
|
||||
existingCredentials: credentials,
|
||||
});
|
||||
return {
|
||||
...rest,
|
||||
credentials: enrichedCredentials,
|
||||
};
|
||||
});
|
||||
log.debug("enrichUsersWithDelegationCredentials", safeStringify({ enrichedUsers, orgId }));
|
||||
return enrichedUsers;
|
||||
}
|
||||
|
||||
export const enrichHostsWithDelegationCredentials = async <
|
||||
THost extends Host<TUser>,
|
||||
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
|
||||
>({
|
||||
orgId,
|
||||
hosts,
|
||||
}: {
|
||||
orgId: number | null;
|
||||
hosts: THost[];
|
||||
}) => {
|
||||
const delegationCredentialsMap = await _getDelegationCredentialsMapPerUser({
|
||||
organizationId: orgId,
|
||||
users: hosts.map((host) => host.user),
|
||||
});
|
||||
|
||||
const enrichedHosts = hosts.map((host) => {
|
||||
const { credentials, ...restUser } = host.user;
|
||||
return {
|
||||
...host,
|
||||
user: {
|
||||
...restUser,
|
||||
credentials: buildAllCredentials({
|
||||
delegationCredentials: delegationCredentialsMap.get(restUser.id) ?? [],
|
||||
existingCredentials: credentials,
|
||||
}),
|
||||
},
|
||||
};
|
||||
});
|
||||
log.debug(
|
||||
"enrichHostsWithDelegationCredentials",
|
||||
safeStringify({
|
||||
enrichedHosts: enrichedHosts.map((host) => {
|
||||
return {
|
||||
userId: host.user.id,
|
||||
};
|
||||
}),
|
||||
orgId,
|
||||
})
|
||||
);
|
||||
return enrichedHosts;
|
||||
};
|
||||
|
||||
export const enrichUserWithDelegationCredentialsIncludeServiceAccountKey = async <
|
||||
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
|
||||
>({
|
||||
user,
|
||||
}: {
|
||||
user: TUser;
|
||||
}) => {
|
||||
const delegationCredentials = await getAllDelegationCredentialsForUserIncludeServiceAccountKey({
|
||||
user,
|
||||
});
|
||||
const { credentials, ...restUser } = user;
|
||||
return {
|
||||
...restUser,
|
||||
credentials: buildAllCredentials({
|
||||
delegationCredentials: delegationCredentials,
|
||||
existingCredentials: credentials,
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
export const enrichUserWithDelegationCredentials = async <
|
||||
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
|
||||
>({
|
||||
user,
|
||||
}: {
|
||||
user: TUser;
|
||||
}) => {
|
||||
const { credentials, ...restUser } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user,
|
||||
});
|
||||
return {
|
||||
...restUser,
|
||||
credentials: credentials.filter(_isConferencingCredential).map(({ delegatedTo: _1, ...rest }) => rest),
|
||||
};
|
||||
};
|
||||
|
||||
export async function enrichUserWithDelegationConferencingCredentialsWithoutOrgId<
|
||||
TUser extends { id: number; email: string; credentials: CredentialPayload[] }
|
||||
>({ user }: { user: TUser }) {
|
||||
const { credentials, ...restUser } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user,
|
||||
});
|
||||
return {
|
||||
...restUser,
|
||||
credentials: credentials.filter(_isConferencingCredential),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Either get Delegation credential from delegationCredentials or find regular credential from Credential table
|
||||
*/
|
||||
export async function getDelegationCredentialOrFindRegularCredential<
|
||||
TDelegationCredential extends { delegatedToId?: string | null }
|
||||
>({
|
||||
id,
|
||||
delegationCredentials,
|
||||
}: {
|
||||
id: {
|
||||
credentialId: number | null | undefined;
|
||||
delegationCredentialId: string | null | undefined;
|
||||
};
|
||||
delegationCredentials: TDelegationCredential[];
|
||||
}) {
|
||||
return id.delegationCredentialId
|
||||
? delegationCredentials.find((cred) => cred.delegatedToId === id.delegationCredentialId)
|
||||
: id.credentialId
|
||||
? await CredentialRepository.findCredentialForCalendarServiceById({
|
||||
id: id.credentialId,
|
||||
})
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function to find a credential from a list of credentials, supporting both regular and DelegationCredential credentials
|
||||
*/
|
||||
export function getDelegationCredentialOrRegularCredential<
|
||||
TCredential extends { delegatedToId?: string | null; id: number }
|
||||
>({
|
||||
credentials,
|
||||
id,
|
||||
}: {
|
||||
credentials: TCredential[];
|
||||
id: { credentialId: number | null | undefined; delegationCredentialId: string | null | undefined };
|
||||
}) {
|
||||
return (
|
||||
credentials.find((cred) => {
|
||||
// Ensure that we don't match null to null
|
||||
if (cred.delegatedToId) {
|
||||
return cred.delegatedToId === id.delegationCredentialId;
|
||||
} else if (id.credentialId) {
|
||||
return cred.id === id.credentialId;
|
||||
}
|
||||
return false;
|
||||
}) || null
|
||||
);
|
||||
}
|
||||
|
||||
export function getFirstDelegationConferencingCredential({
|
||||
credentials,
|
||||
}: {
|
||||
credentials: CredentialForCalendarService[];
|
||||
}) {
|
||||
return credentials.find((credential) => _isConferencingCredential(credential));
|
||||
}
|
||||
|
||||
export function getFirstDelegationConferencingCredentialAppLocation({
|
||||
credentials,
|
||||
}: {
|
||||
credentials: CredentialForCalendarService[];
|
||||
}) {
|
||||
const delegatedConferencingCredential = getFirstDelegationConferencingCredential({ credentials });
|
||||
if (delegatedConferencingCredential?.appId === googleMeetMetadata.slug) {
|
||||
return googleMeetMetadata.appData?.location?.type ?? null;
|
||||
}
|
||||
if (delegatedConferencingCredential?.appId === office365VideoMetaData.slug) {
|
||||
return office365VideoMetaData.appData?.location?.type ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function findUniqueDelegationCalendarCredential({
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
}: {
|
||||
userId: number;
|
||||
delegationCredentialId: string;
|
||||
}) {
|
||||
const [delegationCredential, user] = await Promise.all([
|
||||
DelegationCredentialRepository.findByIdIncludeSensitiveServiceAccountKey({ id: delegationCredentialId }),
|
||||
new UserRepository(prisma).findById({ id: userId }),
|
||||
]);
|
||||
|
||||
if (!delegationCredential) {
|
||||
throw new Error("Delegation Credential not found");
|
||||
}
|
||||
|
||||
if (!delegationCredential.enabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
|
||||
const dwdCredential = _buildDelegatedCalendarCredential({
|
||||
delegationCredential,
|
||||
user,
|
||||
});
|
||||
return dwdCredential;
|
||||
}
|
||||
|
||||
/**
|
||||
* CredentialForCalendarCache is different from CredentialForCalendarService in the sense that CredentialForCalendarCache.id is greater than 0 and CredentialForCalendarService.id is -1
|
||||
* Thus it is a Credential from DB and and also a Delegation User Credential(when CredentialForCalendarCache.delegatedTo is not null)
|
||||
*/
|
||||
export async function getCredentialForCalendarCache({ credentialId }: { credentialId: number }) {
|
||||
const credential = await CredentialRepository.findByIdIncludeDelegationCredential({
|
||||
id: credentialId,
|
||||
});
|
||||
|
||||
let credentialForCalendarService;
|
||||
|
||||
if (credential?.delegationCredential) {
|
||||
if (!credential.userId) {
|
||||
throw new Error(`Credential ${credentialId} doesn't have a user`);
|
||||
}
|
||||
const delegationCredential = await findUniqueDelegationCalendarCredential({
|
||||
userId: credential.userId,
|
||||
delegationCredentialId: credential.delegationCredential.id,
|
||||
});
|
||||
|
||||
if (!delegationCredential) {
|
||||
credentialForCalendarService = null;
|
||||
} else {
|
||||
// We prepare a credential that is in-db(in contrast with an in-memory credential used elsewhere where we generate CredentialForCalendarService)
|
||||
credentialForCalendarService = {
|
||||
...delegationCredential,
|
||||
id: credential.id,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
credentialForCalendarService = buildNonDelegationCredential(credential);
|
||||
}
|
||||
return credentialForCalendarService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the credential for a selected calendar
|
||||
* @param selectedCalendar
|
||||
*/
|
||||
export async function getCredentialForSelectedCalendar({
|
||||
credentialId,
|
||||
delegationCredentialId,
|
||||
userId,
|
||||
}: Partial<SelectedCalendar>) {
|
||||
if (credentialId) {
|
||||
const credentialRepository = new CredentialRepository(prisma);
|
||||
const credential = await credentialRepository.findByIdWithDelegationCredential(credentialId);
|
||||
if (credential?.delegationCredential?.id && credential.userId) {
|
||||
return findUniqueDelegationCalendarCredential({
|
||||
userId: credential.userId,
|
||||
delegationCredentialId: credential.delegationCredential.id,
|
||||
});
|
||||
}
|
||||
return credential ? buildNonDelegationCredential(credential) : undefined;
|
||||
}
|
||||
if (delegationCredentialId && userId) {
|
||||
return findUniqueDelegationCalendarCredential({
|
||||
userId,
|
||||
delegationCredentialId,
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { forbid } from "@calcom/eslint-config/base";
|
||||
import { config } from "@calcom/eslint-config/base";
|
||||
|
||||
export default [
|
||||
...config,
|
||||
forbid({
|
||||
from: "../app-store/**",
|
||||
target: ".",
|
||||
message: "lib package should not import from app-store to avoid circular dependencies.",
|
||||
}),
|
||||
];
|
||||
@@ -1,786 +0,0 @@
|
||||
import "../../tests/libs/__mocks__/prisma";
|
||||
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import GoogleCalendarService from "@calcom/app-store/googlecalendar/lib/CalendarService";
|
||||
import OfficeCalendarService from "@calcom/app-store/office365calendar/lib/CalendarService";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { SelectedCalendar } from "@calcom/prisma/client";
|
||||
import type { EventBusyDate } from "@calcom/types/Calendar";
|
||||
import type { CredentialForCalendarService, CredentialPayload } from "@calcom/types/Credential";
|
||||
|
||||
import { symmetricDecrypt } from "./crypto";
|
||||
import getCalendarsEvents, {
|
||||
getCalendarsEventsWithTimezones,
|
||||
filterSelectedCalendarsForCredential,
|
||||
} from "./getCalendarsEvents";
|
||||
|
||||
vi.mock("./crypto", () => ({
|
||||
symmetricDecrypt: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockedSymmetricDecrypt = vi.mocked(symmetricDecrypt);
|
||||
|
||||
vi.mock("@calcom/app-store/calendar.services.generated", () => {
|
||||
class MockGoogleCalendarService {
|
||||
constructor(credential: any) {
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
getCredentialId() {
|
||||
return this.credential.id;
|
||||
}
|
||||
|
||||
async createEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async updateEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async deleteEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async getAvailability() {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getAvailabilityWithTimeZones() {
|
||||
return [];
|
||||
}
|
||||
|
||||
async listCalendars() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
class MockOfficeCalendarService {
|
||||
constructor(credential: any) {
|
||||
this.credential = credential;
|
||||
}
|
||||
|
||||
getCredentialId() {
|
||||
return this.credential.id;
|
||||
}
|
||||
|
||||
async createEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async updateEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async deleteEvent() {
|
||||
return {};
|
||||
}
|
||||
|
||||
async getAvailability() {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getAvailabilityWithTimeZones() {
|
||||
return [];
|
||||
}
|
||||
|
||||
async listCalendars() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
CalendarServiceMap: {
|
||||
googlecalendar: vi.importActual("@calcom/app-store/googlecalendar/lib/CalendarService"),
|
||||
office365calendar: vi.importActual("@calcom/app-store/office365calendar/lib/CalendarService"),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
function buildDelegationCredential(credential: CredentialPayload): CredentialForCalendarService {
|
||||
return {
|
||||
...credential,
|
||||
id: -1,
|
||||
delegatedTo: {
|
||||
serviceAccountKey: {
|
||||
client_email: "client_email",
|
||||
tenant_id: "tenant_id",
|
||||
client_id: "client_id",
|
||||
private_key: "private_key",
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildRegularCredential(credential: CredentialPayload): CredentialForCalendarService {
|
||||
return {
|
||||
...credential,
|
||||
delegatedTo: null,
|
||||
delegatedToId: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildSelectedCalendar(credential: {
|
||||
credentialId: number;
|
||||
externalId: string;
|
||||
integration: string;
|
||||
userId: number;
|
||||
id: string;
|
||||
}): SelectedCalendar {
|
||||
return {
|
||||
googleChannelId: null,
|
||||
googleChannelKind: null,
|
||||
googleChannelResourceId: null,
|
||||
eventTypeId: null,
|
||||
googleChannelResourceUri: null,
|
||||
googleChannelExpiration: null,
|
||||
delegationCredentialId: null,
|
||||
domainWideDelegationCredentialId: null,
|
||||
error: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
lastErrorAt: null,
|
||||
watchAttempts: 0,
|
||||
unwatchAttempts: 0,
|
||||
maxAttempts: 3,
|
||||
...credential,
|
||||
};
|
||||
}
|
||||
|
||||
describe("getCalendarsEvents", () => {
|
||||
let credential: CredentialPayload;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(logger.constructor.prototype, "debug");
|
||||
|
||||
credential = {
|
||||
id: 303,
|
||||
type: "google_calendar",
|
||||
key: {
|
||||
scope: "example scope",
|
||||
token_type: "Bearer",
|
||||
expiry_date: Date.now() + 84000,
|
||||
access_token: "access token",
|
||||
refresh_token: "refresh token",
|
||||
},
|
||||
userId: 808,
|
||||
teamId: null,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
},
|
||||
appId: "exampleApp",
|
||||
invalid: false,
|
||||
delegationCredentialId: null,
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("Regular Credentials", () => {
|
||||
it("should return empty array if no calendar credentials", async () => {
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "totally_unrelated",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return unknown calendars as empty", async () => {
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "unknown_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
|
||||
it("should return unmatched calendars as empty", async () => {
|
||||
const selectedCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "office365_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[selectedCalendar]
|
||||
);
|
||||
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
|
||||
it("should return availability from selected calendar", async () => {
|
||||
const availability: EventBusyDate[] = [
|
||||
{
|
||||
start: new Date(2010, 11, 2),
|
||||
end: new Date(2010, 11, 3),
|
||||
},
|
||||
{
|
||||
start: new Date(2010, 11, 2, 4),
|
||||
end: new Date(2010, 11, 2, 16),
|
||||
},
|
||||
];
|
||||
|
||||
const getAvailabilitySpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve(availability));
|
||||
|
||||
const selectedCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "google_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedCalendar]
|
||||
);
|
||||
|
||||
expect(getAvailabilitySpy).toHaveBeenCalledWith(
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedCalendar],
|
||||
undefined,
|
||||
false
|
||||
);
|
||||
expect(result).toEqual([
|
||||
availability.map((av) => ({
|
||||
...av,
|
||||
source: "exampleApp",
|
||||
})),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should return availability from multiple calendars", async () => {
|
||||
const googleAvailability: EventBusyDate[] = [
|
||||
{
|
||||
start: new Date(2010, 11, 2),
|
||||
end: new Date(2010, 11, 3),
|
||||
},
|
||||
];
|
||||
const officeAvailability: EventBusyDate[] = [
|
||||
{
|
||||
start: new Date(2010, 11, 2, 4),
|
||||
end: new Date(2010, 11, 2, 16),
|
||||
},
|
||||
];
|
||||
|
||||
const getGoogleAvailabilitySpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve(googleAvailability));
|
||||
const getOfficeAvailabilitySpy = vi
|
||||
.spyOn(OfficeCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve(officeAvailability));
|
||||
|
||||
const selectedGoogleCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "google_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const selectedOfficeCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "office365_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEvents(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "office365_calendar",
|
||||
key: {
|
||||
access_token: "access",
|
||||
refresh_token: "refresh",
|
||||
expires_in: Date.now() + 86400,
|
||||
},
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedGoogleCalendar, selectedOfficeCalendar]
|
||||
);
|
||||
|
||||
expect(getGoogleAvailabilitySpy).toHaveBeenCalledWith(
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedGoogleCalendar],
|
||||
undefined,
|
||||
false
|
||||
);
|
||||
expect(getOfficeAvailabilitySpy).toHaveBeenCalledWith(
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedOfficeCalendar],
|
||||
undefined,
|
||||
false
|
||||
);
|
||||
expect(result).toEqual([
|
||||
googleAvailability.map((av) => ({
|
||||
...av,
|
||||
source: "exampleApp",
|
||||
})),
|
||||
officeAvailability.map((av) => ({
|
||||
...av,
|
||||
source: "exampleApp",
|
||||
})),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should not call getAvailability if selectedCalendars is empty", async () => {
|
||||
const getAvailabilitySpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve([]));
|
||||
|
||||
const result = await getCalendarsEvents(
|
||||
[buildRegularCredential(credential)],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(getAvailabilitySpy).not.toHaveBeenCalled();
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delegation Credentials", () => {
|
||||
it("should allow getAvailability call even without any selected calendars with allowFallbackToPrimary=true", async () => {
|
||||
const startDate = "2010-12-01";
|
||||
const endDate = "2010-12-02";
|
||||
const delegationCredential: CredentialForCalendarService = buildDelegationCredential(credential);
|
||||
const credentials = [delegationCredential];
|
||||
const getAvailabilitySpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailability")
|
||||
.mockReturnValue(Promise.resolve([]));
|
||||
|
||||
const result = await getCalendarsEvents(credentials, startDate, endDate, []);
|
||||
|
||||
expect(getAvailabilitySpy).toHaveBeenCalledWith(startDate, endDate, [], undefined, true);
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCalendarsEventsWithTimezones", () => {
|
||||
let credential: CredentialPayload;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(logger.constructor.prototype, "debug");
|
||||
|
||||
credential = {
|
||||
id: 303,
|
||||
type: "google_calendar",
|
||||
key: {
|
||||
scope: "example scope",
|
||||
token_type: "Bearer",
|
||||
expiry_date: Date.now() + 84000,
|
||||
access_token: "access token",
|
||||
refresh_token: "refresh token",
|
||||
},
|
||||
userId: 808,
|
||||
teamId: null,
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
},
|
||||
appId: "exampleApp",
|
||||
invalid: false,
|
||||
delegationCredentialId: null,
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("Regular Credentials", () => {
|
||||
it("should return empty array if no calendar credentials", async () => {
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "totally_unrelated",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return unknown calendars as empty", async () => {
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "unknown_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return unmatched calendars as empty", async () => {
|
||||
const selectedCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "office365_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[selectedCalendar]
|
||||
);
|
||||
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
|
||||
it("should return availability from selected calendar", async () => {
|
||||
const availability = [
|
||||
{
|
||||
start: new Date(2010, 11, 2),
|
||||
end: new Date(2010, 11, 3),
|
||||
timeZone: "America/New_York",
|
||||
},
|
||||
{
|
||||
start: new Date(2010, 11, 2, 4),
|
||||
end: new Date(2010, 11, 2, 16),
|
||||
timeZone: "America/New_York",
|
||||
},
|
||||
];
|
||||
|
||||
const getAvailabilityWithTimezonesSpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailabilityWithTimeZones")
|
||||
.mockReturnValue(Promise.resolve(availability));
|
||||
|
||||
const selectedCalendar: SelectedCalendar = buildSelectedCalendar({
|
||||
credentialId: 100,
|
||||
externalId: "externalId",
|
||||
integration: "google_calendar",
|
||||
userId: 200,
|
||||
id: "id",
|
||||
});
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[
|
||||
buildRegularCredential({
|
||||
...credential,
|
||||
type: "google_calendar",
|
||||
}),
|
||||
],
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedCalendar]
|
||||
);
|
||||
|
||||
expect(getAvailabilityWithTimezonesSpy).toHaveBeenCalledWith(
|
||||
"2010-12-01",
|
||||
"2010-12-04",
|
||||
[selectedCalendar],
|
||||
false
|
||||
);
|
||||
expect(result).toEqual([
|
||||
availability.map((av) => ({
|
||||
...av,
|
||||
})),
|
||||
]);
|
||||
});
|
||||
|
||||
it("should not call getAvailabilityWithTimezones if selectedCalendars is empty", async () => {
|
||||
const getAvailabilityWithTimezonesSpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailabilityWithTimeZones")
|
||||
.mockReturnValue(Promise.resolve([]));
|
||||
|
||||
const result = await getCalendarsEventsWithTimezones(
|
||||
[buildRegularCredential(credential)],
|
||||
"2010-12-01",
|
||||
"2010-12-02",
|
||||
[]
|
||||
);
|
||||
|
||||
expect(getAvailabilityWithTimezonesSpy).not.toHaveBeenCalled();
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Delegation Credentials", () => {
|
||||
it("should allow getAvailabilityWithTimezones call even without any selected calendars with allowFallbackToPrimary=true", async () => {
|
||||
const startDate = "2010-12-01";
|
||||
const endDate = "2010-12-02";
|
||||
const delegationCredential: CredentialForCalendarService = buildDelegationCredential(credential);
|
||||
const credentials = [delegationCredential];
|
||||
const getAvailabilityWithTimezonesSpy = vi
|
||||
.spyOn(GoogleCalendarService.prototype, "getAvailabilityWithTimeZones")
|
||||
.mockReturnValue(Promise.resolve([]));
|
||||
|
||||
const result = await getCalendarsEventsWithTimezones(credentials, startDate, endDate, []);
|
||||
|
||||
expect(getAvailabilityWithTimezonesSpy).toHaveBeenCalledWith(startDate, endDate, [], true);
|
||||
expect(result).toEqual([[]]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// CalDAV Credential Leak Prevention Tests
|
||||
describe("CalDAV credential leak prevention", () => {
|
||||
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 buildCalDAVSelectedCalendar(data: {
|
||||
id: string;
|
||||
externalId: string;
|
||||
credentialId?: number;
|
||||
}): SelectedCalendar {
|
||||
return {
|
||||
id: data.id,
|
||||
userId: 1,
|
||||
integration: "caldav_calendar",
|
||||
externalId: data.externalId,
|
||||
credentialId: data.credentialId || null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
googleChannelId: null,
|
||||
googleChannelKind: null,
|
||||
googleChannelResourceId: null,
|
||||
googleChannelResourceUri: null,
|
||||
googleChannelExpiration: null,
|
||||
delegationCredentialId: null,
|
||||
domainWideDelegationCredentialId: null,
|
||||
error: null,
|
||||
lastErrorAt: null,
|
||||
watchAttempts: 0,
|
||||
unwatchAttempts: 0,
|
||||
maxAttempts: 3,
|
||||
eventTypeId: null,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("filterSelectedCalendarsForCredential", () => {
|
||||
it("prevents CalDAV credential leak by matching server URLs", () => {
|
||||
// Setup: Two CalDAV servers with different URLs
|
||||
const serverACredential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_server_a_key",
|
||||
});
|
||||
|
||||
const serverBCredential = buildCalDAVCredential({
|
||||
id: 2,
|
||||
key: "encrypted_server_b_key",
|
||||
});
|
||||
|
||||
// Mock encrypted credential data for different servers
|
||||
mockedSymmetricDecrypt
|
||||
.mockReturnValueOnce(
|
||||
JSON.stringify({
|
||||
username: "user_a",
|
||||
password: "pass_a",
|
||||
url: "https://server-a.example.com/dav/calendars/user/",
|
||||
})
|
||||
)
|
||||
.mockReturnValueOnce(
|
||||
JSON.stringify({
|
||||
username: "user_b",
|
||||
password: "pass_b",
|
||||
url: "https://server-b.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
// Selected calendars from both servers
|
||||
const selectedCalendars = [
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_1",
|
||||
externalId: "https://server-a.example.com/dav/calendars/user/calendar1/",
|
||||
credentialId: 1,
|
||||
}),
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_2",
|
||||
externalId: "https://server-b.example.com/dav/calendars/user/calendar2/",
|
||||
credentialId: 2,
|
||||
}),
|
||||
];
|
||||
|
||||
// Test Server A credential - should only return Server A calendars
|
||||
const serverACalendars = filterSelectedCalendarsForCredential(selectedCalendars, serverACredential);
|
||||
expect(serverACalendars).toHaveLength(1);
|
||||
expect(serverACalendars[0].externalId).toBe(
|
||||
"https://server-a.example.com/dav/calendars/user/calendar1/"
|
||||
);
|
||||
|
||||
// Test Server B credential - should only return Server B calendars
|
||||
const serverBCalendars = filterSelectedCalendarsForCredential(selectedCalendars, serverBCredential);
|
||||
expect(serverBCalendars).toHaveLength(1);
|
||||
expect(serverBCalendars[0].externalId).toBe(
|
||||
"https://server-b.example.com/dav/calendars/user/calendar2/"
|
||||
);
|
||||
});
|
||||
|
||||
it("demonstrates the credential leak that existed before the fix", () => {
|
||||
// This test shows what WOULD happen with naive filtering (integration type only)
|
||||
const serverACredential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_server_a_key",
|
||||
});
|
||||
|
||||
const selectedCalendars = [
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_1",
|
||||
externalId: "https://server-a.example.com/dav/calendars/user/calendar1/",
|
||||
credentialId: 1,
|
||||
}),
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_2",
|
||||
externalId: "https://server-b.example.com/dav/calendars/user/calendar2/",
|
||||
credentialId: 2,
|
||||
}),
|
||||
];
|
||||
|
||||
// Legacy filtering (type-only) would return ALL CalDAV calendars
|
||||
const legacyFiltering = selectedCalendars.filter((sc) => sc.integration === "caldav_calendar");
|
||||
expect(legacyFiltering).toHaveLength(2); // This demonstrates the leak - both calendars returned
|
||||
|
||||
// Our new filtering prevents this
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user_a",
|
||||
password: "pass_a",
|
||||
url: "https://server-a.example.com/dav/calendars/user/",
|
||||
})
|
||||
);
|
||||
|
||||
const secureFiltering = filterSelectedCalendarsForCredential(selectedCalendars, serverACredential);
|
||||
expect(secureFiltering).toHaveLength(1); // Only calendars from matching server
|
||||
expect(secureFiltering[0].externalId).toContain("server-a.example.com");
|
||||
});
|
||||
|
||||
it("handles non-CalDAV calendars normally", () => {
|
||||
const googleCredential: CredentialForCalendarService = {
|
||||
id: 1,
|
||||
type: "google_calendar",
|
||||
key: "google_key",
|
||||
userId: 1,
|
||||
user: { email: "[email protected]" },
|
||||
teamId: null,
|
||||
appId: "google-calendar",
|
||||
invalid: false,
|
||||
delegatedTo: null,
|
||||
delegationCredentialId: null,
|
||||
};
|
||||
|
||||
const selectedCalendars = [
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_1",
|
||||
externalId: "https://server-a.example.com/dav/calendars/user/calendar1/",
|
||||
}),
|
||||
{
|
||||
...buildCalDAVSelectedCalendar({
|
||||
id: "cal_2",
|
||||
externalId: "primary",
|
||||
}),
|
||||
integration: "google_calendar",
|
||||
},
|
||||
];
|
||||
|
||||
const googleCalendars = filterSelectedCalendarsForCredential(selectedCalendars, googleCredential);
|
||||
expect(googleCalendars).toHaveLength(1);
|
||||
expect(googleCalendars[0].integration).toBe("google_calendar");
|
||||
});
|
||||
|
||||
it("handles invalid CalDAV credential URLs gracefully", () => {
|
||||
const invalidCredential = buildCalDAVCredential({
|
||||
id: 1,
|
||||
key: "encrypted_invalid_key",
|
||||
});
|
||||
|
||||
mockedSymmetricDecrypt.mockReturnValue(
|
||||
JSON.stringify({
|
||||
username: "user",
|
||||
password: "pass",
|
||||
url: "invalid-url-format",
|
||||
})
|
||||
);
|
||||
|
||||
const selectedCalendars = [
|
||||
buildCalDAVSelectedCalendar({
|
||||
id: "cal_1",
|
||||
externalId: "https://server-a.example.com/dav/calendars/user/calendar1/",
|
||||
}),
|
||||
];
|
||||
|
||||
const result = filterSelectedCalendarsForCredential(selectedCalendars, invalidCredential);
|
||||
expect(result).toHaveLength(0); // Should return empty array for safety
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,275 +0,0 @@
|
||||
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { getPiiFreeSelectedCalendar, getPiiFreeCredential } from "@calcom/lib/piiFreeData";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { performance } from "@calcom/lib/server/perfObserver";
|
||||
import type { EventBusyDate, SelectedCalendar } from "@calcom/types/Calendar";
|
||||
import type { CredentialForCalendarService } from "@calcom/types/Credential";
|
||||
|
||||
import { symmetricDecrypt } from "./crypto";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getCalendarsEvents"] });
|
||||
|
||||
const CALENDSO_ENCRYPTION_KEY = process.env.CALENDSO_ENCRYPTION_KEY || "";
|
||||
// only for Google Calendar for now
|
||||
export const getCalendarsEventsWithTimezones = async (
|
||||
withCredentials: CredentialForCalendarService[],
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: SelectedCalendar[]
|
||||
): Promise<(EventBusyDate & { timeZone: string })[][]> => {
|
||||
const calendarCredentials = withCredentials
|
||||
.filter((credential) => credential.type === "google_calendar")
|
||||
// filter out invalid credentials - these won't work.
|
||||
.filter((credential) => !credential.invalid);
|
||||
|
||||
const calendarAndCredentialPairs = await Promise.all(
|
||||
calendarCredentials.map(async (credential) => {
|
||||
const calendar = await getCalendar(credential);
|
||||
return [calendar, credential] as const;
|
||||
})
|
||||
);
|
||||
|
||||
const calendars = calendarAndCredentialPairs.map(([calendar]) => calendar);
|
||||
const calendarToCredentialMap = new Map(calendarAndCredentialPairs);
|
||||
|
||||
const results = calendars.map(async (c, i) => {
|
||||
/** Filter out nulls */
|
||||
if (!c) return [];
|
||||
/** We rely on the index so we can match credentials with calendars */
|
||||
const { type } = calendarCredentials[i];
|
||||
const credential = calendarToCredentialMap.get(c);
|
||||
/** We just pass the calendars that matched the credential type,
|
||||
* TODO: Migrate credential type or appId
|
||||
*/
|
||||
const passedSelectedCalendars = credential
|
||||
? filterSelectedCalendarsForCredential(selectedCalendars, credential)
|
||||
: selectedCalendars
|
||||
.filter((sc) => sc.integration === type)
|
||||
// Needed to ensure cache keys are consistent
|
||||
.sort((a, b) => (a.externalId < b.externalId ? -1 : a.externalId > b.externalId ? 1 : 0));
|
||||
const isADelegationCredential = credential && isDelegationCredential({ credentialId: credential.id });
|
||||
// We want to fallback to primary calendar when no selectedCalendars are passed
|
||||
// Default behaviour for Google Calendar is to use all available calendars, which isn't good default.
|
||||
const allowFallbackToPrimary = isADelegationCredential;
|
||||
if (!passedSelectedCalendars.length) {
|
||||
if (!isADelegationCredential) {
|
||||
// It was done to fix the secondary calendar connections from always checking the conflicts even if intentional no calendars are selected.
|
||||
// https://github.com/calcom/cal.com/issues/8929
|
||||
log.error(
|
||||
`No selected calendars for non DWD credential: Skipping getAvailability call for credential ${credential?.id}`
|
||||
);
|
||||
return [];
|
||||
}
|
||||
// For delegation credential, we should allow getAvailability even without any selected calendars. It ensures that enabling Delegation Credential at Organization level always ensure one selected calendar for conflicts checking, without requiring any manual action from organization members
|
||||
// This is also, similar to how Google Calendar connect flow(through /googlecalendar/api/callback) sets the primary calendar as the selected calendar automatically.
|
||||
log.info("Allowing getAvailability even without any selected calendars for Delegation Credential");
|
||||
}
|
||||
/** We extract external Ids so we don't cache too much */
|
||||
const eventBusyDates =
|
||||
(await c.getAvailabilityWithTimeZones?.(
|
||||
dateFrom,
|
||||
dateTo,
|
||||
passedSelectedCalendars,
|
||||
allowFallbackToPrimary
|
||||
)) || [];
|
||||
|
||||
return eventBusyDates;
|
||||
});
|
||||
const awaitedResults = await Promise.all(results);
|
||||
return awaitedResults;
|
||||
};
|
||||
|
||||
const getCalendarsEvents = async (
|
||||
withCredentials: CredentialForCalendarService[],
|
||||
dateFrom: string,
|
||||
dateTo: string,
|
||||
selectedCalendars: SelectedCalendar[],
|
||||
shouldServeCache?: boolean
|
||||
): Promise<EventBusyDate[][]> => {
|
||||
const calendarCredentials = withCredentials
|
||||
.filter((credential) => credential.type.endsWith("_calendar"))
|
||||
// filter out invalid credentials - these won't work.
|
||||
.filter((credential) => !credential.invalid);
|
||||
|
||||
const calendarAndCredentialPairs = await Promise.all(
|
||||
calendarCredentials.map(async (credential) => {
|
||||
const calendar = await getCalendar(credential);
|
||||
return [calendar, credential] as const;
|
||||
})
|
||||
);
|
||||
|
||||
const calendars = calendarAndCredentialPairs.map(([calendar]) => calendar);
|
||||
const calendarToCredentialMap = new Map(calendarAndCredentialPairs);
|
||||
performance.mark("getBusyCalendarTimesStart");
|
||||
const results = calendars.map(async (calendarService, i) => {
|
||||
/** Filter out nulls */
|
||||
if (!calendarService) return [];
|
||||
/** We rely on the index so we can match credentials with calendars */
|
||||
const { type, appId } = calendarCredentials[i];
|
||||
const credential = calendarToCredentialMap.get(calendarService);
|
||||
/** We just pass the calendars that matched the credential type,
|
||||
* TODO: Migrate credential type or appId
|
||||
*/
|
||||
// Important to have them unique so that
|
||||
const passedSelectedCalendars = credential
|
||||
? filterSelectedCalendarsForCredential(selectedCalendars, credential)
|
||||
: selectedCalendars
|
||||
.filter((sc) => sc.integration === type)
|
||||
// Needed to ensure cache keys are consistent
|
||||
.sort((a, b) => (a.externalId < b.externalId ? -1 : a.externalId > b.externalId ? 1 : 0));
|
||||
const isADelegationCredential = credential && isDelegationCredential({ credentialId: credential.id });
|
||||
// We want to fallback to primary calendar when no selectedCalendars are passed
|
||||
// Default behaviour for Google Calendar is to use all available calendars, which isn't good default.
|
||||
const allowFallbackToPrimary = isADelegationCredential;
|
||||
if (!passedSelectedCalendars.length) {
|
||||
if (!isADelegationCredential) {
|
||||
// It was done to fix the secondary calendar connections from always checking the conflicts even if intentional no calendars are selected.
|
||||
// https://github.com/calcom/cal.com/issues/8929
|
||||
log.error(
|
||||
`No selected calendars for non DWD credential: Skipping getAvailability call for credential ${credential?.id}`
|
||||
);
|
||||
return [];
|
||||
}
|
||||
// For delegation credential, we should allow getAvailability even without any selected calendars. It ensures that enabling Delegation Credential at Organization level always ensure one selected calendar for conflicts checking, without requiring any manual action from organization members
|
||||
// This is also, similar to how Google Calendar connect flow(through /googlecalendar/api/callback) sets the primary calendar as the selected calendar automatically.
|
||||
log.info("Allowing getAvailability even without any selected calendars for Delegation Credential");
|
||||
}
|
||||
/** We extract external Ids so we don't cache too much */
|
||||
|
||||
const selectedCalendarIds = passedSelectedCalendars.map((sc) => sc.externalId);
|
||||
/** If we don't then we actually fetch external calendars (which can be very slow) */
|
||||
performance.mark("eventBusyDatesStart");
|
||||
log.debug(
|
||||
`Getting availability for`,
|
||||
safeStringify({
|
||||
calendarService: calendarService.constructor.name,
|
||||
selectedCalendars: passedSelectedCalendars.map(getPiiFreeSelectedCalendar),
|
||||
})
|
||||
);
|
||||
const eventBusyDates = await calendarService.getAvailability(
|
||||
dateFrom,
|
||||
dateTo,
|
||||
passedSelectedCalendars,
|
||||
shouldServeCache,
|
||||
allowFallbackToPrimary
|
||||
);
|
||||
performance.mark("eventBusyDatesEnd");
|
||||
performance.measure(
|
||||
`[getAvailability for ${selectedCalendarIds.join(", ")}][$1]'`,
|
||||
"eventBusyDatesStart",
|
||||
"eventBusyDatesEnd"
|
||||
);
|
||||
|
||||
return eventBusyDates.map((a) => ({
|
||||
...a,
|
||||
source: `${appId}`,
|
||||
}));
|
||||
});
|
||||
const awaitedResults = await Promise.all(results);
|
||||
performance.mark("getBusyCalendarTimesEnd");
|
||||
performance.measure(
|
||||
`getBusyCalendarTimes took $1 for creds ${calendarCredentials.map((cred) => cred.id)}`,
|
||||
"getBusyCalendarTimesStart",
|
||||
"getBusyCalendarTimesEnd"
|
||||
);
|
||||
log.debug(
|
||||
"Result",
|
||||
safeStringify({
|
||||
calendarCredentials: calendarCredentials.map(getPiiFreeCredential),
|
||||
selectedCalendars: selectedCalendars.map(getPiiFreeSelectedCalendar),
|
||||
calendarEvents: awaitedResults,
|
||||
})
|
||||
);
|
||||
return awaitedResults;
|
||||
};
|
||||
|
||||
export default getCalendarsEvents;
|
||||
|
||||
/**
|
||||
* Extract server URL from CalDAV calendar externalId
|
||||
*/
|
||||
function getServerUrlFromCalendarExternalId(externalId: string): string | null {
|
||||
try {
|
||||
const url = new URL(externalId);
|
||||
return `${url.protocol}//${url.host}`;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract server URL from CalDAV credential
|
||||
*/
|
||||
function getServerUrlFromCredential(credential: CredentialForCalendarService): string | null {
|
||||
try {
|
||||
if (credential.type !== "caldav_calendar") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const decryptedData = JSON.parse(symmetricDecrypt(credential.key as string, CALENDSO_ENCRYPTION_KEY));
|
||||
|
||||
if (!decryptedData.url) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL(decryptedData.url);
|
||||
return `${url.protocol}//${url.host}`;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter selected calendars for the specific credential, handling CalDAV server URL matching
|
||||
*/
|
||||
export function filterSelectedCalendarsForCredential(
|
||||
selectedCalendars: SelectedCalendar[],
|
||||
credential: CredentialForCalendarService
|
||||
): SelectedCalendar[] {
|
||||
const { type } = credential;
|
||||
|
||||
// For all other calendar types, use the existing logic
|
||||
if (type !== "caldav_calendar") {
|
||||
return selectedCalendars.filter((sc) => sc.integration === type);
|
||||
}
|
||||
|
||||
const credentialServerUrl = getServerUrlFromCredential(credential);
|
||||
|
||||
if (!credentialServerUrl) {
|
||||
log.warn("Could not extract server URL from CalDAV credential", {
|
||||
credentialId: credential.id,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
return selectedCalendars.filter((sc) => {
|
||||
if (sc.integration !== type) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const calendarServerUrl = getServerUrlFromCalendarExternalId(sc.externalId);
|
||||
|
||||
if (!calendarServerUrl) {
|
||||
log.warn("Could not extract server URL from calendar externalId", {
|
||||
externalId: sc.externalId,
|
||||
integration: sc.integration,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const matches = credentialServerUrl === calendarServerUrl;
|
||||
|
||||
if (!matches) {
|
||||
log.debug("CalDAV calendar server URL does not match credential server URL", {
|
||||
credentialId: credential.id,
|
||||
credentialServerUrl,
|
||||
calendarServerUrl,
|
||||
calendarExternalId: sc.externalId,
|
||||
});
|
||||
}
|
||||
|
||||
return matches;
|
||||
});
|
||||
}
|
||||
@@ -1,385 +0,0 @@
|
||||
import { getCalendarCredentials, getConnectedCalendars } from "@calcom/features/calendars/lib/CalendarManager";
|
||||
import { isDelegationCredential } from "@calcom/lib/delegationCredential/clientAndServer";
|
||||
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/lib/delegationCredential/server";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { DestinationCalendar, SelectedCalendar, User } from "@calcom/prisma/client";
|
||||
import { AppCategories } from "@calcom/prisma/enums";
|
||||
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
||||
|
||||
import { DestinationCalendarRepository } from "./server/repository/destinationCalendar";
|
||||
import { EventTypeRepository } from "./server/repository/eventTypeRepository";
|
||||
import { SelectedCalendarRepository } from "./server/repository/selectedCalendar";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getConnectedDestinationCalendarsAndEnsureDefaultsInDb"] });
|
||||
|
||||
type ReturnTypeGetConnectedCalendars = Awaited<ReturnType<typeof getConnectedCalendars>>;
|
||||
type ConnectedCalendarsFromGetConnectedCalendars = ReturnTypeGetConnectedCalendars["connectedCalendars"];
|
||||
|
||||
export type UserWithCalendars = Pick<User, "id" | "email"> & {
|
||||
allSelectedCalendars: Pick<
|
||||
SelectedCalendar,
|
||||
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId"
|
||||
>[];
|
||||
userLevelSelectedCalendars: Pick<
|
||||
SelectedCalendar,
|
||||
"externalId" | "integration" | "eventTypeId" | "updatedAt" | "googleChannelId"
|
||||
>[];
|
||||
destinationCalendar: DestinationCalendar | null;
|
||||
};
|
||||
|
||||
export type ConnectedDestinationCalendars = Awaited<
|
||||
ReturnType<typeof getConnectedDestinationCalendarsAndEnsureDefaultsInDb>
|
||||
>;
|
||||
|
||||
/**
|
||||
* Ensures that when DelegationCredential is enabled and there is already a calendar connected for the corresponding domain, we only allow the DelegationCredential calendar to be returned
|
||||
* This is to ensure that duplicate calendar connections aren't shown in UI(apps/installed/calendars). We choose DelegationCredential connection to be shown because we don't want users to be able to work with individual calendars
|
||||
*/
|
||||
const _ensureNoConflictingNonDelegatedConnectedCalendar = <
|
||||
T extends {
|
||||
integration: { slug: string };
|
||||
primary?: { email?: string | null | undefined } | undefined;
|
||||
delegationCredentialId?: string | null | undefined;
|
||||
}
|
||||
>({
|
||||
connectedCalendars,
|
||||
loggedInUser,
|
||||
}: {
|
||||
connectedCalendars: T[];
|
||||
loggedInUser: { email: string };
|
||||
}) => {
|
||||
return connectedCalendars.filter((connectedCalendar, index, array) => {
|
||||
const allCalendarsWithSameAppSlug = array.filter(
|
||||
(cal) => cal.integration.slug === connectedCalendar.integration.slug
|
||||
);
|
||||
|
||||
// If no other calendar with this slug, keep it
|
||||
if (allCalendarsWithSameAppSlug.length === 1) return true;
|
||||
|
||||
const delegatedCalendarsWithSameAppSlug = allCalendarsWithSameAppSlug.filter(
|
||||
(cal) => cal.delegationCredentialId
|
||||
);
|
||||
if (!delegatedCalendarsWithSameAppSlug.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (connectedCalendar.delegationCredentialId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// DelegationCredential Credential is always of the loggedInUser
|
||||
if (!connectedCalendar.primary?.email || connectedCalendar.primary.email !== loggedInUser.email) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
async function handleNoConnectedCalendars(user: UserWithCalendars) {
|
||||
log.debug(`No connected calendars, deleting destination calendar if it exists for user ${user.id}`);
|
||||
|
||||
if (!user.destinationCalendar) return user;
|
||||
await prisma.destinationCalendar.delete({
|
||||
where: { userId: user.id },
|
||||
});
|
||||
|
||||
return {
|
||||
...user,
|
||||
destinationCalendar: null,
|
||||
};
|
||||
}
|
||||
|
||||
type ToggledCalendarDetails = {
|
||||
externalId: string;
|
||||
integration: string;
|
||||
};
|
||||
|
||||
async function handleNoDestinationCalendar({
|
||||
user,
|
||||
connectedCalendars,
|
||||
onboarding,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
connectedCalendars: ConnectedCalendarsFromGetConnectedCalendars;
|
||||
onboarding: boolean;
|
||||
}) {
|
||||
if (!connectedCalendars.length) {
|
||||
throw new Error("No connected calendars");
|
||||
}
|
||||
|
||||
// This is the calendar that we will ensure is enabled for conflict check
|
||||
let calendarToEnsureIsEnabledForConflictCheck: ToggledCalendarDetails | null = null;
|
||||
|
||||
log.debug(
|
||||
`There are connected calendars, but no destination calendar, so create a default destination calendar in DB for user ${user.id}`
|
||||
);
|
||||
/*
|
||||
So create a default destination calendar with the first primary connected calendar
|
||||
*/
|
||||
const {
|
||||
integration = "",
|
||||
externalId = "",
|
||||
credentialId,
|
||||
delegationCredentialId,
|
||||
email: primaryEmail,
|
||||
} = connectedCalendars[0].primary ?? {};
|
||||
|
||||
// Select the first calendar matching the primary by default since that will also be the destination calendar
|
||||
if (onboarding && externalId) {
|
||||
const calendarIndex = (connectedCalendars[0].calendars || []).findIndex(
|
||||
(item) => item.externalId === externalId && item.integration === integration
|
||||
);
|
||||
if (calendarIndex >= 0 && connectedCalendars[0].calendars) {
|
||||
connectedCalendars[0].calendars[calendarIndex].isSelected = true;
|
||||
calendarToEnsureIsEnabledForConflictCheck = {
|
||||
externalId,
|
||||
integration,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
user.destinationCalendar = await DestinationCalendarRepository.createIfNotExistsForUser({
|
||||
userId: user.id,
|
||||
integration,
|
||||
externalId,
|
||||
primaryEmail,
|
||||
...(!isDelegationCredential({ credentialId })
|
||||
? {
|
||||
credentialId,
|
||||
}
|
||||
: {
|
||||
delegationCredentialId,
|
||||
}),
|
||||
});
|
||||
|
||||
return {
|
||||
user,
|
||||
connectedCalendars,
|
||||
calendarToEnsureIsEnabledForConflictCheck,
|
||||
};
|
||||
}
|
||||
|
||||
async function handleDestinationCalendarNotInConnectedCalendars({
|
||||
user,
|
||||
connectedCalendars,
|
||||
onboarding,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
connectedCalendars: ConnectedCalendarsFromGetConnectedCalendars;
|
||||
onboarding: boolean;
|
||||
}) {
|
||||
let calendarToEnsureIsEnabledForConflictCheck: ToggledCalendarDetails | null = null;
|
||||
log.debug(
|
||||
`Destination calendar isn't in connectedCalendars, update it to the first primary connected calendar for user ${user.id}`
|
||||
);
|
||||
const { integration = "", externalId = "", email: primaryEmail } = connectedCalendars[0].primary ?? {};
|
||||
// Select the first calendar matching the primary by default since that will also be the destination calendar
|
||||
if (onboarding && externalId) {
|
||||
const calendarIndex = (connectedCalendars[0].calendars || []).findIndex(
|
||||
(item) => item.externalId === externalId && item.integration === integration
|
||||
);
|
||||
if (calendarIndex >= 0 && connectedCalendars[0].calendars) {
|
||||
connectedCalendars[0].calendars[calendarIndex].isSelected = true;
|
||||
calendarToEnsureIsEnabledForConflictCheck = {
|
||||
externalId,
|
||||
integration,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
user.destinationCalendar = await prisma.destinationCalendar.update({
|
||||
where: { userId: user.id },
|
||||
data: {
|
||||
integration,
|
||||
externalId,
|
||||
primaryEmail,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
user,
|
||||
connectedCalendars,
|
||||
calendarToEnsureIsEnabledForConflictCheck,
|
||||
};
|
||||
}
|
||||
|
||||
function findMatchingCalendar({
|
||||
connectedCalendars,
|
||||
calendar,
|
||||
}: {
|
||||
connectedCalendars: ConnectedCalendarsFromGetConnectedCalendars;
|
||||
calendar: DestinationCalendar;
|
||||
}) {
|
||||
// Check if destinationCalendar exists in connectedCalendars
|
||||
const allCals = connectedCalendars.map((cal) => cal.calendars ?? []).flat();
|
||||
const matchingCalendar = allCals.find(
|
||||
(cal) => cal.externalId === calendar.externalId && cal.integration === calendar.integration
|
||||
);
|
||||
return matchingCalendar;
|
||||
}
|
||||
|
||||
async function ensureSelectedCalendarIsInDb({
|
||||
user,
|
||||
selectedCalendar,
|
||||
eventTypeId,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
selectedCalendar: {
|
||||
integration: string;
|
||||
externalId: string;
|
||||
};
|
||||
eventTypeId: number | null;
|
||||
}) {
|
||||
console.log(
|
||||
`Upsert the selectedCalendar record to the DB for user ${user.id} with details ${JSON.stringify(
|
||||
selectedCalendar
|
||||
)}`
|
||||
);
|
||||
|
||||
await SelectedCalendarRepository.createIfNotExists({
|
||||
userId: user.id,
|
||||
integration: selectedCalendar.integration,
|
||||
externalId: selectedCalendar.externalId,
|
||||
eventTypeId,
|
||||
});
|
||||
}
|
||||
|
||||
function getSelectedCalendars({
|
||||
user,
|
||||
eventTypeId,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
eventTypeId: number | null;
|
||||
}) {
|
||||
if (eventTypeId) {
|
||||
return EventTypeRepository.getSelectedCalendarsFromUser({
|
||||
user,
|
||||
eventTypeId: eventTypeId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
return user.userLevelSelectedCalendars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the calendars for the authenticated user or the event-type if provided
|
||||
* It also takes care of updating the destination calendar in some edge cases
|
||||
*/
|
||||
export async function getConnectedDestinationCalendarsAndEnsureDefaultsInDb({
|
||||
user,
|
||||
onboarding,
|
||||
eventTypeId,
|
||||
prisma,
|
||||
}: {
|
||||
user: UserWithCalendars;
|
||||
onboarding: boolean;
|
||||
eventTypeId?: number | null;
|
||||
prisma: PrismaClient;
|
||||
}) {
|
||||
const userCredentials = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
app: {
|
||||
categories: { has: AppCategories.calendar },
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
select: credentialForCalendarServiceSelect,
|
||||
});
|
||||
|
||||
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user: { id: user.id, email: user.email, credentials: userCredentials },
|
||||
});
|
||||
|
||||
const selectedCalendars = getSelectedCalendars({ user, eventTypeId: eventTypeId ?? null });
|
||||
// get user's credentials + their connected integrations
|
||||
const calendarCredentials = getCalendarCredentials(allCredentials);
|
||||
|
||||
// get all the connected integrations' calendars (from third party)
|
||||
const getConnectedCalendarsResult = await getConnectedCalendars(
|
||||
calendarCredentials,
|
||||
selectedCalendars,
|
||||
user.destinationCalendar?.externalId
|
||||
);
|
||||
|
||||
let connectedCalendars = getConnectedCalendarsResult.connectedCalendars;
|
||||
const destinationCalendar = getConnectedCalendarsResult.destinationCalendar;
|
||||
|
||||
let calendarToEnsureIsEnabledForConflictCheck: ToggledCalendarDetails | null = null;
|
||||
|
||||
if (connectedCalendars.length === 0) {
|
||||
user = await handleNoConnectedCalendars(user);
|
||||
} else if (!user.destinationCalendar) {
|
||||
({ user, calendarToEnsureIsEnabledForConflictCheck, connectedCalendars } =
|
||||
await handleNoDestinationCalendar({
|
||||
user,
|
||||
connectedCalendars,
|
||||
onboarding,
|
||||
}));
|
||||
} else {
|
||||
/* There are connected calendars and a destination calendar */
|
||||
log.debug(
|
||||
`There are connected calendars and a destination calendar, so check if destinationCalendar exists in connectedCalendars for user ${user.id}`
|
||||
);
|
||||
|
||||
const destinationCal = findMatchingCalendar({ connectedCalendars, calendar: user.destinationCalendar });
|
||||
if (!destinationCal) {
|
||||
({ user, calendarToEnsureIsEnabledForConflictCheck, connectedCalendars } =
|
||||
await handleDestinationCalendarNotInConnectedCalendars({
|
||||
user,
|
||||
connectedCalendars,
|
||||
onboarding,
|
||||
}));
|
||||
} else if (onboarding && !destinationCal.isSelected) {
|
||||
log.debug(
|
||||
`Onboarding:Destination calendar is not selected, but in connectedCalendars, so mark it as selected in the calendar list for user ${user.id}`
|
||||
);
|
||||
// Mark the destination calendar as selected in the calendar list
|
||||
// We use every so that we can exit early once we find the matching calendar
|
||||
connectedCalendars.every((cal) => {
|
||||
const index = (cal.calendars || []).findIndex(
|
||||
(calendar) =>
|
||||
calendar.externalId === destinationCal.externalId &&
|
||||
calendar.integration === destinationCal.integration
|
||||
);
|
||||
if (index >= 0 && cal.calendars) {
|
||||
cal.calendars[index].isSelected = true;
|
||||
calendarToEnsureIsEnabledForConflictCheck = {
|
||||
externalId: destinationCal.externalId,
|
||||
integration: destinationCal.integration || "",
|
||||
};
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Insert the newly toggled record to the DB
|
||||
if (calendarToEnsureIsEnabledForConflictCheck) {
|
||||
await ensureSelectedCalendarIsInDb({
|
||||
user,
|
||||
selectedCalendar: calendarToEnsureIsEnabledForConflictCheck,
|
||||
eventTypeId: eventTypeId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
const noConflictingNonDelegatedConnectedCalendars = _ensureNoConflictingNonDelegatedConnectedCalendar({
|
||||
connectedCalendars,
|
||||
loggedInUser: { email: user.email },
|
||||
});
|
||||
return {
|
||||
connectedCalendars: noConflictingNonDelegatedConnectedCalendars,
|
||||
destinationCalendar: {
|
||||
...(user.destinationCalendar as DestinationCalendar),
|
||||
...destinationCalendar,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Legacy export for @calcom/platform-libraries
|
||||
export const getConnectedDestinationCalendars = getConnectedDestinationCalendarsAndEnsureDefaultsInDb;
|
||||
@@ -1,683 +0,0 @@
|
||||
import * as Sentry from "@sentry/nextjs";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getCalendar } from "@calcom/app-store/_utils/getCalendar";
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { getBusyTimesService } from "@calcom/features/di/containers/BusyTimes";
|
||||
import type { IRedisService } from "@calcom/features/redis/IRedisService";
|
||||
import { getWorkingHours } from "@calcom/lib/availability";
|
||||
import type { DateOverride, WorkingHours } from "@calcom/lib/date-ranges";
|
||||
import { buildDateRanges, subtract } from "@calcom/lib/date-ranges";
|
||||
import { stringToDayjsZod } from "@calcom/lib/dayjs";
|
||||
import { ErrorCode } from "@calcom/lib/errorCodes";
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import { parseBookingLimit } from "@calcom/lib/intervalLimits/isBookingLimits";
|
||||
import { parseDurationLimit } from "@calcom/lib/intervalLimits/isDurationLimits";
|
||||
import {
|
||||
getBusyTimesFromLimits,
|
||||
getBusyTimesFromTeamLimits,
|
||||
} from "@calcom/lib/intervalLimits/server/getBusyTimesFromLimits";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { findUsersForAvailabilityCheck } from "@calcom/lib/server/findUsersForAvailabilityCheck";
|
||||
import type { BookingRepository } from "@calcom/lib/server/repository/booking";
|
||||
import { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
|
||||
import type { PrismaOOORepository } from "@calcom/lib/server/repository/ooo";
|
||||
import type {
|
||||
Booking,
|
||||
Prisma,
|
||||
OutOfOfficeEntry,
|
||||
OutOfOfficeReason,
|
||||
User,
|
||||
EventType as PrismaEventType,
|
||||
} from "@calcom/prisma/client";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
import type { EventBusyDetails, IntervalLimitUnit } from "@calcom/types/Calendar";
|
||||
import type { TimeRange } from "@calcom/types/schedule";
|
||||
|
||||
import { getPeriodStartDatesBetween as getPeriodStartDatesBetweenUtil } from "./intervalLimits/utils/getPeriodStartDatesBetween";
|
||||
import { withReporting } from "./sentryWrapper";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getUserAvailability"] });
|
||||
const availabilitySchema = z
|
||||
.object({
|
||||
dateFrom: stringToDayjsZod,
|
||||
dateTo: stringToDayjsZod,
|
||||
eventTypeId: z.number().optional(),
|
||||
username: z.string().optional(),
|
||||
userId: z.number().optional(),
|
||||
afterEventBuffer: z.number().optional(),
|
||||
beforeEventBuffer: z.number().optional(),
|
||||
duration: z.number().optional(),
|
||||
withSource: z.boolean().optional(),
|
||||
returnDateOverrides: z.boolean(),
|
||||
bypassBusyCalendarTimes: z.boolean().optional(),
|
||||
silentlyHandleCalendarFailures: z.boolean().optional(),
|
||||
shouldServeCache: z.boolean().optional(),
|
||||
})
|
||||
.refine((data) => !!data.username || !!data.userId, "Either username or userId should be filled in.");
|
||||
|
||||
export type EventType = Awaited<ReturnType<(typeof UserAvailabilityService)["prototype"]["_getEventType"]>>;
|
||||
|
||||
type GetUser = Awaited<ReturnType<(typeof UserAvailabilityService)["prototype"]["_getUser"]>>;
|
||||
|
||||
export type GetUserAvailabilityInitialData = {
|
||||
user?: GetUser;
|
||||
eventType?: EventType;
|
||||
currentSeats?: CurrentSeats;
|
||||
rescheduleUid?: string | null;
|
||||
currentBookings?: (Pick<Booking, "id" | "uid" | "userId" | "startTime" | "endTime" | "title"> & {
|
||||
eventType: Pick<
|
||||
PrismaEventType,
|
||||
"id" | "beforeEventBuffer" | "afterEventBuffer" | "seatsPerTimeSlot"
|
||||
> | null;
|
||||
_count?: {
|
||||
seatsReferences: number;
|
||||
};
|
||||
})[];
|
||||
outOfOfficeDays?: (Pick<OutOfOfficeEntry, "id" | "start" | "end"> & {
|
||||
user: Pick<User, "id" | "name">;
|
||||
toUser: Pick<User, "id" | "username" | "name"> | null;
|
||||
reason: Pick<OutOfOfficeReason, "id" | "emoji" | "reason"> | null;
|
||||
})[];
|
||||
busyTimesFromLimitsBookings: EventBusyDetails[];
|
||||
busyTimesFromLimits?: Map<number, EventBusyDetails[]>;
|
||||
eventTypeForLimits?: {
|
||||
id: number;
|
||||
bookingLimits?: unknown;
|
||||
durationLimits?: unknown;
|
||||
} | null;
|
||||
teamBookingLimits?: Map<number, EventBusyDetails[]>;
|
||||
teamForBookingLimits?: {
|
||||
id: number;
|
||||
bookingLimits?: unknown;
|
||||
includeManagedEventsInLimits: boolean;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type GetAvailabilityUser = NonNullable<GetUserAvailabilityInitialData["user"]>;
|
||||
|
||||
type GetUserAvailabilityQuery = {
|
||||
withSource?: boolean;
|
||||
username?: string;
|
||||
userId?: number;
|
||||
dateFrom: string;
|
||||
dateTo: string;
|
||||
eventTypeId?: number;
|
||||
afterEventBuffer?: number;
|
||||
beforeEventBuffer?: number;
|
||||
duration?: number;
|
||||
returnDateOverrides: boolean;
|
||||
bypassBusyCalendarTimes: boolean;
|
||||
silentlyHandleCalendarFailures?: boolean;
|
||||
shouldServeCache?: boolean;
|
||||
};
|
||||
|
||||
export type CurrentSeats = Awaited<
|
||||
ReturnType<(typeof UserAvailabilityService)["prototype"]["_getCurrentSeats"]>
|
||||
>;
|
||||
|
||||
export type GetUserAvailabilityResult = Awaited<
|
||||
ReturnType<(typeof UserAvailabilityService)["prototype"]["_getUserAvailability"]>
|
||||
>;
|
||||
|
||||
interface GetUserAvailabilityParamsDTO {
|
||||
availability: (DateOverride | WorkingHours)[];
|
||||
}
|
||||
|
||||
export interface IFromUser {
|
||||
id: number;
|
||||
displayName: string | null;
|
||||
}
|
||||
|
||||
export interface IToUser {
|
||||
id: number;
|
||||
username: string | null;
|
||||
displayName: string | null;
|
||||
}
|
||||
|
||||
export interface IOutOfOfficeData {
|
||||
[key: string]: {
|
||||
fromUser: IFromUser | null;
|
||||
toUser?: IToUser | null;
|
||||
reason?: string | null;
|
||||
emoji?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
type GetUsersAvailabilityProps = {
|
||||
users: (GetAvailabilityUser & {
|
||||
currentBookings?: GetUserAvailabilityInitialData["currentBookings"];
|
||||
outOfOfficeDays?: GetUserAvailabilityInitialData["outOfOfficeDays"];
|
||||
})[];
|
||||
query: Omit<GetUserAvailabilityQuery, "userId" | "username">;
|
||||
initialData?: Omit<GetUserAvailabilityInitialData, "user">;
|
||||
};
|
||||
|
||||
export interface IUserAvailabilityService {
|
||||
eventTypeRepo: EventTypeRepository;
|
||||
oooRepo: PrismaOOORepository;
|
||||
bookingRepo: BookingRepository;
|
||||
redisClient: IRedisService;
|
||||
}
|
||||
|
||||
export class UserAvailabilityService {
|
||||
constructor(public readonly dependencies: IUserAvailabilityService) {}
|
||||
|
||||
// Fetch timezones from outlook or google using delegated credentials (formely known as domain wide delegatiion)
|
||||
async getTimezoneFromDelegatedCalendars(user: GetAvailabilityUser): Promise<string | null> {
|
||||
if (!user.credentials || user.credentials.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const delegatedCredentials = user.credentials.filter(
|
||||
(credential) => credential.type.endsWith("_calendar") && Boolean(credential.delegatedToId)
|
||||
);
|
||||
|
||||
if (!delegatedCredentials || delegatedCredentials.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cacheKey = `user-timezone:${user.id}`;
|
||||
|
||||
try {
|
||||
const cachedTimezone = await this.dependencies.redisClient.get<string>(cacheKey);
|
||||
|
||||
if (cachedTimezone) {
|
||||
log.debug(`Got timezone ${cachedTimezone} from Redis cache for user ${user.id}`);
|
||||
return cachedTimezone;
|
||||
}
|
||||
} catch (error) {
|
||||
log.warn(`Failed to get timezone from Redis cache for user ${user.id}:`, error);
|
||||
}
|
||||
|
||||
if (delegatedCredentials.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const credential of delegatedCredentials) {
|
||||
try {
|
||||
const calendar = await getCalendar(credential);
|
||||
if (calendar && "getMainTimeZone" in calendar && typeof calendar.getMainTimeZone === "function") {
|
||||
const timezone = await calendar.getMainTimeZone();
|
||||
if (timezone && timezone !== "UTC") {
|
||||
log.debug(`Got timezone ${timezone} from calendar service ${credential.type}`);
|
||||
|
||||
try {
|
||||
await this.dependencies.redisClient.set<string>(cacheKey, timezone, { ttl: 3600 * 6 * 1000 }); // 6 hours ttl in ms;
|
||||
log.debug(`Cached timezone ${timezone} in Redis for user ${user.id}`);
|
||||
} catch (error) {
|
||||
log.warn(`Failed to set timezone in Redis cache for user ${user.id}:`, error);
|
||||
}
|
||||
|
||||
return timezone;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
log.warn(`Failed to get timezone from calendar service ${credential.type}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async _getEventType(id: number) {
|
||||
const eventType = await this.dependencies.eventTypeRepo.findByIdForUserAvailability({ id });
|
||||
if (!eventType) {
|
||||
return eventType;
|
||||
}
|
||||
return {
|
||||
...eventType,
|
||||
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
|
||||
};
|
||||
}
|
||||
|
||||
getEventType = withReporting(this._getEventType.bind(this), "getEventType");
|
||||
|
||||
async _getUser(where: Prisma.UserWhereInput) {
|
||||
return findUsersForAvailabilityCheck({ where });
|
||||
}
|
||||
getUser = withReporting(this._getUser.bind(this), "getUser");
|
||||
|
||||
async _getCurrentSeats(
|
||||
eventType: {
|
||||
id?: number;
|
||||
schedulingType?: SchedulingType | null;
|
||||
hosts?: {
|
||||
user: {
|
||||
email: string;
|
||||
};
|
||||
}[];
|
||||
},
|
||||
dateFrom: Dayjs,
|
||||
dateTo: Dayjs
|
||||
) {
|
||||
const { schedulingType, hosts, id } = eventType;
|
||||
const hostEmails = hosts?.map((host) => host.user.email);
|
||||
const isTeamEvent =
|
||||
schedulingType === SchedulingType.MANAGED ||
|
||||
schedulingType === SchedulingType.ROUND_ROBIN ||
|
||||
schedulingType === SchedulingType.COLLECTIVE;
|
||||
|
||||
const bookings = await this.dependencies.bookingRepo.findAcceptedBookingByEventTypeId({
|
||||
eventTypeId: id,
|
||||
dateFrom: dateFrom.format(),
|
||||
dateTo: dateTo.format(),
|
||||
});
|
||||
|
||||
return bookings.map((booking) => {
|
||||
const attendees = isTeamEvent
|
||||
? booking.attendees.filter((attendee) => !hostEmails?.includes(attendee.email))
|
||||
: booking.attendees;
|
||||
|
||||
return {
|
||||
uid: booking.uid,
|
||||
startTime: booking.startTime,
|
||||
_count: {
|
||||
attendees: attendees.length,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
getCurrentSeats = withReporting(this._getCurrentSeats.bind(this), "getCurrentSeats");
|
||||
|
||||
/** This should be called getUsersWorkingHoursAndBusySlots (...and remaining seats, and final timezone) */
|
||||
async _getUserAvailability(query: GetUserAvailabilityQuery, initialData?: GetUserAvailabilityInitialData) {
|
||||
const {
|
||||
username,
|
||||
userId,
|
||||
dateFrom,
|
||||
dateTo,
|
||||
eventTypeId,
|
||||
afterEventBuffer,
|
||||
beforeEventBuffer,
|
||||
duration,
|
||||
returnDateOverrides,
|
||||
bypassBusyCalendarTimes = false,
|
||||
silentlyHandleCalendarFailures = false,
|
||||
shouldServeCache,
|
||||
} = availabilitySchema.parse(query);
|
||||
|
||||
log.debug(
|
||||
`EventType: ${eventTypeId} | User: ${username} (ID: ${userId}) - Called with: ${safeStringify({
|
||||
query,
|
||||
})}`
|
||||
);
|
||||
|
||||
if (!dateFrom.isValid() || !dateTo.isValid()) {
|
||||
throw new HttpError({ statusCode: 400, message: "Invalid time range given." });
|
||||
}
|
||||
|
||||
const where: Prisma.UserWhereInput = {};
|
||||
if (username) where.username = username;
|
||||
if (userId) where.id = userId;
|
||||
|
||||
const user = initialData?.user || (await this.getUser(where));
|
||||
|
||||
if (!user) {
|
||||
throw new HttpError({ statusCode: 404, message: "No user found in getUserAvailability" });
|
||||
}
|
||||
|
||||
let eventType: EventType | null = initialData?.eventType || null;
|
||||
if (!eventType && eventTypeId) eventType = await this.getEventType(eventTypeId);
|
||||
|
||||
/* Current logic is if a booking is in a time slot mark it as busy, but seats can have more than one attendee so grab
|
||||
current bookings with a seats event type and display them on the calendar, even if they are full */
|
||||
let currentSeats: CurrentSeats | null = initialData?.currentSeats || null;
|
||||
if (!currentSeats && eventType?.seatsPerTimeSlot) {
|
||||
currentSeats = await this.getCurrentSeats(eventType, dateFrom, dateTo);
|
||||
}
|
||||
|
||||
const userSchedule = user.schedules.filter(
|
||||
(schedule) => !user?.defaultScheduleId || schedule.id === user?.defaultScheduleId
|
||||
)[0];
|
||||
|
||||
const hostSchedule = eventType?.hosts?.find((host) => host.user.id === user.id)?.schedule;
|
||||
|
||||
// TODO: It uses default timezone of user. Should we use timezone of team ?
|
||||
const fallbackTimezoneIfScheduleIsMissing = eventType?.timeZone || user.timeZone;
|
||||
|
||||
const fallbackSchedule = {
|
||||
availability: [
|
||||
{
|
||||
startTime: new Date("1970-01-01T09:00:00Z"),
|
||||
endTime: new Date("1970-01-01T17:00:00Z"),
|
||||
days: [1, 2, 3, 4, 5], // Monday to Friday
|
||||
date: null,
|
||||
},
|
||||
],
|
||||
id: 0,
|
||||
|
||||
timeZone: fallbackTimezoneIfScheduleIsMissing,
|
||||
};
|
||||
|
||||
// possible timezones that have been set by or for a user
|
||||
const potentialSchedule = eventType?.schedule
|
||||
? eventType.schedule
|
||||
: hostSchedule
|
||||
? hostSchedule
|
||||
: userSchedule;
|
||||
|
||||
// if no schedules set by or for a user, use fallbackSchedule
|
||||
const schedule = potentialSchedule ?? fallbackSchedule;
|
||||
|
||||
const bookingLimits =
|
||||
eventType?.bookingLimits &&
|
||||
typeof eventType.bookingLimits === "object" &&
|
||||
Object.keys(eventType.bookingLimits).length > 0
|
||||
? parseBookingLimit(eventType.bookingLimits)
|
||||
: null;
|
||||
|
||||
const durationLimits =
|
||||
eventType?.durationLimits &&
|
||||
typeof eventType.durationLimits === "object" &&
|
||||
Object.keys(eventType.durationLimits).length > 0
|
||||
? parseDurationLimit(eventType.durationLimits)
|
||||
: null;
|
||||
|
||||
// TODO: only query what we need after applying limits (shrink date range)
|
||||
const getBusyTimesStart = dateFrom.toISOString();
|
||||
const getBusyTimesEnd = dateTo.toISOString();
|
||||
|
||||
const selectedCalendars = eventType?.useEventLevelSelectedCalendars
|
||||
? EventTypeRepository.getSelectedCalendarsFromUser({ user, eventTypeId: eventType.id })
|
||||
: user.userLevelSelectedCalendars;
|
||||
|
||||
const isTimezoneSet = Boolean(potentialSchedule && potentialSchedule.timeZone !== null);
|
||||
|
||||
// this timezone is synced with google/outlook calendars timezone usingg delegated credentials
|
||||
// it's a fallback for delegated credentials users who want to sync their timezone with third party calendars
|
||||
const calendarTimezone = !isTimezoneSet ? await this.getTimezoneFromDelegatedCalendars(user) : null;
|
||||
|
||||
const finalTimezone =
|
||||
!isTimezoneSet && calendarTimezone
|
||||
? calendarTimezone
|
||||
: schedule?.timeZone || fallbackTimezoneIfScheduleIsMissing;
|
||||
|
||||
let busyTimesFromLimits: EventBusyDetails[] = [];
|
||||
|
||||
if (initialData?.busyTimesFromLimits && initialData?.eventTypeForLimits) {
|
||||
busyTimesFromLimits = initialData.busyTimesFromLimits.get(user.id) || [];
|
||||
} else if (eventType && (bookingLimits || durationLimits)) {
|
||||
// Fall back to individual query if not available in initialData
|
||||
busyTimesFromLimits = await getBusyTimesFromLimits(
|
||||
bookingLimits,
|
||||
durationLimits,
|
||||
dateFrom.tz(finalTimezone),
|
||||
dateTo.tz(finalTimezone),
|
||||
duration,
|
||||
eventType,
|
||||
initialData?.busyTimesFromLimitsBookings ?? [],
|
||||
finalTimezone,
|
||||
initialData?.rescheduleUid ?? undefined
|
||||
);
|
||||
}
|
||||
|
||||
const teamForBookingLimits =
|
||||
initialData?.teamForBookingLimits ??
|
||||
eventType?.team ??
|
||||
(eventType?.parent?.team?.includeManagedEventsInLimits ? eventType?.parent?.team : null);
|
||||
|
||||
const teamBookingLimits = parseBookingLimit(teamForBookingLimits?.bookingLimits);
|
||||
|
||||
let busyTimesFromTeamLimits: EventBusyDetails[] = [];
|
||||
|
||||
if (initialData?.teamBookingLimits && teamForBookingLimits) {
|
||||
busyTimesFromTeamLimits = initialData.teamBookingLimits.get(user.id) || [];
|
||||
} else if (teamForBookingLimits && teamBookingLimits) {
|
||||
// Fall back to individual query if not available in initialData
|
||||
busyTimesFromTeamLimits = await getBusyTimesFromTeamLimits(
|
||||
user,
|
||||
teamBookingLimits,
|
||||
dateFrom.tz(finalTimezone),
|
||||
dateTo.tz(finalTimezone),
|
||||
teamForBookingLimits.id,
|
||||
teamForBookingLimits.includeManagedEventsInLimits,
|
||||
finalTimezone,
|
||||
initialData?.rescheduleUid ?? undefined
|
||||
);
|
||||
}
|
||||
|
||||
let busyTimes = [];
|
||||
try {
|
||||
const busyTimesService = getBusyTimesService();
|
||||
busyTimes = await busyTimesService.getBusyTimes({
|
||||
credentials: user.credentials,
|
||||
startTime: getBusyTimesStart,
|
||||
endTime: getBusyTimesEnd,
|
||||
eventTypeId,
|
||||
userId: user.id,
|
||||
userEmail: user.email,
|
||||
username: `${user.username}`,
|
||||
beforeEventBuffer,
|
||||
afterEventBuffer,
|
||||
selectedCalendars,
|
||||
seatedEvent: !!eventType?.seatsPerTimeSlot,
|
||||
rescheduleUid: initialData?.rescheduleUid || null,
|
||||
duration,
|
||||
currentBookings: initialData?.currentBookings,
|
||||
bypassBusyCalendarTimes,
|
||||
silentlyHandleCalendarFailures,
|
||||
shouldServeCache,
|
||||
});
|
||||
} catch (error) {
|
||||
log.error(`Error fetching busy times for user ${username}:`, error);
|
||||
return {
|
||||
busy: [],
|
||||
timeZone: finalTimezone,
|
||||
dateRanges: [],
|
||||
oooExcludedDateRanges: [],
|
||||
workingHours: [],
|
||||
dateOverrides: [],
|
||||
currentSeats: [],
|
||||
datesOutOfOffice: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const detailedBusyTimes: EventBusyDetails[] = [
|
||||
...busyTimes.map((a) => ({
|
||||
...a,
|
||||
start: dayjs(a.start).toISOString(),
|
||||
end: dayjs(a.end).toISOString(),
|
||||
title: a.title,
|
||||
source: query.withSource ? a.source : undefined,
|
||||
})),
|
||||
...busyTimesFromLimits,
|
||||
...busyTimesFromTeamLimits,
|
||||
];
|
||||
|
||||
const isDefaultSchedule = userSchedule && userSchedule.id === schedule?.id;
|
||||
|
||||
log.debug(
|
||||
`EventType: ${eventTypeId} | User: ${username} (ID: ${userId}) - usingSchedule: ${safeStringify({
|
||||
chosenSchedule: schedule,
|
||||
eventTypeSchedule: eventType?.schedule,
|
||||
userSchedule: userSchedule,
|
||||
hostSchedule: hostSchedule,
|
||||
})}`
|
||||
);
|
||||
|
||||
if (
|
||||
!(
|
||||
schedule?.availability ||
|
||||
(eventType?.availability.length ? eventType.availability : user.availability)
|
||||
)
|
||||
) {
|
||||
throw new HttpError({ statusCode: 400, message: ErrorCode.AvailabilityNotFoundInSchedule });
|
||||
}
|
||||
|
||||
const availability = (
|
||||
schedule?.availability || (eventType?.availability.length ? eventType.availability : user.availability)
|
||||
).map((a) => ({
|
||||
...a,
|
||||
userId: user.id,
|
||||
}));
|
||||
|
||||
const workingHours = getWorkingHours({ timeZone: finalTimezone }, availability);
|
||||
|
||||
const dateOverrides: TimeRange[] = [];
|
||||
// NOTE: getSchedule is currently calling this function for every user in a team event
|
||||
// but not using these values at all, wasting CPU. Adding this check here temporarily to avoid a larger refactor
|
||||
// since other callers do using this data.
|
||||
if (returnDateOverrides) {
|
||||
const calculateDateOverridesSpan = Sentry.startInactiveSpan({ name: "calculateDateOverrides" });
|
||||
const availabilityWithDates = availability.filter((availability) => !!availability.date);
|
||||
|
||||
for (let i = 0; i < availabilityWithDates.length; i++) {
|
||||
const override = availabilityWithDates[i];
|
||||
const startTime = dayjs.utc(override.startTime);
|
||||
const endTime = dayjs.utc(override.endTime);
|
||||
const overrideStartDate = dayjs.utc(override.date).hour(startTime.hour()).minute(startTime.minute());
|
||||
const overrideEndDate = dayjs.utc(override.date).hour(endTime.hour()).minute(endTime.minute());
|
||||
if (
|
||||
overrideStartDate.isBetween(dateFrom, dateTo, null, "[]") ||
|
||||
overrideEndDate.isBetween(dateFrom, dateTo, null, "[]")
|
||||
) {
|
||||
dateOverrides.push({
|
||||
start: overrideStartDate.toDate(),
|
||||
end: overrideEndDate.toDate(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
calculateDateOverridesSpan.end();
|
||||
}
|
||||
|
||||
const outOfOfficeDays =
|
||||
initialData?.outOfOfficeDays ??
|
||||
(await this.dependencies.oooRepo.findUserOOODays({
|
||||
userId: user.id,
|
||||
dateFrom: dateFrom.toISOString(),
|
||||
dateTo: dateTo.toISOString(),
|
||||
}));
|
||||
|
||||
const datesOutOfOffice: IOutOfOfficeData = this.calculateOutOfOfficeRanges(outOfOfficeDays, availability);
|
||||
|
||||
const { dateRanges, oooExcludedDateRanges } = buildDateRanges({
|
||||
dateFrom,
|
||||
dateTo,
|
||||
availability,
|
||||
timeZone: finalTimezone,
|
||||
travelSchedules: isDefaultSchedule
|
||||
? user.travelSchedules.map((schedule) => {
|
||||
return {
|
||||
startDate: dayjs(schedule.startDate),
|
||||
endDate: schedule.endDate ? dayjs(schedule.endDate) : undefined,
|
||||
timeZone: schedule.timeZone,
|
||||
};
|
||||
})
|
||||
: [],
|
||||
outOfOffice: datesOutOfOffice,
|
||||
});
|
||||
|
||||
const formattedBusyTimes = detailedBusyTimes.map((busy) => ({
|
||||
start: dayjs(busy.start),
|
||||
end: dayjs(busy.end),
|
||||
}));
|
||||
|
||||
const dateRangesInWhichUserIsAvailable = subtract(dateRanges, formattedBusyTimes);
|
||||
const dateRangesInWhichUserIsAvailableWithoutOOO = subtract(oooExcludedDateRanges, formattedBusyTimes);
|
||||
|
||||
const result = {
|
||||
busy: detailedBusyTimes,
|
||||
timeZone: finalTimezone,
|
||||
dateRanges: dateRangesInWhichUserIsAvailable,
|
||||
oooExcludedDateRanges: dateRangesInWhichUserIsAvailableWithoutOOO,
|
||||
workingHours,
|
||||
dateOverrides,
|
||||
currentSeats,
|
||||
datesOutOfOffice,
|
||||
};
|
||||
|
||||
log.debug(
|
||||
`EventType: ${eventTypeId} | User: ${username} (ID: ${userId}) - Result: ${safeStringify(result)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
getUserAvailability = withReporting(this._getUserAvailability.bind(this), "getUserAvailability");
|
||||
|
||||
getPeriodStartDatesBetween = withReporting(
|
||||
(dateFrom: Dayjs, dateTo: Dayjs, period: IntervalLimitUnit, timeZone?: string) =>
|
||||
getPeriodStartDatesBetweenUtil(dateFrom, dateTo, period, timeZone),
|
||||
"getPeriodStartDatesBetween"
|
||||
);
|
||||
|
||||
calculateOutOfOfficeRanges(
|
||||
outOfOfficeDays: GetUserAvailabilityInitialData["outOfOfficeDays"],
|
||||
availability: GetUserAvailabilityParamsDTO["availability"]
|
||||
): IOutOfOfficeData {
|
||||
if (!outOfOfficeDays || outOfOfficeDays.length === 0) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return outOfOfficeDays.reduce((acc: IOutOfOfficeData, { start, end, toUser, user, reason }) => {
|
||||
// here we should use startDate or today if start is before today
|
||||
// consider timezone in start and end date range
|
||||
const startDateRange = dayjs(start).utc().isBefore(dayjs().startOf("day").utc())
|
||||
? dayjs().utc().startOf("day")
|
||||
: dayjs(start).utc().startOf("day");
|
||||
|
||||
// get number of day in the week and see if it's on the availability
|
||||
const flattenDays = Array.from(new Set(availability.flatMap((a) => ("days" in a ? a.days : [])))).sort(
|
||||
(a, b) => a - b
|
||||
);
|
||||
|
||||
const endDateRange = dayjs(end).utc().endOf("day");
|
||||
|
||||
for (let date = startDateRange; date.isBefore(endDateRange); date = date.add(1, "day")) {
|
||||
const dayNumberOnWeek = date.day();
|
||||
|
||||
if (!flattenDays?.includes(dayNumberOnWeek)) {
|
||||
continue; // Skip to the next iteration if day not found in flattenDays
|
||||
}
|
||||
|
||||
acc[date.format("YYYY-MM-DD")] = {
|
||||
// @TODO: would be good having start and end availability time here, but for now should be good
|
||||
// you can obtain that from user availability defined outside of here
|
||||
fromUser: { id: user.id, displayName: user.name },
|
||||
// optional chaining destructuring toUser
|
||||
toUser: !!toUser ? { id: toUser.id, displayName: toUser.name, username: toUser.username } : null,
|
||||
reason: !!reason ? reason.reason : null,
|
||||
emoji: !!reason ? reason.emoji : null,
|
||||
};
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
|
||||
async _getUsersAvailability({ users, query, initialData }: GetUsersAvailabilityProps) {
|
||||
if (users.length >= 50) {
|
||||
const userIds = users.map(({ id }) => id).join(", ");
|
||||
log.warn(
|
||||
`High-load warning: Attempting to fetch availability for ${users.length} users. User IDs: [${userIds}], EventTypeId: [${query.eventTypeId}]`
|
||||
);
|
||||
}
|
||||
return await Promise.all(
|
||||
users.map((user) =>
|
||||
this._getUserAvailability(
|
||||
{
|
||||
...query,
|
||||
userId: user.id,
|
||||
username: user.username || "",
|
||||
},
|
||||
initialData
|
||||
? {
|
||||
...initialData,
|
||||
user,
|
||||
currentBookings: user.currentBookings,
|
||||
outOfOfficeDays: user.outOfOfficeDays,
|
||||
}
|
||||
: undefined
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
getUsersAvailability = withReporting(this._getUsersAvailability.bind(this), "getUsersAvailability");
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { EventType } from "@calcom/features/availability/lib/getUserAvailability";
|
||||
import { getCheckBookingLimitsService } from "@calcom/features/di/containers/BookingLimits";
|
||||
import { getBusyTimesService } from "@calcom/features/di/containers/BusyTimes";
|
||||
import type { EventType } from "@calcom/lib/getUserAvailability";
|
||||
import { getPeriodStartDatesBetween } from "@calcom/lib/intervalLimits/utils/getPeriodStartDatesBetween";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
import { performance } from "@calcom/lib/server/perfObserver";
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,461 +0,0 @@
|
||||
import async from "async";
|
||||
import type { ImmutableTree, JsonLogicResult, JsonTree } from "react-awesome-query-builder";
|
||||
import type { Config } from "react-awesome-query-builder/lib";
|
||||
import { Utils as QbUtils } from "react-awesome-query-builder/lib";
|
||||
|
||||
import type { dynamicFieldValueOperands } from "@calcom/lib/raqb/types";
|
||||
import { getAttributesAssignmentData } from "@calcom/lib/service/attribute/server/getAttributes";
|
||||
import type { Attribute } from "@calcom/lib/service/attribute/server/getAttributes";
|
||||
|
||||
import { RaqbLogicResult } from "./evaluateRaqbLogic";
|
||||
import jsonLogic from "./jsonLogic";
|
||||
import { acrossQueryValueCompatiblity, raqbQueryValueUtils } from "./raqbUtils";
|
||||
import type { AttributesQueryValue } from "./types";
|
||||
|
||||
const {
|
||||
getAttributesData: getAttributes,
|
||||
getAttributesQueryBuilderConfigHavingListofLabels,
|
||||
getAttributesQueryValue,
|
||||
} = acrossQueryValueCompatiblity;
|
||||
|
||||
type TeamMemberWithAttributeOptionValuePerAttribute = Awaited<
|
||||
ReturnType<typeof getAttributesAssignmentData>
|
||||
>["attributesAssignedToTeamMembersWithOptions"][number];
|
||||
|
||||
type RunAttributeLogicData = {
|
||||
attributesQueryValue: AttributesQueryValue | null;
|
||||
attributesData: {
|
||||
attributesOfTheOrg: Attribute[];
|
||||
teamMembersWithAttributeOptionValuePerAttribute: TeamMemberWithAttributeOptionValuePerAttribute[];
|
||||
};
|
||||
dynamicFieldValueOperands?: dynamicFieldValueOperands;
|
||||
};
|
||||
|
||||
type RunAttributeLogicOptions = {
|
||||
concurrency: number;
|
||||
enablePerf: boolean;
|
||||
isPreview: boolean;
|
||||
enableTroubleshooter: boolean;
|
||||
};
|
||||
|
||||
export const enum TroubleshooterCase {
|
||||
IS_A_ROUTER = "is-a-router",
|
||||
NO_LOGIC_FOUND = "no-logic-found",
|
||||
MATCH_RESULTS_READY = "match-results-ready",
|
||||
MATCH_RESULTS_READY_WITH_FALLBACK = "match-results-ready-with-fallback",
|
||||
MATCHES_ALL_MEMBERS_BECAUSE_OF_EMPTY_QUERY_VALUE = "matches-all-members-because-of-empty-query-value",
|
||||
MATCHES_ALL_MEMBERS = "matches-all-members",
|
||||
}
|
||||
|
||||
/**
|
||||
* Performance wrapper for async functions
|
||||
*/
|
||||
async function asyncPerf<ReturnValue>(fn: () => Promise<ReturnValue>): Promise<[ReturnValue, number | null]> {
|
||||
const start = performance.now();
|
||||
const result = await fn();
|
||||
const end = performance.now();
|
||||
return [result, end - start];
|
||||
}
|
||||
|
||||
/**
|
||||
* Performance wrapper for sync functions
|
||||
*/
|
||||
function perf<ReturnValue>(fn: () => ReturnValue): [ReturnValue, number | null] {
|
||||
const start = performance.now();
|
||||
const result = fn();
|
||||
const end = performance.now();
|
||||
return [result, end - start];
|
||||
}
|
||||
|
||||
function getErrorsFromImmutableTree(tree: ImmutableTree) {
|
||||
const validatedQueryValue = QbUtils.getTree(tree);
|
||||
if (!raqbQueryValueUtils.isQueryValueARuleGroup(validatedQueryValue)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!validatedQueryValue.children1) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const errors: string[][] = [];
|
||||
Object.values(validatedQueryValue.children1).map((rule) => {
|
||||
if (rule.type !== "rule") {
|
||||
return;
|
||||
}
|
||||
const valueError = rule.properties.valueError;
|
||||
if (valueError) {
|
||||
// Sometimes there are null values in it.
|
||||
errors.push(valueError.filter(Boolean));
|
||||
}
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
function getJsonLogic({
|
||||
attributesQueryValue,
|
||||
attributesQueryBuilderConfig,
|
||||
}: {
|
||||
attributesQueryValue: AttributesQueryValue;
|
||||
attributesQueryBuilderConfig: Config;
|
||||
}) {
|
||||
const state = {
|
||||
tree: QbUtils.checkTree(
|
||||
QbUtils.loadTree(attributesQueryValue as JsonTree),
|
||||
// We know that attributesQueryBuilderConfig is a Config because getAttributesQueryBuilderConfigHavingListofLabels returns a Config. So, asserting it.
|
||||
attributesQueryBuilderConfig as unknown as Config
|
||||
),
|
||||
config: attributesQueryBuilderConfig as unknown as Config,
|
||||
};
|
||||
const jsonLogicQuery = QbUtils.jsonLogicFormat(state.tree, state.config);
|
||||
const logic = jsonLogicQuery.logic;
|
||||
// Considering errors as warnings as we want to continue with the flow without throwing actual errors
|
||||
// We expect fallback logic to take effect in case of errors in main logic
|
||||
const warnings = getErrorsFromImmutableTree(state.tree).flat();
|
||||
if (!logic) {
|
||||
// If children1 is not empty, it means that some rules were added by use
|
||||
if (attributesQueryValue.children1 && Object.keys(attributesQueryValue.children1).length > 0) {
|
||||
// Possible reasons for this
|
||||
// 1. The attribute option value used is not in the options list. Happens if 'Value of field' value is chosen and that field's response value doesn't exist in attribute options list.
|
||||
return { logic, warnings: ["There is some error building the logic, please check the routes."] };
|
||||
}
|
||||
}
|
||||
|
||||
return { logic, warnings };
|
||||
}
|
||||
|
||||
function buildTroubleshooterData({ type, data }: { type: TroubleshooterCase; data: Record<string, any> }) {
|
||||
return {
|
||||
troubleshooter: {
|
||||
type,
|
||||
data,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function getLogicResultForAllMembers(
|
||||
{
|
||||
teamMembersWithAttributeOptionValuePerAttribute,
|
||||
attributeJsonLogic,
|
||||
attributesQueryValue,
|
||||
}: {
|
||||
teamMembersWithAttributeOptionValuePerAttribute: TeamMemberWithAttributeOptionValuePerAttribute[];
|
||||
attributeJsonLogic: NonNullable<JsonLogicResult["logic"]>;
|
||||
attributesQueryValue: AttributesQueryValue;
|
||||
},
|
||||
config: {
|
||||
concurrency?: number;
|
||||
enableTroubleshooter?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
const { concurrency = 2 } = config;
|
||||
const teamMembersMatchingAttributeLogicMap = new Map<number, RaqbLogicResult>();
|
||||
const attributesDataPerUser = new Map<number, ReturnType<typeof getAttributes>>();
|
||||
|
||||
await async.mapLimit<TeamMemberWithAttributeOptionValuePerAttribute, Promise<void>>(
|
||||
teamMembersWithAttributeOptionValuePerAttribute,
|
||||
concurrency,
|
||||
async (member: TeamMemberWithAttributeOptionValuePerAttribute) => {
|
||||
const attributesData = getAttributes({
|
||||
attributesData: member.attributes,
|
||||
attributesQueryValue,
|
||||
});
|
||||
attributesDataPerUser.set(member.userId, attributesData);
|
||||
const result = !!jsonLogic.apply(attributeJsonLogic as any, attributesData)
|
||||
? RaqbLogicResult.MATCH
|
||||
: RaqbLogicResult.NO_MATCH;
|
||||
|
||||
if (result !== RaqbLogicResult.MATCH) {
|
||||
return;
|
||||
}
|
||||
teamMembersMatchingAttributeLogicMap.set(member.userId, result);
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
teamMembersMatchingAttributeLogicMap,
|
||||
attributesDataPerUser,
|
||||
};
|
||||
}
|
||||
|
||||
async function runAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
|
||||
const {
|
||||
attributesQueryValue: _attributesQueryValue,
|
||||
attributesData: { attributesOfTheOrg, teamMembersWithAttributeOptionValuePerAttribute },
|
||||
dynamicFieldValueOperands,
|
||||
} = data;
|
||||
const { concurrency, enablePerf, enableTroubleshooter } = options;
|
||||
const attributesQueryValue = getAttributesQueryValue({
|
||||
attributesQueryValue: _attributesQueryValue ?? null,
|
||||
attributes: attributesOfTheOrg,
|
||||
dynamicFieldValueOperands,
|
||||
});
|
||||
|
||||
// TODO: Do we really need to do !attributesQueryValue check separately?
|
||||
if (!attributesQueryValue || raqbQueryValueUtils.isQueryValueEmpty(attributesQueryValue as JsonTree)) {
|
||||
return {
|
||||
logicBuildingWarnings: null,
|
||||
teamMembersMatchingAttributeLogic: null,
|
||||
timeTaken: null,
|
||||
...buildTroubleshooterData({
|
||||
type: TroubleshooterCase.MATCHES_ALL_MEMBERS_BECAUSE_OF_EMPTY_QUERY_VALUE,
|
||||
data: { attributesQueryValue },
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const [attributesQueryBuilderConfig, ttgetAttributesQueryBuilderConfigHavingListofLabels] = pf(() =>
|
||||
getAttributesQueryBuilderConfigHavingListofLabels({
|
||||
dynamicFieldValueOperands,
|
||||
attributes: attributesOfTheOrg,
|
||||
})
|
||||
);
|
||||
|
||||
const { logic, warnings: logicBuildingWarnings } = getJsonLogic({
|
||||
attributesQueryValue,
|
||||
attributesQueryBuilderConfig: attributesQueryBuilderConfig as unknown as Config,
|
||||
});
|
||||
|
||||
if (!logic) {
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic: null,
|
||||
logicBuildingWarnings: null,
|
||||
timeTaken: {
|
||||
ttgetAttributesQueryBuilderConfigHavingListofLabels,
|
||||
},
|
||||
...buildTroubleshooterData({
|
||||
type: TroubleshooterCase.NO_LOGIC_FOUND,
|
||||
data: {
|
||||
attributesQueryValue,
|
||||
attributesQueryBuilderConfig,
|
||||
teamMembersWithAttributeOptionValuePerAttribute,
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
const [
|
||||
{ teamMembersMatchingAttributeLogicMap, attributesDataPerUser },
|
||||
ttTeamMembersMatchingAttributeLogic,
|
||||
] = await aPf(async () =>
|
||||
getLogicResultForAllMembers(
|
||||
{
|
||||
teamMembersWithAttributeOptionValuePerAttribute,
|
||||
attributeJsonLogic: logic,
|
||||
attributesQueryValue,
|
||||
},
|
||||
{
|
||||
concurrency,
|
||||
enableTroubleshooter,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const teamMembersMatchingAttributeLogic = Array.from(teamMembersMatchingAttributeLogicMap).map((item) => ({
|
||||
userId: item[0],
|
||||
result: item[1],
|
||||
}));
|
||||
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic,
|
||||
logicBuildingWarnings,
|
||||
timeTaken: {
|
||||
ttgetAttributesQueryBuilderConfigHavingListofLabels,
|
||||
ttTeamMembersMatchingAttributeLogic,
|
||||
},
|
||||
...buildTroubleshooterData({
|
||||
type: TroubleshooterCase.MATCH_RESULTS_READY,
|
||||
data: {
|
||||
attributesDataPerUser,
|
||||
attributesQueryValue,
|
||||
attributesQueryBuilderConfig,
|
||||
logic,
|
||||
attributesOfTheOrg,
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
function pf<ReturnValue>(fn: () => ReturnValue): [ReturnValue, number | null] {
|
||||
if (!enablePerf) {
|
||||
return [fn(), null];
|
||||
}
|
||||
return perf(fn);
|
||||
}
|
||||
async function aPf<ReturnValue>(fn: () => Promise<ReturnValue>): Promise<[ReturnValue, number | null]> {
|
||||
if (!enablePerf) {
|
||||
return [await fn(), null];
|
||||
}
|
||||
return asyncPerf(fn);
|
||||
}
|
||||
}
|
||||
|
||||
async function runMainAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
|
||||
const { teamMembersMatchingAttributeLogic, ...rest } = await runAttributeLogic(data, options);
|
||||
return {
|
||||
teamMembersMatchingMainAttributeLogic: teamMembersMatchingAttributeLogic,
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
|
||||
async function runFallbackAttributeLogic(data: RunAttributeLogicData, options: RunAttributeLogicOptions) {
|
||||
const { teamMembersMatchingAttributeLogic, ...rest } = await runAttributeLogic(data, options);
|
||||
return {
|
||||
teamMembersMatchingFallbackLogic: teamMembersMatchingAttributeLogic,
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getAttributesForLogic({ teamId, orgId }: { teamId: number; orgId: number }) {
|
||||
const [result, ttAttributes] = await asyncPerf(async () => {
|
||||
return getAttributesAssignmentData({ teamId, orgId });
|
||||
});
|
||||
|
||||
return {
|
||||
attributesOfTheOrg: result.attributesOfTheOrg,
|
||||
teamMembersWithAttributeOptionValuePerAttribute: result.attributesAssignedToTeamMembersWithOptions,
|
||||
timeTaken: ttAttributes,
|
||||
};
|
||||
}
|
||||
|
||||
export async function findTeamMembersMatchingAttributeLogic(
|
||||
data: {
|
||||
teamId: number;
|
||||
orgId: number;
|
||||
attributesQueryValue: AttributesQueryValue | null;
|
||||
fallbackAttributesQueryValue?: AttributesQueryValue | null;
|
||||
dynamicFieldValueOperands?: dynamicFieldValueOperands;
|
||||
isPreview?: boolean;
|
||||
},
|
||||
options: {
|
||||
enablePerf?: boolean;
|
||||
concurrency?: number;
|
||||
enableTroubleshooter?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
// Higher value of concurrency might not be performant as it might overwhelm the system. So, use a lower value as default.
|
||||
const { enablePerf = false, concurrency = 2, enableTroubleshooter = false } = options;
|
||||
|
||||
// Any explicit value being passed should cause fallback to be considered. Even undefined
|
||||
const considerFallback = "fallbackAttributesQueryValue" in data;
|
||||
|
||||
const {
|
||||
teamId,
|
||||
orgId,
|
||||
attributesQueryValue,
|
||||
fallbackAttributesQueryValue,
|
||||
dynamicFieldValueOperands,
|
||||
isPreview,
|
||||
} = data;
|
||||
|
||||
const {
|
||||
attributesOfTheOrg,
|
||||
teamMembersWithAttributeOptionValuePerAttribute,
|
||||
timeTaken: ttGetAttributesForLogic,
|
||||
} = await getAttributesForLogic({
|
||||
teamId,
|
||||
orgId,
|
||||
});
|
||||
|
||||
const runAttributeLogicOptions = {
|
||||
concurrency,
|
||||
enablePerf,
|
||||
isPreview: !!isPreview,
|
||||
enableTroubleshooter,
|
||||
};
|
||||
|
||||
const runAttributeLogicData: Omit<RunAttributeLogicData, "attributesQueryValue"> = {
|
||||
// Change it as per the main/fallback query
|
||||
attributesData: {
|
||||
attributesOfTheOrg,
|
||||
teamMembersWithAttributeOptionValuePerAttribute,
|
||||
},
|
||||
dynamicFieldValueOperands,
|
||||
};
|
||||
|
||||
const {
|
||||
teamMembersMatchingMainAttributeLogic,
|
||||
timeTaken: teamMembersMatchingMainAttributeLogicTimeTaken,
|
||||
troubleshooter,
|
||||
logicBuildingWarnings: mainAttributeLogicBuildingWarnings,
|
||||
} = await runMainAttributeLogic(
|
||||
{
|
||||
...runAttributeLogicData,
|
||||
attributesQueryValue: attributesQueryValue,
|
||||
},
|
||||
runAttributeLogicOptions
|
||||
);
|
||||
|
||||
// It being null means that no logic was found and thus all members match. In such case, we don't fallback intentionally.
|
||||
// This is the case when user added no rules so, he expects to match all members
|
||||
if (!teamMembersMatchingMainAttributeLogic) {
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic: null,
|
||||
checkedFallback: false,
|
||||
mainAttributeLogicBuildingWarnings,
|
||||
fallbackAttributeLogicBuildingWarnings: [],
|
||||
timeTaken: {
|
||||
...teamMembersMatchingMainAttributeLogicTimeTaken,
|
||||
ttGetAttributesForLogic,
|
||||
},
|
||||
...(enableTroubleshooter
|
||||
? buildTroubleshooterData({
|
||||
...troubleshooter,
|
||||
})
|
||||
: null),
|
||||
};
|
||||
}
|
||||
|
||||
const noMatchingMembersFound = !teamMembersMatchingMainAttributeLogic.length;
|
||||
|
||||
if (noMatchingMembersFound && considerFallback) {
|
||||
const {
|
||||
teamMembersMatchingFallbackLogic,
|
||||
timeTaken: teamMembersMatchingFallbackLogicTimeTaken,
|
||||
troubleshooter,
|
||||
logicBuildingWarnings: fallbackAttributeLogicBuildingWarnings,
|
||||
} = await runFallbackAttributeLogic(
|
||||
{
|
||||
...runAttributeLogicData,
|
||||
attributesQueryValue: fallbackAttributesQueryValue ?? null,
|
||||
},
|
||||
runAttributeLogicOptions
|
||||
);
|
||||
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic: teamMembersMatchingFallbackLogic,
|
||||
checkedFallback: true,
|
||||
fallbackAttributeLogicBuildingWarnings,
|
||||
mainAttributeLogicBuildingWarnings,
|
||||
timeTaken: {
|
||||
...teamMembersMatchingFallbackLogicTimeTaken,
|
||||
ttGetAttributesForLogic,
|
||||
},
|
||||
...(enableTroubleshooter
|
||||
? buildTroubleshooterData({
|
||||
...troubleshooter,
|
||||
type: TroubleshooterCase.MATCH_RESULTS_READY_WITH_FALLBACK,
|
||||
})
|
||||
: null),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
teamMembersMatchingAttributeLogic: teamMembersMatchingMainAttributeLogic,
|
||||
checkedFallback: false,
|
||||
mainAttributeLogicBuildingWarnings,
|
||||
fallbackAttributeLogicBuildingWarnings: [],
|
||||
timeTaken: {
|
||||
...teamMembersMatchingMainAttributeLogicTimeTaken,
|
||||
ttGetAttributesForLogic,
|
||||
},
|
||||
...(enableTroubleshooter
|
||||
? buildTroubleshooterData({
|
||||
...troubleshooter,
|
||||
type: TroubleshooterCase.MATCH_RESULTS_READY,
|
||||
data: {
|
||||
...troubleshooter.data,
|
||||
attributesOfTheOrg,
|
||||
},
|
||||
})
|
||||
: null),
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,224 +0,0 @@
|
||||
import type { JsonGroup, JsonItem, JsonRule, JsonTree } from "react-awesome-query-builder";
|
||||
import type { Config } from "react-awesome-query-builder";
|
||||
import { Utils as QbUtils } from "react-awesome-query-builder";
|
||||
|
||||
import { getQueryBuilderConfigForAttributes } from "@calcom/app-store/routing-forms/lib/getQueryBuilderConfig";
|
||||
import type { LocalRoute } from "@calcom/app-store/routing-forms/types/types";
|
||||
import type { dynamicFieldValueOperands } from "@calcom/lib/raqb/types";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import type {
|
||||
AttributeOptionValueWithType,
|
||||
AttributeOptionValue,
|
||||
Attribute,
|
||||
} from "@calcom/lib/service/attribute/server/getAttributes";
|
||||
import { AttributeType } from "@calcom/prisma/enums";
|
||||
|
||||
import { resolveQueryValue } from "./resolveQueryValue";
|
||||
import { caseInsensitive } from "./utils";
|
||||
|
||||
function ensureArray(value: string | string[]) {
|
||||
return typeof value === "string" ? [value] : value;
|
||||
}
|
||||
|
||||
export const raqbQueryValueUtils = {
|
||||
isQueryValueARuleGroup: function isQueryValueARuleGroup(queryValue: JsonTree): queryValue is JsonGroup {
|
||||
return queryValue.type === "group";
|
||||
},
|
||||
isARule: function isARule(rule: JsonItem): rule is JsonRule {
|
||||
return rule.type === "rule";
|
||||
},
|
||||
getValueTypeFromAttributesQueryValueForRaqbField:
|
||||
function getValueTypeFromAttributesQueryValueForRaqbField({
|
||||
attributesQueryValue,
|
||||
raqbFieldId,
|
||||
}: {
|
||||
attributesQueryValue: JsonTree;
|
||||
raqbFieldId: string;
|
||||
}) {
|
||||
if (!raqbQueryValueUtils.isQueryValueARuleGroup(attributesQueryValue)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!attributesQueryValue.children1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let raqbFieldValueType = null;
|
||||
|
||||
Object.values(attributesQueryValue.children1).reduce((acc, rule) => {
|
||||
if (!raqbQueryValueUtils.isARule(rule)) {
|
||||
return acc;
|
||||
}
|
||||
const ruleProperties = rule?.properties;
|
||||
if (!ruleProperties) {
|
||||
return acc;
|
||||
}
|
||||
if (ruleProperties.field === raqbFieldId) {
|
||||
raqbFieldValueType = ruleProperties.valueType?.[0];
|
||||
}
|
||||
return acc;
|
||||
}, null);
|
||||
|
||||
return raqbFieldValueType;
|
||||
},
|
||||
isQueryValueEmpty: function isQueryValueEmpty(queryValue: JsonTree | null): queryValue is null {
|
||||
if (!queryValue) {
|
||||
return true;
|
||||
}
|
||||
return !queryValue.children1;
|
||||
},
|
||||
};
|
||||
|
||||
export function buildEmptyQueryValue() {
|
||||
return { id: QbUtils.uuid(), type: "group" as const };
|
||||
}
|
||||
|
||||
export const buildStateFromQueryValue = ({
|
||||
queryValue,
|
||||
config,
|
||||
}: {
|
||||
/**
|
||||
* Allow null as the queryValue as initially there could be no queryValue and without that we can't build the state and can't show the UI
|
||||
*/
|
||||
queryValue: JsonTree | null;
|
||||
config: Config;
|
||||
}) => {
|
||||
const queryValueToUse = queryValue || buildEmptyQueryValue();
|
||||
const immutableTree = QbUtils.checkTree(QbUtils.loadTree(queryValueToUse), config);
|
||||
return {
|
||||
state: {
|
||||
tree: immutableTree,
|
||||
config,
|
||||
},
|
||||
queryValue: QbUtils.getTree(immutableTree),
|
||||
};
|
||||
};
|
||||
|
||||
export function getValueOfAttributeOption(
|
||||
attributeOptions:
|
||||
| Pick<AttributeOptionValue, "isGroup" | "contains" | "value">
|
||||
| Pick<AttributeOptionValue, "isGroup" | "contains" | "value">[]
|
||||
) {
|
||||
if (!(attributeOptions instanceof Array)) {
|
||||
return transformAttributeOption(attributeOptions);
|
||||
}
|
||||
return attributeOptions
|
||||
.map(transformAttributeOption)
|
||||
.flat()
|
||||
.filter((value, index, self) => self.indexOf(value) === index);
|
||||
|
||||
function transformAttributeOption(
|
||||
attributeOption: Pick<AttributeOptionValue, "isGroup" | "contains" | "value">
|
||||
) {
|
||||
if (attributeOption.isGroup) {
|
||||
const subOptions = attributeOption.contains.map((option) => option.value);
|
||||
console.log("A group option found. Using all its sub-options instead", safeStringify(subOptions));
|
||||
return subOptions;
|
||||
}
|
||||
return attributeOption.value;
|
||||
}
|
||||
}
|
||||
|
||||
function getAttributesData({
|
||||
attributesData,
|
||||
}: {
|
||||
attributesData: Record<string, AttributeOptionValueWithType>;
|
||||
attributesQueryValue: NonNullable<LocalRoute["attributesQueryValue"]>;
|
||||
}) {
|
||||
return Object.entries(attributesData).reduce(
|
||||
(acc, [attributeId, { type: attributeType, attributeOption }]) => {
|
||||
const compatibleValueForAttributeAndFormFieldMatching = caseInsensitive(
|
||||
getValueOfAttributeOption(attributeOption)
|
||||
);
|
||||
|
||||
acc[attributeId] =
|
||||
// multiselect attribute's value must be an array as all the operators multiselect_some_in, multiselect_all_in and their respective not operators expect an array
|
||||
// If we add an operator that doesn't expect an array, we need to somehow make it operator based.
|
||||
attributeType === AttributeType.MULTI_SELECT
|
||||
? ensureArray(compatibleValueForAttributeAndFormFieldMatching)
|
||||
: compatibleValueForAttributeAndFormFieldMatching;
|
||||
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string | string[]>
|
||||
);
|
||||
}
|
||||
/** Gets the attributes that were used to generate the chosen route and their values */
|
||||
function getAttributesQueryValue({
|
||||
attributesQueryValue,
|
||||
attributes,
|
||||
dynamicFieldValueOperands,
|
||||
}: {
|
||||
attributesQueryValue: LocalRoute["attributesQueryValue"] | null;
|
||||
attributes: Attribute[];
|
||||
dynamicFieldValueOperands?: dynamicFieldValueOperands;
|
||||
}) {
|
||||
if (!attributesQueryValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedQueryValue = resolveQueryValue({
|
||||
queryValue: attributesQueryValue,
|
||||
attributes,
|
||||
dynamicFieldValueOperands,
|
||||
});
|
||||
|
||||
return resolvedQueryValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns attributesQueryBuilderConfig with the list of labels instead of list of ids.
|
||||
*/
|
||||
export function getAttributesQueryBuilderConfigHavingListofLabels({
|
||||
dynamicFieldValueOperands,
|
||||
attributes,
|
||||
}: {
|
||||
dynamicFieldValueOperands?: dynamicFieldValueOperands;
|
||||
attributes: Attribute[];
|
||||
}) {
|
||||
const attributesQueryBuilderConfig = getQueryBuilderConfigForAttributes({
|
||||
attributes,
|
||||
dynamicOperandFields: dynamicFieldValueOperands?.fields,
|
||||
});
|
||||
|
||||
const attributesQueryBuilderConfigFieldsWithCompatibleListValues = Object.fromEntries(
|
||||
Object.entries(attributesQueryBuilderConfig.fields).map(([raqbFieldId, raqbField]) => {
|
||||
const raqbFieldType = raqbField.type;
|
||||
|
||||
return [
|
||||
raqbFieldId,
|
||||
{
|
||||
...raqbField,
|
||||
type: raqbFieldType,
|
||||
fieldSettings: {
|
||||
...raqbField.fieldSettings,
|
||||
listValues: raqbField.fieldSettings.listValues?.map((option) => {
|
||||
return {
|
||||
...option,
|
||||
// Use the title(which is the attributeOption.value) as the value of the raqb field so that it can be compatible for matching with the form field value
|
||||
value: caseInsensitive(option.title),
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
];
|
||||
})
|
||||
);
|
||||
|
||||
const attributesQueryBuilderConfigWithCompatibleListValues = {
|
||||
...attributesQueryBuilderConfig,
|
||||
fields: attributesQueryBuilderConfigFieldsWithCompatibleListValues,
|
||||
};
|
||||
|
||||
return attributesQueryBuilderConfigWithCompatibleListValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Utilities to establish compatibility between formFieldQueryValue and attributeQueryValue
|
||||
*/
|
||||
export const acrossQueryValueCompatiblity = {
|
||||
getAttributesQueryBuilderConfigHavingListofLabels,
|
||||
getAttributesQueryValue,
|
||||
getAttributesData,
|
||||
resolveQueryValue,
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "@calcom/lib/delegationCredential/server";
|
||||
import { availabilityUserSelect } from "@calcom/prisma";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
||||
|
||||
import { withSelectedCalendars } from "./withSelectedCalendars";
|
||||
|
||||
export async function findUsersForAvailabilityCheck({ where }: { where: Prisma.UserWhereInput }) {
|
||||
const user = await prisma.user.findFirst({
|
||||
where,
|
||||
select: {
|
||||
...availabilityUserSelect,
|
||||
selectedCalendars: true,
|
||||
credentials: {
|
||||
select: credentialForCalendarServiceSelect,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user: withSelectedCalendars(user),
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,36 +0,0 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
||||
|
||||
import { enrichUserWithDelegationCredentialsIncludeServiceAccountKey } from "../delegationCredential/server";
|
||||
|
||||
type User = { id: number; email: string };
|
||||
|
||||
/**
|
||||
* It includes in-memory DelegationCredential credentials as well.
|
||||
*/
|
||||
export async function getUsersCredentialsIncludeServiceAccountKey(user: User) {
|
||||
const credentials = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
select: credentialForCalendarServiceSelect,
|
||||
orderBy: {
|
||||
id: "asc",
|
||||
},
|
||||
});
|
||||
|
||||
const { credentials: allCredentials } = await enrichUserWithDelegationCredentialsIncludeServiceAccountKey({
|
||||
user: {
|
||||
email: user.email,
|
||||
id: user.id,
|
||||
credentials,
|
||||
},
|
||||
});
|
||||
|
||||
return allCredentials;
|
||||
}
|
||||
|
||||
export async function getUsersCredentials(user: User) {
|
||||
const credentials = await getUsersCredentialsIncludeServiceAccountKey(user);
|
||||
return credentials.map(({ delegatedTo: _1, ...rest }) => rest);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import type { Prisma, PrismaClient } from "@calcom/prisma/client";
|
||||
import { safeCredentialSelect } from "@calcom/prisma/selects/credential";
|
||||
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
||||
|
||||
import { buildNonDelegationCredential } from "../../delegationCredential/server";
|
||||
import { buildNonDelegationCredential } from "../../delegationCredential";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["CredentialRepository"] });
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { buildNonDelegationCredentials } from "@calcom/lib/delegationCredential";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
@@ -15,7 +16,6 @@ import { userMetadata } from "@calcom/prisma/zod-utils";
|
||||
import type { UpId, UserProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "../../availability";
|
||||
import { buildNonDelegationCredentials } from "../../delegationCredential/clientAndServer";
|
||||
import { withSelectedCalendars } from "../withSelectedCalendars";
|
||||
import { ProfileRepository } from "./profile";
|
||||
import { getParsedTeam } from "./teamUtils";
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { IFromUser, IOutOfOfficeData, IToUser } from "@calcom/lib/getUserAvailability";
|
||||
import type {
|
||||
IFromUser,
|
||||
IOutOfOfficeData,
|
||||
IToUser,
|
||||
} from "@calcom/features/availability/lib/getUserAvailability";
|
||||
import { withReporting } from "@calcom/lib/sentryWrapper";
|
||||
|
||||
import type { DateRange } from "./date-ranges";
|
||||
|
||||
Reference in new issue
Block a user