perf: caching + modularize data fetching for team booking pages (#22172)

* wip

* wip

* wip

* refactor

* refactor

* refactor

* refactor

* refactor

* fix

* better

* fix

* fix

* use notFound

* refactor

* wip

* refactor

* wip

* refactor

* wip

* wip

* finalize

* wip

* fix

* lots of refactors

* better code

* clean up

* fix

* fix type checks

* finalize

* select more fields

* select more fields

* fix

* fix

* fix

* fix

* better

* better

* fix

* fix

* fix

* fix

* add back comment

* fix

* better

* fix

* refactor

* fix

* fix type check

* add comment

* fix

* wip

* wip

* add more comment

* refactor

* rename

* refactors

* fix reschedule logic

* remove hard-coded true from isCachedEnabled

* better

* use revalidateTeamDataCache in team profile update

* fix invalidation

* better comment

* refactors

* add better comments

* add revalidations

* add comments

* fix

* remove hard code

* fix

* update tags

* use features package

* fix type check
This commit is contained in:
Benny Joo authored and GitHub committed 2025-07-15 21:42:55 -03:00
1 parent e6da5c85e0
commit c4eda5f21d
19 files changed
+932 -5

No files matched your search

@@ -0,0 +1,27 @@
"use server";
import { revalidateTag } from "next/cache";
// Coupled with `getCachedTeamData` in `queries.ts`
export async function revalidateTeamDataCache({
teamSlug,
orgSlug,
}: {
teamSlug: string;
orgSlug: string | null;
}) {
revalidateTag(`team:${orgSlug ? `${orgSlug}:` : ""}${teamSlug}`);
}
// Coupled with `getCachedTeamEventType` in `queries.ts`
export async function revalidateTeamEventTypeCache({
teamSlug,
meetingSlug,
orgSlug,
}: {
teamSlug: string;
meetingSlug: string;
orgSlug: string | null;
}) {
revalidateTag(`event-type:${orgSlug ? `${orgSlug}:` : ""}${teamSlug}:${meetingSlug}`);
}
@@ -1,10 +1,11 @@
import { CustomI18nProvider } from "app/CustomI18nProvider";
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps } from "app/_types";
import type { PageProps, SearchParams } from "app/_types";
import { generateMeetingMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { loadTranslations } from "@calcom/lib/server/i18n";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
@@ -13,7 +14,20 @@ import { getServerSideProps } from "@lib/team/[slug]/[type]/getServerSideProps";
import LegacyPage from "~/team/type-view";
import type { PageProps as LegacyPageProps } from "~/team/type-view";
import CachedTeamBooker, { generateMetadata as generateCachedMetadata } from "./pageWithCachedData";
async function isCachedTeamBookingEnabled(searchParams: SearchParams): Promise<boolean> {
const featuresRepository = new FeaturesRepository();
const isGloballyEnabled = await featuresRepository.checkIfFeatureIsEnabledGlobally(
"team-booking-page-cache"
);
return isGloballyEnabled && searchParams.experimentalTeamBookingPageCache === "true";
}
export const generateMetadata = async ({ params, searchParams }: PageProps) => {
if (await isCachedTeamBookingEnabled(await searchParams)) {
return await generateCachedMetadata({ params, searchParams });
}
const legacyCtx = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(legacyCtx);
const { booking, isSEOIndexable, eventData, isBrandingHidden } = props;
@@ -53,6 +67,10 @@ export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const getData = withAppDirSsr<LegacyPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: PageProps) => {
if (await isCachedTeamBookingEnabled(await searchParams)) {
return await CachedTeamBooker({ params, searchParams });
}
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
@@ -70,4 +88,5 @@ const ServerPage = async ({ params, searchParams }: PageProps) => {
return <LegacyPage {...props} />;
};
export default ServerPage;
@@ -0,0 +1,218 @@
import { CustomI18nProvider } from "app/CustomI18nProvider";
import type { PageProps, Params } from "app/_types";
import { generateMeetingMetadata } from "app/_utils";
import { headers, cookies } from "next/headers";
import { notFound, redirect } from "next/navigation";
import { z } from "zod";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getBookingForReschedule, type GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import { getOrgFullOrigin, orgDomainConfig } from "@calcom/features/ee/organizations/lib/orgDomains";
import { getOrganizationSEOSettings } from "@calcom/features/ee/organizations/lib/orgSettings";
import type { TeamData } from "@calcom/features/ee/teams/lib/getTeamData";
import { shouldHideBrandingForTeamEvent } from "@calcom/lib/hideBranding";
import { loadTranslations } from "@calcom/lib/server/i18n";
import slugify from "@calcom/lib/slugify";
import { BookingStatus, RedirectType } from "@calcom/prisma/enums";
import { buildLegacyCtx, buildLegacyRequest } from "@lib/buildLegacyCtx";
import { getTemporaryOrgRedirect } from "@lib/getTemporaryOrgRedirect";
import CachedClientView, { type TeamBookingPageProps } from "~/team/type-view-cached";
import { getCachedTeamData, getEnrichedEventType, getCRMData, shouldUseApiV2ForTeamSlots } from "./queries";
const paramsSchema = z.object({
slug: z.string().transform((s) => slugify(s)),
type: z.string().transform((s) => slugify(s)),
});
const _getTeamMetadataForBooking = (teamData: NonNullable<TeamData>, eventTypeId: number) => {
const organizationSettings = getOrganizationSEOSettings(teamData);
const allowSEOIndexing = organizationSettings?.allowSEOIndexing ?? false;
return {
orgBannerUrl: teamData.parent?.bannerUrl ?? "",
hideBranding: shouldHideBrandingForTeamEvent({
eventTypeId,
team: teamData,
}),
isSEOIndexable: allowSEOIndexing,
};
};
async function _getOrgContext(params: Params) {
const result = paramsSchema.safeParse({
slug: params?.slug,
type: params?.type,
});
if (!result.success) return notFound(); // should never happen
const { slug: teamSlug, type: meetingSlug } = result.data;
const { currentOrgDomain, isValidOrgDomain } = orgDomainConfig(
buildLegacyRequest(await headers(), await cookies()),
params?.orgSlug ?? undefined
);
return {
currentOrgDomain,
isValidOrgDomain,
teamSlug,
meetingSlug,
};
}
const _getMultipleDurationValue = (
multipleDurationConfig: number[] | undefined,
queryDuration: string | string[] | null | undefined,
defaultValue: number
) => {
if (!multipleDurationConfig) return null;
if (multipleDurationConfig.includes(Number(queryDuration))) return Number(queryDuration);
return defaultValue;
};
export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const { currentOrgDomain, isValidOrgDomain, teamSlug, meetingSlug } = await _getOrgContext(await params);
const teamData = await getCachedTeamData(teamSlug, currentOrgDomain);
if (!teamData) return {}; // should never happen
const enrichedEventType = await getEnrichedEventType({
teamSlug,
meetingSlug,
orgSlug: isValidOrgDomain ? currentOrgDomain : null,
fromRedirectOfNonOrgLink: (await searchParams).orgRedirection === "true",
});
if (!enrichedEventType) return {}; // should never happen
const title = enrichedEventType.title;
const profileName = enrichedEventType.profile.name ?? "";
const profileImage = enrichedEventType.profile.image;
const meeting = {
title,
profile: { name: profileName, image: profileImage },
users: [
...(enrichedEventType?.subsetOfUsers || []).map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})),
],
};
const { hideBranding, isSEOIndexable } = _getTeamMetadataForBooking(teamData, enrichedEventType.id);
const metadata = await generateMeetingMetadata(
meeting,
() => `${title} | ${profileName}`,
() => title,
hideBranding,
getOrgFullOrigin(enrichedEventType.entity.orgSlug ?? null),
`/team/${teamSlug}/${meetingSlug}`
);
return {
...metadata,
robots: {
follow: !(enrichedEventType.hidden || !isSEOIndexable),
index: !(enrichedEventType.hidden || !isSEOIndexable),
},
};
};
const CachedTeamBooker = async ({ params, searchParams }: PageProps) => {
const { currentOrgDomain, isValidOrgDomain, teamSlug, meetingSlug } = await _getOrgContext(await params);
const isOrgContext = currentOrgDomain && isValidOrgDomain;
const legacyCtx = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
// Handle org redirects for non-org contexts
if (!isOrgContext) {
const redirectResult = await getTemporaryOrgRedirect({
slugs: teamSlug,
redirectType: RedirectType.Team,
eventTypeSlug: meetingSlug,
currentQuery: legacyCtx.query,
});
if (redirectResult) return redirect(redirectResult.redirect.destination);
}
const teamData = await getCachedTeamData(teamSlug, currentOrgDomain);
if (!teamData) return notFound();
const enrichedEventType = await getEnrichedEventType({
teamSlug,
meetingSlug,
orgSlug: isValidOrgDomain ? currentOrgDomain : null,
fromRedirectOfNonOrgLink: legacyCtx.query.orgRedirection === "true",
});
if (!enrichedEventType) return notFound();
// Handle rescheduling
const { rescheduleUid } = legacyCtx.query;
let bookingForReschedule: GetBookingType | null = null;
if (rescheduleUid) {
const session = await getServerSession({ req: legacyCtx.req });
bookingForReschedule = await getBookingForReschedule(`${rescheduleUid}`, session?.user?.id);
if (enrichedEventType.disableRescheduling) return redirect(`/booking/${rescheduleUid}`);
if (
bookingForReschedule?.status === BookingStatus.CANCELLED &&
legacyCtx.query.allowRescheduleForCancelledBooking !== "true" &&
!enrichedEventType.allowReschedulingCancelledBookings
) {
// redirecting to the same booking page without `rescheduleUid` search param
return redirect(`/team/${teamSlug}/${meetingSlug}`);
}
}
const [crmData, useApiV2] = await Promise.all([
getCRMData(legacyCtx.query, {
id: enrichedEventType.id,
isInstantEvent: enrichedEventType.isInstantEvent,
schedulingType: enrichedEventType.schedulingType,
metadata: enrichedEventType.metadata,
length: enrichedEventType.length,
}),
shouldUseApiV2ForTeamSlots(teamData.id),
]);
const props: TeamBookingPageProps = {
..._getTeamMetadataForBooking(teamData, enrichedEventType.id),
...crmData,
useApiV2,
isInstantMeeting: legacyCtx.query.isInstantMeeting === "true",
eventSlug: meetingSlug,
username: teamSlug,
eventData: {
...enrichedEventType,
},
entity: { ...enrichedEventType.entity },
bookingData: bookingForReschedule,
isTeamEvent: true,
durationConfig: enrichedEventType.metadata?.multipleDuration,
duration: _getMultipleDurationValue(
enrichedEventType.metadata?.multipleDuration,
legacyCtx.query.duration,
enrichedEventType.length
),
};
const Booker = <CachedClientView {...props} />;
const eventLocale = enrichedEventType.interfaceLanguage;
if (eventLocale) {
const ns = "common";
const translations = await loadTranslations(eventLocale, ns);
return (
<CustomI18nProvider translations={translations} locale={eventLocale} ns={ns}>
{Booker}
</CustomI18nProvider>
);
}
return Booker;
};
export default CachedTeamBooker;
@@ -0,0 +1,155 @@
import type { Prisma } from "@prisma/client";
import type { GetServerSidePropsContext } from "next";
import { unstable_cache } from "next/cache";
import { getTeamData } from "@calcom/features/ee/teams/lib/getTeamData";
import {
getEventTypeHosts,
getProfileFromEvent,
getUsersFromEvent,
processEventDataShared,
} from "@calcom/features/eventtypes/lib/getPublicEvent";
import { getTeamEventType } from "@calcom/features/eventtypes/lib/getTeamEventType";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { NEXTJS_CACHE_TTL } from "@calcom/lib/constants";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { UserRepository } from "@calcom/lib/server/repository/user";
import { prisma } from "@calcom/prisma";
import type { SchedulingType } from "@calcom/prisma/enums";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/prisma/zod-utils";
export async function getCachedTeamData(teamSlug: string, orgSlug: string | null) {
return unstable_cache(async () => getTeamData(teamSlug, orgSlug), ["team-data", teamSlug, orgSlug ?? ""], {
revalidate: NEXTJS_CACHE_TTL,
tags: [`team:${orgSlug ? `${orgSlug}:` : ""}${teamSlug}`],
})();
}
export async function getCachedTeamEventType(teamSlug: string, meetingSlug: string, orgSlug: string | null) {
return unstable_cache(
async () => getTeamEventType(teamSlug, meetingSlug, orgSlug),
["team-event-type", teamSlug, meetingSlug, orgSlug ?? ""],
{
revalidate: NEXTJS_CACHE_TTL,
tags: [`event-type:${orgSlug ? `${orgSlug}:` : ""}${teamSlug}:${meetingSlug}`],
}
)();
}
export async function getEnrichedEventType({
teamSlug,
meetingSlug,
orgSlug,
fromRedirectOfNonOrgLink,
}: {
teamSlug: string;
meetingSlug: string;
orgSlug: string | null;
fromRedirectOfNonOrgLink: boolean;
}) {
const [teamData, eventType] = await Promise.all([
getCachedTeamData(teamSlug, orgSlug),
getCachedTeamEventType(teamSlug, meetingSlug, orgSlug),
]);
if (!teamData || !eventType) {
return null;
}
const { subsetOfHosts, hosts } = await getEventTypeHosts({
hosts: eventType.hosts,
prisma,
});
const enrichedOwner = eventType.owner
? await new UserRepository(prisma).enrichUserWithItsProfile({
user: eventType.owner,
})
: null;
const users =
(await getUsersFromEvent({ ...eventType, owner: enrichedOwner, subsetOfHosts, hosts }, prisma)) ?? [];
const name = teamData.parent?.name ?? teamData.name ?? null;
const isUnpublished = teamData.parent ? !teamData.parent.slug : !teamData.slug;
const eventMetaData = eventTypeMetaDataSchemaWithTypedApps.parse(eventType.metadata);
const eventDataShared = await processEventDataShared({
eventData: eventType,
metadata: eventMetaData,
prisma,
});
return {
...eventDataShared,
owner: enrichedOwner,
subsetOfHosts,
hosts,
profile: getProfileFromEvent({ ...eventType, owner: enrichedOwner, subsetOfHosts, hosts }),
subsetOfUsers: users,
users,
entity: {
fromRedirectOfNonOrgLink,
considerUnpublished: isUnpublished && !fromRedirectOfNonOrgLink,
orgSlug,
teamSlug: teamData.slug ?? null,
name,
hideProfileLink: false,
logoUrl: teamData.parent
? getPlaceholderAvatar(teamData.parent.logoUrl, teamData.parent.name)
: getPlaceholderAvatar(teamData.logoUrl, teamData.name),
},
};
}
export async function shouldUseApiV2ForTeamSlots(teamId: number): Promise<boolean> {
const featureRepo = new FeaturesRepository();
const teamHasApiV2Route = await featureRepo.checkIfTeamHasFeature(teamId, "use-api-v2-for-team-slots");
const useApiV2 = teamHasApiV2Route && Boolean(process.env.NEXT_PUBLIC_API_V2_URL);
return useApiV2;
}
export async function getCRMData(
query: GetServerSidePropsContext["query"],
eventData: {
id: number;
isInstantEvent: boolean;
schedulingType: SchedulingType | null;
metadata: Prisma.JsonValue | null;
length: number;
}
) {
const crmContactOwnerEmail = query["cal.crmContactOwnerEmail"];
const crmContactOwnerRecordType = query["cal.crmContactOwnerRecordType"];
const crmAppSlugParam = query["cal.crmAppSlug"];
let teamMemberEmail = Array.isArray(crmContactOwnerEmail) ? crmContactOwnerEmail[0] : crmContactOwnerEmail;
let crmOwnerRecordType = Array.isArray(crmContactOwnerRecordType)
? crmContactOwnerRecordType[0]
: crmContactOwnerRecordType;
let crmAppSlug = Array.isArray(crmAppSlugParam) ? crmAppSlugParam[0] : crmAppSlugParam;
if (!teamMemberEmail || !crmOwnerRecordType || !crmAppSlug) {
const { getTeamMemberEmailForResponseOrContactUsingUrlQuery } = await import(
"@calcom/lib/server/getTeamMemberEmailFromCrm"
);
const {
email,
recordType,
crmAppSlug: crmAppSlugQuery,
} = await getTeamMemberEmailForResponseOrContactUsingUrlQuery({
query,
eventData,
});
teamMemberEmail = email ?? undefined;
crmOwnerRecordType = recordType ?? undefined;
crmAppSlug = crmAppSlugQuery ?? undefined;
}
return {
teamMemberEmail,
crmOwnerRecordType,
crmAppSlug,
};
}
@@ -0,0 +1,19 @@
"use client";
import { BookerWebWrapper, type BookerWebWrapperAtomProps } from "@calcom/atoms/booker";
import { getBookerWrapperClasses } from "@calcom/features/bookings/Booker/utils/getBookerWrapperClasses";
import BookingPageErrorBoundary from "@components/error/BookingPageErrorBoundary";
export type TeamBookingPageProps = Omit<BookerWebWrapperAtomProps, "eventData"> &
Required<Pick<BookerWebWrapperAtomProps, "eventData">> & { isEmbed?: boolean };
export default function TeamBookingPage(props: TeamBookingPageProps) {
return (
<BookingPageErrorBoundary>
<main className={getBookerWrapperClasses({ isEmbed: !!props.isEmbed })}>
<BookerWebWrapper {...props} />
</main>
</BookingPageErrorBoundary>
);
}