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

@@ -8,7 +8,6 @@ import { md } from "@calcom/lib/markdownIt";
import { telemetryEventTypes, useTelemetry } from "@calcom/lib/telemetry";
import turndown from "@calcom/lib/turndownService";
import { trpc } from "@calcom/trpc/react";
import type { Ensure } from "@calcom/types/utils";
import { Button, Editor, ImageUploader, Label, showToast } from "@calcom/ui";
import { UserAvatar } from "@calcom/ui";
import { ArrowRight } from "@calcom/ui/components/icon";
@@ -97,18 +96,10 @@ const UserProfile = () => {
},
];
const organization =
user.organization && user.organization.id
? {
...(user.organization as Ensure<typeof user.organization, "id">),
slug: user.organization.slug || null,
requestedSlug: user.organization.metadata?.requestedSlug || null,
}
: null;
return (
<form onSubmit={onSubmit}>
<div className="flex flex-row items-center justify-start rtl:justify-end">
{user && <UserAvatar size="lg" user={user} previewSrc={imageSrc} organization={organization} />}
{user && <UserAvatar size="lg" user={user} previewSrc={imageSrc} />}
<input
ref={avatarRef}
type="hidden"
+7 -2
View File
@@ -5,11 +5,16 @@ import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { md } from "@calcom/lib/markdownIt";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import type { TeamWithMembers } from "@calcom/lib/server/queries/teams";
import type { UserProfile } from "@calcom/types/UserProfile";
import { UserAvatar } from "@calcom/ui";
type TeamType = Omit<NonNullable<TeamWithMembers>, "inviteToken">;
type MembersType = TeamType["members"];
type MemberType = Pick<MembersType[number], "id" | "name" | "bio" | "username" | "organizationId"> & {
type MemberType = Pick<
MembersType[number],
"id" | "name" | "bio" | "username" | "organizationId" | "avatarUrl"
> & {
profile: Omit<UserProfile, "upId">;
safeBio: string | null;
bookerUrl: string;
};
@@ -27,7 +32,7 @@ const Member = ({ member, teamName }: { member: MemberType; teamName: string | n
key={member.id}
href={{ pathname: `${member.bookerUrl}/${member.username}`, query: queryParamsToForward }}>
<div className="sm:min-w-80 sm:max-w-80 bg-default hover:bg-muted border-subtle group flex min-h-full flex-col space-y-2 rounded-md border p-4 hover:cursor-pointer">
<UserAvatar size="md" user={member} />
<UserAvatar noOrganizationIndicator size="md" user={member} />
<section className="mt-2 line-clamp-4 w-full space-y-1">
<p className="text-default font-medium">{member.name}</p>
<div className="text-subtle line-clamp-3 overflow-ellipsis text-sm font-normal">
@@ -5,6 +5,7 @@ import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getBookingForReschedule, getMultipleDurationValue } from "@calcom/features/bookings/lib/get-booking";
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import { UserRepository } from "@calcom/lib/server/repository/user";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
@@ -56,19 +57,9 @@ async function getUserPageProps(context: GetServerSidePropsContext) {
return notFound;
}
const user = await prisma.user.findFirst({
where: {
username,
organization: isValidOrgDomain
? {
slug: currentOrgDomain,
}
: null,
},
select: {
away: true,
hideBranding: true,
},
const [user] = await UserRepository.findUsersByUsername({
usernameList: [username],
orgSlug: org,
});
if (!user) {
+5 -2
View File
@@ -1589,17 +1589,20 @@ async function createTeamOutsideOrg(
});
}
async function createUserOutsideOrg(data: Omit<Prisma.UserCreateArgs["data"], "organization">) {
async function createUserOutsideOrg(
data: Omit<Prisma.UserCreateArgs["data"], "organization" | "movedToProfile">
) {
return await prismock.user.create({
data: {
...data,
movedToProfileId: null,
organizationId: null,
},
});
}
async function createUserInsideTheOrg(
data: Omit<Prisma.UserUncheckedCreateInput, "organization" | "organizationId" | "id">,
data: Omit<Prisma.UserUncheckedCreateInput, "organization" | "organizationId" | "id" | "movedToProfileId">,
orgId: number
) {
const org = await prismock.team.findUnique({
+37 -3
View File
@@ -3,6 +3,7 @@ import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomai
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import prisma from "@calcom/prisma";
import type { Team, User } from "@calcom/prisma/client";
import { RedirectType } from "@calcom/prisma/client";
@@ -327,7 +328,7 @@ async function setOrgSlugIfNotSet(
slug: string | null;
},
orgMetadata: {
requestedSlug?: string | undefined;
requestedSlug?: string | null | undefined;
},
targetOrgId: number
) {
@@ -348,7 +349,7 @@ async function setOrgSlugIfNotSet(
function assertUserPartOfOrgAndRemigrationAllowed(
userToMoveToOrg: {
organizationId: User["organizationId"];
organizationId: number | null;
},
targetOrgId: number,
targetOrgUsername: string,
@@ -384,7 +385,7 @@ async function getTeamOrThrowError(targetOrgId: number) {
function assertUserPartOfOtherOrg(
userToMoveToOrg: {
organizationId: User["organizationId"];
organizationId: number | null;
} | null,
userName: string | undefined,
userId: number | undefined,
@@ -594,6 +595,35 @@ async function dbMoveUserToOrg({
},
},
});
await prisma.profile.upsert({
create: {
uid: ProfileRepository.generateProfileUid(),
userId: userToMoveToOrg.id,
organizationId: targetOrgId,
username: targetOrgUsername,
movedFromUser: {
connect: {
id: userToMoveToOrg.id,
},
},
},
update: {
organizationId: targetOrgId,
username: targetOrgUsername,
movedFromUser: {
connect: {
id: userToMoveToOrg.id,
},
},
},
where: {
userId_organizationId: {
userId: userToMoveToOrg.id,
organizationId: targetOrgId,
},
},
});
}
async function moveTeamsWithoutMembersToOrg({
@@ -841,6 +871,10 @@ async function dbRemoveUserFromOrg({
},
},
});
await ProfileRepository.deleteMany({
userIds: [userToRemoveFromOrg.id],
});
}
async function removeMembership({
@@ -121,7 +121,9 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
return {
name: member.name,
id: member.id,
avatarUrl: member.avatarUrl,
bio: member.bio,
profile: member.profile,
subteams: member.subteams,
username: member.username,
accepted: member.accepted,
@@ -729,9 +729,9 @@ const EventTypeListHeading = ({
return (
<div className="mb-4 flex items-center space-x-2">
<Avatar
alt={profile?.name || ""}
alt={profile.name || ""}
href={teamId ? `/settings/teams/${teamId}/profile` : "/settings/my-account/profile"}
imageSrc={`${bookerUrl}${teamId ? "/team" : ""}/${profile.slug}/avatar.png`}
imageSrc={profile.image}
size="md"
className="mt-1 inline-flex justify-center"
/>
@@ -739,7 +739,7 @@ const EventTypeListHeading = ({
<Link
href={teamId ? `/settings/teams/${teamId}/profile` : "/settings/my-account/profile"}
className="text-emphasis font-bold">
{profile?.name || ""}
{profile.name || ""}
</Link>
{membershipCount && teamId && (
<span className="text-subtle relative -top-px me-2 ms-2 text-xs">
@@ -751,13 +751,13 @@ const EventTypeListHeading = ({
</Link>
</span>
)}
{profile?.slug && (
{profile.slug && (
<Link href={`${bookerUrl}/${profile.slug}`} className="text-subtle block text-xs">
{`${bookerUrl.replace("https://", "").replace("http://", "")}/${profile.slug}`}
</Link>
)}
</div>
{!profile?.slug && !!teamId && (
{!profile.slug && !!teamId && (
<button onClick={() => publishTeamMutation.mutate({ teamId })}>
<Badge variant="gray" className="-ml-2 mb-1">
{t("upgrade")}
@@ -816,7 +816,7 @@ const CTA = ({ data }: { data: GetByViewerResponse }) => {
const Actions = () => {
return (
<div className="hidden items-center md:flex">
<TeamsFilter popoverTriggerClassNames="mb-0" showVerticalDivider={true} />
<TeamsFilter useProfileFilter popoverTriggerClassNames="mb-0" showVerticalDivider={true} />
</div>
);
};
@@ -853,7 +853,6 @@ const Main = ({
}) => {
const isMobile = useMediaQuery("(max-width: 768px)");
const searchParams = useCompatSearchParams();
const orgBranding = useOrgBranding();
if (!data || status === "pending") {
return <SkeletonLoader />;
@@ -4,23 +4,26 @@ import { encode } from "querystring";
import type { z } from "zod";
import { handleUserRedirection } from "@calcom/features/booking-redirect/handle-user";
import { getSlugOrRequestedSlug } from "@calcom/features/ee/organizations/lib/orgDomains";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import { DEFAULT_DARK_BRAND_COLOR, DEFAULT_LIGHT_BRAND_COLOR } from "@calcom/lib/constants";
import { getUsernameList } from "@calcom/lib/defaultEvents";
import logger from "@calcom/lib/logger";
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
import { safeStringify } from "@calcom/lib/safeStringify";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { stripMarkdown } from "@calcom/lib/stripMarkdown";
import prisma from "@calcom/prisma";
import { RedirectType, type EventType, type User } from "@calcom/prisma/client";
import { baseEventTypeSelect } from "@calcom/prisma/selects";
import { EventTypeMetaDataSchema, teamMetadataSchema } from "@calcom/prisma/zod-utils";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import type { UserProfile } from "@calcom/types/UserProfile";
import { getTemporaryOrgRedirect } from "@lib/getTemporaryOrgRedirect";
import type { EmbedProps } from "@lib/withEmbedSsr";
import { ssrInit } from "@server/lib/ssr";
const log = logger.getSubLogger({ prefix: ["[[pages/[user]]]"] });
export type UserPageProps = {
trpcState: DehydratedState;
profile: {
@@ -33,11 +36,13 @@ export type UserPageProps = {
requestedSlug: string | null;
slug: string | null;
id: number | null;
};
} | null;
allowSEOIndexing: boolean;
username: string | null;
};
users: Pick<User, "away" | "name" | "username" | "bio" | "verified" | "avatarUrl">[];
users: (Pick<User, "away" | "name" | "username" | "bio" | "verified" | "avatarUrl"> & {
profile: UserProfile;
})[];
themeBasis: string | null;
markdownStrippedBio: string;
safeBio: string;
@@ -106,7 +111,7 @@ export const getEventTypesWithHiddenFromDB = async (userId: number) => {
return eventTypes.reduce<typeof eventTypes>((eventTypes, eventType) => {
const parsedMetadata = EventTypeMetaDataSchema.safeParse(eventType.metadata);
if (!parsedMetadata.success) {
logger.error(parsedMetadata.error);
log.error(parsedMetadata.error);
return eventTypes;
}
eventTypes.push({
@@ -124,7 +129,7 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
const isOrgContext = isValidOrgDomain && currentOrgDomain;
const dataFetchStart = Date.now();
let outOfOffice = false;
const isDynamicGroup = usernameList.length > 1;
if (usernameList.length === 1) {
const result = await handleUserRedirection({ username: usernameList[0] });
if (result && result.outOfOffice) {
@@ -136,6 +141,7 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
}
if (!isOrgContext) {
// If there is no org context, see if some redirect is setup due to org migration
const redirect = await getTemporaryOrgRedirect({
slugs: usernameList,
redirectType: RedirectType.User,
@@ -148,51 +154,22 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
}
}
const usersWithoutAvatar = await prisma.user.findMany({
where: {
username: {
in: usernameList,
},
organization: isOrgContext ? getSlugOrRequestedSlug(currentOrgDomain) : null,
},
select: {
id: true,
username: true,
email: true,
name: true,
bio: true,
metadata: true,
brandColor: true,
darkBrandColor: true,
avatarUrl: true,
organizationId: true,
organization: {
select: {
slug: true,
name: true,
metadata: true,
},
},
theme: true,
away: true,
verified: true,
allowDynamicBooking: true,
allowSEOIndexing: true,
},
const usersInOrgContext = await UserRepository.findUsersByUsername({
usernameList,
orgSlug: isValidOrgDomain ? currentOrgDomain : null,
});
const users = usersWithoutAvatar.map((user) => ({
...user,
organization: {
...user.organization,
metadata: user.organization?.metadata ? teamMetadataSchema.parse(user.organization.metadata) : null,
},
avatar: `/${user.username}/avatar.png`,
}));
const usersWithoutAvatar = usersInOrgContext.map((user) => {
const { avatar: _1, ...rest } = user;
return rest;
});
const isDynamicGroup = usersWithoutAvatar.length > 1;
log.debug(safeStringify({ usersInOrgContext, isValidOrgDomain, currentOrgDomain, isDynamicGroup }));
if (isDynamicGroup) {
const destinationUrl = `/${usernameList.join("+")}/dynamic`;
logger.debug(`Dynamic group detected, redirecting to ${destinationUrl}`);
log.debug(`Dynamic group detected, redirecting to ${destinationUrl}`);
return {
redirect: {
permanent: false,
@@ -206,7 +183,18 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
};
}
if (!users.length || (!isValidOrgDomain && !users.some((user) => user.organizationId === null))) {
const users = usersWithoutAvatar.map((user) => ({
...user,
avatar: `/${user.username}/avatar.png`,
}));
const isNonOrgUser = (user: { profile: UserProfile }) => {
return !user.profile?.organization;
};
const isThereAnyNonOrgUser = users.some(isNonOrgUser);
if (!users.length || (!isValidOrgDomain && !isThereAnyNonOrgUser)) {
return {
notFound: true,
} as {
@@ -225,11 +213,7 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
darkBrandColor: user.darkBrandColor ?? DEFAULT_DARK_BRAND_COLOR,
allowSEOIndexing: user.allowSEOIndexing ?? true,
username: user.username,
organization: {
id: user.organizationId,
slug: user.organization?.slug ?? null,
requestedSlug: user.organization?.metadata?.requestedSlug ?? null,
},
organization: user.profile.organization,
};
const eventTypesWithHidden = await getEventTypesWithHiddenFromDB(user.id);
@@ -248,7 +232,7 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
// if profile only has one public event-type, redirect to it
if (eventTypes.length === 1 && context.query.redirect !== "false" && !outOfOffice) {
// Redirect but don't change the URL
const urlDestination = `/${user.username}/${eventTypes[0].slug}`;
const urlDestination = `/${user.profile.username}/${eventTypes[0].slug}`;
const { query } = context;
const urlQuery = new URLSearchParams(encode(query));
@@ -263,7 +247,7 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
const safeBio = markdownToSafeHTML(user.bio) || "";
const markdownStrippedBio = stripMarkdown(user?.bio || "");
const org = usersWithoutAvatar[0].organization;
const org = usersWithoutAvatar[0].profile.organization;
return {
props: {
@@ -274,6 +258,7 @@ export const getServerSideProps: GetServerSideProps<UserPageProps> = async (cont
avatarUrl: user.avatarUrl,
away: usernameList.length === 1 ? outOfOffice : user.away,
verified: user.verified,
profile: user.profile,
})),
entity: {
isUnpublished: org?.slug === null,
@@ -111,19 +111,11 @@ export function UserPage(props: InferGetServerSidePropsType<typeof getServerSide
<UserAvatar
size="xl"
user={{
organizationId: profile.organization?.id,
avatarUrl: user.avatarUrl,
profile: user.profile,
name: profile.name,
username: profile.username,
}}
organization={
profile.organization?.id
? {
id: profile.organization.id,
slug: profile.organization.slug,
requestedSlug: null,
}
: null
}
/>
<h1 className="font-cal text-emphasis my-1 text-3xl" data-testid="name-title">
{profile.name}
@@ -5,10 +5,10 @@ import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { handleTypeRedirection } from "@calcom/features/booking-redirect/handle-type";
import { getBookingForReschedule, getBookingForSeatedEvent } from "@calcom/features/bookings/lib/get-booking";
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import { orgDomainConfig, userOrgQuery } from "@calcom/features/ee/organizations/lib/orgDomains";
import { orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import { getUsernameList } from "@calcom/lib/defaultEvents";
import { UserRepository } from "@calcom/lib/server/repository/user";
import slugify from "@calcom/lib/slugify";
import prisma from "@calcom/prisma";
import { RedirectType } from "@calcom/prisma/client";
import { getTemporaryOrgRedirect } from "@lib/getTemporaryOrgRedirect";
@@ -39,22 +39,13 @@ async function getDynamicGroupPageProps(context: GetServerSidePropsContext) {
}
}
const users = await prisma.user.findMany({
where: {
username: {
in: usernames,
},
organization: isValidOrgDomain
? {
slug: currentOrgDomain,
}
: null,
},
select: {
allowDynamicBooking: true,
},
const usersInOrgContext = await UserRepository.findUsersByUsername({
usernameList: usernames,
orgSlug: isValidOrgDomain ? currentOrgDomain : null,
});
const users = usersInOrgContext;
if (!users.length) {
return {
notFound: true,
@@ -129,16 +120,9 @@ async function getUserPageProps(context: GetServerSidePropsContext) {
const { ssrInit } = await import("@server/lib/ssr");
const ssr = await ssrInit(context);
const user = await prisma.user.findFirst({
where: {
username,
organization: userOrgQuery(context.req, context.params?.orgSlug),
},
select: {
id: true,
hideBranding: true,
allowSEOIndexing: true,
},
const [user] = await UserRepository.findUsersByUsername({
usernameList: [username],
orgSlug: isValidOrgDomain ? currentOrgDomain : null,
});
if (!user) {
@@ -3,6 +3,7 @@ import type { GetServerSidePropsContext } from "next";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getCalVideoReference } from "@calcom/features/get-cal-video-reference";
import { UserRepository } from "@calcom/lib/server/repository/user";
import prisma, { bookingMinimalSelect } from "@calcom/prisma";
import { type inferSSRProps } from "@lib/types/inferSSRProps";
@@ -33,11 +34,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
timeZone: true,
name: true,
email: true,
organization: {
select: {
calVideoLogo: true,
},
},
username: true,
},
},
references: {
@@ -63,6 +60,14 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
};
}
const profile = booking.user
? (
await UserRepository.enrichUserWithItsProfile({
user: booking.user,
})
).profile
: null;
//daily.co calls have a 60 minute exit buffer when a user enters a call when it's not available it will trigger the modals
const now = new Date();
const exitDate = new Date(now.getTime() - 60 * 60 * 1000);
@@ -102,6 +107,12 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
booking: {
...bookingObj,
...(bookingObj.description && { description: md.render(bookingObj.description) }),
user: bookingObj.user
? {
...bookingObj.user,
organization: profile?.organization,
}
: bookingObj.user,
},
trpcState: ssr.dehydrate(),
},
+10
View File
@@ -8,6 +8,7 @@ import { UserPermissionRole } from "@calcom/prisma/enums";
import { TRPCError } from "@calcom/trpc/server";
import { createContext } from "@calcom/trpc/server/createContext";
import { bookingsRouter } from "@calcom/trpc/server/routers/viewer/bookings/_router";
import type { UserProfile } from "@calcom/types/UserProfile";
enum DirectAction {
ACCEPT = "accept",
@@ -46,7 +47,16 @@ async function handler(req: NextApiRequest, res: NextApiResponse<Response>) {
id: userId,
username: "" /* Not used in this context */,
role: UserPermissionRole.USER,
/* Not used in this context */
profile: {
id: null,
organizationId: null,
organization: null,
username: "",
upId: "",
} satisfies UserProfile,
},
upId: "",
hasValidLicense: true,
expires: "" /* Not used in this context */,
};
+19 -3
View File
@@ -42,14 +42,30 @@ async function getIdentityData(req: NextApiRequest) {
: null;
if (username) {
const user = await prisma.user.findFirst({
const users = await prisma.user.findMany({
where: {
username,
organization: orgQuery,
...(orgQuery
? {
profiles: {
some: {
username,
organization: orgQuery,
},
},
}
: {
username,
// If a user is moved, it isn't actually available outside of the organization. So, for non-org domain check for movedToProfileId
movedToProfileId: null,
}),
},
select: { avatar: true, email: true },
});
if (users.length > 1) {
throw new Error(`More than one user found for username "${username}"`);
}
const [user] = users;
return {
name: username,
email: user?.email,
@@ -230,7 +230,10 @@ const ProfileView = () => {
const defaultValues = {
username: user.username || "",
avatar: getUserAvatarUrl(user),
avatar: getUserAvatarUrl({
...user,
profile: user.profile,
}),
name: user.name || "",
email: user.email || "",
bio: user.bio || "",
@@ -443,20 +446,14 @@ const ProfileForm = ({
const organization =
userOrganization && userOrganization.id
? {
...(userOrganization as Ensure<typeof user.organization, "id">),
...(userOrganization as Ensure<NonNullable<typeof user.organization>, "id">),
slug: userOrganization.slug || null,
requestedSlug: userOrganization.metadata?.requestedSlug || null,
}
: null;
return (
<>
<UserAvatar
data-testid="profile-upload-avatar"
previewSrc={value}
size="lg"
user={user}
organization={organization}
/>
<UserAvatar data-testid="profile-upload-avatar" previewSrc={value} size="lg" user={user} />
<div className="ms-4">
<h2 className="mb-2 text-sm font-medium">{t("profile_picture")}</h2>
<div className="flex gap-2">
+1 -1
View File
@@ -30,7 +30,7 @@ export const createOrgsFixture = (page: Page) => {
};
};
async function createOrgInDb({
export async function createOrgInDb({
name,
slug,
requestedSlug,
+92 -26
View File
@@ -4,10 +4,12 @@ import type { Team } from "@prisma/client";
import { Prisma as PrismaType } from "@prisma/client";
import { hashSync as hash } from "bcryptjs";
import { uuid } from "short-uuid";
import { v4 } from "uuid";
import stripe from "@calcom/features/ee/payments/server/stripe";
import { DEFAULT_SCHEDULE, getAvailabilityFromSchedule } from "@calcom/lib/availability";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import { prisma } from "@calcom/prisma";
import { MembershipRole, SchedulingType, TimeUnit, WorkflowTriggerEvents } from "@calcom/prisma/enums";
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
@@ -137,7 +139,21 @@ const createTeamAndAddUser = async (
await createTeamWorkflow(user, team);
data.children = { connect: [{ id: team.id }] };
}
data.orgUsers = isOrg ? { connect: [{ id: user.id }] } : undefined;
data.orgProfiles = isOrg
? {
create: [
{
uid: ProfileRepository.generateProfileUid(),
username: user.username ?? user.email.split("@")[0],
user: {
connect: {
id: user.id,
},
},
},
],
}
: undefined;
data.parent = organizationId ? { connect: { id: organizationId } } : undefined;
const team = await prisma.team.create({
data,
@@ -181,7 +197,11 @@ export const createUsersFixture = (
};
},
create: async (
opts?: CustomUserOpts | null,
opts?:
| (CustomUserOpts & {
organizationId?: number | null;
})
| null,
scenario: {
seedRoutingForms?: boolean;
hasTeam?: true;
@@ -199,6 +219,9 @@ export const createUsersFixture = (
) => {
const _user = await prisma.user.create({
data: createUser(workerInfo, opts),
include: {
profiles: true,
},
});
let defaultEventTypes: SupportedTestEventTypes[] = [
@@ -212,6 +235,9 @@ export const createUsersFixture = (
for (const eventTypeData of defaultEventTypes) {
eventTypeData.owner = { connect: { id: _user.id } };
eventTypeData.users = { connect: { id: _user.id } };
if (_user.profiles[0]) {
eventTypeData.profile = { connect: { id: _user.profiles[0].id } };
}
await prisma.eventType.create({
data: eventTypeData,
});
@@ -370,7 +396,7 @@ export const createUsersFixture = (
const teamEvent = await createTeamEventType(user, team, scenario);
if (scenario.teammates) {
// Create Teammate users
const teamMatesIds = [];
const teamMates = [];
for (const teammateObj of scenario.teammates) {
const teamUser = await prisma.user.create({
data: createUser(workerInfo, teammateObj),
@@ -402,19 +428,49 @@ export const createUsersFixture = (
}),
store.page
);
teamMatesIds.push(teamUser.id);
teamMates.push(teamUser);
store.users.push(teammateFixture);
}
// Add Teammates to OrgUsers
if (scenario.isOrg) {
const orgProfilesCreate = teamMates
.map((teamUser) => ({
user: {
connect: {
id: teamUser.id,
},
},
uid: v4(),
username: teamUser.username || teamUser.email.split("@")[0],
}))
.concat([
{
user: { connect: { id: user.id } },
uid: v4(),
username: user.username || user.email.split("@")[0],
},
]);
const existingProfiles = await prisma.profile.findMany({
where: {
userId: _user.id,
},
});
await prisma.team.update({
where: {
id: team.id,
},
data: {
orgUsers: {
connect: teamMatesIds.map((userId) => ({ id: userId })).concat([{ id: user.id }]),
},
orgProfiles: _user.profiles.length
? {
connect: _user.profiles.map((profile) => ({ id: profile.id })),
}
: {
create: orgProfilesCreate.filter(
(profile) => !existingProfiles.map((p) => p.userId).includes(profile.user.connect.id)
),
},
},
});
}
@@ -615,7 +671,11 @@ type CustomUserOpts = Partial<Pick<Prisma.User, CustomUserOptsKeys>> & {
// creates the actual user in the db.
const createUser = (
workerInfo: WorkerInfo,
opts?: CustomUserOpts | null
opts?:
| (CustomUserOpts & {
organizationId?: number | null;
})
| null
): PrismaType.UserUncheckedCreateInput => {
// build a unique name for our user
const uname =
@@ -666,25 +726,31 @@ const createUser = (
throw new Error("Missing role for user in organization");
}
return {
organizationId: organizationId || null,
...(organizationId
? {
teams: {
// Create membership
create: [
{
team: {
connect: {
id: organizationId,
},
},
accepted: true,
role: MembershipRole.ADMIN,
},
],
profiles: {
create: {
uid: ProfileRepository.generateProfileUid(),
username: uname,
organization: {
connect: {
id: organizationId,
},
}
: null),
},
},
},
teams: {
// Create membership
create: [
{
team: {
connect: {
id: organizationId,
},
},
accepted: true,
role: MembershipRole.ADMIN,
},
],
},
};
}
};
@@ -286,7 +286,7 @@ test.describe("Organization", () => {
page,
emails,
invitedUserEmail,
`${team.name}'s admin invited you to join the organization ${org.name} on Cal.com`,
`${team.name}'s admin invited you to join the team ${team.name} of organization ${org.name} on Cal.com`,
"signup?token"
);
@@ -1490,6 +1490,7 @@
"password_updated": "Password updated!",
"pending_payment": "Pending payment",
"pending_invites": "Pending Invites",
"pending_organization_invites": "Pending Organization Invites",
"not_on_cal": "Not on {{appName}}",
"no_calendar_installed": "No calendar installed",
"no_calendar_installed_description": "You have not yet connected any of your calendars",
@@ -269,7 +269,20 @@ function getTrpcHandlerData({
...getSampleUserInSession(),
...user,
avatarUrl: user.avatarUrl || null,
} satisfies TrpcSessionUser,
profile: {
upId: "",
id: 1,
name: "",
avatarUrl: "",
startTime: 0,
endTime: 0,
username: user.username || "",
organizationId: null,
organization: null,
bufferTime: 5,
avatar: null,
},
} as unknown as NonNullable<TrpcSessionUser>,
},
input: input,
};
@@ -12,6 +12,7 @@ it("correctly handles 1 day", async () => {
endTime: new Date(Date.UTC(1970, 1, 1, 17, 0, 0, 0)),
date: null,
scheduleId: 1,
profileId: null,
};
const result = availabilityAsString(availability, {
@@ -32,6 +33,7 @@ it("correctly handles all days", async () => {
endTime: new Date(Date.UTC(1970, 1, 1, 17, 0, 0, 0)),
date: null,
scheduleId: 1,
profileId: null,
};
const result = availabilityAsString(availability, {
@@ -52,6 +54,7 @@ it("correctly handles staggered days", async () => {
endTime: new Date(Date.UTC(1970, 1, 1, 17, 0, 0, 0)),
date: null,
scheduleId: 1,
profileId: null,
};
const result = availabilityAsString(availability, {
@@ -72,6 +75,7 @@ it("correctly produces days and times - 12 hours", async () => {
endTime: new Date(Date.UTC(1970, 1, 1, 17, 0, 0, 0)),
date: null,
scheduleId: 1,
profileId: null,
};
const result = availabilityAsString(availability, {
@@ -92,6 +96,7 @@ it("correctly produces days and times - 24 hours", async () => {
endTime: new Date(Date.UTC(1970, 1, 1, 17, 0, 0, 0)),
date: null,
scheduleId: 1,
profileId: null,
};
const result = availabilityAsString(availability, {
@@ -41,6 +41,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(result.newUserIds).toEqual(undefined);
expect(result.oldUserIds).toEqual(undefined);
@@ -60,6 +61,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(result.newUserIds).toEqual(undefined);
expect(result.oldUserIds).toEqual(undefined);
@@ -85,6 +87,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(result.newUserIds).toEqual(undefined);
expect(result.oldUserIds).toEqual(undefined);
@@ -120,6 +123,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(prismaMock.eventType.create).toHaveBeenCalledWith({
data: {
@@ -166,6 +170,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: "somestring",
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(prismaMock.eventType.update).toHaveBeenCalledWith({
data: {
@@ -199,6 +204,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(result.newUserIds).toEqual([]);
expect(result.oldUserIds).toEqual([]);
@@ -223,6 +229,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
// Have been called
expect(result.newUserIds).toEqual([5]);
@@ -259,6 +266,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(prismaMock.eventType.create).toHaveBeenCalledWith({
data: {
@@ -305,6 +313,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(prismaMock.eventType.update).toHaveBeenCalledWith({
data: {
@@ -364,6 +373,7 @@ describe("handleChildrenEventTypes", () => {
hashedLink: undefined,
connectedLink: null,
prisma: prismaMock,
profileId: null,
});
expect(prismaMock.eventType.create).toHaveBeenCalledWith({
data: {
@@ -16,6 +16,7 @@ import { weekdayToWeekIndex, type WeekDays } from "@calcom/lib/date-fns";
import type { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { safeStringify } from "@calcom/lib/safeStringify";
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
import type { WorkflowActions, WorkflowTemplates, WorkflowTriggerEvents } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums";
import type { BookingStatus } from "@calcom/prisma/enums";
@@ -104,6 +105,7 @@ type InputUser = Omit<typeof TestData.users.example, "defaultScheduleId"> & {
}[];
destinationCalendar?: Prisma.DestinationCalendarCreateInput;
weekStart?: string;
profiles?: Prisma.ProfileUncheckedCreateWithoutUserInput[];
};
export type InputEventType = {
@@ -455,6 +457,7 @@ async function addUsersToDb(users: (Prisma.UserCreateInput & { schedules: Prisma
include: {
credentials: true,
teams: true,
profiles: true,
schedules: {
include: {
availability: true,
@@ -545,6 +548,15 @@ async function addUsers(users: InputUser[]) {
},
};
}
if (user.profiles) {
newUser.profiles = {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error Not sure why this is not working
createMany: {
data: user.profiles,
},
};
}
prismaUsersCreate.push(newUser);
}
@@ -937,6 +949,7 @@ export function getOrganizer({
weekStart,
teams,
organizationId,
profiles: [],
metadata,
};
}
@@ -965,8 +978,18 @@ export function getScenarioData(
) {
const users = [organizer, ...usersApartFromOrganizer];
if (org) {
const orgId = org.id;
if (!orgId) {
throw new Error("If org is specified org.id is required");
}
users.forEach((user) => {
user.organizationId = org.id;
user.profiles = [
{
organizationId: orgId,
username: user.username || "",
uid: ProfileRepository.generateProfileUid(),
},
];
});
}
@@ -19,6 +19,7 @@ export function getMockRequestDataForBooking({
}: {
data: Partial<ReturnType<typeof getBasicMockRequestDataForBooking>> & {
eventTypeId: number;
user?: string;
rescheduleUid?: string;
bookingUid?: string;
recurringEventId?: string;
@@ -8,7 +8,10 @@ export const getSampleUserInSession = function () {
organization: {
isOrgAdmin: false,
metadata: null,
id: 1,
requestedSlug: null,
},
profile: null,
defaultScheduleId: null,
name: "",
defaultBookerLayouts: null,