Skip to content

Commit 86fc516

Browse files
Udit-takkarkeithwillcodehariombalhara
authored
refactor: loadUsers and move to separate file (#15532)
* refactor: loadUsers and move to separate file * fix: improvement --------- Co-authored-by: Keith Williams <keithwillcode@gmail.com> Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
1 parent dbf4be2 commit 86fc516

File tree

2 files changed

+88
-74
lines changed

2 files changed

+88
-74
lines changed

packages/features/bookings/lib/handleNewBooking.ts

+1-74
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import type { App, DestinationCalendar, EventTypeCustomInput } from "@prisma/client";
22
import { Prisma } from "@prisma/client";
3-
import type { IncomingMessage } from "http";
43
import { isValidPhoneNumber } from "libphonenumber-js";
54
// eslint-disable-next-line no-restricted-imports
65
import { cloneDeep } from "lodash";
@@ -41,7 +40,6 @@ import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/
4140
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
4241
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
4342
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
44-
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
4543
import {
4644
allowDisablingAttendeeConfirmationEmails,
4745
allowDisablingHostConfirmationEmails,
@@ -81,7 +79,6 @@ import { getPiiFreeCalendarEvent, getPiiFreeEventType, getPiiFreeUser } from "@c
8179
import { safeStringify } from "@calcom/lib/safeStringify";
8280
import { checkBookingLimits, checkDurationLimits, getLuckyUser } from "@calcom/lib/server";
8381
import { getTranslation } from "@calcom/lib/server/i18n";
84-
import { UserRepository } from "@calcom/lib/server/repository/user";
8582
import { slugify } from "@calcom/lib/slugify";
8683
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
8784
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
@@ -110,6 +107,7 @@ import { checkForConflicts } from "./conflictChecker/checkForConflicts";
110107
import { getAllCredentials } from "./getAllCredentialsForUsersOnEvent/getAllCredentials";
111108
import { refreshCredentials } from "./getAllCredentialsForUsersOnEvent/refreshCredentials";
112109
import getBookingDataSchema from "./getBookingDataSchema";
110+
import { loadUsers } from "./handleNewBooking/loadUsers";
113111
import handleSeats from "./handleSeats/handleSeats";
114112
import type { BookingSeat } from "./handleSeats/types";
115113

@@ -292,40 +290,6 @@ type IsFixedAwareUser = User & {
292290
priority?: number;
293291
};
294292

295-
const loadUsers = async (eventType: NewBookingEventType, dynamicUserList: string[], req: IncomingMessage) => {
296-
try {
297-
if (!eventType.id) {
298-
if (!Array.isArray(dynamicUserList) || dynamicUserList.length === 0) {
299-
throw new Error("dynamicUserList is not properly defined or empty.");
300-
}
301-
const { isValidOrgDomain, currentOrgDomain } = orgDomainConfig(req);
302-
const users = await findUsersByUsername({
303-
usernameList: dynamicUserList,
304-
orgSlug: isValidOrgDomain ? currentOrgDomain : null,
305-
});
306-
return users;
307-
}
308-
const hosts = eventType.hosts || [];
309-
310-
if (!Array.isArray(hosts)) {
311-
throw new Error("eventType.hosts is not properly defined.");
312-
}
313-
314-
const users = hosts.map(({ user, isFixed, priority }) => ({
315-
...user,
316-
isFixed,
317-
priority,
318-
}));
319-
320-
return users.length ? users : eventType.users;
321-
} catch (error) {
322-
if (error instanceof HttpError || error instanceof Prisma.PrismaClientKnownRequestError) {
323-
throw new HttpError({ statusCode: 400, message: error.message });
324-
}
325-
throw new HttpError({ statusCode: 500, message: "Unable to load users" });
326-
}
327-
};
328-
329293
export async function ensureAvailableUsers(
330294
eventType: Awaited<ReturnType<typeof getEventTypesFromDB>> & {
331295
users: IsFixedAwareUser[];
@@ -2650,40 +2614,3 @@ function handleCustomInputs(
26502614
}
26512615
});
26522616
}
2653-
2654-
/**
2655-
* This method is mostly same as the one in UserRepository but it includes a lot more relations which are specific requirement here
2656-
* TODO: Figure out how to keep it in UserRepository and use it here
2657-
*/
2658-
export const findUsersByUsername = async ({
2659-
usernameList,
2660-
orgSlug,
2661-
}: {
2662-
orgSlug: string | null;
2663-
usernameList: string[];
2664-
}) => {
2665-
log.debug("findUsersByUsername", { usernameList, orgSlug });
2666-
const { where, profiles } = await UserRepository._getWhereClauseForFindingUsersByUsername({
2667-
orgSlug,
2668-
usernameList,
2669-
});
2670-
return (
2671-
await prisma.user.findMany({
2672-
where,
2673-
select: {
2674-
...userSelect.select,
2675-
credentials: {
2676-
select: credentialForCalendarServiceSelect,
2677-
},
2678-
metadata: true,
2679-
},
2680-
})
2681-
).map((user) => {
2682-
const profile = profiles?.find((profile) => profile.user.id === user.id) ?? null;
2683-
return {
2684-
...user,
2685-
organizationId: profile?.organizationId ?? null,
2686-
profile,
2687-
};
2688-
});
2689-
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { Prisma } from "@prisma/client";
2+
import type { IncomingMessage } from "http";
3+
4+
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
5+
import { HttpError } from "@calcom/lib/http-error";
6+
import logger from "@calcom/lib/logger";
7+
import { UserRepository } from "@calcom/lib/server/repository/user";
8+
import prisma, { userSelect } from "@calcom/prisma";
9+
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
10+
11+
import type { NewBookingEventType } from "../handleNewBooking";
12+
13+
const log = logger.getSubLogger({ prefix: ["[loadUsers]:handleNewBooking "] });
14+
15+
type EventType = Pick<NewBookingEventType, "hosts" | "users" | "id">;
16+
17+
export const loadUsers = async (eventType: EventType, dynamicUserList: string[], req: IncomingMessage) => {
18+
try {
19+
const { currentOrgDomain } = orgDomainConfig(req);
20+
21+
return eventType.id
22+
? await loadUsersByEventType(eventType)
23+
: await loadDynamicUsers(dynamicUserList, currentOrgDomain);
24+
} catch (error) {
25+
if (error instanceof HttpError || error instanceof Prisma.PrismaClientKnownRequestError) {
26+
throw new HttpError({ statusCode: 400, message: error.message });
27+
}
28+
throw new HttpError({ statusCode: 500, message: "Unable to load users" });
29+
}
30+
};
31+
32+
const loadUsersByEventType = async (eventType: EventType): Promise<NewBookingEventType["users"]> => {
33+
const hosts = eventType.hosts || [];
34+
const users = hosts.map(({ user, isFixed, priority }) => ({
35+
...user,
36+
isFixed,
37+
priority,
38+
}));
39+
return users.length ? users : eventType.users;
40+
};
41+
42+
const loadDynamicUsers = async (dynamicUserList: string[], currentOrgDomain: string | null) => {
43+
if (!Array.isArray(dynamicUserList) || dynamicUserList.length === 0) {
44+
throw new Error("dynamicUserList is not properly defined or empty.");
45+
}
46+
return findUsersByUsername({
47+
usernameList: dynamicUserList,
48+
orgSlug: !!currentOrgDomain ? currentOrgDomain : null,
49+
});
50+
};
51+
52+
/**
53+
* This method is mostly same as the one in UserRepository but it includes a lot more relations which are specific requirement here
54+
* TODO: Figure out how to keep it in UserRepository and use it here
55+
*/
56+
export const findUsersByUsername = async ({
57+
usernameList,
58+
orgSlug,
59+
}: {
60+
orgSlug: string | null;
61+
usernameList: string[];
62+
}) => {
63+
log.debug("findUsersByUsername", { usernameList, orgSlug });
64+
const { where, profiles } = await UserRepository._getWhereClauseForFindingUsersByUsername({
65+
orgSlug,
66+
usernameList,
67+
});
68+
return (
69+
await prisma.user.findMany({
70+
where,
71+
select: {
72+
...userSelect.select,
73+
credentials: {
74+
select: credentialForCalendarServiceSelect,
75+
},
76+
metadata: true,
77+
},
78+
})
79+
).map((user) => {
80+
const profile = profiles?.find((profile) => profile.user.id === user.id) ?? null;
81+
return {
82+
...user,
83+
organizationId: profile?.organizationId ?? null,
84+
profile,
85+
};
86+
});
87+
};

0 commit comments

Comments
 (0)