chore: [app-router-migration 38]: Refactor migrated pages and fix generateMetadata functions (#13314)

* refactor to keep consistencies in files

* manual: more refactors

* revert unnecessary changes

* fix type errors

* fix build error

* fix
This commit is contained in:
Benny Joo authored and GitHub committed 2024-01-22 17:32:15 -03:00
1 parent 850e222f0e
commit 827d8995a1
23 files changed
+131 -347

No files matched your search

@@ -1,16 +1,15 @@
import CategoryPage from "@pages/apps/categories/[category]";
import CategoryPage, { type PageProps } from "@pages/apps/categories/[category]";
import { Prisma } from "@prisma/client";
import { withAppDirSsg } from "app/WithAppDirSsg";
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import { type GetServerSidePropsContext } from "next";
import { notFound } from "next/navigation";
import z from "zod";
import { getAppRegistry } from "@calcom/app-store/_appRegistry";
import { APP_NAME } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import { AppCategories } from "@calcom/prisma/enums";
import { getStaticProps } from "@lib/apps/categories/[category]/getStaticProps";
export const generateMetadata = async () => {
return await _generateMetadata(
() => `${APP_NAME} | ${APP_NAME}`,
@@ -35,37 +34,7 @@ export const generateStaticParams = async () => {
return paths.map((category) => ({ category }));
};
const querySchema = z.object({
category: z.nativeEnum(AppCategories),
});
const getData = withAppDirSsg<PageProps>(getStaticProps);
const getPageProps = async (context: GetServerSidePropsContext) => {
const p = querySchema.safeParse(context.params);
if (!p.success) {
return notFound();
}
const appQuery = await prisma.app.findMany({
where: {
categories: {
has: p.data.category,
},
},
select: {
slug: true,
},
});
const dbAppsSlugs = appQuery.map((category) => category.slug);
const appStore = await getAppRegistry();
const apps = appStore.filter((app) => dbAppsSlugs.includes(app.slug));
return {
apps,
};
};
export default WithLayout({ getData: getPageProps, Page: CategoryPage, getLayout: null })<"P">;
export default WithLayout({ getData, Page: CategoryPage, getLayout: null })<"P">;
export const dynamic = "force-static";
@@ -1,5 +0,0 @@
import { WithLayout } from "app/layoutHOC";
import { getLayout } from "@calcom/features/MainLayoutAppDir";
export default WithLayout({ getLayout })<"L">;
+4 -1
View File
@@ -1,4 +1,7 @@
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import { getLayout } from "@calcom/features/MainLayoutAppDir";
import EnterprisePage from "@components/EnterprisePage";
@@ -8,4 +11,4 @@ export const generateMetadata = async () =>
(t) => t("create_your_org_description")
);
export default EnterprisePage;
export default WithLayout({ getLayout, Page: EnterprisePage })<"P">;
@@ -1,5 +0,0 @@
import { WithLayout } from "app/layoutHOC";
import { getLayout } from "@calcom/features/MainLayoutAppDir";
export default WithLayout({ getLayout })<"L">;
+4 -1
View File
@@ -1,5 +1,8 @@
import EventTypes from "@pages/event-types";
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import { getLayout } from "@calcom/features/MainLayoutAppDir";
export const generateMetadata = async () =>
await _generateMetadata(
@@ -7,4 +10,4 @@ export const generateMetadata = async () =>
(t) => t("event_types_page_subtitle")
);
export default EventTypes;
export default WithLayout({ getLayout, Page: EventTypes })<"P">;
+5 -13
View File
@@ -1,10 +1,11 @@
import LegacyPage from "@pages/insights/index";
import LegacyPage, { getServerSideProps } from "@pages/insights/index";
import { withAppDirSsr } from "app/WithAppDirSsr";
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import { notFound } from "next/navigation";
import { getLayout } from "@calcom/features/MainLayoutAppDir";
import { getFeatureFlagMap } from "@calcom/features/flags/server/utils";
import { type inferSSRProps } from "@lib/types/inferSSRProps";
export const generateMetadata = async () =>
await _generateMetadata(
@@ -12,15 +13,6 @@ export const generateMetadata = async () =>
(t) => t("insights_subtitle")
);
async function getData() {
const prisma = await import("@calcom/prisma").then((mod) => mod.default);
const flags = await getFeatureFlagMap(prisma);
if (flags.insights === false) {
return notFound();
}
return {};
}
const getData = withAppDirSsr<inferSSRProps<typeof getServerSideProps>>(getServerSideProps);
export default WithLayout({ getLayout, getData, Page: LegacyPage });
+3 -152
View File
@@ -1,18 +1,10 @@
import { withAppDirSsr } from "app/WithAppDirSsr";
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import { type GetServerSidePropsContext } from "next";
import { redirect, notFound } from "next/navigation";
import { z } from "zod";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import PaymentPage from "@calcom/features/ee/payments/components/PaymentPage";
import { getClientSecretFromPayment } from "@calcom/features/ee/payments/pages/getClientSecretFromPayment";
import { getServerSideProps, type PaymentPageProps } from "@calcom/features/ee/payments/pages/payment";
import { APP_NAME } from "@calcom/lib/constants";
import prisma from "@calcom/prisma";
import { BookingStatus } from "@calcom/prisma/enums";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { ssrInit } from "@server/lib/ssr";
export const generateMetadata = async () =>
await _generateMetadata(
@@ -21,147 +13,6 @@ export const generateMetadata = async () =>
() => ""
);
const querySchema = z.object({
uid: z.string(),
});
async function getData(context: GetServerSidePropsContext) {
const session = await getServerSession({ req: context.req });
if (!session?.user?.id) {
return redirect("/auth/login");
}
const ssr = await ssrInit(context);
await ssr.viewer.me.prefetch();
const { uid } = querySchema.parse(context.params);
const rawPayment = await prisma.payment.findFirst({
where: {
uid,
},
select: {
data: true,
success: true,
uid: true,
refunded: true,
bookingId: true,
appId: true,
amount: true,
currency: true,
paymentOption: true,
booking: {
select: {
id: true,
uid: true,
description: true,
title: true,
startTime: true,
endTime: true,
attendees: {
select: {
email: true,
name: true,
},
},
eventTypeId: true,
location: true,
status: true,
rejectionReason: true,
cancellationReason: true,
eventType: {
select: {
id: true,
title: true,
description: true,
length: true,
eventName: true,
requiresConfirmation: true,
userId: true,
metadata: true,
users: {
select: {
name: true,
username: true,
hideBranding: true,
theme: true,
},
},
team: {
select: {
name: true,
hideBranding: true,
},
},
price: true,
currency: true,
successRedirectUrl: true,
},
},
},
},
},
});
if (!rawPayment) {
return notFound();
}
const { data, booking: _booking, ...restPayment } = rawPayment;
const payment = {
...restPayment,
data: data as Record<string, unknown>,
};
if (!_booking) {
return notFound();
}
const { startTime, endTime, eventType, ...restBooking } = _booking;
const booking = {
...restBooking,
startTime: startTime.toString(),
endTime: endTime.toString(),
};
if (!eventType) {
return notFound();
}
if (eventType.users.length === 0 && !!!eventType.team) {
return notFound();
}
const [user] = eventType?.users.length
? eventType.users
: [{ name: null, theme: null, hideBranding: null, username: null }];
const profile = {
name: eventType.team?.name || user?.name || null,
theme: (!eventType.team?.name && user?.theme) || null,
hideBranding: eventType.team?.hideBranding || user?.hideBranding || null,
};
if (
([BookingStatus.CANCELLED, BookingStatus.REJECTED] as BookingStatus[]).includes(
booking.status as BookingStatus
)
) {
return redirect(`/booking/${booking.uid}`);
}
return {
user,
eventType: {
...eventType,
metadata: EventTypeMetaDataSchema.parse(eventType.metadata),
},
booking,
dehydratedState: ssr.dehydrate(),
payment,
clientSecret: getClientSecretFromPayment(payment),
profile,
};
}
const getData = withAppDirSsr<PaymentPageProps>(getServerSideProps);
export default WithLayout({ getLayout: null, getData, Page: PaymentPage });
@@ -1,4 +1,4 @@
import OldPage, { getServerSideProps as _getServerSideProps } from "@pages/reschedule/[uid]";
import { getServerSideProps } from "@pages/reschedule/[uid]";
import { withAppDirSsr } from "app/WithAppDirSsr";
import type { SearchParams } from "app/_types";
import { _generateMetadata } from "app/_utils";
@@ -18,14 +18,14 @@ type PageProps = Readonly<{
searchParams: SearchParams;
}>;
const getData = withAppDirSsr(_getServerSideProps);
const getData = withAppDirSsr(getServerSideProps);
const Page = async ({ params, searchParams }: PageProps) => {
const legacyCtx = buildLegacyCtx(headers(), cookies(), params, searchParams);
await getData(legacyCtx);
return <OldPage />;
return null;
};
export default Page;
@@ -1,36 +1,32 @@
import { getServerCaller } from "app/_trpc/serverClient";
import { type Params } from "app/_types";
import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { WithLayout } from "app/layoutHOC";
import { z } from "zod";
import Page from "@calcom/features/ee/users/pages/users-edit-view";
import prisma from "@calcom/prisma";
import { getLayout } from "@calcom/features/settings/layouts/SettingsLayoutAppDir";
const userIdSchema = z.object({ id: z.coerce.number() });
export const generateMetadata = async ({ params }: { params: Params }) => {
const input = userIdSchema.safeParse(params);
let title = "";
if (!input.success) {
title = "Editing user";
} else {
const req = {
headers: headers(),
cookies: cookies(),
};
// @ts-expect-error Type '{ headers: ReadonlyHeaders; cookies: ReadonlyRequestCookies; }' is not assignable to type 'NextApiRequest'
const data = await getServerCaller({ req, prisma }).viewer.users.get({ userId: input.data.id });
const { user } = data;
title = `Editing user: ${user.username}`;
return await _generateMetadata(
() => "",
() => "Here you can edit a current user."
);
}
const userId = input.data.id;
const { trpc } = await import("@calcom/trpc");
const [data] = trpc.viewer.users.get.useSuspenseQuery({ userId });
const { user } = data;
const title = `Editing user: ${user.username}`;
return await _generateMetadata(
() => title,
() => "Here you can edit a current user."
);
};
export default Page;
export default WithLayout({ getLayout, Page })<"P">;
@@ -1,6 +1,8 @@
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import Page from "@calcom/features/ee/users/pages/users-add-view";
import { getLayout } from "@calcom/features/settings/layouts/SettingsLayoutAppDir";
export const generateMetadata = async () =>
await _generateMetadata(
@@ -8,4 +10,4 @@ export const generateMetadata = async () =>
() => "Here you can add a new user."
);
export default Page;
export default WithLayout({ getLayout, Page })<"P">;
@@ -1,5 +0,0 @@
import { WithLayout } from "app/layoutHOC";
import { getLayout } from "@calcom/features/settings/layouts/SettingsLayoutAppDir";
export default WithLayout({ getLayout })<"L">;
@@ -1,6 +1,8 @@
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import Page from "@calcom/features/ee/users/pages/users-listing-view";
import { getLayout } from "@calcom/features/settings/layouts/SettingsLayoutAppDir";
export const generateMetadata = async () =>
await _generateMetadata(
@@ -8,4 +10,4 @@ export const generateMetadata = async () =>
() => "A list of all the users in your account including their name, title, email and role."
);
export default Page;
export default WithLayout({ getLayout, Page })<"P">;
@@ -1,10 +1,9 @@
import LegacyPage, { WrappedCreateNewOrganizationPage } from "@pages/settings/organizations/new/index";
import LegacyPage, { getServerSideProps, LayoutWrapperAppDir } from "@pages/settings/organizations/new/index";
import { withAppDirSsr } from "app/WithAppDirSsr";
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import { type GetServerSidePropsContext } from "next";
import { notFound } from "next/navigation";
import { getFeatureFlagMap } from "@calcom/features/flags/server/utils";
import { type inferSSRProps } from "@lib/types/inferSSRProps";
export const generateMetadata = async () =>
await _generateMetadata(
@@ -12,23 +11,8 @@ export const generateMetadata = async () =>
(t) => t("organizations_description")
);
const getPageProps = async (context: GetServerSidePropsContext) => {
const prisma = await import("@calcom/prisma").then((mod) => mod.default);
const flags = await getFeatureFlagMap(prisma);
// Check if organizations are enabled
if (flags["organizations"] !== true) {
return notFound();
}
const querySlug = context.query.slug as string;
return {
querySlug: querySlug ?? null,
};
};
export default WithLayout({
getLayout: WrappedCreateNewOrganizationPage,
getLayout: LayoutWrapperAppDir,
Page: LegacyPage,
getData: getPageProps,
getData: withAppDirSsr<inferSSRProps<typeof getServerSideProps>>(getServerSideProps),
});
@@ -1,18 +1,12 @@
import LegacyPage, { getStaticProps } from "@pages/workflows/[workflow]";
import { withAppDirSsg } from "app/WithAppDirSsg";
import { _generateMetadata } from "app/_utils";
import { WithLayout } from "app/layoutHOC";
import { type GetServerSidePropsContext } from "next";
import { headers, cookies } from "next/headers";
import { notFound } from "next/navigation";
import { z } from "zod";
import LegacyPage from "@calcom/features/ee/workflows/pages/workflow";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
const querySchema = z.object({
workflow: z.string(),
});
export const generateMetadata = async ({
params,
searchParams,
@@ -20,7 +14,7 @@ export const generateMetadata = async ({
params: Record<string, string | string[]>;
searchParams: { [key: string]: string | string[] | undefined };
}) => {
const { workflow } = await getProps(
const { workflow } = await getData(
buildLegacyCtx(headers(), cookies(), params, searchParams) as unknown as GetServerSidePropsContext
);
return await _generateMetadata(
@@ -29,19 +23,12 @@ export const generateMetadata = async ({
);
};
async function getProps(context: GetServerSidePropsContext) {
const safeParams = querySchema.safeParse(context.params);
console.log("Built workflow page:", safeParams);
if (!safeParams.success) {
return notFound();
}
return { workflow: safeParams.data.workflow };
}
const getData = withAppDirSsg(getStaticProps);
export const generateStaticParams = () => [];
export default WithLayout({ getLayout: null, getData: getProps, Page: LegacyPage })<"P">;
// @ts-expect-error TODO: fix this
export default WithLayout({ getLayout: null, getData, Page: LegacyPage })<"P">;
export const dynamic = "force-static";
// generate segments on demand
export const dynamicParams = true;
@@ -0,0 +1,15 @@
import { getFeatureFlagMap } from "@calcom/features/flags/server/utils";
// If feature flag is disabled, return not found on getServerSideProps
export const getServerSideProps = async () => {
const prisma = await import("@calcom/prisma").then((mod) => mod.default);
const flags = await getFeatureFlagMap(prisma);
if (flags.insights === false) {
return {
notFound: true,
} as const;
}
return { props: {} };
};
@@ -0,0 +1,22 @@
import type { GetServerSidePropsContext } from "next";
import { getFeatureFlagMap } from "@calcom/features/flags/server/utils";
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
const prisma = await import("@calcom/prisma").then((mod) => mod.default);
const flags = await getFeatureFlagMap(prisma);
// Check if organizations are enabled
if (flags["organizations"] !== true) {
return {
notFound: true,
} as const;
}
const querySlug = context.query.slug as string;
return {
props: {
querySlug: querySlug ?? null,
},
};
};
@@ -0,0 +1,19 @@
import type { GetStaticProps } from "next";
import { z } from "zod";
const querySchema = z.object({
workflow: z.string(),
});
export const getStaticProps: GetStaticProps = (ctx) => {
const params = querySchema.safeParse(ctx.params);
console.log("Built workflow page:", params);
if (!params.success) return { notFound: true };
return {
props: {
workflow: params.data.workflow,
},
revalidate: 10, // seconds
};
};
@@ -15,7 +15,8 @@ import { getStaticProps } from "@lib/apps/categories/[category]/getStaticProps";
import PageWrapper from "@components/PageWrapper";
export default function Apps({ apps }: InferGetStaticPropsType<typeof 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");
+3 -16
View File
@@ -1,7 +1,6 @@
"use client";
import { getLayout } from "@calcom/features/MainLayout";
import { getFeatureFlagMap } from "@calcom/features/flags/server/utils";
import {
AverageEventDurationChart,
BookingKPICards,
@@ -20,6 +19,8 @@ import { trpc } from "@calcom/trpc";
import { Button, ButtonGroup } from "@calcom/ui";
import { RefreshCcw, UserPlus, Users } from "@calcom/ui/components/icon";
import { getServerSideProps } from "@lib/insights/getServerSideProps";
import PageWrapper from "@components/PageWrapper";
export default function InsightsPage() {
@@ -106,18 +107,4 @@ export default function InsightsPage() {
InsightsPage.PageWrapper = PageWrapper;
InsightsPage.getLayout = getLayout;
// If feature flag is disabled, return not found on getServerSideProps
export const getServerSideProps = async () => {
const prisma = await import("@calcom/prisma").then((mod) => mod.default);
const flags = await getFeatureFlagMap(prisma);
if (flags.insights === false) {
return {
notFound: true,
};
}
return {
props: {},
};
};
export { getServerSideProps };
@@ -1,13 +1,11 @@
"use client";
import type { GetServerSidePropsContext } from "next";
import LicenseRequired from "@calcom/features/ee/common/components/LicenseRequired";
import { CreateANewOrganizationForm } from "@calcom/features/ee/organizations/components";
import { getFeatureFlagMap } from "@calcom/features/flags/server/utils";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { WizardLayout, Meta, WizardLayoutAppDir } from "@calcom/ui";
import { getServerSideProps } from "@lib/settings/organizations/new/getServerSideProps";
import type { inferSSRProps } from "@lib/types/inferSSRProps";
import PageWrapper from "@components/PageWrapper";
@@ -29,7 +27,7 @@ const LayoutWrapper = (page: React.ReactElement) => {
);
};
export const WrappedCreateNewOrganizationPage = (page: React.ReactElement) => {
export const LayoutWrapperAppDir = (page: React.ReactElement) => {
return (
<WizardLayoutAppDir currentStep={1} maxSteps={5}>
{page}
@@ -37,26 +35,9 @@ export const WrappedCreateNewOrganizationPage = (page: React.ReactElement) => {
);
};
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
const prisma = await import("@calcom/prisma").then((mod) => mod.default);
const flags = await getFeatureFlagMap(prisma);
// Check if organizations are enabled
if (flags["organizations"] !== true) {
return {
notFound: true,
};
}
const querySlug = context.query.slug as string;
return {
props: {
querySlug: querySlug ?? null,
},
};
};
CreateNewOrganizationPage.getLayout = LayoutWrapper;
CreateNewOrganizationPage.PageWrapper = PageWrapper;
export default CreateNewOrganizationPage;
export { getServerSideProps };
+6 -19
View File
@@ -1,28 +1,14 @@
import type { GetStaticPaths, GetStaticProps } from "next";
import { z } from "zod";
"use client";
import type { GetStaticPaths } from "next";
import Workflow from "@calcom/features/ee/workflows/pages/workflow";
import { getStaticProps } from "@lib/workflows/[workflow]/getStaticProps";
import PageWrapper from "@components/PageWrapper";
import type { CalPageWrapper } from "@components/PageWrapper";
const querySchema = z.object({
workflow: z.string(),
});
export const getStaticProps: GetStaticProps = (ctx) => {
const params = querySchema.safeParse(ctx.params);
console.log("Built workflow page:", params);
if (!params.success) return { notFound: true };
return {
props: {
workflow: params.data.workflow,
},
revalidate: 10, // seconds
};
};
export const getStaticPaths: GetStaticPaths = () => {
return {
paths: [],
@@ -34,3 +20,4 @@ const WorkflowsPage = Workflow as CalPageWrapper;
WorkflowsPage.PageWrapper = PageWrapper;
export default WorkflowsPage;
export { getStaticProps };
@@ -9,7 +9,7 @@ import type { inferSSRProps } from "@calcom/types/inferSSRProps";
import { ssrInit } from "../../../../../apps/web/server/lib/ssr";
export type PaymentPageProps = Omit<inferSSRProps<typeof getServerSideProps>, "trpcState">;
export type PaymentPageProps = inferSSRProps<typeof getServerSideProps>;
const querySchema = z.object({
uid: z.string(),
@@ -86,7 +86,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
},
});
if (!rawPayment) return { notFound: true };
if (!rawPayment) return { notFound: true } as const;
const { data, booking: _booking, ...restPayment } = rawPayment;
@@ -95,7 +95,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
data: data as Record<string, unknown>,
};
if (!_booking) return { notFound: true };
if (!_booking) return { notFound: true } as const;
const { startTime, endTime, eventType, ...restBooking } = _booking;
const booking = {
@@ -104,9 +104,9 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
endTime: endTime.toString(),
};
if (!eventType) return { notFound: true };
if (!eventType) return { notFound: true } as const;
if (eventType.users.length === 0 && !!!eventType.team) return { notFound: true };
if (eventType.users.length === 0 && !!!eventType.team) return { notFound: true } as const;
const [user] = eventType?.users.length
? eventType.users
@@ -1,5 +1,3 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import type { WorkflowStep } from "@prisma/client";
import { isValidPhoneNumber } from "libphonenumber-js";