feat: platform team event-types (#15928)

* fix: dont check OrganizationSettings.orgAutoAcceptEmail uniqueness for platform teams

* feat: display organizationId in OAuthClientCard

* feat: ApiAuthStrategy handle oauth credentials

* refactor: clean up ApiAuthStrategy test

* refactor: use ApiAuthGuard in OauthClientsUsersController and OAuthFlowController

* fix: copying org id

* refactor: more specific error message when api auth

* refactor: auto accept team creator membership

* feat: useTeamEventType and useTeamEventTypes hooks

* refactor: make team event-types public & searchable by eventSlug

* feat: include host name in team event-types hosts response

* fix: isFixed=true by default for COLLECTIVE event hosts

* fix: useTeamEventType eventSlug access

* feat: BookerPlatformWrapper enable team events by exposting orgId and teamId props

* refactor: provide orgId in atoms context

* refactor: use orgId from context in team event-types hooks

* refactor: return teams in useMe

* chore: examples app teams setup

* Revert "refactor: return teams in useMe"

This reverts commit de992ddc9af6ee9a2111938069f5b9c34cc2d8ea.

* Revert "chore: examples app teams setup"

This reverts commit 0766aa21acc25efa2361d38c3f87ddba773a0245.

* feat: useTeams hook

* chore: setup examples app with team event-type

* fix: small fixes

* swagger

* Revert "refactor: provide orgId in atoms context"

This reverts commit f053a498ee6f8fa8ece5ec8d8630c59eda8873e3.

* feat: orgId in atoms context

* feat: PlatformBilling guard

* chore: delete test of the deleted oauth-client-credentials.guard

* refactor: org event-types collective events isFixed always true and priority medium

* refactor: org event-types COLLECTIVE response ignore isFixed and priority as they are same

* fix: organizations event-types e2e

* fix: billing guard

* refactor: tests cleanup

* fix: platform plan guard spec

* refactor: e2e test cleanup

* seed error if not team

* refactor: rename authenticateApiKey to authenticateBearerToken

* refactor: transforming response hosts

* refactor: rename findUniqueByMatchingAutoAcceptEmail to findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail

* refactor: rename findUniqueByMatchingAutoAcceptEmail to findUniqueNonPlatformOrgsByMatchingAutoAcceptEmail

---------

Co-authored-by: Morgan <[email protected]>
This commit is contained in:
Lauris SkraucisandMorgan authored and GitHub committed 2024-07-30 16:58:39 +02:00
1 parent 06bb7055ac
commit 2f946fc5da
59 files changed
+1515 -412

No files matched your search

@@ -1,3 +1,4 @@
NEXT_PUBLIC_X_CAL_ID=""
X_CAL_SECRET_KEY=""
NEXT_PUBLIC_CALCOM_API_URL="http://localhost:5555/api/v2"
ORGANIZATION_ID=
@@ -26,6 +26,9 @@ function generateRandomEmail() {
return `${randomLocalPart}@${randomDomain}`;
}
// note(Lauris): needed because useEffect kicks in twice creating 2 parallel requests
let seeding = false;
export default function App({ Component, pageProps }: AppProps) {
const [accessToken, setAccessToken] = useState("");
const [email, setUserEmail] = useState("");
@@ -47,16 +50,21 @@ export default function App({ Component, pageProps }: AppProps) {
}, []);
useEffect(() => {
const randomEmail = generateRandomEmail();
fetch("/api/managed-user", {
method: "POST",
body: JSON.stringify({ email: randomEmail }),
}).then(async (res) => {
const data = await res.json();
setAccessToken(data.accessToken);
setUserEmail(data.email);
setUsername(data.username);
});
const randomEmailOne = generateRandomEmail();
const randomEmailTwo = generateRandomEmail();
if (!seeding) {
seeding = true;
fetch("/api/managed-user", {
method: "POST",
body: JSON.stringify({ emails: [randomEmailOne, randomEmailTwo] }),
}).then(async (res) => {
const data = await res.json();
setAccessToken(data.accessToken);
setUserEmail(data.email);
setUsername(data.username);
});
}
}, []);
useEffect(() => {
if (!!selectedUser) {
@@ -1,7 +1,7 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { X_CAL_SECRET_KEY } from "@calcom/platform-constants";
import { X_CAL_CLIENT_ID, X_CAL_SECRET_KEY } from "@calcom/platform-constants";
import prisma from "../../lib/prismaClient";
@@ -14,7 +14,9 @@ type Data = {
// example endpoint to create a managed cal.com user
export default async function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
const { email } = JSON.parse(req.body);
const { emails } = JSON.parse(req.body);
const emailOne = emails[0];
const emailTwo = emails[1];
const existingUser = await prisma.user.findFirst({ orderBy: { createdAt: "desc" } });
if (existingUser && existingUser.calcomUserId) {
@@ -25,11 +27,19 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<
accessToken: existingUser.accessToken ?? "",
});
}
const localUser = await prisma.user.create({
const localUserOne = await prisma.user.create({
data: {
email,
email: emailOne,
},
});
const localUserTwo = await prisma.user.create({
data: {
email: emailTwo,
},
});
const response = await fetch(
// eslint-disable-next-line turbo/no-undeclared-env-vars
`${process.env.NEXT_PUBLIC_CALCOM_API_URL ?? ""}/oauth-clients/${process.env.NEXT_PUBLIC_X_CAL_ID}/users`,
@@ -42,11 +52,12 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<
origin: "http://localhost:4321",
},
body: JSON.stringify({
email,
email: emailOne,
name: "John Jones",
}),
}
);
const body = await response.json();
await prisma.user.update({
data: {
@@ -55,9 +66,55 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<
calcomUserId: body.data?.user.id,
calcomUsername: (body.data?.user.username as string) ?? "",
},
where: { id: localUser.id },
where: { id: localUserOne.id },
});
const responseTwo = await fetch(
// eslint-disable-next-line turbo/no-undeclared-env-vars
`${process.env.NEXT_PUBLIC_CALCOM_API_URL ?? ""}/oauth-clients/${process.env.NEXT_PUBLIC_X_CAL_ID}/users`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
// eslint-disable-next-line turbo/no-undeclared-env-vars
[X_CAL_SECRET_KEY]: process.env.X_CAL_SECRET_KEY ?? "",
origin: "http://localhost:4321",
},
body: JSON.stringify({
email: emailTwo,
name: "Jane Doe",
}),
}
);
const bodyTwo = await responseTwo.json();
await prisma.user.update({
data: {
refreshToken: (bodyTwo.data?.refreshToken as string) ?? "",
accessToken: (bodyTwo.data?.accessToken as string) ?? "",
calcomUserId: bodyTwo.data?.user.id,
calcomUsername: (bodyTwo.data?.user.username as string) ?? "",
},
where: { id: localUserTwo.id },
});
await createDefaultSchedule(body.data?.accessToken as string);
await createDefaultSchedule(bodyTwo.data?.accessToken as string);
// eslint-disable-next-line turbo/no-undeclared-env-vars
const organizationId = process.env.ORGANIZATION_ID;
if (!organizationId) {
throw new Error("Organization ID is not set");
}
const team = await createTeam(+organizationId, "Team Doe");
if (!team) {
throw new Error("Failed to create team. Probably your platform team does not have required plan.");
}
await createMembership(+organizationId, team.id, body.data?.user.id);
await createMembership(+organizationId, team.id, bodyTwo.data?.user.id);
await createCollectiveEventType(+organizationId, team.id, [body.data?.user.id, bodyTwo.data?.user.id]);
return res.status(200).json({
id: body?.data?.user?.id,
email: (body.data?.user.email as string) ?? "",
@@ -66,6 +123,77 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse<
});
}
async function createTeam(orgId: number, name: string) {
const response = await fetch(
// eslint-disable-next-line turbo/no-undeclared-env-vars
`${process.env.NEXT_PUBLIC_CALCOM_API_URL ?? ""}/organizations/${orgId}/teams`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
// eslint-disable-next-line turbo/no-undeclared-env-vars
[X_CAL_SECRET_KEY]: process.env.X_CAL_SECRET_KEY ?? "",
// eslint-disable-next-line turbo/no-undeclared-env-vars
[X_CAL_CLIENT_ID]: process.env.NEXT_PUBLIC_X_CAL_ID ?? "",
origin: "http://localhost:4321",
},
body: JSON.stringify({
name,
}),
}
);
const body = await response.json();
return body.data;
}
async function createMembership(orgId: number, teamId: number, userId: number) {
await fetch(
// eslint-disable-next-line turbo/no-undeclared-env-vars
`${process.env.NEXT_PUBLIC_CALCOM_API_URL ?? ""}/organizations/${orgId}/teams/${teamId}/memberships`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
// eslint-disable-next-line turbo/no-undeclared-env-vars
[X_CAL_SECRET_KEY]: process.env.X_CAL_SECRET_KEY ?? "",
// eslint-disable-next-line turbo/no-undeclared-env-vars
[X_CAL_CLIENT_ID]: process.env.NEXT_PUBLIC_X_CAL_ID ?? "",
origin: "http://localhost:4321",
},
body: JSON.stringify({
userId,
accepted: true,
}),
}
);
}
async function createCollectiveEventType(orgId: number, teamId: number, userIds: number[]) {
await fetch(
// eslint-disable-next-line turbo/no-undeclared-env-vars
`${process.env.NEXT_PUBLIC_CALCOM_API_URL ?? ""}/organizations/${orgId}/teams/${teamId}/event-types`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
// eslint-disable-next-line turbo/no-undeclared-env-vars
[X_CAL_SECRET_KEY]: process.env.X_CAL_SECRET_KEY ?? "",
// eslint-disable-next-line turbo/no-undeclared-env-vars
[X_CAL_CLIENT_ID]: process.env.NEXT_PUBLIC_X_CAL_ID ?? "",
origin: "http://localhost:4321",
},
body: JSON.stringify({
lengthInMinutes: 60,
title: "Doe collective",
slug: "doe-collective",
schedulingType: "COLLECTIVE",
hosts: userIds.map((userId) => ({ userId })),
}),
}
);
}
async function createDefaultSchedule(accessToken: string) {
const name = "Default Schedule";
const timeZone = "Europe/London";
@@ -4,7 +4,7 @@ import { Inter } from "next/font/google";
import { useRouter } from "next/router";
import { useState } from "react";
import { Booker, useEventTypes } from "@calcom/atoms";
import { Booker, useEventTypes, useTeamEventTypes, useTeams } from "@calcom/atoms";
const inter = Inter({ subsets: ["latin"] });
@@ -12,8 +12,11 @@ export default function Bookings(props: { calUsername: string; calEmail: string
const [bookingTitle, setBookingTitle] = useState<string | null>(null);
const [eventTypeSlug, setEventTypeSlug] = useState<string | null>(null);
const [eventTypeDuration, setEventTypeDuration] = useState<number | null>(null);
const [isTeamEvent, setIsTeamEvent] = useState<boolean>(false);
const router = useRouter();
const { isLoading: isLoadingEvents, data: eventTypes } = useEventTypes(props.calUsername);
const { data: teams } = useTeams();
const { isLoading: isLoadingTeamEvents, data: teamEventTypes } = useTeamEventTypes(teams?.[0]?.id || 0);
const rescheduleUid = (router.query.rescheduleUid as string) ?? "";
const eventTypeSlugQueryParam = (router.query.eventTypeSlug as string) ?? "";
@@ -28,6 +31,7 @@ export default function Bookings(props: { calUsername: string; calEmail: string
{!isLoadingEvents && !eventTypeSlug && Boolean(eventTypes?.length) && !rescheduleUid && (
<div className="flex flex-col gap-4">
<h1>User event types</h1>
{eventTypes?.map(
(event: { id: number; slug: string; title: string; lengthInMinutes: number }) => {
const formatEventSlug = event.slug
@@ -40,6 +44,36 @@ export default function Bookings(props: { calUsername: string; calEmail: string
onClick={() => {
setEventTypeSlug(event.slug);
setEventTypeDuration(event.lengthInMinutes);
setIsTeamEvent(false);
}}
className="mx-10 w-[80vw] cursor-pointer rounded-md border-[0.8px] border-black px-10 py-4"
key={event.id}>
<h1 className="text-lg font-semibold">{formatEventSlug}</h1>
<p>{`/${event.slug}`}</p>
<span className="border-none bg-gray-800 px-2 text-white">{event?.lengthInMinutes}</span>
</div>
);
}
)}
</div>
)}
{!isLoadingTeamEvents && !eventTypeSlug && Boolean(teamEventTypes?.length) && !rescheduleUid && (
<div className="flex flex-col gap-4">
<h1>Team event types</h1>
{teamEventTypes?.map(
(event: { id: number; slug: string; title: string; lengthInMinutes: number }) => {
const formatEventSlug = event.slug
.split("-")
.map((item) => `${item[0].toLocaleUpperCase()}${item.slice(1)}`)
.join(" ");
return (
<div
onClick={() => {
setEventTypeSlug(event.slug);
setEventTypeDuration(event.lengthInMinutes);
setIsTeamEvent(true);
}}
className="mx-10 w-[80vw] cursor-pointer rounded-md border-[0.8px] border-black px-10 py-4"
key={event.id}>
@@ -54,28 +88,33 @@ export default function Bookings(props: { calUsername: string; calEmail: string
)}
{!bookingTitle && eventTypeSlug && !rescheduleUid && (
<Booker
eventSlug={eventTypeSlug}
username={props.calUsername ?? ""}
onCreateBookingSuccess={(data) => {
setBookingTitle(data.data.title ?? "");
router.push(`/${data.data.uid}`);
}}
duration={eventTypeDuration}
customClassNames={{
bookerContainer: "!bg-[#F5F2FE] [&_button:!rounded-full] border-subtle border",
datePickerCustomClassNames: {
datePickerDatesActive: "!bg-[#D7CEF5]",
},
eventMetaCustomClassNames: {
eventMetaTitle: "text-[#7151DC]",
},
availableTimeSlotsCustomClassNames: {
availableTimeSlotsHeaderContainer: "!bg-[#F5F2FE]",
availableTimes: "!bg-[#D7CEF5]",
},
}}
/>
<>
<h1>{eventTypeSlug}</h1>
<Booker
eventSlug={eventTypeSlug}
username={props.calUsername ?? ""}
onCreateBookingSuccess={(data) => {
setBookingTitle(data.data.title ?? "");
router.push(`/${data.data.uid}`);
}}
teamId={teams?.[0]?.id || 0}
isTeamEvent={isTeamEvent}
duration={eventTypeDuration}
customClassNames={{
bookerContainer: "!bg-[#F5F2FE] [&_button:!rounded-full] border-subtle border",
datePickerCustomClassNames: {
datePickerDatesActive: "!bg-[#D7CEF5]",
},
eventMetaCustomClassNames: {
eventMetaTitle: "text-[#7151DC]",
},
availableTimeSlotsCustomClassNames: {
availableTimeSlotsHeaderContainer: "!bg-[#F5F2FE]",
availableTimes: "!bg-[#D7CEF5]",
},
}}
/>
</>
)}
{!bookingTitle && rescheduleUid && eventTypeSlugQueryParam && (
<Booker