feat: new App install flow (#11975)

* feat(appStore): add isOAuth config

* refactor(appStore): EventTypeAppSettngsInterface

* refactor(qr_code): split EventTypeAppCardInterface and EventTypeAppSettingsInterface

* feat(appStore): redirect to onboarding for stripe and basecam

* fix(ui/ScrollableArea): overflow indicator not working

* feat(apps): new install app flow

* fix(configureStep): get disabled props for settings

* fix: getAppInstallsBySlug now use teamIds

* chore: Alby to AppSettingsInterface

* chore: Giphy to appsettings interface

* chore: GTM migration

* chore: GT4 - migration

* chore: fathom migration

* chore: paypal

* feat: basecamp migration

* feat: metapixel migration

* feat:plausable

* feat:stripe

* fix merge issues

* fix merge issues in new app install flow steps

* wip: callback to onboarding

* fix: imports

* fix: more imports

* feat: use redirect to onboarding on install flow

* feat: New app install flow 2 (#14077)

* fix: redirect to event-type after oauth flow

* When clicking on install new app button, only redirect to the new app install flow if it is an oAuth app or an app that extends the EventType feature in it's config

* code refactor, skip event-type step

* removed extra consoles

* so that no one can change the eventTypeId in url

* theme support enabled

* only pass eventTypeId instead of whole evetType obj to OmniInstallAppButton

* fix: clicking on event-type gives error and redirects to /apps

* saved appOnboardingRedirectUrl to OAuth State

* fix: a user having no team breaks the onboarding flow

* add optional chaining to appMetadata.extendsFeature and appMetadata.isOAuth;

* encode appOnboardingRedirectUrl

* fix: dark theme ui issues

* skip configure step if no-event types

if user/team does not have event-type then skip configure step and goto apps/installed/[category]

* exclude calendars from apps- onboarding flow

* Update getAppOnboardingRedirectUrl.ts

* fix: On configure step, inputs aren't showing errors

* change route from `apps/onboarding` to `apps/installation`

* fix: flow not correctly working for teams

* should only allow team ADMIN or OWER to install an app to team

* Prevent two payment apps to be enabled

* removed loading state

* Fix type error

* undo new-app-flow from OmniInstallAppButton

* remove OAuth Step, handle step numbering

* fix: redirect url

* getAppOnboardingRedirectUrl refactor

* for debugging

* Revert "for debugging"

This reverts commit b9362c1a8f47f2280e684c213d7ec08d04a8ac4c.

* fix: added toaster

* feat: added support to select multiple events (almost)

* hide button

* Move inner form outside outer form using portal

Due to limitations with nested forms in React Hook Form, moved the inner form outside the outer form using a portal to ensure proper form handling.

* submit buttons refs madness

* removed configure step

we had to use query params to manage selected event-types, between routes which was causing 2 issues:
* each time we selected or unselected an event the whole page was reloaded including getserversideprops being called again and again
* the form was reloaded causing more issues

* removed extra unwanted code

* small fix

* fix: type error

* fix: types

* implemented suggested changes

* removed step footer
* fixed error.message
* removed commented styles

* removed step footer

* fix: Display team event types instead of user's on event types step when team selected

* fix: typo

* removed shouldLockDisableProps

* refactor setUpdatedEventTypesStatus, fix type

* removed extra code

* can't delete while saving

* added translations

* fix: loading in select account step, fix handle onSelect params type

* Fix typo

---------

Co-authored-by: Joe Au-Yeung <[email protected]>

* fix: type errors

* fix: failing tests

---------

Co-authored-by: sean-brydon <[email protected]>
Co-authored-by: Keith Williams <[email protected]>
Co-authored-by: Joe Au-Yeung <[email protected]>
Co-authored-by: Somay Chauhan <[email protected]>
This commit is contained in:
authored and GitHub committed 2024-04-10 16:24:31 +00:00
1 parent b748b8d077
commit 6d5d2a1c4d
146 files changed
+2151 -698

No files matched your search

+4
View File
@@ -21,6 +21,7 @@ export type AppPageProps = {
isGlobal?: AppType["isGlobal"];
logo: string;
slug: string;
dirName: string | undefined;
variant: string;
body: React.ReactNode;
categories: string[];
@@ -68,6 +69,7 @@ export const AppPage = ({
dependencies,
concurrentMeetings,
paid,
dirName,
}: AppPageProps) => {
const { t, i18n } = useLocale();
const hasDescriptionItems = descriptionItems && descriptionItems.length > 0;
@@ -223,6 +225,7 @@ export const AppPage = ({
multiInstall
concurrentMeetings={concurrentMeetings}
paid={paid}
dirName={dirName}
{...props}
/>
);
@@ -262,6 +265,7 @@ export const AppPage = ({
credentials={appDbQuery.data?.credentials}
concurrentMeetings={concurrentMeetings}
paid={paid}
dirName={dirName}
{...props}
/>
);
@@ -1,7 +1,14 @@
import { useRouter } from "next/navigation";
import { useMemo } from "react";
import useAddAppMutation from "@calcom/app-store/_utils/useAddAppMutation";
import { appStoreMetadata } from "@calcom/app-store/appStoreMetaData";
import { doesAppSupportTeamInstall } from "@calcom/app-store/utils";
import { Spinner } from "@calcom/features/calendars/weeklyview/components/spinner/Spinner";
import type { UserAdminTeams } from "@calcom/features/ee/teams/lib/getUserAdminTeams";
import { AppOnboardingSteps } from "@calcom/lib/apps/appOnboardingSteps";
import { getAppOnboardingUrl } from "@calcom/lib/apps/getAppOnboardingUrl";
import { shouldRedirectToAppOnboarding } from "@calcom/lib/apps/shouldRedirectToAppOnboarding";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
@@ -26,7 +33,9 @@ export const InstallAppButtonChild = ({
multiInstall,
credentials,
concurrentMeetings,
dirName,
paid,
onClick,
...props
}: {
userAdminTeams?: UserAdminTeams;
@@ -36,8 +45,10 @@ export const InstallAppButtonChild = ({
credentials?: RouterOutputs["viewer"]["appCredentialsByType"]["credentials"];
concurrentMeetings?: boolean;
paid?: AppFrontendPayload["paid"];
dirName: string | undefined;
} & ButtonProps) => {
const { t } = useLocale();
const router = useRouter();
const mutation = useAddAppMutation(null, {
onSuccess: (data) => {
@@ -49,6 +60,18 @@ export const InstallAppButtonChild = ({
},
});
const shouldDisableInstallation = !multiInstall ? !!(credentials && credentials.length) : false;
const appMetadata = appStoreMetadata[dirName as keyof typeof appStoreMetadata];
const redirectToAppOnboarding = useMemo(() => shouldRedirectToAppOnboarding(appMetadata), [appMetadata]);
const _onClick = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
if (redirectToAppOnboarding) {
router.push(
getAppOnboardingUrl({ slug: addAppMutationInput.slug, step: AppOnboardingSteps.ACCOUNTS_STEP })
);
} else if (onClick) {
onClick(e);
}
};
// Paid apps don't support team installs at the moment
// Also, cal.ai(the only paid app at the moment) doesn't support team install either
@@ -56,6 +79,7 @@ export const InstallAppButtonChild = ({
return (
<Button
data-testid="install-app-button"
onClick={_onClick}
{...props}
disabled={shouldDisableInstallation}
color="primary"
@@ -72,6 +96,7 @@ export const InstallAppButtonChild = ({
return (
<Button
data-testid="install-app-button"
onClick={_onClick}
{...props}
// @TODO: Overriding color and size prevent us from
// having to duplicate InstallAppButton for now.
@@ -83,6 +108,19 @@ export const InstallAppButtonChild = ({
);
}
if (redirectToAppOnboarding) {
return (
<Button
data-testid="install-app-button"
disabled={shouldDisableInstallation}
onClick={_onClick}
color="primary"
size="base"
{...props}>
{multiInstall ? t("install_another") : t("install_app")}
</Button>
);
}
return (
<Dropdown>
<DropdownMenuTrigger asChild>
@@ -0,0 +1,97 @@
import type { FC } from "react";
import React, { useState } from "react";
import { classNames } from "@calcom/lib";
import { CAL_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { Team, User } from "@calcom/prisma/client";
import { Avatar, StepCard } from "@calcom/ui";
type AccountSelectorProps = {
avatar?: string;
name: string;
alreadyInstalled: boolean;
onClick?: () => void;
loading: boolean;
testId: string;
};
const AccountSelector: FC<AccountSelectorProps> = ({
avatar,
alreadyInstalled,
name,
onClick,
loading,
testId,
}) => {
const { t } = useLocale();
const [selected, setSelected] = useState(false);
return (
<div
className={classNames(
"hover:bg-muted flex cursor-pointer flex-row items-center gap-2 p-1",
(alreadyInstalled || loading) && "cursor-not-allowed",
selected && "bg-muted animate-pulse"
)}
data-testid={testId}
onClick={() => {
if (onClick) {
setSelected(true);
onClick();
}
}}>
<Avatar
alt={avatar || ""}
imageSrc={avatar || `${CAL_URL}/${avatar}`} // if no image, use default avatar
size="sm"
/>
<div className="text-md pt-0.5 font-medium text-gray-500">
{name}
{alreadyInstalled ? <span className="ml-1 text-sm text-gray-400">{t("already_installed")}</span> : ""}
</div>
</div>
);
};
export type PersonalAccountProps = Pick<User, "id" | "avatar" | "name"> & { alreadyInstalled: boolean };
export type TeamsProp = (Pick<Team, "id" | "name" | "logo"> & {
alreadyInstalled: boolean;
})[];
type AccountStepCardProps = {
teams: TeamsProp;
personalAccount: PersonalAccountProps;
onSelect: (id?: number) => void;
loading: boolean;
};
export const AccountsStepCard: FC<AccountStepCardProps> = ({ teams, personalAccount, onSelect, loading }) => {
const { t } = useLocale();
return (
<StepCard>
<div className="text-sm font-medium text-gray-400">{t("install_app_on")}</div>
<div className={classNames("mt-2 flex flex-col gap-2 ")}>
<AccountSelector
testId="install-app-on-personal-account"
avatar={personalAccount.avatar ?? ""}
name={personalAccount.name ?? ""}
alreadyInstalled={personalAccount.alreadyInstalled}
onClick={() => !personalAccount.alreadyInstalled && !loading && onSelect()}
loading={loading}
/>
{teams.map((team) => (
<AccountSelector
key={team.id}
testId={`install-app-on-team-${team.id}`}
alreadyInstalled={team.alreadyInstalled}
avatar={team.logo ?? ""}
name={team.name}
onClick={() => !team.alreadyInstalled && !loading && onSelect(team.id)}
loading={loading}
/>
))}
</div>
</StepCard>
);
};
@@ -0,0 +1,206 @@
import type { TEventType, TEventTypesForm } from "@pages/apps/installation/[[...step]]";
import { X } from "lucide-react";
import type { Dispatch, SetStateAction } from "react";
import type { FC } from "react";
import React, { forwardRef, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useFieldArray, useFormContext } from "react-hook-form";
import { useForm } from "react-hook-form";
import type { z } from "zod";
import { EventTypeAppSettings } from "@calcom/app-store/_components/EventTypeAppSettingsInterface";
import type { EventTypeAppsList } from "@calcom/app-store/utils";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AppCategories } from "@calcom/prisma/enums";
import type { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { Button, Form } from "@calcom/ui";
import useAppsData from "@lib/hooks/useAppsData";
type TFormType = {
metadata: z.infer<typeof EventTypeMetaDataSchema>;
};
type ConfigureStepCardProps = {
slug: string;
userName: string;
categories: AppCategories[];
credentialId?: number;
loading?: boolean;
formPortalRef: React.RefObject<HTMLDivElement>;
eventTypes: TEventType[] | undefined;
setConfigureStep: Dispatch<SetStateAction<boolean>>;
};
type EventTypeAppSettingsFormProps = Pick<
ConfigureStepCardProps,
"slug" | "userName" | "categories" | "credentialId" | "loading"
> & {
eventType: TEventType;
handleDelete: () => void;
onSubmit: (values: z.infer<typeof EventTypeMetaDataSchema>) => void;
};
type EventTypeAppSettingsWrapperProps = Pick<
ConfigureStepCardProps,
"slug" | "userName" | "categories" | "credentialId"
> & {
eventType: TEventType;
};
const EventTypeAppSettingsWrapper: FC<EventTypeAppSettingsWrapperProps> = ({
slug,
eventType,
categories,
credentialId,
}) => {
const { getAppDataGetter, getAppDataSetter } = useAppsData();
useEffect(() => {
const appDataSetter = getAppDataSetter(slug as EventTypeAppsList, categories, credentialId);
appDataSetter("enabled", true);
}, []);
return (
<EventTypeAppSettings
slug={slug}
eventType={eventType}
getAppData={getAppDataGetter(slug as EventTypeAppsList)}
setAppData={getAppDataSetter(slug as EventTypeAppsList, categories, credentialId)}
/>
);
};
const EventTypeAppSettingsForm = forwardRef<HTMLButtonElement, EventTypeAppSettingsFormProps>(
function EventTypeAppSettingsForm(props, ref) {
const { handleDelete, onSubmit, eventType, loading } = props;
const formMethods = useForm<TFormType>({
defaultValues: {
metadata: eventType?.metadata,
},
});
return (
<Form
form={formMethods}
id={`eventtype-${eventType.id}`}
handleSubmit={() => {
const data = formMethods.getValues("metadata");
onSubmit(data);
}}>
<div>
<div className="sm:border-subtle bg-default relative border p-4 dark:bg-black sm:rounded-md">
<div>
<span className="text-default font-semibold ltr:mr-1 rtl:ml-1">{eventType.title}</span>{" "}
<small className="text-subtle hidden font-normal sm:inline">
/{eventType.team ? eventType.team.slug : props.userName}/{eventType.slug}
</small>
</div>
<EventTypeAppSettingsWrapper {...props} />
<X
className="absolute right-4 top-4 h-4 w-4 cursor-pointer"
onClick={() => !loading && handleDelete()}
/>
<button type="submit" className="hidden" ref={ref}>
Save
</button>
</div>
</div>
</Form>
);
}
);
export const ConfigureStepCard: FC<ConfigureStepCardProps> = ({
loading,
formPortalRef,
eventTypes,
setConfigureStep,
...props
}) => {
const { t } = useLocale();
const { control, getValues } = useFormContext<TEventTypesForm>();
const { fields, update } = useFieldArray({
control,
name: "eventTypes",
keyName: "fieldId",
});
const submitRefs = useRef<Array<React.RefObject<HTMLButtonElement>>>([]);
submitRefs.current = fields.map(
(_ref, index) => (submitRefs.current[index] = React.createRef<HTMLButtonElement>())
);
const mainForSubmitRef = useRef<HTMLButtonElement>(null);
const [updatedEventTypesStatus, setUpdatedEventTypesStatus] = useState(
fields.filter((field) => field.selected).map((field) => ({ id: field.id, updated: false }))
);
const [submit, setSubmit] = useState(false);
const allUpdated = updatedEventTypesStatus.every((item) => item.updated);
useEffect(() => {
setUpdatedEventTypesStatus((prev) =>
prev.filter((state) => fields.some((field) => field.id === state.id && field.selected))
);
if (!fields.some((field) => field.selected)) {
setConfigureStep(false);
}
}, [fields]);
useEffect(() => {
if (submit && allUpdated && mainForSubmitRef.current) {
mainForSubmitRef.current?.click();
setSubmit(false);
}
}, [submit, allUpdated, getValues, mainForSubmitRef]);
return (
formPortalRef?.current &&
createPortal(
<div className="mt-8">
<div className="flex flex-col space-y-6">
{fields.map((field, index) => {
return (
field.selected && (
<EventTypeAppSettingsForm
key={field.fieldId}
eventType={field}
loading={loading}
handleDelete={() => {
const eventMetadataDb = eventTypes?.find(
(eventType) => eventType.id == field.id
)?.metadata;
update(index, { ...field, selected: false, metadata: eventMetadataDb });
}}
onSubmit={(data) => {
update(index, { ...field, metadata: data });
setUpdatedEventTypesStatus((prev) =>
prev.map((item) => (item.id === field.id ? { ...item, updated: true } : item))
);
}}
ref={submitRefs.current[index]}
{...props}
/>
)
);
})}
</div>
<button form="outer-event-type-form" type="submit" className="hidden" ref={mainForSubmitRef}>
Save
</button>
<Button
className="text-md mt-6 w-full justify-center"
type="button"
onClick={() => {
submitRefs.current.reverse().map((ref) => ref.current?.click());
setSubmit(true);
}}
loading={loading}>
{t("save")}
</Button>
</div>,
formPortalRef?.current
)
);
};
@@ -0,0 +1,110 @@
import type { TEventType, TEventTypesForm } from "@pages/apps/installation/[[...step]]";
import type { Dispatch, SetStateAction } from "react";
import type { FC } from "react";
import React from "react";
import { useFieldArray, useFormContext } from "react-hook-form";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { EventTypeMetaDataSchema } from "@calcom/prisma/zod-utils";
import { ScrollableArea, Badge, Button } from "@calcom/ui";
type EventTypesCardProps = {
userName: string;
setConfigureStep: Dispatch<SetStateAction<boolean>>;
};
export const EventTypesStepCard: FC<EventTypesCardProps> = ({ setConfigureStep, userName }) => {
const { t } = useLocale();
const { control } = useFormContext<TEventTypesForm>();
const { fields, update } = useFieldArray({
control,
name: "eventTypes",
keyName: "fieldId",
});
return (
<>
<div className="sm:border-subtle bg-default mt-10 border dark:bg-black sm:rounded-md">
<ScrollableArea className="rounded-md">
<ul className="border-subtle max-h-97 !static w-full divide-y">
{fields.map((field, index) => (
<EventTypeCard
handleSelect={() => update(index, { ...field, selected: !field.selected })}
userName={userName}
key={field.fieldId}
{...field}
/>
))}
</ul>
</ScrollableArea>
</div>
<Button
className="text-md mt-6 w-full justify-center"
onClick={() => {
setConfigureStep(true);
}}
disabled={!fields.some((field) => field.selected === true)}>
{t("save")}
</Button>
</>
);
};
type EventTypeCardProps = TEventType & { userName: string; handleSelect: () => void };
const EventTypeCard: FC<EventTypeCardProps> = ({
title,
description,
id,
metadata,
length,
selected,
slug,
handleSelect,
team,
userName,
}) => {
const parsedMetaData = EventTypeMetaDataSchema.safeParse(metadata);
const durations =
parsedMetaData.success &&
parsedMetaData.data?.multipleDuration &&
Boolean(parsedMetaData.data?.multipleDuration.length)
? [length, ...parsedMetaData.data?.multipleDuration?.filter((duration) => duration !== length)].sort()
: [length];
return (
<div
className="hover:bg-muted min-h-20 box-border flex w-full cursor-pointer select-none items-center space-x-4 px-4 py-3"
onClick={() => handleSelect()}>
<input
id={`${id}`}
checked={selected}
className="bg-default border-default h-4 w-4 shrink-0 cursor-pointer rounded-[4px] border ring-offset-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed"
type="checkbox"
/>
<label htmlFor={`${id}`} className="cursor-pointer text-sm">
<li>
<div>
<span className="text-default font-semibold ltr:mr-1 rtl:ml-1">{title}</span>{" "}
<small className="text-subtle hidden font-normal sm:inline">
/{team ? team.slug : userName}/{slug}
</small>
</div>
{Boolean(description) && (
<div className="text-subtle line-clamp-4 break-words text-sm sm:max-w-[650px] [&>*:not(:first-child)]:hidden [&_a]:text-blue-500 [&_a]:underline [&_a]:hover:text-blue-600">
{description}
</div>
)}
<div className="mt-2 flex flex-row flex-wrap gap-2">
{Boolean(durations.length) &&
durations.map((duration) => (
<Badge key={`event-type-${id}-duration-${duration}`} variant="gray" startIcon="clock">
{duration}m
</Badge>
))}
</div>
</li>
</label>
</div>
);
};
@@ -0,0 +1,19 @@
import type { FC, ReactNode } from "react";
type StepHeaderProps = {
children?: ReactNode;
title: string;
subtitle: string;
};
export const StepHeader: FC<StepHeaderProps> = ({ children, title, subtitle }) => {
return (
<div>
<header>
<p className="font-cal mb-3 text-[28px] font-medium capitalize leading-7">{title}</p>
<p className="text-subtle font-sans text-sm font-normal">{subtitle}</p>
</header>
{children}
</div>
);
};
+3 -45
View File
@@ -3,7 +3,6 @@ import Link from "next/link";
import type { EventTypeSetupProps } from "pages/event-types/[type]";
import { useFormContext } from "react-hook-form";
import type { GetAppData, SetAppData } from "@calcom/app-store/EventTypeAppContext";
import { EventTypeAppCard } from "@calcom/app-store/_components/EventTypeAppCardInterface";
import type { EventTypeAppCardComponentProps } from "@calcom/app-store/types";
import type { EventTypeAppsList } from "@calcom/app-store/utils";
@@ -13,6 +12,8 @@ import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Alert, Button, EmptyScreen } from "@calcom/ui";
import useAppsData from "@lib/hooks/useAppsData";
export type EventType = Pick<EventTypeSetupProps, "eventType">["eventType"] &
EventTypeAppCardComponentProps["eventType"];
@@ -28,51 +29,8 @@ export const EventAppsTab = ({ eventType }: { eventType: EventType }) => {
eventTypeApps?.items.filter((app) => app.userCredentialIds.length || app.teams.length) || [];
const notInstalledApps =
eventTypeApps?.items.filter((app) => !app.userCredentialIds.length && !app.teams.length) || [];
const allAppsData = formMethods.watch("metadata")?.apps || {};
const setAllAppsData = (_allAppsData: typeof allAppsData) => {
formMethods.setValue(
"metadata",
{
...formMethods.getValues("metadata"),
apps: _allAppsData,
},
{ shouldDirty: true }
);
};
const getAppDataGetter = (appId: EventTypeAppsList): GetAppData => {
return function (key) {
const appData = allAppsData[appId as keyof typeof allAppsData] || {};
if (key) {
return appData[key as keyof typeof appData];
}
return appData;
};
};
const eventTypeFormMetadata = formMethods.getValues("metadata");
const getAppDataSetter = (
appId: EventTypeAppsList,
appCategories: string[],
credentialId?: number
): SetAppData => {
return function (key, value) {
// Always get latest data available in Form because consequent calls to setData would update the Form but not allAppsData(it would update during next render)
const allAppsDataFromForm = formMethods.getValues("metadata")?.apps || {};
const appData = allAppsDataFromForm[appId];
setAllAppsData({
...allAppsDataFromForm,
[appId]: {
...appData,
[key]: value,
credentialId,
appCategories,
},
});
};
};
const { getAppDataGetter, getAppDataSetter, eventTypeFormMetadata } = useAppsData();
const { shouldLockDisableProps, isManagedEventType, isChildrenManagedEventType } = useLockedFieldsManager({
eventType,