feat: New Organization Schema along with the ability to invite existing users to an organization (#13002)
* Add profile table Copy to profile table Update schema Migrations * wip * Get switcher working * Add organization seeder * wip * Remove dead code * Fix unit tests * relevantProfile -> profile * cache bust * One more comment * Squash migrations * Copy to profile table * Update schema * Fix existing user invite flow * Add profile table * Copy to profile table * Update schema * Format * Add profile table Copy to profile table Update schema Migrations * Format * wip Get switcher working Add organization seeder wip Remove dead code Fix unit tests relevantProfile -> profile cache bust One more comment Squash migrations Copy to profile table Update schema Fix existing user invite flow Add profile table Copy to profile table Update schema chore: small improvements to signup (#13227) * removed features on mobile, better background color * nit * dark mode nits New Crowdin translations by Github Action fix: event reschedule workflow trigger (#13122) * fix event reschedule workflow trigger * uncomment previously failed test * review fix --------- Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: CarinaWolli <[email protected]> chore: added community support to help (#13213) refactor: Abstract `handleSeats` from `handleNewBooking` (#12062) * Refactor createBooking * Type fix * Abstract handleSeats * Create Invitee type * Create OrganizerUser type * Abstract addVideoCallDataToEvt * Abstract createLoggerWithEventDetails * Abstract `handleAppStatus` from handler * Create ReqAppsStatus type * Move `deleteMeeting` and `getCalendar` * Set parameters for `handleSeats` * Typescript refactor * Change function params from req * Type fix --------- Co-authored-by: Morgan <[email protected]> Co-authored-by: Erik <[email protected]> fix: Dynamic group booking org-migration redirect (#13223) * fix: Dynamic group booking redirect * Fix flaky private team test test: Check availability tab and all your functions (teste2e-availability) (#12434) * add changes * add changes * add changes * add changes * Requested changes * Change way to grab element --------- Co-authored-by: gitstart-calcom <[email protected]> Co-authored-by: gitstart-calcom <[email protected]> Co-authored-by: Morgan <[email protected]> Co-authored-by: Keith Williams <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]> fix: Reschedule a cancelled booking (#13170) * fix: Reschedule a cancelled booking * canceled instead of cancelled --------- Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: Carina Wollendorfer <[email protected]> v3.7.0 test: In Team Event type when location is Organizer Default App and U… (#12939) * test: In Team Event type when location is Organizer Default App and User Metadata is emoty * chore: use variable * fix: type error test: add test for invalid cal video (#13103) * test: add test for invalid cal video * chore: add confirm * chore: fix type error * chore: update code * test: add unit test * chore: type error * chore * chore: type * chore: fix test * chore --------- Co-authored-by: Carina Wollendorfer <[email protected]> chore: add error message for no availability (#13230) * chore: add error message for no default user availability * chore: check only availability * chore: change message * chore: add eventType fix: Team revert with members (#13228) refactor: Refactor seats logic (#12905) * Refactor createBooking * Type fix * Abstract handleSeats * Create Invitee type * Create OrganizerUser type * Abstract addVideoCallDataToEvt * Abstract createLoggerWithEventDetails * Abstract `handleAppStatus` from handler * Create ReqAppsStatus type * Move `deleteMeeting` and `getCalendar` * Set parameters for `handleSeats` * Typescript refactor * Change function params from req * Type fix * Move handleSeats * Abstract lastAttendeeDeleteBooking * Create function for rescheduling seated events * Fix imports on reschedule seats function * Fix imports * Import handleSeats function * Fix rescheduleUid type * Refactor owner reschedule to new time slot * Refactor combine two booking times together * Reschedule as an attendee * Refactor createNewSeat * Remove old handleSeats * Remove lastAttendeeDeleteBooking from handleNewBooking * Test for new attendee right params are passed * Unit test params for reschedule * Typo fix * Clean up * Create new seat test * Test when attendee already signs up for booking * Type fix * Test reschedule move attendee to existing booking * On reschedule create new booking * Test on last attendee cancel booking * Owner reschedule to new time slot * Owner rescheduling, merge two bookings together * Test: when merging more than available seats, then fail * Test: fail when event is full * Remove duplicate E2E tests * Clean up * Rename `addVideoCallDataToEvt` to `addVideoCallDataToEvent` * Refactor `calcAppsStatus` * Assign `evt` to resutl of `addVideoCallDataToEvent` * Use prisma.transaction when moving attendees * Clean create seat call * Use ErrorCode enum * Use attendeeRescheduledSeatedBooking function * Await function * Prevent double triggering of workflows * Use inviteeToAdd in createNewSeat * Remove unused error code * Remove old handleSeats file * Type fix * Type fix * Type fix * Type fix * Type fix * Type fix * Type fix * Type fix --------- Co-authored-by: Morgan <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Erik <[email protected]> feat: Allow admins to filter bookings only by attendee emails (#13236) * chore: Allow admins to filter bookings only by attendee emails * Fix type error Fixed [CAL-2930] Org branding isnt centered in shell #13225 (#13237) Add profile table Copy to profile table Update schema Migrations Format * wip * Add profile relation everywhere * Fix schema * Fix invite handler * Add profileId during eventTypec reation * Get dashboard working with profile relatioon * Add workflow create repository * Add profileId to host * Add profileId to credential table * Add destinationCalendar repository * Add profileId to membership * Revert all profile related changes * Add acme and dunder * Fix membership profileId usgae * Various fixes * Some renaming * Fix failing tests * Debugging next-aut * Consolidate migrations * Testing fixes * Fix unit tests * Self review feedback * PR feedback * Fix orgMigration as well * Add profile schema and copy users to it * Remove migrations from here * Fix type issues * Fix type error after main merge * Remove movedFromUserId * Add missing migration file * Self review addressed * Joe's review addressed * Fix profile switcher --------- Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
178 files changed
+4091
-1262
No files matched your search
@@ -2,6 +2,7 @@ import type { Prisma } from "@prisma/client";
|
||||
|
||||
import { HttpError } from "@calcom/lib/http-error";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { UserProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
export async function checkInstalled(slug: string, userId: number) {
|
||||
const alreadyInstalled = await prisma.credential.findFirst({
|
||||
@@ -17,7 +18,10 @@ export async function checkInstalled(slug: string, userId: number) {
|
||||
|
||||
type InstallationArgs = {
|
||||
appType: string;
|
||||
userId: number;
|
||||
user: {
|
||||
id: number;
|
||||
profile: UserProfile;
|
||||
};
|
||||
slug: string;
|
||||
key?: Prisma.InputJsonValue;
|
||||
teamId?: number;
|
||||
@@ -28,7 +32,7 @@ type InstallationArgs = {
|
||||
|
||||
export async function createDefaultInstallation({
|
||||
appType,
|
||||
userId,
|
||||
user,
|
||||
slug,
|
||||
key = {},
|
||||
teamId,
|
||||
@@ -40,7 +44,7 @@ export async function createDefaultInstallation({
|
||||
data: {
|
||||
type: appType,
|
||||
key,
|
||||
...(teamId ? { teamId } : { userId }),
|
||||
...(teamId ? { teamId } : { userId: user.id }),
|
||||
appId: slug,
|
||||
subscriptionId,
|
||||
paymentStatus,
|
||||
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "https://amie.so/signup",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -17,7 +17,7 @@ export async function getHandler(req: NextApiRequest) {
|
||||
await checkInstalled(slug, session.user.id);
|
||||
await createDefaultInstallation({
|
||||
appType,
|
||||
userId: session.user.id,
|
||||
user: session.user,
|
||||
slug,
|
||||
key: {},
|
||||
teamId,
|
||||
|
||||
@@ -33,7 +33,7 @@ export async function getHandler(req: NextApiRequest, res: NextApiResponse) {
|
||||
await checkInstalled(slug, session.user.id);
|
||||
await createDefaultInstallation({
|
||||
appType,
|
||||
userId: session.user.id,
|
||||
user: session.user,
|
||||
slug,
|
||||
key: {
|
||||
apiKey,
|
||||
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "https://cron.com",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "https://go.cal.com/deel",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "/apps/make/setup",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
newTab: true,
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -15,7 +15,7 @@ export async function getHandler(req: NextApiRequest) {
|
||||
await checkInstalled(slug, session.user.id);
|
||||
await createDefaultInstallation({
|
||||
appType,
|
||||
userId: session.user.id,
|
||||
user: session.user,
|
||||
slug,
|
||||
key: {},
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "https://pipedream.com/apps/cal-com",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -16,13 +16,14 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
// Check that user is authenticated
|
||||
req.session = await getServerSession({ req, res });
|
||||
const { teamId } = req.query;
|
||||
const userId = req.session?.user.id;
|
||||
if (!userId) {
|
||||
const user = req.session?.user;
|
||||
if (!user) {
|
||||
throw new HttpError({ statusCode: 401, message: "You must be logged in to do this" });
|
||||
}
|
||||
const userId = user.id;
|
||||
await createDefaultInstallation({
|
||||
appType: `${appConfig.slug}_other_calendar`,
|
||||
userId: userId,
|
||||
user,
|
||||
slug: appConfig.slug,
|
||||
key: {},
|
||||
teamId: Number(teamId),
|
||||
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -13,7 +13,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "raycast://extensions/eluce2/cal-com-share-meeting-links?source=webstore",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -15,7 +15,7 @@ export async function getHandler(req: NextApiRequest) {
|
||||
await checkInstalled(slug, session.user.id);
|
||||
await createDefaultInstallation({
|
||||
appType,
|
||||
userId: session.user.id,
|
||||
user: session.user,
|
||||
slug,
|
||||
key: {},
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -1,7 +1,6 @@
|
||||
import { stringify } from "querystring";
|
||||
import z from "zod";
|
||||
|
||||
import { getSlugOrRequestedSlug } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { TRPCError } from "@calcom/trpc/server";
|
||||
@@ -34,15 +33,16 @@ export const getServerSideProps = async function getServerSideProps(
|
||||
notFound: true,
|
||||
};
|
||||
}
|
||||
const { ProfileRepository } = await import("@calcom/lib/server/repository/profile");
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { form: formId, slug: _slug, pages: _pages, ...fieldsResponses } = queryParsed.data;
|
||||
const { currentOrgDomain, isValidOrgDomain } = orgDomainConfig(context.req);
|
||||
const { currentOrgDomain } = orgDomainConfig(context.req);
|
||||
|
||||
const form = await prisma.app_RoutingForms_Form.findFirst({
|
||||
where: {
|
||||
id: formId,
|
||||
user: {
|
||||
organization: isValidOrgDomain && currentOrgDomain ? getSlugOrRequestedSlug(currentOrgDomain) : null,
|
||||
...ProfileRepository._getPrismaWhereForProfilesOfOrg({ orgSlug: currentOrgDomain }),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -19,19 +19,16 @@ export const getServerSideProps = async function getServerSideProps(
|
||||
notFound: true,
|
||||
};
|
||||
}
|
||||
const { currentOrgDomain, isValidOrgDomain } = orgDomainConfig(context.req);
|
||||
const { currentOrgDomain } = orgDomainConfig(context.req);
|
||||
|
||||
const isEmbed = params.appPages[1] === "embed";
|
||||
const { ProfileRepository } = await import("@calcom/lib/server/repository/profile");
|
||||
|
||||
const form = await prisma.app_RoutingForms_Form.findFirst({
|
||||
where: {
|
||||
id: formId,
|
||||
user: {
|
||||
organization: isValidOrgDomain
|
||||
? {
|
||||
slug: currentOrgDomain,
|
||||
}
|
||||
: null,
|
||||
...ProfileRepository._getPrismaWhereForProfilesOfOrg({ orgSlug: currentOrgDomain }),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
|
||||
@@ -71,11 +71,13 @@ export const formsHandler = async ({ ctx, input }: FormsHandlerOptions) => {
|
||||
};
|
||||
|
||||
export default formsHandler;
|
||||
type SupportedFilters = Omit<NonNullable<NonNullable<TFormSchema>["filters"]>, "upIds"> | undefined;
|
||||
|
||||
export function getPrismaWhereFromFilters(
|
||||
user: {
|
||||
id: number;
|
||||
},
|
||||
filters: NonNullable<TFormSchema>["filters"]
|
||||
filters: SupportedFilters
|
||||
) {
|
||||
const where = {
|
||||
OR: [] as Prisma.App_RoutingForms_FormWhereInput[],
|
||||
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "https://skiff.com/blog/skiff-cal-com-launch",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "https://example.com/link",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -13,7 +13,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "/apps/typeform/how-to-use",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "https://cal.com/blog/cal-plus-vimcal",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -10,7 +10,7 @@ const handler: AppDeclarativeHandler = {
|
||||
supportsMultipleInstalls: false,
|
||||
handlerType: "add",
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -15,7 +15,7 @@ export async function getHandler(req: NextApiRequest) {
|
||||
await checkInstalled(slug, session.user.id);
|
||||
await createDefaultInstallation({
|
||||
appType,
|
||||
userId: session.user.id,
|
||||
user: session.user,
|
||||
slug,
|
||||
key: {},
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ const handler: AppDeclarativeHandler = {
|
||||
url: "https://wordpress.org/plugins/cal-com/",
|
||||
},
|
||||
createCredential: ({ appType, user, slug, teamId }) =>
|
||||
createDefaultInstallation({ appType, userId: user.id, slug, key: {}, teamId }),
|
||||
createDefaultInstallation({ appType, user: user, slug, key: {}, teamId }),
|
||||
};
|
||||
|
||||
export default handler;
|
||||
@@ -7,6 +7,7 @@ import { OrganizerScheduledEmail } from "./OrganizerScheduledEmail";
|
||||
export const OrganizerRequestEmail = (props: React.ComponentProps<typeof OrganizerScheduledEmail>) => {
|
||||
const seedData = { bookingUid: props.calEvent.uid, userId: props.calEvent.organizer.id };
|
||||
const token = symmetricEncrypt(JSON.stringify(seedData), process.env.CALENDSO_ENCRYPTION_KEY || "");
|
||||
//TODO: We should switch to using org domain if available
|
||||
const actionHref = `${WEBAPP_URL}/api/link/?token=${encodeURIComponent(token)}`;
|
||||
return (
|
||||
<OrganizerScheduledEmail
|
||||
|
||||
@@ -11,6 +11,7 @@ type TeamInvite = {
|
||||
teamName: string;
|
||||
joinLink: string;
|
||||
isCalcomMember: boolean;
|
||||
isAutoJoin: boolean;
|
||||
isOrg: boolean;
|
||||
parentTeamName: string | undefined;
|
||||
};
|
||||
@@ -75,7 +76,9 @@ export const TeamInviteEmail = (
|
||||
</p>
|
||||
<div style={{ display: "flex", justifyContent: "center" }}>
|
||||
<CallToAction
|
||||
label={props.language(props.isCalcomMember ? "email_user_cta" : "create_your_account")}
|
||||
label={props.language(
|
||||
props.isCalcomMember ? (props.isAutoJoin ? "login" : "email_user_cta") : "create_your_account"
|
||||
)}
|
||||
href={props.joinLink}
|
||||
endIconName="linkIcon"
|
||||
/>
|
||||
@@ -163,34 +166,3 @@ export const TeamInviteEmail = (
|
||||
</V2BaseEmailHtml>
|
||||
);
|
||||
};
|
||||
|
||||
const EmailStep = (props: { translationString: string; iconsrc: string }) => {
|
||||
return (
|
||||
<div style={{ display: "flex", alignItems: "center" }}>
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: "#E5E7EB",
|
||||
borderRadius: "48px",
|
||||
minHeight: "48px",
|
||||
minWidth: "48px",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
color: "white",
|
||||
marginRight: "16px",
|
||||
}}>
|
||||
<img src={props.iconsrc} alt="#" style={{ height: "24px", width: "auto" }} />
|
||||
</div>
|
||||
<p
|
||||
style={{
|
||||
fontStyle: "normal",
|
||||
fontWeight: 500,
|
||||
fontSize: "18px",
|
||||
lineHeight: "20px",
|
||||
color: "#black",
|
||||
}}>
|
||||
<>{props.translationString}</>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -12,6 +12,10 @@ export type TeamInvite = {
|
||||
teamName: string;
|
||||
joinLink: string;
|
||||
isCalcomMember: boolean;
|
||||
/**
|
||||
* We ideally should have a separate email for auto-join(when a user is automatically accepted into a team/org), but we don't have one yet.
|
||||
*/
|
||||
isAutoJoin: boolean;
|
||||
isOrg: boolean;
|
||||
parentTeamName: string | undefined;
|
||||
};
|
||||
|
||||
@@ -5,8 +5,12 @@ import { getToken } from "next-auth/jwt";
|
||||
|
||||
import checkLicense from "@calcom/features/ee/common/server/checkLicense";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getServerSession"] });
|
||||
/**
|
||||
* Stores the session in memory using the stringified token as the key.
|
||||
*
|
||||
@@ -29,6 +33,7 @@ export async function getServerSession(options: {
|
||||
res?: NextApiResponse | GetServerSidePropsContext["res"];
|
||||
authOptions?: AuthOptions;
|
||||
}) {
|
||||
log.debug("Getting server session");
|
||||
const { req, authOptions: { secret } = {} } = options;
|
||||
|
||||
const token = await getToken({
|
||||
@@ -37,6 +42,7 @@ export async function getServerSession(options: {
|
||||
});
|
||||
|
||||
if (!token || !token.email || !token.sub) {
|
||||
log.debug("Couldnt get token");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -46,7 +52,7 @@ export async function getServerSession(options: {
|
||||
return cachedSession;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
const userFromDb = await prisma.user.findUnique({
|
||||
where: {
|
||||
email: token.email.toLowerCase(),
|
||||
},
|
||||
@@ -54,12 +60,29 @@ export async function getServerSession(options: {
|
||||
// cacheStrategy: { ttl: 60, swr: 1 },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
if (!userFromDb) {
|
||||
log.debug("No user found");
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasValidLicense = await checkLicense(prisma);
|
||||
|
||||
let upId = token.upId;
|
||||
|
||||
if (!upId) {
|
||||
upId = `usr-${userFromDb.id}`;
|
||||
}
|
||||
|
||||
if (!upId) {
|
||||
log.error("No upId found for session", { userId: userFromDb.id });
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await UserRepository.enrichUserWithTheProfile({
|
||||
user: userFromDb,
|
||||
upId,
|
||||
});
|
||||
|
||||
const session: Session = {
|
||||
hasValidLicense,
|
||||
expires: new Date(typeof token.exp === "number" ? token.exp * 1000 : Date.now()).toISOString(),
|
||||
@@ -75,7 +98,10 @@ export async function getServerSession(options: {
|
||||
belongsToActiveTeam: token.belongsToActiveTeam,
|
||||
org: token.org,
|
||||
locale: user.locale ?? undefined,
|
||||
profile: user.profile,
|
||||
},
|
||||
profileId: token.profileId,
|
||||
upId,
|
||||
};
|
||||
|
||||
if (token?.impersonatedBy?.id) {
|
||||
@@ -98,5 +124,6 @@ export async function getServerSession(options: {
|
||||
|
||||
CACHE.set(JSON.stringify(token), session);
|
||||
|
||||
log.debug("Returned session", safeStringify(session));
|
||||
return session;
|
||||
}
|
||||
@@ -75,21 +75,5 @@ export default function CalComAdapter(prismaClient: PrismaClient) {
|
||||
// @NOTE: All methods below here are not being used but leaved if they are required
|
||||
unlinkAccount: (provider_providerAccountId: Prisma.AccountProviderProviderAccountIdCompoundUniqueInput) =>
|
||||
prismaClient.account.delete({ where: { provider_providerAccountId } }),
|
||||
async getSessionAndUser(sessionToken: string) {
|
||||
const userAndSession = await prismaClient.session.findUnique({
|
||||
where: { sessionToken },
|
||||
include: { user: true },
|
||||
});
|
||||
if (!userAndSession) return null;
|
||||
const { user, ...session } = userAndSession;
|
||||
return { user, session };
|
||||
},
|
||||
createSession: (data: Prisma.SessionCreateInput) => prismaClient.session.create({ data }),
|
||||
updateSession: (data: Prisma.SessionUpdateInput) =>
|
||||
prismaClient.session.update({
|
||||
where: { sessionToken: typeof data.sessionToken === "string" ? data.sessionToken : undefined },
|
||||
data,
|
||||
}),
|
||||
deleteSession: (sessionToken: string) => prismaClient.session.delete({ where: { sessionToken } }),
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Membership, Team, UserPermissionRole } from "@prisma/client";
|
||||
import type { AuthOptions, Session } from "next-auth";
|
||||
import type { JWT } from "next-auth/jwt";
|
||||
import { encode } from "next-auth/jwt";
|
||||
import type { Provider } from "next-auth/providers";
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
@@ -11,11 +12,15 @@ import ImpersonationProvider from "@calcom/features/ee/impersonation/lib/Imperso
|
||||
import { getOrgFullOrigin, subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { clientSecretVerifier, hostedCal, isSAMLLoginEnabled } from "@calcom/features/ee/sso/lib/saml";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { ENABLE_PROFILE_SWITCHER, IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { symmetricDecrypt, symmetricEncrypt } from "@calcom/lib/crypto";
|
||||
import { defaultCookies } from "@calcom/lib/default-cookies";
|
||||
import { isENVDev } from "@calcom/lib/env";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { randomString } from "@calcom/lib/random";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
|
||||
@@ -26,6 +31,7 @@ import { isPasswordValid } from "./isPasswordValid";
|
||||
import CalComAdapter from "./next-auth-custom-adapter";
|
||||
import { verifyPassword } from "./verifyPassword";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["next-auth-options"] });
|
||||
const GOOGLE_API_CREDENTIALS = process.env.GOOGLE_API_CREDENTIALS || "{}";
|
||||
const { client_id: GOOGLE_CLIENT_ID, client_secret: GOOGLE_CLIENT_SECRET } =
|
||||
JSON.parse(GOOGLE_API_CREDENTIALS)?.web || {};
|
||||
@@ -100,38 +106,7 @@ const providers: Provider[] = [
|
||||
throw new Error(ErrorCode.InternalServerError);
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
email: credentials.email.toLowerCase(),
|
||||
},
|
||||
select: {
|
||||
locked: true,
|
||||
role: true,
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
metadata: true,
|
||||
identityProvider: true,
|
||||
password: true,
|
||||
organizationId: true,
|
||||
twoFactorEnabled: true,
|
||||
twoFactorSecret: true,
|
||||
backupCodes: true,
|
||||
locale: true,
|
||||
organization: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const user = await UserRepository.findByEmailAndIncludeProfiles({ email: credentials.email });
|
||||
// Don't leak information about it being username or password that is invalid
|
||||
if (!user) {
|
||||
throw new Error(ErrorCode.IncorrectEmailPassword);
|
||||
@@ -253,8 +228,8 @@ const providers: Provider[] = [
|
||||
name: user.name,
|
||||
role: validateRole(user.role),
|
||||
belongsToActiveTeam: hasActiveTeams,
|
||||
organizationId: user.organizationId,
|
||||
locale: user.locale,
|
||||
profile: user.allProfiles[0],
|
||||
};
|
||||
},
|
||||
}),
|
||||
@@ -291,15 +266,28 @@ if (isSAMLLoginEnabled) {
|
||||
params: { grant_type: "authorization_code" },
|
||||
},
|
||||
userinfo: `${WEBAPP_URL}/api/auth/saml/userinfo`,
|
||||
profile: (profile) => {
|
||||
profile: async (profile: {
|
||||
id?: number;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
locale?: string;
|
||||
}) => {
|
||||
const user = await UserRepository.findByEmailAndIncludeProfiles({ email: profile.email || "" });
|
||||
if (!user) {
|
||||
throw new Error(ErrorCode.UserNotFound);
|
||||
}
|
||||
|
||||
const [userProfile] = user.allProfiles;
|
||||
return {
|
||||
id: profile.id || "",
|
||||
id: profile.id || 0,
|
||||
firstName: profile.firstName || "",
|
||||
lastName: profile.lastName || "",
|
||||
email: profile.email || "",
|
||||
name: `${profile.firstName || ""} ${profile.lastName || ""}`.trim(),
|
||||
email_verified: true,
|
||||
locale: profile.locale,
|
||||
profile: userProfile,
|
||||
};
|
||||
},
|
||||
options: {
|
||||
@@ -351,6 +339,12 @@ if (isSAMLLoginEnabled) {
|
||||
}
|
||||
|
||||
const { id, firstName, lastName, email } = userInfo;
|
||||
const user = await UserRepository.findByEmailAndIncludeProfiles({ email });
|
||||
if (!user) {
|
||||
throw new Error(ErrorCode.UserNotFound);
|
||||
}
|
||||
|
||||
const [profile] = user.allProfiles;
|
||||
|
||||
return {
|
||||
id: id as unknown as number,
|
||||
@@ -359,6 +353,7 @@ if (isSAMLLoginEnabled) {
|
||||
email,
|
||||
name: `${firstName} ${lastName}`.trim(),
|
||||
email_verified: true,
|
||||
profile,
|
||||
};
|
||||
},
|
||||
})
|
||||
@@ -427,15 +422,31 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
},
|
||||
providers,
|
||||
callbacks: {
|
||||
async jwt({ token, user, account, trigger, session }) {
|
||||
async jwt({
|
||||
// Always available but with a little difference in value
|
||||
token,
|
||||
// Available only in case of signIn, signUp or useSession().update call.
|
||||
trigger,
|
||||
// Available when useSession().update is called. The value will be the POST data
|
||||
session,
|
||||
// Available only in the first call once the user signs in. Not available in subsequent calls
|
||||
user,
|
||||
// Available only in the first call once the user signs in. Not available in subsequent calls
|
||||
account,
|
||||
}) {
|
||||
log.debug("callbacks:jwt", safeStringify({ token, user, account, trigger, session }));
|
||||
|
||||
// The data available in 'session' depends on what data was supplied in update method call of session
|
||||
if (trigger === "update") {
|
||||
return {
|
||||
...token,
|
||||
profileId: session?.profileId ?? token.profileId ?? null,
|
||||
upId: session?.upId ?? token.upId ?? null,
|
||||
locale: session?.locale ?? token.locale ?? "en",
|
||||
name: session?.name ?? token.name,
|
||||
username: session?.username ?? token.username,
|
||||
email: session?.email ?? token.email,
|
||||
};
|
||||
} as JWT;
|
||||
}
|
||||
const autoMergeIdentities = async () => {
|
||||
const existingUser = await prisma.user.findFirst({
|
||||
@@ -446,16 +457,9 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
organization: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
},
|
||||
},
|
||||
role: true,
|
||||
locale: true,
|
||||
movedToProfileId: true,
|
||||
teams: {
|
||||
include: {
|
||||
team: true,
|
||||
@@ -470,24 +474,41 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
|
||||
// Check if the existingUser has any active teams
|
||||
const belongsToActiveTeam = checkIfUserBelongsToActiveTeam(existingUser);
|
||||
const { teams: _teams, organization, ...existingUserWithoutTeamsField } = existingUser;
|
||||
const { teams: _teams, ...existingUserWithoutTeamsField } = existingUser;
|
||||
const allProfiles = await ProfileRepository.findAllProfilesForUserIncludingMovedUser(existingUser);
|
||||
log.debug(
|
||||
"callbacks:jwt:autoMergeIdentities",
|
||||
safeStringify({
|
||||
allProfiles,
|
||||
})
|
||||
);
|
||||
const { upId } = determineProfile({ profiles: allProfiles, token });
|
||||
|
||||
const parsedOrgMetadata = teamMetadataSchema.parse(organization?.metadata ?? {});
|
||||
const profile = await ProfileRepository.findByUpId(upId);
|
||||
if (!profile) {
|
||||
throw new Error("Profile not found");
|
||||
}
|
||||
|
||||
const profileOrg = profile?.organization;
|
||||
|
||||
return {
|
||||
...existingUserWithoutTeamsField,
|
||||
...token,
|
||||
profileId: profile.id,
|
||||
upId,
|
||||
belongsToActiveTeam,
|
||||
org: organization
|
||||
// All organizations in the token would be too big to store. It breaks the sessions request.
|
||||
// So, we just set the currently switched organization only here.
|
||||
org: profileOrg
|
||||
? {
|
||||
id: organization.id,
|
||||
name: organization.name,
|
||||
slug: organization.slug ?? parsedOrgMetadata?.requestedSlug ?? "",
|
||||
fullDomain: getOrgFullOrigin(organization.slug ?? parsedOrgMetadata?.requestedSlug ?? ""),
|
||||
id: profileOrg.id,
|
||||
name: profileOrg.name,
|
||||
slug: profileOrg.slug ?? profileOrg.requestedSlug ?? "",
|
||||
fullDomain: getOrgFullOrigin(profileOrg.slug ?? profileOrg.requestedSlug ?? ""),
|
||||
domainSuffix: subdomainSuffix(),
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
: null,
|
||||
} as JWT;
|
||||
};
|
||||
if (!user) {
|
||||
return await autoMergeIdentities();
|
||||
@@ -512,7 +533,9 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
belongsToActiveTeam: user?.belongsToActiveTeam,
|
||||
org: user?.org,
|
||||
locale: user?.locale,
|
||||
};
|
||||
profileId: user.profile?.id ?? token.profileId ?? null,
|
||||
upId: user.profile?.upId ?? token.upId ?? null,
|
||||
} as JWT;
|
||||
}
|
||||
|
||||
// The arguments above are from the provider so we need to look up the
|
||||
@@ -551,15 +574,23 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
belongsToActiveTeam: token?.belongsToActiveTeam as boolean,
|
||||
org: token?.org,
|
||||
locale: existingUser.locale,
|
||||
};
|
||||
} as JWT;
|
||||
}
|
||||
|
||||
if (account.type === "email") {
|
||||
return await autoMergeIdentities();
|
||||
}
|
||||
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
async session({ session, token, user }) {
|
||||
log.debug("callbacks:session - Session callback called", safeStringify({ session, token, user }));
|
||||
const hasValidLicense = await checkLicense(prisma);
|
||||
const profileId = token.profileId;
|
||||
const calendsoSession: Session = {
|
||||
...session,
|
||||
profileId,
|
||||
upId: token.upId || session.upId,
|
||||
hasValidLicense,
|
||||
user: {
|
||||
...session.user,
|
||||
@@ -576,7 +607,19 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
return calendsoSession;
|
||||
},
|
||||
async signIn(params) {
|
||||
const { user, account, profile } = params;
|
||||
const {
|
||||
/**
|
||||
* Available when Credentials provider is used - Has the value returned by authorize callback
|
||||
*/
|
||||
user,
|
||||
/**
|
||||
* Available when Credentials provider is used - Has the value submitted as the body of the HTTP POST submission
|
||||
*/
|
||||
profile,
|
||||
account,
|
||||
} = params;
|
||||
|
||||
log.debug("callbacks:signin", safeStringify(params));
|
||||
|
||||
if (account?.provider === "email") {
|
||||
return true;
|
||||
@@ -814,6 +857,9 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
|
||||
return false;
|
||||
},
|
||||
/**
|
||||
* Used to handle the navigation right after successful login or logout
|
||||
*/
|
||||
async redirect({ url, baseUrl }) {
|
||||
// Allows relative callback URLs
|
||||
if (url.startsWith("/")) return `${baseUrl}${url}`;
|
||||
@@ -823,3 +869,27 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Identifies the profile the user should be logged into.
|
||||
*/
|
||||
const determineProfile = ({
|
||||
token,
|
||||
profiles,
|
||||
}: {
|
||||
token: JWT;
|
||||
profiles: { id: number | null; upId: string }[];
|
||||
}) => {
|
||||
// If profile switcher is disabled, we can only show the first profile.
|
||||
if (!ENABLE_PROFILE_SWITCHER) {
|
||||
return profiles[0];
|
||||
}
|
||||
|
||||
if (token.upId) {
|
||||
// Otherwise use what's in the token
|
||||
return { profileId: token.profileId, upId: token.upId as string };
|
||||
}
|
||||
|
||||
// If there is just one profile it has to be the one we want to log into.
|
||||
return profiles[0];
|
||||
};
|
||||
@@ -127,6 +127,9 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
|
||||
where: {
|
||||
id: foundToken.teamId,
|
||||
},
|
||||
include: {
|
||||
parent: true,
|
||||
},
|
||||
});
|
||||
if (team) {
|
||||
const teamMetadata = teamMetadataSchema.parse(team?.metadata);
|
||||
@@ -157,10 +160,10 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
|
||||
closeComUpsertTeamUser(team, user, membership.role);
|
||||
|
||||
// Accept any child team invites for orgs.
|
||||
if (team.parentId) {
|
||||
if (team.parent) {
|
||||
await joinAnyChildTeamOnOrgInvite({
|
||||
userId: user.id,
|
||||
orgId: team.parentId,
|
||||
org: team.parent,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
where: {
|
||||
id: foundToken.teamId,
|
||||
},
|
||||
include: {
|
||||
parent: true,
|
||||
},
|
||||
});
|
||||
if (team) {
|
||||
const teamMetadata = teamMetadataSchema.parse(team?.metadata);
|
||||
@@ -97,10 +100,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
closeComUpsertTeamUser(team, user, membership.role);
|
||||
|
||||
// Accept any child team invites for orgs.
|
||||
if (team.parentId) {
|
||||
if (team.parent) {
|
||||
await joinAnyChildTeamOnOrgInvite({
|
||||
userId: user.id,
|
||||
orgId: team.parentId,
|
||||
org: team.parent,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +84,11 @@ const usernameCheck = async (usernameRaw: string) => {
|
||||
const username = slugify(usernameRaw);
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { username, organizationId: null },
|
||||
where: {
|
||||
username,
|
||||
// Simply remove it when we drop organizationId column
|
||||
organizationId: null,
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
},
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import type z from "zod";
|
||||
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Team, User } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { getOrgUsernameFromEmail } from "./getOrgUsernameFromEmail";
|
||||
|
||||
export const createOrUpdateMemberships = async ({
|
||||
teamMetadata,
|
||||
user,
|
||||
@@ -17,13 +20,39 @@ export const createOrUpdateMemberships = async ({
|
||||
}) => {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
if (teamMetadata?.isOrganization) {
|
||||
await tx.user.update({
|
||||
const dbUser = await tx.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
organizationId: team.id,
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
email: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Ideally dbUser.username should never be null, but just in case.
|
||||
// This method being called only during signup means that dbUser.username should be the correct org username
|
||||
const orgUsername =
|
||||
dbUser.username || getOrgUsernameFromEmail(dbUser.email, teamMetadata?.orgAutoAcceptEmail ?? null);
|
||||
await tx.profile.upsert({
|
||||
create: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: user.id,
|
||||
organizationId: team.id,
|
||||
username: orgUsername,
|
||||
},
|
||||
update: {
|
||||
username: orgUsername,
|
||||
},
|
||||
where: {
|
||||
userId_organizationId: {
|
||||
userId: user.id,
|
||||
organizationId: team.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const membership = await tx.membership.upsert({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
|
||||
export const getOrgUsernameFromEmail = (email: string, autoAcceptEmailDomain: string) => {
|
||||
export const getOrgUsernameFromEmail = (email: string, autoAcceptEmailDomain: string | null) => {
|
||||
const [emailUser, emailDomain = ""] = email.split("@");
|
||||
const username =
|
||||
emailDomain === autoAcceptEmailDomain
|
||||
|
||||
@@ -1,38 +1,58 @@
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
export async function joinOrganization({
|
||||
organizationId,
|
||||
userId,
|
||||
}: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
}) {
|
||||
return await prisma.user.update({
|
||||
import { getOrgUsernameFromEmail } from "./getOrgUsernameFromEmail";
|
||||
|
||||
export async function joinAnyChildTeamOnOrgInvite({ userId, org }: { userId: number; org: Team }) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
organizationId: organizationId,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
|
||||
const orgMetadata = teamMetadataSchema.parse(org.metadata);
|
||||
|
||||
const orgUsername =
|
||||
user.username || getOrgUsernameFromEmail(user.email, orgMetadata?.orgAutoAcceptEmail ?? null);
|
||||
|
||||
export async function joinAnyChildTeamOnOrgInvite({ userId, orgId }: { userId: number; orgId: number }) {
|
||||
await prisma.$transaction([
|
||||
// Simply remove this update when we remove the `organizationId` field from the user table
|
||||
prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
organizationId: orgId,
|
||||
organizationId: org.id,
|
||||
},
|
||||
}),
|
||||
prisma.profile.upsert({
|
||||
create: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: userId,
|
||||
organizationId: org.id,
|
||||
username: orgUsername,
|
||||
},
|
||||
update: {
|
||||
username: orgUsername,
|
||||
},
|
||||
where: {
|
||||
userId_organizationId: {
|
||||
userId: user.id,
|
||||
organizationId: org.id,
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.membership.updateMany({
|
||||
where: {
|
||||
userId,
|
||||
team: {
|
||||
id: orgId,
|
||||
id: org.id,
|
||||
},
|
||||
accepted: false,
|
||||
},
|
||||
@@ -44,7 +64,7 @@ export async function joinAnyChildTeamOnOrgInvite({ userId, orgId }: { userId: n
|
||||
where: {
|
||||
userId,
|
||||
team: {
|
||||
parentId: orgId,
|
||||
parentId: org.id,
|
||||
},
|
||||
accepted: false,
|
||||
},
|
||||
@@ -54,5 +74,5 @@ export async function joinAnyChildTeamOnOrgInvite({ userId, orgId }: { userId: n
|
||||
}),
|
||||
]);
|
||||
|
||||
await updateNewTeamMemberEventTypes(userId, orgId);
|
||||
await updateNewTeamMemberEventTypes(userId, org.id);
|
||||
}
|
||||
@@ -35,8 +35,8 @@ export const BookerSeo = (props: BookerSeoProps) => {
|
||||
{ refetchOnWindowFocus: false }
|
||||
);
|
||||
|
||||
const profileName = event?.profile?.name ?? "";
|
||||
const profileImage = event?.profile?.image;
|
||||
const profileName = event?.profile.name ?? "";
|
||||
const profileImage = event?.profile.image;
|
||||
const title = event?.title ?? "";
|
||||
return (
|
||||
<HeadSeo
|
||||
|
||||
@@ -40,7 +40,7 @@ import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/
|
||||
import { getCalEventResponses } from "@calcom/features/bookings/lib/getCalEventResponses";
|
||||
import { handleWebhookTrigger } from "@calcom/features/bookings/lib/handleWebhookTrigger";
|
||||
import { isEventTypeLoggingEnabled } from "@calcom/features/bookings/lib/isEventTypeLoggingEnabled";
|
||||
import { userOrgQuery } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import {
|
||||
allowDisablingAttendeeConfirmationEmails,
|
||||
allowDisablingHostConfirmationEmails,
|
||||
@@ -69,6 +69,7 @@ import { getPiiFreeCalendarEvent, getPiiFreeEventType, getPiiFreeUser } from "@c
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { checkBookingLimits, checkDurationLimits, getLuckyUser } from "@calcom/lib/server";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import { slugify } from "@calcom/lib/slugify";
|
||||
import { updateWebUser as syncServicesUpdateWebUser } from "@calcom/lib/sync/SyncServiceManager";
|
||||
import { getTimeFormatStringFromUserTimeFormat } from "@calcom/lib/timeFormat";
|
||||
@@ -185,7 +186,7 @@ export async function refreshCredentials(
|
||||
* Gets credentials from the user, team, and org if applicable
|
||||
*
|
||||
*/
|
||||
export const getAllCredentials = async (
|
||||
const getAllCredentials = async (
|
||||
user: User & { credentials: CredentialPayload[] },
|
||||
eventType: Awaited<ReturnType<typeof getEventTypesFromDB>>
|
||||
) => {
|
||||
@@ -223,11 +224,15 @@ export const getAllCredentials = async (
|
||||
}
|
||||
}
|
||||
|
||||
const { profile } = await UserRepository.enrichUserWithItsProfile({
|
||||
user: user,
|
||||
});
|
||||
|
||||
// If the user is a part of an organization, query for the organization's credentials
|
||||
if (user?.organizationId) {
|
||||
if (profile?.organizationId) {
|
||||
const org = await prisma.team.findUnique({
|
||||
where: {
|
||||
id: user.organizationId,
|
||||
id: profile.organizationId,
|
||||
},
|
||||
select: {
|
||||
credentials: {
|
||||
@@ -366,11 +371,6 @@ export const getEventTypesFromDB = async (eventTypeId: number) => {
|
||||
select: credentialForCalendarServiceSelect,
|
||||
},
|
||||
...userSelect.select,
|
||||
organization: {
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -409,18 +409,10 @@ const loadUsers = async (eventType: NewBookingEventType, dynamicUserList: string
|
||||
if (!Array.isArray(dynamicUserList) || dynamicUserList.length === 0) {
|
||||
throw new Error("dynamicUserList is not properly defined or empty.");
|
||||
}
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
username: { in: dynamicUserList },
|
||||
organization: userOrgQuery(req),
|
||||
},
|
||||
select: {
|
||||
...userSelect.select,
|
||||
credentials: {
|
||||
select: credentialForCalendarServiceSelect,
|
||||
},
|
||||
metadata: true,
|
||||
},
|
||||
const { isValidOrgDomain, currentOrgDomain } = orgDomainConfig(req);
|
||||
const users = await findUsersByUsername({
|
||||
usernameList: dynamicUserList,
|
||||
orgSlug: isValidOrgDomain ? currentOrgDomain : null,
|
||||
});
|
||||
|
||||
return users;
|
||||
@@ -1320,7 +1312,6 @@ async function handler(
|
||||
const [organizerUser] = users;
|
||||
|
||||
const tOrganizer = await getTranslation(organizerUser?.locale ?? "en", "common");
|
||||
|
||||
const allCredentials = await getAllCredentials(organizerUser, eventType);
|
||||
|
||||
const { userReschedulingIsOwner, isConfirmedByDefault } = getRequiresConfirmationFlags({
|
||||
@@ -1449,11 +1440,20 @@ async function handler(
|
||||
});
|
||||
// For bookings made before introducing iCalSequence, assume that the sequence should start at 1. For new bookings start at 0.
|
||||
const iCalSequence = getICalSequence(originalRescheduledBooking);
|
||||
const organizerOrganizationProfile = await prisma.profile.findFirst({
|
||||
where: {
|
||||
userId: organizerUser.id,
|
||||
username: dynamicUserList[0],
|
||||
},
|
||||
});
|
||||
|
||||
const organizerOrganizationId = organizerOrganizationProfile?.organizationId;
|
||||
const bookerUrl = eventType.team
|
||||
? await getBookerBaseUrl(eventType.team.parentId)
|
||||
: await getBookerBaseUrl(organizerOrganizationId ?? null);
|
||||
|
||||
let evt: CalendarEvent = {
|
||||
bookerUrl: eventType.team
|
||||
? await getBookerBaseUrl({ organizationId: eventType.team.parentId })
|
||||
: await getBookerBaseUrl(organizerUser),
|
||||
bookerUrl,
|
||||
type: eventType.slug,
|
||||
title: getEventName(eventNameObject), //this needs to be either forced in english, or fetched for each attendee and organizer separately
|
||||
description: eventType.description,
|
||||
@@ -2401,3 +2401,40 @@ function handleCustomInputs(
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is mostly same as the one in UserRepository but it includes a lot more relations which are specific requirement here
|
||||
* TODO: Figure out how to keep it in UserRepository and use it here
|
||||
*/
|
||||
export const findUsersByUsername = async ({
|
||||
usernameList,
|
||||
orgSlug,
|
||||
}: {
|
||||
orgSlug: string | null;
|
||||
usernameList: string[];
|
||||
}) => {
|
||||
log.debug("findUsersByUsername", { usernameList, orgSlug });
|
||||
const { where, profiles } = await UserRepository._getWhereClauseForFindingUsersByUsername({
|
||||
orgSlug,
|
||||
usernameList,
|
||||
});
|
||||
return (
|
||||
await prisma.user.findMany({
|
||||
where,
|
||||
select: {
|
||||
...userSelect.select,
|
||||
credentials: {
|
||||
select: credentialForCalendarServiceSelect,
|
||||
},
|
||||
metadata: true,
|
||||
},
|
||||
})
|
||||
).map((user) => {
|
||||
const profile = profiles?.find((profile) => profile.user.id === user.id) ?? null;
|
||||
return {
|
||||
...user,
|
||||
organizationId: profile?.organizationId ?? null,
|
||||
profile,
|
||||
};
|
||||
});
|
||||
};
|
||||
@@ -157,6 +157,7 @@ describe("handleNewBooking", () => {
|
||||
|
||||
const mockBookingData = getMockRequestDataForBooking({
|
||||
data: {
|
||||
user: organizer.username,
|
||||
eventTypeId: 1,
|
||||
responses: {
|
||||
email: booker.email,
|
||||
@@ -1991,6 +1992,7 @@ describe("handleNewBooking", () => {
|
||||
|
||||
const mockBookingData = getMockRequestDataForBooking({
|
||||
data: {
|
||||
user: organizer.username,
|
||||
eventTypeId: 1,
|
||||
responses: {
|
||||
email: booker.email,
|
||||
|
||||
@@ -4,15 +4,30 @@ import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import { z } from "zod";
|
||||
|
||||
import { getSession } from "@calcom/features/auth/lib/getSession";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Prisma } from "@calcom/prisma/client";
|
||||
import type { Membership } from "@calcom/prisma/client";
|
||||
import type { OrgProfile, PersonalProfile, UserAsPersonalProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
const teamIdschema = z.object({
|
||||
teamId: z.preprocess((a) => parseInt(z.string().parse(a), 10), z.number().positive()),
|
||||
});
|
||||
|
||||
type ProfileType =
|
||||
| UserAsPersonalProfile
|
||||
| PersonalProfile
|
||||
| (Omit<OrgProfile, "organization"> & {
|
||||
organization: OrgProfile["organization"] & {
|
||||
members: Membership[];
|
||||
};
|
||||
});
|
||||
|
||||
const auditAndReturnNextUser = async (
|
||||
impersonatedUser: Pick<User, "id" | "username" | "email" | "name" | "role" | "organizationId" | "locale">,
|
||||
impersonatedUser: Pick<User, "id" | "username" | "email" | "name" | "role" | "locale"> & {
|
||||
organizationId: number | null;
|
||||
profile: ProfileType;
|
||||
},
|
||||
impersonatedByUID: number,
|
||||
hasTeam?: boolean,
|
||||
isReturningToSelf?: boolean
|
||||
@@ -42,6 +57,7 @@ const auditAndReturnNextUser = async (
|
||||
belongsToActiveTeam: hasTeam,
|
||||
organizationId: impersonatedUser.organizationId,
|
||||
locale: impersonatedUser.locale,
|
||||
profile: impersonatedUser.profile,
|
||||
};
|
||||
|
||||
if (!isReturningToSelf) {
|
||||
@@ -136,7 +152,6 @@ async function getImpersonatedUser({
|
||||
role: true,
|
||||
name: true,
|
||||
email: true,
|
||||
organizationId: true,
|
||||
disableImpersonation: true,
|
||||
locale: true,
|
||||
teams: {
|
||||
@@ -154,7 +169,13 @@ async function getImpersonatedUser({
|
||||
throw new Error("This user does not exist");
|
||||
}
|
||||
|
||||
return impersonatedUser;
|
||||
const profile = await findProfile(impersonatedUser);
|
||||
|
||||
return {
|
||||
...impersonatedUser,
|
||||
organizationId: profile.organization?.id ?? null,
|
||||
profile,
|
||||
};
|
||||
}
|
||||
|
||||
async function isReturningToSelf({ session, creds }: { session: Session | null; creds: Credentials | null }) {
|
||||
@@ -195,6 +216,8 @@ async function isReturningToSelf({ session, creds }: { session: Session | null;
|
||||
if (returningUser.role !== "ADMIN" && !returningUser.organizationId) return;
|
||||
|
||||
const hasTeams = returningUser.teams.length >= 1;
|
||||
|
||||
const profile = await findProfile(returningUser);
|
||||
return {
|
||||
user: {
|
||||
id: returningUser.id,
|
||||
@@ -204,6 +227,7 @@ async function isReturningToSelf({ session, creds }: { session: Session | null;
|
||||
organizationId: returningUser.organizationId,
|
||||
role: returningUser.role,
|
||||
username: returningUser.username,
|
||||
profile,
|
||||
},
|
||||
impersonatedByUID,
|
||||
hasTeams,
|
||||
@@ -242,7 +266,6 @@ const ImpersonationProvider = CredentialsProvider({
|
||||
checkGlobalPermission(session);
|
||||
|
||||
const impersonatedUser = await getImpersonatedUser({ session, teamId, creds });
|
||||
|
||||
if (session?.user.role === "ADMIN") {
|
||||
if (impersonatedUser.disableImpersonation) {
|
||||
throw new Error("This user has disabled Impersonation.");
|
||||
@@ -302,3 +325,29 @@ const ImpersonationProvider = CredentialsProvider({
|
||||
});
|
||||
|
||||
export default ImpersonationProvider;
|
||||
async function findProfile(returningUser: { id: number; username: string | null }) {
|
||||
const allOrgProfiles = await ProfileRepository.findAllProfilesForUserIncludingMovedUser({
|
||||
id: returningUser.id,
|
||||
username: returningUser.username,
|
||||
});
|
||||
|
||||
const firstOrgProfile = allOrgProfiles[0];
|
||||
const orgMembers = firstOrgProfile.organizationId
|
||||
? await prisma.membership.findMany({
|
||||
where: {
|
||||
teamId: firstOrgProfile.organizationId,
|
||||
},
|
||||
})
|
||||
: [];
|
||||
|
||||
const profile = !firstOrgProfile.organization
|
||||
? firstOrgProfile
|
||||
: {
|
||||
...firstOrgProfile,
|
||||
organization: {
|
||||
...firstOrgProfile.organization,
|
||||
members: orgMembers,
|
||||
},
|
||||
};
|
||||
return profile;
|
||||
}
|
||||
@@ -19,6 +19,7 @@ const generateHashedLink = (id: number) => {
|
||||
|
||||
interface handleChildrenEventTypesProps {
|
||||
eventTypeId: number;
|
||||
profileId: number | null;
|
||||
updatedEventType: {
|
||||
schedulingType: SchedulingType | null;
|
||||
slug: string;
|
||||
@@ -101,6 +102,7 @@ export default async function handleChildrenEventTypes({
|
||||
connectedLink,
|
||||
children,
|
||||
prisma,
|
||||
profileId,
|
||||
}: handleChildrenEventTypesProps) {
|
||||
// Check we are dealing with a managed event type
|
||||
if (updatedEventType?.schedulingType !== SchedulingType.MANAGED)
|
||||
@@ -177,6 +179,7 @@ export default async function handleChildrenEventTypes({
|
||||
newUserIds.map((userId) => {
|
||||
return prisma.eventType.create({
|
||||
data: {
|
||||
profileId: profileId ?? null,
|
||||
...managedEventTypeValues,
|
||||
...unlockedEventTypeValues,
|
||||
bookingLimits:
|
||||
@@ -233,6 +236,7 @@ export default async function handleChildrenEventTypes({
|
||||
},
|
||||
data: {
|
||||
...managedEventTypeValues,
|
||||
profileId: profileId ?? null,
|
||||
hidden: children?.find((ch) => ch.owner.id === userId)?.hidden ?? false,
|
||||
bookingLimits:
|
||||
(managedEventTypeValues.bookingLimits as unknown as Prisma.InputJsonObject) ?? undefined,
|
||||
|
||||
@@ -35,7 +35,7 @@ export default function MemberListItem(props: Props) {
|
||||
<div className="my-4 flex justify-between">
|
||||
<div className="flex w-full flex-col justify-between overflow-hidden sm:flex-row">
|
||||
<div className="flex">
|
||||
<UserAvatar size="sm" user={user} className="h-10 w-10 rounded-full" />
|
||||
<UserAvatar noOrganizationIndicator size="sm" user={user} className="h-10 w-10 rounded-full" />
|
||||
|
||||
<div className="ms-3 inline-block overflow-hidden">
|
||||
<div className="mb-1 flex">
|
||||
|
||||
@@ -118,16 +118,7 @@ const MembersView = () => {
|
||||
router.push("/settings");
|
||||
}
|
||||
},
|
||||
[otherMembersError, otherTeamError]
|
||||
);
|
||||
|
||||
useEffect(
|
||||
function refactorMeWithoutEffect() {
|
||||
if (data) {
|
||||
router.push("/settings");
|
||||
}
|
||||
},
|
||||
[data]
|
||||
[router, otherMembersError, otherTeamError]
|
||||
);
|
||||
|
||||
const isPending = isTeamLoading || isOrgListLoading;
|
||||
|
||||
@@ -138,12 +138,18 @@ export default function MemberListItem(props: Props) {
|
||||
)
|
||||
) : null;
|
||||
});
|
||||
|
||||
return (
|
||||
<li className="divide-subtle divide-y px-5">
|
||||
<div className="my-4 flex justify-between">
|
||||
<div className="flex w-full flex-col justify-between truncate sm:flex-row">
|
||||
<div className="flex">
|
||||
<UserAvatar size="sm" user={props.member} className="h-10 w-10 rounded-full" />
|
||||
<UserAvatar
|
||||
noOrganizationIndicator
|
||||
size="sm"
|
||||
user={props.member}
|
||||
className="h-10 w-10 rounded-full"
|
||||
/>
|
||||
<div className="ms-3 inline-block">
|
||||
<div className="mb-1 flex" data-testid={`member-${props.member.username}`}>
|
||||
<span data-testid="member-name" className="text-default mr-2 text-sm font-bold leading-4">
|
||||
|
||||
@@ -6,6 +6,7 @@ import InviteLinkSettingsModal from "@calcom/ee/teams/components/InviteLinkSetti
|
||||
import MemberInvitationModal from "@calcom/ee/teams/components/MemberInvitationModal";
|
||||
import classNames from "@calcom/lib/classNames";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { isOrganization } from "@calcom/lib/entityPermissionUtils";
|
||||
import { getTeamUrlSync } from "@calcom/lib/getBookerUrl/client";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
@@ -42,7 +43,6 @@ import {
|
||||
X,
|
||||
} from "@calcom/ui/components/icon";
|
||||
|
||||
import { useOrgBranding } from "../../organizations/context/provider";
|
||||
import { TeamRole } from "./TeamPill";
|
||||
|
||||
interface Props {
|
||||
@@ -86,7 +86,6 @@ export default function TeamListItem(props: Props) {
|
||||
|
||||
const acceptInvite = () => acceptOrLeave(true);
|
||||
const declineInvite = () => acceptOrLeave(false);
|
||||
const orgBranding = useOrgBranding();
|
||||
|
||||
const isOwner = props.team.role === MembershipRole.OWNER;
|
||||
const isInvitee = !props.team.accepted;
|
||||
@@ -94,7 +93,9 @@ export default function TeamListItem(props: Props) {
|
||||
const { hideDropdown, setHideDropdown } = props;
|
||||
|
||||
if (!team) return <></>;
|
||||
|
||||
const teamUrl = isOrganization({ team })
|
||||
? getTeamUrlSync({ orgSlug: team.slug, teamSlug: null })
|
||||
: getTeamUrlSync({ orgSlug: team.parent ? team.parent.slug : null, teamSlug: team.slug });
|
||||
const teamInfo = (
|
||||
<div className="item-center flex px-5 py-5">
|
||||
<Avatar
|
||||
@@ -106,11 +107,7 @@ export default function TeamListItem(props: Props) {
|
||||
<div className="ms-3 inline-block truncate">
|
||||
<span className="text-default text-sm font-bold">{team.name}</span>
|
||||
<span className="text-muted block text-xs">
|
||||
{team.slug ? (
|
||||
`${getTeamUrlSync({ orgSlug: team.parent ? team.parent.slug : null, teamSlug: team.slug })}`
|
||||
) : (
|
||||
<Badge>{t("upgrade")}</Badge>
|
||||
)}
|
||||
{team.slug ? `${teamUrl}` : <Badge>{t("upgrade")}</Badge>}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { APP_NAME, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { isOrganization } from "@calcom/lib/entityPermissionUtils";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
@@ -21,9 +22,14 @@ export function TeamsListing() {
|
||||
|
||||
const [inviteTokenChecked, setInviteTokenChecked] = useState(false);
|
||||
|
||||
const { data, isPending, error } = trpc.viewer.teams.list.useQuery(undefined, {
|
||||
enabled: inviteTokenChecked,
|
||||
});
|
||||
const { data, isPending, error } = trpc.viewer.teams.list.useQuery(
|
||||
{
|
||||
includeOrgs: true,
|
||||
},
|
||||
{
|
||||
enabled: inviteTokenChecked,
|
||||
}
|
||||
);
|
||||
|
||||
const { data: user } = trpc.viewer.me.useQuery();
|
||||
|
||||
@@ -40,8 +46,22 @@ export function TeamsListing() {
|
||||
},
|
||||
});
|
||||
|
||||
const teams = useMemo(() => data?.filter((m) => m.accepted) || [], [data]);
|
||||
const invites = useMemo(() => data?.filter((m) => !m.accepted) || [], [data]);
|
||||
const teams = useMemo(() => data?.filter((m) => m.accepted && !isOrganization({ team: m })) || [], [data]);
|
||||
|
||||
const teamInvites = useMemo(
|
||||
() => data?.filter((m) => !m.accepted && !isOrganization({ team: m })) || [],
|
||||
[data]
|
||||
);
|
||||
|
||||
const organizationInvites = (data?.filter((m) => !m.accepted && isOrganization({ team: m })) || []).filter(
|
||||
(orgInvite) => {
|
||||
const isThereASubTeamOfTheOrganizationInInvites = teamInvites.find(
|
||||
(teamInvite) => teamInvite.parentId === orgInvite.id
|
||||
);
|
||||
// Accepting a subteam invite automatically accepts the invite for the parent organization. So, need to show such an organization's invite
|
||||
return !isThereASubTeamOfTheOrganizationInInvites;
|
||||
}
|
||||
);
|
||||
|
||||
const isCreateTeamButtonDisabled = !!(user?.organizationId && !user?.organization?.isOrgAdmin);
|
||||
|
||||
@@ -92,12 +112,20 @@ export function TeamsListing() {
|
||||
<>
|
||||
{!!error && <Alert severity="error" title={error.message} />}
|
||||
|
||||
{invites.length > 0 && (
|
||||
{organizationInvites.length > 0 && (
|
||||
<div className="bg-subtle mb-6 rounded-md p-5">
|
||||
<Label className="text-emphasis pb-2 font-semibold">{t("pending_invites")}</Label>
|
||||
<TeamList teams={invites} pending />
|
||||
<Label className="text-emphasis pb-2 font-semibold">{t("pending_organization_invites")}</Label>
|
||||
<TeamList teams={organizationInvites} pending />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{teamInvites.length > 0 && (
|
||||
<div className="bg-subtle mb-6 rounded-md p-5">
|
||||
<Label className="text-emphasis pb-2 font-semibold">{t("pending_invites")}</Label>
|
||||
<TeamList teams={teamInvites} pending />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<UpgradeTip
|
||||
plan="team"
|
||||
title={t("calcom_is_better_with_team", { appName: APP_NAME })}
|
||||
|
||||
@@ -58,9 +58,10 @@ const getUserAdminTeams = async ({
|
||||
},
|
||||
}),
|
||||
},
|
||||
orderBy: {
|
||||
orgUsers: { _count: "desc" },
|
||||
},
|
||||
// FIXME - OrgNewSchema: Fix this orderBy
|
||||
// orderBy: {
|
||||
// orgUsers: { _count: "desc" },
|
||||
// },
|
||||
});
|
||||
|
||||
if (teams.length && getUserInfo) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { getStripeCustomerIdFromUserId } from "@calcom/app-store/stripepayment/l
|
||||
import stripe from "@calcom/app-store/stripepayment/lib/server";
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { ORGANIZATION_MIN_SEATS } from "@calcom/lib/constants";
|
||||
import { isOrganization } from "@calcom/lib/entityPermissionUtils";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
@@ -120,8 +121,9 @@ export const purchaseTeamSubscription = async (input: {
|
||||
const getTeamWithPaymentMetadata = async (teamId: number) => {
|
||||
const team = await prisma.team.findUniqueOrThrow({
|
||||
where: { id: teamId },
|
||||
select: { metadata: true, members: true, _count: { select: { orgUsers: true } } },
|
||||
select: { metadata: true, members: true },
|
||||
});
|
||||
|
||||
const metadata = teamPaymentMetadataSchema.parse(team.metadata);
|
||||
return { ...team, metadata };
|
||||
};
|
||||
@@ -155,7 +157,7 @@ export const updateQuantitySubscriptionFromStripe = async (teamId: number) => {
|
||||
)?.quantity;
|
||||
if (!subscriptionQuantity) throw new Error("Subscription not found");
|
||||
|
||||
if (!!team._count.orgUsers && membershipCount < ORGANIZATION_MIN_SEATS) {
|
||||
if (!!isOrganization({ team }) && membershipCount < ORGANIZATION_MIN_SEATS) {
|
||||
console.info(
|
||||
`Org ${teamId} has less members than the min ${ORGANIZATION_MIN_SEATS}, skipping updating subscription.`
|
||||
);
|
||||
|
||||
@@ -176,6 +176,7 @@ function UsersTableBare() {
|
||||
<Avatar
|
||||
size="md"
|
||||
alt={`Avatar of ${user.username || "Nameless"}`}
|
||||
// @ts-expect-error - Figure it out later. Ideally we should show all the profiles here for the user.
|
||||
imageSrc={`${WEBAPP_URL}/${user.username}/avatar.png?orgId=${user.organizationId}`}
|
||||
/>
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { User } from "@prisma/client";
|
||||
import type { User as UserType } from "@prisma/client";
|
||||
import { Prisma } from "@prisma/client";
|
||||
|
||||
import type { LocationObject } from "@calcom/app-store/locations";
|
||||
@@ -10,6 +10,7 @@ import { isRecurringEvent, parseRecurringEvent } from "@calcom/lib";
|
||||
import { getDefaultEvent, getUsernameList } from "@calcom/lib/defaultEvents";
|
||||
import { getBookerBaseUrlSync } from "@calcom/lib/getBookerUrl/client";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import type { BookerLayoutSettings } from "@calcom/prisma/zod-utils";
|
||||
import {
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
BookerLayouts,
|
||||
teamMetadataSchema,
|
||||
} from "@calcom/prisma/zod-utils";
|
||||
import type { UserProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
const publicEventSelect = Prisma.validator<Prisma.EventTypeSelect>()({
|
||||
id: true,
|
||||
@@ -76,18 +78,14 @@ const publicEventSelect = Prisma.validator<Prisma.EventTypeSelect>()({
|
||||
select: {
|
||||
user: {
|
||||
select: {
|
||||
id: true,
|
||||
avatarUrl: true,
|
||||
username: true,
|
||||
name: true,
|
||||
weekStart: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
theme: true,
|
||||
organizationId: true,
|
||||
organization: {
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
metadata: true,
|
||||
},
|
||||
},
|
||||
@@ -95,6 +93,8 @@ const publicEventSelect = Prisma.validator<Prisma.EventTypeSelect>()({
|
||||
},
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
avatarUrl: true,
|
||||
weekStart: true,
|
||||
username: true,
|
||||
name: true,
|
||||
@@ -102,13 +102,6 @@ const publicEventSelect = Prisma.validator<Prisma.EventTypeSelect>()({
|
||||
metadata: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
organizationId: true,
|
||||
organization: {
|
||||
select: {
|
||||
name: true,
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
hidden: true,
|
||||
@@ -126,30 +119,12 @@ export const getPublicEvent = async (
|
||||
const orgQuery = org ? getSlugOrRequestedSlug(org) : null;
|
||||
// In case of dynamic group event, we fetch user's data and use the default event.
|
||||
if (usernameList.length > 1) {
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
username: {
|
||||
in: usernameList,
|
||||
},
|
||||
organization: orgQuery,
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
name: true,
|
||||
weekStart: true,
|
||||
metadata: true,
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
theme: true,
|
||||
organizationId: true,
|
||||
organization: {
|
||||
select: {
|
||||
slug: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
const usersInOrgContext = await UserRepository.findUsersByUsername({
|
||||
usernameList,
|
||||
orgSlug: org,
|
||||
});
|
||||
console.log("getPublicEvent - dynamic", usersInOrgContext);
|
||||
const users = usersInOrgContext;
|
||||
|
||||
const defaultEvent = getDefaultEvent(eventSlug);
|
||||
let locations = defaultEvent.locations ? (defaultEvent.locations as LocationObject[]) : [];
|
||||
@@ -173,7 +148,7 @@ export const getPublicEvent = async (
|
||||
defaultLayout: BookerLayouts.MONTH_VIEW,
|
||||
} as BookerLayoutSettings;
|
||||
const disableBookingTitle = !defaultEvent.isDynamic;
|
||||
const unPublishedOrgUser = users.find((user) => user.organization?.slug === null);
|
||||
const unPublishedOrgUser = users.find((user) => user.profile?.organization?.slug === null);
|
||||
|
||||
return {
|
||||
...defaultEvent,
|
||||
@@ -182,7 +157,7 @@ export const getPublicEvent = async (
|
||||
users: users.map((user) => ({
|
||||
...user,
|
||||
metadata: undefined,
|
||||
bookerUrl: getBookerBaseUrlSync(user.organization?.slug ?? null),
|
||||
bookerUrl: getBookerBaseUrlSync(user.profile?.organization?.slug ?? null),
|
||||
})),
|
||||
locations: privacyFilteredLocations(locations),
|
||||
profile: {
|
||||
@@ -200,7 +175,7 @@ export const getPublicEvent = async (
|
||||
entity: {
|
||||
isUnpublished: unPublishedOrgUser !== undefined,
|
||||
orgSlug: org,
|
||||
name: unPublishedOrgUser?.organization?.name ?? null,
|
||||
name: unPublishedOrgUser?.profile?.organization?.name ?? null,
|
||||
},
|
||||
isInstantEvent: false,
|
||||
};
|
||||
@@ -216,8 +191,17 @@ export const getPublicEvent = async (
|
||||
: {
|
||||
users: {
|
||||
some: {
|
||||
username,
|
||||
organization: orgQuery,
|
||||
...(orgQuery
|
||||
? {
|
||||
profiles: {
|
||||
some: {
|
||||
organization: orgQuery,
|
||||
},
|
||||
},
|
||||
}
|
||||
: {
|
||||
username,
|
||||
}),
|
||||
},
|
||||
},
|
||||
team: null,
|
||||
@@ -236,35 +220,61 @@ export const getPublicEvent = async (
|
||||
|
||||
const eventMetaData = EventTypeMetaDataSchema.parse(event.metadata || {});
|
||||
const teamMetadata = teamMetadataSchema.parse(event.team?.metadata || {});
|
||||
const hosts = [];
|
||||
for (const host of event.hosts) {
|
||||
hosts.push({
|
||||
...host,
|
||||
user: await UserRepository.enrichUserWithItsProfile({
|
||||
user: host.user,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const eventWithUserProfiles = {
|
||||
...event,
|
||||
owner: event.owner
|
||||
? await UserRepository.enrichUserWithItsProfile({
|
||||
user: event.owner,
|
||||
})
|
||||
: null,
|
||||
hosts: hosts,
|
||||
};
|
||||
|
||||
const users = getUsersFromEvent(eventWithUserProfiles) || (await getOwnerFromUsersArray(prisma, event.id));
|
||||
|
||||
const users = getUsersFromEvent(event) || (await getOwnerFromUsersArray(prisma, event.id));
|
||||
if (users === null) {
|
||||
throw new Error("Event has no owner");
|
||||
}
|
||||
|
||||
return {
|
||||
...event,
|
||||
...eventWithUserProfiles,
|
||||
bookerLayouts: bookerLayoutsSchema.parse(eventMetaData?.bookerLayouts || null),
|
||||
description: markdownToSafeHTML(event.description),
|
||||
description: markdownToSafeHTML(eventWithUserProfiles.description),
|
||||
metadata: eventMetaData,
|
||||
customInputs: customInputSchema.array().parse(event.customInputs || []),
|
||||
locations: privacyFilteredLocations((event.locations || []) as LocationObject[]),
|
||||
locations: privacyFilteredLocations((eventWithUserProfiles.locations || []) as LocationObject[]),
|
||||
bookingFields: getBookingFieldsWithSystemFields(event),
|
||||
recurringEvent: isRecurringEvent(event.recurringEvent) ? parseRecurringEvent(event.recurringEvent) : null,
|
||||
recurringEvent: isRecurringEvent(eventWithUserProfiles.recurringEvent)
|
||||
? parseRecurringEvent(event.recurringEvent)
|
||||
: null,
|
||||
// Sets user data on profile object for easier access
|
||||
profile: getProfileFromEvent(event),
|
||||
profile: getProfileFromEvent(eventWithUserProfiles),
|
||||
users,
|
||||
entity: {
|
||||
isUnpublished:
|
||||
event.team?.slug === null ||
|
||||
event.owner?.organization?.slug === null ||
|
||||
event.team?.parent?.slug === null,
|
||||
eventWithUserProfiles.team?.slug === null ||
|
||||
eventWithUserProfiles.owner?.profile?.organization?.slug === null ||
|
||||
eventWithUserProfiles.team?.parent?.slug === null,
|
||||
orgSlug: org,
|
||||
teamSlug: (event.team?.slug || teamMetadata?.requestedSlug) ?? null,
|
||||
name: (event.owner?.organization?.name || event.team?.parent?.name || event.team?.name) ?? null,
|
||||
teamSlug: (eventWithUserProfiles.team?.slug || teamMetadata?.requestedSlug) ?? null,
|
||||
name:
|
||||
(eventWithUserProfiles.owner?.profile?.organization?.name ||
|
||||
eventWithUserProfiles.team?.parent?.name ||
|
||||
eventWithUserProfiles.team?.name) ??
|
||||
null,
|
||||
},
|
||||
isDynamic: false,
|
||||
isInstantEvent: event.isInstantEvent,
|
||||
isInstantEvent: eventWithUserProfiles.isInstantEvent,
|
||||
assignAllTeamMembers: event.assignAllTeamMembers,
|
||||
};
|
||||
};
|
||||
@@ -301,8 +311,20 @@ function getProfileFromEvent(event: Event) {
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function getUsersFromEvent(event: Event) {
|
||||
function getUsersFromEvent(
|
||||
event: Omit<Event, "owner" | "hosts"> & {
|
||||
owner:
|
||||
| (Event["owner"] & {
|
||||
profile: UserProfile;
|
||||
})
|
||||
| null;
|
||||
hosts: (Omit<Event["hosts"][number], "user"> & {
|
||||
user: Event["hosts"][number]["user"] & {
|
||||
profile: UserProfile;
|
||||
};
|
||||
})[];
|
||||
}
|
||||
) {
|
||||
const { team, hosts, owner } = event;
|
||||
if (team) {
|
||||
return (hosts || []).filter((host) => host.user.username).map(mapHostsToUsers);
|
||||
@@ -310,14 +332,17 @@ function getUsersFromEvent(event: Event) {
|
||||
if (!owner) {
|
||||
return null;
|
||||
}
|
||||
const { username, name, weekStart, organizationId } = owner;
|
||||
const { username, name, weekStart, profile, avatarUrl } = owner;
|
||||
const organizationId = profile?.organization?.id ?? null;
|
||||
return [
|
||||
{
|
||||
username,
|
||||
name,
|
||||
weekStart,
|
||||
organizationId,
|
||||
bookerUrl: getBookerBaseUrlSync(owner.organization?.slug ?? null),
|
||||
avatarUrl,
|
||||
profile,
|
||||
bookerUrl: getBookerBaseUrlSync(owner.profile?.organization?.slug ?? null),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -328,33 +353,48 @@ async function getOwnerFromUsersArray(prisma: PrismaClient, eventTypeId: number)
|
||||
select: {
|
||||
users: {
|
||||
select: {
|
||||
avatarUrl: true,
|
||||
username: true,
|
||||
name: true,
|
||||
weekStart: true,
|
||||
organizationId: true,
|
||||
organization: {
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!users.length) return null;
|
||||
return [{ ...users[0], bookerUrl: getBookerBaseUrlSync(users[0].organization?.slug ?? null) }];
|
||||
const usersWithUserProfile = [];
|
||||
for (const user of users) {
|
||||
const { profile } = await UserRepository.enrichUserWithItsProfile({
|
||||
user: user,
|
||||
});
|
||||
usersWithUserProfile.push({
|
||||
...user,
|
||||
organizationId: profile?.organization?.id ?? null,
|
||||
organization: profile?.organization,
|
||||
profile,
|
||||
});
|
||||
}
|
||||
return [
|
||||
{
|
||||
...usersWithUserProfile[0],
|
||||
bookerUrl: getBookerBaseUrlSync(usersWithUserProfile[0].organization?.slug ?? null),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function mapHostsToUsers(host: {
|
||||
user: Pick<User, "username" | "name" | "weekStart" | "organizationId"> & {
|
||||
organization: { slug: string | null } | null;
|
||||
user: Pick<UserType, "username" | "name" | "weekStart" | "avatarUrl"> & {
|
||||
profile: UserProfile;
|
||||
};
|
||||
}) {
|
||||
return {
|
||||
username: host.user.username,
|
||||
name: host.user.name,
|
||||
avatarUrl: host.user.avatarUrl,
|
||||
weekStart: host.user.weekStart,
|
||||
organizationId: host.user.organizationId,
|
||||
bookerUrl: getBookerBaseUrlSync(host.user.organization?.slug ?? null),
|
||||
organizationId: host.user.profile?.organizationId ?? null,
|
||||
bookerUrl: getBookerBaseUrlSync(host.user.profile?.organization?.slug ?? null),
|
||||
profile: host.user.profile,
|
||||
};
|
||||
}
|
||||
@@ -24,10 +24,12 @@ function useFilterQuery() {
|
||||
|
||||
export const TeamsFilter = ({
|
||||
popoverTriggerClassNames,
|
||||
useProfileFilter = false,
|
||||
showVerticalDivider = false,
|
||||
}: {
|
||||
popoverTriggerClassNames?: string;
|
||||
showVerticalDivider?: boolean;
|
||||
useProfileFilter?: boolean;
|
||||
}) => {
|
||||
const { t } = useLocale();
|
||||
const session = useSession();
|
||||
@@ -39,6 +41,7 @@ export const TeamsFilter = ({
|
||||
const getCheckedOptionsNames = () => {
|
||||
const checkedOptions: string[] = [];
|
||||
const teamIds = query.teamIds;
|
||||
const users = useProfileFilter ? query.upIds : query.userIds;
|
||||
if (teamIds) {
|
||||
const selectedTeamsNames = teams
|
||||
?.filter((team) => {
|
||||
@@ -50,7 +53,7 @@ export const TeamsFilter = ({
|
||||
}
|
||||
return `${t("team")}: ${checkedOptions.join(",")}`;
|
||||
}
|
||||
if (query.userIds) {
|
||||
if (users) {
|
||||
return t("yours");
|
||||
}
|
||||
return t("all");
|
||||
@@ -58,6 +61,9 @@ export const TeamsFilter = ({
|
||||
|
||||
if (!teams || !teams.length) return null;
|
||||
|
||||
const userId = session.data?.user?.id || 0;
|
||||
const upId = session.data?.upId || "";
|
||||
const isUserInQuery = useProfileFilter ? query.upIds?.includes(upId) : query.userIds?.includes(userId);
|
||||
return (
|
||||
<div className="flex items-center">
|
||||
<AnimatedPopover
|
||||
@@ -68,7 +74,7 @@ export const TeamsFilter = ({
|
||||
<FilterCheckboxField
|
||||
id="all"
|
||||
icon={<Layers className="h-4 w-4" />}
|
||||
checked={!query.teamIds && !query.userIds?.includes(session.data?.user.id || 0)}
|
||||
checked={!query.teamIds && !isUserInQuery}
|
||||
onChange={removeAllQueryParams}
|
||||
label={t("all")}
|
||||
/>
|
||||
@@ -76,12 +82,14 @@ export const TeamsFilter = ({
|
||||
<FilterCheckboxField
|
||||
id="yours"
|
||||
icon={<User className="h-4 w-4" />}
|
||||
checked={!!query.userIds?.includes(session.data?.user.id || 0)}
|
||||
checked={!!isUserInQuery}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
pushItemToKey("userIds", session.data?.user.id || 0);
|
||||
if (useProfileFilter) pushItemToKey("upIds", upId);
|
||||
else pushItemToKey("userIds", userId);
|
||||
} else if (!e.target.checked) {
|
||||
removeItemByKeyAndValue("userIds", session.data?.user.id || 0);
|
||||
if (useProfileFilter) removeItemByKeyAndValue("upIds", upId);
|
||||
else removeItemByKeyAndValue("userIds", userId);
|
||||
}
|
||||
}}
|
||||
label={t("yours")}
|
||||
|
||||
@@ -7,6 +7,15 @@ export type IEventTypesFilters = RouterOutputs["viewer"]["eventTypes"]["listWith
|
||||
export type IEventTypeFilter = IEventTypesFilters[0];
|
||||
|
||||
// Take array as a string and return zod array
|
||||
const queryStringArray = z
|
||||
.string()
|
||||
.or(z.array(z.string()))
|
||||
.transform((a) => {
|
||||
if (typeof a === "string") return a.split(",");
|
||||
if (Array.isArray(a)) return a;
|
||||
return [a];
|
||||
});
|
||||
|
||||
const queryNumberArray = z
|
||||
.string()
|
||||
.or(z.number())
|
||||
@@ -21,11 +30,13 @@ const queryNumberArray = z
|
||||
export const filterQuerySchema = z.object({
|
||||
teamIds: queryNumberArray.optional(),
|
||||
userIds: queryNumberArray.optional(),
|
||||
upIds: queryStringArray.optional(),
|
||||
});
|
||||
|
||||
export const filterQuerySchemaStrict = z.object({
|
||||
teamIds: z.number().array().optional(),
|
||||
userIds: z.number().array().optional(),
|
||||
upIds: z.string().array().optional(),
|
||||
});
|
||||
|
||||
export const getTeamsFiltersFromQuery = (query: ParsedUrlQuery) => {
|
||||
@@ -33,9 +44,12 @@ export const getTeamsFiltersFromQuery = (query: ParsedUrlQuery) => {
|
||||
// Ensure that filters are sorted so that react-query caching can work better
|
||||
// [1,2] is equivalent to [2,1] when fetching filter data.
|
||||
filters.teamIds = filters.teamIds?.sort();
|
||||
filters.upIds = filters.upIds?.sort();
|
||||
filters.userIds = filters.userIds?.sort();
|
||||
|
||||
if (!filters.teamIds?.length && !filters.userIds?.length) {
|
||||
const isUserIdFilterPresent = filters.userIds?.length;
|
||||
const isUpIdFilterPresent = filters.upIds?.length;
|
||||
if (!filters.teamIds?.length && !isUserIdFilterPresent && !isUpIdFilterPresent) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
WEBAPP_URL,
|
||||
IS_VISUAL_REGRESSION_TESTING,
|
||||
TOP_BANNER_HEIGHT,
|
||||
ENABLE_PROFILE_SWITCHER,
|
||||
} from "@calcom/lib/constants";
|
||||
import getBrandColours from "@calcom/lib/getBrandColours";
|
||||
import { useBookerUrl } from "@calcom/lib/hooks/useBookerUrl";
|
||||
@@ -94,6 +95,7 @@ import {
|
||||
User as UserIcon,
|
||||
Users,
|
||||
Zap,
|
||||
Check,
|
||||
} from "@calcom/ui/components/icon";
|
||||
import { Discord } from "@calcom/ui/components/icon/Discord";
|
||||
|
||||
@@ -118,7 +120,9 @@ export const ONBOARDING_NEXT_REDIRECT = {
|
||||
} as const;
|
||||
|
||||
export const shouldShowOnboarding = (
|
||||
user: Pick<User, "createdDate" | "completedOnboarding" | "organizationId">
|
||||
user: Pick<User, "createdDate" | "completedOnboarding"> & {
|
||||
organizationId: number | null;
|
||||
}
|
||||
) => {
|
||||
return (
|
||||
!user.completedOnboarding &&
|
||||
@@ -440,7 +444,7 @@ function UserDropdown({ small }: UserDropdownProps) {
|
||||
)}>
|
||||
<Avatar
|
||||
size={small ? "xs" : "xsm"}
|
||||
imageSrc={`${bookerUrl}/${user.username}/avatar.png`}
|
||||
imageSrc={`${user.avatarUrl || user.avatar}`}
|
||||
alt={user.username || "Nameless User"}
|
||||
className="overflow-hidden"
|
||||
/>
|
||||
@@ -900,18 +904,22 @@ function SideBar({ bannersHeight, user }: SideBarProps) {
|
||||
<div className="flex h-full flex-col justify-between py-3 lg:pt-4">
|
||||
<header className="todesktop:-mt-3 todesktop:flex-col-reverse todesktop:[-webkit-app-region:drag] items-center justify-between md:hidden lg:flex">
|
||||
{orgBranding ? (
|
||||
<Link href="/settings/organizations/profile" className="w-full px-1.5">
|
||||
<div className="flex items-center gap-2 font-medium">
|
||||
<Avatar
|
||||
alt={`${orgBranding.name} logo`}
|
||||
imageSrc={`${orgBranding.fullDomain}/org/${orgBranding.slug}/avatar.png`}
|
||||
size="xsm"
|
||||
/>
|
||||
<p className="text line-clamp-1 text-sm">
|
||||
<span>{orgBranding.name}</span>
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
!ENABLE_PROFILE_SWITCHER ? (
|
||||
<Link href="/settings/organizations/profile" className="w-full px-1.5">
|
||||
<div className="flex items-center gap-2 font-medium">
|
||||
<Avatar
|
||||
alt={`${orgBranding.name} logo`}
|
||||
imageSrc={`${orgBranding.fullDomain}/org/${orgBranding.slug}/avatar.png`}
|
||||
size="xsm"
|
||||
/>
|
||||
<p className="text line-clamp-1 text-sm">
|
||||
<span>{orgBranding.name}</span>
|
||||
</p>
|
||||
</div>
|
||||
</Link>
|
||||
) : (
|
||||
<ProfileDropdown />
|
||||
)
|
||||
) : (
|
||||
<div data-testid="user-dropdown-trigger" className="todesktop:mt-4 w-full">
|
||||
<span className="hidden lg:inline">
|
||||
@@ -922,7 +930,7 @@ function SideBar({ bannersHeight, user }: SideBarProps) {
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex w-full justify-end space-x-2 rtl:space-x-reverse">
|
||||
<div className="flex justify-end rtl:space-x-reverse">
|
||||
<button
|
||||
color="minimal"
|
||||
onClick={() => window.history.back()}
|
||||
@@ -1129,3 +1137,93 @@ export const MobileNavigationMoreItems = () => (
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
|
||||
function ProfileDropdown() {
|
||||
const { update, data: sessionData } = useSession();
|
||||
const { data } = trpc.viewer.me.useQuery();
|
||||
const [menuOpen, setMenuOpen] = useState(false);
|
||||
|
||||
if (!data || !ENABLE_PROFILE_SWITCHER || !sessionData) {
|
||||
return null;
|
||||
}
|
||||
const options = data.profiles.map((profile) => {
|
||||
let label;
|
||||
if (profile.organization) {
|
||||
label = profile.organization.name;
|
||||
} else {
|
||||
label = sessionData.user.name;
|
||||
}
|
||||
|
||||
return {
|
||||
label,
|
||||
value: profile.upId,
|
||||
};
|
||||
});
|
||||
|
||||
const currentOption = options.find((option) => option.value === sessionData.upId) || options[0];
|
||||
|
||||
return (
|
||||
<Dropdown open={menuOpen}>
|
||||
<DropdownMenuTrigger asChild onClick={() => setMenuOpen((menuOpen) => !menuOpen)}>
|
||||
<button
|
||||
data-testid="user-dropdown-trigger-button"
|
||||
className={classNames(
|
||||
"hover:bg-emphasis todesktop:!bg-transparent group mx-0 flex w-full cursor-pointer appearance-none items-center rounded-full px-2 py-1.5 text-left outline-none transition focus:outline-none focus:ring-0 md:rounded-none lg:rounded"
|
||||
)}>
|
||||
<span className="flex w-full flex-grow items-center justify-around gap-2 text-sm font-medium leading-none">
|
||||
<Avatar alt={currentOption.label || ""} size="xsm" />
|
||||
<span className="block w-20 overflow-hidden overflow-ellipsis whitespace-nowrap">
|
||||
{currentOption.label}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className="group-hover:text-subtle text-muted h-4 w-4 flex-shrink-0 rtl:mr-4"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
onInteractOutside={() => {
|
||||
setMenuOpen(false);
|
||||
}}
|
||||
className="min-w-56 hariom group overflow-hidden rounded-md">
|
||||
<DropdownMenuItem className="p-3 uppercase">
|
||||
<span>Switch to</span>
|
||||
</DropdownMenuItem>
|
||||
{options.map((option) => {
|
||||
const isSelected = currentOption.value === option.value;
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={option.value}
|
||||
onClick={() => {
|
||||
setMenuOpen(false);
|
||||
if (isSelected) return;
|
||||
update({
|
||||
upId: option.value,
|
||||
}).then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
}}
|
||||
className={classNames("flex w-full", isSelected ? "bg-subtle text-emphasis" : "")}>
|
||||
<DropdownItem
|
||||
type="button"
|
||||
childrenClassName={classNames("flex w-full justify-between items-center")}>
|
||||
<span>
|
||||
<Avatar alt={option.label || ""} size="xsm" />
|
||||
<span className="ml-2">{option.label}</span>
|
||||
</span>
|
||||
{isSelected ? <Check className="ml-2 inline h-4 w-4" aria-hidden="true" /> : null}
|
||||
</DropdownItem>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* <DropdownMenuSeparator /> */}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</Dropdown>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type { DateRange } from "@calcom/lib/date-ranges";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import type { MembershipRole } from "@calcom/prisma/enums";
|
||||
import { trpc } from "@calcom/trpc";
|
||||
import type { UserProfile } from "@calcom/types/UserProfile";
|
||||
import { Button, ButtonGroup, DataTable } from "@calcom/ui";
|
||||
import { UserAvatar } from "@calcom/ui";
|
||||
|
||||
@@ -22,11 +23,13 @@ export interface SliderUser {
|
||||
username: string | null;
|
||||
name: string | null;
|
||||
organizationId: number;
|
||||
avatarUrl: string | null;
|
||||
email: string;
|
||||
timeZone: string;
|
||||
role: MembershipRole;
|
||||
defaultScheduleId: number | null;
|
||||
dateRanges: DateRange[];
|
||||
profile: UserProfile;
|
||||
}
|
||||
|
||||
function UpgradeTeamTip() {
|
||||
@@ -57,7 +60,6 @@ function UpgradeTeamTip() {
|
||||
}
|
||||
|
||||
export function AvailabilitySliderTable() {
|
||||
const { t } = useLocale();
|
||||
const tableContainerRef = useRef<HTMLDivElement>(null);
|
||||
const [browsingDate, setBrowsingDate] = useState(dayjs());
|
||||
const [editSheetOpen, setEditSheetOpen] = useState(false);
|
||||
@@ -83,7 +85,7 @@ export function AvailabilitySliderTable() {
|
||||
accessorFn: (data) => data.email,
|
||||
header: "Member",
|
||||
cell: ({ row }) => {
|
||||
const { username, email, timeZone, name, organizationId } = row.original;
|
||||
const { username, email, timeZone, name, avatarUrl, profile } = row.original;
|
||||
return (
|
||||
<div className="max-w-64 flex flex-shrink-0 items-center gap-2 overflow-hidden">
|
||||
<UserAvatar
|
||||
@@ -91,7 +93,8 @@ export function AvailabilitySliderTable() {
|
||||
user={{
|
||||
username,
|
||||
name,
|
||||
organizationId,
|
||||
avatarUrl,
|
||||
profile,
|
||||
}}
|
||||
/>
|
||||
<div className="">
|
||||
|
||||
@@ -117,7 +117,7 @@ export const Meeting = ({ title, users = [], profile }: MeetingImageProps) => {
|
||||
// Users ALWAYS have an image (albeit a gray empty person avatar), so this mainly filters out
|
||||
// any non existing images for dynamic collectives, while at the same time removing them from
|
||||
// the names list, because the profile name of that event is a concatenation of all names.
|
||||
const attendees = (profile?.image ? [profile, ...users] : users).filter(
|
||||
const attendees = (profile.image ? [profile, ...users] : users).filter(
|
||||
(value, index, self) => self.findIndex((v) => v.name === value.name) == index
|
||||
);
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ export const IS_STRIPE_ENABLED = !!(
|
||||
export const IS_TEAM_BILLING_ENABLED = IS_STRIPE_ENABLED && HOSTED_CAL_FEATURES;
|
||||
export const FULL_NAME_LENGTH_MAX_LIMIT = 50;
|
||||
export const MINUTES_TO_BOOK = process.env.NEXT_PUBLIC_MINUTES_TO_BOOK || "5";
|
||||
|
||||
export const ENABLE_PROFILE_SWITCHER = process.env.NEXT_PUBLIC_ENABLE_PROFILE_SWITCHER === "1";
|
||||
// Needed for orgs
|
||||
export const ALLOWED_HOSTNAMES = JSON.parse(`[${process.env.ALLOWED_HOSTNAMES || ""}]`) as string[];
|
||||
export const RESERVED_SUBDOMAINS = JSON.parse(`[${process.env.RESERVED_SUBDOMAINS || ""}]`) as string[];
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { getOrgFullOrigin } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { TeamRepository } from "@calcom/lib/server/repository/team";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { RedirectType } from "@calcom/prisma/enums";
|
||||
|
||||
import { getOrgUsernameFromEmail } from "../features/auth/signup/utils/getOrgUsernameFromEmail";
|
||||
import logger from "./logger";
|
||||
import { safeStringify } from "./safeStringify";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["lib", "createAProfileForAnExistingUser"] });
|
||||
export const createAProfileForAnExistingUser = async ({
|
||||
user,
|
||||
organizationId,
|
||||
}: {
|
||||
user: {
|
||||
email: string;
|
||||
id: number;
|
||||
username: string | null;
|
||||
};
|
||||
organizationId: number;
|
||||
}) => {
|
||||
const org = await TeamRepository.findById({ id: organizationId });
|
||||
if (!org) {
|
||||
throw new Error(`Organization with id ${organizationId} not found`);
|
||||
}
|
||||
const usernameInOrg = getOrgUsernameFromEmail(user.email, org.metadata.orgAutoAcceptEmail ?? null);
|
||||
const profile = await ProfileRepository.createForExistingUser({
|
||||
userId: user.id,
|
||||
organizationId,
|
||||
username: usernameInOrg,
|
||||
email: user.email,
|
||||
movedFromUserId: user.id,
|
||||
});
|
||||
|
||||
await UserRepository.updateWhereId({
|
||||
whereId: user.id,
|
||||
data: {
|
||||
movedToProfileId: profile.id,
|
||||
},
|
||||
});
|
||||
|
||||
log.debug(
|
||||
"Created profile for user",
|
||||
safeStringify({ userId: user.id, profileId: profile.id, usernameInOrg, username: user.username })
|
||||
);
|
||||
|
||||
const orgSlug = org.slug || org.requestedSlug;
|
||||
|
||||
if (!orgSlug) {
|
||||
throw new Error(`Organization with id ${organizationId} doesn't have a slug`);
|
||||
}
|
||||
|
||||
const orgUrl = getOrgFullOrigin(orgSlug);
|
||||
|
||||
if (user.username) {
|
||||
log.debug(`Creating redirect for user ${user.username} to ${orgUrl}/${usernameInOrg}`);
|
||||
await prisma.tempOrgRedirect.upsert({
|
||||
where: {
|
||||
from_type_fromOrgId: {
|
||||
from: user.username,
|
||||
type: RedirectType.User,
|
||||
fromOrgId: 0,
|
||||
},
|
||||
},
|
||||
update: {
|
||||
type: RedirectType.User,
|
||||
from: user.username,
|
||||
fromOrgId: 0,
|
||||
toUrl: `${orgUrl}/${usernameInOrg}`,
|
||||
},
|
||||
create: {
|
||||
type: RedirectType.User,
|
||||
from: user.username,
|
||||
fromOrgId: 0,
|
||||
toUrl: `${orgUrl}/${usernameInOrg}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
return profile;
|
||||
};
|
||||
@@ -49,7 +49,6 @@ const user: User & { credentials: CredentialPayload[] } = {
|
||||
darkBrandColor: "#efefef",
|
||||
allowDynamicBooking: true,
|
||||
timeFormat: 12,
|
||||
organizationId: null,
|
||||
};
|
||||
|
||||
const customInputs: CustomInputSchema[] = [];
|
||||
|
||||
@@ -1,21 +1,27 @@
|
||||
import { WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { AVATAR_FALLBACK } from "@calcom/lib/constants";
|
||||
import type { User, Team } from "@calcom/prisma/client";
|
||||
import type { UserProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
/**
|
||||
* Gives an organization aware avatar url for a user
|
||||
* It ensures that the wrong avatar isn't fetched by ensuring that organizationId is always passed
|
||||
*/
|
||||
export const getUserAvatarUrl = (
|
||||
user: (Pick<User, "username" | "organizationId"> & { avatarUrl?: string | null }) | undefined
|
||||
user:
|
||||
| (Pick<User, "username"> & {
|
||||
profile: Omit<UserProfile, "upId">;
|
||||
avatarUrl: string | null;
|
||||
})
|
||||
| undefined
|
||||
) => {
|
||||
if (user?.avatarUrl) {
|
||||
return user.avatarUrl;
|
||||
}
|
||||
if (!user?.username) return AVATAR_FALLBACK;
|
||||
// avatar.png automatically redirects to fallback avatar if user doesn't have one
|
||||
return `${WEBAPP_URL}/${user.username}/avatar.png${
|
||||
user.organizationId ? `?orgId=${user.organizationId}` : ""
|
||||
return `${WEBAPP_URL}/${user.profile?.username}/avatar.png${
|
||||
user.profile?.organizationId ? `?orgId=${user.profile.organizationId}` : ""
|
||||
}`;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { CAL_URL } from "../constants";
|
||||
import { getBrand } from "../server/getBrand";
|
||||
|
||||
export const getBookerBaseUrl = async (user: { organizationId: number | null }) => {
|
||||
const orgBrand = await getBrand(user.organizationId);
|
||||
export const getBookerBaseUrl = async (organizationId: number | null) => {
|
||||
const orgBrand = await getBrand(organizationId);
|
||||
return orgBrand?.fullDomain ?? CAL_URL;
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getBookingFieldsWithSystemFields } from "@calcom/features/bookings/lib/
|
||||
import { parseBookingLimit, parseDurationLimit, parseRecurringEvent } from "@calcom/lib";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { getTranslation } from "@calcom/lib/server/i18n";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import type { PrismaClient } from "@calcom/prisma";
|
||||
import { SchedulingType, MembershipRole } from "@calcom/prisma/enums";
|
||||
import { customInputSchema, EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
|
||||
@@ -22,9 +23,11 @@ interface getEventTypeByIdProps {
|
||||
prisma: PrismaClient;
|
||||
isTrpcCall?: boolean;
|
||||
isUserOrganizationAdmin: boolean;
|
||||
currentOrganizationId: number | null;
|
||||
}
|
||||
|
||||
export default async function getEventTypeById({
|
||||
currentOrganizationId,
|
||||
eventTypeId,
|
||||
userId,
|
||||
prisma,
|
||||
@@ -33,10 +36,10 @@ export default async function getEventTypeById({
|
||||
}: getEventTypeByIdProps) {
|
||||
const userSelect = Prisma.validator<Prisma.UserSelect>()({
|
||||
name: true,
|
||||
avatarUrl: true,
|
||||
username: true,
|
||||
id: true,
|
||||
email: true,
|
||||
organizationId: true,
|
||||
locale: true,
|
||||
defaultScheduleId: true,
|
||||
});
|
||||
@@ -111,7 +114,7 @@ export default async function getEventTypeById({
|
||||
bookingFields: true,
|
||||
owner: {
|
||||
select: {
|
||||
organizationId: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
parent: {
|
||||
@@ -171,11 +174,11 @@ export default async function getEventTypeById({
|
||||
select: {
|
||||
owner: {
|
||||
select: {
|
||||
avatarUrl: true,
|
||||
name: true,
|
||||
username: true,
|
||||
email: true,
|
||||
id: true,
|
||||
organizationId: true,
|
||||
},
|
||||
},
|
||||
hidden: true,
|
||||
@@ -245,6 +248,36 @@ export default async function getEventTypeById({
|
||||
const newMetadata = EventTypeMetaDataSchema.parse(metadata || {}) || {};
|
||||
const apps = newMetadata?.apps || {};
|
||||
const eventTypeWithParsedMetadata = { ...rawEventType, metadata: newMetadata };
|
||||
const eventTeamMembershipsWithUserProfile = [];
|
||||
for (const eventTeamMembership of rawEventType.team?.members || []) {
|
||||
eventTeamMembershipsWithUserProfile.push({
|
||||
...eventTeamMembership,
|
||||
user: await UserRepository.enrichUserWithItsProfile({
|
||||
user: eventTeamMembership.user,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const childrenWithUserProfile = [];
|
||||
for (const child of rawEventType.children || []) {
|
||||
childrenWithUserProfile.push({
|
||||
...child,
|
||||
owner: child.owner
|
||||
? await UserRepository.enrichUserWithItsProfile({
|
||||
user: child.owner,
|
||||
})
|
||||
: null,
|
||||
});
|
||||
}
|
||||
|
||||
const eventTypeUsersWithUserProfile = [];
|
||||
for (const eventTypeUser of rawEventType.users) {
|
||||
eventTypeUsersWithUserProfile.push(
|
||||
await UserRepository.enrichUserWithItsProfile({
|
||||
user: eventTypeUser,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
newMetadata.apps = {
|
||||
...apps,
|
||||
@@ -267,11 +300,11 @@ export default async function getEventTypeById({
|
||||
customInputs: parsedCustomInputs,
|
||||
users: rawEventType.users,
|
||||
bookerUrl: restEventType.team
|
||||
? await getBookerBaseUrl({ organizationId: restEventType.team.parentId })
|
||||
? await getBookerBaseUrl(restEventType.team.parentId)
|
||||
: restEventType.owner
|
||||
? await getBookerBaseUrl(restEventType.owner)
|
||||
? await getBookerBaseUrl(currentOrganizationId)
|
||||
: CAL_URL,
|
||||
children: restEventType.children.flatMap((ch) =>
|
||||
children: childrenWithUserProfile.flatMap((ch) =>
|
||||
ch.owner !== null
|
||||
? {
|
||||
...ch,
|
||||
@@ -312,12 +345,11 @@ export default async function getEventTypeById({
|
||||
eventType.users.push(fallbackUser);
|
||||
}
|
||||
|
||||
const eventTypeUsers: ((typeof eventType.users)[number] & { avatar: string })[] = eventType.users.map(
|
||||
(user) => ({
|
||||
const eventTypeUsers: ((typeof eventType.users)[number] & { avatar: string })[] =
|
||||
eventTypeUsersWithUserProfile.map((user) => ({
|
||||
...user,
|
||||
avatar: getUserAvatarUrl(user),
|
||||
})
|
||||
);
|
||||
}));
|
||||
|
||||
const currentUser = eventType.users.find((u) => u.id === userId);
|
||||
|
||||
@@ -356,7 +388,7 @@ export default async function getEventTypeById({
|
||||
|
||||
const isOrgEventType = !!eventTypeObject.team?.parentId;
|
||||
const teamMembers = eventTypeObject.team
|
||||
? eventTypeObject.team.members
|
||||
? eventTeamMembershipsWithUserProfile
|
||||
.filter((member) => member.accepted || isOrgEventType)
|
||||
.map((member) => {
|
||||
const user: typeof member.user & { avatar: string } = {
|
||||
@@ -365,6 +397,7 @@ export default async function getEventTypeById({
|
||||
};
|
||||
return {
|
||||
...user,
|
||||
profileId: user.profile.id,
|
||||
eventTypes: user.eventTypes.map((evTy) => evTy.slug),
|
||||
membership: member.role,
|
||||
};
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
import { ProfileRepository } from "./repository/profile";
|
||||
|
||||
export async function checkRegularUsername(_username: string, currentOrgDomain?: string | null) {
|
||||
const username = slugify(_username);
|
||||
const premium = !!process.env.NEXT_PUBLIC_IS_E2E && username.length < 5;
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: {
|
||||
username,
|
||||
organization: currentOrgDomain
|
||||
? {
|
||||
slug: currentOrgDomain,
|
||||
}
|
||||
: null,
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
},
|
||||
});
|
||||
const profiles = currentOrgDomain
|
||||
? await ProfileRepository.findManyByOrgSlugOrRequestedSlug({
|
||||
orgSlug: currentOrgDomain,
|
||||
usernames: [username],
|
||||
})
|
||||
: null;
|
||||
|
||||
const user = profiles ? profiles[0].user : null;
|
||||
|
||||
if (user) {
|
||||
return {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import { credentialForCalendarServiceSelect } from "@calcom/prisma/selects/credential";
|
||||
import type { TrpcSessionUser } from "@calcom/trpc/server/trpc";
|
||||
|
||||
export async function getUsersCredentials(userId: number) {
|
||||
export async function getUsersCredentials(user: NonNullable<TrpcSessionUser>) {
|
||||
const credentials = await prisma.credential.findMany({
|
||||
where: {
|
||||
userId,
|
||||
userId: user.id,
|
||||
},
|
||||
select: credentialForCalendarServiceSelect,
|
||||
orderBy: {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Prisma } from "@prisma/client";
|
||||
|
||||
import { getAppFromSlug } from "@calcom/app-store/utils";
|
||||
import prisma, { baseEventTypeSelect } from "@calcom/prisma";
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
import { SchedulingType } from "@calcom/prisma/enums";
|
||||
import { _EventTypeModel } from "@calcom/prisma/zod";
|
||||
import {
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
import { WEBAPP_URL } from "../../../constants";
|
||||
import { getBookerBaseUrlSync } from "../../../getBookerUrl/client";
|
||||
import { getTeam, getOrg } from "../../repository/team";
|
||||
import { UserRepository } from "../../repository/user";
|
||||
|
||||
export type TeamWithMembers = Awaited<ReturnType<typeof getTeamWithMembers>>;
|
||||
|
||||
@@ -23,12 +25,13 @@ export async function getTeamWithMembers(args: {
|
||||
orgSlug?: string | null;
|
||||
includeTeamLogo?: boolean;
|
||||
isTeamView?: boolean;
|
||||
currentOrg?: Team | null;
|
||||
/**
|
||||
* If true, means that you are fetching an organization and not a team
|
||||
*/
|
||||
isOrgView?: boolean;
|
||||
}) {
|
||||
const { id, slug, userId, orgSlug, isTeamView, isOrgView, includeTeamLogo } = args;
|
||||
const { id, slug, currentOrg, userId, orgSlug, isTeamView, isOrgView, includeTeamLogo } = args;
|
||||
|
||||
// This should improve performance saving already app data found.
|
||||
const appDataMap = new Map();
|
||||
@@ -36,14 +39,9 @@ export async function getTeamWithMembers(args: {
|
||||
username: true,
|
||||
email: true,
|
||||
name: true,
|
||||
avatarUrl: true,
|
||||
id: true,
|
||||
bio: true,
|
||||
organizationId: true,
|
||||
organization: {
|
||||
select: {
|
||||
slug: true,
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
select: {
|
||||
team: {
|
||||
@@ -150,11 +148,24 @@ export async function getTeamWithMembers(args: {
|
||||
|
||||
if (!teamOrOrg) return null;
|
||||
|
||||
const members = teamOrOrg.members.map((m) => {
|
||||
const { credentials, ...restUser } = m.user;
|
||||
const teamOrOrgMemberships = [];
|
||||
for (const membership of teamOrOrg.members) {
|
||||
teamOrOrgMemberships.push({
|
||||
...membership,
|
||||
user: await UserRepository.enrichUserWithItsProfile({
|
||||
user: membership.user,
|
||||
}),
|
||||
});
|
||||
}
|
||||
const members = teamOrOrgMemberships.map((m) => {
|
||||
const { credentials, profile, ...restUser } = m.user;
|
||||
return {
|
||||
...restUser,
|
||||
username: profile?.username ?? restUser.username,
|
||||
role: m.role,
|
||||
profile: profile,
|
||||
organizationId: profile?.organizationId ?? null,
|
||||
organization: profile?.organization,
|
||||
accepted: m.accepted,
|
||||
disableImpersonation: m.disableImpersonation,
|
||||
subteams: orgSlug
|
||||
@@ -163,7 +174,7 @@ export async function getTeamWithMembers(args: {
|
||||
.map((membership) => membership.team.slug)
|
||||
: null,
|
||||
avatar: `${WEBAPP_URL}/${m.user.username}/avatar.png`,
|
||||
bookerUrl: getBookerBaseUrlSync(m.user.organization?.slug || ""),
|
||||
bookerUrl: getBookerBaseUrlSync(profile?.organization?.slug || ""),
|
||||
connectedApps: !isTeamView
|
||||
? credentials?.map((cred) => {
|
||||
const appSlug = cred.app?.slug;
|
||||
@@ -187,10 +198,26 @@ export async function getTeamWithMembers(args: {
|
||||
};
|
||||
});
|
||||
|
||||
const eventTypes = teamOrOrg.eventTypes.map((eventType) => ({
|
||||
const eventTypesWithUsersUserProfile = [];
|
||||
for (const eventType of teamOrOrg.eventTypes) {
|
||||
const usersWithUserProfile = [];
|
||||
for (const user of eventType.users) {
|
||||
usersWithUserProfile.push(
|
||||
await UserRepository.enrichUserWithItsProfile({
|
||||
user,
|
||||
})
|
||||
);
|
||||
}
|
||||
eventTypesWithUsersUserProfile.push({
|
||||
...eventType,
|
||||
users: usersWithUserProfile,
|
||||
});
|
||||
}
|
||||
const eventTypes = eventTypesWithUsersUserProfile.map((eventType) => ({
|
||||
...eventType,
|
||||
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
|
||||
}));
|
||||
|
||||
// Don't leak invite tokens to the frontend
|
||||
const { inviteTokens, ...teamWithoutInviteTokens } = teamOrOrg;
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { Prisma, EventType as PrismaEventType } from "@prisma/client";
|
||||
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Ensure } from "@calcom/types/utils";
|
||||
|
||||
import { safeStringify } from "../../safeStringify";
|
||||
import { LookupTarget, ProfileRepository } from "./profile";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["repository/eventType"] });
|
||||
type NotSupportedProps = "locations";
|
||||
type IEventType = Ensure<
|
||||
Partial<
|
||||
Omit<Prisma.EventTypeCreateInput, NotSupportedProps> & {
|
||||
userId: PrismaEventType["userId"];
|
||||
profileId: PrismaEventType["profileId"];
|
||||
teamId: PrismaEventType["teamId"];
|
||||
parentId: PrismaEventType["parentId"];
|
||||
scheduleId: PrismaEventType["scheduleId"];
|
||||
}
|
||||
>,
|
||||
"title" | "slug" | "length"
|
||||
>;
|
||||
|
||||
export class EventTypeRepository {
|
||||
static async create(data: IEventType) {
|
||||
const {
|
||||
userId,
|
||||
profileId,
|
||||
teamId,
|
||||
parentId,
|
||||
scheduleId,
|
||||
bookingLimits,
|
||||
recurringEvent,
|
||||
metadata,
|
||||
bookingFields,
|
||||
durationLimits,
|
||||
...rest
|
||||
} = data;
|
||||
return await prisma.eventType.create({
|
||||
data: {
|
||||
...rest,
|
||||
...(userId ? { owner: { connect: { id: userId } } } : null),
|
||||
...(profileId
|
||||
? {
|
||||
profile: {
|
||||
connect: {
|
||||
id: profileId,
|
||||
},
|
||||
},
|
||||
}
|
||||
: null),
|
||||
...(teamId ? { team: { connect: { id: teamId } } } : null),
|
||||
...(parentId ? { parent: { connect: { id: parentId } } } : null),
|
||||
...(scheduleId ? { schedule: { connect: { id: scheduleId } } } : null),
|
||||
...(metadata ? { metadata: metadata } : null),
|
||||
...(bookingLimits
|
||||
? {
|
||||
bookingLimits,
|
||||
}
|
||||
: null),
|
||||
...(recurringEvent
|
||||
? {
|
||||
recurringEvent,
|
||||
}
|
||||
: null),
|
||||
...(bookingFields
|
||||
? {
|
||||
bookingFields,
|
||||
}
|
||||
: null),
|
||||
...(durationLimits
|
||||
? {
|
||||
durationLimits,
|
||||
}
|
||||
: null),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findAllByUpId(
|
||||
{ upId }: { upId: string },
|
||||
{
|
||||
orderBy,
|
||||
where = {},
|
||||
}: { orderBy?: Prisma.EventTypeOrderByWithRelationInput[]; where?: Prisma.EventTypeWhereInput } = {}
|
||||
) {
|
||||
if (!upId) return [];
|
||||
const lookupTarget = ProfileRepository.getLookupTarget(upId);
|
||||
const eventTypeWhere = {
|
||||
...(lookupTarget.type === LookupTarget.User
|
||||
? {
|
||||
userId: lookupTarget.id,
|
||||
}
|
||||
: {
|
||||
profileId: lookupTarget.id,
|
||||
}),
|
||||
...where,
|
||||
};
|
||||
log.debug(
|
||||
"findAllByUpId",
|
||||
safeStringify({
|
||||
upId,
|
||||
orderBy,
|
||||
argumentWhere: where,
|
||||
where: eventTypeWhere,
|
||||
})
|
||||
);
|
||||
return await prisma.eventType.findMany({
|
||||
where: eventTypeWhere,
|
||||
include: {
|
||||
// TODO: As required by getByViewHandler - Make it configurable
|
||||
team: {
|
||||
include: {
|
||||
eventTypes: true,
|
||||
},
|
||||
},
|
||||
hashedLink: true,
|
||||
users: true,
|
||||
children: {
|
||||
include: {
|
||||
users: true,
|
||||
},
|
||||
},
|
||||
hosts: {
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Prisma, MembershipRole } from "@calcom/prisma/client";
|
||||
|
||||
import logger from "../../logger";
|
||||
import { safeStringify } from "../../safeStringify";
|
||||
import { LookupTarget, ProfileRepository } from "./profile";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["repository/membership"] });
|
||||
type IMembership = {
|
||||
teamId: number;
|
||||
userId: number;
|
||||
profileId: number | null;
|
||||
accepted: boolean;
|
||||
role: MembershipRole;
|
||||
};
|
||||
|
||||
export class MembershipRepository {
|
||||
static async create(data: IMembership) {
|
||||
return await prisma.membership.create({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
static async createMany(data: IMembership[]) {
|
||||
return await prisma.membership.createMany({
|
||||
data,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO: Using a specific function for specific tasks so that we don't have to focus on TS magic at the moment. May be try to make it a a generic findAllByProfileId with various options.
|
||||
*/
|
||||
static async findAllByUpIdIncludeTeamWithMembersAndEventTypes(
|
||||
{ upId }: { upId: string },
|
||||
{ where }: { where?: Prisma.MembershipWhereInput } = {}
|
||||
) {
|
||||
const lookupTarget = ProfileRepository.getLookupTarget(upId);
|
||||
let prismaWhere;
|
||||
if (lookupTarget.type === LookupTarget.Profile) {
|
||||
/**
|
||||
* TODO: When we add profileId to membership, we lookup by profileId
|
||||
* If the profile is movedFromUser, we lookup all memberships without profileId as well.
|
||||
*/
|
||||
const profile = await ProfileRepository.findById(lookupTarget.id);
|
||||
if (!profile) {
|
||||
return [];
|
||||
}
|
||||
prismaWhere = {
|
||||
userId: profile.user.id,
|
||||
...where,
|
||||
};
|
||||
} else {
|
||||
prismaWhere = {
|
||||
userId: lookupTarget.id,
|
||||
...where,
|
||||
};
|
||||
}
|
||||
|
||||
log.debug(
|
||||
"findAllByUpIdIncludeTeamWithMembersAndEventTypes",
|
||||
safeStringify({
|
||||
prismaWhere,
|
||||
})
|
||||
);
|
||||
|
||||
return await prisma.membership.findMany({
|
||||
where: prismaWhere,
|
||||
include: {
|
||||
team: {
|
||||
include: {
|
||||
members: true,
|
||||
parent: true,
|
||||
eventTypes: {
|
||||
include: {
|
||||
team: {
|
||||
include: {
|
||||
eventTypes: true,
|
||||
},
|
||||
},
|
||||
hashedLink: true,
|
||||
users: true,
|
||||
hosts: {
|
||||
include: {
|
||||
user: true,
|
||||
},
|
||||
},
|
||||
children: {
|
||||
include: {
|
||||
users: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
// As required by getByViewHandler - Make it configurable
|
||||
orderBy: [
|
||||
{
|
||||
position: "desc",
|
||||
},
|
||||
{
|
||||
id: "asc",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
import type { User as PrismaUser } from "@prisma/client";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
import type { UpId, UserAsPersonalProfile, UserProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
import logger from "../../logger";
|
||||
import { getParsedTeam } from "./teamUtils";
|
||||
import { UserRepository } from "./user";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["repository/profile"] });
|
||||
const organizationSelect = {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
metadata: true,
|
||||
calVideoLogo: true,
|
||||
};
|
||||
|
||||
export enum LookupTarget {
|
||||
User,
|
||||
Profile,
|
||||
}
|
||||
|
||||
export class ProfileRepository {
|
||||
static generateProfileUid() {
|
||||
return uuidv4();
|
||||
}
|
||||
|
||||
private static getInheritedDataFromUser({ user }: { user: PrismaUser }) {
|
||||
return {
|
||||
name: user.name,
|
||||
avatarUrl: user.avatarUrl,
|
||||
startTime: user.startTime,
|
||||
endTime: user.endTime,
|
||||
bufferTime: user.bufferTime,
|
||||
avatar: user.avatar,
|
||||
};
|
||||
}
|
||||
|
||||
static getLookupTarget(upId: UpId) {
|
||||
if (upId.startsWith("usr-")) {
|
||||
return {
|
||||
type: LookupTarget.User,
|
||||
id: parseInt(upId.replace("usr-", "")),
|
||||
} as const;
|
||||
}
|
||||
return {
|
||||
type: LookupTarget.Profile,
|
||||
id: parseInt(upId),
|
||||
} as const;
|
||||
}
|
||||
|
||||
private static async _create({
|
||||
userId,
|
||||
organizationId,
|
||||
username,
|
||||
email,
|
||||
movedFromUserId,
|
||||
}: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
username: string | null;
|
||||
email: string;
|
||||
movedFromUserId?: number;
|
||||
}) {
|
||||
log.debug("_create", safeStringify({ userId, organizationId, username, email }));
|
||||
return prisma.profile.create({
|
||||
data: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
user: {
|
||||
connect: {
|
||||
id: userId,
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
connect: {
|
||||
id: organizationId,
|
||||
},
|
||||
},
|
||||
...(movedFromUserId
|
||||
? {
|
||||
movedFromUser: {
|
||||
connect: {
|
||||
id: movedFromUserId,
|
||||
},
|
||||
},
|
||||
}
|
||||
: null),
|
||||
|
||||
username: username || email.split("@")[0],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts `email` as a source to derive username from when username is null
|
||||
* @returns
|
||||
*/
|
||||
static create({
|
||||
userId,
|
||||
organizationId,
|
||||
username,
|
||||
email,
|
||||
}: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
username: string | null;
|
||||
email: string;
|
||||
}) {
|
||||
return ProfileRepository._create({ userId, organizationId, username, email });
|
||||
}
|
||||
|
||||
static async upsert({
|
||||
create,
|
||||
update,
|
||||
updateWhere,
|
||||
}: {
|
||||
create: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
username: string | null;
|
||||
email: string;
|
||||
};
|
||||
update: {
|
||||
username: string | null;
|
||||
email: string;
|
||||
};
|
||||
updateWhere: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
};
|
||||
}) {
|
||||
return prisma.profile.upsert({
|
||||
create: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
user: {
|
||||
connect: {
|
||||
id: create.userId,
|
||||
},
|
||||
},
|
||||
organization: {
|
||||
connect: {
|
||||
id: create.organizationId,
|
||||
},
|
||||
},
|
||||
username: create.username || create.email.split("@")[0],
|
||||
},
|
||||
update: {
|
||||
username: update.username || update.email.split("@")[0],
|
||||
},
|
||||
where: {
|
||||
userId_organizationId: {
|
||||
userId: updateWhere.userId,
|
||||
organizationId: updateWhere.organizationId,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async createForExistingUser({
|
||||
userId,
|
||||
organizationId,
|
||||
username,
|
||||
email,
|
||||
movedFromUserId,
|
||||
}: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
username: string | null;
|
||||
email: string;
|
||||
movedFromUserId: number;
|
||||
}) {
|
||||
return await ProfileRepository._create({
|
||||
userId,
|
||||
organizationId,
|
||||
username,
|
||||
email: email,
|
||||
movedFromUserId,
|
||||
});
|
||||
}
|
||||
|
||||
static createMany({
|
||||
users,
|
||||
organizationId,
|
||||
}: {
|
||||
users: { id: number; username: string; email: string }[];
|
||||
organizationId: number;
|
||||
}) {
|
||||
return prisma.profile.createMany({
|
||||
data: users.map((user) => ({
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: user.id,
|
||||
organizationId,
|
||||
username: user.username || user.email.split("@")[0],
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
static delete({ userId, organizationId }: { userId: number; organizationId: number }) {
|
||||
// Even though there can be just one profile matching a userId and organizationId, we are using deleteMany as it won't error if the profile doesn't exist
|
||||
return prisma.profile.deleteMany({
|
||||
where: { userId, organizationId },
|
||||
});
|
||||
}
|
||||
|
||||
static deleteMany({ userIds }: { userIds: number[] }) {
|
||||
// Even though there can be just one profile matching a userId and organizationId, we are using deleteMany as it won't error if the profile doesn't exist
|
||||
return prisma.profile.deleteMany({
|
||||
where: { userId: { in: userIds } },
|
||||
});
|
||||
}
|
||||
|
||||
static async findByUserIdAndOrgId({
|
||||
userId,
|
||||
organizationId,
|
||||
}: {
|
||||
userId: number;
|
||||
organizationId: number | null;
|
||||
}) {
|
||||
if (!organizationId) {
|
||||
return null;
|
||||
}
|
||||
const profile = await prisma.profile.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
organizationId,
|
||||
},
|
||||
include: {
|
||||
organization: {
|
||||
select: organizationSelect,
|
||||
},
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!profile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const organization = getParsedTeam(profile.organization);
|
||||
return normalizeProfile({
|
||||
...profile,
|
||||
organization: {
|
||||
...organization,
|
||||
requestedSlug: organization.metadata?.requestedSlug ?? null,
|
||||
metadata: organization.metadata,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findByOrgIdAndUsername({
|
||||
organizationId,
|
||||
username,
|
||||
}: {
|
||||
organizationId: number;
|
||||
username: string;
|
||||
}) {
|
||||
const profile = await prisma.profile.findFirst({
|
||||
where: {
|
||||
username,
|
||||
organizationId,
|
||||
},
|
||||
include: {
|
||||
organization: {
|
||||
select: organizationSelect,
|
||||
},
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
return profile;
|
||||
}
|
||||
|
||||
static async findByUpId(upId: string) {
|
||||
const lookupTarget = ProfileRepository.getLookupTarget(upId);
|
||||
log.debug("findById", safeStringify({ upId, lookupTarget }));
|
||||
if (lookupTarget.type === LookupTarget.User) {
|
||||
const user = await UserRepository.findById({ id: lookupTarget.id });
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
username: user.username,
|
||||
upId: `usr-${user.id}`,
|
||||
id: null,
|
||||
organizationId: null,
|
||||
organization: null,
|
||||
...ProfileRepository.getInheritedDataFromUser({ user }),
|
||||
};
|
||||
}
|
||||
|
||||
const profile = await ProfileRepository.findById(lookupTarget.id);
|
||||
if (!profile) {
|
||||
return null;
|
||||
}
|
||||
const user = profile.user;
|
||||
return {
|
||||
...profile,
|
||||
...ProfileRepository.getInheritedDataFromUser({ user }),
|
||||
};
|
||||
}
|
||||
|
||||
static async findById(id: number | null) {
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const profile = await prisma.profile.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
organization: {
|
||||
include: {
|
||||
members: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!profile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeProfile(profile);
|
||||
}
|
||||
|
||||
static async findManyByOrgSlugOrRequestedSlug({
|
||||
usernames,
|
||||
orgSlug,
|
||||
}: {
|
||||
usernames: string[];
|
||||
orgSlug: string;
|
||||
}) {
|
||||
logger.debug("findManyByOrgSlugOrRequestedSlug", safeStringify({ usernames, orgSlug }));
|
||||
const profiles = await prisma.profile.findMany({
|
||||
where: {
|
||||
username: {
|
||||
in: usernames,
|
||||
},
|
||||
organization: whereClauseForOrgWithSlugOrRequestedSlug(orgSlug),
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
organization: {
|
||||
select: organizationSelect,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return profiles.map(normalizeProfile);
|
||||
}
|
||||
|
||||
static async findAllProfilesForUserIncludingMovedUser(user: {
|
||||
id: number;
|
||||
username: string | null;
|
||||
}): Promise<UserProfile[]> {
|
||||
const profiles = await ProfileRepository.findManyForUser(user);
|
||||
// User isn't member of any organization. Also, he has no user profile. We build the profile from user table
|
||||
if (!profiles.length) {
|
||||
return [
|
||||
ProfileRepository.buildPersonalProfileFromUser({
|
||||
user,
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
return profiles;
|
||||
}
|
||||
|
||||
static async findManyForUser(user: { id: number }) {
|
||||
const profiles = (
|
||||
await prisma.profile.findMany({
|
||||
where: {
|
||||
userId: user.id,
|
||||
},
|
||||
include: {
|
||||
organization: {
|
||||
select: organizationSelect,
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
.map((profile) => {
|
||||
return {
|
||||
...profile,
|
||||
organization: getParsedTeam(profile.organization),
|
||||
};
|
||||
})
|
||||
.map((profile) => {
|
||||
return normalizeProfile({
|
||||
username: profile.username,
|
||||
id: profile.id,
|
||||
userId: profile.userId,
|
||||
uid: profile.uid,
|
||||
name: profile.organization.name,
|
||||
organizationId: profile.organizationId,
|
||||
organization: {
|
||||
...profile.organization,
|
||||
requestedSlug: profile.organization.metadata?.requestedSlug ?? null,
|
||||
metadata: profile.organization.metadata,
|
||||
},
|
||||
});
|
||||
});
|
||||
return profiles;
|
||||
}
|
||||
|
||||
static async findManyForOrg({ organizationId }: { organizationId: number }) {
|
||||
return await prisma.profile.findMany({
|
||||
where: {
|
||||
organizationId,
|
||||
},
|
||||
include: {
|
||||
user: true,
|
||||
organization: {
|
||||
select: organizationSelect,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static async findByUserIdAndProfileId({ userId, profileId }: { userId: number; profileId: number }) {
|
||||
const profile = await prisma.profile.findUnique({
|
||||
where: {
|
||||
userId,
|
||||
id: profileId,
|
||||
},
|
||||
include: {
|
||||
organization: {
|
||||
select: organizationSelect,
|
||||
},
|
||||
user: true,
|
||||
},
|
||||
});
|
||||
if (!profile) {
|
||||
return profile;
|
||||
}
|
||||
return normalizeProfile(profile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Personal profile should come from Profile table only
|
||||
*/
|
||||
static buildPersonalProfileFromUser({
|
||||
user,
|
||||
}: {
|
||||
user: { username: string | null; id: number };
|
||||
}): UserAsPersonalProfile {
|
||||
return {
|
||||
id: null,
|
||||
upId: `usr-${user.id}`,
|
||||
username: user.username,
|
||||
organizationId: null,
|
||||
organization: null,
|
||||
};
|
||||
}
|
||||
|
||||
static _getPrismaWhereForProfilesOfOrg({ orgSlug }: { orgSlug: string | null }) {
|
||||
return {
|
||||
profiles: {
|
||||
...(orgSlug
|
||||
? {
|
||||
some: {
|
||||
organization: {
|
||||
slug: orgSlug,
|
||||
},
|
||||
},
|
||||
}
|
||||
: // If it's not orgSlug we want to ensure that no profile is there. Having a profile means that the user is a member of some organization.
|
||||
{
|
||||
none: {},
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const normalizeProfile = <
|
||||
T extends {
|
||||
id: number;
|
||||
organization: Pick<Team, keyof typeof organizationSelect>;
|
||||
createdAt?: Date;
|
||||
updatedAt?: Date;
|
||||
}
|
||||
>(
|
||||
profile: T
|
||||
) => {
|
||||
return {
|
||||
...profile,
|
||||
upId: profile.id.toString(),
|
||||
organization: getParsedTeam(profile.organization),
|
||||
// Make these ↓ props ISO strings so that they can be returned from getServerSideProps as is without any issues
|
||||
...(profile.createdAt ? { createdAt: profile.createdAt.toISOString() } : null),
|
||||
...(profile.updatedAt ? { updatedAt: profile.updatedAt.toISOString() } : null),
|
||||
};
|
||||
};
|
||||
@@ -6,6 +6,8 @@ import logger from "@calcom/lib/logger";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { getParsedTeam } from "./teamUtils";
|
||||
|
||||
type TeamGetPayloadWithParsedMetadata<TeamSelect extends Prisma.TeamSelect> =
|
||||
| (Omit<Prisma.TeamGetPayload<{ select: TeamSelect }>, "metadata"> & {
|
||||
metadata: z.infer<typeof teamMetadataSchema>;
|
||||
@@ -146,3 +148,16 @@ export async function getOrg<TeamSelect extends Prisma.TeamSelect>({
|
||||
teamSelect,
|
||||
});
|
||||
}
|
||||
export class TeamRepository {
|
||||
static async findById({ id }: { id: number }) {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
if (!team) {
|
||||
return null;
|
||||
}
|
||||
return getParsedTeam(team);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
export const getParsedTeam = <T extends { metadata: Team["metadata"] }>(team: T) => {
|
||||
const metadata = teamMetadataSchema.parse(team.metadata);
|
||||
const requestedSlug = metadata?.requestedSlug ?? null;
|
||||
const { metadata: _1, ...rest } = team;
|
||||
return {
|
||||
...rest,
|
||||
requestedSlug,
|
||||
metadata: {
|
||||
...metadata,
|
||||
requestedSlug,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,336 @@
|
||||
import { whereClauseForOrgWithSlugOrRequestedSlug } from "@calcom/ee/organizations/lib/orgDomains";
|
||||
import prisma from "@calcom/prisma";
|
||||
import type { UpId, UserProfile } from "@calcom/types/UserProfile";
|
||||
|
||||
import { isOrganization } from "../../entityPermissionUtils";
|
||||
import logger from "../../logger";
|
||||
import { safeStringify } from "../../safeStringify";
|
||||
import { ProfileRepository } from "./profile";
|
||||
import { getParsedTeam } from "./teamUtils";
|
||||
import type { User as UserType, Prisma } from ".prisma/client";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["[repository/user]"] });
|
||||
|
||||
export const ORGANIZATION_ID_UNKNOWN = "ORGANIZATION_ID_UNKNOWN";
|
||||
export class UserRepository {
|
||||
static async findTeamsByUserId({ userId }: { userId: UserType["id"] }) {
|
||||
const teamMemberships = await prisma.membership.findMany({
|
||||
where: {
|
||||
userId: userId,
|
||||
},
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
});
|
||||
|
||||
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) =>
|
||||
isOrganization({ team: membership.team })
|
||||
);
|
||||
|
||||
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.debug("findUsersByUsername", safeStringify({ where, profiles }));
|
||||
|
||||
return (
|
||||
await prisma.user.findMany({
|
||||
where,
|
||||
})
|
||||
).map((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
|
||||
? {
|
||||
// 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 findByEmailAndIncludeProfiles({ 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: 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,
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
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 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 if you don't directly has the profileId.
|
||||
* It can happen in two 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.
|
||||
*/
|
||||
static async enrichUserWithItsProfile<T extends { id: number; username: string | null }>({
|
||||
user,
|
||||
}: {
|
||||
user: T;
|
||||
}): Promise<T & { profile: UserProfile }> {
|
||||
const profiles = await ProfileRepository.findManyForUser({ id: user.id });
|
||||
if (profiles.length) {
|
||||
const profile = profiles[0];
|
||||
return {
|
||||
...user,
|
||||
username: profile.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,
|
||||
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;
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,7 @@ export const buildEventType = (eventType?: Partial<EventType>): EventType => {
|
||||
successRedirectUrl: null,
|
||||
bookingFields: [],
|
||||
parentId: null,
|
||||
profileId: null,
|
||||
...eventType,
|
||||
};
|
||||
};
|
||||
@@ -236,6 +237,7 @@ export const buildUser = <T extends Partial<UserPayload>>(user?: T): UserPayload
|
||||
organizationId: null,
|
||||
allowSEOIndexing: null,
|
||||
receiveMonthlyDigestEmail: null,
|
||||
movedToProfileId: null,
|
||||
...user,
|
||||
};
|
||||
};
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- A unique constraint covering the columns `[movedToProfileId]` on the table `users` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- AlterTable
|
||||
ALTER TABLE "EventType" ADD COLUMN "profileId" INTEGER;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "movedToProfileId" INTEGER;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Profile" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"uid" TEXT NOT NULL,
|
||||
"userId" INTEGER NOT NULL,
|
||||
"organizationId" INTEGER NOT NULL,
|
||||
"username" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Profile_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Profile_uid_idx" ON "Profile"("uid");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Profile_userId_idx" ON "Profile"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Profile_organizationId_idx" ON "Profile"("organizationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Profile_userId_organizationId_key" ON "Profile"("userId", "organizationId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_movedToProfileId_key" ON "users"("movedToProfileId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "EventType" ADD CONSTRAINT "EventType_profileId_fkey" FOREIGN KEY ("profileId") REFERENCES "Profile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "users" ADD CONSTRAINT "users_movedToProfileId_fkey" FOREIGN KEY ("movedToProfileId") REFERENCES "Profile"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Profile" ADD CONSTRAINT "Profile_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
|
||||
-- Copy Data to Profile table
|
||||
WITH new_profile AS (
|
||||
INSERT INTO "Profile" ("uid", "organizationId", "userId", "username", "updatedAt")
|
||||
SELECT "id" as "uid", "organizationId", "id" AS "userId", "username", NOW()
|
||||
FROM "users"
|
||||
WHERE "organizationId" IS NOT NULL
|
||||
RETURNING "uid", "userId", "id"
|
||||
)
|
||||
UPDATE "users"
|
||||
SET "movedToProfileId" = "new_profile"."id"
|
||||
FROM "new_profile"
|
||||
WHERE "users"."id" = "new_profile"."userId";
|
||||
@@ -47,23 +47,27 @@ model Host {
|
||||
}
|
||||
|
||||
model EventType {
|
||||
id Int @id @default(autoincrement())
|
||||
id Int @id @default(autoincrement())
|
||||
/// @zod.min(1)
|
||||
title String
|
||||
title String
|
||||
/// @zod.custom(imports.eventTypeSlug)
|
||||
slug String
|
||||
description String?
|
||||
position Int @default(0)
|
||||
slug String
|
||||
description String?
|
||||
position Int @default(0)
|
||||
/// @zod.custom(imports.eventTypeLocations)
|
||||
locations Json?
|
||||
locations Json?
|
||||
/// @zod.min(1)
|
||||
length Int
|
||||
offsetStart Int @default(0)
|
||||
hidden Boolean @default(false)
|
||||
hosts Host[]
|
||||
users User[] @relation("user_eventtype")
|
||||
owner User? @relation("owner", fields: [userId], references: [id], onDelete: Cascade)
|
||||
userId Int?
|
||||
length Int
|
||||
offsetStart Int @default(0)
|
||||
hidden Boolean @default(false)
|
||||
hosts Host[]
|
||||
users User[] @relation("user_eventtype")
|
||||
owner User? @relation("owner", fields: [userId], references: [id], onDelete: Cascade)
|
||||
userId Int?
|
||||
|
||||
profileId Int?
|
||||
profile Profile? @relation(fields: [profileId], references: [id], onDelete: Cascade)
|
||||
|
||||
team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)
|
||||
teamId Int?
|
||||
hashedLink HashedLink?
|
||||
@@ -185,6 +189,7 @@ enum UserPermissionRole {
|
||||
ADMIN
|
||||
}
|
||||
|
||||
// It holds Personal Profiles of a User plus it has email, password and other core things
|
||||
model User {
|
||||
id Int @id @default(autoincrement())
|
||||
username String?
|
||||
@@ -260,17 +265,17 @@ model User {
|
||||
accessCodes AccessCode[]
|
||||
bookingRedirects OutOfOfficeEntry[]
|
||||
bookingRedirectsTo OutOfOfficeEntry[] @relation(name: "toUser")
|
||||
// Linking account code for orgs v2
|
||||
//linkedByUserId Int?
|
||||
//linkedBy User? @relation("linked_account", fields: [linkedByUserId], references: [id], onDelete: Cascade)
|
||||
//linkedUsers User[] @relation("linked_account")*/
|
||||
|
||||
// Used to lock the user account
|
||||
locked Boolean @default(false)
|
||||
locked Boolean @default(false)
|
||||
profiles Profile[]
|
||||
movedToProfileId Int?
|
||||
movedToProfile Profile? @relation("moved_to_profile", fields: [movedToProfileId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@unique([email])
|
||||
@@unique([email, username])
|
||||
@@unique([username, organizationId])
|
||||
@@unique([movedToProfileId])
|
||||
@@index([username])
|
||||
@@index([emailVerified])
|
||||
@@index([identityProvider])
|
||||
@@ -278,6 +283,27 @@ model User {
|
||||
@@map(name: "users")
|
||||
}
|
||||
|
||||
// It holds Organization Profiles
|
||||
model Profile {
|
||||
id Int @id @default(autoincrement())
|
||||
// uid allows us to set an identifier chosen by us which is helpful in migration when we create the Profile from User directly.
|
||||
uid String
|
||||
userId Int
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
organizationId Int
|
||||
organization Team @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
username String
|
||||
eventTypes EventType[]
|
||||
movedFromUser User? @relation("moved_to_profile")
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@unique([userId, organizationId])
|
||||
@@index([uid])
|
||||
@@index([userId])
|
||||
@@index([organizationId])
|
||||
}
|
||||
|
||||
model Team {
|
||||
id Int @id @default(autoincrement())
|
||||
/// @zod.min(1)
|
||||
@@ -317,6 +343,7 @@ model Team {
|
||||
credentials Credential[]
|
||||
accessCodes AccessCode[]
|
||||
instantMeetingTokens InstantMeetingToken[]
|
||||
orgProfiles Profile[]
|
||||
pendingPayment Boolean @default(false)
|
||||
|
||||
@@unique([slug, parentId])
|
||||
|
||||
+377
-1
@@ -1,4 +1,5 @@
|
||||
import type { Prisma } from "@prisma/client";
|
||||
import type { Membership, Team, User } from "@prisma/client";
|
||||
import { Prisma } from "@prisma/client";
|
||||
import { uuid } from "short-uuid";
|
||||
import type z from "zod";
|
||||
|
||||
@@ -6,7 +7,9 @@ import dailyMeta from "@calcom/app-store/dailyvideo/_metadata";
|
||||
import googleMeetMeta from "@calcom/app-store/googlevideo/_metadata";
|
||||
import zoomMeta from "@calcom/app-store/zoomvideo/_metadata";
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { hashPassword } from "@calcom/features/auth/lib/hashPassword";
|
||||
import { BookingStatus, MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { Ensure } from "@calcom/types/utils";
|
||||
|
||||
import prisma from ".";
|
||||
import mainAppStore from "./seed-app-store";
|
||||
@@ -75,6 +78,260 @@ async function createTeamAndAddUsers(
|
||||
return team;
|
||||
}
|
||||
|
||||
async function createOrganizationAndAddMembersAndTeams({
|
||||
org: { orgData, members: orgMembers },
|
||||
teams,
|
||||
usersOutsideOrg,
|
||||
}: {
|
||||
org: {
|
||||
orgData: Ensure<Partial<Prisma.TeamCreateInput>, "name" | "slug">;
|
||||
members: {
|
||||
memberData: Ensure<Partial<Prisma.UserCreateInput>, "username" | "name" | "email" | "password">;
|
||||
orgMembership: Partial<Membership>;
|
||||
orgProfile: {
|
||||
username: string;
|
||||
};
|
||||
inTeams: { slug: string; role: MembershipRole }[];
|
||||
}[];
|
||||
};
|
||||
teams: {
|
||||
teamData: Omit<Ensure<Partial<Prisma.TeamCreateInput>, "name" | "slug">, "members">;
|
||||
nonOrgMembers: Ensure<Partial<Prisma.UserCreateInput>, "username" | "name" | "email" | "password">[];
|
||||
}[];
|
||||
usersOutsideOrg: {
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
}[];
|
||||
}) {
|
||||
console.log(`\n🏢 Creating organization "${orgData.name}"`);
|
||||
const orgMembersInDb: (User & {
|
||||
inTeams: { slug: string; role: MembershipRole }[];
|
||||
orgMembership: Partial<Membership>;
|
||||
orgProfile: {
|
||||
username: string;
|
||||
};
|
||||
})[] = [];
|
||||
|
||||
// Create all users first
|
||||
try {
|
||||
for (const member of orgMembers) {
|
||||
const orgMemberInDb = {
|
||||
...(await prisma.user.create({
|
||||
data: {
|
||||
...member.memberData,
|
||||
password: await hashPassword(member.memberData.password),
|
||||
},
|
||||
})),
|
||||
inTeams: member.inTeams,
|
||||
orgMembership: member.orgMembership,
|
||||
orgProfile: member.orgProfile,
|
||||
};
|
||||
|
||||
orgMembersInDb.push(orgMemberInDb);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
if (e.code === "P2002") {
|
||||
console.log(`One of the organization members already exists, skipping the entire seeding`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
usersOutsideOrg.map(async (user) => {
|
||||
return await prisma.user.create({
|
||||
data: {
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
password: await hashPassword(user.username),
|
||||
},
|
||||
});
|
||||
}),
|
||||
]);
|
||||
|
||||
// Create organization with those users as members
|
||||
const orgInDb = await prisma.team.create({
|
||||
data: {
|
||||
...orgData,
|
||||
metadata: {
|
||||
...(orgData.metadata && typeof orgData.metadata === "object" ? orgData.metadata : {}),
|
||||
isOrganization: true,
|
||||
},
|
||||
orgProfiles: {
|
||||
create: orgMembersInDb.map((member) => ({
|
||||
uid: uuid(),
|
||||
username: member.orgProfile.username,
|
||||
user: {
|
||||
connect: {
|
||||
id: member.id,
|
||||
},
|
||||
},
|
||||
})),
|
||||
},
|
||||
members: {
|
||||
create: orgMembersInDb.map((member) => ({
|
||||
user: {
|
||||
connect: {
|
||||
id: member.id,
|
||||
},
|
||||
},
|
||||
role: member.orgMembership.role || "MEMBER",
|
||||
accepted: member.orgMembership.accepted,
|
||||
})),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
members: true,
|
||||
orgProfiles: true,
|
||||
},
|
||||
});
|
||||
|
||||
const orgMembersInDBWithProfileId = await Promise.all(
|
||||
orgMembersInDb.map(async (member) => ({
|
||||
...member,
|
||||
profile: {
|
||||
...member.orgProfile,
|
||||
id: orgInDb.orgProfiles.find((p) => p.userId === member.id)?.id,
|
||||
},
|
||||
}))
|
||||
);
|
||||
|
||||
// For each member create one event
|
||||
for (const member of orgMembersInDBWithProfileId) {
|
||||
await prisma.eventType.create({
|
||||
data: {
|
||||
title: `${member.name} Event`,
|
||||
slug: `${member.username}-event`,
|
||||
length: 15,
|
||||
owner: {
|
||||
connect: {
|
||||
id: member.id,
|
||||
},
|
||||
},
|
||||
profile: {
|
||||
connect: {
|
||||
id: member.profile.id,
|
||||
},
|
||||
},
|
||||
users: {
|
||||
connect: {
|
||||
id: member.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Create schedule for every member
|
||||
await prisma.schedule.create({
|
||||
data: {
|
||||
name: "Working Hours",
|
||||
userId: member.id,
|
||||
availability: {
|
||||
create: {
|
||||
days: [1, 2, 3, 4, 5],
|
||||
startTime: "1970-01-01T09:00:00.000Z",
|
||||
endTime: "1970-01-01T17:00:00.000Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const organizationTeams: Team[] = [];
|
||||
|
||||
// Create all the teams in the organization
|
||||
for (let teamIndex = 0; teamIndex < teams.length; teamIndex++) {
|
||||
const nonOrgMembers: User[] = [];
|
||||
const team = teams[teamIndex];
|
||||
for (const nonOrgMember of team.nonOrgMembers) {
|
||||
nonOrgMembers.push(
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
...nonOrgMember,
|
||||
password: await hashPassword(nonOrgMember.password),
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
organizationTeams.push(
|
||||
await prisma.team.create({
|
||||
data: {
|
||||
...team.teamData,
|
||||
parent: {
|
||||
connect: {
|
||||
id: orgInDb.id,
|
||||
},
|
||||
},
|
||||
metadata: team.teamData.metadata || {},
|
||||
members: {
|
||||
create: nonOrgMembers.map((member) => ({
|
||||
user: {
|
||||
connect: {
|
||||
id: member.id,
|
||||
},
|
||||
},
|
||||
role: "MEMBER",
|
||||
accepted: true,
|
||||
})),
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
const ownerForEvent = orgMembersInDBWithProfileId[0];
|
||||
// Create event for each team
|
||||
await prisma.eventType.create({
|
||||
data: {
|
||||
title: `${team.teamData.name} Event1`,
|
||||
slug: `${team.teamData.slug}-event-1`,
|
||||
length: 15,
|
||||
team: {
|
||||
connect: {
|
||||
id: organizationTeams[teamIndex].id,
|
||||
},
|
||||
},
|
||||
owner: {
|
||||
connect: {
|
||||
id: ownerForEvent.id,
|
||||
},
|
||||
},
|
||||
profile: {
|
||||
connect: {
|
||||
id: ownerForEvent.profile.id,
|
||||
},
|
||||
},
|
||||
users: {
|
||||
connect: {
|
||||
id: ownerForEvent.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create memberships for all the organization members with the respective teams
|
||||
for (const member of orgMembersInDBWithProfileId) {
|
||||
for (const { slug: teamSlug, role: role } of member.inTeams) {
|
||||
const team = organizationTeams.find((t) => t.slug === teamSlug);
|
||||
if (!team) {
|
||||
throw Error(`Team with slug ${teamSlug} not found`);
|
||||
}
|
||||
await prisma.membership.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: member.id,
|
||||
role: role,
|
||||
accepted: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await createUserAndEventType({
|
||||
user: {
|
||||
@@ -116,6 +373,7 @@ async function main() {
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await createUserAndEventType({
|
||||
user: {
|
||||
email: "[email protected]",
|
||||
@@ -530,6 +788,124 @@ async function main() {
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
await createOrganizationAndAddMembersAndTeams({
|
||||
org: {
|
||||
orgData: {
|
||||
name: "Acme Inc",
|
||||
slug: "acme",
|
||||
metadata: {
|
||||
isOrganizationVerified: true,
|
||||
orgAutoAcceptEmail: "acme.com",
|
||||
},
|
||||
},
|
||||
members: [
|
||||
{
|
||||
memberData: {
|
||||
email: "[email protected]",
|
||||
password: "owner1-acme",
|
||||
username: "owner1-acme",
|
||||
name: "Owner 1",
|
||||
},
|
||||
orgMembership: {
|
||||
role: "OWNER",
|
||||
accepted: true,
|
||||
},
|
||||
orgProfile: {
|
||||
username: "owner1",
|
||||
},
|
||||
inTeams: [
|
||||
{
|
||||
slug: "team1",
|
||||
role: "ADMIN",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
teams: [
|
||||
{
|
||||
teamData: {
|
||||
name: "Team 1",
|
||||
slug: "team1",
|
||||
},
|
||||
nonOrgMembers: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
password: "non-acme-member-1",
|
||||
username: "non-acme-member-1",
|
||||
name: "NonAcme Member1",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
usersOutsideOrg: [
|
||||
{
|
||||
name: "Jane Doe",
|
||||
email: "[email protected]",
|
||||
username: "jane-outside-org",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await createOrganizationAndAddMembersAndTeams({
|
||||
org: {
|
||||
orgData: {
|
||||
name: "Dunder Mifflin",
|
||||
slug: "dunder-mifflin",
|
||||
metadata: {
|
||||
isOrganizationVerified: true,
|
||||
orgAutoAcceptEmail: "dunder-mifflin.com",
|
||||
},
|
||||
},
|
||||
members: [
|
||||
{
|
||||
memberData: {
|
||||
email: "[email protected]",
|
||||
password: "owner1-dunder",
|
||||
username: "owner1-dunder",
|
||||
name: "Owner 1",
|
||||
},
|
||||
orgMembership: {
|
||||
role: "OWNER",
|
||||
accepted: true,
|
||||
},
|
||||
orgProfile: {
|
||||
username: "owner1",
|
||||
},
|
||||
inTeams: [
|
||||
{
|
||||
slug: "team1",
|
||||
role: "ADMIN",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
teams: [
|
||||
{
|
||||
teamData: {
|
||||
name: "Team 1",
|
||||
slug: "team1",
|
||||
},
|
||||
nonOrgMembers: [
|
||||
{
|
||||
email: "[email protected]",
|
||||
password: "non-dunder-member-1",
|
||||
username: "non-dunder-member-1",
|
||||
name: "NonDunder Member1",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
usersOutsideOrg: [
|
||||
{
|
||||
name: "John Doe",
|
||||
email: "[email protected]",
|
||||
username: "john-outside-org",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
main()
|
||||
|
||||
@@ -51,7 +51,6 @@ export const userSelect = Prisma.validator<Prisma.UserArgs>()({
|
||||
brandColor: true,
|
||||
darkBrandColor: true,
|
||||
metadata: true,
|
||||
organizationId: true,
|
||||
...availabilityUserSelect,
|
||||
},
|
||||
});
|
||||
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user