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

@@ -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 -2
View File
@@ -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}`}
/>