feat: app install flow followup (#15193)

Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Omar López <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-07-08 19:15:57 +02:00
1 parent 7d8cb7d6bb
commit f1b4d7d9e0
57 files changed
+1471 -1224

No files matched your search

+1 -3
View File
@@ -1,7 +1,6 @@
import type { NextApiRequest, NextApiResponse } from "next";
import type { Session } from "next-auth";
import getInstalledAppPath from "@calcom/app-store/_utils/getInstalledAppPath";
import { throwIfNotHaveAdminAccessToTeam } from "@calcom/app-store/_utils/throwIfNotHaveAdminAccessToTeam";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { deriveAppDictKeyFromType } from "@calcom/lib/deriveAppDictKeyFromType";
@@ -62,7 +61,6 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const handlers = await handlerMap[handlerKey as keyof typeof handlerMap];
if (!handlers) throw new HttpError({ statusCode: 404, message: `No handlers found for ${handlerKey}` });
const handler = handlers[apiEndpoint as keyof typeof handlers] as AppHandler;
let redirectUrl = "/apps/installed";
if (typeof handler === "undefined")
throw new HttpError({ statusCode: 404, message: `API handler not found` });
@@ -70,7 +68,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
await handler(req, res);
} else {
await defaultIntegrationAddHandler({ user: req.session?.user, teamId: Number(teamId), ...handler });
redirectUrl = handler.redirect?.url || getInstalledAppPath(handler);
const redirectUrl = handler.redirect?.url ?? undefined;
res.json({ url: redirectUrl, newTab: handler.redirect?.newTab });
}
if (!res.writableEnded) return res.status(200);
-1
View File
@@ -53,7 +53,6 @@ function SingleAppPage(props: inferSSRProps<typeof getStaticProps>) {
slug={data.slug}
variant={data.variant}
type={data.type}
dirName={data.dirName}
logo={data.logo}
categories={data.categories ?? [data.category]}
author={data.publisher}
+124 -56
View File
@@ -8,17 +8,22 @@ import { Toaster } from "react-hot-toast";
import { z } from "zod";
import checkForMultiplePaymentApps from "@calcom/app-store/_utils/payments/checkForMultiplePaymentApps";
import useAddAppMutation from "@calcom/app-store/_utils/useAddAppMutation";
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import type { EventTypeAppSettingsComponentProps, EventTypeModel } from "@calcom/app-store/types";
import { isConferencing as isConferencingApp } from "@calcom/app-store/utils";
import type { LocationObject } from "@calcom/core/location";
import { getLocale } from "@calcom/features/auth/lib/getLocale";
import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import type { LocationFormValues } from "@calcom/features/eventtypes/lib/types";
import { AppOnboardingSteps } from "@calcom/lib/apps/appOnboardingSteps";
import { getAppOnboardingRedirectUrl } from "@calcom/lib/apps/getAppOnboardingRedirectUrl";
import { getAppOnboardingUrl } from "@calcom/lib/apps/getAppOnboardingUrl";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { CAL_URL } from "@calcom/lib/constants";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import prisma from "@calcom/prisma";
import { 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";
@@ -34,8 +39,13 @@ import { EventTypesStepCard } from "@components/apps/installation/EventTypesStep
import { StepHeader } from "@components/apps/installation/StepHeader";
export type TEventType = EventTypeAppSettingsComponentProps["eventType"] &
Pick<EventTypeModel, "metadata" | "schedulingType" | "slug" | "requiresConfirmation" | "position"> & {
Pick<
EventTypeModel,
"metadata" | "schedulingType" | "slug" | "requiresConfirmation" | "position" | "destinationCalendar"
> & {
selected: boolean;
locations: LocationFormValues["locations"];
bookingFields?: LocationFormValues["bookingFields"];
};
export type TEventTypesForm = {
@@ -47,7 +57,6 @@ const STEPS = [
AppOnboardingSteps.EVENT_TYPES_STEP,
AppOnboardingSteps.CONFIGURE_STEP,
] as const;
const MAX_NUMBER_OF_STEPS = STEPS.length;
type StepType = (typeof STEPS)[number];
@@ -63,11 +72,21 @@ type StepObj = Record<
type OnboardingPageProps = {
appMetadata: AppMeta;
step: StepType;
teams: TeamsProp;
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 = ({
@@ -78,6 +97,9 @@ const OnboardingPage = ({
eventTypes,
userName,
credentialId,
showEventTypesStep,
isConferencing,
installableOnTeams,
}: OnboardingPageProps) => {
const { t } = useLocale();
const pathname = usePathname();
@@ -92,16 +114,15 @@ const OnboardingPage = ({
[AppOnboardingSteps.EVENT_TYPES_STEP]: {
getTitle: () => `${t("select_event_types_header")}`,
getDescription: (appName) => `${t("select_event_types_description", { appName })}`,
stepNumber: 2,
stepNumber: installableOnTeams ? 2 : 1,
},
[AppOnboardingSteps.CONFIGURE_STEP]: {
getTitle: (appName) => `${t("configure_app_header", { appName })}`,
getDescription: () => `${t("configure_app_description")}`,
stepNumber: 3,
stepNumber: installableOnTeams ? 3 : 2,
},
} as const;
const [configureStep, setConfigureStep] = useState(false);
const [isSelectingAccount, setIsSelectingAccount] = useState(false);
const currentStep: AppOnboardingSteps = useMemo(() => {
if (step == AppOnboardingSteps.EVENT_TYPES_STEP && configureStep) {
@@ -111,6 +132,13 @@ const OnboardingPage = ({
}, [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);
@@ -120,9 +148,19 @@ const OnboardingPage = ({
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({
@@ -156,47 +194,22 @@ const OnboardingPage = ({
});
const handleSelectAccount = async (teamId?: number) => {
try {
setIsSelectingAccount(true);
if (appMetadata.isOAuth) {
const state = JSON.stringify({
appOnboardingRedirectUrl: getAppOnboardingRedirectUrl(appMetadata.slug, teamId),
teamId,
});
const res = await fetch(
`/api/integrations/${
appMetadata.slug == "stripe" ? "stripepayment" : appMetadata.slug
}/add?state=${state}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
);
const oAuthUrl = (await res.json())?.url;
router.push(oAuthUrl);
return;
} else {
await fetch(`/api/integrations/${appMetadata.slug}/add${teamId ? `?teamId=${teamId}` : ""}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
router.push(
mutation.mutate({
type: appMetadata.type,
variant: appMetadata.variant,
slug: appMetadata.slug,
...(teamId && { teamId }),
// for oAuth apps
...(showEventTypesStep && {
returnTo:
WEBAPP_URL +
getAppOnboardingUrl({
slug: appMetadata.slug,
step: AppOnboardingSteps.EVENT_TYPES_STEP,
teamId,
})
);
}
} catch (error) {
setIsSelectingAccount(false);
router.push(`/apps`);
}
step: AppOnboardingSteps.EVENT_TYPES_STEP,
}),
}),
});
};
const handleSetUpLater = () => {
@@ -233,10 +246,21 @@ const OnboardingPage = ({
if (value.metadata?.apps?.stripe?.paymentOption === "HOLD" && value.seatsPerTimeSlot) {
throw new Error(t("seats_and_no_show_fee_error"));
}
return updateMutation.mutateAsync({
id: value.id,
metadata: value.metadata,
});
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);
@@ -248,14 +272,15 @@ const OnboardingPage = ({
<StepHeader
title={stepObj.getTitle(appMetadata.name)}
subtitle={stepObj.getDescription(appMetadata.name)}>
<Steps maxSteps={MAX_NUMBER_OF_STEPS} currentStep={stepObj.stepNumber} disableNavigation />
<Steps maxSteps={maxSteps} currentStep={stepObj.stepNumber} disableNavigation />
</StepHeader>
{currentStep === AppOnboardingSteps.ACCOUNTS_STEP && (
<AccountsStepCard
teams={teams}
personalAccount={personalAccount}
onSelect={handleSelectAccount}
loading={isSelectingAccount}
loading={mutation.isPending}
installableOnTeams={installableOnTeams}
/>
)}
{currentStep === AppOnboardingSteps.EVENT_TYPES_STEP &&
@@ -278,6 +303,7 @@ const OnboardingPage = ({
setConfigureStep={setConfigureStep}
eventTypes={eventTypes}
handleSetUpLater={handleSetUpLater}
isConferencing={isConferencing}
/>
)}
</Form>
@@ -385,19 +411,31 @@ const getEventTypes = async (userId: number, teamId?: number) => {
users: { select: { username: true } },
seatsPerTimeSlot: true,
slug: true,
locations: true,
userId: true,
destinationCalendar: true,
bookingFields: true,
},
where: teamId ? { teamId } : { userId, teamId: null },
/**
* filter out managed events for now
* @todo: can install apps to managed event types
*/
where: teamId ? { teamId } : { userId, parent: null, teamId: null },
})
).sort((eventTypeA, eventTypeB) => {
return eventTypeB.position - eventTypeA.position;
});
if (eventTypes.length === 0) {
return [];
}
return eventTypes.map((item) => ({
...item,
URL: `${CAL_URL}/${item.team ? `team/${item.team.slug}` : item?.users?.[0]?.username}/${item.slug}`,
selected: false,
locations: item.locations as unknown as LocationObject[],
bookingFields: eventTypeBookingFields.parse(item.bookingFields || []),
}));
};
@@ -434,12 +472,13 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
const locale = await getLocale(context.req);
const app = await getAppBySlug(parsedAppSlug);
const appMetadata = appStoreMetadata[app.dirName as keyof typeof appStoreMetadata];
const hasEventTypes = appMetadata?.extendsFeature === "EventType";
const extendsEventType = appMetadata?.extendsFeature === "EventType";
const isConferencing = isConferencingApp(appMetadata.categories);
const showEventTypesStep = extendsEventType || isConferencing;
console.log("sshowEventTypesStephowEventTypesStep: ", showEventTypesStep);
if (!session?.user?.id) throw new Error(ERROR_MESSAGES.userNotAuthed);
if (!hasEventTypes) {
throw new Error(ERROR_MESSAGES.appNotExtendsEventType);
}
const user = await getUser(session.user.id);
@@ -460,7 +499,31 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
}
if (parsedStepParam == AppOnboardingSteps.EVENT_TYPES_STEP) {
if (!showEventTypesStep) {
return {
redirect: {
permanent: false,
destination: `/apps/installed/${appMetadata.categories[0]}?hl=${appMetadata.slug}`,
},
};
}
eventTypes = await getEventTypes(user.id, parsedTeamIdParam);
if (isConferencing) {
const destinationCalendar = await prisma.destinationCalendar.findFirst({
where: {
userId: user.id,
eventTypeId: null,
},
});
for (let index = 0; index < eventTypes.length; index++) {
let eventType = eventTypes[index];
if (!eventType.destinationCalendar) {
eventType = { ...eventType, destinationCalendar };
}
eventTypes[index] = eventType;
}
}
if (eventTypes.length === 0) {
return {
redirect: {
@@ -498,6 +561,7 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
...(await serverSideTranslations(locale, ["common"])),
app,
appMetadata,
showEventTypesStep,
step: parsedStepParam,
teams: teamsWithIsAppInstalled,
personalAccount,
@@ -505,9 +569,13 @@ export const getServerSideProps = async (context: GetServerSidePropsContext) =>
teamId: parsedTeamIdParam ?? null,
userName: user.username,
credentialId,
isConferencing,
// conferencing apps dont support team install
installableOnTeams: !isConferencing,
} as OnboardingPageProps,
};
} catch (err) {
console.log("eerrerrerrerrerrerrerrerrrr: ", err);
if (err instanceof z.ZodError) {
return { redirect: { permanent: false, destination: "/apps" } };
}