chore: App-router-migration(/apps) fix metadata, extract components into /module and finish migration (#16354)

* fix metadata for apps page

* migrate apps route to modules

* migrate apps/[slug]

* migrate apps/[slug]/setup

* migrate apps/categories/**/*

* add apps/installed page to app router

* migrate apps/[slug]/[...pages]

* migrate apps/installed/**/*

* Add apps/installation/[[...step]] to App router

* fix imports

* add missing use client directive

* finish migration

* fix metadata

* fix metadata for apps/categories

* fix type for installation/[[...step]]

* fix type for apps/[slug]/[...pages]

* remove unnecessary code

* refactor

* fix apps/installation

* move getServerSideProps to lib

* fix import of apps/installation

* fix import for app slug page

* refactor

* fix installation page in app router

* remove res in getServerSideProps

* replace setHeader with NextResponse header setHeader

* refactor installed pages

---------

Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Peer Richelsen <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-09-06 15:40:19 +00:00
1 parent a910eb96ad
commit d2f7a427d0
34 files changed
+1523 -1430

No files matched your search

@@ -0,0 +1,99 @@
"use client";
import RoutingFormsRoutingConfig from "@calcom/app-store/routing-forms/pages/app-routing.config";
import TypeformRoutingConfig from "@calcom/app-store/typeform/pages/app-routing.config";
import { useParamsWithFallback } from "@calcom/lib/hooks/useParamsWithFallback";
import type { AppGetServerSideProps } from "@calcom/types/AppGetServerSideProps";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import type { AppProps } from "@lib/app-providers";
import type { getServerSideProps } from "@lib/apps/[slug]/[...pages]/getServerSideProps";
type AppPageType = {
getServerSideProps: AppGetServerSideProps;
// A component than can accept any properties
// eslint-disable-next-line @typescript-eslint/no-explicit-any
default: ((props: any) => JSX.Element) &
Pick<AppProps["Component"], "isBookingPage" | "getLayout" | "PageWrapper">;
};
type Found = {
notFound: false;
Component: AppPageType["default"];
getServerSideProps: AppPageType["getServerSideProps"];
};
type NotFound = {
notFound: true;
};
// TODO: It is a candidate for apps.*.generated.*
const AppsRouting = {
"routing-forms": RoutingFormsRoutingConfig,
typeform: TypeformRoutingConfig,
};
function getRoute(appName: string, pages: string[]) {
const routingConfig = AppsRouting[appName as keyof typeof AppsRouting] as Record<string, AppPageType>;
if (!routingConfig) {
return {
notFound: true,
} as NotFound;
}
const mainPage = pages[0];
const appPage = routingConfig.layoutHandler || (routingConfig[mainPage] as AppPageType);
if (!appPage) {
return {
notFound: true,
} as NotFound;
}
return { notFound: false, Component: appPage.default, ...appPage } as Found;
}
export type PageProps = inferSSRProps<typeof getServerSideProps>;
const AppPage: AppPageType["default"] = function AppPage(props: PageProps) {
const appName = props.appName;
const params = useParamsWithFallback();
const pages = Array.isArray(params.pages) ? params.pages : params.pages?.split("/") ?? [];
const route = getRoute(appName, pages);
const componentProps = {
...props,
pages: pages.slice(1),
};
if (!route || route.notFound) {
throw new Error("Route can't be undefined");
}
return <route.Component {...componentProps} />;
};
AppPage.isBookingPage = ({ router }) => {
const route = getRoute(router.query.slug as string, router.query.pages as string[]);
if (route.notFound) {
return false;
}
const isBookingPage = route.Component.isBookingPage;
if (typeof isBookingPage === "function") {
return isBookingPage({ router });
}
return !!isBookingPage;
};
export const getLayout: NonNullable<(typeof AppPage)["getLayout"]> = (page) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { slug, pages } = useParamsWithFallback();
const route = getRoute(slug as string, pages as string[]);
if (route.notFound) {
return null;
}
if (!route.Component.getLayout) {
return page;
}
return route.Component.getLayout(page);
};
export default AppPage;
@@ -0,0 +1,38 @@
"use client";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { AppSetupPage } from "@calcom/app-store/_pages/setup";
import type { getServerSideProps } from "@calcom/app-store/_pages/setup/_getServerSideProps";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import { HeadSeo } from "@calcom/ui";
export type PageProps = inferSSRProps<typeof getServerSideProps>;
export default function SetupInformation(props: PageProps) {
const searchParams = useCompatSearchParams();
const router = useRouter();
const slug = searchParams?.get("slug") as string;
const { status } = useSession();
if (status === "loading") {
return <div className="bg-emphasis absolute z-50 flex h-screen w-full items-center" />;
}
if (status === "unauthenticated") {
const urlSearchParams = new URLSearchParams({
callbackUrl: `/apps/${slug}/setup`,
});
router.replace(`/auth/login?${urlSearchParams.toString()}`);
}
return (
<>
{/* So that the set up page does not get indexed by search engines */}
<HeadSeo nextSeoProps={{ noindex: true, nofollow: true }} title={`${slug} | Cal.com`} description="" />
<AppSetupPage slug={slug} {...props} />
</>
);
}
@@ -0,0 +1,81 @@
"use client";
import MarkdownIt from "markdown-it";
import type { InferGetStaticPropsType } from "next";
import Link from "next/link";
import { IS_PRODUCTION } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { showToast } from "@calcom/ui";
import type { getStaticProps } from "@lib/apps/[slug]/getStaticProps";
import useRouterQuery from "@lib/hooks/useRouterQuery";
import App from "@components/apps/App";
const md = new MarkdownIt("default", { html: true, breaks: true });
export type PageProps = InferGetStaticPropsType<typeof getStaticProps>;
function SingleAppPage(props: PageProps) {
const { error, setQuery: setError } = useRouterQuery("error");
const { t } = useLocale();
if (error === "account_already_linked") {
showToast(t(error), "error", { id: error });
setError(undefined);
}
// If it's not production environment, it would be a better idea to inform that the App is disabled.
if (props.isAppDisabled) {
if (!IS_PRODUCTION) {
// TODO: Improve disabled App UI. This is just a placeholder.
return (
<div className="p-2">
This App seems to be disabled. If you are an admin, you can enable this app from{" "}
<Link href="/settings/admin/apps" className="cursor-pointer text-blue-500 underline">
here
</Link>
</div>
);
}
// Disabled App should give 404 any ways in production.
return null;
}
const { source, data } = props;
return (
<App
name={data.name}
description={data.description}
isGlobal={data.isGlobal}
slug={data.slug}
variant={data.variant}
type={data.type}
logo={data.logo}
categories={data.categories ?? [data.category]}
author={data.publisher}
feeType={data.feeType || "usage-based"}
price={data.price || 0}
commission={data.commission || 0}
docs={data.docsUrl}
website={data.url}
email={data.email}
licenseRequired={data.licenseRequired}
teamsPlanRequired={data.teamsPlanRequired}
descriptionItems={source.data?.items as string[] | undefined}
isTemplate={data.isTemplate}
dependencies={data.dependencies}
concurrentMeetings={data.concurrentMeetings}
paid={data.paid}
// tos="https://zoom.us/terms"
// privacy="https://zoom.us/privacy"
body={
<>
<div dangerouslySetInnerHTML={{ __html: md.render(source.content) }} />
</>
}
/>
);
}
export default SingleAppPage;
+110
View File
@@ -0,0 +1,110 @@
"use client";
import type { ChangeEventHandler } from "react";
import { useState } from "react";
import Shell from "@calcom/features/shell/Shell";
import { classNames } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import type { HorizontalTabItemProps } from "@calcom/ui";
import {
AllApps,
AppStoreCategories,
HorizontalTabs,
TextField,
PopularAppsSlider,
RecentAppsSlider,
} from "@calcom/ui";
import { Icon } from "@calcom/ui";
import { type getServerSideProps } from "@lib/apps/getServerSideProps";
import AppsLayout from "@components/apps/layouts/AppsLayout";
const tabs: HorizontalTabItemProps[] = [
{
name: "app_store",
href: "/apps",
},
{
name: "installed_apps",
href: "/apps/installed",
},
];
function AppsSearch({
onChange,
className,
}: {
onChange: ChangeEventHandler<HTMLInputElement>;
className?: string;
}) {
const { t } = useLocale();
return (
<TextField
className="bg-subtle !border-muted !pl-0 focus:!ring-offset-0"
addOnLeading={<Icon name="search" className="text-subtle h-4 w-4" />}
addOnClassname="!border-muted"
containerClassName={classNames("focus:!ring-offset-0 m-1", className)}
type="search"
autoComplete="false"
onChange={onChange}
placeholder={t("search")}
/>
);
}
export type PageProps = inferSSRProps<typeof getServerSideProps>;
export default function Apps({ categories, appStore, userAdminTeams }: PageProps) {
const { t } = useLocale();
const [searchText, setSearchText] = useState<string | undefined>(undefined);
return (
<AppsLayout
isPublic
heading={t("app_store")}
subtitle={t("app_store_description")}
actions={(className) => (
<div className="flex w-full flex-col pt-4 md:flex-row md:justify-between md:pt-0 lg:w-auto">
<div className="ltr:mr-2 rtl:ml-2 lg:hidden">
<HorizontalTabs tabs={tabs} />
</div>
<div>
<AppsSearch className={className} onChange={(e) => setSearchText(e.target.value)} />
</div>
</div>
)}
headerClassName="sm:hidden lg:block hidden"
emptyStore={!appStore.length}>
<div className="flex flex-col gap-y-8">
{!searchText && (
<>
<AppStoreCategories categories={categories} />
<PopularAppsSlider items={appStore} />
<RecentAppsSlider items={appStore} />
</>
)}
<AllApps
apps={appStore}
searchText={searchText}
categories={categories.map((category) => category.name)}
userAdminTeams={userAdminTeams}
/>
</div>
</AppsLayout>
);
}
export const LayoutWrapper = (page: React.ReactElement) => {
return (
<Shell
title="Apps Store"
description="Create forms to direct attendees to the correct destinations."
withoutMain={true}
hideHeadingOnMobile>
{page}
</Shell>
);
};
@@ -0,0 +1,54 @@
"use client";
import type { InferGetStaticPropsType } from "next";
import Link from "next/link";
import Shell from "@calcom/features/shell/Shell";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { AppCard, SkeletonText } from "@calcom/ui";
import type { getStaticProps } from "@lib/apps/categories/[category]/getStaticProps";
export type PageProps = InferGetStaticPropsType<typeof getStaticProps>;
export default function Apps({ apps }: PageProps) {
const searchParams = useCompatSearchParams();
const { t, isLocaleReady } = useLocale();
const category = searchParams?.get("category");
return (
<>
<Shell
isPublic
backPath="/apps"
title="Apps Store"
description="Connecting people, technology and the workplace."
smallHeading
heading={
<>
<Link
href="/apps"
className="text-emphasis inline-flex items-center justify-start gap-1 rounded-sm py-2">
{isLocaleReady ? t("app_store") : <SkeletonText className="h-4 w-24" />}{" "}
</Link>
{category && (
<span className="text-default gap-1">
<span>&nbsp;/&nbsp;</span>
{t("category_apps", { category: category[0].toUpperCase() + category?.slice(1) })}
</span>
)}
</>
}>
<div className="mb-16">
<div className="grid-col-1 grid grid-cols-1 gap-3 md:grid-cols-3">
{apps
?.sort((a, b) => (b.installCount || 0) - (a.installCount || 0))
.map((app) => {
return <AppCard key={app.slug} app={app} />;
})}
</div>
</div>
</Shell>
</>
);
}
@@ -0,0 +1,53 @@
"use client";
import Link from "next/link";
import Shell from "@calcom/features/shell/Shell";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import { Icon, SkeletonText } from "@calcom/ui";
import type { getServerSideProps } from "@lib/apps/categories/getServerSideProps";
export type PageProps = inferSSRProps<typeof getServerSideProps>;
export default function Apps({ categories }: PageProps) {
const { t, isLocaleReady } = useLocale();
return (
<Shell
isPublic
large
hideHeadingOnMobile
title="Apps Store"
description="Connecting people, technology and the workplace.">
<div className="text-md flex items-center gap-1 px-4 pb-3 pt-3 font-normal md:px-8 lg:px-0 lg:pt-0">
<Link
href="/apps"
className="text-emphasis inline-flex items-center justify-start gap-1 rounded-sm py-2">
<Icon name="arrow-left" className="h-4 w-4" />
{isLocaleReady ? t("app_store") : <SkeletonText className="h-6 w-24" />}{" "}
</Link>
</div>
<div className="mb-16">
<div className="grid h-auto w-full grid-cols-5 gap-3">
{categories.map((category) => (
<Link
key={category.name}
href={`/apps/categories/${category.name}`}
data-testid={`app-store-category-${category.name}`}
className="bg-subtle relative flex rounded-sm px-6 py-4 sm:block">
<div className="self-center">
<h3 className="font-medium capitalize">{category.name}</h3>
<p className="text-subtle text-sm">
{t("number_apps", { count: category.count })}{" "}
<Icon name="arrow-right" className="inline-block h-4 w-4" />
</p>
</div>
</Link>
))}
</div>
</div>
</Shell>
);
}
@@ -0,0 +1,7 @@
import { AppOnboardingSteps } from "@calcom/lib/apps/appOnboardingSteps";
export const STEPS = [
AppOnboardingSteps.ACCOUNTS_STEP,
AppOnboardingSteps.EVENT_TYPES_STEP,
AppOnboardingSteps.CONFIGURE_STEP,
] as const;
@@ -0,0 +1,306 @@
"use client";
import Head from "next/head";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { Toaster } from "react-hot-toast";
import type { z } from "zod";
import checkForMultiplePaymentApps from "@calcom/app-store/_utils/payments/checkForMultiplePaymentApps";
import useAddAppMutation from "@calcom/app-store/_utils/useAddAppMutation";
import type { EventTypeAppSettingsComponentProps, EventTypeModel } from "@calcom/app-store/types";
import type { LocationObject } from "@calcom/core/location";
import type { LocationFormValues } from "@calcom/features/eventtypes/lib/types";
import { AppOnboardingSteps } from "@calcom/lib/apps/appOnboardingSteps";
import { getAppOnboardingUrl } from "@calcom/lib/apps/getAppOnboardingUrl";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { eventTypeBookingFields } from "@calcom/prisma/zod-utils";
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import type { AppMeta } from "@calcom/types/App";
import { Form, Steps, showToast } from "@calcom/ui";
import { HttpError } from "@lib/core/http/error";
import type { PersonalAccountProps, TeamsProp } from "@components/apps/installation/AccountsStepCard";
import { AccountsStepCard } from "@components/apps/installation/AccountsStepCard";
import { ConfigureStepCard } from "@components/apps/installation/ConfigureStepCard";
import { EventTypesStepCard } from "@components/apps/installation/EventTypesStepCard";
import { StepHeader } from "@components/apps/installation/StepHeader";
import { STEPS } from "~/apps/installation/[[...step]]/constants";
export type TEventType = EventTypeAppSettingsComponentProps["eventType"] &
Pick<
EventTypeModel,
"metadata" | "schedulingType" | "slug" | "requiresConfirmation" | "position" | "destinationCalendar"
> & {
selected: boolean;
locations: LocationFormValues["locations"];
bookingFields?: LocationFormValues["bookingFields"];
};
export type TEventTypesForm = {
eventTypes: TEventType[];
};
type StepType = (typeof STEPS)[number];
type StepObj = Record<
StepType,
{
getTitle: (appName: string) => string;
getDescription: (appName: string) => string;
stepNumber: number;
}
>;
export type OnboardingPageProps = {
appMetadata: AppMeta;
step: StepType;
teams?: TeamsProp;
personalAccount: PersonalAccountProps;
eventTypes?: TEventType[];
userName: string;
credentialId?: number;
showEventTypesStep: boolean;
isConferencing: boolean;
installableOnTeams: boolean;
};
type TUpdateObject = {
id: number;
metadata?: z.infer<typeof EventTypeMetaDataSchema>;
bookingFields?: z.infer<typeof eventTypeBookingFields>;
locations?: LocationObject[];
};
const OnboardingPage = ({
step,
teams,
personalAccount,
appMetadata,
eventTypes,
userName,
credentialId,
showEventTypesStep,
isConferencing,
installableOnTeams,
}: OnboardingPageProps) => {
const { t } = useLocale();
const pathname = usePathname();
const router = useRouter();
const STEPS_MAP: StepObj = {
[AppOnboardingSteps.ACCOUNTS_STEP]: {
getTitle: () => `${t("select_account_header")}`,
getDescription: (appName) => `${t("select_account_description", { appName })}`,
stepNumber: 1,
},
[AppOnboardingSteps.EVENT_TYPES_STEP]: {
getTitle: () => `${t("select_event_types_header")}`,
getDescription: (appName) => `${t("select_event_types_description", { appName })}`,
stepNumber: installableOnTeams ? 2 : 1,
},
[AppOnboardingSteps.CONFIGURE_STEP]: {
getTitle: (appName) => `${t("configure_app_header", { appName })}`,
getDescription: () => `${t("configure_app_description")}`,
stepNumber: installableOnTeams ? 3 : 2,
},
} as const;
const [configureStep, setConfigureStep] = useState(false);
const currentStep: AppOnboardingSteps = useMemo(() => {
if (step == AppOnboardingSteps.EVENT_TYPES_STEP && configureStep) {
return AppOnboardingSteps.CONFIGURE_STEP;
}
return step;
}, [step, configureStep]);
const stepObj = STEPS_MAP[currentStep];
const maxSteps = useMemo(() => {
if (!showEventTypesStep) {
return 1;
}
return installableOnTeams ? STEPS.length : STEPS.length - 1;
}, [showEventTypesStep, installableOnTeams]);
const utils = trpc.useContext();
const formPortalRef = useRef<HTMLDivElement>(null);
const formMethods = useForm<TEventTypesForm>({
defaultValues: {
eventTypes,
},
});
const mutation = useAddAppMutation(null, {
onSuccess: (data) => {
if (data?.setupPending) return;
showToast(t("app_successfully_installed"), "success");
},
onError: (error) => {
if (error instanceof Error) showToast(error.message || t("app_could_not_be_installed"), "error");
},
});
useEffect(() => {
eventTypes && formMethods.setValue("eventTypes", eventTypes);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [eventTypes]);
const updateMutation = trpc.viewer.eventTypes.update.useMutation({
onSuccess: async (data) => {
showToast(t("event_type_updated_successfully", { eventTypeTitle: data.eventType?.title }), "success");
},
async onSettled() {
await utils.viewer.eventTypes.get.invalidate();
},
onError: (err) => {
let message = "";
if (err instanceof HttpError) {
const message = `${err.statusCode}: ${err.message}`;
showToast(message, "error");
}
if (err.data?.code === "UNAUTHORIZED") {
message = `${err.data.code}: ${t("error_event_type_unauthorized_update")}`;
}
if (err.data?.code === "PARSE_ERROR" || err.data?.code === "BAD_REQUEST") {
message = `${err.data.code}: ${t(err.message)}`;
}
if (err.data?.code === "INTERNAL_SERVER_ERROR") {
message = t("unexpected_error_try_again");
}
showToast(message ? t(message) : t(err.message), "error");
},
});
const handleSelectAccount = async (teamId?: number) => {
mutation.mutate({
type: appMetadata.type,
variant: appMetadata.variant,
slug: appMetadata.slug,
...(teamId && { teamId }),
// for oAuth apps
...(showEventTypesStep && {
returnTo:
WEBAPP_URL +
getAppOnboardingUrl({
slug: appMetadata.slug,
teamId,
step: AppOnboardingSteps.EVENT_TYPES_STEP,
}),
}),
});
};
const handleSetUpLater = () => {
router.push(`/apps/installed/${appMetadata.categories[0]}?hl=${appMetadata.slug}`);
};
return (
<div
key={pathname}
className="dark:bg-brand dark:text-brand-contrast text-emphasis min-h-screen px-4"
data-testid="onboarding">
<Head>
<title>
{t("install")} {appMetadata?.name ?? ""}
</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<div className="mx-auto py-6 sm:px-4 md:py-24">
<div className="relative">
<div className="sm:mx-auto sm:w-full sm:max-w-[600px]" ref={formPortalRef}>
<Form
form={formMethods}
id="outer-event-type-form"
handleSubmit={async (values) => {
const mutationPromises = values?.eventTypes
.filter((eventType) => eventType.selected)
.map((value: TEventType) => {
// Prevent two payment apps to be enabled
// Ok to cast type here because this metadata will be updated as the event type metadata
if (
checkForMultiplePaymentApps(value.metadata as z.infer<typeof EventTypeMetaDataSchema>)
)
throw new Error(t("event_setup_multiple_payment_apps_error"));
if (value.metadata?.apps?.stripe?.paymentOption === "HOLD" && value.seatsPerTimeSlot) {
throw new Error(t("seats_and_no_show_fee_error"));
}
let updateObject: TUpdateObject = { id: value.id };
if (isConferencing) {
updateObject = {
...updateObject,
locations: value.locations,
bookingFields: value.bookingFields ? value.bookingFields : undefined,
};
} else {
updateObject = {
...updateObject,
metadata: value.metadata,
};
}
return updateMutation.mutateAsync(updateObject);
});
try {
await Promise.all(mutationPromises);
router.push("/event-types");
} catch (err) {
console.error(err);
}
}}>
<StepHeader
title={stepObj.getTitle(appMetadata.name)}
subtitle={stepObj.getDescription(appMetadata.name)}>
<Steps maxSteps={maxSteps} currentStep={stepObj.stepNumber} disableNavigation />
</StepHeader>
{currentStep === AppOnboardingSteps.ACCOUNTS_STEP && (
<AccountsStepCard
teams={teams}
personalAccount={personalAccount}
onSelect={handleSelectAccount}
loading={mutation.isPending}
installableOnTeams={installableOnTeams}
/>
)}
{currentStep === AppOnboardingSteps.EVENT_TYPES_STEP &&
eventTypes &&
Boolean(eventTypes?.length) && (
<EventTypesStepCard
setConfigureStep={setConfigureStep}
userName={userName}
handleSetUpLater={handleSetUpLater}
/>
)}
{currentStep === AppOnboardingSteps.CONFIGURE_STEP && formPortalRef.current && (
<ConfigureStepCard
slug={appMetadata.slug}
categories={appMetadata.categories}
credentialId={credentialId}
userName={userName}
loading={updateMutation.isPending}
formPortalRef={formPortalRef}
setConfigureStep={setConfigureStep}
eventTypes={eventTypes}
handleSetUpLater={handleSetUpLater}
isConferencing={isConferencing}
/>
)}
</Form>
</div>
</div>
</div>
<Toaster position="bottom-right" />
</div>
);
};
export default OnboardingPage;
@@ -0,0 +1,162 @@
"use client";
import { useReducer } from "react";
import getAppCategoryTitle from "@calcom/app-store/_utils/getAppCategoryTitle";
import DisconnectIntegrationModal from "@calcom/features/apps/components/DisconnectIntegrationModal";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { AppCategories } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import type { Icon } from "@calcom/ui";
import { AppSkeletonLoader as SkeletonLoader, Button, EmptyScreen, ShellSubHeading } from "@calcom/ui";
import { QueryCell } from "@lib/QueryCell";
import type { querySchemaType, getServerSideProps } from "@lib/apps/installed/[category]/getServerSideProps";
import { AppList } from "@components/apps/AppList";
import { CalendarListContainer } from "@components/apps/CalendarListContainer";
import InstalledAppsLayout from "@components/apps/layouts/InstalledAppsLayout";
interface IntegrationsContainerProps {
variant?: AppCategories;
exclude?: AppCategories[];
handleDisconnect: (credentialId: number) => void;
}
const IntegrationsContainer = ({
variant,
exclude,
handleDisconnect,
}: IntegrationsContainerProps): JSX.Element => {
const { t } = useLocale();
const query = trpc.viewer.integrations.useQuery({
variant,
exclude,
onlyInstalled: true,
includeTeamInstalledApps: true,
});
// TODO: Refactor and reuse getAppCategories?
const emptyIcon: Record<AppCategories, React.ComponentProps<typeof Icon>["name"]> = {
calendar: "calendar",
conferencing: "video",
automation: "share-2",
analytics: "chart-bar",
payment: "credit-card",
other: "grid-3x3",
web3: "credit-card", // deprecated
video: "video", // deprecated
messaging: "mail",
crm: "contact",
};
return (
<QueryCell
query={query}
customLoader={<SkeletonLoader />}
success={({ data }) => {
if (!data.items.length) {
const emptyHeaderCategory = getAppCategoryTitle(variant || "other", true);
return (
<EmptyScreen
Icon={emptyIcon[variant || "other"]}
headline={t("no_category_apps", {
category: emptyHeaderCategory,
})}
description={t(`no_category_apps_description_${variant || "other"}`)}
buttonRaw={
<Button
color="secondary"
data-testid={`connect-${variant || "other"}-apps`}
href={variant ? `/apps/categories/${variant}` : "/apps/categories/other"}>
{t(`connect_${variant || "other"}_apps`)}
</Button>
}
/>
);
}
return (
<div className="border-subtle rounded-md border p-7">
<ShellSubHeading
title={t(variant || "other")}
subtitle={t(`installed_app_${variant || "other"}_description`)}
className="mb-6"
actions={
<Button
data-testid="add-apps"
href={variant ? `/apps/categories/${variant}` : "/apps"}
color="secondary"
StartIcon="plus">
{t("add")}
</Button>
}
/>
<AppList handleDisconnect={handleDisconnect} data={data} variant={variant} />
</div>
);
}}
/>
);
};
type ModalState = {
isOpen: boolean;
credentialId: null | number;
teamId?: number;
};
export type PageProps = inferSSRProps<typeof getServerSideProps>;
export default function InstalledApps(props: PageProps) {
const searchParams = useCompatSearchParams();
const { t } = useLocale();
const category = searchParams?.get("category") as querySchemaType["category"];
const categoryList: AppCategories[] = Object.values(AppCategories).filter((category) => {
// Exclude calendar and other from categoryList, we handle those slightly differently below
return !(category in { other: null, calendar: null });
});
const [data, updateData] = useReducer(
(data: ModalState, partialData: Partial<ModalState>) => ({ ...data, ...partialData }),
{
isOpen: false,
credentialId: null,
}
);
const handleModelClose = () => {
updateData({ isOpen: false, credentialId: null });
};
const handleDisconnect = (credentialId: number, teamId?: number) => {
updateData({ isOpen: true, credentialId, teamId });
};
return (
<>
<InstalledAppsLayout heading={t("installed_apps")} subtitle={t("manage_your_connected_apps")}>
{categoryList.includes(category) && (
<IntegrationsContainer handleDisconnect={handleDisconnect} variant={category} />
)}
{category === "calendar" && <CalendarListContainer />}
{category === "other" && (
<IntegrationsContainer
handleDisconnect={handleDisconnect}
variant={category}
exclude={[...categoryList, "calendar"]}
/>
)}
</InstalledAppsLayout>
<DisconnectIntegrationModal
handleModelClose={handleModelClose}
isOpen={data.isOpen}
credentialId={data.credentialId}
teamId={data.teamId}
/>
</>
);
}