refactor: Cal.diy (#28903)

* feat: Cal.diy — community-driven MIT-licensed fork of Cal.com

This squashed commit contains all Cal.diy changes applied on top of calcom/cal.com main:

- Rebrand Cal.com to Cal.diy across the entire codebase
- Remove Enterprise Edition (EE) features, license checks, and AGPL restrictions
- Switch license from AGPL-3.0 to MIT
- Remove docs/ directory (migrated to Nextra at cal.diy)
- Remove dead code: org tests, EE tips, platform nav, premium username, SAML/SSO, etc.
- Clean up .env.example for self-hosted Cal.diy
- Update Docker image references to calcom/cal.diy
- Update README, CONTRIBUTING.md, and issue templates for Cal.diy community fork
- Add PR welcome bot for Cal.diy contributors
- Fix API v2 breaking changes oasdiff ignore entries
- Replace Blacksmith CI runners with default GitHub Actions

3893 files changed, 20789 insertions(+), 411020 deletions(-)

Co-Authored-By: [email protected] <[email protected]>

* refactor: remove org-specific /organizations/:orgId endpoints from API v2 atoms controllers (#1701)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: revert Cal.diy Inc to Cal.com, Inc. in license files, copyright notices, and package metadata (#1702)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* rip out org related comments in api v2

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2026-04-15 09:52:36 -03:00
1 parent a17f28e9ab
commit ab21c7f805
4080 files changed
+14403 -404922

No files matched your search

@@ -1,58 +1,21 @@
import { CustomI18nProvider } from "app/CustomI18nProvider";
import { withAppDirSsr } from "app/WithAppDirSsr";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@server/lib/[user]/[type]/getServerSideProps";
import type { PageProps } from "app/_types";
import { generateMeetingMetadata } from "app/_utils";
import { headers, cookies } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@server/lib/[user]/[type]/getServerSideProps";
import { CustomI18nProvider } from "app/CustomI18nProvider";
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { Metadata } from "next";
import { cookies, headers } from "next/headers";
import type React from "react";
import type { PageProps as LegacyPageProps } from "~/users/views/users-type-public-view";
import LegacyPage from "~/users/views/users-type-public-view";
export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const legacyCtx = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(legacyCtx);
const getData: (ctx: ReturnType<typeof buildLegacyCtx>) => Promise<LegacyPageProps> =
withAppDirSsr<LegacyPageProps>(getServerSideProps);
const { booking, isSEOIndexable = true, eventData, isBrandingHidden } = props;
const rescheduleUid = booking?.uid;
const profileName = eventData?.profile?.name ?? "";
const profileImage = eventData?.profile.image;
const title = eventData?.title ?? "";
const meeting = {
title,
profile: { name: profileName, image: profileImage },
users:
eventData?.subsetOfUsers.map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})) || [],
};
const decodedParams = decodeParams(await params);
const metadata = await generateMeetingMetadata(
meeting,
(t) => `${rescheduleUid && !!booking ? t("reschedule") : ""} ${title} | ${profileName}`,
(t) => `${rescheduleUid ? t("reschedule") : ""} ${title}`,
isBrandingHidden,
getOrgFullOrigin(eventData?.entity.orgSlug ?? null),
`/${decodedParams.user}/${decodedParams.type}`
);
return {
...metadata,
robots: {
follow: !(eventData?.hidden || !isSEOIndexable),
index: !(eventData?.hidden || !isSEOIndexable),
},
};
};
const getData = withAppDirSsr<LegacyPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: PageProps) => {
const ServerPage = async ({ params, searchParams }: PageProps): Promise<JSX.Element> => {
const legacyCtx = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(legacyCtx);
@@ -70,4 +33,40 @@ const ServerPage = async ({ params, searchParams }: PageProps) => {
return <LegacyPage {...props} />;
};
export const generateMetadata = async ({ params, searchParams }: PageProps): Promise<Metadata> => {
const legacyCtx = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(legacyCtx);
const { booking, isSEOIndexable = true, eventData, isBrandingHidden } = props;
const rescheduleUid = booking?.uid;
const profileName = eventData?.profile?.name ?? "";
const title = eventData?.title ?? "";
const meeting = {
title,
profile: { name: profileName, image: eventData?.profile.image },
users:
eventData?.subsetOfUsers.map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})) || [],
};
const decodedParams = decodeParams(await params);
const metadata = await generateMeetingMetadata(
meeting,
(t) => `${rescheduleUid && !!booking ? t("reschedule") : ""} ${title} | ${profileName}`,
(t) => `${rescheduleUid ? t("reschedule") : ""} ${title}`,
isBrandingHidden,
WEBAPP_URL,
`/${decodedParams.user}/${decodedParams.type}`
);
return {
...metadata,
robots: {
follow: !(eventData?.hidden || !isSEOIndexable),
index: !(eventData?.hidden || !isSEOIndexable),
},
};
};
export default ServerPage;
@@ -1,23 +1,32 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@server/lib/[user]/getServerSideProps";
import type { PageProps } from "app/_types";
import { generateMeetingMetadata } from "app/_utils";
import { headers, cookies } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@server/lib/[user]/getServerSideProps";
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { Metadata } from "next";
import { cookies, headers } from "next/headers";
import type React from "react";
import type { PageProps as LegacyPageProps } from "~/users/views/users-public-view";
import LegacyPage from "~/users/views/users-public-view";
export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const getData: (ctx: ReturnType<typeof buildLegacyCtx>) => Promise<LegacyPageProps> =
withAppDirSsr<LegacyPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: PageProps): Promise<JSX.Element> => {
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
const { profile, markdownStrippedBio, isOrgSEOIndexable, entity } = props;
return <LegacyPage {...props} />;
};
export const generateMetadata = async ({ params, searchParams }: PageProps): Promise<Metadata> => {
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
const { profile, markdownStrippedBio, isOrgSEOIndexable } = props;
const isOrg = !!profile?.organization;
const allowSEOIndexing =
(!isOrg && profile.allowSEOIndexing) || (isOrg && isOrgSEOIndexable && profile.allowSEOIndexing);
@@ -32,7 +41,7 @@ export const generateMetadata = async ({ params, searchParams }: PageProps) => {
() => profile.name,
() => markdownStrippedBio,
false,
getOrgFullOrigin(entity.orgSlug ?? null),
WEBAPP_URL,
`/${decodeParams(await params).user}`
);
@@ -45,13 +54,4 @@ export const generateMetadata = async ({ params, searchParams }: PageProps) => {
};
};
const getData = withAppDirSsr<LegacyPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: PageProps) => {
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
return <LegacyPage {...props} />;
};
export default ServerPage;
@@ -1,19 +1,15 @@
import { CustomI18nProvider } from "app/CustomI18nProvider";
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps as _PageProps } from "app/_types";
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { loadTranslations } from "@calcom/i18n/server";
import { BookingStatus } from "@calcom/prisma/enums";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import type { PageProps as _PageProps } from "app/_types";
import { _generateMetadata } from "app/_utils";
import { CustomI18nProvider } from "app/CustomI18nProvider";
import { withAppDirSsr } from "app/WithAppDirSsr";
import { cookies, headers } from "next/headers";
import OldPage from "~/bookings/views/bookings-single-view";
import {
getServerSideProps,
type PageProps as ClientPageProps,
getServerSideProps,
} from "~/bookings/views/bookings-single-view.getServerSideProps";
const getData = withAppDirSsr<ClientPageProps>(getServerSideProps);
@@ -30,7 +26,7 @@ export const generateMetadata = async ({ params, searchParams }: _PageProps) =>
(t) =>
t(`booking_${needsConfirmation ? "submitted" : "confirmed"}${recurringBookings ? "_recurring" : ""}`),
false,
getOrgFullOrigin(orgSlug),
process.env.NEXT_PUBLIC_WEBAPP_URL ?? "",
`/booking/${(await params).uid}`
);
@@ -1,56 +0,0 @@
import { CustomI18nProvider } from "app/CustomI18nProvider";
import withEmbedSsrAppDir from "app/WithEmbedSSR";
import type { PageProps as ServerPageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/org/[orgSlug]/[user]/[type]/getServerSideProps";
import type { PageProps as TeamTypePageProps } from "~/team/type-view";
import TeamTypePage from "~/team/type-view";
import UserTypePage from "~/users/views/users-type-public-view";
import type { PageProps as UserTypePageProps } from "~/users/views/users-type-public-view";
const getData = withEmbedSsrAppDir<ClientPageProps>(getServerSideProps);
export type ClientPageProps = UserTypePageProps | TeamTypePageProps;
export const generateMetadata = async () => {
return {
robots: {
follow: false,
index: false,
},
};
};
const ServerPage = async ({ params, searchParams }: ServerPageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(context);
const eventLocale = props.eventData?.interfaceLanguage;
const ns = "common";
const translations = await loadTranslations(eventLocale ?? "en", ns);
if ((props as TeamTypePageProps)?.teamId) {
return eventLocale ? (
<CustomI18nProvider translations={translations} locale={eventLocale} ns={ns}>
<TeamTypePage {...(props as TeamTypePageProps)} />
</CustomI18nProvider>
) : (
<TeamTypePage {...(props as TeamTypePageProps)} />
);
}
return eventLocale ? (
<CustomI18nProvider translations={translations} locale={eventLocale} ns={ns}>
<UserTypePage {...(props as UserTypePageProps)} />
</CustomI18nProvider>
) : (
<UserTypePage {...(props as UserTypePageProps)} />
);
};
export default ServerPage;
@@ -1,92 +0,0 @@
import { CustomI18nProvider } from "app/CustomI18nProvider";
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps } from "app/_types";
import { generateMeetingMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/org/[orgSlug]/[user]/[type]/getServerSideProps";
import type { PageProps as TeamTypePageProps } from "~/team/type-view";
import TeamTypePage from "~/team/type-view";
import UserTypePage from "~/users/views/users-type-public-view";
import type { PageProps as UserTypePageProps } from "~/users/views/users-type-public-view";
export type OrgTypePageProps = UserTypePageProps | TeamTypePageProps;
const getData = withAppDirSsr<OrgTypePageProps>(getServerSideProps);
export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const legacyCtx = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(legacyCtx);
const { booking, isSEOIndexable = true, eventData, isBrandingHidden } = props;
const rescheduleUid = booking?.uid;
const profileName = eventData?.profile?.name ?? "";
const profileImage = eventData?.profile.image;
const title = eventData?.title ?? "";
const meeting = {
title,
profile: { name: profileName, image: profileImage },
users: [
...(
(eventData as UserTypePageProps["eventData"])?.subsetOfUsers ??
(eventData as TeamTypePageProps["eventData"])?.users ??
[]
).map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})),
],
};
const decodedParams = decodeParams(await params);
const metadata = await generateMeetingMetadata(
meeting,
(t) => `${rescheduleUid && !!booking ? t("reschedule") : ""} ${title} | ${profileName}`,
(t) => `${rescheduleUid ? t("reschedule") : ""} ${title}`,
isBrandingHidden,
getOrgFullOrigin(eventData?.entity.orgSlug ?? null),
`/${decodedParams.user}/${decodedParams.type}`
);
return {
...metadata,
robots: {
follow: !(eventData?.hidden || !isSEOIndexable),
index: !(eventData?.hidden || !isSEOIndexable),
},
};
};
const ServerPage = async ({ params, searchParams }: PageProps) => {
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
const eventLocale = props.eventData?.interfaceLanguage;
const ns = "common";
const translations = await loadTranslations(eventLocale ?? "en", ns);
if ((props as TeamTypePageProps)?.teamId) {
return eventLocale ? (
<CustomI18nProvider translations={translations} locale={eventLocale} ns={ns}>
<TeamTypePage {...(props as TeamTypePageProps)} />
</CustomI18nProvider>
) : (
<TeamTypePage {...(props as TeamTypePageProps)} />
);
}
return eventLocale ? (
<CustomI18nProvider translations={translations} locale={eventLocale} ns={ns}>
<UserTypePage {...(props as UserTypePageProps)} />
</CustomI18nProvider>
) : (
<UserTypePage {...(props as UserTypePageProps)} />
);
};
export default ServerPage;
@@ -1,33 +0,0 @@
import withEmbedSsrAppDir from "app/WithEmbedSSR";
import type { PageProps as ServerPageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/org/[orgSlug]/[user]/getServerSideProps";
import type { PageProps as TeamPageProps } from "~/team/team-view";
import TeamPage from "~/team/team-view";
import UserPage from "~/users/views/users-public-view";
import type { PageProps as UserPageProps } from "~/users/views/users-public-view";
const getData = withEmbedSsrAppDir<ClientPageProps>(getServerSideProps);
export type ClientPageProps = UserPageProps | TeamPageProps;
export const generateMetadata = async () => {
return {
robots: {
follow: false,
index: false,
},
};
};
const ServerPage = async ({ params, searchParams }: ServerPageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(context);
if ((props as TeamPageProps)?.team) return <TeamPage {...(props as TeamPageProps)} />;
return <UserPage {...(props as UserPageProps)} />;
};
export default ServerPage;
@@ -1,91 +0,0 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps } from "app/_types";
import { generateMeetingMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { getOrgOrTeamAvatar } from "@calcom/lib/defaultAvatarImage";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/org/[orgSlug]/[user]/getServerSideProps";
import type { PageProps as TeamPageProps } from "~/team/team-view";
import TeamPage from "~/team/team-view";
import UserPage from "~/users/views/users-public-view";
import type { PageProps as UserPageProps } from "~/users/views/users-public-view";
export type OrgPageProps = UserPageProps | TeamPageProps;
const getData = withAppDirSsr<OrgPageProps>(getServerSideProps);
export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const legacyCtx = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(legacyCtx);
const decodedParams = decodeParams(await params);
if ((props as TeamPageProps)?.team) {
const { team, markdownStrippedBio, isSEOIndexable, currentOrgDomain } = props as TeamPageProps;
const meeting = {
title: markdownStrippedBio ?? "",
profile: {
name: `${team.name}`,
image: getOrgOrTeamAvatar(team),
},
};
return {
...(await generateMeetingMetadata(
meeting,
(t) => team.name ?? t("nameless_team"),
(t) => team.name ?? t("nameless_team"),
false,
getOrgFullOrigin(currentOrgDomain ?? null),
`/${decodedParams.user}`
)),
robots: {
index: isSEOIndexable,
follow: isSEOIndexable,
},
};
} else {
const { profile, markdownStrippedBio, isOrgSEOIndexable, entity } = props as UserPageProps;
const meeting = {
title: markdownStrippedBio,
profile: { name: `${profile.name}`, image: profile.image },
users: [
{
username: `${profile.username ?? ""}`,
name: `${profile.name ?? ""}`,
},
],
};
const isOrg = !!profile?.organization;
const allowSEOIndexing =
(!isOrg && profile.allowSEOIndexing) || (isOrg && isOrgSEOIndexable && profile.allowSEOIndexing);
return {
...(await generateMeetingMetadata(
meeting,
() => profile.name,
() => markdownStrippedBio,
false,
getOrgFullOrigin(entity.orgSlug ?? null),
`/${decodedParams.user}`
)),
robots: {
index: allowSEOIndexing,
follow: allowSEOIndexing,
},
};
}
};
const ServerPage = async ({ params, searchParams }: PageProps) => {
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
if ((props as TeamPageProps)?.team) {
return <TeamPage {...(props as TeamPageProps)} />;
}
return <UserPage {...(props as UserPageProps)} />;
};
export default ServerPage;
@@ -1 +0,0 @@
export { default } from "../../../team/[slug]/embed/page";
@@ -1,63 +0,0 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps as _PageProps } from "app/_types";
import { generateMeetingMetadata } from "app/_utils";
import { headers, cookies } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/org/[orgSlug]/instant-meeting/team/[slug]/[type]/getServerSideProps";
import type { Props } from "~/org/[orgSlug]/instant-meeting/team/[slug]/[type]/instant-meeting-view";
import Page from "~/org/[orgSlug]/instant-meeting/team/[slug]/[type]/instant-meeting-view";
export const generateMetadata = async ({ params, searchParams }: _PageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const { isBrandingHidden, eventData, teamIsPrivate } = await getData(context);
const profileName = eventData?.profile.name ?? "";
const profileImage = eventData?.profile.image;
const title = eventData?.title ?? "";
const meeting = {
title,
profile: { name: profileName, image: profileImage },
// Hide team member names in preview if team is private
users: teamIsPrivate
? []
: [
...(eventData?.users || []).map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})),
],
};
const decodedParams = decodeParams(await params);
const metadata = await generateMeetingMetadata(
meeting,
() => `${title} | ${profileName}`,
() => `${title}`,
isBrandingHidden,
getOrgFullOrigin(eventData?.entity.orgSlug ?? null),
`/instant-meeting/team/${decodedParams.slug}/${decodedParams.type}`
);
return {
...metadata,
robots: {
follow: !eventData?.hidden,
index: !eventData?.hidden,
},
};
};
const getData = withAppDirSsr<Props>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: _PageProps) => {
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
return <Page {...props} />;
};
export default ServerPage;
@@ -1,4 +0,0 @@
import Page from "app/(booking-page-wrapper)/team/[slug]/page";
export { generateMetadata } from "app/(booking-page-wrapper)/team/[slug]/page";
export default Page;
@@ -1,4 +0,0 @@
import Page from "app/(booking-page-wrapper)/team/[slug]/[type]/page";
export { generateMetadata } from "app/(booking-page-wrapper)/team/[slug]/[type]/page";
export default Page;
@@ -1,4 +0,0 @@
import Page from "app/(booking-page-wrapper)/team/[slug]/page";
export { generateMetadata } from "app/(booking-page-wrapper)/team/[slug]/page";
export default Page;
@@ -1,27 +0,0 @@
"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}`, "max");
}
// 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}`, "max");
}
@@ -1,42 +0,0 @@
import { CustomI18nProvider } from "app/CustomI18nProvider";
import withEmbedSsrAppDir from "app/WithEmbedSSR";
import type { PageProps as ServerPageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/team/[slug]/[type]/getServerSideProps";
import TypePage, { type PageProps as ClientPageProps } from "~/team/type-view";
export const generateMetadata = async () => {
return {
robots: {
follow: false,
index: false,
},
};
};
const getData = withEmbedSsrAppDir<ClientPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: ServerPageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(context);
const eventLocale = props.eventData?.interfaceLanguage;
if (eventLocale) {
const ns = "common";
const translations = await loadTranslations(eventLocale, ns);
return (
<CustomI18nProvider translations={translations} locale={eventLocale} ns={ns}>
<TypePage {...props} />
</CustomI18nProvider>
);
}
return <TypePage {...props} />;
};
export default ServerPage;
@@ -1,107 +0,0 @@
import { CustomI18nProvider } from "app/CustomI18nProvider";
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps, Params, 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/i18n/server";
import { prisma } from "@calcom/prisma";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
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,
getOrgContext,
} from "./pageWithCachedData";
import { getTeamId } from "./queries";
async function isCachedTeamBookingEnabled(params: Params, searchParams: SearchParams): Promise<boolean> {
if (searchParams.experimentalTeamBookingPageCache !== "true") return false;
const { teamSlug, currentOrgDomain, isValidOrgDomain } = await getOrgContext(params);
const orgSlug = isValidOrgDomain ? currentOrgDomain : null;
const teamId = await getTeamId(teamSlug, orgSlug);
if (!teamId) return false;
const featuresRepository = new FeaturesRepository(prisma);
const isTeamFeatureEnabled = await featuresRepository.checkIfTeamHasFeature(
teamId,
"team-booking-page-cache"
);
return isTeamFeatureEnabled;
}
export const generateMetadata = async ({ params, searchParams }: PageProps) => {
if (await isCachedTeamBookingEnabled(await params, 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;
const profileName = eventData?.profile?.name ?? "";
const profileImage = eventData?.profile.image;
const title = eventData?.title ?? "";
const meeting = {
title,
profile: { name: profileName, image: profileImage },
users: [
...(eventData?.users || []).map((user) => ({
name: `${user.name}`,
username: `${user.username}`,
})),
],
};
const decodedParams = decodeParams(await params);
const metadata = await generateMeetingMetadata(
meeting,
(t) => `${booking?.uid && !!booking ? t("reschedule") : ""} ${title} | ${profileName}`,
(t) => `${booking?.uid ? t("reschedule") : ""} ${title}`,
isBrandingHidden,
getOrgFullOrigin(eventData.entity.orgSlug ?? null),
`/team/${decodedParams.slug}/${decodedParams.type}`
);
return {
...metadata,
robots: {
follow: !(eventData?.hidden || !isSEOIndexable),
index: !(eventData?.hidden || !isSEOIndexable),
},
};
};
const getData = withAppDirSsr<LegacyPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: PageProps) => {
if (await isCachedTeamBookingEnabled(await params, await searchParams)) {
return await CachedTeamBooker({ params, searchParams });
}
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
const eventLocale = props.eventData?.interfaceLanguage;
if (eventLocale) {
const ns = "common";
const translations = await loadTranslations(eventLocale, ns);
return (
<CustomI18nProvider translations={translations} locale={eventLocale} ns={ns}>
<LegacyPage {...props} />
</CustomI18nProvider>
);
}
return <LegacyPage {...props} />;
};
export default ServerPage;
@@ -1,221 +0,0 @@
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/features/profile/lib/hideBranding";
import { loadTranslations } from "@calcom/i18n/server";
import slugify from "@calcom/lib/slugify";
import { BookingStatus, RedirectType } from "@calcom/prisma/enums";
import { buildLegacyCtx, buildLegacyRequest } from "@lib/buildLegacyCtx";
import { handleOrgRedirect } from "@lib/handleOrgRedirect";
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,
};
};
export 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 teamIsPrivate = teamData.isPrivate;
const meeting = {
title,
profile: { name: profileName, image: profileImage },
// Hide team member names in preview if team is private
users: teamIsPrivate
? []
: [
...(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 legacyCtx = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
// Handle org redirects
const redirectResult = await handleOrgRedirect({
slugs: [teamSlug],
redirectType: RedirectType.Team,
eventTypeSlug: meetingSlug,
context: legacyCtx,
currentOrgDomain: isValidOrgDomain ? currentOrgDomain : null,
});
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;
@@ -1,177 +0,0 @@
import type { GetServerSidePropsContext } from "next";
import { unstable_cache } from "next/cache";
import { eventTypeMetaDataSchemaWithTypedApps } from "@calcom/app-store/zod-utils";
import { getTeamData } from "@calcom/features/ee/teams/lib/getTeamData";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
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 { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { NEXTJS_CACHE_TTL } from "@calcom/lib/constants";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { prisma } from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
import type { SchedulingType } from "@calcom/prisma/enums";
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(prisma);
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"];
const crmRecordIdParam = query["cal.crmRecordId"];
const crmLookupDoneParam = query["cal.crmLookupDone"];
let teamMemberEmail = Array.isArray(crmContactOwnerEmail) ? crmContactOwnerEmail[0] : crmContactOwnerEmail;
let crmOwnerRecordType = Array.isArray(crmContactOwnerRecordType)
? crmContactOwnerRecordType[0]
: crmContactOwnerRecordType;
let crmAppSlug = Array.isArray(crmAppSlugParam) ? crmAppSlugParam[0] : crmAppSlugParam;
let crmRecordId = Array.isArray(crmRecordIdParam) ? crmRecordIdParam[0] : crmRecordIdParam;
// If crmLookupDone is true, the router already performed the CRM lookup, so skip it here
const crmLookupDone =
(Array.isArray(crmLookupDoneParam) ? crmLookupDoneParam[0] : crmLookupDoneParam) === "true";
if (!crmLookupDone && (!teamMemberEmail || !crmOwnerRecordType || !crmAppSlug)) {
const { getTeamMemberEmailForResponseOrContactUsingUrlQuery } = await import(
"@calcom/features/ee/teams/lib/getTeamMemberEmailFromCrm"
);
const {
email,
recordType,
crmAppSlug: crmAppSlugQuery,
recordId: crmRecordIdQuery,
} = await getTeamMemberEmailForResponseOrContactUsingUrlQuery({
query,
eventData,
});
teamMemberEmail = email ?? undefined;
crmOwnerRecordType = recordType ?? undefined;
crmAppSlug = crmAppSlugQuery ?? undefined;
crmRecordId = crmRecordIdQuery ?? undefined;
}
return {
teamMemberEmail,
crmOwnerRecordType,
crmAppSlug,
crmRecordId,
};
}
export async function getTeamId(teamSlug: string, orgSlug: string | null): Promise<number | null> {
const teamRepo = new TeamRepository(prisma);
const team = await teamRepo.findFirstBySlugAndParentSlug({
slug: teamSlug,
parentSlug: orgSlug,
select: { id: true },
});
return team?.id ?? null;
}
@@ -1,27 +0,0 @@
import withEmbedSsrAppDir from "app/WithEmbedSSR";
import type { PageProps as ServerPageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/team/[slug]/getServerSideProps";
import TeamPage, { type PageProps as ClientPageProps } from "~/team/team-view";
export const generateMetadata = async () => {
return {
robots: {
follow: false,
index: false,
},
};
};
const getData = withEmbedSsrAppDir<ClientPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: ServerPageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(context);
return <TeamPage {...props} />;
};
export default ServerPage;
@@ -1,53 +0,0 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps as _PageProps } from "app/_types";
import { generateMeetingMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { getOrgOrTeamAvatar } from "@calcom/lib/defaultAvatarImage";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/team/[slug]/getServerSideProps";
import type { PageProps } from "~/team/team-view";
import LegacyPage from "~/team/team-view";
export const generateMetadata = async ({ params, searchParams }: _PageProps) => {
const { team, markdownStrippedBio, isSEOIndexable, currentOrgDomain } = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
const meeting = {
title: markdownStrippedBio ?? "",
profile: {
name: `${team.name}`,
image: getOrgOrTeamAvatar(team),
},
};
const decodedParams = decodeParams(await params);
const metadata = await generateMeetingMetadata(
meeting,
(t) => team.name || t("nameless_team"),
(t) => team.name || t("nameless_team"),
false,
getOrgFullOrigin(currentOrgDomain ?? null),
`/team/${decodedParams.slug}`
);
return {
...metadata,
robots: {
follow: isSEOIndexable,
index: isSEOIndexable,
},
};
};
const getData = withAppDirSsr<PageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: _PageProps) => {
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
);
return <LegacyPage {...props} />;
};
export default ServerPage;
@@ -1,22 +1,14 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getScheduleListItemData } from "@calcom/lib/schedules/transformers/getScheduleListItemData";
import { availabilityRouter } from "@calcom/trpc/server/routers/viewer/availability/_router";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { createRouterCaller, getTRPCContext } from "app/_trpc/context";
import type { PageProps, ReadonlyHeaders, ReadonlyRequestCookies } from "app/_types";
import { _generateMetadata, getTranslate } from "app/_utils";
import { unstable_cache } from "next/cache";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getOrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.container";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { getScheduleListItemData } from "@calcom/lib/schedules/transformers/getScheduleListItemData";
import { MembershipRole } from "@calcom/prisma/enums";
import { availabilityRouter } from "@calcom/trpc/server/routers/viewer/availability/_router";
import { AvailabilitySliderTable } from "@calcom/web/modules/timezone-buddy/components/AvailabilitySliderTable";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { AvailabilityList, AvailabilityCTA } from "~/availability/availability-view";
import { AvailabilityCTA, AvailabilityList } from "~/availability/availability-view";
import { ShellMainAppDir } from "../ShellMainAppDir";
export const generateMetadata = async () => {
@@ -60,32 +52,12 @@ const Page = async ({ searchParams: _searchParams }: PageProps) => {
schedules: cachedAvailabilities.schedules.map((schedule) => getScheduleListItemData(schedule)),
};
const organizationId = session?.user?.profile?.organizationId ?? session?.user.org?.id;
const organizationRepository = getOrganizationRepository();
const isOrgPrivate = organizationId
? await organizationRepository.checkIfPrivate({
orgId: organizationId,
})
: false;
const permissionService = new PermissionCheckService();
const teamIdsWithPermission = await permissionService.getTeamIdsWithPermission({
userId: session.user.id,
permission: "availability.read",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
const canViewTeamAvailability = teamIdsWithPermission.length > 0 || !isOrgPrivate;
return (
<ShellMainAppDir
heading={t("availability")}
subtitle={t("configure_availability")}
CTA={<AvailabilityCTA canViewTeamAvailability={canViewTeamAvailability} />}>
{searchParams?.type === "team" && canViewTeamAvailability ? (
<AvailabilitySliderTable isOrg={!!organizationId} />
) : (
<AvailabilityList availabilities={availabilities ?? { schedules: [] }} />
)}
CTA={<AvailabilityCTA />}>
<AvailabilityList availabilities={availabilities ?? { schedules: [] }} />
</ShellMainAppDir>
);
};
@@ -1,10 +1,8 @@
"use client";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import SkeletonLoader from "@calcom/features/availability/components/SkeletonLoader";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import { AvailabilityCTA } from "~/availability/availability-view";
export default function AvailabilityLoader() {
@@ -14,7 +12,7 @@ export default function AvailabilityLoader() {
<ShellMainAppDir
heading={t("availability")}
subtitle={t("configure_availability")}
CTA={<AvailabilityCTA canViewTeamAvailability />}>
CTA={<AvailabilityCTA />}>
<SkeletonLoader />
</ShellMainAppDir>
);
@@ -1,5 +1,5 @@
// Added as a separate route for now to ease the testing of the audit logs feature
// It partially matches the figma design - https://www.figma.com/design/wleA2SR6rn60EK7ORxAfMy/Cal.com-New-Features?node-id=5641-6732&p=f
// It partially matches the figma design - https://www.figma.com/design/wleA2SR6rn60EK7ORxAfMy/Cal.diy-New-Features?node-id=5641-6732&p=f
// TOOD: Move it to the booking page side bar later
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import type { PageProps } from "app/_types";
@@ -1,8 +1,6 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getFeatureOptInService } from "@calcom/features/di/containers/FeatureOptInService";
import { getUserFeatureRepository } from "@calcom/features/di/containers/UserFeatureRepository";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { MembershipRole } from "@calcom/prisma/enums";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { prisma } from "@calcom/prisma";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import type { PageProps } from "app/_types";
import { _generateMetadata, getTranslate } from "app/_utils";
@@ -39,32 +37,16 @@ const Page = async ({ params }: PageProps) => {
}
const userId = session.user.id;
const permissionService = new PermissionCheckService();
const userFeatureRepository = getUserFeatureRepository();
const featuresRepository = new FeaturesRepository(prisma);
const teamIdsWithPermission = await permissionService.getTeamIdsWithPermission({
userId,
permission: "booking.read",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
// We check if teamIdsWithPermission.length > 0.
// While this may not be entirely accurate, it's acceptable
// because we perform a thorough validation on the server side for the actual filter values.
// This variable is primarily for UI purposes.
const canReadOthersBookings = teamIdsWithPermission.length > 0;
// No teams in cal.diy, so canReadOthersBookings is always false.
const canReadOthersBookings = false;
const featureOptInService = getFeatureOptInService();
const [bookingAuditEnabled, featureStates] = await Promise.all([
userFeatureRepository.checkIfUserHasFeature(userId, "booking-audit"),
featureOptInService.resolveFeatureStates({
userId,
featureIds: ["bookings-v3"],
}),
const [bookingAuditEnabled, bookingsV3Enabled] = await Promise.all([
featuresRepository.checkIfUserHasFeature(userId, "booking-audit"),
featuresRepository.checkIfUserHasFeature(userId, "bookings-v3"),
]);
const bookingsV3Enabled = featureStates["bookings-v3"]?.effectiveEnabled ?? false;
return (
<ShellMainAppDir
{...(!bookingsV3Enabled
@@ -1,45 +0,0 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { _generateMetadata, getTranslate } from "app/_utils";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getOrgMembersPageData } from "~/members/getOrgMembersPageData";
import { MembersView } from "~/members/members-view";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("organization_members"),
(t) => t("organization_description"),
undefined,
undefined,
"/members"
);
const Page = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user.id || !session?.user.profile?.organizationId || !session?.user.org) {
return redirect("/settings/my-account/profile");
}
const { org, teams, facetedTeamValues, attributes, permissions } = await getOrgMembersPageData(session);
const t = await getTranslate();
return (
<ShellMainAppDir heading={t("organization_members")} subtitle={t("organization_description")}>
<MembersView
org={org}
teams={teams}
facetedTeamValues={facetedTeamValues}
attributes={attributes}
permissions={permissions}
/>
</ShellMainAppDir>
);
};
export default Page;
@@ -1,24 +0,0 @@
"use client";
import posthog from "posthog-js";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
export const TeamsCTA = () => {
const { t } = useLocale();
return (
<Button
data-testid="new-team-btn"
variant="fab"
StartIcon="plus"
size="sm"
type="button"
onClick={() => {
posthog.capture("add_team_button_clicked");
}}
href={`${WEBAPP_URL}/settings/teams/new?returnTo=${WEBAPP_URL}/teams`}>
{t("new")}
</Button>
);
};
@@ -1,7 +0,0 @@
"use server";
import { updateTag } from "next/cache";
export async function revalidateTeamsList() {
updateTag("viewer.teams.list");
}
@@ -1,5 +0,0 @@
import { TeamsListSkeleton } from "./skeleton";
export default function Loading() {
return <TeamsListSkeleton />;
}
@@ -1,49 +0,0 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import type { PageProps as ServerPageProps } from "app/_types";
import { _generateMetadata, getTranslate } from "app/_utils";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { ServerTeamsListing } from "./server-page";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("teams"),
(t) => t("create_manage_teams_collaborative"),
undefined,
undefined,
"/teams"
);
const ServerPage = async ({ searchParams: _searchParams }: ServerPageProps) => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
const searchParams = await _searchParams;
const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token;
const autoAccept = Array.isArray(searchParams?.autoAccept)
? searchParams.autoAccept[0]
: searchParams?.autoAccept;
const callbackUrl = token
? `/teams?token=${encodeURIComponent(token)}${
autoAccept ? `&autoAccept=${encodeURIComponent(autoAccept)}` : ""
}`
: null;
if (!session) {
redirect(callbackUrl ? `/auth/login?callbackUrl=${callbackUrl}` : "/auth/login");
}
const t = await getTranslate();
const { Main, CTA, showHeader } = await ServerTeamsListing({ searchParams, session });
return (
<ShellMainAppDir
CTA={showHeader ? CTA : null}
heading={showHeader ? t("teams") : undefined}
subtitle={showHeader ? t("create_manage_teams_collaborative") : undefined}
flexChildrenContainer={!showHeader}>
{Main}
</ShellMainAppDir>
);
};
export default ServerPage;
@@ -1,99 +0,0 @@
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { TeamService } from "@calcom/features/ee/teams/services/teamService";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { ErrorWithCode } from "@calcom/lib/errors";
import prisma from "@calcom/prisma";
import { MembershipRole } from "@calcom/prisma/enums";
import type { SearchParams } from "app/_types";
import { unstable_cache } from "next/cache";
import type { Session } from "next-auth";
import { TeamsListing } from "~/ee/teams/components/TeamsListing";
import { TeamsCTA } from "./CTA";
const getCachedTeams = unstable_cache(
async (userId: number) => {
const teamRepo = new TeamRepository(prisma);
return await teamRepo.findTeamsByUserId({
userId,
includeOrgs: true,
});
},
undefined,
{ revalidate: 3600, tags: ["viewer.teams.list"] } // Cache for 1 hour
);
export const ServerTeamsListing = async ({
searchParams,
session,
}: {
searchParams: SearchParams;
session: Session;
}): Promise<{
Main: JSX.Element;
CTA: JSX.Element | null;
showHeader: boolean;
}> => {
const token = Array.isArray(searchParams?.token) ? searchParams.token[0] : searchParams?.token;
const autoAccept = Array.isArray(searchParams?.autoAccept)
? searchParams.autoAccept[0]
: searchParams?.autoAccept;
const userId = session.user.id;
let invitationAccepted = false;
let teamNameFromInvite,
errorMsgFromInvite = null;
if (token) {
try {
if (autoAccept === "true") {
await TeamService.acceptInvitationByToken(token, userId);
invitationAccepted = true;
} else {
teamNameFromInvite = await TeamService.inviteMemberByToken(token, userId);
}
} catch (e) {
errorMsgFromInvite = "Error while fetching teams";
if (e instanceof ErrorWithCode) errorMsgFromInvite = e.message;
}
}
const teams = await getCachedTeams(userId);
const userProfile = session?.user?.profile;
const orgId = userProfile?.organizationId ?? session?.user.org?.id;
// Filter to get accepted non-organization teams (same logic as TeamsListing)
const acceptedTeams = teams.filter((m) => m.accepted && !m.isOrganization);
// Check if user has a team plan (any accepted team with a slug)
const hasTeamPlan = teams.some((team) => team.accepted === true && team.slug !== null);
// Show header unless we're showing the upgrade banner (no teams and no team plan)
const showHeader = acceptedTeams.length > 0 || hasTeamPlan;
const permissionCheckService = new PermissionCheckService();
const canCreateTeam = orgId
? await permissionCheckService.checkPermission({
userId: session.user.id,
teamId: orgId,
permission: "team.create",
fallbackRoles: [MembershipRole.ADMIN, MembershipRole.OWNER],
})
: false;
return {
Main: (
<TeamsListing
invitationAccepted={invitationAccepted}
teams={teams}
orgId={orgId ?? null}
permissions={{
canCreateTeam: canCreateTeam,
}}
teamNameFromInvite={teamNameFromInvite ?? null}
errorMsgFromInvite={errorMsgFromInvite}
/>
),
CTA: !orgId || canCreateTeam ? <TeamsCTA /> : null,
showHeader,
};
};
@@ -1,14 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import SkeletonLoaderTeamList from "~/ee/teams/components/SkeletonloaderTeamList";
export const TeamsListSkeleton = () => {
const { t } = useLocale();
return (
<ShellMainAppDir heading={t("teams")} subtitle={t("create_manage_teams_collaborative")}>
<SkeletonLoaderTeamList />
</ShellMainAppDir>
);
};
@@ -1,393 +0,0 @@
"use client";
import { FieldTypes } from "@calcom/app-store/routing-forms/lib/FieldTypes";
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
import { LearnMoreLink } from "@calcom/features/eventtypes/components/LearnMoreLink";
import { getFieldIdentifier } from "@calcom/features/form-builder/utils/getFieldIdentifier";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { FormCard, FormCardBody } from "@calcom/ui/components/card";
import {
BooleanToggleGroupField,
Label,
MultiOptionInput,
SelectField,
TextField,
} from "@calcom/ui/components/form";
import { Tooltip } from "@calcom/ui/components/tooltip";
import type { getServerSidePropsForSingleFormView as getServerSideProps } from "@calcom/web/lib/apps/routing-forms/[...pages]/getServerSidePropsSingleForm";
import SingleForm from "@components/apps/routing-forms/SingleForm";
import { ChevronDownIcon, MenuIcon } from "@coss/ui/icons";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import type { inferSSRProps } from "@lib/types/inferSSRProps";
import type { UseFormReturn } from "react-hook-form";
import { Controller, useFieldArray, useWatch } from "react-hook-form";
import { Toaster } from "sonner";
import { v4 as uuidv4 } from "uuid";
type HookForm = UseFormReturn<RoutingFormWithResponseCount>;
function Field({
fieldIndex,
hookForm,
hookFieldNamespace,
deleteField,
moveUp,
moveDown,
appUrl,
disableTypeChange,
}: {
fieldIndex: number;
hookForm: HookForm;
hookFieldNamespace: `fields.${number}`;
deleteField: {
check: () => boolean;
fn: () => void;
};
moveUp: {
check: () => boolean;
fn: () => void;
};
moveDown: {
check: () => boolean;
fn: () => void;
};
appUrl: string;
disableTypeChange: boolean;
}) {
const { t } = useLocale();
const router = hookForm.getValues(`${hookFieldNamespace}.router`);
const routerField = hookForm.getValues(`${hookFieldNamespace}.routerField`);
const label = useWatch({
control: hookForm.control,
name: `${hookFieldNamespace}.label`,
});
const identifier = useWatch({
control: hookForm.control,
name: `${hookFieldNamespace}.identifier`,
});
const fieldType = useWatch({
control: hookForm.control,
name: `${hookFieldNamespace}.type`,
});
const preCountFieldLabel = label || routerField?.label || "Field";
const fieldLabel = `${fieldIndex + 1}. ${preCountFieldLabel}`;
return (
<div data-testid="field">
<FormCard
label={fieldLabel}
moveUp={moveUp}
moveDown={moveDown}
badge={
router
? {
text: router.name,
variant: "gray",
href: `${appUrl}/form-edit/${router.id}`,
}
: null
}
deleteField={router ? null : deleteField}>
<FormCardBody>
<div className="mb-3 w-full">
<TextField
data-testid={`${hookFieldNamespace}.label`}
disabled={!!router}
label="Label"
className="grow"
placeholder={t("this_is_what_your_users_would_see")}
defaultValue={label || routerField?.label || "Field"}
required
{...hookForm.register(`${hookFieldNamespace}.label`)}
onChange={(e) => {
const newLabel = e.target.value;
// Use label from useWatch which is guaranteed to be the previous value
// since useWatch updates reactively (after re-render), not synchronously
const previousLabel = label || "";
hookForm.setValue(`${hookFieldNamespace}.label`, newLabel, {
shouldDirty: true,
});
const currentIdentifier = hookForm.getValues(`${hookFieldNamespace}.identifier`);
// Only auto-update identifier if it was auto-generated from the previous label
// This preserves manual identifier changes
const isIdentifierGeneratedFromPreviousLabel =
currentIdentifier === getFieldIdentifier(previousLabel).toLowerCase();
if (!currentIdentifier || isIdentifierGeneratedFromPreviousLabel) {
hookForm.setValue(
`${hookFieldNamespace}.identifier`,
getFieldIdentifier(newLabel).toLowerCase(),
{ shouldDirty: true }
);
}
}}
/>
</div>
<div className="mb-3 w-full">
<TextField
disabled={!!router}
label={t("identifier_url_parameter")}
hint={
<LearnMoreLink
t={t}
i18nKey="identifier_url_parameter_hint"
href="https://cal.com/help/routing/connect-routing-form-to-booking-questions"
/>
}
name={`${hookFieldNamespace}.identifier`}
required
placeholder={t("identifies_name_field")}
value={identifier || routerField?.identifier || label || routerField?.label || ""}
onChange={(e) => {
hookForm.setValue(`${hookFieldNamespace}.identifier`, e.target.value.toLowerCase(), {
shouldDirty: true,
});
}}
/>
</div>
<div className="mb-3 w-full">
<Controller
name={`${hookFieldNamespace}.type`}
control={hookForm.control}
defaultValue={routerField?.type}
render={({ field: { value, onChange } }) => {
const defaultValue = FieldTypes.find((fieldType) => fieldType.value === value);
if (disableTypeChange) {
return (
<div className="data-testid-field-type">
<Label htmlFor="field-type-button">{t("type")}</Label>
<Tooltip content={t("field_type_change_suggestion")}>
<Button
type="button"
disabled
color="secondary"
className={classNames(
"h-8 w-full justify-between text-left text-sm",
!!router && "bg-subtle cursor-not-allowed"
)}>
<span className="text-default">{defaultValue?.label || t("select_field_type")}</span>
<ChevronDownIcon className="text-default h-4 w-4" />
</Button>
</Tooltip>
</div>
);
} else {
return (
<SelectField
maxMenuHeight={200}
styles={{
singleValue: (baseStyles) =>
Object.assign({}, baseStyles, {
fontSize: "14px",
}),
option: (baseStyles) =>
Object.assign({}, baseStyles, {
fontSize: "14px",
}),
}}
label="Type"
isDisabled={!!router}
containerClassName="data-testid-field-type"
options={FieldTypes}
onChange={(option) => {
if (!option) {
return;
}
onChange(option.value);
}}
defaultValue={defaultValue}
/>
);
}
}}
/>
</div>
{["select", "multiselect"].includes(fieldType) ? (
<div className="bg-cal-muted w-full rounded-[10px] p-2">
<Label className="text-subtle">{t("options")}</Label>
<MultiOptionInput
fieldArrayName={`${hookFieldNamespace}.options`}
disabled={!!router}
optionPlaceholders={["< 10", "10 - 100", "100 - 500", "> 500"]}
defaultNumberOfOptions={4}
pasteDelimiters={["\n", ","]}
showMoveButtons={true}
minOptions={1}
addOptionLabel={t("add_an_option")}
addOptionButtonColor="minimal"
/>
</div>
) : null}
<div className="w-[106px]">
<Controller
name={`${hookFieldNamespace}.required`}
control={hookForm.control}
defaultValue={routerField?.required}
render={({ field: { value, onChange } }) => {
return (
<BooleanToggleGroupField
variant="small"
disabled={!!router}
label={t("required")}
value={value}
onValueChange={onChange}
/>
);
}}
/>
</div>
</FormCardBody>
</FormCard>
</div>
);
}
const FormEdit = ({
hookForm,
form,
appUrl,
}: {
hookForm: HookForm;
form: inferSSRProps<typeof getServerSideProps>["form"];
appUrl: string;
}) => {
const fieldsNamespace = "fields";
const {
fields: hookFormFields,
append: appendHookFormField,
remove: removeHookFormField,
swap: swapHookFormField,
} = useFieldArray({
control: hookForm.control,
name: fieldsNamespace,
keyName: "_id",
});
const [animationRef] = useAutoAnimate<HTMLDivElement>();
const addField = () => {
appendHookFormField({
id: uuidv4(),
// This is same type from react-awesome-query-builder
type: "text",
label: "",
});
};
// hookForm.reset(form);
if (!form.fields) {
form.fields = [];
}
return hookFormFields.length ? (
<div className="w-full py-4 lg:py-8">
<div ref={animationRef} className="flex w-full flex-col rounded-md">
{hookFormFields.map((field, key) => {
const existingField = Boolean((form.fields || []).find((f) => f.id === field.id));
const hasFormResponses = (form._count?.responses ?? 0) > 0;
return (
<Field
appUrl={appUrl}
fieldIndex={key}
hookForm={hookForm}
hookFieldNamespace={`${fieldsNamespace}.${key}`}
disableTypeChange={existingField && hasFormResponses}
deleteField={{
check: () => hookFormFields.length > 1,
fn: () => {
removeHookFormField(key);
},
}}
moveUp={{
check: () => key !== 0,
fn: () => {
swapHookFormField(key, key - 1);
},
}}
moveDown={{
check: () => key !== hookFormFields.length - 1,
fn: () => {
if (key === hookFormFields.length - 1) {
return;
}
swapHookFormField(key, key + 1);
},
}}
key={field.id}
/>
);
})}
</div>
{hookFormFields.length ? (
<div className={classNames("flex")}>
<Button data-testid="add-field" type="button" StartIcon="plus" color="secondary" onClick={addField}>
Add question
</Button>
</div>
) : null}
</div>
) : (
<div className="w-full py-4 lg:py-8">
{/* TODO: remake empty screen for V3 */}
<div className="border-subtle bg-cal-muted flex flex-col items-center gap-6 rounded-xl border p-11">
<div className="mb-3 grid">
{/* Icon card - Top */}
<div className="bg-default border-subtle z-30 col-start-1 col-end-1 row-start-1 row-end-1 h-10 w-10 transform rounded-md border shadow-sm">
<div className="text-emphasis flex h-full items-center justify-center">
<MenuIcon className="text-emphasis h-4 w-4" />
</div>
</div>
{/* Left fanned card */}
<div
className="bg-default border-subtle z-20 col-start-1 col-end-1 row-start-1 row-end-1 h-10 w-10 rounded-md border shadow-sm"
style={{
transform: "translate(-12px, 2px) rotate(-6deg)",
}}
/>
{/* Right fanned card */}
<div
className="bg-default border-subtle z-10 col-start-1 col-end-1 row-start-1 row-end-1 h-10 w-10 rounded-md border shadow-sm"
style={{
transform: "translate(12px, 2px) rotate(6deg)",
}}
/>
</div>
<div>
<h1 className="text-emphasis text-emphasis text-center text-lg font-semibold">
Create your first question
</h1>
<p className="text-default mt-2 text-center text-sm leading-normal">
Fields are the form fields that the booker would see.
</p>
</div>
<Button data-testid="add-field" onClick={addField} StartIcon="plus" className="mt-6">
Add question
</Button>
</div>
</div>
);
};
export default function FormEditPage({
appUrl,
permissions,
...props
}: inferSSRProps<typeof getServerSideProps> & { appUrl: string }) {
return (
<>
<Toaster position="bottom-right" />
<SingleForm
{...props}
appUrl={appUrl}
permissions={permissions}
Page={({ hookForm, form }) => <FormEdit appUrl={appUrl} hookForm={hookForm} form={form} />}
/>
</>
);
}
@@ -1,9 +0,0 @@
"use client";
import { FormProvider as ReactHookFormProvider, useForm } from "react-hook-form";
export default function FormProvider({ children }: { children: React.ReactNode }) {
const methods = useForm();
return <ReactHookFormProvider {...methods}>{children}</ReactHookFormProvider>;
}
@@ -1,336 +0,0 @@
"use client";
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
import { SalesforceFieldType, WhenToWriteToRecord } from "@calcom/app-store/salesforce/lib/enums";
import type { writeToRecordDataSchema as salesforceWriteToRecordDataSchema } from "@calcom/app-store/salesforce/zod";
import { routingFormIncompleteBookingDataSchema as salesforceRoutingFormIncompleteBookingDataSchema } from "@calcom/app-store/salesforce/zod";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { IncompleteBookingActionType } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import { Button } from "@calcom/ui/components/button";
import { InputField, Label, Select, Switch } from "@calcom/ui/components/form";
import { showToast } from "@calcom/ui/components/toast";
import type { getServerSidePropsForSingleFormView as getServerSideProps } from "@calcom/web/lib/apps/routing-forms/[...pages]/getServerSidePropsSingleForm";
import SingleForm from "@components/apps/routing-forms/SingleForm";
import { GlobeIcon } from "@coss/ui/icons";
import { useEffect, useState } from "react";
import type z from "zod";
function Page({ form }: { form: RoutingFormWithResponseCount }) {
const { t } = useLocale();
const { data, isLoading } = trpc.viewer.appRoutingForms.getIncompleteBookingSettings.useQuery({
formId: form.id,
});
const mutation = trpc.viewer.appRoutingForms.saveIncompleteBookingSettings.useMutation({
onSuccess: () => {
showToast(t("success"), "success");
},
onError: (error) => {
showToast(t(`error: ${error.message}`), "error");
},
});
const [salesforceWriteToRecordObject, setSalesforceWriteToRecordObject] = useState<
z.infer<typeof salesforceWriteToRecordDataSchema>
>({});
// Handle just Salesforce for now but need to expand this to other apps
const [salesforceActionEnabled, setSalesforceActionEnabled] = useState<boolean>(false);
const fieldTypeOptions = [{ label: t("text"), value: SalesforceFieldType.TEXT }];
const [selectedFieldType, setSelectedFieldType] = useState(fieldTypeOptions[0]);
const whenToWriteToRecordOptions = [
{ label: t("on_every_instance"), value: WhenToWriteToRecord.EVERY_BOOKING },
{ label: t("only_if_field_is_empty"), value: WhenToWriteToRecord.FIELD_EMPTY },
];
const [selectedWhenToWrite, setSelectedWhenToWrite] = useState(whenToWriteToRecordOptions[0]);
const [newSalesforceAction, setNewSalesforceAction] = useState({
field: "",
fieldType: selectedFieldType.value,
value: "",
whenToWrite: WhenToWriteToRecord.FIELD_EMPTY,
});
const credentialOptions = data?.credentials.map((credential) => ({
label: credential.team?.name,
value: credential.id,
}));
const [selectedCredential, setSelectedCredential] = useState(
Array.isArray(credentialOptions) ? credentialOptions[0] : null
);
useEffect(() => {
const salesforceAction = data?.incompleteBookingActions.find(
(action) => action.actionType === IncompleteBookingActionType.SALESFORCE
);
if (salesforceAction) {
setSalesforceActionEnabled(salesforceAction.enabled);
const parsedSalesforceActionData = salesforceRoutingFormIncompleteBookingDataSchema.safeParse(
salesforceAction.data
);
if (parsedSalesforceActionData.success) {
setSalesforceWriteToRecordObject(parsedSalesforceActionData.data?.writeToRecordObject ?? {});
}
setSelectedCredential(
credentialOptions
? (credentialOptions.find((option) => option.value === salesforceAction?.credentialId) ??
selectedCredential)
: selectedCredential
);
}
}, [data]);
if (isLoading) {
return <div>Loading...</div>;
}
return (
<>
<div className="bg-default border-subtle mt-4 rounded-2xl border px-4 py-2">
<>
<div className="flex items-center justify-between">
<div className="flex items-center gap-0.5">
<div className="border-subtle rounded-lg border p-1">
<GlobeIcon className="text-subtle h-4 w-4" />
</div>
<div className="flex flex-col">
<span className="text-emphasis ml-2 text-sm font-medium">
Write to Salesforce contact/lead record
</span>
</div>
</div>
<Switch
size="sm"
checked={salesforceActionEnabled}
onCheckedChange={(checked) => {
setSalesforceActionEnabled(checked);
}}
/>
</div>
{salesforceActionEnabled ? (
<div className="bg-cal-muted mt-1 rounded-xl p-2">
{form.team && (
<>
<div className="bg-default mt-2 rounded-xl px-2 py-2">
<Label>Credential to use</Label>
<Select
size="sm"
options={credentialOptions}
value={selectedCredential}
onChange={(option) => {
if (!option) {
return;
}
setSelectedCredential(option);
}}
/>
</div>
</>
)}
<div className="bg-default mt-2 rounded-xl px-2 py-2">
<div className="hidden md:grid md:grid-cols-5 md:gap-4">
<Label>{t("field_name")}</Label>
<Label>{t("field_type")}</Label>
<Label>{t("value")}</Label>
<Label>{t("when_to_write")}</Label>
</div>
<div>
{Object.keys(salesforceWriteToRecordObject).map((key) => {
const action =
salesforceWriteToRecordObject[key as keyof typeof salesforceWriteToRecordObject];
return (
<div
className="mt-2 border-subtle flex flex-col gap-3 rounded-lg border p-3 md:mt-2 md:grid md:grid-cols-5 md:gap-4 md:border-0 md:p-0"
key={key}>
<div className="w-full">
<Label className="md:hidden">{t("field_name")}</Label>
<InputField value={key} readOnly />
</div>
<div className="w-full">
<Label className="md:hidden">{t("field_type")}</Label>
<Select
value={fieldTypeOptions.find((option) => option.value === action.fieldType)}
isDisabled={true}
/>
</div>
<div className="w-full">
<Label className="md:hidden">{t("value")}</Label>
<InputField value={action.value as string} readOnly />
</div>
<div className="w-full">
<Label className="md:hidden">{t("when_to_write")}</Label>
<Select
value={whenToWriteToRecordOptions.find(
(option) => option.value === action.whenToWrite
)}
isDisabled={true}
/>
</div>
<div className="flex justify-end md:justify-start">
<Button
StartIcon="trash"
variant="icon"
color="destructive"
onClick={() => {
const newActions = { ...salesforceWriteToRecordObject };
delete newActions[key];
setSalesforceWriteToRecordObject(newActions);
}}
/>
</div>
</div>
);
})}
<div className="mt-2 border-subtle flex flex-col gap-4 rounded-lg border p-3 md:mt-2 md:grid md:grid-cols-5 md:gap-4 md:border-0 md:p-0">
<div>
<Label className="md:hidden">{t("field_name")}</Label>
<InputField
size="sm"
value={newSalesforceAction.field}
onChange={(e) =>
setNewSalesforceAction({
...newSalesforceAction,
field: e.target.value,
})
}
/>
</div>
<div>
<Label className="md:hidden">{t("field_type")}</Label>
<Select
size="sm"
options={fieldTypeOptions}
value={selectedFieldType}
onChange={(e) => {
if (e) {
setSelectedFieldType(e);
setNewSalesforceAction({
...newSalesforceAction,
fieldType: e.value,
});
}
}}
/>
</div>
<div>
<Label className="md:hidden">{t("value")}</Label>
<InputField
size="sm"
value={newSalesforceAction.value}
onChange={(e) =>
setNewSalesforceAction({
...newSalesforceAction,
value: e.target.value,
})
}
/>
</div>
<div>
<Label className="md:hidden">{t("when_to_write")}</Label>
<Select
size="sm"
options={whenToWriteToRecordOptions}
value={selectedWhenToWrite}
onChange={(e) => {
if (e) {
setSelectedWhenToWrite(e);
setNewSalesforceAction({
...newSalesforceAction,
whenToWrite: e.value,
});
}
}}
/>
</div>
</div>
</div>
<Button
className="mt-2"
size="sm"
disabled={
!(
newSalesforceAction.field &&
newSalesforceAction.fieldType &&
newSalesforceAction.value &&
newSalesforceAction.whenToWrite
)
}
onClick={() => {
if (
Object.keys(salesforceWriteToRecordObject).includes(newSalesforceAction.field.trim())
) {
showToast("Field already exists", "error");
return;
}
setSalesforceWriteToRecordObject({
...salesforceWriteToRecordObject,
[newSalesforceAction.field]: {
fieldType: newSalesforceAction.fieldType,
value: newSalesforceAction.value,
whenToWrite: newSalesforceAction.whenToWrite,
},
});
setNewSalesforceAction({
field: "",
fieldType: selectedFieldType.value,
value: "",
whenToWrite: WhenToWriteToRecord.FIELD_EMPTY,
});
}}>
{t("add_new_field")}
</Button>
</div>
</div>
) : null}
<div className="mt-2 flex justify-end">
<Button
size="sm"
disabled={mutation.isPending}
onClick={() => {
mutation.mutate({
formId: form.id,
data: {
writeToRecordObject: salesforceWriteToRecordObject,
},
actionType: IncompleteBookingActionType.SALESFORCE,
enabled: salesforceActionEnabled,
credentialId: selectedCredential?.value ?? data?.credentials[0].id,
});
}}>
{t("save")}
</Button>
</div>
</>
</div>
</>
);
}
export default function IncompleteBookingPage({
form,
appUrl,
enrichedWithUserProfileForm,
permissions,
}: inferSSRProps<typeof getServerSideProps> & { appUrl: string }) {
return (
<SingleForm
form={form}
appUrl={appUrl}
enrichedWithUserProfileForm={enrichedWithUserProfileForm}
permissions={permissions}
Page={Page}
/>
);
}
File diff suppressed because it is too large. Load diff
@@ -1,9 +0,0 @@
"use client";
import { useRedirectToLoginIfUnauthenticated } from "@calcom/web/modules/auth/hooks/useRedirectToLoginIfUnauthenticated";
export function RoutingFormAuthGuard({ children }: { children: React.ReactNode }) {
useRedirectToLoginIfUnauthenticated();
return <>{children}</>;
}
@@ -1,247 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import type { FormEvent } from "react";
import { useEffect, useRef, useState } from "react";
import { Toaster } from "sonner";
import { v4 as uuidv4 } from "uuid";
import FormInputFields from "@calcom/app-store/routing-forms/components/FormInputFields";
import { getAbsoluteEventTypeRedirectUrlWithEmbedSupport } from "@calcom/app-store/routing-forms/getEventTypeRedirectUrl";
import getFieldIdentifier from "@calcom/app-store/routing-forms/lib/getFieldIdentifier";
import { findMatchingRoute } from "@calcom/app-store/routing-forms/lib/processRoute";
import { substituteVariables } from "@calcom/app-store/routing-forms/lib/substituteVariables";
import { getFieldResponseForJsonLogic } from "@calcom/app-store/routing-forms/lib/transformResponse";
import type { NonRouterRoute, FormResponse } from "@calcom/app-store/routing-forms/types/types";
import { sdkActionManager, useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { getUrlSearchParamsToForward } from "@calcom/features/routing-forms/lib/getUrlSearchParamsToForward";
import useGetBrandingColours from "@calcom/lib/getBrandColours";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useTheme from "@calcom/lib/hooks/useTheme";
import { markdownToSafeHTMLClient } from "@calcom/lib/markdownToSafeHTMLClient";
import { navigateInTopWindow } from "@calcom/lib/navigateInTopWindow";
import { trpc } from "@calcom/trpc/react";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { showToast } from "@calcom/ui/components/toast";
import { useCalcomTheme } from "@calcom/ui/styles";
import type { getServerSideProps } from "@calcom/web/lib/apps/routing-forms/[...pages]/getServerSidePropsRoutingLink";
type Props = inferSSRProps<typeof getServerSideProps>;
const useBrandColors = ({
brandColor,
darkBrandColor,
}: {
brandColor?: string | null;
darkBrandColor?: string | null;
}) => {
const brandTheme = useGetBrandingColours({
lightVal: brandColor,
darkVal: darkBrandColor,
});
useCalcomTheme(brandTheme);
};
function RoutingForm({ form, profile, ...restProps }: Props) {
const [customPageMessage, setCustomPageMessage] = useState<NonRouterRoute["action"]["value"]>("");
const formFillerIdRef = useRef(uuidv4());
const isEmbed = useIsEmbed(restProps.isEmbed);
useTheme(profile.theme);
useBrandColors({
brandColor: profile.brandColor,
darkBrandColor: profile.darkBrandColor,
});
const [response, setResponse] = usePrefilledResponse(form);
const pageSearchParams = useCompatSearchParams();
const isBookingDryRun = pageSearchParams?.get("cal.isBookingDryRun") === "true";
// TODO: We might want to prevent spam from a single user by having same formFillerId across pageviews
// But technically, a user can fill form multiple times due to any number of reasons and we currently can't differentiate b/w that.
// - like a network error
// - or he abandoned booking flow in between
const formFillerId = formFillerIdRef.current;
const chosenRouteWithFormResponseRef = useRef<{
route: NonRouterRoute;
response: FormResponse;
}>();
const router = useRouter();
const onSubmit = (response: FormResponse) => {
const chosenRoute = findMatchingRoute({ form, response });
if (!chosenRoute) {
// This error should never happen as we ensure that fallback route is always there that matches always
throw new Error("No matching route found");
}
responseMutation.mutate({
formId: form.id,
formFillerId,
response: response,
chosenRouteId: chosenRoute.id,
isPreview: isBookingDryRun,
});
chosenRouteWithFormResponseRef.current = {
route: chosenRoute,
response,
};
};
useEffect(() => {
// Custom Page doesn't actually change Route, so fake it so that embed can adjust the scroll to make the content visible
sdkActionManager?.fire("__routeChanged", {});
}, [customPageMessage]);
const responseMutation = trpc.viewer.routingForms.public.response.useMutation({
onSuccess: async (data) => {
const {
teamMembersMatchingAttributeLogic,
formResponse,
queuedFormResponse,
attributeRoutingConfig,
crmContactOwnerEmail,
crmContactOwnerRecordType,
crmAppSlug,
} = data;
const chosenRouteWithFormResponse = chosenRouteWithFormResponseRef.current;
if (!chosenRouteWithFormResponse) {
return;
}
const fields = form.fields;
if (!fields) {
throw new Error("Routing Form fields must exist here");
}
const allURLSearchParams = getUrlSearchParamsToForward({
formResponse: chosenRouteWithFormResponse.response,
formResponseId: formResponse?.id ?? null,
queuedFormResponseId: queuedFormResponse?.id ?? null,
fields,
searchParams: new URLSearchParams(window.location.search),
teamMembersMatchingAttributeLogic,
attributeRoutingConfig: attributeRoutingConfig ?? null,
crmContactOwnerEmail,
crmContactOwnerRecordType,
crmAppSlug,
});
const chosenRoute = chosenRouteWithFormResponse.route;
const decidedAction = chosenRoute.action;
sdkActionManager?.fire("routed", {
actionType: decidedAction.type,
actionValue: decidedAction.value,
});
//TODO: Maybe take action after successful mutation
if (decidedAction.type === "customPageMessage") {
setCustomPageMessage(decidedAction.value);
} else if (decidedAction.type === "eventTypeRedirectUrl") {
const eventTypeUrlWithResolvedVariables = substituteVariables(decidedAction.value, response, fields);
router.push(
getAbsoluteEventTypeRedirectUrlWithEmbedSupport({
form,
eventTypeRedirectUrl: eventTypeUrlWithResolvedVariables,
allURLSearchParams,
isEmbed: !!isEmbed,
})
);
} else if (decidedAction.type === "externalRedirectUrl") {
navigateInTopWindow(`${decidedAction.value}?${allURLSearchParams}`);
}
// We don't want to show this message as it doesn't look good in Embed.
// showToast("Form submitted successfully! Redirecting now ...", "success");
},
onError: (e) => {
if (e?.message) {
return void showToast(e?.message, "error");
}
if (e?.data?.code === "CONFLICT") {
return void showToast("Form already submitted", "error");
}
// We don't want to show this error as it doesn't look good in Embed.
// showToast("Something went wrong", "error");
},
});
const handleOnSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
onSubmit(response);
};
const { t } = useLocale();
return (
<div>
<div>
{!customPageMessage ? (
<>
<div className={classNames("mx-auto my-0 max-w-3xl", isEmbed ? "" : "md:my-24")}>
<div className="w-full max-w-4xl ltr:mr-2 rtl:ml-2">
<div className="main border-booker md:border-booker-width dark:bg-cal-muted bg-default mx-0 rounded-md p-4 py-6 sm:-mx-4 sm:px-8 ">
<Toaster position="bottom-right" />
<form onSubmit={handleOnSubmit}>
<div className="mb-8">
<h1 className="font-cal text-emphasis mb-1 text-xl font-semibold tracking-wide">
{form.name}
</h1>
{form.description ? (
<p className="min-h-10 text-subtle text-sm ltr:mr-4 rtl:ml-4">{form.description}</p>
) : null}
</div>
<FormInputFields form={form} response={response} setResponse={setResponse} />
<div className="mt-4 flex justify-end space-x-2 rtl:space-x-reverse">
<Button
className="dark:bg-darkmodebrand dark:text-darkmodebrandcontrast dark:hover:border-darkmodebrandcontrast dark:border-transparent"
loading={responseMutation.isPending}
type="submit"
color="primary">
{t("continue")}
</Button>
</div>
</form>
</div>
</div>
</div>
</>
) : (
<div className="mx-auto my-0 max-w-3xl md:my-24">
<div className="w-full max-w-4xl ltr:mr-2 rtl:ml-2">
<div className="main sm:border-subtle bg-default -mx-4 rounded-md border border-neutral-200 p-4 py-6 sm:mx-0 sm:px-8">
{/* biome-ignore lint/security/noDangerouslySetInnerHtml: Content is sanitized via markdownToSafeHTMLClient */}
<div
className="text-emphasis prose prose-sm dark:prose-invert max-w-none"
dangerouslySetInnerHTML={{ __html: markdownToSafeHTMLClient(customPageMessage) }}
/>
</div>
</div>
</div>
)}
</div>
</div>
);
}
export default function RoutingLink(props: inferSSRProps<typeof getServerSideProps>) {
return <RoutingForm {...props} />;
}
const usePrefilledResponse = (form: Props["form"]) => {
const searchParams = useCompatSearchParams();
const prefillResponse: FormResponse = {};
// Prefill the form from query params
form.fields?.forEach((field) => {
const valuesFromQuery = searchParams?.getAll(getFieldIdentifier(field)).filter(Boolean) ?? [];
// We only want to keep arrays if the field is a multi-select
const value = valuesFromQuery.length > 1 ? valuesFromQuery : valuesFromQuery[0];
prefillResponse[field.id] = {
value: getFieldResponseForJsonLogic({ field, value }),
label: field.label,
};
});
const [response, setResponse] = useState<FormResponse>(prefillResponse);
return [response, setResponse] as const;
};
@@ -1,6 +0,0 @@
export const routingFormsComponents = {
"form-edit": () => import("./FormEdit").then((mod) => mod.default),
"route-builder": () => import("./RouteBuilder").then((mod) => mod.default),
"routing-link": () => import("./RoutingLink").then((mod) => mod.default),
"incomplete-booking": () => import("./IncompleteBooking").then((mod) => mod.default),
};
@@ -1,23 +0,0 @@
import type { ReactNode } from "react";
import FormProvider from "./FormProvider";
import { RoutingFormAuthGuard } from "./RoutingFormAuthGuard";
interface LayoutProps {
children: ReactNode;
params: Promise<{ pages: string[] }>;
}
export default async function Layout({ children, params }: LayoutProps) {
const { pages } = await params;
const isPublic = pages?.[0] === "routing-link";
if (isPublic) {
return <FormProvider>{children}</FormProvider>;
}
return (
<RoutingFormAuthGuard>
<FormProvider>{children}</FormProvider>
</RoutingFormAuthGuard>
);
}
@@ -1,42 +0,0 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps as ServerPageProps } from "app/_types";
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import type { routingServerSidePropsConfig } from "@lib/apps/routing-forms/[...pages]/app-routing.server-config";
import { getServerSideProps } from "@lib/apps/routing-forms/[...pages]/getServerSideProps";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import { routingFormsComponents } from "./app-routing.client-config";
const normalizePages = (pages: string[] | string | undefined) => {
const normalizedPages = Array.isArray(pages) ? pages : (pages?.split("/") ?? []);
return normalizedPages[0];
};
export const generateMetadata = async ({ params }: { params: Promise<{ pages: string[] }> }) => {
const mainPage = normalizePages((await params).pages);
return await _generateMetadata(
(t) => (mainPage === "routing-link" ? `Form | Cal.com Forms` : `${t("routing_forms")} | Cal.com Forms`),
() => "",
undefined,
undefined,
`/routing/${(await params).pages.join("/")}`
);
};
type GetServerSidePropsResult =
(typeof routingServerSidePropsConfig)[keyof typeof routingServerSidePropsConfig];
const getData = withAppDirSsr<GetServerSidePropsResult>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: ServerPageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(context);
const mainPage = normalizePages((await params).pages);
const Component = await routingFormsComponents[mainPage as keyof typeof routingFormsComponents]();
return <Component {...(props as any)} />;
};
export default ServerPage;
@@ -1,288 +0,0 @@
"use client";
import { isFallbackRoute } from "@calcom/app-store/routing-forms/lib/isFallbackRoute";
import type { RoutingFormWithResponseCount } from "@calcom/app-store/routing-forms/types/types";
import { FilterResults } from "~/filters/components/FilterResults";
import { TeamsFilter } from "~/filters/components/TeamsFilter";
import { getTeamsFiltersFromQuery } from "@calcom/features/filters/lib/getTeamsFiltersFromQuery";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { MembershipRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { ArrowButton } from "@calcom/ui/components/arrow-button";
import { Badge } from "@calcom/ui/components/badge";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
import { List, ListLinkItem } from "@calcom/ui/components/list";
import { Tooltip } from "@calcom/ui/components/tooltip";
import type {
NewFormDialogState,
SetNewFormDialogState,
} from "@calcom/web/components/apps/routing-forms/FormActions";
import {
FormAction,
FormActionsDropdown,
FormActionsProvider,
} from "@calcom/web/components/apps/routing-forms/FormActions";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import posthog from "posthog-js";
import { useEffect, useState } from "react";
import { useFormContext } from "react-hook-form";
import { useHasPaidPlan, useHasTeamPlan } from "~/billing/hooks/useHasPaidPlan";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import { CreateButtonWithTeamsList } from "~/ee/teams/components/createButton/CreateButtonWithTeamsList";
import SkeletonLoaderTeamList from "~/ee/teams/components/SkeletonloaderTeamList";
import { ShellMain } from "~/shell/Shell";
function NewFormButton({ setNewFormDialogState }: { setNewFormDialogState: SetNewFormDialogState }) {
const { t } = useLocale();
return (
<CreateButtonWithTeamsList
subtitle={t("create_routing_form_on").toUpperCase()}
data-testid="new-routing-form"
createFunction={(teamId) => {
setNewFormDialogState({ action: "new", target: teamId ? String(teamId) : "" });
posthog.capture("new_routing_form_button_clicked", { teamId });
}}
withPermission={{
permission: "routingForm.create",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
}}
/>
);
}
export default function RoutingForms({ appUrl }: { appUrl: string }) {
const { t } = useLocale();
const { hasPaidPlan } = useHasPaidPlan();
const { hasTeamPlan, isPending: isPendingTeamPlan } = useHasTeamPlan();
const routerQuery = useRouterQuery();
const hookForm = useFormContext<RoutingFormWithResponseCount>();
const utils = trpc.useUtils();
const [parent] = useAutoAnimate<HTMLUListElement>();
const mutation = trpc.viewer.loggedInViewerRouter.routingFormOrder.useMutation({
onError: async (err) => {
console.error(err.message);
await utils.viewer.appRoutingForms.forms.cancel();
await utils.viewer.appRoutingForms.invalidate();
},
onSettled: () => {
utils.viewer.appRoutingForms.invalidate();
},
});
useEffect(() => {
hookForm.reset({});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const filters = getTeamsFiltersFromQuery(routerQuery);
const queryRes = trpc.viewer.appRoutingForms.forms.useQuery({
filters,
});
const [newFormDialogState, setNewFormDialogState] = useState<NewFormDialogState>(null);
const forms = queryRes.data?.filtered;
async function moveRoutingForm(index: number, increment: 1 | -1) {
const types = forms?.map((type) => {
return type.form;
});
if (types?.length) {
const newList = [...types];
const type = types[index];
const tmp = types[index + increment];
if (tmp) {
newList[index] = tmp;
newList[index + increment] = type;
}
await utils.viewer.appRoutingForms.forms.cancel();
mutation.mutate({
ids: newList?.map((type) => type.id),
});
}
}
return (
<LicenseRequired>
<ShellMain
disableSticky={true}
heading={t("routing")}
CTA={
hasPaidPlan && forms?.length ? (
<NewFormButton setNewFormDialogState={setNewFormDialogState} />
) : null
}
subtitle={t("routing_forms_description")}>
{isPendingTeamPlan && <SkeletonLoaderTeamList />}
{!isPendingTeamPlan && hasTeamPlan && (
<FormActionsProvider
appUrl={appUrl}
newFormDialogState={newFormDialogState}
setNewFormDialogState={setNewFormDialogState}>
<div className="mb-10 w-full">
<div className="mb-2 flex">
<TeamsFilter />
</div>
<FilterResults
queryRes={queryRes}
emptyScreen={
<EmptyScreen
Icon="git-merge"
headline={t("create_your_first_form")}
description={t("create_your_first_form_description")}
buttonRaw={<NewFormButton setNewFormDialogState={setNewFormDialogState} />}
/>
}
noResultsScreen={
<EmptyScreen
Icon="git-merge"
headline={t("no_results_for_filter")}
description={t("change_filter_common")}
/>
}
SkeletonLoader={SkeletonLoaderTeamList}>
<div className="bg-default mb-16 overflow-hidden">
<List data-testid="routing-forms-list" ref={parent}>
{forms?.map(({ form, readOnly, hasError }, index) => {
// Make the form read only if it has an error
// TODO: Consider showing error in UI so user can report and get it fixed.
readOnly = readOnly || hasError;
if (!form) {
return null;
}
const description = form.description || "";
form.routes = form.routes || [];
const fields = form.fields || [];
const userRoutes = form.routes.filter((route) => !isFallbackRoute(route));
const firstItem = forms[0].form;
const lastItem = forms[forms.length - 1].form;
return (
<div
className="group flex w-full max-w-full items-center justify-between overflow-hidden"
key={form.id}>
{!(firstItem && firstItem.id === form.id) && (
<ArrowButton onClick={() => moveRoutingForm(index, -1)} arrowDirection="up" />
)}
{!(lastItem && lastItem.id === form.id) && (
<ArrowButton onClick={() => moveRoutingForm(index, 1)} arrowDirection="down" />
)}
<ListLinkItem
href={`${appUrl}/form-edit/${form.id}`}
heading={form.name}
readOnly={readOnly}
subHeading={description}
className="space-x-2 rtl:space-x-reverse"
actions={
<>
{form.team?.name && (
<div className="border-subtle border-r-2">
<Badge className="ltr:mr-2 rtl:ml-2" variant="gray">
{form.team.name}
</Badge>
</div>
)}
<FormAction
disabled={readOnly}
className="self-center"
action="toggle"
routingForm={form}
/>
<ButtonGroup combined>
<Tooltip content={t("preview")}>
<FormAction
action="preview"
routingForm={form}
target="_blank"
StartIcon="external-link"
color="secondary"
variant="icon"
/>
</Tooltip>
<FormAction
routingForm={form}
action="copyLink"
color="secondary"
variant="icon"
StartIcon="link"
tooltip={t("copy_link_to_form")}
/>
<FormAction
routingForm={form}
action="embed"
color="secondary"
variant="icon"
StartIcon="code"
tooltip={t("embed")}
/>
<FormActionsDropdown disabled={readOnly}>
<FormAction
action="edit"
routingForm={form}
color="minimal"
className="flex!"
StartIcon="pencil">
{t("edit")}
</FormAction>
<FormAction
action="download"
routingForm={form}
color="minimal"
StartIcon="download">
{t("download_responses")}
</FormAction>
<FormAction
action="duplicate"
routingForm={form}
color="minimal"
className="w-full"
StartIcon="copy">
{t("duplicate")}
</FormAction>
<FormAction
action="_delete"
routingForm={form}
color="destructive"
className="w-full rounded-t-none"
StartIcon="trash">
{t("delete")}
</FormAction>
</FormActionsDropdown>
</ButtonGroup>
</>
}>
<div className="flex flex-wrap gap-1">
<Badge variant="gray" startIcon="menu">
{fields.length} {fields.length === 1 ? "field" : "fields"}
</Badge>
<Badge variant="gray" startIcon="git-merge">
{userRoutes.length} {userRoutes.length === 1 ? "route" : "routes"}
</Badge>
<Badge variant="gray" startIcon="message-circle">
{form._count.responses}{" "}
{form._count.responses === 1 ? "response" : "responses"}
</Badge>
</div>
</ListLinkItem>
</div>
);
})}
</List>
</div>
</FilterResults>
</div>
</FormActionsProvider>
)}
</ShellMain>
</LicenseRequired>
);
}
@@ -1,33 +0,0 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { FullscreenUpgradeBannerForRoutingFormPage } from "@calcom/web/modules/billing/upgrade-banners/FullscreenUpgradeBannerForRoutingFormPage";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import Forms from "./Forms";
export const generateMetadata = async ({ params }: { params: Promise<{ pages: string[] }> }) => {
const pages = (await params).pages;
return await _generateMetadata(
(t) => `${t("routing_forms")} | Cal.com Forms`,
() => "",
undefined,
undefined,
`/routing/forms/${pages?.length > 0 ? pages.join("/") : ""}`
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
const userId = session?.user?.id;
const hasTeamPlan = userId && (await MembershipRepository.hasAnyAcceptedMembershipByUserId(userId));
if (!hasTeamPlan) {
return <FullscreenUpgradeBannerForRoutingFormPage />;
}
return <Forms appUrl="/routing" />;
};
export default ServerPage;
@@ -1,24 +0,0 @@
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import type { ReactNode } from "react";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import Shell from "~/shell/Shell";
import FormProvider from "../[...pages]/FormProvider";
export default async function Layout({ children }: { children: ReactNode }) {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
redirect("/auth/login");
}
return (
<Shell withoutMain={true}>
<FormProvider>{children}</FormProvider>
</Shell>
);
}
@@ -1,18 +0,0 @@
import type { PageProps } from "app/_types";
import { notFound } from "next/navigation";
import { z } from "zod";
import SamlIdpClient from "~/auth/saml-idp/saml-idp-view";
const querySchema = z.object({
code: z.string(),
});
export default async function SamlIdpPage({ searchParams }: PageProps) {
const parsed = querySchema.safeParse(await searchParams);
if (!parsed.success) {
notFound();
}
return <SamlIdpClient code={parsed.data.code} />;
}
@@ -1,20 +0,0 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@server/lib/auth/sso/[provider]/getServerSideProps";
import type { SSOProviderPageProps } from "~/auth/sso/provider-view";
import SSOProviderView from "~/auth/sso/provider-view";
const getData = withAppDirSsr<SSOProviderPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: PageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(context);
return <SSOProviderView {...props} />;
};
export default ServerPage;
@@ -1,20 +0,0 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { PageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@server/lib/auth/sso/direct/getServerSideProps";
import type { SSODirectPageProps } from "~/auth/sso/direct-view";
import SSODirectView from "~/auth/sso/direct-view";
const getData = withAppDirSsr<SSODirectPageProps>(getServerSideProps);
const ServerPage = async ({ params, searchParams }: PageProps) => {
const context = buildLegacyCtx(await headers(), await cookies(), await params, await searchParams);
const props = await getData(context);
return <SSODirectView {...props} />;
};
export default ServerPage;
@@ -1,24 +0,0 @@
import { _generateMetadata } from "app/_utils";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import LegacyPage from "~/connect-and-join/connect-and-join-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => t("connect_and_join"),
() => "",
undefined,
undefined,
"/connect-and-join"
);
};
const ServerPage = async () => {
return (
<LicenseRequired>
<LegacyPage />
</LicenseRequired>
);
};
export default ServerPage;
@@ -1,18 +1,5 @@
import { _generateMetadata } from "app/_utils";
import { redirect } from "next/navigation";
import EnterprisePage from "@components/EnterprisePage";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("create_your_org"),
(t) => t("create_your_org_description"),
undefined,
undefined,
"/enterprise"
);
const ServerPageWrapper = async () => {
return <EnterprisePage />;
};
export default ServerPageWrapper;
export default function ServerPageWrapper() {
redirect("/");
}
@@ -1,3 +1,7 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { eventTypesRouter } from "@calcom/trpc/server/routers/viewer/eventTypes/_router";
import { EventTypeWebWrapper } from "@calcom/web/modules/event-types/components/EventTypeWebWrapper";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { createRouterCaller, getTRPCContext } from "app/_trpc/context";
import type { PageProps, ReadonlyHeaders, ReadonlyRequestCookies } from "app/_types";
import { _generateMetadata } from "app/_utils";
@@ -6,17 +10,10 @@ import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { z } from "zod";
import { EventTypeWebWrapper } from "@calcom/web/modules/event-types/components/EventTypeWebWrapper";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { getEventTypePermissions } from "@calcom/features/pbac/lib/event-type-permissions";
import { eventTypesRouter } from "@calcom/trpc/server/routers/viewer/eventTypes/_router";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
const querySchema = z.object({
type: z
.string()
.refine((val) => !isNaN(Number(val)), {
.refine((val) => !Number.isNaN(Number(val)), {
message: "event-type id must be a string that can be cast to a number",
})
.transform((val) => Number(val)),
@@ -61,7 +58,9 @@ const ServerPage = async ({ params }: PageProps) => {
}
// Fetch permissions for the event type's team
const permissions = await getEventTypePermissions(session.user.id, data.eventType.teamId);
const permissions = {
eventTypes: { canRead: true, canCreate: true, canUpdate: true, canDelete: true },
};
return <EventTypeWebWrapper data={data} id={eventTypeId} permissions={permissions} />;
};
@@ -1,63 +0,0 @@
"use client";
import { useSession } from "next-auth/react";
import { usePathname } from "next/navigation";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
import { RefreshCcwIcon, UserPlusIcon, UsersIcon } from "@coss/ui/icons";
import { UpgradeTip } from "~/shell/UpgradeTip";
export default function UpgradeTipWrapper({ children }: { children: React.ReactNode }) {
const { t } = useLocale();
const session = useSession();
const pathname = usePathname();
if (pathname?.startsWith("/insights/call-history")) {
return !session.data?.user ? null : <>{children}</>;
}
const features = [
{
icon: <UsersIcon className="h-5 w-5 text-red-500" />,
title: t("view_bookings_across"),
description: t("view_bookings_across_description"),
},
{
icon: <RefreshCcwIcon className="h-5 w-5 text-blue-500" />,
title: t("identify_booking_trends"),
description: t("identify_booking_trends_description"),
},
{
icon: <UserPlusIcon className="h-5 w-5 text-green-500" />,
title: t("spot_popular_event_types"),
description: t("spot_popular_event_types_description"),
},
];
return (
<UpgradeTip
plan="team"
title={t("make_informed_decisions")}
description={t("make_informed_decisions_description")}
features={features}
background="/tips/insights"
buttons={
<div className="stack-y-2 rtl:space-x-reverse sm:space-x-2">
<ButtonGroup>
<Button color="primary" href={`${WEBAPP_URL}/settings/teams/new`}>
{t("create_team")}
</Button>
<Button color="minimal" href="https://go.cal.com/insights" target="_blank">
{t("learn_more")}
</Button>
</ButtonGroup>
</div>
}>
{!session.data?.user ? null : children}
</UpgradeTip>
);
}
@@ -1,33 +0,0 @@
import { CTA_CONTAINER_CLASS_NAME } from "@calcom/features/data-table/lib/utils";
import { _generateMetadata, getTranslate } from "app/_utils";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import InsightsCallHistoryPage from "~/insights/views/insights-call-history-view";
import Shell from "~/shell/Shell";
import { checkInsightsPagePermission } from "../checkInsightsPagePermission";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("call_history"),
(t) => t("call_history_subtitle"),
undefined,
undefined,
"/insights/call-history"
);
export default async function Page() {
await checkInsightsPagePermission();
const t = await getTranslate();
return (
<Shell withoutMain={true}>
<ShellMainAppDir
heading={t("insights")}
subtitle={t("insights_subtitle")}
actions={<div className={`flex items-center gap-2 ${CTA_CONTAINER_CLASS_NAME}`} />}>
<InsightsCallHistoryPage />
</ShellMainAppDir>
</Shell>
);
}
@@ -1,24 +0,0 @@
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { prisma } from "@calcom/prisma";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
export async function checkInsightsPagePermission() {
const featuresRepository = new FeaturesRepository(prisma);
const insightsEnabled = await featuresRepository.checkIfFeatureIsEnabledGlobally("insights");
if (!insightsEnabled) {
redirect("/");
}
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
redirect("/auth/login");
}
return session;
}
@@ -1,18 +0,0 @@
import { MembershipRepository } from "@calcom/features/membership/repositories/MembershipRepository";
import { FullscreenUpgradeBannerForInsightsPage } from "@calcom/web/modules/billing/upgrade-banners/FullscreenUpgradeBannerForInsightsPage";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import Shell from "~/shell/Shell";
export async function getInsightsUpgradeBanner(userId: number) {
const hasMembership = await MembershipRepository.hasAnyAcceptedMembershipByUserId(userId);
if (hasMembership) return null;
return (
<Shell withoutMain={true}>
<ShellMainAppDir>
<FullscreenUpgradeBannerForInsightsPage />
</ShellMainAppDir>
</Shell>
);
}
@@ -1,43 +0,0 @@
import { CTA_CONTAINER_CLASS_NAME } from "@calcom/features/data-table/lib/utils";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import prisma from "@calcom/prisma";
import { _generateMetadata, getTranslate } from "app/_utils";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import InsightsPage from "~/insights/views/insights-view";
import Shell from "~/shell/Shell";
import { checkInsightsPagePermission } from "./checkInsightsPagePermission";
import { getInsightsUpgradeBanner } from "./getInsightsUpgradeBanner";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("insights"),
(t) => t("insights_subtitle"),
undefined,
undefined,
"/insights"
);
export default async function Page() {
const session = await checkInsightsPagePermission();
const banner = await getInsightsUpgradeBanner(session.user.id);
if (banner) return banner;
const t = await getTranslate();
const userRepository = new UserRepository(prisma);
const user = await userRepository.getTimeZoneAndDefaultScheduleId({ userId: session.user.id });
const timeZone = user?.timeZone ?? "UTC";
return (
<Shell withoutMain={true}>
<ShellMainAppDir
heading={t("insights")}
subtitle={t("insights_subtitle")}
actions={<div className={`flex items-center gap-2 ${CTA_CONTAINER_CLASS_NAME}`} />}>
<InsightsPage timeZone={timeZone} />
</ShellMainAppDir>
</Shell>
);
}
@@ -1,37 +0,0 @@
import { CTA_CONTAINER_CLASS_NAME } from "@calcom/features/data-table/lib/utils";
import { _generateMetadata, getTranslate } from "app/_utils";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import InsightsVirtualQueuesPage from "~/insights/views/insights-virtual-queues-view";
import Shell from "~/shell/Shell";
import { checkInsightsPagePermission } from "../checkInsightsPagePermission";
import { getInsightsUpgradeBanner } from "../getInsightsUpgradeBanner";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("insights"),
(t) => t("insights_subtitle"),
undefined,
undefined,
"/insights/router-position"
);
export default async function Page() {
const session = await checkInsightsPagePermission();
const banner = await getInsightsUpgradeBanner(session.user.id);
if (banner) return banner;
const t = await getTranslate();
return (
<Shell withoutMain={true}>
<ShellMainAppDir
heading={t("insights")}
subtitle={t("insights_subtitle")}
actions={<div className={`flex items-center gap-2 ${CTA_CONTAINER_CLASS_NAME}`} />}>
<InsightsVirtualQueuesPage />
</ShellMainAppDir>
</Shell>
);
}
@@ -1,43 +0,0 @@
import { CTA_CONTAINER_CLASS_NAME } from "@calcom/features/data-table/lib/utils";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma";
import { _generateMetadata, getTranslate } from "app/_utils";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import InsightsRoutingPage from "~/insights/views/insights-routing-view";
import Shell from "~/shell/Shell";
import { checkInsightsPagePermission } from "../checkInsightsPagePermission";
import { getInsightsUpgradeBanner } from "../getInsightsUpgradeBanner";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("insights"),
(t) => t("insights_subtitle"),
undefined,
undefined,
"/insights/routing"
);
export default async function Page() {
const session = await checkInsightsPagePermission();
const banner = await getInsightsUpgradeBanner(session.user.id);
if (banner) return banner;
const t = await getTranslate();
const userRepository = new UserRepository(prisma);
const user = await userRepository.getTimeZoneAndDefaultScheduleId({ userId: session.user.id });
const timeZone = user?.timeZone ?? "UTC";
return (
<Shell withoutMain={true}>
<ShellMainAppDir
heading={t("insights")}
subtitle={t("insights_subtitle")}
actions={<div className={`flex items-center gap-2 ${CTA_CONTAINER_CLASS_NAME}`} />}>
<InsightsRoutingPage timeZone={timeZone} />
</ShellMainAppDir>
</Shell>
);
}
@@ -1,42 +0,0 @@
import { CTA_CONTAINER_CLASS_NAME } from "@calcom/features/data-table/lib/utils";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import prisma from "@calcom/prisma";
import { _generateMetadata, getTranslate } from "app/_utils";
import { ShellMainAppDir } from "app/(use-page-wrapper)/(main-nav)/ShellMainAppDir";
import InsightsWrongRoutingPage from "~/insights/views/insights-wrong-routing-view";
import Shell from "~/shell/Shell";
import { checkInsightsPagePermission } from "../checkInsightsPagePermission";
import { getInsightsUpgradeBanner } from "../getInsightsUpgradeBanner";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("wrong_routing"),
(t) => t("wrong_routing_description"),
undefined,
undefined,
"/insights/wrong-routing"
);
export default async function Page() {
const session = await checkInsightsPagePermission();
const banner = await getInsightsUpgradeBanner(session.user.id);
if (banner) return banner;
const t = await getTranslate();
const userRepository = new UserRepository(prisma);
const user = await userRepository.getTimeZoneAndDefaultScheduleId({ userId: session.user.id });
return (
<Shell withoutMain={true}>
<ShellMainAppDir
heading={t("insights")}
subtitle={t("insights_subtitle")}
actions={<div className={`flex items-center gap-2 ${CTA_CONTAINER_CLASS_NAME}`} />}>
<InsightsWrongRoutingPage timeZone={user?.timeZone ?? "UTC"} />
</ShellMainAppDir>
</Shell>
);
}
@@ -1,34 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { OrganizationBrandView } from "~/onboarding/organization/brand/organization-brand-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${APP_NAME} - ${t("organization_brand")}`,
() => "",
true,
undefined,
"/onboarding/organization/brand"
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
return <OrganizationBrandView userEmail={userEmail} />;
};
export default ServerPage;
@@ -1,44 +0,0 @@
import { clearSessionCache, getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { isCompanyEmail } from "@calcom/features/ee/organizations/lib/utils";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { CompanyEmailRequired } from "~/onboarding/organization/details/company-email-required-view";
import { OrganizationDetailsView } from "~/onboarding/organization/details/organization-details-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${APP_NAME} - ${t("organization_details")}`,
() => "",
true,
undefined,
"/onboarding/organization/details"
);
};
const ServerPage = async (props: { searchParams: Promise<{ sessionClear?: string }> }) => {
const searchParams = await props.searchParams;
const req = buildLegacyRequest(await headers(), await cookies());
let session = await getServerSession({ req });
if (!session?.user?.id) {
return redirect("/auth/login");
}
if (searchParams.sessionClear) {
clearSessionCache();
session = await getServerSession({ req });
}
const userEmail = session?.user?.email || "";
if (!isCompanyEmail(userEmail)) {
return <CompanyEmailRequired userEmail={userEmail} />;
}
return <OrganizationDetailsView userEmail={userEmail} />;
};
export default ServerPage;
@@ -1,34 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { OrganizationInviteEmailView } from "~/onboarding/organization/invite/email/organization-invite-email-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${APP_NAME} - ${t("invite_teammates")}`,
() => "",
true,
undefined,
"/onboarding/organization/invite/email"
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
return <OrganizationInviteEmailView userEmail={userEmail} />;
};
export default ServerPage;
@@ -1,34 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { OrganizationInviteView } from "~/onboarding/organization/invite/organization-invite-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${APP_NAME} - ${t("invite_teammates")}`,
() => "",
true,
undefined,
"/onboarding/organization/invite"
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
return <OrganizationInviteView userEmail={userEmail} />;
};
export default ServerPage;
@@ -1,28 +0,0 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { OnboardingPathService } from "@calcom/features/onboarding/lib/onboarding-path.service";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
export default async function OrganizationOnboardingLayout({ children }: { children: React.ReactNode }) {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userId = session.user.id;
const gettingStartedPath = await OnboardingPathService.getGettingStartedPath();
const userRepository = new UserRepository(prisma);
const { organizations } = await userRepository.findOrganizations({ userId });
if (organizations.length > 0) {
return redirect(gettingStartedPath);
}
return children;
}
@@ -1,37 +0,0 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { isCompanyEmail } from "@calcom/features/ee/organizations/lib/utils";
import { OnboardingPathService } from "@calcom/features/onboarding/lib/onboarding-path.service";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { OrganizationMigrateMembersView } from "~/onboarding/organization/migrate-members/organization-migrate-members-view";
export default async function MigrateMembersPage() {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
const userId = session.user.id;
const gettingStartedPath = await OnboardingPathService.getGettingStartedPath();
if (!isCompanyEmail(userEmail)) {
return redirect(gettingStartedPath);
}
const userRepository = new UserRepository(prisma);
const isMemberOfOrganization = await userRepository.findIfAMemberOfSomeOrganization({
user: { id: userId },
});
if (isMemberOfOrganization) {
return redirect(gettingStartedPath);
}
return <OrganizationMigrateMembersView userEmail={userEmail} />;
}
@@ -1,58 +0,0 @@
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { isCompanyEmail } from "@calcom/features/ee/organizations/lib/utils";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import { OnboardingPathService } from "@calcom/features/onboarding/lib/onboarding-path.service";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { OrganizationMigrateTeamsView } from "~/onboarding/organization/migrate-teams/organization-migrate-teams-view";
type PageProps = {
searchParams: Promise<{ migrate?: string }>;
};
export default async function MigrateTeamsPage({ searchParams }: PageProps) {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
const userId = session.user.id;
const gettingStartedPath = await OnboardingPathService.getGettingStartedPath();
if (!isCompanyEmail(userEmail)) {
return redirect(gettingStartedPath);
}
const userRepository = new UserRepository(prisma);
const { organizations } = await userRepository.findOrganizations({ userId });
if (organizations.length > 0) {
return redirect(gettingStartedPath);
}
// Check for migrate query param
const params = await searchParams;
const migrateParam = params?.migrate;
// If no migrate param, redirect to teams step
if (migrateParam !== "true") {
return redirect("/onboarding/organization/teams");
}
// Check if user has teams to migrate
const teamRepository = new TeamRepository(prisma);
const ownedTeams = await teamRepository.findOwnedTeamsByUserId({ userId });
// If no teams, redirect to teams step
if (ownedTeams.length === 0) {
return redirect("/onboarding/organization/teams");
}
return <OrganizationMigrateTeamsView userEmail={userEmail} />;
}
@@ -1,34 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { OrganizationTeamsView } from "~/onboarding/organization/teams/organization-teams-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${APP_NAME} - ${t("organization_teams")}`,
() => "",
true,
undefined,
"/onboarding/organization/teams"
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
return <OrganizationTeamsView userEmail={userEmail} />;
};
export default ServerPage;
@@ -1,34 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { TeamDetailsView } from "~/onboarding/teams/details/team-details-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${APP_NAME} - ${t("team_details")}`,
() => "",
true,
undefined,
"/onboarding/teams/details"
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
return <TeamDetailsView userEmail={userEmail} />;
};
export default ServerPage;
@@ -1,34 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { TeamInviteEmailView } from "~/onboarding/teams/invite/email/team-invite-email-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${APP_NAME} - ${t("invite_teammates")}`,
() => "",
true,
undefined,
"/onboarding/teams/invite/email"
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
return <TeamInviteEmailView userEmail={userEmail} />;
};
export default ServerPage;
@@ -1,39 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { TeamInviteEmailView } from "~/onboarding/teams/invite/email/team-invite-email-view";
export const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${APP_NAME} - ${t("team_invite")}`,
() => "",
true,
undefined,
"/onboarding/teams/invite"
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const userEmail = session.user.email || "";
// If user is not ADMIN, show the email view directly instead of redirecting
if (session.user.role !== "ADMIN") {
return <TeamInviteEmailView userEmail={userEmail} />;
}
return <TeamInviteEmailView userEmail={userEmail} />;
};
export default ServerPage;
@@ -1,27 +1,31 @@
"use client";
import classNames from "classnames";
import dynamic from "next/dynamic";
import type { FC } from "react";
import { useEffect, useState } from "react";
import { getPaymentAppData } from "@calcom/app-store/_utils/payments/getPaymentAppData";
import { getSuccessPageLocationMessage } from "@calcom/app-store/locations";
import dayjs from "@calcom/dayjs";
import { sdkActionManager, useIsEmbed } from "@calcom/embed-core/embed-iframe";
import { PayIcon } from "@calcom/features/bookings/components/event-meta/PayIcon";
import { Price } from "@calcom/features/bookings/components/event-meta/Price";
import type { PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
import { APP_NAME, WEBSITE_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import useTheme from "@calcom/lib/hooks/useTheme";
import { getIs24hClockFromLocalStorage, isBrowserLocale24h } from "@calcom/lib/timeFormat";
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
import { localStorage } from "@calcom/lib/webstorage";
import classNames from "classnames";
import dynamic from "next/dynamic";
import type { FC } from "react";
import { useEffect, useState } from "react";
const StripePaymentComponent = dynamic(() => import("@calcom/features/ee/payments/components/Payment"), {
ssr: false,
});
type PaymentPageProps = {
payment: { id: number; success: boolean; refunded: boolean; amount: number; currency: string; paymentOption: string | null; data: Record<string, unknown>; appId?: string | null };
clientSecret?: string | null;
booking: { id: number; uid: string; title: string; startTime: string; endTime: string; status: string; paid: boolean; description?: string | null; location?: string | null };
eventType: { id: number; title: string; length: number; price: number; currency: string; metadata: Record<string, unknown> | null; successRedirectUrl?: string | null; forwardParamsSuccessRedirect?: boolean | null; recurringEvent?: unknown };
profile: { theme?: string | null; hideBranding?: boolean };
user?: { name?: string | null; username?: string | null } | null;
};
const PaypalPaymentComponent = dynamic(
() =>
@@ -87,7 +91,7 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isEmbed]);
}, [isEmbed, date.tz]);
const eventName = props.booking.title;
@@ -95,36 +99,36 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
<div className="h-screen">
<main className="mx-auto max-w-3xl py-24">
<div className="fixed inset-0 z-50 overflow-y-auto scroll-auto">
<div className="flex min-h-screen items-end justify-center px-4 pb-20 pt-4 text-center sm:block sm:p-0">
<div className="flex min-h-screen items-end justify-center px-4 pt-4 pb-20 text-center sm:block sm:p-0">
<div className="inset-0 my-4 transition-opacity sm:my-0" aria-hidden="true">
<span className="hidden sm:inline-block sm:h-screen sm:align-middle" aria-hidden="true">
&#8203;
</span>
<div
className={classNames(
"main bg-default border-subtle inline-block transform overflow-hidden rounded-lg border px-8 pb-4 pt-5 text-left align-bottom transition-all sm:w-full sm:max-w-lg sm:py-6 sm:align-middle",
"main inline-block transform overflow-hidden rounded-lg border border-subtle bg-default px-8 pt-5 pb-4 text-left align-bottom transition-all sm:w-full sm:max-w-lg sm:py-6 sm:align-middle",
isEmbed ? "" : "sm:my-8"
)}
role="dialog"
aria-modal="true"
aria-labelledby="modal-headline">
<div>
<div className="bg-cal-success mx-auto flex h-12 w-12 items-center justify-center rounded-full">
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-cal-success">
<PayIcon currency={paymentAppData.currency} className="h-8 w-8 text-green-600" />
</div>
<div className="mt-3 text-center sm:mt-5">
<h3 className="text-emphasis text-2xl font-semibold leading-6" id="modal-headline">
<h3 className="font-semibold text-2xl text-emphasis leading-6" id="modal-headline">
{paymentAppData.paymentOption === "HOLD" ? t("complete_your_booking") : t("payment")}
</h3>
<div className="text-default mt-4 grid grid-cols-3 border-b border-t py-4 text-left dark:border-gray-900 dark:text-gray-300">
<div className="mt-4 grid grid-cols-3 border-t border-b py-4 text-left text-default dark:border-gray-900 dark:text-gray-300">
<div className="font-medium">{t("what")}</div>
<div className="col-span-2 mb-6">{eventName}</div>
<div className="font-medium">{t("when")}</div>
<div className="col-span-2 mb-6">
{date.locale(i18n.language ?? "en").format("dddd, DD MMMM YYYY")}
<br />
{date.format(is24h ? "H:mm" : "h:mma")} - {props.eventType.length} {t("minute_timeUnit")}{" "}
{date.format(is24h ? "H:mm" : "h:mma")} - {props.eventType.length} mins{" "}
<span className="text-subtle">({timezone})</span>
</div>
{props.booking.location && (
@@ -150,17 +154,10 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
</div>
<div>
{props.payment.success && !props.payment.refunded && (
<div className="text-default mt-4 text-center dark:text-gray-300">{t("paid")}</div>
<div className="mt-4 text-center text-default dark:text-gray-300">{t("paid")}</div>
)}
{props.payment.appId === "stripe" && !props.payment.success && (
<StripePaymentComponent
clientSecret={props.clientSecret}
payment={props.payment}
eventType={props.eventType}
user={props.user}
location={props.booking.location}
booking={props.booking}
/>
<div>{/* StripePaymentComponent removed */}</div>
)}
{props.payment.appId === "paypal" && !props.payment.success && (
<PaypalPaymentComponent payment={props.payment} />
@@ -175,11 +172,11 @@ const PaymentPage: FC<PaymentPageProps> = (props) => {
<BtcpayPaymentComponent payment={props.payment} paymentPageProps={props} />
)}
{props.payment.refunded && (
<div className="text-default mt-4 text-center dark:text-gray-300">{t("refunded")}</div>
<div className="mt-4 text-center text-default dark:text-gray-300">{t("refunded")}</div>
)}
</div>
{!props.profile.hideBranding && (
<div className="text-muted dark:text-inverted mt-4 border-t pt-4 text-center text-xs dark:border-gray-900">
<div className="mt-4 border-t pt-4 text-center text-muted text-xs dark:border-gray-900 dark:text-inverted">
<a href={`${WEBSITE_URL}/signup`}>
{t("create_booking_link_with_calcom", { appName: APP_NAME })}
</a>
@@ -1,15 +1,49 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import type { PageProps } from "app/_types";
import { _generateMetadata } from "app/_utils";
import { withAppDirSsr } from "app/WithAppDirSsr";
import { cookies, headers } from "next/headers";
import { getServerSideProps, type PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import PaymentPage from "./PaymentPage";
type PaymentPageProps = {
payment: {
id: number;
success: boolean;
refunded: boolean;
amount: number;
currency: string;
paymentOption: string | null;
data: Record<string, unknown>;
appId?: string | null;
};
clientSecret?: string | null;
booking: {
id: number;
uid: string;
title: string;
startTime: string;
endTime: string;
status: string;
paid: boolean;
description?: string | null;
location?: string | null;
};
eventType: {
id: number;
title: string;
length: number;
price: number;
currency: string;
metadata: Record<string, unknown> | null;
successRedirectUrl?: string | null;
forwardParamsSuccessRedirect?: boolean | null;
recurringEvent?: unknown;
};
profile: { theme?: string | null; hideBranding?: boolean };
user?: { name?: string | null; username?: string | null } | null;
};
export const generateMetadata = async ({ params, searchParams }: PageProps) => {
const props = await getData(
buildLegacyCtx(await headers(), await cookies(), await params, await searchParams)
@@ -24,7 +58,32 @@ export const generateMetadata = async ({ params, searchParams }: PageProps) => {
);
};
const getData = withAppDirSsr<PaymentPageProps>(getServerSideProps);
const getData = withAppDirSsr<PaymentPageProps>(async () => ({
props: {
payment: {
id: 0,
success: false,
refunded: false,
amount: 0,
currency: "usd",
paymentOption: null,
data: {},
appId: null,
},
booking: {
id: 0,
uid: "",
title: "",
startTime: "",
endTime: "",
status: "",
paid: false,
location: null,
},
eventType: { id: 0, title: "", length: 0, price: 0, currency: "usd", metadata: null },
profile: { theme: null, hideBranding: false },
},
}));
const ServerPage = async ({ params, searchParams }: PageProps) => {
const props = await getData(
@@ -8,9 +8,9 @@ import Shell from "~/shell/Shell";
import { DubReferralsPage } from "./DubReferralsPage";
export const metadata: Metadata = {
title: "Cal.com referral program - Earn money by sharing your link",
title: "Cal.diy referral program - Earn money by sharing your link",
description:
"Earn 20% recurring commissions for a full year by referring others to Cal.com, while giving your referrals 20% off for 12 months. Share your link and start earning today!",
"Earn 20% recurring commissions for a full year by referring others to Cal.diy, while giving your referrals 20% off for 12 months. Share your link and start earning today!",
};
// Export the appropriate component based on the feature flag
@@ -1,11 +0,0 @@
import type { ReactNode } from "react";
import Shell from "~/shell/Shell";
import FormProvider from "../apps/routing-forms/[...pages]/FormProvider";
export default async function Layout({ children }: { children: ReactNode }) {
return (
<Shell withoutMain={true}>
<FormProvider>{children}</FormProvider>
</Shell>
);
}
@@ -1,32 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import Forms from "../apps/routing-forms/forms/[[...pages]]/Forms";
const generateMetadata = async () => {
return await _generateMetadata(
(t) => `${t("routing_forms")} | Cal.com Forms`,
() => "",
undefined,
undefined,
`/routing`
);
};
const ServerPage = async () => {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
if (!session?.user?.id) {
redirect("/auth/login");
}
return <Forms appUrl="/routing" />;
};
export { generateMetadata };
export default ServerPage;
@@ -1,25 +0,0 @@
import { _generateMetadata, getTranslate } from "app/_utils";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import AdminBillingView from "~/settings/admin/billing-view";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("admin_billing_title"),
(t) => t("admin_billing_description"),
undefined,
undefined,
"/settings/admin/billing"
);
const Page = async () => {
const t = await getTranslate();
return (
<SettingsHeader title={t("admin_billing_title")} description={t("admin_billing_description")}>
<AdminBillingView />
</SettingsHeader>
);
};
export default Page;
@@ -1,24 +0,0 @@
import { _generateMetadata, getTranslate } from "app/_utils";
import SystemBlocklistView from "~/ee/organizations/admin/views/SystemBlocklistView";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("system_blocklist"),
(t) => t("system_blocklist_description"),
undefined,
undefined,
"/settings/admin/blocklist"
);
const Page = async () => {
const t = await getTranslate();
return (
<SettingsHeader title={t("system_blocklist")} description={t("system_blocklist_description")}>
<SystemBlocklistView />
</SettingsHeader>
);
};
export default Page;
@@ -1,26 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { getTranslate } from "app/_utils";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import ImpersonationView from "~/settings/admin/impersonation-view";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("admin"),
(t) => t("impersonation"),
undefined,
undefined,
"/settings/admin/impersonation"
);
const Page = async () => {
const t = await getTranslate();
return (
<SettingsHeader title={t("admin")} description={t("impersonation")}>
<ImpersonationView />
</SettingsHeader>
);
};
export default Page;
@@ -1,25 +0,0 @@
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { _generateMetadata, getTranslate } from "app/_utils";
import MoveTeamToOrgView from "~/settings/admin/org-migrations/move-team-to-org-view";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("organization_migration_move_team"),
(t) => t("organization_migration_move_team_description"),
undefined,
undefined,
"/settings/admin/migrations/move-team-to-org"
);
const Page = async (): Promise<React.ReactNode> => {
const t = await getTranslate();
return (
<SettingsHeader
title={t("organization_migration_move_team")}
description={t("organization_migration_move_team_description")}>
<MoveTeamToOrgView />
</SettingsHeader>
);
};
export default Page;
@@ -1,9 +0,0 @@
"use client";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
export default function Error() {
const { t } = useLocale();
return <Alert severity="error" title={t("something_went_wrong")} />;
}
@@ -1,53 +0,0 @@
import { type Params } from "app/_types";
import { _generateMetadata, getTranslate } from "app/_utils";
import { z } from "zod";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import { OrgForm } from "~/ee/organizations/admin/views/AdminOrgEditPage";
import { getOrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.container";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
const orgIdSchema = z.object({ id: z.coerce.number() });
export const generateMetadata = async ({ params }: { params: Params }) => {
const organizationRepository = getOrganizationRepository();
const input = orgIdSchema.safeParse(await params);
if (!input.success) {
return await _generateMetadata(
(t) => t("editing_org"),
(t) => t("admin_orgs_edit_description"),
undefined,
undefined,
"/settings/admin/organizations/edit"
);
}
const org = await organizationRepository.adminFindById({ id: input.data.id });
return await _generateMetadata(
(t) => `${t("editing_org")}: ${org.name}`,
(t) => t("admin_orgs_edit_description"),
undefined,
undefined,
`/settings/admin/organizations/${input.data.id}/edit`
);
};
const Page = async ({ params }: { params: Params }) => {
const organizationRepository = getOrganizationRepository();
const input = orgIdSchema.safeParse(await params);
if (!input.success) throw new Error("Invalid access");
const org = await organizationRepository.adminFindById({ id: input.data.id });
const t = await getTranslate();
return (
<SettingsHeader title={`${t("editing_org")}: ${org.name}`} description={t("admin_orgs_edit_description")}>
<LicenseRequired>
<OrgForm org={org} />
</LicenseRequired>
</SettingsHeader>
);
};
export default Page;
@@ -1,28 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { getTranslate } from "app/_utils";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import AdminOrgTable from "~/ee/organizations/admin/views/AdminOrgPage";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("organizations"),
(t) => t("orgs_page_description"),
undefined,
undefined,
"/settings/admin/organizations"
);
const Page = async () => {
const t = await getTranslate();
return (
<SettingsHeader title={t("organizations")} description={t("orgs_page_description")}>
<LicenseRequired>
<AdminOrgTable />
</LicenseRequired>
</SettingsHeader>
);
};
export default Page;
@@ -1,60 +0,0 @@
"use client";
import { ChartCard } from "@calcom/web/modules/insights/components/ChartCard";
import { BookingsByHourChartContent } from "@calcom/web/modules/insights/components/booking/BookingsByHourChart";
import { useLocale } from "@calcom/lib/hooks/useLocale";
// Sample data for playground testing
const sampleBookingsByHourStats = [
{ hour: 0, count: 4 },
{ hour: 1, count: 10 },
{ hour: 2, count: 3 },
{ hour: 3, count: 12 },
{ hour: 4, count: 3 },
{ hour: 5, count: 7 },
{ hour: 6, count: 6 },
{ hour: 7, count: 4 },
{ hour: 8, count: 9 },
{ hour: 9, count: 7 },
{ hour: 10, count: 6 },
{ hour: 11, count: 5 },
{ hour: 12, count: 8 },
{ hour: 13, count: 5 },
{ hour: 14, count: 9 },
{ hour: 15, count: 9 },
{ hour: 16, count: 4 },
{ hour: 17, count: 5 },
{ hour: 18, count: 4 },
{ hour: 19, count: 6 },
{ hour: 20, count: 6 },
{ hour: 21, count: 12 },
{ hour: 22, count: 4 },
{ hour: 23, count: 10 },
];
export default function BookingsByHourPlayground() {
const { t } = useLocale();
return (
<div className="stack-y-6 p-6">
<div className="mb-6">
<h1 className="text-3xl font-bold">Bookings by Hour Playground</h1>
<p className="mt-2 text-gray-600">
This page demonstrates the BookingsByHourChartContent component with sample data.
</p>
</div>
<div className="max-w-4xl">
<ChartCard title={t("bookings_by_hour")}>
<BookingsByHourChartContent data={sampleBookingsByHourStats} />
</ChartCard>
</div>
<div className="mt-8 rounded-lg bg-gray-50 p-4">
<h2 className="mb-2 text-lg font-semibold">Sample Data Used:</h2>
<pre className="overflow-auto text-sm text-gray-700">
{JSON.stringify(sampleBookingsByHourStats, null, 2)}
</pre>
</div>
</div>
);
}
@@ -1,12 +1,11 @@
"use client";
import { useReactTable, getCoreRowModel, createColumnHelper } from "@tanstack/react-table";
import { useMemo } from "react";
import { ColumnFilterType } from "@calcom/features/data-table";
import { DataTableProvider } from "~/data-table/DataTableProvider";
import type { DateRangeFilterOptions } from "@calcom/features/data-table/lib/types";
import { ColumnFilterType } from "@calcom/features/data-table/lib/types";
import { createColumnHelper, getCoreRowModel, useReactTable } from "@tanstack/react-table";
import { useMemo } from "react";
import { DateRangeFilter } from "~/data-table/components/filters/DateRangeFilter";
import { DataTableProvider } from "~/data-table/DataTableProvider";
type DemoRow = {
id: number;
@@ -1,28 +1,9 @@
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { Icon } from "@calcom/ui/components/icon";
import { _generateMetadata, getTranslate } from "app/_utils";
import Link from "next/link";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { Icon } from "@calcom/ui/components/icon";
const LINKS = [
{
title: "Routing Funnel",
description: "Visualize booking conversion flow and routing patterns",
href: "/settings/admin/playground/routing-funnel",
icon: "filter" as const,
},
{
title: "Bookings by Hour",
description: "View booking distribution across different hours",
href: "/settings/admin/playground/bookings-by-hour",
icon: "chart-bar" as const,
},
{
title: "Weekly Calendar",
description: "Interactive weekly calendar view for scheduling",
href: "/settings/admin/playground/weekly-calendar",
icon: "calendar" as const,
},
{
title: "Date Range Filter",
description: "Test date range selection and filtering components",
@@ -1,91 +0,0 @@
"use client";
import { ChartCard } from "@calcom/web/modules/insights/components/ChartCard";
import {
RoutingFunnelContent,
legend,
} from "@calcom/web/modules/insights/components/routing/RoutingFunnelContent";
import { useLocale } from "@calcom/lib/hooks/useLocale";
// Random sample data for playground testing
const sampleRoutingFunnelData = [
{
name: "Week 1",
formattedDateFull: "Week 1",
totalSubmissions: 150,
successfulRoutings: 120,
acceptedBookings: 95,
},
{
name: "Week 2",
formattedDateFull: "Week 2",
totalSubmissions: 180,
successfulRoutings: 145,
acceptedBookings: 110,
},
{
name: "Week 3",
formattedDateFull: "Week 3",
totalSubmissions: 200,
successfulRoutings: 160,
acceptedBookings: 125,
},
{
name: "Week 4",
formattedDateFull: "Week 4",
totalSubmissions: 170,
successfulRoutings: 135,
acceptedBookings: 105,
},
{
name: "Week 5",
formattedDateFull: "Week 5",
totalSubmissions: 220,
successfulRoutings: 175,
acceptedBookings: 140,
},
{
name: "Week 6",
formattedDateFull: "Week 6",
totalSubmissions: 190,
successfulRoutings: 155,
acceptedBookings: 120,
},
];
export default function RoutingFunnelPlayground() {
const { t } = useLocale();
return (
<div className="stack-y-6 p-6">
<div className="mb-6">
<h1 className="text-3xl font-bold">Routing Funnel Playground</h1>
<p className="mt-2 text-gray-600">
This page demonstrates the RoutingFunnelContent component with sample data.
</p>
</div>
<div className="max-w-4xl">
<ChartCard
title={t("routing_funnel")}
subtitle="Hello world!"
legend={legend}
legendSize="sm"
cta={{
label: "Show all",
onClick: () => {
alert("hello!");
},
}}>
<RoutingFunnelContent data={sampleRoutingFunnelData} />
</ChartCard>
</div>
<div className="mt-8 rounded-lg bg-gray-50 p-4">
<h2 className="mb-2 text-lg font-semibold">Sample Data Used:</h2>
<pre className="overflow-auto text-sm text-gray-700">
{JSON.stringify(sampleRoutingFunnelData, null, 2)}
</pre>
</div>
</div>
);
}
@@ -1,548 +0,0 @@
"use client";
import { useState } from "react";
import dayjs from "@calcom/dayjs";
import { Calendar } from "@calcom/features/calendars/weeklyview/components/Calendar";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
import type { CalendarComponentProps, Hours } from "@calcom/features/calendars/weeklyview/types/state";
const makeDate = (dayOffset: number, hour: number, minute: number = 0) => {
return dayjs("2025-01-06").add(dayOffset, "day").hour(hour).minute(minute).second(0).toDate();
};
const getBaseProps = ({
events,
startHour = 6,
}: {
events: CalendarEvent[];
startHour?: Hours;
}): CalendarComponentProps => ({
startDate: dayjs("2025-01-06").toDate(), // Monday
endDate: dayjs("2025-01-12").toDate(), // Sunday
events,
startHour,
endHour: 18,
gridCellsPerHour: 4,
timezone: "UTC",
showBackgroundPattern: false,
showBorder: false,
hideHeader: true,
borderColor: "subtle",
scrollToCurrentTime: false,
});
type Scenario = {
id: string;
title: string;
description: string;
expected: string;
events: CalendarEvent[];
startHour: Hours;
};
const scenarios: Scenario[] = [
{
id: "two-overlapping",
title: "Two Overlapping Events",
description: "Two events with overlapping time ranges on the same day",
expected:
"First event 80% width at left edge (0%), second event 50% width aligned to right edge (49.5% offset). Events spread across full width for maximum visual distinction. Hover should bring event to front.",
startHour: 9,
events: [
{
id: 1,
title: "Meeting A",
start: makeDate(0, 10, 0),
end: makeDate(0, 11, 0),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 2,
title: "Meeting B",
start: makeDate(0, 10, 30),
end: makeDate(0, 11, 30),
options: { status: "ACCEPTED", color: "#10b981" },
},
],
},
{
id: "three-cascading",
title: "Three Overlapping Events (Cascading)",
description: "Three events that overlap, creating a cascading effect",
expected:
"Events spread across full width with variable widths (55%, ~42%, 33%). Offsets: 0%, ~35%, 66.5% (last event aligned to right edge). Right edges evenly distributed for maximum scatter. Z-index should increment. Hover brings any to top.",
startHour: 9,
events: [
{
id: 3,
title: "Long Meeting",
start: makeDate(1, 10, 0),
end: makeDate(1, 12, 0),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 4,
title: "Mid Meeting",
start: makeDate(1, 10, 30),
end: makeDate(1, 11, 30),
options: { status: "PENDING", color: "#f59e0b" },
},
{
id: 5,
title: "Late Meeting",
start: makeDate(1, 11, 0),
end: makeDate(1, 12, 30),
options: { status: "ACCEPTED", color: "#10b981" },
},
],
},
{
id: "non-overlapping",
title: "Non-Overlapping Events",
description: "Events that don't overlap should not cascade",
expected: "Both events at 0% offset (separate groups), no cascade. Both should be 100% width.",
startHour: 9,
events: [
{
id: 6,
title: "Morning Meeting",
start: makeDate(2, 10, 0),
end: makeDate(2, 11, 0),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 7,
title: "Afternoon Meeting",
start: makeDate(2, 12, 0),
end: makeDate(2, 13, 0),
options: { status: "ACCEPTED", color: "#10b981" },
},
],
},
{
id: "same-start-time",
title: "Same Start Time, Different Durations",
description: "Multiple events starting at the same time with varying lengths",
expected:
"Longest event first (base of cascade), spread across full width with variable widths (55%, ~42%, 33%). Last event aligned to right edge. All start at 10:00.",
startHour: 9,
events: [
{
id: 8,
title: "2-Hour Meeting",
start: makeDate(3, 10, 0),
end: makeDate(3, 12, 0),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 9,
title: "1.5-Hour Meeting",
start: makeDate(3, 10, 0),
end: makeDate(3, 11, 30),
options: { status: "ACCEPTED", color: "#f59e0b" },
},
{
id: 10,
title: "30-Min Meeting",
start: makeDate(3, 10, 0),
end: makeDate(3, 10, 30),
options: { status: "PENDING", color: "#10b981" },
},
],
},
{
id: "four-overlapping",
title: "Four Overlapping Events",
description: "Four events that overlap simultaneously",
expected:
"Events spread across full width with variable widths (40%, ~33%, ~28%, 25%). Last event aligned to right edge. Right edges evenly distributed for maximum scatter.",
startHour: 9,
events: [
{
id: 11,
title: "Event A",
start: makeDate(4, 10, 0),
end: makeDate(4, 12, 0),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 12,
title: "Event B",
start: makeDate(4, 10, 30),
end: makeDate(4, 11, 30),
options: { status: "ACCEPTED", color: "#f59e0b" },
},
{
id: 13,
title: "Event C",
start: makeDate(4, 11, 0),
end: makeDate(4, 12, 30),
options: { status: "ACCEPTED", color: "#10b981" },
},
{
id: 50,
title: "Event D",
start: makeDate(4, 11, 15),
end: makeDate(4, 12, 15),
options: { status: "PENDING", color: "#8b5cf6" },
},
],
},
{
id: "dense-day",
title: "Dense Day (20+ Events)",
description: "A very busy day with many overlapping events",
expected:
"Visually tight stack with multiple cascading levels. Right edge should not overflow. Hover should still work.",
startHour: 8,
events: [
{
id: 14,
title: "Team Standup",
start: makeDate(5, 9, 0),
end: makeDate(5, 9, 30),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 15,
title: "Client Call",
start: makeDate(5, 9, 15),
end: makeDate(5, 10, 0),
options: { status: "ACCEPTED", color: "#10b981" },
},
{
id: 16,
title: "Design Review",
start: makeDate(5, 9, 45),
end: makeDate(5, 11, 0),
options: { status: "PENDING", color: "#f59e0b" },
},
{
id: 17,
title: "1-on-1",
start: makeDate(5, 10, 0),
end: makeDate(5, 10, 30),
options: { status: "ACCEPTED", color: "#8b5cf6" },
},
{
id: 18,
title: "Planning",
start: makeDate(5, 10, 15),
end: makeDate(5, 11, 30),
options: { status: "ACCEPTED", color: "#ec4899" },
},
{
id: 19,
title: "Code Review",
start: makeDate(5, 11, 0),
end: makeDate(5, 12, 0),
options: { status: "ACCEPTED", color: "#14b8a6" },
},
{
id: 20,
title: "Lunch Meeting",
start: makeDate(5, 11, 30),
end: makeDate(5, 12, 30),
options: { status: "ACCEPTED", color: "#f97316" },
},
{
id: 21,
title: "Workshop",
start: makeDate(5, 12, 0),
end: makeDate(5, 13, 30),
options: { status: "ACCEPTED", color: "#06b6d4" },
},
{
id: 22,
title: "Interview",
start: makeDate(5, 12, 30),
end: makeDate(5, 13, 0),
options: { status: "PENDING", color: "#84cc16" },
},
{
id: 23,
title: "Retrospective",
start: makeDate(5, 13, 0),
end: makeDate(5, 14, 0),
options: { status: "ACCEPTED", color: "#a855f7" },
},
{
id: 24,
title: "Demo",
start: makeDate(5, 13, 15),
end: makeDate(5, 14, 0),
options: { status: "CANCELLED", color: "#ef4444" },
},
{
id: 30,
title: "Quick Sync",
start: makeDate(5, 9, 10),
end: makeDate(5, 9, 40),
options: { status: "ACCEPTED", color: "#6366f1" },
},
{
id: 31,
title: "Architecture Discussion",
start: makeDate(5, 9, 30),
end: makeDate(5, 10, 30),
options: { status: "ACCEPTED", color: "#ec4899" },
},
{
id: 32,
title: "Sprint Planning",
start: makeDate(5, 10, 10),
end: makeDate(5, 11, 0),
options: { status: "ACCEPTED", color: "#f59e0b" },
},
{
id: 33,
title: "Product Demo",
start: makeDate(5, 10, 45),
end: makeDate(5, 11, 45),
options: { status: "PENDING", color: "#14b8a6" },
},
{
id: 34,
title: "Bug Triage",
start: makeDate(5, 11, 15),
end: makeDate(5, 12, 15),
options: { status: "ACCEPTED", color: "#8b5cf6" },
},
{
id: 35,
title: "Customer Feedback",
start: makeDate(5, 11, 45),
end: makeDate(5, 12, 45),
options: { status: "ACCEPTED", color: "#10b981" },
},
{
id: 36,
title: "Team Sync",
start: makeDate(5, 12, 15),
end: makeDate(5, 13, 15),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 37,
title: "Tech Talk",
start: makeDate(5, 12, 45),
end: makeDate(5, 13, 45),
options: { status: "ACCEPTED", color: "#f97316" },
},
{
id: 38,
title: "Standup Follow-up",
start: makeDate(5, 13, 30),
end: makeDate(5, 14, 0),
options: { status: "ACCEPTED", color: "#06b6d4" },
},
{
id: 39,
title: "Office Hours",
start: makeDate(5, 13, 45),
end: makeDate(5, 14, 30),
options: { status: "ACCEPTED", color: "#a855f7" },
},
],
},
{
id: "touching-events",
title: "Touching Events (Edge Case)",
description: "Events that touch exactly at boundaries",
expected:
"Separate groups; no cascade; both at 0% offset. Both should be 100% width. Events touching at 11:00 should not overlap.",
startHour: 9,
events: [
{
id: 25,
title: "Morning Block",
start: makeDate(6, 10, 0),
end: makeDate(6, 11, 0),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 26,
title: "Afternoon Block",
start: makeDate(6, 11, 0),
end: makeDate(6, 12, 0),
options: { status: "ACCEPTED", color: "#10b981" },
},
],
},
{
id: "mixed-statuses",
title: "Mixed Event Statuses",
description: "Events with different booking statuses",
expected:
"Visual styling should differ by status (ACCEPTED, PENDING, CANCELLED). Cascade should still work.",
startHour: 13,
events: [
{
id: 27,
title: "Confirmed Meeting",
start: makeDate(0, 14, 0),
end: makeDate(0, 15, 0),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 28,
title: "Pending Approval",
start: makeDate(0, 14, 30),
end: makeDate(0, 15, 30),
options: { status: "PENDING", color: "#f59e0b" },
},
{
id: 29,
title: "Cancelled Meeting",
start: makeDate(0, 15, 0),
end: makeDate(0, 16, 0),
options: { status: "CANCELLED", color: "#ef4444" },
},
],
},
{
id: "event-durations",
title: "Event Duration Layout Tests",
description: "Events with different durations to test layout logic (eventDuration > 30 changes flex-col)",
expected:
"Events ≤30min show horizontal layout (title and time inline). Events >30min show vertical layout (title and time stacked).",
startHour: 8,
events: [
{
id: 40,
title: "3min Quick Chat",
start: makeDate(0, 9, 0),
end: makeDate(0, 9, 3),
options: { status: "ACCEPTED", color: "#3b82f6" },
},
{
id: 41,
title: "7min Standup",
start: makeDate(0, 9, 15),
end: makeDate(0, 9, 22),
options: { status: "ACCEPTED", color: "#10b981" },
},
{
id: 42,
title: "15min Check-in",
start: makeDate(0, 9, 30),
end: makeDate(0, 9, 45),
options: { status: "PENDING", color: "#f59e0b" },
},
{
id: 43,
title: "20min Review",
start: makeDate(0, 10, 0),
end: makeDate(0, 10, 20),
options: { status: "ACCEPTED", color: "#8b5cf6" },
},
{
id: 44,
title: "30min Discussion",
start: makeDate(0, 10, 30),
end: makeDate(0, 11, 0),
options: { status: "ACCEPTED", color: "#ec4899" },
},
{
id: 45,
title: "32min Discussion",
start: makeDate(0, 11, 10),
end: makeDate(0, 11, 42),
options: { status: "ACCEPTED", color: "#ec4899" },
},
{
id: 46,
title: "40min Discussion",
start: makeDate(0, 12, 0),
end: makeDate(0, 12, 40),
options: { status: "ACCEPTED", color: "#ec4899" },
},
{
id: 47,
title: "53min Workshop",
description: "Learn about the latest trends in web development",
start: makeDate(0, 13, 0),
end: makeDate(0, 13, 53),
options: { status: "ACCEPTED", color: "#14b8a6" },
},
{
id: 48,
title: "90min Workshop",
description: "Learn about the latest trends in web development",
start: makeDate(0, 14, 0),
end: makeDate(0, 15, 30),
options: { status: "ACCEPTED", color: "#14b8a6" },
},
],
},
];
function ScenarioCard({ scenario }: { scenario: Scenario }) {
const [showData, setShowData] = useState(false);
return (
<div className="border-subtle rounded-lg border p-4">
<div className="mb-4">
<h3 className="text-lg font-semibold">{scenario.title}</h3>
<p className="text-subtle mt-1 text-sm">{scenario.description}</p>
<div className="bg-subtle mt-2 rounded p-2 text-xs">
<strong>Expected:</strong> {scenario.expected}
</div>
</div>
<div className="h-[600px] overflow-hidden rounded border">
<Calendar {...getBaseProps({ events: scenario.events, startHour: scenario.startHour })} />
</div>
<button
onClick={() => setShowData(!showData)}
className="text-emphasis mt-2 text-sm underline hover:no-underline">
{showData ? "Hide" : "Show"} Event Data
</button>
{showData && (
<pre className="bg-subtle mt-2 overflow-auto rounded p-2 text-xs">
{JSON.stringify(scenario.events, null, 2)}
</pre>
)}
</div>
);
}
export default function WeeklyCalendarPlayground() {
return (
<div className="stack-y-8 p-6">
<div>
<h1 className="text-3xl font-bold">Weekly Calendar Playground</h1>
<p className="text-subtle mt-2">
Test the overlapping events cascading layout with various scenarios. Events should cascade with 80%
width and 8% left offset per overlap level. Hovering an event should bring it to the front.
</p>
</div>
{/* Grid View of All Scenarios */}
<div className="stack-y-8">
<h2 className="mb-4 text-2xl font-bold">All Scenarios (Side-by-Side)</h2>
{scenarios.map((scenario, index) => (
<ScenarioCard key={index} scenario={scenario} />
))}
</div>
{/* Testing Checklist */}
<div className="border-subtle rounded-lg border p-6">
<h2 className="mb-4 text-xl font-bold">Testing Checklist</h2>
<ul className="text-subtle stack-y-2 text-sm">
<li>✓ Visual appearance matches expectations (80% width with 8% cascading offsets)</li>
<li>✓ Hover behavior works smoothly - hovered event appears topmost</li>
<li>✓ No visual glitches with 3+ overlapping events</li>
<li>✓ Performance is acceptable with dense event days (10+ events)</li>
<li>✓ Edge case: Events with identical start times render correctly</li>
<li>✓ Edge case: Events that touch exactly (end = next start) don&apos;t incorrectly overlap</li>
<li>✓ Different booking statuses (ACCEPTED, PENDING, CANCELLED) display correctly</li>
<li>✓ Color bars on the left side of events display correctly</li>
</ul>
</div>
</div>
);
}
@@ -1,12 +1,10 @@
import { type Params } from "app/_types";
import { _generateMetadata, getTranslate } from "app/_utils";
import { z } from "zod";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import { UsersEditView } from "~/ee/users/views/users-edit-view";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { UserRepository } from "@calcom/features/users/repositories/UserRepository";
import { prisma } from "@calcom/prisma";
import type { Params } from "app/_types";
import { _generateMetadata, getTranslate } from "app/_utils";
import { z } from "zod";
import { UsersEditView } from "~/users/views/users-edit-view";
const userIdSchema = z.object({ id: z.coerce.number() });
@@ -46,9 +44,7 @@ const Page = async ({ params }: { params: Params }) => {
return (
<SettingsHeader title={t("editing_user")} description={t("admin_users_edit_description")}>
<LicenseRequired>
<UsersEditView user={user} />
</LicenseRequired>
<UsersEditView user={user} />
</SettingsHeader>
);
};
@@ -1,7 +1,6 @@
import { _generateMetadata, getTranslate } from "app/_utils";
import UsersAddView from "~/ee/users/views/users-add-view";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { _generateMetadata, getTranslate } from "app/_utils";
import UsersAddView from "~/users/views/users-add-view";
export const generateMetadata = async () =>
await _generateMetadata(
@@ -1,8 +1,7 @@
import { _generateMetadata, getTranslate } from "app/_utils";
import UsersListingView from "~/ee/users/views/users-listing-view";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { Button } from "@calcom/ui/components/button";
import { _generateMetadata, getTranslate } from "app/_utils";
import UsersListingView from "~/users/views/users-listing-view";
export const generateMetadata = async () =>
await _generateMetadata(
@@ -21,9 +20,7 @@ const Page = async () => {
description={t("admin_users_description")}
CTA={
<div className="mt-4 space-x-5 sm:ml-16 sm:mt-0 sm:flex-none">
{/* TODO: Add import users functionality */}
{/* <Button disabled>Import users</Button> */}
<Button href="/settings/admin/users/add">Add user</Button>
<Button href="/settings/admin/users/add">{t("add_new_user")}</Button>
</div>
}>
<UsersListingView />
@@ -1,27 +0,0 @@
import { _generateMetadata, getTranslate } from "app/_utils";
import LicenseRequired from "~/ee/common/components/LicenseRequired";
import WorkspacePlatformsPage from "~/ee/organizations/admin/views/WorkspacePlatformPage";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("workspace_platforms"),
(t) => t("workspace_platforms_description"),
undefined,
undefined,
"/settings/admin/workspace-platforms"
);
const Page = async () => {
const t = await getTranslate();
return (
<SettingsHeader title={t("workspace_platforms")} description={t("workspace_platforms_description")}>
<LicenseRequired>
<WorkspacePlatformsPage />
</LicenseRequired>
</SettingsHeader>
);
};
export default Page;
@@ -1,19 +1,10 @@
"use client";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import type { OrganizationBranding } from "@calcom/features/ee/organizations/context/provider";
import { useOrgBranding } from "@calcom/features/ee/organizations/context/provider";
import {
HAS_ORG_OPT_IN_FEATURES,
HAS_TEAM_OPT_IN_FEATURES,
HAS_USER_OPT_IN_FEATURES,
} from "@calcom/features/feature-opt-in/config";
import { HAS_ORG_OPT_IN_FEATURES } from "@calcom/features/feature-opt-in/config";
import type { TeamFeatures } from "@calcom/features/flags/config";
import { useIsFeatureEnabledForTeam } from "@calcom/features/flags/hooks/useIsFeatureEnabledForTeam";
import { HOSTED_CAL_FEATURES, IS_CALCOM, WEBAPP_URL } from "@calcom/lib/constants";
import { IS_CALCOM, WEBAPP_URL } from "@calcom/lib/constants";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useIsStandalone } from "@calcom/lib/hooks/useIsStandalone";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { IdentityProvider, UserPermissionRole } from "@calcom/prisma/enums";
@@ -23,12 +14,11 @@ import { Badge } from "@calcom/ui/components/badge";
import { Button } from "@calcom/ui/components/button";
import { ErrorBoundary } from "@calcom/ui/components/errorBoundary";
import { Icon } from "@calcom/ui/components/icon";
import { ArrowLeftIcon, ChevronDownIcon, ChevronRightIcon } from "@coss/ui/icons";
import type { VerticalTabItemProps } from "@calcom/ui/components/navigation";
import { VerticalTabItem } from "@calcom/ui/components/navigation";
import { Skeleton } from "@calcom/ui/components/skeleton";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@radix-ui/react-collapsible";
import { Avatar } from "@calcom/ui/components/avatar";
import { ArrowLeftIcon } from "@coss/ui/icons";
import Image from "next/image";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
@@ -36,7 +26,15 @@ import type { ComponentProps } from "react";
import React, { useEffect, useMemo, useState } from "react";
import Shell from "~/shell/Shell";
const getTabs = (orgBranding: OrganizationBranding | null) => {
const getTabs = (
orgBranding: {
id?: number;
slug?: string;
name?: string;
logoUrl?: string | null;
fullDomain?: string | null;
} | null
) => {
const tabs: VerticalTabItemProps[] = [
{
name: "my_account",
@@ -78,15 +76,6 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
href: "/settings/my-account/push-notifications",
trackingMetadata: { section: "my_account", page: "push_notifications" },
},
...(HAS_USER_OPT_IN_FEATURES
? [
{
name: "features",
href: "/settings/my-account/features",
trackingMetadata: { section: "my_account", page: "features" },
},
]
: []),
// TODO
// { name: "referrals", href: "/settings/my-account/referrals" },
],
@@ -101,33 +90,11 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
href: "/settings/security/password",
trackingMetadata: { section: "security", page: "password" },
},
{
name: "impersonation",
href: "/settings/security/impersonation",
trackingMetadata: { section: "security", page: "impersonation" },
},
{
name: "2fa_auth",
href: "/settings/security/two-factor-auth",
trackingMetadata: { section: "security", page: "2fa_auth" },
},
{
name: "compliance",
href: "/settings/security/compliance",
trackingMetadata: { section: "security", page: "compliance" },
},
],
},
{
name: "billing",
href: "/settings/billing",
icon: "credit-card",
children: [
{
name: "manage_billing",
href: "/settings/billing",
trackingMetadata: { section: "billing", page: "manage_billing" },
},
],
},
{
@@ -153,8 +120,7 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
},
{
name: "api_docs",
href: "https://cal.com/docs/api-reference/v2/introduction",
isExternalLink: true,
href: "/docs",
trackingMetadata: { section: "developer", page: "api_docs" },
},
// TODO: Add profile level for embeds
@@ -181,13 +147,13 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
},
...(orgBranding
? [
{
name: "members",
href: `${WEBAPP_URL}/settings/organizations/${orgBranding.slug}/members`,
isExternalLink: true,
trackingMetadata: { section: "organization", page: "members" },
},
]
{
name: "members",
href: `${WEBAPP_URL}/settings/organizations/${orgBranding?.slug}/members`,
isExternalLink: true,
trackingMetadata: { section: "organization", page: "members" },
},
]
: []),
{
name: "privacy_and_security",
@@ -206,33 +172,20 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
},
{
name: "api_docs",
href: "https://cal.com/docs/api-reference/v2/introduction",
isExternalLink: true,
href: "/docs",
trackingMetadata: { section: "organization", page: "api_docs" },
},
...(HAS_ORG_OPT_IN_FEATURES
? [
{
name: "features",
href: "/settings/organizations/features",
trackingMetadata: { section: "organization", page: "features" },
},
]
{
name: "features",
href: "/settings/organizations/features",
trackingMetadata: { section: "organization", page: "features" },
},
]
: []),
],
},
{
name: "teams",
href: "/teams",
icon: "users",
children: [],
},
{
name: "other_teams",
href: "/settings/organizations/teams/other",
icon: "users",
children: [],
},
{
name: "admin",
href: "/settings/admin",
@@ -249,16 +202,6 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
href: "/auth/setup?step=1",
trackingMetadata: { section: "admin", page: "license" },
},
{
name: "admin_billing",
href: "/settings/admin/billing",
trackingMetadata: { section: "admin", page: "billing" },
},
{
name: "impersonation",
href: "/settings/admin/impersonation",
trackingMetadata: { section: "admin", page: "impersonation" },
},
{
name: "apps",
href: "/settings/admin/apps/calendar",
@@ -269,36 +212,16 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
href: "/settings/admin/users",
trackingMetadata: { section: "admin", page: "users" },
},
{
name: "organizations",
href: "/settings/admin/organizations",
trackingMetadata: { section: "admin", page: "organizations" },
},
{
name: "migrations",
href: "/settings/admin/migrations/move-team-to-org",
trackingMetadata: { section: "admin", page: "migrations" },
},
{
name: "lockedSMS",
href: "/settings/admin/lockedSMS",
trackingMetadata: { section: "admin", page: "locked_sms" },
},
{
name: "pbac_resource_blocklist",
href: "/settings/admin/blocklist",
trackingMetadata: { section: "admin", page: "blocklist" },
},
{
name: "oAuth",
href: "/settings/admin/oauth",
trackingMetadata: { section: "admin", page: "oauth" },
},
{
name: "Workspace Platforms",
href: "/settings/admin/workspace-platforms",
trackingMetadata: { section: "admin", page: "workspace_platforms" },
},
{
name: "Playground",
href: "/settings/admin/playground",
@@ -309,16 +232,6 @@ const getTabs = (orgBranding: OrganizationBranding | null) => {
];
for (const tab of tabs) {
if (tab.name === "security" && !HOSTED_CAL_FEATURES) {
tab.children?.push({
name: "sso_configuration",
href: "/settings/security/sso",
trackingMetadata: { section: "security", page: "sso_configuration" },
});
// TODO: Enable dsync for self hosters
// tab.children?.push({ name: "directory_sync", href: "/settings/security/dsync" });
}
if (tab.name === "admin" && IS_CALCOM) {
tab.children?.push({
name: "create_org",
@@ -366,7 +279,7 @@ const useTabs = ({
}) => {
const session = useSession();
const { data: user } = trpc.viewer.me.get.useQuery({ includePasswordAdded: true });
const orgBranding = useOrgBranding();
const orgBranding = null as { id?: number; slug?: string; name?: string; logoUrl?: string | null } | null;
const isAdmin = session.data?.user.role === UserPermissionRole.ADMIN;
const processTabsMemod = useMemo(() => {
@@ -478,9 +391,9 @@ const BackButtonInSidebar = ({ name }: { name: string }) => {
return (
<Link
href="/event-types"
className="hover:bg-subtle todesktop:mt-10 [&[aria-current='page']]:bg-emphasis [&[aria-current='page']]:text-emphasis group-hover:text-default text-emphasis group my-6 flex h-6 max-h-6 w-full flex-row items-center rounded-md px-3 py-2 text-sm font-medium leading-4 transition"
className="group my-6 todesktop:mt-10 flex h-6 max-h-6 w-full flex-row items-center rounded-md px-3 py-2 font-medium text-emphasis text-sm leading-4 transition hover:bg-subtle group-hover:text-default [&[aria-current='page']]:bg-emphasis [&[aria-current='page']]:text-emphasis"
data-testid={`vertical-tab-${name}`}>
<ArrowLeftIcon className="h-4 w-4 stroke-[2px] ltr:mr-[10px] rtl:ml-[10px] rtl:rotate-180 md:mt-0" />
<ArrowLeftIcon className="h-4 w-4 stroke-[2px] md:mt-0 ltr:mr-[10px] rtl:ml-[10px] rtl:rotate-180" />
<Skeleton title={name} as="p" className="min-h-4 max-w-36 truncate" loadingClassName="ms-3">
{name}
</Skeleton>
@@ -496,236 +409,6 @@ interface SettingsSidebarContainerProps {
permissions?: SettingsPermissions;
}
const TeamRolesNavItem = ({
team,
teamFeatures,
}: {
team: { id: number; parentId?: number | null };
teamFeatures?: Record<number, TeamFeatures>;
}) => {
const { t } = useLocale();
// Always call the hook first (Rules of Hooks)
const isPbacEnabled = useIsFeatureEnabledForTeam({
teamFeatures,
teamId: team.parentId || 0, // Use 0 as fallback when no parentId
feature: "pbac",
});
// For sub-teams with PBAC-enabled parent org: show functional roles page
if (team.parentId && isPbacEnabled) {
return (
<VerticalTabItem
name={t("roles_and_permissions")}
href={`/settings/teams/${team.id}/roles`}
trackingMetadata={{ section: "team", page: "roles_and_permissions", teamId: team.id }}
textClassNames="px-3 text-emphasis font-medium text-sm"
disableChevron
/>
);
}
// For standalone teams (not in an org): show upgrade banner page
if (!team.parentId) {
return (
<VerticalTabItem
name={t("roles_and_permissions")}
href={`/settings/teams/${team.id}/roles`}
trackingMetadata={{ section: "team", page: "roles_and_permissions", teamId: team.id }}
textClassNames="px-3 text-emphasis font-medium text-sm"
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
);
}
return null;
};
const TeamListCollapsible = ({ teamFeatures }: { teamFeatures?: Record<number, TeamFeatures> }) => {
const { data: teams } = trpc.viewer.teams.list.useQuery();
const { t } = useLocale();
const [teamMenuState, setTeamMenuState] =
useState<{ teamId: number | undefined; teamMenuOpen: boolean }[]>();
const searchParams = useCompatSearchParams();
const pathname = usePathname();
const searchParamsId = searchParams?.get("id");
const pathTeamId = pathname?.match(/\/settings\/teams\/(\d+)/)?.[1];
const activeTeamId = pathTeamId || searchParamsId;
useEffect(() => {
if (teams) {
const teamStates = teams?.map((team) => ({
teamId: team.id,
teamMenuOpen: String(team.id) === activeTeamId,
}));
setTeamMenuState(teamStates);
if (activeTeamId) {
setTimeout(() => {
const teamTrigger = document.querySelector(`[aria-controls="team-content-${activeTeamId}"]`);
teamTrigger?.scrollIntoView({ behavior: "smooth", block: "center" });
}, 100);
}
}
}, [activeTeamId, teams]);
return (
<>
{teams &&
teamMenuState &&
teams.map((team, index: number) => {
if (!teamMenuState[index]) {
return null;
}
if (teamMenuState.some((teamState) => teamState.teamId === team.id)) {
return (
<Collapsible
className="cursor-pointer"
key={team.id}
open={teamMenuState[index].teamMenuOpen}
onOpenChange={(open) => {
const newTeamMenuState = [...teamMenuState];
newTeamMenuState[index] = {
...newTeamMenuState[index],
teamMenuOpen: open,
};
setTeamMenuState(newTeamMenuState);
}}>
<CollapsibleTrigger asChild>
<button
className="hover:bg-subtle [&[aria-current='page']]:bg-emphasis [&[aria-current='page']]:text-emphasis text-default flex h-9 w-full flex-row items-center rounded-md px-2 py-[10px] text-left text-sm font-medium leading-none transition"
aria-controls={`team-content-${team.id}`}
aria-expanded={teamMenuState[index].teamMenuOpen}
onClick={() => {
const newTeamMenuState = [...teamMenuState];
newTeamMenuState[index] = {
...newTeamMenuState[index],
teamMenuOpen: !teamMenuState[index].teamMenuOpen,
};
setTeamMenuState(newTeamMenuState);
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
const newTeamMenuState = [...teamMenuState];
newTeamMenuState[index] = {
...newTeamMenuState[index],
teamMenuOpen: !teamMenuState[index].teamMenuOpen,
};
setTeamMenuState(newTeamMenuState);
}
}}
aria-label={`${team.name} ${teamMenuState[index].teamMenuOpen ? t("collapse_menu") : t("expand_menu")
}`}>
<div className="me-3">
{teamMenuState[index].teamMenuOpen ? (
<ChevronDownIcon className="h-4 w-4" />
) : (
<ChevronRightIcon className="h-4 w-4" />
)}
</div>
{ }
{!team.parentId && (
<Avatar
size="xs"
imageSrc={getPlaceholderAvatar(team.logoUrl, team.name)}
alt={team.name || "Team logo"}
className="self-start border-0 bg-transparent ltr:mr-2 rtl:ml-2 md:mt-0"
/>
)}
<p className="w-1/2 truncate leading-normal">{team.name}</p>
{!team.accepted && (
<Badge className="ms-3" variant="orange">
Inv.
</Badge>
)}
</button>
</CollapsibleTrigger>
<CollapsibleContent className="flex flex-col space-y-1" id={`team-content-${team.id}`}>
{team.accepted && (
<VerticalTabItem
name={t("profile")}
href={`/settings/teams/${team.id}/profile`}
trackingMetadata={{ section: "team", page: "profile", teamId: team.id }}
textClassNames="px-3 text-emphasis font-medium text-sm"
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
)}
<VerticalTabItem
name={t("members")}
href={`/settings/teams/${team.id}/members`}
trackingMetadata={{ section: "team", page: "members", teamId: team.id }}
textClassNames="px-3 text-emphasis font-medium text-sm"
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
{/* Show roles only for sub-teams with PBAC-enabled parent */}
<TeamRolesNavItem team={team} teamFeatures={teamFeatures} />
{(checkAdminOrOwner(team.role) ||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error this exists wtf?
(team.isOrgAdmin && team.isOrgAdmin)) && (
<>
{/* TODO */}
{/* <VerticalTabItem
name={t("general")}
href={`${WEBAPP_URL}/settings/my-account/appearance`}
textClassNames="px-3 text-emphasis font-medium text-sm"
disableChevron
/> */}
<VerticalTabItem
name={t("appearance")}
href={`/settings/teams/${team.id}/appearance`}
textClassNames="px-3 text-emphasis font-medium text-sm"
trackingMetadata={{ section: "team", page: "appearance", teamId: team.id }}
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
{HAS_TEAM_OPT_IN_FEATURES && (
<VerticalTabItem
name={t("features")}
href={`/settings/teams/${team.id}/features`}
textClassNames="px-3 text-emphasis font-medium text-sm"
trackingMetadata={{ section: "team", page: "features", teamId: team.id }}
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
)}
{/* Hide if there is a parent ID */}
{!team.parentId ? (
<>
<VerticalTabItem
name={t("billing")}
href={`/settings/teams/${team.id}/billing`}
textClassNames="px-3 text-emphasis font-medium text-sm"
trackingMetadata={{ section: "team", page: "billing", teamId: team.id }}
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
</>
) : null}
<VerticalTabItem
name={t("settings")}
href={`/settings/teams/${team.id}/settings`}
textClassNames="px-3 text-emphasis font-medium text-sm"
trackingMetadata={{ section: "team", page: "settings", teamId: team.id }}
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
</>
)}
</CollapsibleContent>
</Collapsible>
);
}
return null;
})}
</>
);
};
const SettingsSidebarContainer = ({
className = "",
navigationIsOpenedOnMobile,
@@ -733,300 +416,81 @@ const SettingsSidebarContainer = ({
teamFeatures,
permissions,
}: SettingsSidebarContainerProps) => {
const searchParams = useCompatSearchParams();
const orgBranding = useOrgBranding();
const { t } = useLocale();
const [otherTeamMenuState, setOtherTeamMenuState] =
useState<
{
teamId: number | undefined;
teamMenuOpen: boolean;
}[]
>();
const session = useSession();
const organizationId = session.data?.user?.org?.id;
const isDelegationCredentialEnabled = useIsFeatureEnabledForTeam({
teamFeatures,
teamId: organizationId,
feature: "delegation-credential",
});
const isPbacEnabled = useIsFeatureEnabledForTeam({
teamFeatures,
teamId: organizationId,
feature: "pbac",
});
const tabsWithPermissions = useTabs({
isDelegationCredentialEnabled,
isPbacEnabled,
isDelegationCredentialEnabled: false,
isPbacEnabled: false,
permissions,
});
const { data: otherTeams } = trpc.viewer.organizations.listOtherTeams.useQuery(undefined, {
enabled: !!session.data?.user?.org,
});
const searchParamsId = searchParams?.get("id");
// Same as above but for otherTeams
useEffect(() => {
if (otherTeams) {
const otherTeamStates = otherTeams?.map((team) => ({
teamId: team.id,
teamMenuOpen: String(team.id) === searchParamsId,
}));
setOtherTeamMenuState(otherTeamStates);
setTimeout(() => {
// @TODO: test if this works for 2 dataset testids
const tabMembers = Array.from(document.getElementsByTagName("a")).filter(
(bottom) => bottom.dataset.testid === "vertical-tab-Members"
)[1];
tabMembers?.scrollIntoView({ behavior: "smooth" });
}, 100);
}
}, [searchParamsId, otherTeams]);
return (
<nav
style={{ maxHeight: `calc(100vh - ${bannersHeight}px)`, top: `${bannersHeight}px` }}
className={classNames(
"no-scrollbar bg-cal-muted stack-y-1 fixed bottom-0 left-0 top-0 z-20 flex max-h-screen w-56 flex-col overflow-x-hidden overflow-y-scroll px-2 pb-3 transition-transform max-lg:z-10 lg:sticky lg:flex",
"no-scrollbar stack-y-1 fixed top-0 bottom-0 left-0 z-20 flex max-h-screen w-56 flex-col overflow-x-hidden overflow-y-scroll bg-cal-muted px-2 pb-3 transition-transform max-lg:z-10 lg:sticky lg:flex",
className,
navigationIsOpenedOnMobile
? "translate-x-0 opacity-100"
: "-translate-x-full opacity-0 lg:translate-x-0 lg:opacity-100"
)}
aria-label={t("settings_navigation")}>
<>
<BackButtonInSidebar name={t("back")} />
{tabsWithPermissions.map((tab) => {
return (
<React.Fragment key={tab.href}>
{!["teams", "other_teams"].includes(tab.name) && (
<React.Fragment key={tab.href}>
<div className={`${!tab.children?.length ? "mb-3!" : ""}`}>
<div className="[&[aria-current='page']]:bg-emphasis [&[aria-current='page']]:text-emphasis text-default group flex h-7 w-full flex-row items-center rounded-md px-2 text-sm font-medium leading-none">
{tab && tab.icon && (
<Icon
name={tab.icon}
className="text-subtle h-[16px] w-[16px] stroke-[2px] ltr:mr-3 rtl:ml-3 md:mt-0"
/>
)}
{ }
{!tab.icon && tab?.avatar && (
<Avatar
size="xs"
imageSrc={tab?.avatar}
alt={tab.name || "Organization Logo"}
className="border-0 bg-transparent ltr:mr-3 rtl:ml-3"
/>
)}
<Skeleton
title={tab.name}
as="p"
className="text-subtle truncate text-sm font-medium leading-5"
loadingClassName="ms-3">
{t(tab.name)}
</Skeleton>
</div>
</div>
<div className="flex flex-col space-y-1">
{tab.children?.map((child, index) => (
<div key={child.href} className="flex items-start gap-2">
<VerticalTabItem
name={t(child.name)}
isExternalLink={child.isExternalLink}
href={child.href || "/"}
trackingMetadata={child.trackingMetadata}
textClassNames="text-emphasis font-medium text-sm"
className={`px-2! py-1! min-h-7 h-auto w-full ${
tab.children && index === tab.children?.length - 1 && "mb-3!"
}`}
disableChevron
/>
{child.isBadged && (
<Badge variant="blue" className="mt-0.5 text-xs">
New
</Badge>
)}
</div>
))}
</div>
</React.Fragment>
)}
{tab.name === "teams" && (
<React.Fragment key={tab.href}>
<div data-testid="tab-teams" className={`${!tab.children?.length ? "mb-3" : ""}`}>
<Link href={tab.href}>
<div className="hover:bg-subtle [&[aria-current='page']]:bg-emphasis [&[aria-current='page']]:text-emphasis group-hover:text-default text-default group flex h-9 w-full flex-row items-center rounded-md px-2 py-[10px] text-sm font-medium leading-none transition">
{tab && tab.icon && (
<Icon
name={tab.icon}
className="text-subtle h-[16px] w-[16px] stroke-[2px] ltr:mr-3 rtl:ml-3 md:mt-0"
/>
)}
<Skeleton
title={tab.name}
as="p"
className="text-subtle truncate text-sm font-medium leading-5"
loadingClassName="ms-3">
{t("my_teams")}
</Skeleton>
</div>
</Link>
<TeamListCollapsible teamFeatures={teamFeatures} />
{(!orgBranding?.id || permissions?.canUpdateOrganization) && (
<VerticalTabItem
name={t("add_a_team")}
href={`${WEBAPP_URL}/settings/teams/new`}
trackingMetadata={{ section: "team", page: "add_a_team" }}
textClassNames="px-3 items-center mt-2 text-emphasis font-medium text-sm"
className="px-2! me-5 h-7 w-auto"
icon="plus"
disableChevron
/>
)}
</div>
</React.Fragment>
)}
{tab.name === "other_teams" && (
<React.Fragment key={tab.href}>
<div className={`${!tab.children?.length ? "mb-3" : ""}`}>
<Link href={tab.href}>
<div className="hover:bg-subtle [&[aria-current='page']]:bg-emphasis [&[aria-current='page']]:text-emphasis group-hover:text-default text-default group flex h-9 w-full flex-row items-center rounded-md px-2 py-[10px] text-sm font-medium leading-none transition">
{tab && tab.icon && (
<Icon
name={tab.icon}
className="text-subtle h-[16px] w-[16px] stroke-[2px] ltr:mr-3 rtl:ml-3 md:mt-0"
/>
)}
<Skeleton
title={t("org_admin_other_teams")}
as="p"
className="text-subtle truncate text-sm font-medium leading-5"
loadingClassName="ms-3">
{t("org_admin_other_teams")}
</Skeleton>
</div>
</Link>
{otherTeams &&
otherTeamMenuState &&
otherTeams.map((otherTeam, index: number) => {
if (!otherTeamMenuState[index]) {
return null;
}
if (otherTeamMenuState.some((teamState) => teamState.teamId === otherTeam.id))
return (
<Collapsible
className="cursor-pointer"
key={otherTeam.id}
open={otherTeamMenuState[index].teamMenuOpen}
onOpenChange={(open) => {
const newOtherTeamMenuState = [...otherTeamMenuState];
newOtherTeamMenuState[index] = {
...newOtherTeamMenuState[index],
teamMenuOpen: open,
};
setOtherTeamMenuState(newOtherTeamMenuState);
}}>
<CollapsibleTrigger asChild>
<button
className="hover:bg-subtle [&[aria-current='page']]:bg-emphasis [&[aria-current='page']]:text-emphasis text-default flex h-9 w-full flex-row items-center rounded-md px-2 py-[10px] text-left text-sm font-medium leading-none transition"
aria-controls={`other-team-content-${otherTeam.id}`}
aria-expanded={otherTeamMenuState[index].teamMenuOpen}
onClick={() => {
const newOtherTeamMenuState = [...otherTeamMenuState];
newOtherTeamMenuState[index] = {
...newOtherTeamMenuState[index],
teamMenuOpen: !otherTeamMenuState[index].teamMenuOpen,
};
setOtherTeamMenuState(newOtherTeamMenuState);
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
const newOtherTeamMenuState = [...otherTeamMenuState];
newOtherTeamMenuState[index] = {
...newOtherTeamMenuState[index],
teamMenuOpen: !otherTeamMenuState[index].teamMenuOpen,
};
setOtherTeamMenuState(newOtherTeamMenuState);
}
}}
aria-label={`${otherTeam.name} ${otherTeamMenuState[index].teamMenuOpen
? t("collapse_menu")
: t("expand_menu")
}`}>
<div className="me-3">
{otherTeamMenuState[index].teamMenuOpen ? (
<ChevronDownIcon className="h-4 w-4" />
) : (
<ChevronRightIcon className="h-4 w-4" />
)}
</div>
{ }
{!otherTeam.parentId && (
<Avatar
size="xs"
imageSrc={getPlaceholderAvatar(otherTeam.logoUrl, otherTeam.name)}
alt={otherTeam.name || "Team logo"}
className="self-start border-0 bg-transparent ltr:mr-2 rtl:ml-2 md:mt-0"
/>
)}
<p className="w-1/2 truncate leading-normal">{otherTeam.name}</p>
</button>
</CollapsibleTrigger>
<CollapsibleContent
className="flex flex-col space-y-1"
id={`other-team-content-${otherTeam.id}`}>
<VerticalTabItem
name={t("profile")}
href={`/settings/organizations/teams/other/${otherTeam.id}/profile`}
trackingMetadata={{
section: "other_team",
page: "profile",
teamId: otherTeam.id,
}}
textClassNames="px-3 text-emphasis font-medium text-sm"
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
<VerticalTabItem
name={t("members")}
href={`/settings/organizations/teams/other/${otherTeam.id}/members`}
trackingMetadata={{
section: "other_team",
page: "members",
teamId: otherTeam.id,
}}
textClassNames="px-3 text-emphasis font-medium text-sm"
className="px-2! me-5 h-7 w-auto"
disableChevron
/>
<>
{/* TODO: enable appearance edit */}
{/* <VerticalTabItem
name={t("appearance")}
href={`/settings/organizations/teams/other/${otherTeam.id}/appearance`}
textClassNames="px-3 text-emphasis font-medium text-sm"
disableChevron
/> */}
</>
</CollapsibleContent>
</Collapsible>
);
})}
</div>
</React.Fragment>
)}
</React.Fragment>
);
})}
</>
<BackButtonInSidebar name={t("back")} />
{tabsWithPermissions.map((tab) => {
return (
<React.Fragment key={tab.href}>
<div className={`${!tab.children?.length ? "mb-3!" : ""}`}>
<div className="group flex h-7 w-full flex-row items-center rounded-md px-2 font-medium text-default text-sm leading-none [&[aria-current='page']]:bg-emphasis [&[aria-current='page']]:text-emphasis">
{tab?.icon && (
<Icon
name={tab.icon}
className="h-[16px] w-[16px] stroke-[2px] text-subtle md:mt-0 ltr:mr-3 rtl:ml-3"
/>
)}
{}
{!tab.icon && tab?.avatar && (
<Image
width={16}
height={16}
className="rounded-full ltr:mr-3 rtl:ml-3"
src={tab?.avatar}
alt="Organization Logo"
/>
)}
<Skeleton
title={tab.name}
as="p"
className="truncate font-medium text-sm text-subtle leading-5"
loadingClassName="ms-3">
{t(tab.name)}
</Skeleton>
</div>
</div>
<div className="flex flex-col space-y-1">
{tab.children?.map((child, index) => (
<div key={child.href} className="flex items-start gap-2">
<VerticalTabItem
name={t(child.name)}
isExternalLink={child.isExternalLink}
href={child.href || "/"}
trackingMetadata={child.trackingMetadata}
textClassNames="text-emphasis font-medium text-sm"
className={`h-auto min-h-7 w-fit px-2! py-1! ${
tab.children && index === tab.children?.length - 1 && "mb-3!"
}`}
disableChevron
/>
{child.isBadged && (
<Badge variant="blue" className="mt-0.5 text-xs">
New
</Badge>
)}
</div>
))}
</div>
</React.Fragment>
);
})}
</nav>
);
};
@@ -1039,22 +503,20 @@ const MobileSettingsContainer = (props: { onSideContainerOpen?: () => void }) =>
if (isStandalone) return null;
return (
<>
<nav className="bg-cal-muted border-muted sticky top-0 z-20 flex w-full items-center justify-between border-b px-2 py-2 sm:relative lg:hidden">
<div className="flex items-center space-x-3">
<Button StartIcon="menu" color="minimal" variant="icon" onClick={props.onSideContainerOpen}>
<span className="sr-only">{t("show_navigation")}</span>
</Button>
<nav className="sticky top-0 z-20 flex w-full items-center justify-between border-muted border-b bg-cal-muted px-2 py-2 sm:relative lg:hidden">
<div className="flex items-center space-x-3">
<Button StartIcon="menu" color="minimal" variant="icon" onClick={props.onSideContainerOpen}>
<span className="sr-only">{t("show_navigation")}</span>
</Button>
<button
className="hover:bg-emphasis flex items-center space-x-2 rounded-md px-3 py-1 rtl:space-x-reverse"
onClick={() => router.back()}>
<ArrowLeftIcon className="text-default h-4 w-4" />
<p className="text-emphasis font-semibold">{t("settings")}</p>
</button>
</div>
</nav>
</>
<button
className="flex items-center space-x-2 rounded-md px-3 py-1 hover:bg-emphasis rtl:space-x-reverse"
onClick={() => router.back()}>
<ArrowLeftIcon className="h-4 w-4 text-default" />
<p className="font-semibold text-emphasis">{t("settings")}</p>
</button>
</div>
</nav>
);
};
@@ -1066,10 +528,7 @@ type SettingsLayoutProps = {
} & ComponentProps<typeof Shell>;
function SettingsLayoutAppDirClient({ children, teamFeatures, permissions, ...rest }: SettingsLayoutProps) {
const pathname = usePathname();
const isFullWidthPage =
pathname?.includes("/settings/teams/") &&
(pathname?.includes("/attributes") || pathname?.includes("/roles"));
const _pathname = usePathname();
const state = useState(false);
const [sideContainerOpen, setSideContainerOpen] = state;
@@ -1088,7 +547,7 @@ function SettingsLayoutAppDirClient({ children, teamFeatures, permissions, ...re
useEffect(() => {
setSideContainerOpen((prev) => (prev ? false : prev));
}, [pathname, setSideContainerOpen]);
}, [setSideContainerOpen]);
return (
<Shell
@@ -1107,13 +566,9 @@ function SettingsLayoutAppDirClient({ children, teamFeatures, permissions, ...re
TopNavContainer={
<MobileSettingsContainer onSideContainerOpen={() => setSideContainerOpen(!sideContainerOpen)} />
}>
<div className="*:flex-1 flex flex-1">
<div className="flex flex-1 *:flex-1">
<div
className={classNames(
"mx-auto justify-center",
!isFullWidthPage && "max-w-full lg:max-w-3xl",
rest.containerClassName
)}>
className={classNames("mx-auto max-w-full justify-center lg:max-w-3xl", rest.containerClassName)}>
<ErrorBoundary>{children}</ErrorBoundary>
</div>
</div>
@@ -1143,7 +598,7 @@ const SidebarContainerElement = ({
{sideContainerOpen && (
<button
onClick={() => setSideContainerOpen(false)}
className="fixed left-0 top-0 z-10 h-full w-full bg-black/50">
className="fixed top-0 left-0 z-10 h-full w-full bg-black/50">
<span className="sr-only">{t("hide_navigation")}</span>
</button>
)}
@@ -1,30 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { getTranslate } from "app/_utils";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import BillingView from "~/settings/billing/billing-view";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("billing"),
(t) => t("manage_billing_description"),
undefined,
undefined,
"/settings/billing"
);
const Page = async () => {
const t = await getTranslate();
return (
<SettingsHeader
title={t("billing")}
description={t("manage_billing_description")}
borderInShellHeader={true}>
<BillingView />
</SettingsHeader>
);
};
export default Page;
@@ -4,7 +4,7 @@ import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { PrismaApiKeyRepository } from "@calcom/features/ee/api-keys/repositories/PrismaApiKeyRepository";
import { PrismaApiKeyRepository } from "@calcom/features/api-keys-legacy/api-keys/repositories/PrismaApiKeyRepository";
import { APP_NAME } from "@calcom/lib/constants";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
@@ -4,8 +4,8 @@ import { cookies, headers } from "next/headers";
import { notFound, redirect } from "next/navigation";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { WebhookRepository } from "@calcom/features/webhooks/lib/repository/WebhookRepository";
import prisma from "@calcom/prisma";
import { APP_NAME } from "@calcom/lib/constants";
import { MembershipRole } from "@calcom/prisma/enums";
@@ -34,16 +34,17 @@ const Page = async ({ params: _params }: PageProps) => {
const webhookRepository = WebhookRepository.getInstance();
const webhook = await webhookRepository.findByWebhookId(id);
// Ownership check: align with PBAC middleware in webhook/util.ts
// Ownership check: verify user has access to this webhook
if (webhook.teamId) {
const permissionService = new PermissionCheckService();
const hasPermission = await permissionService.checkPermission({
userId: session.user.id,
teamId: webhook.teamId,
permission: "webhook.read",
fallbackRoles: [MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER],
const membership = await prisma.membership.findFirst({
where: {
userId: session.user.id,
teamId: webhook.teamId,
role: { in: [MembershipRole.ADMIN, MembershipRole.OWNER, MembershipRole.MEMBER] },
},
select: { id: true },
});
if (!hasPermission) {
if (!membership) {
notFound();
}
} else if (webhook.userId !== session.user.id) {
@@ -1,42 +1,10 @@
import { unstable_cache } from "next/cache";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import React from "react";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import type { TeamFeatures } from "@calcom/features/flags/config";
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { PermissionMapper } from "@calcom/features/pbac/domain/mappers/PermissionMapper";
import { Resource, CrudAction, CustomAction } from "@calcom/features/pbac/domain/types/permission-registry";
import { PermissionCheckService } from "@calcom/features/pbac/services/permission-check.service";
import { prisma } from "@calcom/prisma";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import type { SettingsLayoutProps } from "./SettingsLayoutAppDirClient";
import SettingsLayoutAppDirClient from "./SettingsLayoutAppDirClient";
const getTeamFeatures = unstable_cache(
async (teamId: number) => {
const featuresRepository = new FeaturesRepository(prisma);
return await featuresRepository.getEnabledTeamFeatures(teamId);
},
["team-features"],
{
revalidate: 120,
}
);
const getCachedResourcePermissions = unstable_cache(
async (userId: number, teamId: number, resource: Resource) => {
const permissionService = new PermissionCheckService();
return permissionService.getResourcePermissions({ userId, teamId, resource });
},
["resource-permissions"],
{ revalidate: 120 }
);
export default async function SettingsLayoutAppDir(props: SettingsLayoutProps) {
const session = await getServerSession({ req: buildLegacyRequest(await headers(), await cookies()) });
const userId = session?.user?.id;
@@ -44,59 +12,16 @@ export default async function SettingsLayoutAppDir(props: SettingsLayoutProps) {
return redirect("/auth/login");
}
let teamFeatures: Record<number, TeamFeatures> | null = null;
let canViewRoles = false;
let canViewOrganizationBilling = false;
let canUpdateOrganization = false;
let canViewAttributes = false;
const orgId = session?.user?.profile?.organizationId ?? session?.user.org?.id;
// For now we only grab organization features but it would be nice to fetch these on the server side for specific team feature flags
if (orgId) {
const isOrgAdminOrOwner = checkAdminOrOwner(session.user.org?.role);
const features = await getTeamFeatures(orgId);
if (features) {
teamFeatures = {
[orgId]: features,
};
}
// Check if PBAC feature is enabled
const isPbacEnabled = features?.pbac === true;
if (isPbacEnabled) {
// Only fetch and apply PBAC permissions if the feature is enabled
const [rolePermissions, organizationPermissions, attributesPermissions] = await Promise.all([
getCachedResourcePermissions(userId, orgId, Resource.Role),
getCachedResourcePermissions(userId, orgId, Resource.Organization),
getCachedResourcePermissions(userId, orgId, Resource.Attributes),
]);
// Check if user has permission to read roles
const roleActions = PermissionMapper.toActionMap(rolePermissions, Resource.Role);
canViewRoles = roleActions[CrudAction.Read] ?? false;
const orgActions = PermissionMapper.toActionMap(organizationPermissions, Resource.Organization);
canViewOrganizationBilling = orgActions[CustomAction.ManageBilling] ?? isOrgAdminOrOwner;
canUpdateOrganization = orgActions[CrudAction.Update] ?? isOrgAdminOrOwner;
const attributesActions = PermissionMapper.toActionMap(attributesPermissions, Resource.Attributes);
canViewAttributes = attributesActions[CrudAction.Read] ?? isOrgAdminOrOwner;
} else {
// Fall back to legacy permissions when PBAC is not enabled or features not loaded
canViewRoles = features ? isOrgAdminOrOwner : false;
canViewOrganizationBilling = isOrgAdminOrOwner;
canUpdateOrganization = isOrgAdminOrOwner;
canViewAttributes = isOrgAdminOrOwner;
}
}
return (
<>
<SettingsLayoutAppDirClient
{...props}
teamFeatures={teamFeatures ?? {}}
permissions={{ canViewRoles, canViewOrganizationBilling, canUpdateOrganization, canViewAttributes }}
/>
</>
<SettingsLayoutAppDirClient
{...props}
teamFeatures={{}}
permissions={{
canViewRoles: false,
canViewOrganizationBilling: false,
canUpdateOrganization: false,
canViewAttributes: false,
}}
/>
);
}
@@ -1,22 +0,0 @@
import type { Metadata } from "next";
import type { ReactElement } from "react";
import { _generateMetadata } from "app/_utils";
import FeaturesView from "~/settings/my-account/features-view";
const generateMetadata = async (): Promise<Metadata> =>
await _generateMetadata(
(t) => t("features"),
(t) => t("feature_opt_in_description"),
undefined,
undefined,
"/settings/my-account/features"
);
const Page = (): ReactElement => {
return <FeaturesView />;
};
export { generateMetadata };
export default Page;
@@ -1,26 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { MembershipRole } from "@calcom/prisma/enums";
import OrgAttributesEditPage from "@calcom/web/modules/ee/organizations/attributes/attributes-edit-view";
import { validateUserHasOrgPerms } from "../../../../actions/validateUserHasOrgPerms";
export const generateMetadata = async ({ params }: { params: Promise<{ id: string }> }) =>
await _generateMetadata(
(t) => t("attribute"),
(t) => t("edit_attribute_description"),
undefined,
undefined,
`/settings/organizations/attributes/${(await params).id}/edit`
);
const OrgAttributesEditPageWrapper = async () => {
await validateUserHasOrgPerms({
permission: "organization.attributes.update",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
return <OrgAttributesEditPage />;
};
export default OrgAttributesEditPageWrapper;
@@ -1,26 +0,0 @@
import { _generateMetadata } from "app/_utils";
import OrgAttributesCreatePage from "@calcom/web/modules/ee/organizations/attributes/attributes-create-view";
import { MembershipRole } from "@calcom/prisma/enums";
import { validateUserHasOrgPerms } from "../../../actions/validateUserHasOrgPerms";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("attribute"),
(t) => t("create_attribute_description"),
undefined,
undefined,
"/settings/organizations/attributes/create"
);
const OrgAttributesCreatePageWrapper = async () => {
await validateUserHasOrgPerms({
permission: "organization.attributes.create",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
return <OrgAttributesCreatePage />;
};
export default OrgAttributesCreatePageWrapper;
@@ -1,58 +0,0 @@
import { _generateMetadata, getTranslate } from "app/_utils";
import { redirect } from "next/navigation";
import { Resource } from "@calcom/features/pbac/domain/types/permission-registry";
import { getResourcePermissions } from "@calcom/features/pbac/lib/resource-permissions";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { MembershipRole } from "@calcom/prisma/enums";
import OrgSettingsAttributesPage from "~/ee/organizations/attributes/attributes-list-view";
import { validateUserHasOrg } from "../../actions/validateUserHasOrg";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("attributes"),
(t) => t("attribute_meta_description"),
undefined,
undefined,
"/settings/organizations/attributes"
);
const Page = async () => {
const t = await getTranslate();
const session = await validateUserHasOrg();
const { canRead, canEdit, canDelete, canCreate } = await getResourcePermissions({
userId: session.user.id,
teamId: session.user.profile.organizationId,
resource: Resource.Attributes,
userRole: session.user.org.role,
fallbackRoles: {
read: {
roles: [MembershipRole.MEMBER, MembershipRole.ADMIN, MembershipRole.OWNER],
},
update: {
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
},
delete: {
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
},
create: {
roles: [MembershipRole.ADMIN, MembershipRole.OWNER],
},
},
});
if (!canRead) {
return redirect("/settings/profile");
}
return (
<SettingsHeader title={t("attributes")} description={t("attribute_meta_description")}>
<OrgSettingsAttributesPage permissions={{ canEdit, canDelete, canCreate }} />
</SettingsHeader>
);
};
export default Page;
@@ -1,62 +0,0 @@
import { _generateMetadata, getTranslate } from "app/_utils";
import { getIntegrationAttributeSyncService } from "@calcom/features/ee/integration-attribute-sync/di/IntegrationAttributeSyncService.container";
import { TeamRepository } from "@calcom/features/ee/teams/repositories/TeamRepository";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { PrismaAttributeRepository } from "@calcom/features/attributes/repositories/PrismaAttributeRepository";
import { prisma } from "@calcom/prisma";
import IntegrationAttributeSyncView from "@calcom/web/modules/integration-attribute-sync/components/IntegrationAttributeSyncView";
import { validateUserHasOrgPerms } from "../../../actions/validateUserHasOrgPerms";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("attribute_sync"),
(t) => t("attribute_sync_description"),
undefined,
undefined,
"/settings/organizations/attributes/sync"
);
const Page = async () => {
const t = await getTranslate();
const session = await validateUserHasOrgPerms({
permission: "organization.attributes.create",
fallbackRoles: ["ADMIN", "OWNER"],
redirectTo: "/settings/my-account/profile",
});
const organizationId = session.user.org.id;
const integrationAttributeSyncService = getIntegrationAttributeSyncService();
const teamRepository = new TeamRepository(prisma);
const attributeRepo = new PrismaAttributeRepository(prisma);
const [credentialData, integrationAttributeSyncs, organizationTeams, attributes] = await Promise.all([
integrationAttributeSyncService.getEnabledAppCredentials(organizationId),
integrationAttributeSyncService.getAllIntegrationAttributeSyncs(organizationId),
teamRepository.findAllByParentId({
parentId: organizationId,
select: {
id: true,
name: true,
},
}),
attributeRepo.findAllByOrgIdWithOptions({ orgId: organizationId }),
]);
return (
<SettingsHeader title={t("attribute_sync")} description={t("attribute_sync_description")}>
<IntegrationAttributeSyncView
credentialsData={credentialData}
initialIntegrationAttributeSyncs={integrationAttributeSyncs}
organizationTeams={organizationTeams}
attributes={attributes}
organizationId={organizationId}
/>
</SettingsHeader>
);
};
export default Page;
@@ -1,38 +0,0 @@
import { _generateMetadata } from "app/_utils";
import { getTranslate } from "app/_utils";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { MembershipRole } from "@calcom/prisma/enums";
import BillingView from "~/settings/billing/billing-view";
import { validateUserHasOrgPerms } from "../../actions/validateUserHasOrgPerms";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("billing"),
(t) => t("manage_billing_description"),
undefined,
undefined,
"/settings/organizations/billing"
);
const Page = async () => {
const t = await getTranslate();
await validateUserHasOrgPerms({
permission: "organization.manageBilling",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
return (
<SettingsHeader
title={t("billing")}
description={t("manage_billing_description")}
borderInShellHeader={true}>
<BillingView />
</SettingsHeader>
);
};
export default Page;
@@ -1,36 +0,0 @@
import { _generateMetadata, getTranslate } from "app/_utils";
import DelegationCredentialList from "~/ee/organizations/delegationCredential";
import SettingsHeader from "@calcom/features/settings/appDir/SettingsHeader";
import { MembershipRole } from "@calcom/prisma/enums";
import { validateUserHasOrgPerms } from "../../actions/validateUserHasOrgPerms";
export const generateMetadata = async () =>
await _generateMetadata(
(t) => t("delegation_credential"),
(t) => t("delegation_credential_description"),
undefined,
undefined,
"/settings/organizations/delegation-credential"
);
const Page = async () => {
const t = await getTranslate();
await validateUserHasOrgPerms({
permission: "organization.update",
fallbackRoles: [MembershipRole.OWNER, MembershipRole.ADMIN],
});
return (
<SettingsHeader
borderInShellHeader
title={t("delegation_credential")}
description={t("delegation_credential_description")}>
<DelegationCredentialList />
</SettingsHeader>
);
};
export default Page;
Loaded 100 of 4080 files, more files were not shown because too many files have changed in this diff. Show more