Scheduling infrastructure for absolutely everyone.
Fixes Apple Calendar onboarding and type fixes (#988)
Omar López85d7122e43c4
diff --git a/components/integrations/CalendarSwitch.tsx b/components/integrations/CalendarSwitch.tsxnew file mode 100644index 00000000000..9e4330d9b28--- /dev/null+++ b/components/integrations/CalendarSwitch.tsx@@ -0,0 +1,75 @@+import { useMutation } from "react-query";++import showToast from "@lib/notification";+import { trpc } from "@lib/trpc";++import Switch from "@components/ui/Switch";++export default function CalendarSwitch(props: {+ type: string;+ externalId: string;+ title: string;+ defaultSelected: boolean;+}) {+ const utils = trpc.useContext();++ const mutation = useMutation<+ unknown,+ unknown,+ {+ isOn: boolean;+ }+ >(+ async ({ isOn }) => {+ const body = {+ integration: props.type,+ externalId: props.externalId,+ };+ if (isOn) {+ const res = await fetch("/api/availability/calendar", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(body),+ });+ if (!res.ok) {+ throw new Error("Something went wrong");+ }+ } else {+ const res = await fetch("/api/availability/calendar", {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(body),+ });++ if (!res.ok) {+ throw new Error("Something went wrong");+ }+ }+ },+ {+ async onSettled() {+ await utils.invalidateQueries(["viewer.integrations"]);+ },+ onError() {+ showToast(`Something went wrong when toggling "${props.title}""`, "error");+ },+ }+ );+ return (+ <div className="py-1">+ <Switch+ key={props.externalId}+ name="enabled"+ label={props.title}+ defaultChecked={props.defaultSelected}+ onCheckedChange={(isOn: boolean) => {+ mutation.mutate({ isOn });+ }}+ />+ </div>+ );+}diff --git a/components/integrations/CalendarsList.tsx b/components/integrations/CalendarsList.tsxnew file mode 100644index 00000000000..c845dad3f63--- /dev/null+++ b/components/integrations/CalendarsList.tsx@@ -0,0 +1,45 @@+import React, { ReactNode } from "react";++import { List } from "@components/List";+import Button from "@components/ui/Button";++import ConnectIntegration from "./ConnectIntegrations";+import IntegrationListItem from "./IntegrationListItem";++interface Props {+ calendars: {+ children?: ReactNode;+ description: string;+ imageSrc: string;+ title: string;+ type: string;+ }[];+ onChanged: () => void | Promise<void>;+}++const CalendarsList = (props: Props): JSX.Element => {+ const { calendars, onChanged } = props;+ return (+ <List>+ {calendars.map((item) => (+ <IntegrationListItem+ key={item.title}+ {...item}+ actions={+ <ConnectIntegration+ type={item.type}+ render={(btnProps) => (+ <Button color="secondary" {...btnProps}>+ Connect+ </Button>+ )}+ onOpenChange={onChanged}+ />+ }+ />+ ))}+ </List>+ );+};++export default CalendarsList;diff --git a/components/integrations/ConnectIntegrations.tsx b/components/integrations/ConnectIntegrations.tsxnew file mode 100644index 00000000000..40b10d90f72--- /dev/null+++ b/components/integrations/ConnectIntegrations.tsx@@ -0,0 +1,56 @@+import { useState } from "react";+import { useMutation } from "react-query";++import { AddAppleIntegrationModal } from "@lib/integrations/Apple/components/AddAppleIntegration";+import { AddCalDavIntegrationModal } from "@lib/integrations/CalDav/components/AddCalDavIntegration";++import { ButtonBaseProps } from "@components/ui/Button";++export default function ConnectIntegration(props: {+ type: string;+ render: (renderProps: ButtonBaseProps) => JSX.Element;+ onOpenChange: (isOpen: boolean) => void | Promise<void>;+}) {+ const { type } = props;+ const [isLoading, setIsLoading] = useState(false);+ const mutation = useMutation(async () => {+ const res = await fetch("/api/integrations/" + type.replace("_", "") + "/add");+ if (!res.ok) {+ throw new Error("Something went wrong");+ }+ const json = await res.json();+ window.location.href = json.url;+ setIsLoading(true);+ });+ const [isModalOpen, _setIsModalOpen] = useState(false);++ const setIsModalOpen = (v: boolean) => {+ _setIsModalOpen(v);+ props.onOpenChange(v);+ };++ return (+ <>+ {props.render({+ onClick() {+ if (["caldav_calendar", "apple_calendar"].includes(type)) {+ // special handlers+ setIsModalOpen(true);+ return;+ }++ mutation.mutate();+ },+ loading: mutation.isLoading || isLoading,+ disabled: isModalOpen,+ })}+ {type === "caldav_calendar" && (+ <AddCalDavIntegrationModal open={isModalOpen} onOpenChange={setIsModalOpen} />+ )}++ {type === "apple_calendar" && (+ <AddAppleIntegrationModal open={isModalOpen} onOpenChange={setIsModalOpen} />+ )}+ </>+ );+}diff --git a/components/integrations/ConnectedCalendarsList.tsx b/components/integrations/ConnectedCalendarsList.tsxnew file mode 100644index 00000000000..5c1c185a67e--- /dev/null+++ b/components/integrations/ConnectedCalendarsList.tsx@@ -0,0 +1,98 @@+import React, { Fragment, ReactNode } from "react";++import { List } from "@components/List";+import { Alert } from "@components/ui/Alert";+import Button from "@components/ui/Button";++import CalendarSwitch from "./CalendarSwitch";+import DisconnectIntegration from "./DisconnectIntegration";+import IntegrationListItem from "./IntegrationListItem";++type CalIntersection =+ | {+ calendars: {+ externalId: string;+ name: string;+ isSelected: boolean;+ }[];+ error?: never;+ }+ | {+ calendars?: never;+ error: {+ message: string;+ };+ };++type Props = {+ onChanged: (isOpen: boolean) => void | Promise<void>;+ connectedCalendars: (CalIntersection & {+ credentialId: number;+ integration: {+ type: string;+ imageSrc: string;+ title: string;+ children?: ReactNode;+ };+ primary?: { externalId: string } | undefined | null;+ })[];+};++const ConnectedCalendarsList = (props: Props): JSX.Element => {+ const { connectedCalendars, onChanged } = props;+ return (+ <List>+ {connectedCalendars.map((item) => (+ <Fragment key={item.credentialId}>+ {item.calendars ? (+ <IntegrationListItem+ {...item.integration}+ description={item.primary?.externalId || "No external Id"}+ actions={+ <DisconnectIntegration+ id={item.credentialId}+ render={(btnProps) => (+ <Button {...btnProps} color="warn">+ Disconnect+ </Button>+ )}+ onOpenChange={onChanged}+ />+ }>+ <ul className="p-4 space-y-2">+ {item.calendars.map((cal) => (+ <CalendarSwitch+ key={cal.externalId}+ externalId={cal.externalId}+ title={cal.name}+ type={item.integration.type}+ defaultSelected={cal.isSelected}+ />+ ))}+ </ul>+ </IntegrationListItem>+ ) : (+ <Alert+ severity="warning"+ title="Something went wrong"+ message={item.error?.message}+ actions={+ <DisconnectIntegration+ id={item.credentialId}+ render={(btnProps) => (+ <Button {...btnProps} color="warn">+ Disconnect+ </Button>+ )}+ onOpenChange={onChanged}+ />+ }+ />+ )}+ </Fragment>+ ))}+ </List>+ );+};++export default ConnectedCalendarsList;diff --git a/components/integrations/DisconnectIntegration.tsx b/components/integrations/DisconnectIntegration.tsxnew file mode 100644index 00000000000..f656de80a2d--- /dev/null+++ b/components/integrations/DisconnectIntegration.tsx@@ -0,0 +1,60 @@+import { useState } from "react";+import { useMutation } from "react-query";++import { Dialog } from "@components/Dialog";+import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";+import { ButtonBaseProps } from "@components/ui/Button";++export default function DisconnectIntegration(props: {+ /** Integration credential id */+ id: number;+ render: (renderProps: ButtonBaseProps) => JSX.Element;+ onOpenChange: (isOpen: boolean) => void | Promise<void>;+}) {+ const [modalOpen, setModalOpen] = useState(false);+ const mutation = useMutation(+ async () => {+ const res = await fetch("/api/integrations", {+ method: "DELETE",+ body: JSON.stringify({ id: props.id }),+ headers: {+ "Content-Type": "application/json",+ },+ });+ if (!res.ok) {+ throw new Error("Something went wrong");+ }+ },+ {+ async onSettled() {+ props.onOpenChange(modalOpen);+ },+ onSuccess() {+ setModalOpen(false);+ },+ }+ );+ return (+ <>+ <Dialog open={modalOpen} onOpenChange={setModalOpen}>+ <ConfirmationDialogContent+ variety="danger"+ title="Disconnect Integration"+ confirmBtnText="Yes, disconnect integration"+ cancelBtnText="Cancel"+ onConfirm={() => {+ mutation.mutate();+ }}>+ Are you sure you want to disconnect this integration?+ </ConfirmationDialogContent>+ </Dialog>+ {props.render({+ onClick() {+ setModalOpen(true);+ },+ disabled: modalOpen,+ loading: mutation.isLoading,+ })}+ </>+ );+}diff --git a/components/integrations/IntegrationListItem.tsx b/components/integrations/IntegrationListItem.tsxnew file mode 100644index 00000000000..ae11c7b2d56--- /dev/null+++ b/components/integrations/IntegrationListItem.tsx@@ -0,0 +1,30 @@+import Image from "next/image";+import { ReactNode } from "react";++import classNames from "@lib/classNames";++import { ListItem, ListItemText, ListItemTitle } from "@components/List";++function IntegrationListItem(props: {+ imageSrc: string;+ title: string;+ description: string;+ actions?: ReactNode;+ children?: ReactNode;+}): JSX.Element {+ return (+ <ListItem expanded={!!props.children} className={classNames("flex-col")}>+ <div className={classNames("flex flex-1 space-x-2 w-full p-3 items-center")}>+ <Image width={40} height={40} src={`/${props.imageSrc}`} alt={props.title} />+ <div className="flex-grow pl-2 truncate">+ <ListItemTitle component="h3">{props.title}</ListItemTitle>+ <ListItemText component="p">{props.description}</ListItemText>+ </div>+ <div>{props.actions}</div>+ </div>+ {props.children && <div className="w-full border-t border-gray-200">{props.children}</div>}+ </ListItem>+ );+}++export default IntegrationListItem;diff --git a/components/integrations/SubHeadingTitleWithConnections.tsx b/components/integrations/SubHeadingTitleWithConnections.tsxnew file mode 100644index 00000000000..80d120d3015--- /dev/null+++ b/components/integrations/SubHeadingTitleWithConnections.tsx@@ -0,0 +1,29 @@+import { ReactNode } from "react";++import Badge from "@components/ui/Badge";++function pluralize(opts: { num: number; plural: string; singular: string }) {+ if (opts.num === 0) {+ return opts.singular;+ }+ return opts.singular;+}++export default function SubHeadingTitleWithConnections(props: { title: ReactNode; numConnections?: number }) {+ const num = props.numConnections;+ return (+ <>+ <span>{props.title}</span>+ {num ? (+ <Badge variant="success">+ {num}{" "}+ {pluralize({+ num,+ singular: "connection",+ plural: "connections",+ })}+ </Badge>+ ) : null}+ </>+ );+}diff --git a/components/ui/UsernameInput.tsx b/components/ui/UsernameInput.tsxindex fa458e03f44..cd3b615f0dd 100644--- a/components/ui/UsernameInput.tsx+++ b/components/ui/UsernameInput.tsx@@ -1,6 +1,10 @@import React from "react";-const UsernameInput = React.forwardRef((props, ref) => (+interface UsernameInputProps extends React.ComponentPropsWithRef<"input"> {+ label?: string;+}++const UsernameInput = React.forwardRef<HTMLInputElement, UsernameInputProps>((props, ref) => (// todo, check if username is already taken here?<div><label htmlFor="username" className="block text-sm font-medium text-gray-700">diff --git a/components/ui/WeekdaySelect.tsx b/components/ui/WeekdaySelect.tsxindex 24ee655ef7c..83fdddfca21 100644--- a/components/ui/WeekdaySelect.tsx+++ b/components/ui/WeekdaySelect.tsx@@ -1,8 +1,13 @@import React, { useEffect, useState } from "react";-export const WeekdaySelect = (props) => {- const [activeDays, setActiveDays] = useState(- [...Array(7).keys()].map((v, i) => (props.defaultValue || []).includes(i))+interface WeekdaySelectProps {+ defaultValue: number[];+ onSelect: (selected: number[]) => void;+}++export const WeekdaySelect = (props: WeekdaySelectProps) => {+ const [activeDays, setActiveDays] = useState<boolean[]>(+ Array.from(Array(7).keys()).map((v, i) => (props.defaultValue || []).includes(i)));const days = ["S", "M", "T", "W", "T", "F", "S"];@@ -11,10 +16,9 @@ export const WeekdaySelect = (props) => {props.onSelect(activeDays.map((v, idx) => (v ? idx : -1)).filter((v) => v !== -1));}, [activeDays]);- const toggleDay = (e, idx: number) => {- e.preventDefault();+ const toggleDay = (idx: number) => {activeDays[idx] = !activeDays[idx];- setActiveDays([].concat(activeDays));+ setActiveDays(([] as boolean[]).concat(activeDays));};return (@@ -24,7 +28,10 @@ export const WeekdaySelect = (props) => {activeDays[idx] ? (<buttonkey={idx}- onClick={(e) => toggleDay(e, idx)}+ onClick={(e) => {+ e.preventDefault();+ toggleDay(idx);+ }}className={`w-10 h-10bg-black text-white focus:outline-none px-3 py-1 rounded@@ -38,7 +45,10 @@ export const WeekdaySelect = (props) => {) : (<buttonkey={idx}- onClick={(e) => toggleDay(e, idx)}+ onClick={(e) => {+ e.preventDefault();+ toggleDay(idx);+ }}style={{ marginTop: "1px", marginBottom: "1px" }}className={`w-10 h-10 bg-gray-50 focus:outline-none px-3 py-1 rounded-none ${idx === 0 ? "rounded-l" : "border-l-0"diff --git a/components/ui/form/radio-area/RadioAreaGroup.tsx b/components/ui/form/radio-area/RadioAreaGroup.tsxindex 39cc56f65a9..e22f1a91c82 100644--- a/components/ui/form/radio-area/RadioAreaGroup.tsx+++ b/components/ui/form/radio-area/RadioAreaGroup.tsx@@ -1,10 +1,10 @@-import React, { PropsWithChildren, useState } from "react";+import React, { ReactNode, useState } from "react";import classNames from "@lib/classNames";-type RadioAreaProps = React.InputHTMLAttributes<HTMLInputElement> & {- onChange: (value: string) => void;- defaultChecked: boolean;+type RadioAreaProps = Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange"> & {+ onChange?: (value: string) => void;+ defaultChecked?: boolean;};const RadioArea = (props: RadioAreaProps) => {@@ -16,9 +16,13 @@ const RadioArea = (props: RadioAreaProps) => {props.className)}><input- onChange={(e) => props.onChange(e.target.value)}+ onChange={(e) => {+ if (typeof props.onChange === "function") {+ props.onChange(e.target.value);+ }+ }}checked={props.checked}- className="float-right text-neutral-900 focus:ring-neutral-500 ml-3"+ className="float-right ml-3 text-neutral-900 focus:ring-neutral-500"name={props.name}value={props.value}type="radio"@@ -28,17 +32,17 @@ const RadioArea = (props: RadioAreaProps) => {);};-type RadioAreaGroupProps = {- name?: string;- onChange?: (value) => void;+type ChildrenProps = {+ props: RadioAreaProps;+ children?: ReactNode;};+interface RadioAreaGroupProps extends Omit<React.ComponentPropsWithoutRef<"div">, "onChange"> {+ children: ChildrenProps | ChildrenProps[];+ name?: string;+ onChange?: (value: string) => void;+}-const RadioAreaGroup = ({- children,- name,- onChange,- ...passThroughProps-}: PropsWithChildren<RadioAreaGroupProps>) => {+const RadioAreaGroup = ({ children, name, onChange, ...passThroughProps }: RadioAreaGroupProps) => {const [checkedIdx, setCheckedIdx] = useState<number | null>(null);const changeHandler = (value: string, idx: number) => {@@ -50,23 +54,21 @@ const RadioAreaGroup = ({return (<div {...passThroughProps}>- {(Array.isArray(children) ? children : [children]).map(- (child: React.ReactElement<RadioAreaProps>, idx: number) => {- if (checkedIdx === null && child.props.defaultChecked) {- setCheckedIdx(idx);- }- return (- <Item- {...child.props}- key={idx}- name={name}- checked={idx === checkedIdx}- onChange={(value: string) => changeHandler(value, idx)}>- {child.props.children}- </Item>- );+ {(Array.isArray(children) ? children : [children]).map((child, idx: number) => {+ if (checkedIdx === null && child.props.defaultChecked) {+ setCheckedIdx(idx);}- )}+ return (+ <Item+ {...child.props}+ key={idx}+ name={name}+ checked={idx === checkedIdx}+ onChange={(value: string) => changeHandler(value, idx)}>+ {child.props.children}+ </Item>+ );+ })}</div>);};diff --git a/ee/pages/api/integrations/stripepayment/webhook.ts b/ee/pages/api/integrations/stripepayment/webhook.tsindex df8cc5cadcc..42e7fb804bb 100644--- a/ee/pages/api/integrations/stripepayment/webhook.ts+++ b/ee/pages/api/integrations/stripepayment/webhook.ts@@ -1,12 +1,12 @@import { buffer } from "micro";import type { NextApiRequest, NextApiResponse } from "next";-import { getErrorFromUnknown } from "pages/_error";import Stripe from "stripe";import stripe from "@ee/lib/stripe/server";import { CalendarEvent } from "@lib/calendarClient";import { HttpError } from "@lib/core/http/error";+import { getErrorFromUnknown } from "@lib/errors";import EventManager from "@lib/events/EventManager";import prisma from "@lib/prisma";diff --git a/lib/core/i18n/i18n.utils.ts b/lib/core/i18n/i18n.utils.tsindex b67da656afc..1ba93e3d916 100644--- a/lib/core/i18n/i18n.utils.ts+++ b/lib/core/i18n/i18n.utils.ts@@ -9,8 +9,10 @@ import { Maybe } from "@trpc/server";import { i18n } from "../../../next-i18next.config";export function getLocaleFromHeaders(req: IncomingMessage): string {- const preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]) as Maybe<string>;-+ let preferredLocale: string | null | undefined;+ if (req.headers["accept-language"]) {+ preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]) as Maybe<string>;+ }return preferredLocale ?? i18n.defaultLocale;}diff --git a/lib/errors.ts b/lib/errors.tsnew file mode 100644index 00000000000..9d1df3ae6b5--- /dev/null+++ b/lib/errors.ts@@ -0,0 +1,11 @@+export function getErrorFromUnknown(cause: unknown): Error & { statusCode?: number } {+ if (cause instanceof Error) {+ return cause;+ }+ if (typeof cause === "string") {+ // @ts-expect-error https://github.com/tc39/proposal-error-cause+ return new Error(cause, { cause });+ }++ return new Error(`Unhandled error of type '${typeof cause}''`);+}diff --git a/package.json b/package.jsonindex 7fc3aa3c943..ec2ee9af530 100644--- a/package.json+++ b/package.json@@ -53,7 +53,6 @@"@trpc/next": "^9.9.1","@trpc/react": "^9.9.1","@trpc/server": "^9.9.1",- "@types/stripe": "^8.0.417","@wojtekmaj/react-daterange-picker": "^3.3.1","accept-language-parser": "^1.5.0","async": "^3.2.1",@@ -99,6 +98,7 @@},"devDependencies": {"@trivago/prettier-plugin-sort-imports": "2.0.4",+ "@types/accept-language-parser": "1.5.2","@types/async": "^3.2.7","@types/bcryptjs": "^2.4.2","@types/jest": "^27.0.1",@@ -110,6 +110,7 @@"@types/react": "^17.0.18","@types/react-phone-number-input": "^3.0.13","@types/react-select": "^4.0.17",+ "@types/stripe": "^8.0.417","@types/uuid": "8.3.1","@typescript-eslint/eslint-plugin": "^4.33.0","@typescript-eslint/parser": "^4.29.2",diff --git a/pages/_error.tsx b/pages/_error.tsxindex b80c9074ae7..49bba4c2aa3 100644--- a/pages/_error.tsx+++ b/pages/_error.tsx@@ -7,6 +7,7 @@ import NextError, { ErrorProps } from "next/error";import React from "react";import { HttpError } from "@lib/core/http/error";+import { getErrorFromUnknown } from "@lib/errors";import logger from "@lib/logger";import { ErrorPage } from "@components/error/error-page";@@ -25,23 +26,6 @@ type AugmentedNextPageContext = Omit<NextPageContext, "err"> & {const log = logger.getChildLogger({ prefix: ["[error]"] });-export function getErrorFromUnknown(cause: unknown): Error & {- // status code error- statusCode?: number;- // prisma error- code?: unknown;-} {- if (cause instanceof Error) {- return cause;- }- if (typeof cause === "string") {- // @ts-expect-error https://github.com/tc39/proposal-error-cause- return new Error(cause, { cause });- }-- return new Error(`Unhandled error of type '${typeof cause}''`);-}-const CustomError: NextPage<CustomErrorProps> = (props) => {const { statusCode, err, message, hasGetInitialPropsRun } = props;diff --git a/pages/event-types/index.tsx b/pages/event-types/index.tsxindex aa082a19d16..653270c7e75 100644--- a/pages/event-types/index.tsx+++ b/pages/event-types/index.tsx@@ -40,6 +40,8 @@ import * as RadioArea from "@components/ui/form/radio-area";import UserCalendarIllustration from "@components/ui/svg/UserCalendarIllustration";type Profiles = inferQueryOutput<"viewer.eventTypes">["profiles"];+type EventTypeGroups = inferQueryOutput<"viewer.eventTypes">["eventTypeGroups"];+type EventTypeGroupProfile = EventTypeGroups[number]["profile"];interface CreateEventTypeProps {canAddEvents: boolean;@@ -223,7 +225,7 @@ const EventTypeList = ({ readOnly, types, profile }: EventTypeListProps): JSX.El};interface EventTypeListHeadingProps {- profile: Profile;+ profile: EventTypeGroupProfile;membershipCount: number;}const EventTypeListHeading = ({ profile, membershipCount }: EventTypeListHeadingProps): JSX.Element => (diff --git a/pages/getting-started.tsx b/pages/getting-started.tsxindex 94b16818a38..9a2f1b38c19 100644--- a/pages/getting-started.tsx+++ b/pages/getting-started.tsx@@ -1,12 +1,5 @@import { ArrowRightIcon } from "@heroicons/react/outline";-import {- EventType,- EventTypeCreateInput,- Schedule,- ScheduleCreateInput,- User,- UserUpdateInput,-} from "@prisma/client";+import { Prisma } from "@prisma/client";import classnames from "classnames";import dayjs from "dayjs";import timezone from "dayjs/plugin/timezone";@@ -22,36 +15,36 @@ import TimezoneSelect from "react-timezone-select";import { getSession } from "@lib/auth";import { useLocale } from "@lib/hooks/useLocale";-import AddCalDavIntegration, {- ADD_CALDAV_INTEGRATION_FORM_TITLE,-} from "@lib/integrations/CalDav/components/AddCalDavIntegration";import getIntegrations from "@lib/integrations/getIntegrations";import prisma from "@lib/prisma";+import { inferSSRProps } from "@lib/types/inferSSRProps";-import { Dialog, DialogClose, DialogContent, DialogHeader } from "@components/Dialog";import Loader from "@components/Loader";+import { ShellSubHeading } from "@components/Shell";+import CalendarsList from "@components/integrations/CalendarsList";+import ConnectedCalendarsList from "@components/integrations/ConnectedCalendarsList";+import SubHeadingTitleWithConnections from "@components/integrations/SubHeadingTitleWithConnections";+import { Alert } from "@components/ui/Alert";import Button from "@components/ui/Button";import SchedulerForm, { SCHEDULE_FORM_ID } from "@components/ui/Schedule/Schedule";import Text from "@components/ui/Text";-import ErrorAlert from "@components/ui/alerts/Error";-import { AddCalDavIntegrationRequest } from "../lib/integrations/CalDav/components/AddCalDavIntegration";+import getCalendarCredentials from "@server/integrations/getCalendarCredentials";+import getConnectedCalendars from "@server/integrations/getConnectedCalendars";+import getEventTypes from "../lib/queries/event-types/get-event-types";dayjs.extend(utc);dayjs.extend(timezone);-type OnboardingProps = {- user: User;- integrations?: Record<string, string>[];- eventTypes?: EventType[];- schedules?: Schedule[];-};--export default function Onboarding(props: OnboardingProps) {+export default function Onboarding(props: inferSSRProps<typeof getServerSideProps>) {const { t } = useLocale();const router = useRouter();+ const refreshData = () => {+ router.replace(router.asPath);+ };+const DEFAULT_EVENT_TYPES = [{title: t("15min_meeting"),@@ -72,12 +65,12 @@ export default function Onboarding(props: OnboardingProps) {];const [isSubmitting, setSubmitting] = React.useState(false);- const [enteredName, setEnteredName] = React.useState();+ const [enteredName, setEnteredName] = React.useState("");const Sess = useSession();const [ready, setReady] = useState(false);- const [error, setError] = useState(null);+ const [error, setError] = useState<Error | null>(null);- const updateUser = async (data: UserUpdateInput) => {+ const updateUser = async (data: Prisma.UserUpdateInput) => {const res = await fetch(`/api/user/${props.user.id}`, {method: "PATCH",body: JSON.stringify({ data: { ...data } }),@@ -93,7 +86,7 @@ export default function Onboarding(props: OnboardingProps) {return responseData.data;};- const createEventType = async (data: EventTypeCreateInput) => {+ const createEventType = async (data: Prisma.EventTypeCreateInput) => {const res = await fetch(`/api/availability/eventtype`, {method: "POST",body: JSON.stringify(data),@@ -109,7 +102,7 @@ export default function Onboarding(props: OnboardingProps) {return responseData.data;};- const createSchedule = async (data: ScheduleCreateInput) => {+ const createSchedule = async (data: Prisma.ScheduleCreateInput) => {const res = await fetch(`/api/schedule`, {method: "POST",body: JSON.stringify({ data: { ...data } }),@@ -125,53 +118,9 @@ export default function Onboarding(props: OnboardingProps) {return responseData.data;};- const handleAddIntegration = (type: string) => {- if (type === "caldav_calendar") {- setAddCalDavError(null);- setIsAddCalDavIntegrationDialogOpen(true);- return;- }-- fetch("/api/integrations/" + type.replace("_", "") + "/add")- .then((response) => response.json())- .then((data) => {- window.location.href = data.url;- });- };-- /** Internal Components */- const IntegrationGridListItem = ({ integration }: { integration: Integration }) => {- if (!integration || !integration.installed) {- return null;- }-- return (- <li- onClick={() => handleAddIntegration(integration.type)}- key={integration.type}- className="flex px-4 py-3 items-center">- <div className="w-1/12 mr-4">- <img className="h-8 w-8 mr-2" src={integration.imageSrc} alt={integration.title} />- </div>- <div className="w-10/12">- <Text className="text-gray-900 text-sm font-medium">{integration.title}</Text>- <Text className="text-gray-400" variant="subtitle">- {integration.description}- </Text>- </div>- <div className="w-2/12 text-right">- <Button className="btn-sm" color="secondary" onClick={() => handleAddIntegration(integration.type)}>- {t("connect")}- </Button>- </div>- </li>- );- };- /** End Internal Components */-/** Name */- const nameRef = useRef(null);- const bioRef = useRef(null);+ const nameRef = useRef<HTMLInputElement>(null);+ const bioRef = useRef<HTMLInputElement>(null);/** End Name *//** TimeZone */const [selectedTimeZone, setSelectedTimeZone] = useState({@@ -183,88 +132,6 @@ export default function Onboarding(props: OnboardingProps) {}, [selectedTimeZone]);/** End TimeZone */- /** CalDav Form */- const addCalDavIntegrationRef = useRef<HTMLFormElement>(null);- const [isAddCalDavIntegrationDialogOpen, setIsAddCalDavIntegrationDialogOpen] = useState(false);- const [addCalDavError, setAddCalDavError] = useState<{ message: string } | null>(null);-- const handleAddCalDavIntegration = async ({ url, username, password }: AddCalDavIntegrationRequest) => {- const requestBody = JSON.stringify({- url,- username,- password,- });-- return await fetch("/api/integrations/caldav/add", {- method: "POST",- body: requestBody,- headers: {- "Content-Type": "application/json",- },- });- };-- const handleAddCalDavIntegrationSaveButtonPress = async () => {- const form = addCalDavIntegrationRef.current.elements;- const url = form.url.value;- const password = form.password.value;- const username = form.username.value;-- try {- setAddCalDavError(null);- const addCalDavIntegrationResponse = await handleAddCalDavIntegration({ username, password, url });- if (addCalDavIntegrationResponse.ok) {- setIsAddCalDavIntegrationDialogOpen(false);- incrementStep();- } else {- const j = await addCalDavIntegrationResponse.json();- setAddCalDavError({ message: j.message });- }- } catch (reason) {- console.error(reason);- }- };-- const ConnectCalDavServerDialog = () => {- return (- <Dialog- open={isAddCalDavIntegrationDialogOpen}- onOpenChange={(isOpen) => setIsAddCalDavIntegrationDialogOpen(isOpen)}>- <DialogContent>- <DialogHeader title={t("connect_caldav")} subtitle={t("credentials_stored_and_encrypted")} />- <div className="my-4">- {addCalDavError && (- <p className="text-red-700 text-sm">- <span className="font-bold">{t("error")}: </span>- {addCalDavError.message}- </p>- )}- <AddCalDavIntegration- ref={addCalDavIntegrationRef}- onSubmit={handleAddCalDavIntegrationSaveButtonPress}- />- </div>- <div className="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">- <button- type="submit"- form={ADD_CALDAV_INTEGRATION_FORM_TITLE}- className="flex justify-center py-2 px-4 border border-transparent rounded-sm shadow-sm text-sm font-medium text-white bg-neutral-900 hover:bg-neutral-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-neutral-900">- {t("save")}- </button>- <DialogClose- onClick={() => {- setIsAddCalDavIntegrationDialogOpen(false);- }}- asChild>- <Button color="secondary">{t("cancel")}</Button>- </DialogClose>- </div>- </DialogContent>- </Dialog>- );- };- /**End CalDav Form */-/** Onboarding Steps */const [currentStep, setCurrentStep] = useState(0);const detectStep = () => {@@ -274,7 +141,7 @@ export default function Onboarding(props: OnboardingProps) {step = 1;}- const hasConfigureCalendar = props.integrations.some((integration) => integration.credential != null);+ const hasConfigureCalendar = props.integrations.some((integration) => integration.credential !== null);if (hasConfigureCalendar) {step = 2;}@@ -292,17 +159,17 @@ export default function Onboarding(props: OnboardingProps) {setSubmitting(true);if (steps[currentStep] &&- steps[currentStep]?.onComplete &&- typeof steps[currentStep]?.onComplete === "function"+ steps[currentStep].onComplete &&+ typeof steps[currentStep].onComplete === "function") {- await steps[currentStep].onComplete();+ await steps[currentStep].onComplete!();}incrementStep();setSubmitting(false);} catch (error) {console.log("handleConfirmStep", error);setSubmitting(false);- setError(error);+ setError(error as Error);}};@@ -385,7 +252,7 @@ export default function Onboarding(props: OnboardingProps) {placeholder={t("your_name")}defaultValue={props.user.name ?? enteredName}required- className="mt-1 block w-full border border-gray-300 rounded-sm shadow-sm py-2 px-3 focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"+ className="block w-full px-3 py-2 mt-1 border border-gray-300 rounded-sm shadow-sm focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"/></fieldset>@@ -403,7 +270,7 @@ export default function Onboarding(props: OnboardingProps) {id="timeZone"value={selectedTimeZone}onChange={setSelectedTimeZone}- className="shadow-sm focus:ring-blue-500 focus:border-blue-500 mt-1 block w-full sm:text-sm border-gray-300 rounded-md"+ className="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm"/></fieldset></section>@@ -417,13 +284,13 @@ export default function Onboarding(props: OnboardingProps) {try {setSubmitting(true);await updateUser({- name: nameRef.current.value,+ name: nameRef.current?.value,timeZone: selectedTimeZone.value,});- setEnteredName(nameRef.current.value);+ setEnteredName(nameRef.current?.value || "");setSubmitting(true);} catch (error) {- setError(error);+ setError(error as Error);setSubmitting(false);}},@@ -433,11 +300,28 @@ export default function Onboarding(props: OnboardingProps) {title: t("connect_your_calendar"),description: t("connect_your_calendar_instructions"),Component: (- <ul className="divide-y divide-gray-200 sm:mx-auto sm:w-full border border-gray-200 rounded-sm">- {props.integrations.map((integration) => {- return <IntegrationGridListItem key={integration.type} integration={integration} />;- })}- </ul>+ <>+ {props.connectedCalendars.length > 0 && (+ <>+ <ConnectedCalendarsList+ connectedCalendars={props.connectedCalendars}+ onChanged={() => {+ refreshData();+ }}+ />+ <ShellSubHeading+ className="mt-6"+ title={<SubHeadingTitleWithConnections title="Connect an additional calendar" />}+ />+ </>+ )}+ <CalendarsList+ calendars={props.integrations}+ onChanged={() => {+ refreshData();+ }}+ />+ </>),hideConfirm: true,confirmText: t("continue"),@@ -450,7 +334,7 @@ export default function Onboarding(props: OnboardingProps) {description: t("set_availability_instructions"),Component: (<>- <section className="bg-white dark:bg-opacity-5 text-black dark:text-white mx-auto max-w-lg">+ <section className="max-w-lg mx-auto text-black bg-white dark:bg-opacity-5 dark:text-white"><SchedulerFormonSubmit={async (data) => {try {@@ -461,12 +345,12 @@ export default function Onboarding(props: OnboardingProps) {debouncedHandleConfirmStep();setSubmitting(false);} catch (error) {- setError(error);+ setError(error as Error);}}}/></section>- <footer className="py-6 sm:mx-auto sm:w-full flex flex-col space-y-6">+ <footer className="flex flex-col py-6 space-y-6 sm:mx-auto sm:w-full"><Button className="justify-center" EndIcon={ArrowRightIcon} type="submit" form={SCHEDULE_FORM_ID}>{t("continue")}</Button>@@ -496,7 +380,7 @@ export default function Onboarding(props: OnboardingProps) {placeholder={t("your_name")}defaultValue={props.user.name || enteredName}required- className="mt-1 block w-full border border-gray-300 rounded-sm shadow-sm py-2 px-3 focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"+ className="block w-full px-3 py-2 mt-1 border border-gray-300 rounded-sm shadow-sm focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"/></fieldset><fieldset>@@ -509,8 +393,8 @@ export default function Onboarding(props: OnboardingProps) {name="bio"id="bio"required- className="mt-1 block w-full border border-gray-300 rounded-sm shadow-sm py-2 px-3 focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"- defaultValue={props.user.bio}+ className="block w-full px-3 py-2 mt-1 border border-gray-300 rounded-sm shadow-sm focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"+ defaultValue={props.user.bio || undefined}/><Text variant="caption" className="mt-2">{t("few_sentences_about_yourself")}@@ -528,11 +412,11 @@ export default function Onboarding(props: OnboardingProps) {setSubmitting(true);console.log("updating");await updateUser({- description: bioRef.current.value,+ bio: bioRef.current?.value,});setSubmitting(false);} catch (error) {- setError(error);+ setError(error as Error);setSubmitting(false);}},@@ -550,20 +434,20 @@ export default function Onboarding(props: OnboardingProps) {}return (- <div className="bg-black min-h-screen">+ <div className="min-h-screen bg-black"><Head><title>Cal.com - {t("getting_started")}</title><link rel="icon" href="/favicon.ico" /></Head>{isSubmitting && (- <div className="fixed w-full h-full bg-white bg-opacity-25 flex flex-col justify-center items-center content-center z-10">+ <div className="fixed z-10 flex flex-col items-center content-center justify-center w-full h-full bg-white bg-opacity-25"><Loader /></div>)}- <div className="mx-auto py-24 px-4">+ <div className="px-4 py-24 mx-auto"><article className="relative">- <section className="sm:mx-auto sm:w-full sm:max-w-lg space-y-4">+ <section className="space-y-4 sm:mx-auto sm:w-full sm:max-w-lg"><header><Text className="text-white" variant="largetitle">{steps[currentStep].title}@@ -572,14 +456,14 @@ export default function Onboarding(props: OnboardingProps) {{steps[currentStep].description}</Text></header>- <section className="space-y-2 pt-4">+ <section className="pt-4 space-y-2"><Text variant="footnote">Step {currentStep + 1} of {steps.length}</Text>- {error && <ErrorAlert {...error} />}+ {error && <Alert severity="error" {...error} />}- <section className="w-full space-x-2 flex">+ <section className="flex w-full space-x-2">{steps.map((s, index) => {return index <= currentStep ? (<div@@ -590,17 +474,17 @@ export default function Onboarding(props: OnboardingProps) {index < currentStep ? "cursor-pointer" : "")}></div>) : (- <div key={`step-${index}`} className="h-1 bg-white bg-opacity-25 w-1/4"></div>+ <div key={`step-${index}`} className="w-1/4 h-1 bg-white bg-opacity-25"></div>);})}</section></section></section>- <section className="mt-10 mx-auto max-w-xl bg-white p-10 rounded-sm">+ <section className="max-w-xl p-10 mx-auto mt-10 bg-white rounded-sm">{steps[currentStep].Component}{!steps[currentStep].hideConfirm && (- <footer className="sm:mx-auto sm:w-full flex flex-col space-y-6 mt-8">+ <footer className="flex flex-col mt-8 space-y-6 sm:mx-auto sm:w-full"><ButtonclassName="justify-center"disabled={isSubmitting}@@ -611,8 +495,8 @@ export default function Onboarding(props: OnboardingProps) {</footer>)}</section>- <section className="py-8 mx-auto max-w-xl">- <div className="flex justify-between flex-row-reverse">+ <section className="max-w-xl py-8 mx-auto">+ <div className="flex flex-row-reverse justify-between"><button disabled={isSubmitting} onClick={handleSkipStep}><Text variant="caption">Skip Step</Text></button>@@ -625,7 +509,6 @@ export default function Onboarding(props: OnboardingProps) {</section></article></div>- <ConnectCalDavServerDialog /></div>);}@@ -634,6 +517,7 @@ export async function getServerSideProps(context: NextPageContext) {const session = await getSession(context);let integrations = [];+ let connectedCalendars = [];let credentials = [];let eventTypes = [];let schedules = [];@@ -660,6 +544,12 @@ export async function getServerSideProps(context: NextPageContext) {avatar: true,timeZone: true,completedOnboarding: true,+ selectedCalendars: {+ select: {+ externalId: true,+ integration: true,+ },+ },},});if (!user) {@@ -686,7 +576,14 @@ export async function getServerSideProps(context: NextPageContext) {},});- integrations = getIntegrations(credentials).map((item) => omit(item, "key"));+ integrations = getIntegrations(credentials)+ .filter((item) => item.type.endsWith("_calendar"))+ .map((item) => omit(item, "key"));++ // get user's credentials + their connected integrations+ const calendarCredentials = getCalendarCredentials(credentials, user.id);+ // get all the connected integrations' calendars (from third party)+ connectedCalendars = await getConnectedCalendars(calendarCredentials, user.selectedCalendars);eventTypes = await prisma.eventType.findMany({where: {@@ -716,6 +613,7 @@ export async function getServerSideProps(context: NextPageContext) {session,user,integrations,+ connectedCalendars,eventTypes,schedules,},diff --git a/pages/integrations/index.tsx b/pages/integrations/index.tsxindex e7fcd49fb8b..e2a7aebb4f3 100644--- a/pages/integrations/index.tsx+++ b/pages/integrations/index.tsx@@ -2,17 +2,15 @@ import { PencilAltIcon, TrashIcon } from "@heroicons/react/outline";import { ClipboardIcon } from "@heroicons/react/solid";import { WebhookTriggerEvents } from "@prisma/client";import Image from "next/image";-import { getErrorFromUnknown } from "pages/_error";-import { Fragment, ReactNode, useState } from "react";+import { useState } from "react";import { Controller, useForm } from "react-hook-form";import { useMutation } from "react-query";import { QueryCell } from "@lib/QueryCell";import classNames from "@lib/classNames";import * as fetcher from "@lib/core/http/fetch-wrapper";+import { getErrorFromUnknown } from "@lib/errors";import { useLocale } from "@lib/hooks/useLocale";-import { AddAppleIntegrationModal } from "@lib/integrations/Apple/components/AddAppleIntegration";-import { AddCalDavIntegrationModal } from "@lib/integrations/CalDav/components/AddCalDavIntegration";import showToast from "@lib/notification";import { inferQueryOutput, trpc } from "@lib/trpc";@@ -22,18 +20,16 @@ import Shell, { ShellSubHeading } from "@components/Shell";import { Tooltip } from "@components/Tooltip";import ConfirmationDialogContent from "@components/dialog/ConfirmationDialogContent";import { FieldsetLegend, Form, InputGroupBox, TextField } from "@components/form/fields";+import CalendarsList from "@components/integrations/CalendarsList";+import ConnectIntegration from "@components/integrations/ConnectIntegrations";+import ConnectedCalendarsList from "@components/integrations/ConnectedCalendarsList";+import DisconnectIntegration from "@components/integrations/DisconnectIntegration";+import IntegrationListItem from "@components/integrations/IntegrationListItem";+import SubHeadingTitleWithConnections from "@components/integrations/SubHeadingTitleWithConnections";import { Alert } from "@components/ui/Alert";-import Badge from "@components/ui/Badge";-import Button, { ButtonBaseProps } from "@components/ui/Button";+import Button from "@components/ui/Button";import Switch from "@components/ui/Switch";-function pluralize(opts: { num: number; plural: string; singular: string }) {- if (opts.num === 0) {- return opts.singular;- }- return opts.singular;-}-type TIntegrations = inferQueryOutput<"viewer.integrations">;type TWebhook = TIntegrations["webhooks"][number];@@ -123,8 +119,8 @@ function WebhookDialogForm(props: {handleClose: () => void;}) {const { t } = useLocale();-const utils = trpc.useContext();+const {defaultValues = {id: "",@@ -378,129 +374,6 @@ function WebhookEmbed(props: { webhooks: TWebhook[] }) {);}-function SubHeadingTitleWithConnections(props: { title: ReactNode; numConnections?: number }) {- const num = props.numConnections;- return (- <>- <span>{props.title}</span>- {num ? (- <Badge variant="success">- {num}{" "}- {pluralize({- num,- singular: "connection",- plural: "connections",- })}- </Badge>- ) : null}- </>- );-}--function ConnectIntegration(props: { type: string; render: (renderProps: ButtonBaseProps) => JSX.Element }) {- const { type } = props;- const [isLoading, setIsLoading] = useState(false);- const mutation = useMutation(async () => {- const res = await fetch("/api/integrations/" + type.replace("_", "") + "/add");- if (!res.ok) {- throw new Error("Something went wrong");- }- const json = await res.json();- window.location.href = json.url;- setIsLoading(true);- });- const [isModalOpen, _setIsModalOpen] = useState(false);- const utils = trpc.useContext();-- const setIsModalOpen: typeof _setIsModalOpen = (v) => {- _setIsModalOpen(v);- // refetch intergrations on modal toggles-- utils.invalidateQueries(["viewer.integrations"]);- };-- return (- <>- {props.render({- onClick() {- if (["caldav_calendar", "apple_calendar"].includes(type)) {- // special handlers- setIsModalOpen(true);- return;- }-- mutation.mutate();- },- loading: mutation.isLoading || isLoading,- disabled: isModalOpen,- })}- {type === "caldav_calendar" && (- <AddCalDavIntegrationModal open={isModalOpen} onOpenChange={setIsModalOpen} />- )}-- {type === "apple_calendar" && (- <AddAppleIntegrationModal open={isModalOpen} onOpenChange={setIsModalOpen} />- )}- </>- );-}--function DisconnectIntegration(props: {- /**- * Integration credential id- */- id: number;- render: (renderProps: ButtonBaseProps) => JSX.Element;-}) {- const utils = trpc.useContext();- const [modalOpen, setModalOpen] = useState(false);- const mutation = useMutation(- async () => {- const res = await fetch("/api/integrations", {- method: "DELETE",- body: JSON.stringify({ id: props.id }),- headers: {- "Content-Type": "application/json",- },- });- if (!res.ok) {- throw new Error("Something went wrong");- }- },- {- async onSettled() {- await utils.invalidateQueries(["viewer.integrations"]);- },- onSuccess() {- setModalOpen(false);- },- }- );- return (- <>- <Dialog open={modalOpen} onOpenChange={setModalOpen}>- <ConfirmationDialogContent- variety="danger"- title="Disconnect Integration"- confirmBtnText="Yes, disconnect integration"- cancelBtnText="Cancel"- onConfirm={() => {- mutation.mutate();- }}>- Are you sure you want to disconnect this integration?- </ConfirmationDialogContent>- </Dialog>- {props.render({- onClick() {- setModalOpen(true);- },- disabled: modalOpen,- loading: mutation.isLoading,- })}- </>- );-}-function ConnectOrDisconnectIntegrationButton(props: {//credentialIds: number[];@@ -508,6 +381,11 @@ function ConnectOrDisconnectIntegrationButton(props: {installed: boolean;}) {const [credentialId] = props.credentialIds;+ const utils = trpc.useContext();+ const handleOpenChange = () => {+ utils.invalidateQueries(["viewer.integrations"]);+ };+if (credentialId) {return (<DisconnectIntegration@@ -517,6 +395,7 @@ function ConnectOrDisconnectIntegrationButton(props: {Disconnect</Button>)}+ onOpenChange={handleOpenChange}/>);}@@ -543,103 +422,17 @@ function ConnectOrDisconnectIntegrationButton(props: {Connect</Button>)}+ onOpenChange={handleOpenChange}/>);}-function IntegrationListItem(props: {- imageSrc: string;- title: string;- description: string;- actions?: ReactNode;- children?: ReactNode;-}) {- return (- <ListItem expanded={!!props.children} className={classNames("flex-col")}>- <div className={classNames("flex flex-1 space-x-2 w-full p-3 items-center")}>- <Image width={40} height={40} src={`/${props.imageSrc}`} alt={props.title} />- <div className="flex-grow pl-2 truncate">- <ListItemTitle component="h3">{props.title}</ListItemTitle>- <ListItemText component="p">{props.description}</ListItemText>- </div>- <div>{props.actions}</div>- </div>- {props.children && <div className="w-full border-t border-gray-200">{props.children}</div>}- </ListItem>- );-}--export function CalendarSwitch(props: {- type: string;- externalId: string;- title: string;- defaultSelected: boolean;-}) {- const utils = trpc.useContext();-- const mutation = useMutation<- unknown,- unknown,- {- isOn: boolean;- }- >(- async ({ isOn }) => {- const body = {- integration: props.type,- externalId: props.externalId,- };- if (isOn) {- const res = await fetch("/api/availability/calendar", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(body),- });- if (!res.ok) {- throw new Error("Something went wrong");- }- } else {- const res = await fetch("/api/availability/calendar", {- method: "DELETE",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(body),- });-- if (!res.ok) {- throw new Error("Something went wrong");- }- }- },- {- async onSettled() {- await utils.invalidateQueries(["viewer.integrations"]);- },- onError() {- showToast(`Something went wrong when toggling "${props.title}""`, "error");- },- }- );- return (- <div className="py-1">- <Switch- key={props.externalId}- name="enabled"- label={props.title}- defaultChecked={props.defaultSelected}- onCheckedChange={(isOn: boolean) => {- mutation.mutate({ isOn });- }}- />- </div>- );-}-export default function IntegrationsPage() {const query = trpc.useQuery(["viewer.integrations"]);+ const utils = trpc.useContext();+ const handleOpenChange = () => {+ utils.invalidateQueries(["viewer.integrations"]);+ };return (<Shell heading="Integrations" subtitle="Connect your favourite apps.">@@ -701,79 +494,17 @@ export default function IntegrationsPage() {{data.connectedCalendars.length > 0 && (<>- <List>- {data.connectedCalendars.map((item) => (- <Fragment key={item.credentialId}>- {item.calendars ? (- <IntegrationListItem- {...item.integration}- description={item.primary.externalId}- actions={- <DisconnectIntegration- id={item.credentialId}- render={(btnProps) => (- <Button {...btnProps} color="warn">- Disconnect- </Button>- )}- />- }>- <ul className="p-4 space-y-2">- {item.calendars.map((cal) => (- <CalendarSwitch- key={cal.externalId}- externalId={cal.externalId}- title={cal.name}- type={item.integration.type}- defaultSelected={cal.isSelected}- />- ))}- </ul>- </IntegrationListItem>- ) : (- <Alert- severity="warning"- title="Something went wrong"- message={item.error.message}- actions={- <DisconnectIntegration- id={item.credentialId}- render={(btnProps) => (- <Button {...btnProps} color="warn">- Disconnect- </Button>- )}- />- }- />- )}- </Fragment>- ))}- </List>+ <ConnectedCalendarsList+ connectedCalendars={data.connectedCalendars}+ onChanged={handleOpenChange}+ /><ShellSubHeadingclassName="mt-6"title={<SubHeadingTitleWithConnections title="Connect an additional calendar" />}/></>)}- <List>- {data.calendar.items.map((item) => (- <IntegrationListItem- key={item.title}- {...item}- actions={- <ConnectIntegration- type={item.type}- render={(btnProps) => (- <Button color="secondary" {...btnProps}>- Connect- </Button>- )}- />- }- />- ))}- </List>+ <CalendarsList calendars={data.calendar.items} onChanged={handleOpenChange} /><WebhookEmbed webhooks={data.webhooks} /></>);diff --git a/pages/reschedule/[uid].tsx b/pages/reschedule/[uid].tsxindex d21821f26b3..27eca3ada19 100644--- a/pages/reschedule/[uid].tsx+++ b/pages/reschedule/[uid].tsx@@ -44,7 +44,11 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {const eventType = booking.eventType;const eventPage =- (eventType.team ? "team/" + eventType.team.slug : booking.user.username) + "/" + booking.eventType.slug;+ (eventType.team+ ? "team/" + eventType.team.slug+ : booking.user?.username || "rick") /* This shouldn't happen */ ++ "/" ++ booking.eventType.slug;return {redirect: {diff --git a/pages/settings/profile.tsx b/pages/settings/profile.tsxindex b37531f79fd..9e9ef8732d1 100644--- a/pages/settings/profile.tsx+++ b/pages/settings/profile.tsx@@ -2,7 +2,7 @@ import { InformationCircleIcon } from "@heroicons/react/outline";import crypto from "crypto";import { GetServerSidePropsContext } from "next";import { i18n } from "next-i18next.config";-import { ComponentProps, RefObject, useEffect, useRef, useState } from "react";+import { ComponentProps, FormEvent, RefObject, useEffect, useRef, useState } from "react";import Select, { OptionTypeBase } from "react-select";import TimezoneSelect from "react-timezone-select";@@ -32,6 +32,9 @@ type Props = inferSSRProps<typeof getServerSideProps>;const getLocaleOptions = (displayLocale: string | string[]): OptionTypeBase[] => {return i18n.locales.map((locale) => ({value: locale,+ // FIXME+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment+ // @ts-ignorelabel: new Intl.DisplayNames(displayLocale, { type: "language" }).of(locale),}));};@@ -151,7 +154,7 @@ function SettingsView(props: ComponentProps<typeof Settings> & { localeProp: str);}, []);- async function updateProfileHandler(event) {+ async function updateProfileHandler(event: FormEvent<HTMLFormElement>) {event.preventDefault();const enteredUsername = usernameRef.current.value.toLowerCase();@@ -186,7 +189,7 @@ function SettingsView(props: ComponentProps<typeof Settings> & { localeProp: str<div className="flex-grow space-y-6"><div className="block sm:flex"><div className="w-full mb-6 sm:w-1/2 sm:mr-2">- <UsernameInput ref={usernameRef} defaultValue={props.user.username} />+ <UsernameInput ref={usernameRef} defaultValue={props.user.username || undefined} /></div><div className="w-full sm:w-1/2 sm:ml-2"><label htmlFor="name" className="block text-sm font-medium text-gray-700">@@ -201,7 +204,7 @@ function SettingsView(props: ComponentProps<typeof Settings> & { localeProp: strplaceholder={t("your_name")}requiredclassName="block w-full px-3 py-2 mt-1 border border-gray-300 rounded-sm shadow-sm focus:outline-none focus:ring-neutral-500 focus:border-neutral-500 sm:text-sm"- defaultValue={props.user.name}+ defaultValue={props.user.name || undefined}/></div></div>@@ -247,7 +250,7 @@ function SettingsView(props: ComponentProps<typeof Settings> & { localeProp: str<div><div className="flex mt-1"><Avatar- displayName={props.user.name}+ alt={props.user.name || ""}className="relative w-10 h-10 rounded-full"gravatarFallbackMd5={props.user.emailMd5}imageSrc={imageSrc}@@ -270,11 +273,11 @@ function SettingsView(props: ComponentProps<typeof Settings> & { localeProp: strconst nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"- ).set;- nativeInputValueSetter.call(avatarRef.current, newAvatar);+ )?.set;+ nativeInputValueSetter?.call(avatarRef.current, newAvatar);const ev2 = new Event("input", { bubbles: true });avatarRef.current.dispatchEvent(ev2);- updateProfileHandler(ev2);+ updateProfileHandler(ev2 as unknown as FormEvent<HTMLFormElement>);setImageSrc(newAvatar);}}imageSrc={imageSrc}@@ -350,7 +353,7 @@ function SettingsView(props: ComponentProps<typeof Settings> & { localeProp: strid="theme-adjust-os"name="theme-adjust-os"type="checkbox"- onChange={(e) => setSelectedTheme(e.target.checked ? null : themeOptions[0])}+ onChange={(e) => setSelectedTheme(e.target.checked ? undefined : themeOptions[0])}checked={!selectedTheme}className="w-4 h-4 border-gray-300 rounded-sm focus:ring-neutral-500 text-neutral-900"/>diff --git a/pages/settings/security.tsx b/pages/settings/security.tsxindex 93b798d9415..fa636071353 100644--- a/pages/settings/security.tsx+++ b/pages/settings/security.tsx@@ -15,7 +15,7 @@ export default function Security() {<Shell heading={t("security")} subtitle={t("manage_account_security")}><SettingsShell><ChangePasswordSection />- <TwoFactorAuthSection twoFactorEnabled={user?.twoFactorEnabled} />+ <TwoFactorAuthSection twoFactorEnabled={user?.twoFactorEnabled || false} /></SettingsShell></Shell>);diff --git a/server/integrations/getCalendarCredentials.ts b/server/integrations/getCalendarCredentials.tsnew file mode 100644index 00000000000..20c6c49b5f8--- /dev/null+++ b/server/integrations/getCalendarCredentials.ts@@ -0,0 +1,25 @@+import { Credential } from "@prisma/client";++import { getCalendarAdapterOrNull } from "@lib/calendarClient";+import { ALL_INTEGRATIONS } from "@lib/integrations/getIntegrations";++export default function getCalendarCredentials(+ credentials: Array<Omit<Credential, "userId">>,+ userId: number+) {+ const calendarCredentials = credentials+ .filter((credential) => credential.type.endsWith("_calendar"))+ .flatMap((credential) => {+ const integration = ALL_INTEGRATIONS.find((integration) => integration.type === credential.type);++ const adapter = getCalendarAdapterOrNull({+ ...credential,+ userId,+ });+ return integration && adapter && integration.variant === "calendar"+ ? [{ integration, credential, adapter }]+ : [];+ });++ return calendarCredentials;+}diff --git a/server/integrations/getConnectedCalendars.ts b/server/integrations/getConnectedCalendars.tsnew file mode 100644index 00000000000..461075e9375--- /dev/null+++ b/server/integrations/getConnectedCalendars.ts@@ -0,0 +1,50 @@+import _ from "lodash";++import { getErrorFromUnknown } from "@lib/errors";++import getCalendarCredentials from "./getCalendarCredentials";++export default async function getConnectedCalendars(+ calendarCredentials: ReturnType<typeof getCalendarCredentials>,+ selectedCalendars: { externalId: string }[]+) {+ const connectedCalendars = await Promise.all(+ calendarCredentials.map(async (item) => {+ const { adapter, integration, credential } = item;++ const credentialId = credential.id;+ try {+ const cals = await adapter.listCalendars();+ const calendars = _(cals)+ .map((cal) => ({+ ...cal,+ primary: cal.primary || null,+ isSelected: selectedCalendars.some((selected) => selected.externalId === cal.externalId),+ }))+ .sortBy(["primary"])+ .value();+ const primary = calendars.find((item) => item.primary) ?? calendars[0];+ if (!primary) {+ throw new Error("No primary calendar found");+ }+ return {+ integration,+ credentialId,+ primary,+ calendars,+ };+ } catch (_error) {+ const error = getErrorFromUnknown(_error);+ return {+ integration,+ credentialId,+ error: {+ message: error.message,+ },+ };+ }+ })+ );++ return connectedCalendars;+}diff --git a/server/routers/viewer.tsx b/server/routers/viewer.tsxindex a9e60f0e9a5..03e3455cd7c 100644--- a/server/routers/viewer.tsx+++ b/server/routers/viewer.tsx@@ -1,6 +1,4 @@import { BookingStatus, Prisma } from "@prisma/client";-import _ from "lodash";-import { getErrorFromUnknown } from "pages/_error";import { z } from "zod";import { checkPremiumUsername } from "@ee/lib/core/checkPremiumUsername";@@ -9,9 +7,10 @@ import { checkRegularUsername } from "@lib/core/checkRegularUsername";import { ALL_INTEGRATIONS } from "@lib/integrations/getIntegrations";import slugify from "@lib/slugify";+import getCalendarCredentials from "@server/integrations/getCalendarCredentials";+import getConnectedCalendars from "@server/integrations/getConnectedCalendars";import { TRPCError } from "@trpc/server";-import { getCalendarAdapterOrNull } from "../../lib/calendarClient";import { createProtectedRouter, createRouter } from "../createRouter";import { resizeBase64Image } from "../lib/resizeBase64Image";@@ -314,57 +313,10 @@ const loggedInViewerRouter = createProtectedRouter()const calendar = integrations.flatMap((item) => (item.variant === "calendar" ? [item] : []));// get user's credentials + their connected integrations- const calendarCredentials = user.credentials- .filter((credential) => credential.type.endsWith("_calendar"))- .flatMap((credential) => {- const integration = ALL_INTEGRATIONS.find((integration) => integration.type === credential.type);-- const adapter = getCalendarAdapterOrNull({- ...credential,- userId: user.id,- });- return integration && adapter && integration.variant === "calendar"- ? [{ integration, credential, adapter }]- : [];- });+ const calendarCredentials = getCalendarCredentials(user.credentials, user.id);// get all the connected integrations' calendars (from third party)- const connectedCalendars = await Promise.all(- calendarCredentials.map(async (item) => {- const { adapter, integration, credential } = item;-- const credentialId = credential.id;- try {- const cals = await adapter.listCalendars();- const calendars = _(cals)- .map((cal) => ({- ...cal,- isSelected: user.selectedCalendars.some((selected) => selected.externalId === cal.externalId),- }))- .sortBy(["primary"])- .value();- const primary = calendars.find((item) => item.primary) ?? calendars[0];- if (!primary) {- throw new Error("No primary calendar found");- }- return {- integration,- credentialId,- primary,- calendars,- };- } catch (_error) {- const error = getErrorFromUnknown(_error);- return {- integration,- credentialId,- error: {- message: error.message,- },- };- }- })- );+ const connectedCalendars = await getConnectedCalendars(calendarCredentials, user.selectedCalendars);const webhooks = await ctx.prisma.webhook.findMany({where: {diff --git a/server/ssg.ts b/server/ssg.tsindex 075dfc9e232..fa1bfd738e1 100644--- a/server/ssg.ts+++ b/server/ssg.ts@@ -10,5 +10,12 @@ export const ssg = createSSGHelpers({prisma,session: null,user: null,+ i18n: {+ _nextI18Next: {+ initialI18nStore: null,+ userConfig: null,+ },+ },+ locale: "en",},});diff --git a/test/lib/slots.test.ts b/test/lib/slots.test.tsindex e89a4af01cd..9f37591dddf 100644--- a/test/lib/slots.test.ts+++ b/test/lib/slots.test.ts@@ -17,7 +17,7 @@ it("can fit 24 hourly slots for an empty day", async () => {getSlots({inviteeDate: dayjs().add(1, "day"),frequency: 60,- workingHours: [{ days: [...Array(7).keys()], startTime: 0, endTime: 1440 }],+ workingHours: [{ days: Array.from(Array(7).keys()), startTime: 0, endTime: 1440 }],organizerTimeZone: "Europe/London",})).toHaveLength(24);@@ -29,7 +29,7 @@ it.skip("only shows future booking slots on the same day", async () => {getSlots({inviteeDate: dayjs(),frequency: 60,- workingHours: [{ days: [...Array(7).keys()], startTime: 0, endTime: 1440 }],+ workingHours: [{ days: Array.from(Array(7).keys()), startTime: 0, endTime: 1440 }],organizerTimeZone: "GMT",})).toHaveLength(12);diff --git a/yarn.lock b/yarn.lockindex a2ad314d70c..e9b33b146dd 100644--- a/yarn.lock+++ b/yarn.lock@@ -1763,6 +1763,11 @@version "1.0.2"resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.2.tgz#423c77877d0569db20e1fc80885ac4118314010e"+"@types/[email protected]":+ version "1.5.2"+ resolved "https://registry.yarnpkg.com/@types/accept-language-parser/-/accept-language-parser-1.5.2.tgz#ea48ed07a3dc9d2ba6666d45c018ad1b5e59d665"+ integrity sha512-G8NhvYQ4JVT0GhvgPSVDVskFwWhjFvjbTNou3rRkkDgB8dTBZtxZ1xcU9jqJSth5qTGCzbrKwRf+vKleKdrb7w==+"@types/async@^3.2.7":version "3.2.8"resolved "https://registry.yarnpkg.com/@types/async/-/async-3.2.8.tgz#c4171a8990ed9ae4f0843cacbdceb4fabd7cc7e8"