* extract NextRequest * update api and tests * booking limits tests * fix more tests to use new approach * update more tests with new format * extract getOrgDomainConfig to not use req * extract req from loadNewUsers and pass in hostname/forcedSlug * fix instant meeting types and hostname fixes * fix handleNewBookingReq * fix type errors in tests * make hostName and forcedSlug optional * fix type err * Revert "fix type err" This reverts commit 9d5de9019d9dafe348c97b876baaa1d0675967e5. * wip fix e2e * fix: add missing headers * migrate handle recurring event and also create tests specific to fn * platform recurringbooking * fix type * hard code types on request object * bump libraries * fixup! bump libraries * fix: accessing host if headers not passed * fix: v2 recurring booking * fix: accessing host if headers not passed * chore: bump platform libraries * fix tests * push * chore: bump libraries * push lock changes * bump libraries --------- Co-authored-by: amrit <iamamrit27@gmail.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com> Co-authored-by: Morgan Vernay <morgan@cal.com> Co-authored-by: supalarry <laurisskraucis@gmail.com> Co-authored-by: Lauris Skraucis <lauris.skraucis@gmail.com>
225 lines
7.1 KiB
TypeScript
225 lines
7.1 KiB
TypeScript
import type { Prisma } from "@prisma/client";
|
|
import type { Logger } from "tslog";
|
|
|
|
import { checkIfUsersAreBlocked } from "@calcom/features/watchlist/operations/check-if-users-are-blocked.controller";
|
|
import { findQualifiedHostsWithDelegationCredentials } from "@calcom/lib/bookings/findQualifiedHostsWithDelegationCredentials";
|
|
import { enrichUsersWithDelegationCredentials } from "@calcom/lib/delegationCredential/server";
|
|
import getOrgIdFromMemberOrTeamId from "@calcom/lib/getOrgIdFromMemberOrTeamId";
|
|
import { HttpError } from "@calcom/lib/http-error";
|
|
import { getPiiFreeUser } from "@calcom/lib/piiFreeData";
|
|
import { safeStringify } from "@calcom/lib/safeStringify";
|
|
import type { RoutingFormResponse } from "@calcom/lib/server/getLuckyUser";
|
|
import { withSelectedCalendars } from "@calcom/lib/server/repository/user";
|
|
import { userSelect } from "@calcom/prisma";
|
|
import prisma from "@calcom/prisma";
|
|
import { SchedulingType } from "@calcom/prisma/enums";
|
|
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
|
import type { CredentialForCalendarService } from "@calcom/types/Credential";
|
|
|
|
import type { NewBookingEventType } from "./getEventTypesFromDB";
|
|
import { loadUsers } from "./loadUsers";
|
|
|
|
type Users = (Awaited<ReturnType<typeof loadUsers>>[number] & {
|
|
isFixed?: boolean;
|
|
metadata?: Prisma.JsonValue;
|
|
createdAt?: Date;
|
|
})[];
|
|
|
|
export type UsersWithDelegationCredentials = (Omit<
|
|
Awaited<ReturnType<typeof loadUsers>>[number],
|
|
"credentials"
|
|
> & {
|
|
isFixed?: boolean;
|
|
metadata?: Prisma.JsonValue;
|
|
createdAt?: Date;
|
|
credentials: CredentialForCalendarService[];
|
|
})[];
|
|
|
|
type EventType = Pick<
|
|
NewBookingEventType,
|
|
| "hosts"
|
|
| "users"
|
|
| "id"
|
|
| "userId"
|
|
| "schedulingType"
|
|
| "maxLeadThreshold"
|
|
| "team"
|
|
| "assignAllTeamMembers"
|
|
| "assignRRMembersUsingSegment"
|
|
| "rrSegmentQueryValue"
|
|
| "isRRWeightsEnabled"
|
|
| "rescheduleWithSameRoundRobinHost"
|
|
| "teamId"
|
|
>;
|
|
|
|
type InputProps = {
|
|
eventType: EventType;
|
|
eventTypeId: number;
|
|
dynamicUserList: string[];
|
|
logger: Logger<unknown>;
|
|
routedTeamMemberIds: number[] | null;
|
|
contactOwnerEmail: string | null;
|
|
rescheduleUid: string | null;
|
|
routingFormResponse: RoutingFormResponse | null;
|
|
isPlatform: boolean;
|
|
hostname: string | undefined;
|
|
forcedSlug: string | undefined;
|
|
};
|
|
|
|
export async function loadAndValidateUsers({
|
|
eventType,
|
|
eventTypeId,
|
|
dynamicUserList,
|
|
logger,
|
|
routedTeamMemberIds,
|
|
contactOwnerEmail,
|
|
rescheduleUid,
|
|
routingFormResponse,
|
|
isPlatform,
|
|
hostname,
|
|
forcedSlug,
|
|
}: InputProps): Promise<{
|
|
qualifiedRRUsers: UsersWithDelegationCredentials;
|
|
additionalFallbackRRUsers: UsersWithDelegationCredentials;
|
|
fixedUsers: UsersWithDelegationCredentials;
|
|
}> {
|
|
let users: Users = await loadUsers({
|
|
eventType,
|
|
dynamicUserList,
|
|
hostname: hostname || "",
|
|
forcedSlug,
|
|
isPlatform,
|
|
routedTeamMemberIds,
|
|
contactOwnerEmail,
|
|
});
|
|
|
|
const isDynamicAllowed = !users.some((user) => !user.allowDynamicBooking);
|
|
if (!isDynamicAllowed && !eventTypeId) {
|
|
logger.warn({
|
|
message: "NewBooking: Some of the users in this group do not allow dynamic booking",
|
|
});
|
|
throw new HttpError({
|
|
message: "Some of the users in this group do not allow dynamic booking",
|
|
statusCode: 400,
|
|
});
|
|
}
|
|
|
|
// If this event was pre-relationship migration
|
|
// TODO: Establish whether this is dead code.
|
|
if (!users.length && eventType.userId) {
|
|
const eventTypeUser = await prisma.user.findUnique({
|
|
where: {
|
|
id: eventType.userId,
|
|
},
|
|
select: {
|
|
credentials: {
|
|
select: credentialForCalendarServiceSelect,
|
|
}, // Don't leak to client
|
|
...userSelect.select,
|
|
},
|
|
});
|
|
if (!eventTypeUser) {
|
|
logger.warn({ message: "NewBooking: eventTypeUser.notFound" });
|
|
throw new HttpError({ statusCode: 404, message: "eventTypeUser.notFound" });
|
|
}
|
|
users.push(withSelectedCalendars(eventTypeUser));
|
|
}
|
|
|
|
if (!users) throw new HttpError({ statusCode: 404, message: "eventTypeUser.notFound" });
|
|
|
|
// Determine if users are locked
|
|
const containsBlockedUser = await checkIfUsersAreBlocked(users);
|
|
|
|
if (containsBlockedUser) throw new HttpError({ statusCode: 404, message: "eventTypeUser.notFound" });
|
|
|
|
// map fixed users
|
|
users = users.map((user) => ({
|
|
...user,
|
|
isFixed:
|
|
user.isFixed === false
|
|
? false
|
|
: user.isFixed || eventType.schedulingType !== SchedulingType.ROUND_ROBIN,
|
|
}));
|
|
const { qualifiedRRHosts, allFallbackRRHosts, fixedHosts } =
|
|
await findQualifiedHostsWithDelegationCredentials({
|
|
eventType,
|
|
routedTeamMemberIds: routedTeamMemberIds || [],
|
|
rescheduleUid,
|
|
contactOwnerEmail,
|
|
routingFormResponse,
|
|
});
|
|
const allQualifiedHostsHashMap = [...qualifiedRRHosts, ...(allFallbackRRHosts ?? []), ...fixedHosts].reduce(
|
|
(acc, host) => {
|
|
if (host.user.id) {
|
|
return { ...acc, [host.user.id]: host };
|
|
}
|
|
return acc;
|
|
},
|
|
{} as {
|
|
[key: number]: Awaited<
|
|
ReturnType<typeof findQualifiedHostsWithDelegationCredentials>
|
|
>["qualifiedRRHosts"][number];
|
|
}
|
|
);
|
|
|
|
let qualifiedRRUsers: UsersWithDelegationCredentials = [];
|
|
let allFallbackRRUsers: UsersWithDelegationCredentials = [];
|
|
let fixedUsers: UsersWithDelegationCredentials = [];
|
|
|
|
if (qualifiedRRHosts.length) {
|
|
// remove users that are not in the qualified hosts array
|
|
const qualifiedHostIds = new Set(qualifiedRRHosts.map((qualifiedHost) => qualifiedHost.user.id));
|
|
qualifiedRRUsers = users
|
|
.filter((user) => qualifiedHostIds.has(user.id))
|
|
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
|
|
}
|
|
|
|
if (allFallbackRRHosts?.length) {
|
|
const fallbackHostIds = new Set(allFallbackRRHosts.map((fallbackHost) => fallbackHost.user.id));
|
|
allFallbackRRUsers = users
|
|
.filter((user) => fallbackHostIds.has(user.id))
|
|
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
|
|
}
|
|
|
|
if (fixedHosts?.length) {
|
|
const fixedHostIds = new Set(fixedHosts.map((fixedHost) => fixedHost.user.id));
|
|
fixedUsers = users
|
|
.filter((user) => fixedHostIds.has(user.id))
|
|
.map((user) => ({ ...user, credentials: allQualifiedHostsHashMap[user.id].user.credentials }));
|
|
}
|
|
|
|
logger.debug(
|
|
"Concerned users",
|
|
safeStringify({
|
|
users: users.map(getPiiFreeUser),
|
|
})
|
|
);
|
|
|
|
const additionalFallbackRRUsers = allFallbackRRUsers.filter(
|
|
(fallbackUser) => !qualifiedRRUsers.find((qualifiedUser) => qualifiedUser.id === fallbackUser.id)
|
|
);
|
|
|
|
if (!qualifiedRRUsers.length && !fixedUsers.length) {
|
|
const firstUser = users[0];
|
|
const firstUserOrgId = await getOrgIdFromMemberOrTeamId({
|
|
memberId: firstUser.id ?? null,
|
|
teamId: eventType.teamId,
|
|
});
|
|
const usersEnrichedWithDelegationCredential = await enrichUsersWithDelegationCredentials({
|
|
orgId: firstUserOrgId ?? null,
|
|
users,
|
|
});
|
|
return {
|
|
qualifiedRRUsers,
|
|
additionalFallbackRRUsers, // without qualified
|
|
fixedUsers: usersEnrichedWithDelegationCredential,
|
|
};
|
|
}
|
|
|
|
return {
|
|
qualifiedRRUsers,
|
|
additionalFallbackRRUsers, // without qualified
|
|
fixedUsers,
|
|
};
|
|
}
|