diff --git a/packages/features/bookings/Booker/Booker.tsx b/packages/features/bookings/Booker/Booker.tsx index 1164e057ca..244f799d48 100644 --- a/packages/features/bookings/Booker/Booker.tsx +++ b/packages/features/bookings/Booker/Booker.tsx @@ -1,35 +1,42 @@ import { LazyMotion, m, AnimatePresence } from "framer-motion"; import dynamic from "next/dynamic"; -import { usePathname, useRouter, useSearchParams } from "next/navigation"; -import { useEffect, useRef } from "react"; +import { useSearchParams } from "next/navigation"; +import { usePathname, useRouter } from "next/navigation"; +import { useEffect, useRef, useMemo } from "react"; import StickyBox from "react-sticky-box"; import { shallow } from "zustand/shallow"; import BookingPageTagManager from "@calcom/app-store/BookingPageTagManager"; import dayjs from "@calcom/dayjs"; -import { useEmbedType, useEmbedUiConfig, useIsEmbed } from "@calcom/embed-core/embed-iframe"; +import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param"; import { useNonEmptyScheduleDays } from "@calcom/features/schedules"; import classNames from "@calcom/lib/classNames"; import { DEFAULT_LIGHT_BRAND_COLOR, DEFAULT_DARK_BRAND_COLOR } from "@calcom/lib/constants"; import { useLocale } from "@calcom/lib/hooks/useLocale"; -import useMediaQuery from "@calcom/lib/hooks/useMediaQuery"; -import { BookerLayouts, defaultBookerLayoutSettings } from "@calcom/prisma/zod-utils"; -import { Button } from "@calcom/ui"; +import { BookerLayouts } from "@calcom/prisma/zod-utils"; +import { VerifyCodeDialog } from "../components/VerifyCodeDialog"; import { AvailableTimeSlots } from "./components/AvailableTimeSlots"; import { BookEventForm } from "./components/BookEventForm"; import { BookFormAsModal } from "./components/BookEventForm/BookFormAsModal"; import { EventMeta } from "./components/EventMeta"; import { Header } from "./components/Header"; +import { InstantBooking } from "./components/InstantBooking"; import { LargeCalendar } from "./components/LargeCalendar"; +import { OverlayCalendar } from "./components/OverlayCalendar/OverlayCalendar"; +import { RedirectToInstantMeetingModal } from "./components/RedirectToInstantMeetingModal"; import { BookerSection } from "./components/Section"; import { Away, NotFound } from "./components/Unavailable"; -import { extraDaysConfig, fadeInLeft, getBookerSizeClassNames, useBookerResizeAnimation } from "./config"; +import { useBookerLayout } from "./components/hooks/useBookerLayout"; +import { useBookingForm } from "./components/hooks/useBookingForm"; +import { useBookings } from "./components/hooks/useBookings"; +import { useCalendars } from "./components/hooks/useCalendars"; +import { useSlots } from "./components/hooks/useSlots"; +import { useVerifyEmail } from "./components/hooks/useVerifyEmail"; +import { fadeInLeft, getBookerSizeClassNames, useBookerResizeAnimation } from "./config"; import { useBookerStore, useInitializeBookerStore } from "./store"; -import type { BookerLayout, BookerProps } from "./types"; +import type { BookerProps } from "./types"; import { useEvent, useScheduleForEvent } from "./utils/event"; -import { validateLayout } from "./utils/layout"; -import { getQueryParam } from "./utils/query-param"; import { useBrandColors } from "./utils/use-brand-colors"; const loadFramerFeatures = () => import("./framer-features").then((res) => res.default); @@ -54,68 +61,61 @@ const BookerComponent = ({ hashedLink, isInstantMeeting = false, }: BookerProps) => { + const router = useRouter(); + const pathname = usePathname(); + const [bookerState, setBookerState] = useBookerStore((state) => [state.state, state.setState], shallow); + const selectedDate = useBookerStore((state) => state.selectedDate); + const [seatedEventData, setSeatedEventData] = useBookerStore( + (state) => [state.seatedEventData, state.setSeatedEventData], + shallow + ); + const event = useEvent(); + const { selectedTimeslot, setSelectedTimeslot } = useSlots(event); + + const { + shouldShowFormInDialog, + hasDarkBackground, + extraDays, + columnViewExtraDays, + isMobile, + layout, + defaultLayout, + hideEventTypeDetails, + isEmbed, + bookerLayouts, + } = useBookerLayout(event.data); + const date = dayjs(selectedDate).format("YYYY-MM-DD"); + + const prefetchNextMonth = + (layout === BookerLayouts.WEEK_VIEW && + !!extraDays && + dayjs(date).month() !== dayjs(date).add(extraDays, "day").month()) || + (layout === BookerLayouts.COLUMN_VIEW && + dayjs(date).month() !== dayjs(date).add(columnViewExtraDays.current, "day").month()); + + const monthCount = + ((layout !== BookerLayouts.WEEK_VIEW && bookerState === "selecting_time") || + layout === BookerLayouts.COLUMN_VIEW) && + dayjs(date).add(1, "month").month() !== dayjs(date).add(columnViewExtraDays.current, "day").month() + ? 2 + : undefined; + /** * Prioritize dateSchedule load * Component will render but use data already fetched from here, and no duplicate requests will be made * */ const schedule = useScheduleForEvent({ - prefetchNextMonth: false, + prefetchNextMonth, username, + monthCount, eventSlug, month, duration, }); - const isMobile = useMediaQuery("(max-width: 768px)"); - const isTablet = useMediaQuery("(max-width: 1024px)"); - const timeslotsRef = useRef(null); - const StickyOnDesktop = isMobile ? "div" : StickyBox; - const rescheduleUid = - typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("rescheduleUid") : null; - const bookingUid = - typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("bookingUid") : null; - const event = useEvent(); - const [_layout, setLayout] = useBookerStore((state) => [state.layout, state.setLayout], shallow); - - const isEmbed = useIsEmbed(); - const embedType = useEmbedType(); - // Floating Button and Element Click both are modal and thus have dark background - const hasDarkBackground = isEmbed && embedType !== "inline"; - const embedUiConfig = useEmbedUiConfig(); - - const { t } = useLocale(); - - const searchParams = useSearchParams(); - const isRedirect = searchParams?.get("redirected") === "true" || false; - const fromUserNameRedirected = searchParams?.get("username") || ""; - - // In Embed we give preference to embed configuration for the layout.If that's not set, we use the App configuration for the event layout - // But if it's mobile view, there is only one layout supported which is 'mobile' - const layout = isEmbed ? (isMobile ? "mobile" : validateLayout(embedUiConfig.layout) || _layout) : _layout; - const columnViewExtraDays = useRef( - isTablet ? extraDaysConfig[layout].tablet : extraDaysConfig[layout].desktop - ); - - const [bookerState, setBookerState] = useBookerStore((state) => [state.state, state.setState], shallow); - const selectedDate = useBookerStore((state) => state.selectedDate); - const [selectedTimeslot, setSelectedTimeslot] = useBookerStore( - (state) => [state.selectedTimeslot, state.setSelectedTimeslot], - shallow - ); - // const seatedEventData = useBookerStore((state) => state.seatedEventData); - const [seatedEventData, setSeatedEventData] = useBookerStore( - (state) => [state.seatedEventData, state.setSeatedEventData], - shallow - ); - - const date = dayjs(selectedDate).format("YYYY-MM-DD"); const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.data?.slots).filter( (slot) => dayjs(selectedDate).diff(slot, "day") <= 0 ); - - const extraDays = isTablet ? extraDaysConfig[layout].tablet : extraDaysConfig[layout].desktop; - const bookerLayouts = event.data?.profile?.bookerLayouts || defaultBookerLayoutSettings; - const animationScope = useBookerResizeAnimation(layout, bookerState); const totalWeekDays = 7; const addonDays = nonEmptyScheduleDays.length < extraDays @@ -123,26 +123,28 @@ const BookerComponent = ({ : nonEmptyScheduleDays.length === extraDays ? totalWeekDays : 0; - // Taking one more available slot(extraDays + 1) to calculate the no of days in between, that next and prev button need to shift. const availableSlots = nonEmptyScheduleDays.slice(0, extraDays + 1); if (nonEmptyScheduleDays.length !== 0) columnViewExtraDays.current = Math.abs(dayjs(selectedDate).diff(availableSlots[availableSlots.length - 2], "day")) + addonDays; - const prefetchNextMonth = - layout === BookerLayouts.COLUMN_VIEW && - dayjs(date).month() !== dayjs(date).add(columnViewExtraDays.current, "day").month(); - const monthCount = - dayjs(date).add(1, "month").month() !== dayjs(date).add(columnViewExtraDays.current, "day").month() - ? 2 - : undefined; const nextSlots = Math.abs(dayjs(selectedDate).diff(availableSlots[availableSlots.length - 1], "day")) + addonDays; - // I would expect isEmbed to be not needed here as it's handled in derived variable layout, but somehow removing it breaks the views. - const defaultLayout = isEmbed - ? validateLayout(embedUiConfig.layout) || bookerLayouts.defaultLayout - : bookerLayouts.defaultLayout; + const animationScope = useBookerResizeAnimation(layout, bookerState); + + const timeslotsRef = useRef(null); + const StickyOnDesktop = isMobile ? "div" : StickyBox; + const rescheduleUid = + typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("rescheduleUid") : null; + const bookingUid = + typeof window !== "undefined" ? new URLSearchParams(window.location.search).get("bookingUid") : null; + + const { t } = useLocale(); + + const searchParams = useSearchParams(); + const isRedirect = searchParams?.get("redirected") === "true" || false; + const fromUserNameRedirected = searchParams?.get("username") || ""; useBrandColors({ brandColor: event.data?.profile.brandColor ?? DEFAULT_LIGHT_BRAND_COLOR, @@ -165,28 +167,44 @@ const BookerComponent = ({ isInstantMeeting, }); - useEffect(() => { - if (isMobile && layout !== "mobile") { - setLayout("mobile"); - } else if (!isMobile && layout === "mobile") { - setLayout(defaultLayout); - } - }, [isMobile, setLayout, layout, defaultLayout]); + const { + bookerFormErrorRef, + key, + formEmail, + formName, + bookingForm, + beforeVerifyEmail, + errors: formErrors, + } = useBookingForm({ + event, + }); - //setting layout from query param - useEffect(() => { - const layout = getQueryParam("layout") as BookerLayouts; - if ( - !isMobile && - !isEmbed && - validateLayout(layout) && - bookerLayouts?.enabledLayouts?.length && - layout !== _layout - ) { - const validLayout = bookerLayouts.enabledLayouts.find((userLayout) => userLayout === layout); - validLayout && setLayout(validLayout); - } - }, [bookerLayouts, validateLayout, setLayout, _layout]); + const { handleBookEvent, hasInstantMeetingTokenExpired, errors, loadingStates } = useBookings({ + event, + hashedLink, + bookingForm, + }); + + const { + isEmailVerificationModalVisible, + setEmailVerificationModalVisible, + handleVerifyEmail, + setVerifiedEmail, + renderConfirmNotVerifyEmailButtonCond, + } = useVerifyEmail({ + email: formEmail, + name: formName, + requiresBookerEmailVerification: event?.data?.requiresBookerEmailVerification, + onVerifyEmail: beforeVerifyEmail, + }); + + const { + overlayBusyDates, + isOverlayCalendarEnabled, + connectedCalendars, + loadingConnectedCalendar, + onToggleCalendar, + } = useCalendars(); useEffect(() => { if (event.isLoading) return setBookerState("loading"); @@ -195,7 +213,74 @@ const BookerComponent = ({ return setBookerState("booking"); }, [event, selectedDate, selectedTimeslot, setBookerState]); - const hideEventTypeDetails = isEmbed ? embedUiConfig.hideEventTypeDetails : false; + const EventBooker = useMemo( + () => + bookerState === "booking" ? ( + { + setSelectedTimeslot(null); + if (seatedEventData.bookingUid) { + setSeatedEventData({ ...seatedEventData, bookingUid: undefined, attendees: undefined }); + } + }} + onSubmit={renderConfirmNotVerifyEmailButtonCond ? handleBookEvent : handleVerifyEmail} + errorRef={bookerFormErrorRef} + errors={{ ...formErrors, ...errors }} + loadingStates={loadingStates} + renderConfirmNotVerifyEmailButtonCond={renderConfirmNotVerifyEmailButtonCond} + bookingForm={bookingForm} + eventQuery={event} + rescheduleUid={rescheduleUid}> + <> + { + setVerifiedEmail(formEmail); + setEmailVerificationModalVisible(false); + handleBookEvent(); + }} + isUserSessionRequiredToVerify={false} + /> + { + // Prevent null on app directory + if (pathname) window.location.href = pathname; + }} + /> + + + ) : ( + <> + ), + [ + bookerFormErrorRef, + bookerState, + bookingForm, + errors, + event, + formEmail, + formErrors, + handleBookEvent, + handleVerifyEmail, + hasInstantMeetingTokenExpired, + isEmailVerificationModalVisible, + key, + loadingStates, + pathname, + renderConfirmNotVerifyEmailButtonCond, + rescheduleUid, + seatedEventData, + setEmailVerificationModalVisible, + setSeatedEventData, + setSelectedTimeslot, + setVerifiedEmail, + ] + ); if (entity.isUnpublished) { return ; @@ -205,22 +290,6 @@ const BookerComponent = ({ return ; } - // In Embed, a Dialog doesn't look good, we disable it intentionally for the layouts that support showing Form without Dialog(i.e. no-dialog Form) - const shouldShowFormInDialogMap: Record = { - // mobile supports showing the Form without Dialog - mobile: !isEmbed, - // We don't show Dialog in month_view currently. Can be easily toggled though as it supports no-dialog Form - month_view: false, - // week_view doesn't support no-dialog Form - // When it's supported, disable it for embed - week_view: true, - // column_view doesn't support no-dialog Form - // When it's supported, disable it for embed - column_view: true, - }; - - const shouldShowFormInDialog = shouldShowFormInDialogMap[layout]; - if (bookerState === "loading") { return null; } @@ -233,7 +302,12 @@ const BookerComponent = ({
- + { + const newPath = `${pathname}?isInstantMeeting=true`; + router.push(newPath); + }} + />
)}
+ isEmbed ? ( + <> + ) : ( + <> + { + router.push("/apps/categories/calendar"); + }} + /> + + ) + } /> )} @@ -304,11 +396,11 @@ const BookerComponent = ({ - + {layout !== BookerLayouts.MONTH_VIEW && !(layout === "mobile" && bookerState === "booking") && (
- +
)}
@@ -320,15 +412,7 @@ const BookerComponent = ({ className="border-subtle sticky top-0 ml-[-1px] h-full p-6 md:w-[var(--booker-main-width)] md:border-l" {...fadeInLeft} visible={bookerState === "booking" && !shouldShowFormInDialog}> - { - setSelectedTimeslot(null); - if (seatedEventData.bookingUid) { - setSeatedEventData({ ...seatedEventData, bookingUid: undefined, attendees: undefined }); - } - }} - hashedLink={hashedLink} - /> + {EventBooker} - + - + @@ -389,9 +473,10 @@ const BookerComponent = ({
setSelectedTimeslot(null)} - /> + visible={bookerState === "booking" && shouldShowFormInDialog}> + {EventBooker} + ); }; @@ -405,54 +490,3 @@ export const Booker = (props: BookerProps) => { ); }; - -export const InstantBooking = () => { - const { t } = useLocale(); - const router = useRouter(); - const pathname = usePathname(); - - return ( -
-
- {/* TODO: max. show 4 people here */} -
- {/* */} -
-
-
{t("dont_want_to_wait")}
-
-
- -
-
- ); -}; diff --git a/packages/features/bookings/Booker/components/AvailableTimeSlots.tsx b/packages/features/bookings/Booker/components/AvailableTimeSlots.tsx index e01b40ef1e..f308ce22f8 100644 --- a/packages/features/bookings/Booker/components/AvailableTimeSlots.tsx +++ b/packages/features/bookings/Booker/components/AvailableTimeSlots.tsx @@ -1,24 +1,21 @@ import { useRef } from "react"; import dayjs from "@calcom/dayjs"; -import { useIsEmbed } from "@calcom/embed-core/embed-iframe"; import { AvailableTimes, AvailableTimesSkeleton } from "@calcom/features/bookings"; import { useNonEmptyScheduleDays } from "@calcom/features/schedules"; import { useSlotsForAvailableDates } from "@calcom/features/schedules/lib/use-schedule/useSlotsForDate"; import { classNames } from "@calcom/lib"; -import useMediaQuery from "@calcom/lib/hooks/useMediaQuery"; import { BookerLayouts } from "@calcom/prisma/zod-utils"; -import { trpc } from "@calcom/trpc"; import { AvailableTimesHeader } from "../../components/AvailableTimesHeader"; import { useBookerStore } from "../store"; -import { useEvent, useScheduleForEvent } from "../utils/event"; +import type { useScheduleForEventReturnType } from "../utils/event"; type AvailableTimeSlotsProps = { extraDays?: number; limitHeight?: boolean; - prefetchNextMonth: boolean; - monthCount: number | undefined; + schedule?: useScheduleForEventReturnType["data"]; + isLoading: boolean; seatsPerTimeSlot?: number | null; showAvailableSeatsCount?: boolean | null; }; @@ -35,16 +32,12 @@ export const AvailableTimeSlots = ({ limitHeight, seatsPerTimeSlot, showAvailableSeatsCount, - prefetchNextMonth, - monthCount, + schedule, + isLoading, }: AvailableTimeSlotsProps) => { - const reserveSlotMutation = trpc.viewer.public.slots.reserveSlot.useMutation(); - const isMobile = useMediaQuery("(max-width: 768px)"); const selectedDate = useBookerStore((state) => state.selectedDate); const setSelectedTimeslot = useBookerStore((state) => state.setSelectedTimeslot); const setSeatedEventData = useBookerStore((state) => state.setSeatedEventData); - const isEmbed = useIsEmbed(); - const event = useEvent(); const date = selectedDate || dayjs().format("YYYY-MM-DD"); const [layout] = useBookerStore((state) => [state.layout]); const isColumnView = layout === BookerLayouts.COLUMN_VIEW; @@ -57,7 +50,6 @@ export const AvailableTimeSlots = ({ bookingUid?: string ) => { setSelectedTimeslot(time); - if (seatsPerTimeSlot) { setSeatedEventData({ seatsPerTimeSlot, @@ -65,20 +57,11 @@ export const AvailableTimeSlots = ({ bookingUid, showAvailableSeatsCount, }); - - if (seatsPerTimeSlot && seatsPerTimeSlot - attendees > 1) { - return; - } } - - if (!event.data) return; + return; }; - const schedule = useScheduleForEvent({ - prefetchNextMonth, - monthCount, - }); - const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.data?.slots); + const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.slots); const nonEmptyScheduleDaysFromSelectedDate = nonEmptyScheduleDays.filter( (slot) => dayjs(selectedDate).diff(slot, "day") <= 0 ); @@ -91,12 +74,12 @@ export const AvailableTimeSlots = ({ ? nonEmptyScheduleDaysFromSelectedDate.slice(0, extraDays) : []; - const slotsPerDay = useSlotsForAvailableDates(dates, schedule?.data?.slots); + const slotsPerDay = useSlotsForAvailableDates(dates, schedule?.slots); return ( <>
- {schedule.isLoading ? ( + {isLoading ? (
) : ( slotsPerDay.length > 0 && @@ -120,7 +103,7 @@ export const AvailableTimeSlots = ({ limitHeight && "scroll-bar flex-grow overflow-auto md:h-[400px]", !limitHeight && "flex h-full w-full flex-row gap-4" )}> - {schedule.isLoading + {isLoading ? // Shows exact amount of days as skeleton. Array.from({ length: 1 + (extraDays ?? 0) }).map((_, i) => ) : slotsPerDay.length > 0 && diff --git a/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx b/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx index 53b2054ab0..56047cdff2 100644 --- a/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx +++ b/packages/features/bookings/Booker/components/BookEventForm/BookEventForm.tsx @@ -1,182 +1,59 @@ -import { zodResolver } from "@hookform/resolvers/zod"; -import type { UseMutationResult } from "@tanstack/react-query"; -import { useMutation } from "@tanstack/react-query"; -import { useSession } from "next-auth/react"; import type { TFunction } from "next-i18next"; import { Trans } from "next-i18next"; import Link from "next/link"; -import { useRouter, useSearchParams, usePathname } from "next/navigation"; -import { useEffect, useRef, useState, useMemo } from "react"; +import { useState, useMemo } from "react"; import type { FieldError } from "react-hook-form"; -import { useForm } from "react-hook-form"; -import { z } from "zod"; -import type { EventLocationType } from "@calcom/app-store/locations"; -import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client"; -import dayjs from "@calcom/dayjs"; -import { updateQueryParam, getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param"; -import { VerifyCodeDialog } from "@calcom/features/bookings/components/VerifyCodeDialog"; -import { - createBooking, - createRecurringBooking, - mapBookingToMutationInput, - mapRecurringBookingToMutationInput, - useTimePreferences, - createInstantBooking, -} from "@calcom/features/bookings/lib"; -import getBookingResponsesSchema, { - getBookingResponsesPartialSchema, -} from "@calcom/features/bookings/lib/getBookingResponsesSchema"; -import { getFullName } from "@calcom/features/form-builder/utils"; -import { useBookingSuccessRedirect } from "@calcom/lib/bookingSuccessRedirect"; import { WEBSITE_URL } from "@calcom/lib/constants"; -import { MINUTES_TO_BOOK } from "@calcom/lib/constants"; import getPaymentAppData from "@calcom/lib/getPaymentAppData"; import { useLocale } from "@calcom/lib/hooks/useLocale"; import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery"; -import { bookingMetadataSchema } from "@calcom/prisma/zod-utils"; -import { trpc } from "@calcom/trpc"; -import { Dialog, DialogContent } from "@calcom/ui"; -import { Alert, Button, EmptyScreen, Form, showToast } from "@calcom/ui"; +import { Alert, Button, EmptyScreen, Form } from "@calcom/ui"; import { Calendar } from "@calcom/ui/components/icon"; import { useBookerStore } from "../../store"; -import { useSlotReservationId } from "../../useSlotReservationId"; -import { useEvent } from "../../utils/event"; +import type { useEventReturnType } from "../../utils/event"; +import type { useBookingFormReturnType } from "../hooks/useBookingForm"; +import type { IUseBookingErrors, IUseBookingLoadingStates } from "../hooks/useBookings"; import { BookingFields } from "./BookingFields"; import { FormSkeleton } from "./Skeleton"; type BookEventFormProps = { onCancel?: () => void; - hashedLink?: string | null; + onSubmit: () => void; + errorRef: React.RefObject; + errors: useBookingFormReturnType["errors"] & IUseBookingErrors; + loadingStates: IUseBookingLoadingStates; + children?: React.ReactNode; + bookingForm: useBookingFormReturnType["bookingForm"]; + renderConfirmNotVerifyEmailButtonCond: boolean; }; -type DefaultValues = Record; - -export const BookEventForm = ({ onCancel, hashedLink }: BookEventFormProps) => { - const [slotReservationId, setSlotReservationId] = useSlotReservationId(); - const reserveSlotMutation = trpc.viewer.public.slots.reserveSlot.useMutation({ - trpc: { - context: { - skipBatch: true, - }, - }, - onSuccess: (data) => { - setSlotReservationId(data.uid); - }, - }); - const removeSelectedSlot = trpc.viewer.public.slots.removeSelectedSlotMark.useMutation({ - trpc: { context: { skipBatch: true } }, - }); - - const rescheduleUid = useBookerStore((state) => state.rescheduleUid); - const bookingData = useBookerStore((state) => state.bookingData); - const duration = useBookerStore((state) => state.selectedDuration); - const timeslot = useBookerStore((state) => state.selectedTimeslot); - const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting); - const isRescheduling = !!rescheduleUid && !!bookingData; - const eventQuery = useEvent(); - const eventType = eventQuery.data; - - const reserveSlot = () => { - if (eventType?.id && timeslot && (duration || eventType?.length)) { - reserveSlotMutation.mutate({ - slotUtcStartDate: dayjs(timeslot).utc().format(), - eventTypeId: eventType?.id, - slotUtcEndDate: dayjs(timeslot) - .utc() - .add(duration || eventType?.length, "minutes") - .format(), - }); - } - }; - - useEffect(() => { - reserveSlot(); - - const interval = setInterval(() => { - reserveSlot(); - }, parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000); - - return () => { - if (eventType) { - removeSelectedSlot.mutate({ uid: slotReservationId }); - } - clearInterval(interval); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [eventType?.id, timeslot]); - - const { initialValues, key } = useInitialFormValues({ - eventType, - rescheduleUid, - isRescheduling, - }); - - return ( - - ); -}; - -export const BookEventFormChild = ({ +export const BookEventForm = ({ onCancel, - initialValues, - isRescheduling, eventQuery, rescheduleUid, - hashedLink, - isInstantMeeting, -}: BookEventFormProps & { - initialValues: DefaultValues; - isRescheduling: boolean; - eventQuery: ReturnType; + onSubmit, + errorRef, + errors, + loadingStates, + renderConfirmNotVerifyEmailButtonCond, + bookingForm, + children, +}: Omit & { + eventQuery: useEventReturnType; rescheduleUid: string | null; - hashedLink?: string | null; - isInstantMeeting?: boolean; }) => { const eventType = eventQuery.data; - const bookingFormSchema = z - .object({ - responses: eventQuery?.data - ? getBookingResponsesSchema({ - eventType: eventQuery?.data, - view: rescheduleUid ? "reschedule" : "booking", - }) - : // Fallback until event is loaded. - z.object({}), - }) - .passthrough(); - const searchParams = useSearchParams(); const routerQuery = useRouterQuery(); const setFormValues = useBookerStore((state) => state.setFormValues); - const seatedEventData = useBookerStore((state) => state.seatedEventData); - const verifiedEmail = useBookerStore((state) => state.verifiedEmail); - const setVerifiedEmail = useBookerStore((state) => state.setVerifiedEmail); - const bookingSuccessRedirect = useBookingSuccessRedirect(); - const [responseVercelIdHeader, setResponseVercelIdHeader] = useState(null); - - const router = useRouter(); - const { t, i18n } = useLocale(); - const { timezone } = useTimePreferences(); - const errorRef = useRef(null); const bookingData = useBookerStore((state) => state.bookingData); - const eventSlug = useBookerStore((state) => state.eventSlug); - const duration = useBookerStore((state) => state.selectedDuration); const timeslot = useBookerStore((state) => state.selectedTimeslot); - const recurringEventCount = useBookerStore((state) => state.recurringEventCount); const username = useBookerStore((state) => state.username); - const [expiryTime, setExpiryTime] = useState(); + const isInstantMeeting = useBookerStore((state) => state.isInstantMeeting); + + const [responseVercelIdHeader] = useState(null); + const { t } = useLocale(); const isPaidEvent = useMemo(() => { if (!eventType?.price) return false; @@ -184,143 +61,6 @@ export const BookEventFormChild = ({ return eventType?.price > 0 || paymentAppData.price > 0; }, [eventType]); - type BookingFormValues = { - locationType?: EventLocationType["type"]; - responses: z.infer["responses"] | null; - // Key is not really part of form values, but only used to have a key - // to set generic error messages on. Needed until RHF has implemented root error keys. - globalError: undefined; - }; - - const bookingForm = useForm({ - defaultValues: initialValues, - resolver: zodResolver( - // Since this isn't set to strict we only validate the fields in the schema - bookingFormSchema, - {}, - { - // bookingFormSchema is an async schema, so inform RHF to do async validation. - mode: "async", - } - ), - }); - const createBookingMutation = useMutation(createBooking, { - onSuccess: (responseData) => { - const { uid, paymentUid } = responseData; - const fullName = getFullName(bookingForm.getValues("responses.name")); - if (paymentUid) { - router.push( - createPaymentLink({ - paymentUid, - date: timeslot, - name: fullName, - email: bookingForm.getValues("responses.email"), - absolute: false, - }) - ); - return; - } - - if (!uid) { - console.error("No uid returned from createBookingMutation"); - return; - } - - const query = { - isSuccessBookingPage: true, - email: bookingForm.getValues("responses.email"), - eventTypeSlug: eventSlug, - seatReferenceUid: "seatReferenceUid" in responseData ? responseData.seatReferenceUid : null, - formerTime: - isRescheduling && bookingData?.startTime ? dayjs(bookingData.startTime).toString() : undefined, - }; - - bookingSuccessRedirect({ - successRedirectUrl: eventType?.successRedirectUrl || "", - query, - booking: responseData, - }); - }, - onError: (err, _, ctx) => { - // TODO: - // const vercelId = ctx?.meta?.headers?.get("x-vercel-id"); - // if (vercelId) { - // setResponseVercelIdHeader(vercelId); - // } - errorRef && errorRef.current?.scrollIntoView({ behavior: "smooth" }); - }, - }); - - const createInstantBookingMutation = useMutation(createInstantBooking, { - onSuccess: (responseData) => { - updateQueryParam("bookingId", responseData.bookingId); - setExpiryTime(responseData.expires); - }, - onError: (err, _, ctx) => { - console.error("Error creating instant booking", err); - - errorRef && errorRef.current?.scrollIntoView({ behavior: "smooth" }); - }, - }); - - const createRecurringBookingMutation = useMutation(createRecurringBooking, { - onSuccess: async (responseData) => { - const booking = responseData[0] || {}; - const { uid } = booking; - - if (!uid) { - console.error("No uid returned from createRecurringBookingMutation"); - return; - } - - const query = { - isSuccessBookingPage: true, - allRemainingBookings: true, - email: bookingForm.getValues("responses.email"), - eventTypeSlug: eventSlug, - formerTime: - isRescheduling && bookingData?.startTime ? dayjs(bookingData.startTime).toString() : undefined, - }; - - bookingSuccessRedirect({ - successRedirectUrl: eventType?.successRedirectUrl || "", - query, - booking, - }); - }, - }); - - const [isEmailVerificationModalVisible, setEmailVerificationModalVisible] = useState(false); - const email = bookingForm.watch("responses.email"); - - const sendEmailVerificationByCodeMutation = trpc.viewer.auth.sendVerifyEmailCode.useMutation({ - onSuccess() { - showToast(t("email_sent"), "success"); - }, - onError() { - showToast(t("email_not_sent"), "error"); - }, - }); - - const verifyEmail = () => { - bookingForm.clearErrors(); - - // It shouldn't be possible that this method is fired without having event data, - // but since in theory (looking at the types) it is possible, we still handle that case. - if (!eventQuery?.data) { - bookingForm.setError("globalError", { message: t("error_booking_event") }); - return; - } - - const name = bookingForm.getValues("responses.name"); - - sendEmailVerificationByCodeMutation.mutate({ - email, - username: typeof name === "string" ? name : name.firstName, - }); - setEmailVerificationModalVisible(true); - }; - if (eventQuery.isError) return ; if (eventQuery.isLoading || !eventQuery.data) return ; if (!timeslot) @@ -334,66 +74,11 @@ export const BookEventFormChild = ({ /> ); - const bookEvent = (values: BookingFormValues) => { - // It shouldn't be possible that this method is fired without having eventQuery data, - // but since in theory (looking at the types) it is possible, we still handle that case. - if (!eventQuery?.data) { - bookingForm.setError("globalError", { message: t("error_booking_event") }); - return; - } - - // Ensures that duration is an allowed value, if not it defaults to the - // default eventQuery duration. - const validDuration = eventQuery.data.isDynamic - ? duration || eventQuery.data.length - : duration && eventQuery.data.metadata?.multipleDuration?.includes(duration) - ? duration - : eventQuery.data.length; - - const bookingInput = { - values, - duration: validDuration, - event: eventQuery.data, - date: timeslot, - timeZone: timezone, - language: i18n.language, - rescheduleUid: rescheduleUid || undefined, - bookingUid: (bookingData && bookingData.uid) || seatedEventData?.bookingUid || undefined, - username: username || "", - metadata: Object.keys(routerQuery) - .filter((key) => key.startsWith("metadata")) - .reduce( - (metadata, key) => ({ - ...metadata, - [key.substring("metadata[".length, key.length - 1)]: searchParams?.get(key), - }), - {} - ), - hashedLink, - }; - - if (isInstantMeeting) { - createInstantBookingMutation.mutate(mapBookingToMutationInput(bookingInput)); - } else if (eventQuery.data?.recurringEvent?.freq && recurringEventCount && !rescheduleUid) { - createRecurringBookingMutation.mutate( - mapRecurringBookingToMutationInput(bookingInput, recurringEventCount) - ); - } else { - createBookingMutation.mutate(mapBookingToMutationInput(bookingInput)); - } - // Clears form values stored in store, so old values won't stick around. - setFormValues({}); - bookingForm.clearErrors(); - }; - if (!eventType) { console.warn("No event type found for event", routerQuery); return ; } - const renderConfirmNotVerifyEmailButtonCond = - !eventType?.requiresBookerEmailVerification || (email && verifiedEmail && verifiedEmail === email); - return (
-1)} @@ -415,24 +100,14 @@ export const BookEventFormChild = ({ rescheduleUid={rescheduleUid || undefined} bookingData={bookingData} /> - {(createBookingMutation.isError || - createRecurringBookingMutation.isError || - createInstantBookingMutation.isError || - bookingForm.formState.errors["globalError"]) && ( + {(errors.hasFormErrors || errors.hasDataErrors) && (
)} @@ -451,7 +126,7 @@ export const BookEventFormChild = ({
{isInstantMeeting ? ( - ) : ( @@ -464,14 +139,7 @@ export const BookEventFormChild = ({
- { - setVerifiedEmail(email); - setEmailVerificationModalVisible(false); - bookEvent(bookingForm.getValues()); - }} - isUserSessionRequiredToVerify={false} - /> - + {children}
); }; -const RedirectToInstantMeetingModal = ({ expiryTime }: { expiryTime?: Date }) => { - const { t } = useLocale(); - const router = useRouter(); - const pathname = usePathname(); - const bookingId = parseInt(getQueryParam("bookingId") || "0"); - const hasInstantMeetingTokenExpired = expiryTime && new Date(expiryTime) < new Date(); - - const instantBooking = trpc.viewer.bookings.getInstantBookingLocation.useQuery( - { - bookingId: bookingId, - }, - { - enabled: !!bookingId && !hasInstantMeetingTokenExpired, - refetchInterval: 2000, - onSuccess: (data) => { - try { - showToast(t("something_went_wrong_on_our_end"), "error"); - - const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse( - data.booking?.metadata || {} - )?.videoCallUrl; - - if (locationVideoCallUrl) { - router.push(locationVideoCallUrl); - } else { - showToast(t("something_went_wrong_on_our_end"), "error"); - } - } catch (err) { - showToast(t("something_went_wrong_on_our_end"), "error"); - } - }, - } - ); - - return ( - - -
- {hasInstantMeetingTokenExpired ? ( -
-

{t("please_book_a_time_sometime_later")}

- -
- ) : ( -
-

{t("connecting_you_to_someone")}

- {/* TODO: Add countdown from 60 seconds - We are connecting you! - Please schedule a future call if we're not available in XX seconds. - */} - - {/* Once countdown ends: - Oops, we couldn't connect you this time. - Please schedule a future call instead. We value your time. - */} - -

{t("please_do_not_close_this_tab")}

-
-