* Add endpoints for testing the flow * Add MVP * new route * Fixes * Fixes * Remove enable toggle support from domainWideDelegation * Fixes * Revert "Remove enable toggle support from domainWideDelegation" This reverts commit c29e729206cd1fa063f9c9ce0cf148ef1577d60b. * Revert yarn.lock * More fixes * Fix new workspace platform add * refactor: improvements * refactor: bug fixes and improvements * fix: type errors * fix: conflicts * chore: update test * fix: logic * chore: improvements * fix: toglle * fix: bugs * fix: type err * chore: check number type * fix: after conflicts * chore: fix type err * fix: type errors and tests * fix: tets * test * chore: remove unused * fix: google meet url on booking page and secondary calendar * fix: add property * fix: type err * fix: re assingment bug * fix: use getAllCredentials * chore: fix import * fix: installed count * fix: pass event type * fix: import * fix: [Stacked PR] Review fixes (#17958) * Review fixes * fix: destination calendar bug --------- Co-authored-by: Udit Takkar <udit222001@gmail.com> * refactor: use repository * chore: remove duplicate * fix: More review fixes for domain wide delegation (#17969) * Reuse buildCredentialPayloadForCalendar * fixes --------- Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com> * fix ts error * Fix getSchedule not using dwd credentials (#17995) * fix: Remove direct DWD table access from google-calendar and remove delegatedToId column from Credential (#18015) * Remove fn rename to reduce number of files changed * chore: check feature globally * test: add unit tests * chore: move function * test: add booking test * wip * Remove domain-wide-delegation team feature flag * Make sure duplicate calendars are not shown due to DWD. Show DWD when there is conflict * Fix tests and their ts errors * Fix more tests * Move findUsersForAvailabilityCheck to separate file as it has AppStore dependency causing problem with Routing Forms. Build crashes * fix: Multiple calendar connections from Google not showing up in apps/installed * DestinationCalendar must have either credentialId or domainWideDeelgationId. Also handle the case when DWD is disabled and there was a non-dwd credential that could be used * Disable deletetion of DWD as it is destructive and prefer disabling instead * Show DWD credential calendars at the top * Fixed tests * Calendar Cache DWD support * Self-Review: Verify email required and add more selectedCalendar tests * Self Review: shorten names * Self ReviewL Dead code removal * Revert "Calendar Cache DWD support" This reverts commit 009f236470fa21eba5986117d4f6e4d4c5e38c34. * Some misc fixes * fixes * Performance improvememt in slots loading and booking * More cases for handling dwd credentials * simplify the logic. Ensure that EventManager and the modules below it in the flow have CredentialForCalendarService available * Fix tests * Fix installed/conferencing not showing gogole meet * Shorten name * Fix ApI v2 tests * Add some more tests * add getSchedule tests * Improve tests * Make Google Meet default when DWD for google is enabled * Enable feature flagging for DWD * chore: bump libraries * Encrypt serviceaccount private key * Fix ts errors * bump platform libraries * org add dwd * org add dwd * bump platform libraries * fix selected calendars * fix remove selected dwd calendar * remove oauthclient id aliad in authedCalendar * remove oauthclient id aliad in authedCalendar * refactor: OrganizationsDwdController * chore: export toggleDwdEnabled from platform-libraries * feat: v2 update (enable / disable) dwd * refactor: SelectedCalendarsController check if user belongs to dwd org & for not dwd use previous logic * wip: DestinationCalendar send domainWideDelegationCredentialId from frontend to api * try fix set destination calendar api v2 * fixup! try fix set destination calendar api v2 * setting google meet as default location working for dwd * bump platform libraries version * allow office 365 workspace slug * allow office 365 workspace slug * chore: v2 create dwd MS and Google service keys input * fix: CreateDwdInput serviceAccountKey * fix: CredentialForCalendarService type * fix: check workspace slug * feat: update serviceAccessKey of DWD * testing * fixup! testing * fix: getAuthUtl bug * fix: unit tests * fix: type err and unit test * fix: e2e test * fix: credentials bug and failing unit tests * Update CalendarService.ts * chore: refactor office365 calendar service and add testDomainWideDelegationSetup * fix: office365Calendar use correct clientId/Secret for DWD * fix: office365Calendar dwd no need refresh token * test: add unit test for outlook dwd and setup * feat: added dwd support for office365 calendar * feat: added dwd support for office365 video * test: finish test for outlook dwd * fix: create dialog bug * chore: remove console logs * fix: refreshToken bug * bump version libraries * refactor: fetch dwd credentials only in findQualifiedHosts * fixup! refactor: fetch dwd credentials only in findQualifiedHosts * fix: type err * fix: type err * fix: getUserDisplayName * fix: unit test * chore: bump platform lib --------- Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com> Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com> Co-authored-by: Udit Takkar <udit222001@gmail.com> Co-authored-by: Morgan Vernay <morgan@cal.com> Co-authored-by: supalarry <laurisskraucis@gmail.com> Co-authored-by: Somay Chauhan <somaychauhan98@gmail.com> Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
914 lines
24 KiB
TypeScript
914 lines
24 KiB
TypeScript
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
|
|
import logger from "@calcom/lib/logger";
|
|
import { safeStringify } from "@calcom/lib/safeStringify";
|
|
import { getTranslation } from "@calcom/lib/server/i18n";
|
|
import prisma from "@calcom/prisma";
|
|
import { Prisma } from "@calcom/prisma/client";
|
|
import type { User as UserType } from "@calcom/prisma/client";
|
|
import type { CreationSource } from "@calcom/prisma/enums";
|
|
import { MembershipRole } from "@calcom/prisma/enums";
|
|
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
|
import { userMetadata } from "@calcom/prisma/zod-utils";
|
|
import type { UpId, UserProfile } from "@calcom/types/UserProfile";
|
|
|
|
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "../../availability";
|
|
import { buildNonDwdCredentials } from "../../domainWideDelegation/clientAndServer";
|
|
import { withSelectedCalendars } from "../withSelectedCalendars";
|
|
import { ProfileRepository } from "./profile";
|
|
import { getParsedTeam } from "./teamUtils";
|
|
|
|
export type { UserWithLegacySelectedCalendars } from "../withSelectedCalendars";
|
|
export { withSelectedCalendars };
|
|
export type UserAdminTeams = number[];
|
|
|
|
const log = logger.getSubLogger({ prefix: ["[repository/user]"] });
|
|
|
|
export const ORGANIZATION_ID_UNKNOWN = "ORGANIZATION_ID_UNKNOWN";
|
|
|
|
const teamSelect = Prisma.validator<Prisma.TeamSelect>()({
|
|
id: true,
|
|
name: true,
|
|
slug: true,
|
|
metadata: true,
|
|
logoUrl: true,
|
|
organizationSettings: true,
|
|
isOrganization: true,
|
|
isPlatform: true,
|
|
});
|
|
|
|
const userSelect = Prisma.validator<Prisma.UserSelect>()({
|
|
id: true,
|
|
username: true,
|
|
name: true,
|
|
email: true,
|
|
emailVerified: true,
|
|
bio: true,
|
|
avatarUrl: true,
|
|
timeZone: true,
|
|
startTime: true,
|
|
endTime: true,
|
|
weekStart: true,
|
|
bufferTime: true,
|
|
hideBranding: true,
|
|
theme: true,
|
|
createdDate: true,
|
|
trialEndsAt: true,
|
|
completedOnboarding: true,
|
|
locale: true,
|
|
timeFormat: true,
|
|
twoFactorSecret: true,
|
|
twoFactorEnabled: true,
|
|
backupCodes: true,
|
|
identityProviderId: true,
|
|
invitedTo: true,
|
|
brandColor: true,
|
|
darkBrandColor: true,
|
|
allowDynamicBooking: true,
|
|
allowSEOIndexing: true,
|
|
receiveMonthlyDigestEmail: true,
|
|
verified: true,
|
|
disableImpersonation: true,
|
|
locked: true,
|
|
movedToProfileId: true,
|
|
metadata: true,
|
|
isPlatformManaged: true,
|
|
lastActiveAt: true,
|
|
identityProvider: true,
|
|
teams: true,
|
|
});
|
|
|
|
export class UserRepository {
|
|
static async findTeamsByUserId({ userId }: { userId: UserType["id"] }) {
|
|
const teamMemberships = await prisma.membership.findMany({
|
|
where: {
|
|
userId: userId,
|
|
},
|
|
include: {
|
|
team: {
|
|
select: teamSelect,
|
|
},
|
|
},
|
|
});
|
|
|
|
const acceptedTeamMemberships = teamMemberships.filter((membership) => membership.accepted);
|
|
const pendingTeamMemberships = teamMemberships.filter((membership) => !membership.accepted);
|
|
|
|
return {
|
|
teams: acceptedTeamMemberships.map((membership) => membership.team),
|
|
memberships: teamMemberships,
|
|
acceptedTeamMemberships,
|
|
pendingTeamMemberships,
|
|
};
|
|
}
|
|
|
|
static async findOrganizations({ userId }: { userId: UserType["id"] }) {
|
|
const { acceptedTeamMemberships } = await UserRepository.findTeamsByUserId({
|
|
userId,
|
|
});
|
|
|
|
const acceptedOrgMemberships = acceptedTeamMemberships.filter(
|
|
(membership) => membership.team.isOrganization
|
|
);
|
|
|
|
const organizations = acceptedOrgMemberships.map((membership) => membership.team);
|
|
|
|
return {
|
|
organizations,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* It is aware of the fact that a user can be part of multiple organizations.
|
|
*/
|
|
static async findUsersByUsername({
|
|
orgSlug,
|
|
usernameList,
|
|
}: {
|
|
orgSlug: string | null;
|
|
usernameList: string[];
|
|
}) {
|
|
const { where, profiles } = await UserRepository._getWhereClauseForFindingUsersByUsername({
|
|
orgSlug,
|
|
usernameList,
|
|
});
|
|
log.info("findUsersByUsername", safeStringify({ where, profiles }));
|
|
|
|
return (
|
|
await prisma.user.findMany({
|
|
select: userSelect,
|
|
where,
|
|
})
|
|
).map((user) => {
|
|
log.info("findUsersByUsername", safeStringify({ user }));
|
|
// User isn't part of any organization
|
|
if (!profiles) {
|
|
return {
|
|
...user,
|
|
profile: ProfileRepository.buildPersonalProfileFromUser({ user }),
|
|
};
|
|
}
|
|
const profile = profiles.find((profile) => profile.user.id === user.id) ?? null;
|
|
if (!profile) {
|
|
log.error("Profile not found for user", safeStringify({ user, profiles }));
|
|
// Profile must be there because profile itself was used to retrieve the user
|
|
throw new Error("Profile couldn't be found");
|
|
}
|
|
const { user: _1, ...profileWithoutUser } = profile;
|
|
return {
|
|
...user,
|
|
profile: profileWithoutUser,
|
|
};
|
|
});
|
|
}
|
|
|
|
static async _getWhereClauseForFindingUsersByUsername({
|
|
orgSlug,
|
|
usernameList,
|
|
}: {
|
|
orgSlug: string | null;
|
|
usernameList: string[];
|
|
}) {
|
|
// Lookup in profiles because that's where the organization usernames exist
|
|
const profiles = orgSlug
|
|
? (
|
|
await ProfileRepository.findManyByOrgSlugOrRequestedSlug({
|
|
orgSlug: orgSlug,
|
|
usernames: usernameList,
|
|
})
|
|
).map((profile) => ({
|
|
...profile,
|
|
organization: getParsedTeam(profile.organization),
|
|
}))
|
|
: null;
|
|
const where =
|
|
profiles && profiles.length > 0
|
|
? {
|
|
// Get UserIds from profiles
|
|
id: {
|
|
in: profiles.map((profile) => profile.user.id),
|
|
},
|
|
}
|
|
: {
|
|
username: {
|
|
in: usernameList,
|
|
},
|
|
...(orgSlug
|
|
? {
|
|
organization: whereClauseForOrgWithSlugOrRequestedSlug(orgSlug),
|
|
}
|
|
: {
|
|
organization: null,
|
|
}),
|
|
};
|
|
return { where, profiles };
|
|
}
|
|
|
|
static async findByEmail({ email }: { email: string }) {
|
|
const user = await prisma.user.findUnique({
|
|
where: {
|
|
email: email.toLowerCase(),
|
|
},
|
|
select: userSelect,
|
|
});
|
|
return user;
|
|
}
|
|
|
|
static async findByEmailAndIncludeProfilesAndPassword({ email }: { email: string }) {
|
|
const user = await prisma.user.findUnique({
|
|
where: {
|
|
email: email.toLowerCase(),
|
|
},
|
|
select: {
|
|
locked: true,
|
|
role: true,
|
|
id: true,
|
|
username: true,
|
|
name: true,
|
|
email: true,
|
|
metadata: true,
|
|
identityProvider: true,
|
|
password: true,
|
|
twoFactorEnabled: true,
|
|
twoFactorSecret: true,
|
|
backupCodes: true,
|
|
locale: true,
|
|
teams: {
|
|
include: {
|
|
team: {
|
|
select: teamSelect,
|
|
},
|
|
},
|
|
},
|
|
createdDate: true,
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
const allProfiles = await ProfileRepository.findAllProfilesForUserIncludingMovedUser(user);
|
|
return {
|
|
...user,
|
|
allProfiles,
|
|
};
|
|
}
|
|
|
|
static async findById({ id }: { id: number }) {
|
|
const user = await prisma.user.findUnique({
|
|
where: {
|
|
id,
|
|
},
|
|
select: userSelect,
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
return {
|
|
...user,
|
|
metadata: userMetadata.parse(user.metadata),
|
|
};
|
|
}
|
|
|
|
static async findByIds({ ids }: { ids: number[] }) {
|
|
return prisma.user.findMany({
|
|
where: {
|
|
id: {
|
|
in: ids,
|
|
},
|
|
},
|
|
select: userSelect,
|
|
});
|
|
}
|
|
|
|
static async findByIdOrThrow({ id }: { id: number }) {
|
|
const user = await UserRepository.findById({ id });
|
|
if (!user) {
|
|
throw new Error(`User with id ${id} not found`);
|
|
}
|
|
return user;
|
|
}
|
|
|
|
static async findManyByOrganization({ organizationId }: { organizationId: number }) {
|
|
const profiles = await ProfileRepository.findManyForOrg({ organizationId });
|
|
return profiles.map((profile) => profile.user);
|
|
}
|
|
|
|
static isAMemberOfOrganization({
|
|
user,
|
|
organizationId,
|
|
}: {
|
|
user: { profiles: { organizationId: number }[] };
|
|
organizationId: number;
|
|
}) {
|
|
return user.profiles.some((profile) => profile.organizationId === organizationId);
|
|
}
|
|
|
|
static async findIfAMemberOfSomeOrganization({ user }: { user: { id: number } }) {
|
|
return !!(
|
|
await ProfileRepository.findManyForUser({
|
|
id: user.id,
|
|
})
|
|
).length;
|
|
}
|
|
|
|
static isMigratedToOrganization({
|
|
user,
|
|
}: {
|
|
user: {
|
|
metadata?: {
|
|
migratedToOrgFrom?: unknown;
|
|
} | null;
|
|
};
|
|
}) {
|
|
return !!user.metadata?.migratedToOrgFrom;
|
|
}
|
|
|
|
static async isMovedToAProfile({ user }: { user: Pick<UserType, "movedToProfileId"> }) {
|
|
return !!user.movedToProfileId;
|
|
}
|
|
|
|
static async enrichUserWithTheProfile<T extends { username: string | null; id: number }>({
|
|
user,
|
|
upId,
|
|
}: {
|
|
user: T;
|
|
upId: UpId;
|
|
}) {
|
|
log.debug("enrichUserWithTheProfile", safeStringify({ user, upId }));
|
|
const profile = await ProfileRepository.findByUpId(upId);
|
|
if (!profile) {
|
|
return {
|
|
...user,
|
|
profile: ProfileRepository.buildPersonalProfileFromUser({ user }),
|
|
};
|
|
}
|
|
return {
|
|
...user,
|
|
profile,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Use this method instead of `enrichUserWithTheProfile` if you don't directly have the profileId.
|
|
* It can happen in following cases:
|
|
* 1. While dealing with a User that hasn't been added to any organization yet and thus have no Profile entries.
|
|
* 2. While dealing with a User that has been moved to a Profile i.e. he was invited to an organization when he was an existing user.
|
|
* 3. We haven't added profileId to all the entities, so they aren't aware of which profile they belong to. So, we still mostly use this function to enrich the user with its profile.
|
|
*/
|
|
static async enrichUserWithItsProfile<T extends { id: number; username: string | null }>({
|
|
user,
|
|
}: {
|
|
user: T;
|
|
}): Promise<
|
|
T & {
|
|
nonProfileUsername: string | null;
|
|
profile: UserProfile;
|
|
}
|
|
> {
|
|
const profiles = await ProfileRepository.findManyForUser({ id: user.id });
|
|
if (profiles.length) {
|
|
const profile = profiles[0];
|
|
// platform org user doesn't need org profile
|
|
if (profile?.organization?.isPlatform) {
|
|
return {
|
|
...user,
|
|
nonProfileUsername: user.username,
|
|
profile: ProfileRepository.buildPersonalProfileFromUser({ user }),
|
|
};
|
|
}
|
|
|
|
return {
|
|
...user,
|
|
username: profile.username,
|
|
nonProfileUsername: user.username,
|
|
profile,
|
|
};
|
|
}
|
|
|
|
// If no organization profile exists, use the personal profile so that the returned user is normalized to have a profile always
|
|
return {
|
|
...user,
|
|
nonProfileUsername: user.username,
|
|
profile: ProfileRepository.buildPersonalProfileFromUser({ user }),
|
|
};
|
|
}
|
|
|
|
static async enrichUsersWithTheirProfiles<T extends { id: number; username: string | null }>(
|
|
users: T[]
|
|
): Promise<
|
|
Array<
|
|
T & {
|
|
nonProfileUsername: string | null;
|
|
profile: UserProfile;
|
|
}
|
|
>
|
|
> {
|
|
if (users.length === 0) return [];
|
|
|
|
const userIds = users.map((user) => user.id);
|
|
const profiles = await ProfileRepository.findManyForUsers(userIds);
|
|
|
|
// Create a Map for faster lookups, preserving arrays of profiles per user
|
|
const profileMap = new Map<number, UserProfile[]>();
|
|
profiles.forEach((profile) => {
|
|
if (!profileMap.has(profile.userId)) {
|
|
profileMap.set(profile.userId, []);
|
|
}
|
|
profileMap.get(profile.userId)!.push(profile);
|
|
});
|
|
|
|
// Precompute personal profiles for all users
|
|
const personalProfileMap = new Map<number, UserProfile>();
|
|
users.forEach((user) => {
|
|
personalProfileMap.set(user.id, ProfileRepository.buildPersonalProfileFromUser({ user }));
|
|
});
|
|
|
|
return users.map((user) => {
|
|
const userProfiles = profileMap.get(user.id) || [];
|
|
if (userProfiles.length > 0) {
|
|
const profile = userProfiles[0];
|
|
if (profile?.organization?.isPlatform) {
|
|
return {
|
|
...user,
|
|
nonProfileUsername: user.username,
|
|
profile: personalProfileMap.get(user.id)!,
|
|
};
|
|
}
|
|
|
|
return {
|
|
...user,
|
|
username: profile.username,
|
|
nonProfileUsername: user.username,
|
|
profile,
|
|
};
|
|
}
|
|
|
|
// If no organization profile exists, use the precomputed personal profile
|
|
return {
|
|
...user,
|
|
nonProfileUsername: user.username,
|
|
profile: personalProfileMap.get(user.id)!,
|
|
};
|
|
});
|
|
}
|
|
|
|
static enrichUserWithItsProfileBuiltFromUser<T extends { id: number; username: string | null }>({
|
|
user,
|
|
}: {
|
|
user: T;
|
|
}): T & {
|
|
nonProfileUsername: string | null;
|
|
profile: UserProfile;
|
|
} {
|
|
// If no organization profile exists, use the personal profile so that the returned user is normalized to have a profile always
|
|
return {
|
|
...user,
|
|
nonProfileUsername: user.username,
|
|
profile: ProfileRepository.buildPersonalProfileFromUser({ user }),
|
|
};
|
|
}
|
|
|
|
static async enrichEntityWithProfile<
|
|
T extends
|
|
| {
|
|
profile: {
|
|
id: number;
|
|
username: string | null;
|
|
organizationId: number | null;
|
|
organization?: {
|
|
id: number;
|
|
name: string;
|
|
calVideoLogo?: string | null;
|
|
bannerUrl: string | null;
|
|
slug: string | null;
|
|
metadata: Prisma.JsonValue;
|
|
};
|
|
};
|
|
}
|
|
| {
|
|
user: {
|
|
username: string | null;
|
|
id: number;
|
|
};
|
|
}
|
|
>(entity: T) {
|
|
if ("profile" in entity) {
|
|
const { profile, ...entityWithoutProfile } = entity;
|
|
const { organization, ...profileWithoutOrganization } = profile || {};
|
|
const parsedOrg = organization ? getParsedTeam(organization) : null;
|
|
|
|
const ret = {
|
|
...entityWithoutProfile,
|
|
profile: {
|
|
...profileWithoutOrganization,
|
|
...(parsedOrg
|
|
? {
|
|
organization: parsedOrg,
|
|
}
|
|
: {
|
|
organization: null,
|
|
}),
|
|
},
|
|
};
|
|
return ret;
|
|
} else {
|
|
const profiles = await ProfileRepository.findManyForUser(entity.user);
|
|
if (!profiles.length) {
|
|
return {
|
|
...entity,
|
|
profile: ProfileRepository.buildPersonalProfileFromUser({ user: entity.user }),
|
|
};
|
|
} else {
|
|
return {
|
|
...entity,
|
|
profile: profiles[0],
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
static async updateWhereId({
|
|
whereId,
|
|
data,
|
|
}: {
|
|
whereId: number;
|
|
data: {
|
|
movedToProfileId?: number | null;
|
|
};
|
|
}) {
|
|
return prisma.user.update({
|
|
where: {
|
|
id: whereId,
|
|
},
|
|
data: {
|
|
movedToProfile: data.movedToProfileId
|
|
? {
|
|
connect: {
|
|
id: data.movedToProfileId,
|
|
},
|
|
}
|
|
: undefined,
|
|
},
|
|
});
|
|
}
|
|
|
|
static async create(
|
|
data: Omit<Prisma.UserCreateInput, "password" | "organization" | "movedToProfile"> & {
|
|
username: string;
|
|
hashedPassword?: string;
|
|
organizationId: number | null;
|
|
creationSource: CreationSource;
|
|
locked: boolean;
|
|
}
|
|
) {
|
|
const organizationIdValue = data.organizationId;
|
|
const { email, username, creationSource, locked, hashedPassword, ...rest } = data;
|
|
|
|
logger.info("create user", { email, username, organizationIdValue, locked });
|
|
const t = await getTranslation("en", "common");
|
|
const availability = getAvailabilityFromSchedule(DEFAULT_SCHEDULE);
|
|
|
|
const user = await prisma.user.create({
|
|
data: {
|
|
username,
|
|
email: email,
|
|
...(hashedPassword && { password: { create: { hash: hashedPassword } } }),
|
|
// Default schedule
|
|
schedules: {
|
|
create: {
|
|
name: t("default_schedule_name"),
|
|
availability: {
|
|
createMany: {
|
|
data: availability.map((schedule) => ({
|
|
days: schedule.days,
|
|
startTime: schedule.startTime,
|
|
endTime: schedule.endTime,
|
|
})),
|
|
},
|
|
},
|
|
},
|
|
},
|
|
creationSource,
|
|
locked,
|
|
...(organizationIdValue
|
|
? {
|
|
organizationId: organizationIdValue,
|
|
profiles: {
|
|
create: {
|
|
username,
|
|
organizationId: organizationIdValue,
|
|
uid: ProfileRepository.generateProfileUid(),
|
|
},
|
|
},
|
|
}
|
|
: {}),
|
|
...rest,
|
|
},
|
|
});
|
|
|
|
return user;
|
|
}
|
|
static async getUserAdminTeams(userId: number) {
|
|
return prisma.user.findFirst({
|
|
where: {
|
|
id: userId,
|
|
},
|
|
select: {
|
|
id: true,
|
|
avatarUrl: true,
|
|
name: true,
|
|
username: true,
|
|
teams: {
|
|
where: {
|
|
accepted: true,
|
|
OR: [
|
|
{
|
|
role: { in: [MembershipRole.ADMIN, MembershipRole.OWNER] },
|
|
},
|
|
{
|
|
team: {
|
|
parent: {
|
|
members: {
|
|
some: {
|
|
id: userId,
|
|
role: { in: [MembershipRole.ADMIN, MembershipRole.OWNER] },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
],
|
|
},
|
|
select: {
|
|
team: {
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
logoUrl: true,
|
|
isOrganization: true,
|
|
parent: {
|
|
select: {
|
|
logoUrl: true,
|
|
name: true,
|
|
id: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|
|
static async isAdminOfTeamOrParentOrg({ userId, teamId }: { userId: number; teamId: number }) {
|
|
const membershipQuery = {
|
|
members: {
|
|
some: {
|
|
userId,
|
|
role: { in: [MembershipRole.ADMIN, MembershipRole.OWNER] },
|
|
},
|
|
},
|
|
};
|
|
const teams = await prisma.team.findMany({
|
|
where: {
|
|
id: teamId,
|
|
OR: [
|
|
membershipQuery,
|
|
{
|
|
parent: { ...membershipQuery },
|
|
},
|
|
],
|
|
},
|
|
select: {
|
|
id: true,
|
|
},
|
|
});
|
|
return !!teams.length;
|
|
}
|
|
static async isAdminOrOwnerOfTeam({ userId, teamId }: { userId: number; teamId: number }) {
|
|
const isAdminOrOwnerOfTeam = await prisma.membership.findFirst({
|
|
where: {
|
|
userId,
|
|
teamId,
|
|
role: { in: [MembershipRole.ADMIN, MembershipRole.OWNER] },
|
|
accepted: true,
|
|
},
|
|
select: {
|
|
id: true,
|
|
},
|
|
});
|
|
return !!isAdminOrOwnerOfTeam;
|
|
}
|
|
static async getTimeZoneAndDefaultScheduleId({ userId }: { userId: number }) {
|
|
return await prisma.user.findUnique({
|
|
where: {
|
|
id: userId,
|
|
},
|
|
select: {
|
|
timeZone: true,
|
|
defaultScheduleId: true,
|
|
},
|
|
});
|
|
}
|
|
|
|
static async adminFindById(userId: number) {
|
|
return await prisma.user.findUniqueOrThrow({
|
|
where: {
|
|
id: userId,
|
|
},
|
|
});
|
|
}
|
|
|
|
static async findUserTeams({ id }: { id: number }) {
|
|
const user = await prisma.user.findUnique({
|
|
where: {
|
|
id,
|
|
},
|
|
select: {
|
|
completedOnboarding: true,
|
|
teams: {
|
|
select: {
|
|
accepted: true,
|
|
team: {
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
logoUrl: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
return user;
|
|
}
|
|
|
|
static async updateAvatar({ id, avatarUrl }: { id: number; avatarUrl: string }) {
|
|
// Using updateMany here since if the user already has a profile it would throw an error
|
|
// because no records were found to update the profile picture
|
|
await prisma.user.updateMany({
|
|
where: {
|
|
id,
|
|
avatarUrl: {
|
|
equals: null,
|
|
},
|
|
},
|
|
data: {
|
|
avatarUrl,
|
|
},
|
|
});
|
|
}
|
|
static async findUserWithCredentials({ id }: { id: number }) {
|
|
const user = await prisma.user.findUnique({
|
|
where: {
|
|
id,
|
|
},
|
|
select: {
|
|
credentials: {
|
|
select: credentialForCalendarServiceSelect,
|
|
},
|
|
timeZone: true,
|
|
id: true,
|
|
selectedCalendars: true,
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
const { credentials, ...userWithSelectedCalendars } = withSelectedCalendars(user);
|
|
return {
|
|
...userWithSelectedCalendars,
|
|
credentials: buildNonDwdCredentials(credentials),
|
|
};
|
|
}
|
|
|
|
static async findUnlockedUserForSession({ userId }: { userId: number }) {
|
|
const user = await prisma.user.findUnique({
|
|
where: {
|
|
id: userId,
|
|
// Locked users can't login
|
|
locked: false,
|
|
},
|
|
select: {
|
|
id: true,
|
|
username: true,
|
|
name: true,
|
|
email: true,
|
|
emailVerified: true,
|
|
bio: true,
|
|
avatarUrl: true,
|
|
timeZone: true,
|
|
weekStart: true,
|
|
startTime: true,
|
|
endTime: true,
|
|
defaultScheduleId: true,
|
|
bufferTime: true,
|
|
theme: true,
|
|
appTheme: true,
|
|
createdDate: true,
|
|
hideBranding: true,
|
|
twoFactorEnabled: true,
|
|
disableImpersonation: true,
|
|
identityProvider: true,
|
|
identityProviderId: true,
|
|
brandColor: true,
|
|
darkBrandColor: true,
|
|
movedToProfileId: true,
|
|
selectedCalendars: {
|
|
select: {
|
|
eventTypeId: true,
|
|
externalId: true,
|
|
integration: true,
|
|
},
|
|
},
|
|
completedOnboarding: true,
|
|
destinationCalendar: true,
|
|
locale: true,
|
|
timeFormat: true,
|
|
trialEndsAt: true,
|
|
metadata: true,
|
|
role: true,
|
|
allowDynamicBooking: true,
|
|
allowSEOIndexing: true,
|
|
receiveMonthlyDigestEmail: true,
|
|
profiles: true,
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
return withSelectedCalendars(user);
|
|
}
|
|
|
|
static async getUserStats({ userId }: { userId: number }) {
|
|
const user = await prisma.user.findFirst({
|
|
where: {
|
|
id: userId,
|
|
},
|
|
select: {
|
|
_count: {
|
|
select: {
|
|
bookings: true,
|
|
// We only need user level selected calendars
|
|
selectedCalendars: {
|
|
where: {
|
|
eventTypeId: null,
|
|
},
|
|
},
|
|
teams: true,
|
|
eventTypes: true,
|
|
},
|
|
},
|
|
teams: {
|
|
select: {
|
|
team: {
|
|
select: {
|
|
eventTypes: {
|
|
select: {
|
|
id: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
const { _count, ...restUser } = user;
|
|
const { selectedCalendars, ...restCount } = _count;
|
|
return {
|
|
...restUser,
|
|
_count: {
|
|
...restCount,
|
|
userLevelSelectedCalendars: selectedCalendars,
|
|
},
|
|
};
|
|
}
|
|
|
|
static async findManyByIdsIncludeDestinationAndSelectedCalendars({ ids }: { ids: number[] }) {
|
|
const users = await prisma.user.findMany({
|
|
where: { id: { in: ids } },
|
|
include: {
|
|
selectedCalendars: true,
|
|
destinationCalendar: true,
|
|
},
|
|
});
|
|
return users.map(withSelectedCalendars);
|
|
}
|
|
}
|