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

@@ -22,8 +22,12 @@ import type {
} from "@calcom/platform-types";
import { BookerLayouts } from "@calcom/prisma/zod-utils";
import { transformApiEventTypeForAtom } from "../event-types/atom-api-transformers/transformApiEventTypeForAtom";
import {
transformApiEventTypeForAtom,
transformApiTeamEventTypeForAtom,
} from "../event-types/atom-api-transformers/transformApiEventTypeForAtom";
import { useEventType } from "../hooks/event-types/public/useEventType";
import { useTeamEventType } from "../hooks/event-types/public/useTeamEventType";
import { useAtomsContext } from "../hooks/useAtomsContext";
import { useAvailableSlots } from "../hooks/useAvailableSlots";
import { useCalendarsBusyTimes } from "../hooks/useCalendarsBusyTimes";
@@ -44,7 +48,7 @@ import { AtomsWrapper } from "../src/components/atoms-wrapper";
export type BookerPlatformWrapperAtomProps = Omit<BookerProps, "username" | "entity"> & {
rescheduleUid?: string;
bookingUid?: string;
username: string | string[];
username: string | string[] | undefined;
entity?: BookerProps["entity"];
// values for the booking form and booking fields
defaultFormValues?: {
@@ -68,6 +72,7 @@ export type BookerPlatformWrapperAtomProps = Omit<BookerProps, "username" | "ent
onDeleteSlotSuccess?: (data: ApiSuccessResponseWithoutData) => void;
onDeleteSlotError?: (data: ApiErrorResponse) => void;
locationUrl?: string;
teamId?: number;
};
export const BookerPlatformWrapper = (props: BookerPlatformWrapperAtomProps) => {
@@ -88,7 +93,10 @@ export const BookerPlatformWrapper = (props: BookerPlatformWrapperAtomProps) =>
});
const queryClient = useQueryClient();
const username = useMemo(() => {
return formatUsername(props.username);
if (props.username) {
return formatUsername(props.username);
}
return "";
}, [props.username]);
setSelectedDuration(props.duration ?? null);
@@ -98,16 +106,45 @@ export const BookerPlatformWrapper = (props: BookerPlatformWrapperAtomProps) =>
return getUsernameList(username ?? "").length > 1;
}, [username]);
const { isSuccess, isError, isPending, data } = useEventType(username, props.eventSlug);
const { isSuccess, isError, isPending, data } = useEventType(username, props.eventSlug, props.isTeamEvent);
const {
isSuccess: isTeamSuccess,
isError: isTeamError,
isPending: isTeamPending,
data: teamData,
} = useTeamEventType(props.teamId, props.eventSlug, props.isTeamEvent);
const event = useMemo(() => {
if (props.isTeamEvent) {
return {
isSuccess: isTeamSuccess,
isError: isTeamError,
isPending: isTeamPending,
data:
teamData && teamData.length > 0
? transformApiTeamEventTypeForAtom(teamData[0], props.entity)
: undefined,
};
}
return {
isSuccess,
isError,
isPending,
data: data && data.length > 0 ? transformApiEventTypeForAtom(data[0], props.entity) : undefined,
};
}, [isSuccess, isError, isPending, data, props.entity]);
}, [
props.isTeamEvent,
props.entity,
isSuccess,
isError,
isPending,
data,
isTeamSuccess,
isTeamError,
isTeamPending,
teamData,
]);
if (isDynamic && props.duration && event.data) {
// note(Lauris): Mandatory - In case of "dynamic" event type default event duration returned by the API is 30,
@@ -188,7 +225,7 @@ export const BookerPlatformWrapper = (props: BookerPlatformWrapperAtomProps) =>
// Should only wait for one or the other, not both.
(Boolean(eventSlug) || Boolean(event?.data?.id) || event?.data?.id === 0),
orgSlug: props.entity?.orgSlug ?? undefined,
eventTypeSlug: isDynamic ? "dynamic" : undefined,
eventTypeSlug: isDynamic ? "dynamic" : eventSlug || "",
});
const bookerForm = useBookingForm({
@@ -9,6 +9,7 @@ import frTranslations from "@calcom/web/public/static/locales/fr/common.json";
import ptBrTranslations from "@calcom/web/public/static/locales/pt-BR/common.json";
import { AtomsContext } from "../hooks/useAtomsContext";
import { useMe } from "../hooks/useMe";
import { useOAuthClient } from "../hooks/useOAuthClient";
import { useOAuthFlow } from "../hooks/useOAuthFlow";
import { useTimezone } from "../hooks/useTimezone";
@@ -38,6 +39,7 @@ export function BaseCalProvider({
onTimezoneChange,
}: CalProviderProps) {
const [error, setError] = useState<string>("");
const { data: me } = useMe();
const { mutateAsync } = useUpdateUserTimezone();
@@ -117,6 +119,7 @@ export function BaseCalProvider({
isInit: isInit,
isValidClient: Boolean(!error && clientId && isInit),
isAuth: Boolean(isInit && !error && clientId && currentAccessToken && http.getAuthorizationHeader()),
organizationId: me?.data.organizationId || 0,
...translations,
}}>
<TooltipProvider>{children}</TooltipProvider>
@@ -134,6 +137,7 @@ export function BaseCalProvider({
isInit: false,
isRefreshing: false,
...translations,
organizationId: 0,
}}>
<>
<TooltipProvider>{children}</TooltipProvider>
@@ -7,7 +7,7 @@ import {
transformApiEventTypeBookingFields,
} from "@calcom/lib/event-types/transformers";
import { getBookerBaseUrlSync } from "@calcom/lib/getBookerUrl/client";
import type { EventTypeOutput_2024_06_14 } from "@calcom/platform-types";
import type { EventTypeOutput_2024_06_14, TeamEventTypeOutput_2024_06_14 } from "@calcom/platform-types";
import {
bookerLayoutOptions,
BookerLayouts,
@@ -91,6 +91,91 @@ export function transformApiEventTypeForAtom(
};
}
export function transformApiTeamEventTypeForAtom(
eventType: TeamEventTypeOutput_2024_06_14,
entity: BookerProps["entity"] | undefined
) {
const { lengthInMinutes, locations, hosts, bookingFields, ...rest } = eventType;
const isDefault = isDefaultEvent(rest.title);
const defaultEventBookerLayouts = {
enabledLayouts: [...bookerLayoutOptions],
defaultLayout: BookerLayouts.MONTH_VIEW,
};
const firstUsersMetadata = userMetadataSchema.parse({});
const bookerLayouts = bookerLayoutsSchema.parse(
firstUsersMetadata?.defaultBookerLayouts || defaultEventBookerLayouts
);
return {
...rest,
length: lengthInMinutes,
locations: getLocations(locations),
bookingFields: getBookingFields(bookingFields),
isDefault,
isDynamic: false,
profile: {
username: "team",
name: "team",
weekStart: "Sunday",
image: "",
brandColor: null,
darkBrandColor: null,
theme: null,
bookerLayouts,
},
entity: entity
? {
...entity,
orgSlug: entity.orgSlug || null,
teamSlug: entity.teamSlug || null,
fromRedirectOfNonOrgLink: true,
name: entity.name || null,
logoUrl: entity.logoUrl || undefined,
}
: {
fromRedirectOfNonOrgLink: true,
considerUnpublished: false,
orgSlug: null,
teamSlug: null,
name: null,
logoUrl: undefined,
},
hosts: hosts.map((host) => ({
user: {
id: host.userId,
avatarUrl: null,
name: host.name,
username: "",
metadata: {},
darkBrandColor: null,
brandColor: null,
theme: null,
weekStart: "Sunday",
},
})),
users: hosts.map((host) => ({
metadata: undefined,
bookerUrl: getBookerBaseUrlSync(null),
profile: {
username: "",
name: host.name,
weekStart: "Sunday",
image: "",
brandColor: null,
darkBrandColor: null,
theme: null,
organization: null,
id: host.userId,
organizationId: null,
userId: host.userId,
upId: `usr-${host.userId}`,
},
})),
};
}
function isDefaultEvent(eventSlug: string) {
const foundInDefaults = defaultEvents.find((obj) => {
return obj.slug === eventSlug;
@@ -13,7 +13,7 @@ import http from "../../../lib/http";
export const QUERY_KEY = "use-event-type";
export type UsePublicEventReturnType = ReturnType<typeof useEventType>;
export const useEventType = (username: string, eventSlug: string) => {
export const useEventType = (username: string, eventSlug: string, isTeamEvent: boolean | undefined) => {
const [stateUsername, stateEventSlug] = useBookerStore(
(state) => [state.username, state.eventSlug],
shallow
@@ -29,6 +29,10 @@ export const useEventType = (username: string, eventSlug: string) => {
const event = useQuery({
queryKey: [QUERY_KEY, stateUsername ?? username, stateEventSlug ?? eventSlug],
queryFn: async () => {
if (isTeamEvent) {
return;
}
if (isDynamic) {
return http
.get<ApiResponse<EventTypeOutput_2024_06_14[]>>(
@@ -0,0 +1,41 @@
import { useQuery } from "@tanstack/react-query";
import { shallow } from "zustand/shallow";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ApiSuccessResponse, TeamEventTypeOutput_2024_06_14 } from "@calcom/platform-types";
import type { ApiResponse } from "@calcom/platform-types";
import http from "../../../lib/http";
import { useAtomsContext } from "../../useAtomsContext";
export const QUERY_KEY = "use-team-event-type";
export const useTeamEventType = (teamId: number | undefined, eventSlug: string, isTeamEvent: boolean | undefined) => {
const { organizationId } = useAtomsContext();
const [stateEventSlug] = useBookerStore(
(state) => [state.eventSlug],
shallow
);
const requestEventSlug = stateEventSlug ?? eventSlug;
const pathname = `/organizations/${organizationId}/teams/${teamId}/event-types?eventSlug=${requestEventSlug}`;
const event = useQuery({
queryKey: [QUERY_KEY, eventSlug, organizationId, teamId],
queryFn: async () => {
if(organizationId && teamId && eventSlug && isTeamEvent) {
return http?.get<ApiResponse<TeamEventTypeOutput_2024_06_14[]>>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<TeamEventTypeOutput_2024_06_14[]>).data;
}
throw new Error(res.data.error.message);
});
}
},
});
return event;
};
@@ -0,0 +1,27 @@
import { useQuery } from "@tanstack/react-query";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { TeamEventTypeOutput_2024_06_14 } from "@calcom/platform-types";
import type { ApiResponse, ApiSuccessResponse } from "@calcom/platform-types";
import http from "../../../lib/http";
import { useAtomsContext } from "../../useAtomsContext";
export const QUERY_KEY = "use-team-event-types";
export const useTeamEventTypes = (teamId: number) => {
const { organizationId } = useAtomsContext();
const pathname = `/organizations/${organizationId}/teams/${teamId}/event-types`;
return useQuery({
queryKey: [QUERY_KEY, organizationId, teamId],
queryFn: () => {
return http?.get<ApiResponse<TeamEventTypeOutput_2024_06_14[]>>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<TeamEventTypeOutput_2024_06_14[]>).data;
}
throw new Error(res.data.error.message);
});
},
enabled: !!organizationId && !!teamId,
});
};
@@ -0,0 +1,32 @@
import { useQuery } from "@tanstack/react-query";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import type { ApiSuccessResponse } from "@calcom/platform-types";
import type { ApiResponse } from "@calcom/platform-types";
import type { OrgTeamOutputDto } from "@calcom/platform-types";
import http from "../../lib/http";
import { useAtomsContext } from "../useAtomsContext";
export const QUERY_KEY = "use-teams";
export const useTeams = () => {
const { organizationId } = useAtomsContext();
const pathname = `/organizations/${organizationId}/teams/me`;
const event = useQuery({
queryKey: [QUERY_KEY, organizationId],
queryFn: async () => {
return http?.get<ApiResponse<OrgTeamOutputDto[]>>(pathname).then((res) => {
if (res.data.status === SUCCESS_STATUS) {
return (res.data as ApiSuccessResponse<OrgTeamOutputDto[]>).data;
}
throw new Error(res.data.error.message);
});
},
enabled: !!organizationId,
});
return event;
};
@@ -26,11 +26,13 @@ export interface IAtomsContext {
locales: CalProviderLanguagesType[];
exists: (key: translationKeys | string) => boolean;
};
organizationId: number;
}
export const AtomsContext = createContext({
clientId: "",
accessToken: "",
organizationId: 0,
options: { refreshUrl: "", apiUrl: "" },
error: "",
getClient: () => {
+2
View File
@@ -6,6 +6,7 @@ export { useIsPlatform } from "./hooks/useIsPlatform";
export { useAtomsContext } from "./hooks/useAtomsContext";
export { useConnectedCalendars } from "./hooks/useConnectedCalendars";
export { useEventTypes } from "./hooks/event-types/public/useEventTypes";
export { useTeamEventTypes } from "./hooks/event-types/public/useTeamEventTypes";
export { useEventType as useEvent } from "./hooks/event-types/public/useEventType";
export { useEventTypeById } from "./hooks/event-types/private/useEventTypeById";
export { useCancelBooking } from "./hooks/useCancelBooking";
@@ -18,3 +19,4 @@ export { BookerEmbed } from "./booker-embed";
export { useDeleteCalendarCredentials } from "./hooks/calendars/useDeleteCalendarCredentials";
export { useAddSelectedCalendar } from "./hooks/calendars/useAddSelectedCalendar";
export { useRemoveSelectedCalendar } from "./hooks/calendars/useRemoveSelectedCalendar";
export { useTeams } from "./hooks/teams/useTeams";
@@ -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
@@ -15,6 +15,12 @@ export class GetEventTypesQuery_2024_06_14 {
usernames?: string[];
}
export class GetTeamEventTypesQuery_2024_06_14 {
@IsString()
@IsOptional()
eventSlug?: string;
}
function TransformUsernames() {
return Transform(({ value }) => {
if (typeof value === "string") {
@@ -12,7 +12,7 @@ import {
} from "class-validator";
import type { Location_2024_06_14, BookingField_2024_06_14 } from "../inputs";
import { Host } from "../inputs";
import { Host as TeamEventTypeHostInput } from "../inputs";
import { RecurringEvent_2024_06_14 } from "../inputs";
import { ValidateBookingFields_2024_06_14 } from "../inputs/booking-fields.input";
import { ValidateLocations_2024_06_14 } from "../inputs/locations.input";
@@ -139,6 +139,11 @@ export class EventTypeOutput_2024_06_14 {
scheduleId!: number | null;
}
export class TeamEventTypeResponseHost extends TeamEventTypeHostInput {
@IsString()
name!: string;
}
export class TeamEventTypeOutput_2024_06_14 {
@IsInt()
@DocsProperty({ example: 1 })
@@ -235,9 +240,9 @@ export class TeamEventTypeOutput_2024_06_14 {
parentEventTypeId?: number | null;
@ValidateNested({ each: true })
@Type(() => Host)
@Type(() => TeamEventTypeResponseHost)
@IsArray()
hosts!: Host[];
hosts!: TeamEventTypeResponseHost[];
@IsBoolean()
@IsOptional()
+1
View File
@@ -7,3 +7,4 @@ export * from "./bookings";
export * from "./billing";
export * from "./schedules";
export * from "./event-types";
export * from "./organizations";
+1
View File
@@ -46,6 +46,7 @@ export const userSchemaResponse = z.object({
weekStart: z.string(),
timeZone: z.string().default("Europe/London"),
username: z.string(),
organizationId: z.number().nullable(),
});
export type UserResponse = z.infer<typeof userSchemaResponse>;
@@ -0,0 +1 @@
export * from "./teams";
@@ -0,0 +1 @@
export * from "./outputs";
@@ -0,0 +1 @@
export * from "./team.output";
@@ -0,0 +1,107 @@
import { Expose } from "class-transformer";
import { IsBoolean, IsInt, IsOptional, IsString, IsUrl, Length } from "class-validator";
export class OrgTeamOutputDto {
@IsInt()
@Expose()
readonly id!: number;
@IsInt()
@IsOptional()
@Expose()
readonly parentId?: number;
@IsString()
@Length(1)
@Expose()
readonly name!: string;
@IsOptional()
@IsString()
@Expose()
readonly slug?: string;
@IsOptional()
@IsUrl()
@Expose()
readonly logoUrl?: string;
@IsOptional()
@IsUrl()
@Expose()
readonly calVideoLogo?: string;
@IsOptional()
@IsUrl()
@Expose()
readonly appLogo?: string;
@IsOptional()
@IsUrl()
@Expose()
readonly appIconLogo?: string;
@IsOptional()
@IsString()
@Expose()
readonly bio?: string;
@IsOptional()
@IsBoolean()
@Expose()
readonly hideBranding?: boolean;
@IsBoolean()
@Expose()
readonly isOrganization?: boolean;
@IsOptional()
@IsBoolean()
@Expose()
readonly isPrivate?: boolean;
@IsOptional()
@IsBoolean()
@Expose()
readonly hideBookATeamMember?: boolean = false;
@IsOptional()
@IsString()
@Expose()
readonly metadata?: string;
@IsOptional()
@IsString()
@Expose()
readonly theme?: string;
@IsOptional()
@IsString()
@Expose()
readonly brandColor?: string;
@IsOptional()
@IsString()
@Expose()
readonly darkBrandColor?: string;
@IsOptional()
@IsUrl()
@Expose()
readonly bannerUrl?: string;
@IsOptional()
@IsString()
@Expose()
readonly timeFormat?: number;
@IsOptional()
@IsString()
@Expose()
readonly timeZone?: string = "Europe/London";
@IsOptional()
@IsString()
@Expose()
readonly weekStart?: string = "Sunday";
}