fix: skip confirm step followup (#19076)

* Fix: Resolved double-click issue on timeSlot in Booker Atom

* fix: show toast on booking error

* fix: type error

* Prevent the automatic change of bookerState when all fields are filled.

* fix: when a user clicks on a new timeslot, any previously displayed "Confirm" button should be hidden

* Update useSkipConfirmStep.ts

* fix: remove 2 states for slots

* Update useSlotsForDate.ts

* fix types

* use common types

* fix: show VerifyCodeDialog and RedirectToInstantMeetingModal when skiping confirm step

* fix for instant bookings

---------

Co-authored-by: Udit Takkar <[email protected]>
This commit is contained in:
Somay ChauhanandUdit Takkar authored and GitHub committed 2025-02-21 19:07:54 +05:30
1 parent 07accf700e
commit 829bb63eb9
11 files changed
+174 -139

No files matched your search

+27 -27
View File
@@ -161,7 +161,12 @@ const BookerComponent = ({
} }
}; };
const skipConfirmStep = useSkipConfirmStep(bookingForm, event?.data?.bookingFields); const skipConfirmStep = useSkipConfirmStep(
bookingForm,
bookerState,
isInstantMeeting,
event?.data?.bookingFields
);
// Cloudflare Turnstile Captcha // Cloudflare Turnstile Captcha
const shouldRenderCaptcha = !!( const shouldRenderCaptcha = !!(
@@ -175,7 +180,8 @@ const BookerComponent = ({
useEffect(() => { useEffect(() => {
if (event.isPending) return setBookerState("loading"); if (event.isPending) return setBookerState("loading");
if (!selectedDate) return setBookerState("selecting_date"); if (!selectedDate) return setBookerState("selecting_date");
if (!selectedTimeslot || skipConfirmStep) return setBookerState("selecting_time"); if (!selectedTimeslot) return setBookerState("selecting_time");
if (selectedTimeslot && skipConfirmStep && !isInstantMeeting) return setBookerState("selecting_time");
return setBookerState("booking"); return setBookerState("booking");
}, [event, selectedDate, selectedTimeslot, setBookerState, skipConfirmStep]); }, [event, selectedDate, selectedTimeslot, setBookerState, skipConfirmStep]);
@@ -212,22 +218,6 @@ const BookerComponent = ({
isVerificationCodeSending={isVerificationCodeSending} isVerificationCodeSending={isVerificationCodeSending}
isPlatform={isPlatform}> isPlatform={isPlatform}>
<> <>
{verifyCode && formEmail ? (
<VerifyCodeDialog
isOpenDialog={isEmailVerificationModalVisible}
setIsOpenDialog={setEmailVerificationModalVisible}
email={formEmail}
isUserSessionRequiredToVerify={false}
verifyCodeWithSessionNotRequired={verifyCode.verifyCodeWithSessionNotRequired}
verifyCodeWithSessionRequired={verifyCode.verifyCodeWithSessionRequired}
error={verifyCode.error}
resetErrors={verifyCode.resetErrors}
isPending={verifyCode.isPending}
setIsPending={verifyCode.setIsPending}
/>
) : (
<></>
)}
{!isPlatform && ( {!isPlatform && (
<RedirectToInstantMeetingModal <RedirectToInstantMeetingModal
expiryTime={expiryTime} expiryTime={expiryTime}
@@ -253,26 +243,17 @@ const BookerComponent = ({
event, event,
expiryTime, expiryTime,
extraOptions, extraOptions,
formEmail,
formErrors, formErrors,
handleBookEvent, handleBookEvent,
handleVerifyEmail, handleVerifyEmail,
isEmailVerificationModalVisible,
key, key,
loadingStates, loadingStates,
onGoBackInstantMeeting, onGoBackInstantMeeting,
renderConfirmNotVerifyEmailButtonCond, renderConfirmNotVerifyEmailButtonCond,
rescheduleUid, rescheduleUid,
seatedEventData, seatedEventData,
setEmailVerificationModalVisible,
setSeatedEventData, setSeatedEventData,
setSelectedTimeslot, setSelectedTimeslot,
verifyCode?.error,
verifyCode?.isPending,
verifyCode?.resetErrors,
verifyCode?.setIsPending,
verifyCode?.verifyCodeWithSessionNotRequired,
verifyCode?.verifyCodeWithSessionRequired,
isPlatform, isPlatform,
shouldRenderCaptcha, shouldRenderCaptcha,
isVerificationCodeSending, isVerificationCodeSending,
@@ -532,6 +513,25 @@ const BookerComponent = ({
)} )}
</div> </div>
<>
{verifyCode && formEmail ? (
<VerifyCodeDialog
isOpenDialog={isEmailVerificationModalVisible}
setIsOpenDialog={setEmailVerificationModalVisible}
email={formEmail}
isUserSessionRequiredToVerify={false}
verifyCodeWithSessionNotRequired={verifyCode.verifyCodeWithSessionNotRequired}
verifyCodeWithSessionRequired={verifyCode.verifyCodeWithSessionRequired}
error={verifyCode.error}
resetErrors={verifyCode.resetErrors}
isPending={verifyCode.isPending}
setIsPending={verifyCode.setIsPending}
/>
) : (
<></>
)}
</>
<BookFormAsModal <BookFormAsModal
onCancel={() => setSelectedTimeslot(null)} onCancel={() => setSelectedTimeslot(null)}
visible={bookerState === "booking" && shouldShowFormInDialog}> visible={bookerState === "booking" && shouldShowFormInDialog}>
@@ -1,10 +1,11 @@
import { useRef } from "react"; import { useCallback, useMemo, useRef } from "react";
import dayjs from "@calcom/dayjs"; import dayjs from "@calcom/dayjs";
import { AvailableTimes, AvailableTimesSkeleton } from "@calcom/features/bookings"; import { AvailableTimes, AvailableTimesSkeleton } from "@calcom/features/bookings";
import type { IUseBookingLoadingStates } from "@calcom/features/bookings/Booker/components/hooks/useBookings"; import type { IUseBookingLoadingStates } from "@calcom/features/bookings/Booker/components/hooks/useBookings";
import type { BookerEvent } from "@calcom/features/bookings/types"; import type { BookerEvent } from "@calcom/features/bookings/types";
import { useNonEmptyScheduleDays } from "@calcom/features/schedules"; import { useNonEmptyScheduleDays } from "@calcom/features/schedules";
import type { Slot } from "@calcom/features/schedules";
import { useSlotsForAvailableDates } from "@calcom/features/schedules/lib/use-schedule/useSlotsForDate"; import { useSlotsForAvailableDates } from "@calcom/features/schedules/lib/use-schedule/useSlotsForDate";
import { classNames } from "@calcom/lib"; import { classNames } from "@calcom/lib";
import { BookerLayouts } from "@calcom/prisma/zod-utils"; import { BookerLayouts } from "@calcom/prisma/zod-utils";
@@ -12,6 +13,7 @@ import { BookerLayouts } from "@calcom/prisma/zod-utils";
import { AvailableTimesHeader } from "../../components/AvailableTimesHeader"; import { AvailableTimesHeader } from "../../components/AvailableTimesHeader";
import { useBookerStore } from "../store"; import { useBookerStore } from "../store";
import type { useScheduleForEventReturnType } from "../utils/event"; import type { useScheduleForEventReturnType } from "../utils/event";
import { getQueryParam } from "../utils/query-param";
type AvailableTimeSlotsProps = { type AvailableTimeSlotsProps = {
extraDays?: number; extraDays?: number;
@@ -55,10 +57,12 @@ export const AvailableTimeSlots = ({
isLoading, isLoading,
customClassNames, customClassNames,
skipConfirmStep, skipConfirmStep,
seatsPerTimeSlot,
onSubmit, onSubmit,
...props ...props
}: AvailableTimeSlotsProps) => { }: AvailableTimeSlotsProps) => {
const selectedDate = useBookerStore((state) => state.selectedDate); const selectedDate = useBookerStore((state) => state.selectedDate);
const setSelectedTimeslot = useBookerStore((state) => state.setSelectedTimeslot); const setSelectedTimeslot = useBookerStore((state) => state.setSelectedTimeslot);
const setSeatedEventData = useBookerStore((state) => state.setSeatedEventData); const setSeatedEventData = useBookerStore((state) => state.setSeatedEventData);
const date = selectedDate || dayjs().format("YYYY-MM-DD"); const date = selectedDate || dayjs().format("YYYY-MM-DD");
@@ -66,27 +70,6 @@ export const AvailableTimeSlots = ({
const isColumnView = layout === BookerLayouts.COLUMN_VIEW; const isColumnView = layout === BookerLayouts.COLUMN_VIEW;
const containerRef = useRef<HTMLDivElement | null>(null); const containerRef = useRef<HTMLDivElement | null>(null);
const onTimeSelect = (
time: string,
attendees: number,
seatsPerTimeSlot?: number | null,
bookingUid?: string
) => {
setSelectedTimeslot(time);
if (seatsPerTimeSlot) {
setSeatedEventData({
seatsPerTimeSlot,
attendees,
bookingUid,
showAvailableSeatsCount,
});
}
if (skipConfirmStep) {
onSubmit(time);
}
return;
};
const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.slots); const nonEmptyScheduleDays = useNonEmptyScheduleDays(schedule?.slots);
const nonEmptyScheduleDaysFromSelectedDate = nonEmptyScheduleDays.filter( const nonEmptyScheduleDaysFromSelectedDate = nonEmptyScheduleDays.filter(
(slot) => dayjs(selectedDate).diff(slot, "day") <= 0 (slot) => dayjs(selectedDate).diff(slot, "day") <= 0
@@ -94,13 +77,53 @@ export const AvailableTimeSlots = ({
// Creates an array of dates to fetch slots for. // Creates an array of dates to fetch slots for.
// If `extraDays` is passed in, we will extend the array with the next `extraDays` days. // If `extraDays` is passed in, we will extend the array with the next `extraDays` days.
const dates = !extraDays const dates = useMemo(() => {
? [date] if (!extraDays) return [date];
: nonEmptyScheduleDaysFromSelectedDate.length > 0 if (nonEmptyScheduleDaysFromSelectedDate.length > 0) {
? nonEmptyScheduleDaysFromSelectedDate.slice(0, extraDays) return nonEmptyScheduleDaysFromSelectedDate.slice(0, extraDays);
: []; }
return [];
}, [date, extraDays, nonEmptyScheduleDaysFromSelectedDate]);
const slotsPerDay = useSlotsForAvailableDates(dates, schedule?.slots); const { slotsPerDay, toggleConfirmButton } = useSlotsForAvailableDates(dates, schedule?.slots);
const overlayCalendarToggled =
getQueryParam("overlayCalendar") === "true" || localStorage.getItem("overlayCalendarSwitchDefault");
const onTimeSelect = useCallback(
(time: string, attendees: number, seatsPerTimeSlot?: number | null, bookingUid?: string) => {
setSelectedTimeslot(time);
if (seatsPerTimeSlot) {
setSeatedEventData({
seatsPerTimeSlot,
attendees,
bookingUid,
showAvailableSeatsCount,
});
}
if (skipConfirmStep) {
onSubmit(time);
}
return;
},
[onSubmit, setSeatedEventData, setSelectedTimeslot, skipConfirmStep, showAvailableSeatsCount]
);
const handleSlotClick = useCallback(
(selectedSlot: Slot, isOverlapping: boolean) => {
if ((overlayCalendarToggled && isOverlapping) || skipConfirmStep) {
toggleConfirmButton(selectedSlot);
} else {
onTimeSelect(
selectedSlot.time,
selectedSlot?.attendees || 0,
seatsPerTimeSlot,
selectedSlot.bookingUid
);
}
},
[overlayCalendarToggled, onTimeSelect, seatsPerTimeSlot, skipConfirmStep, toggleConfirmButton]
);
return ( return (
<> <>
@@ -150,6 +173,8 @@ export const AvailableTimeSlots = ({
slots={slots.slots} slots={slots.slots}
showAvailableSeatsCount={showAvailableSeatsCount} showAvailableSeatsCount={showAvailableSeatsCount}
skipConfirmStep={skipConfirmStep} skipConfirmStep={skipConfirmStep}
seatsPerTimeSlot={seatsPerTimeSlot}
handleSlotClick={handleSlotClick}
{...props} {...props}
/> />
</div> </div>
@@ -124,7 +124,6 @@ export const BookEventForm = ({
/> />
</div> </div>
)} )}
{/* Cloudflare Turnstile Captcha */}
{!isPlatform && ( {!isPlatform && (
<div className="text-subtle my-3 w-full text-xs"> <div className="text-subtle my-3 w-full text-xs">
<Trans <Trans
@@ -3,10 +3,14 @@ import { useState, useEffect } from "react";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm"; import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm";
import { useBookerStore } from "@calcom/features/bookings/Booker/store"; import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import { getBookingResponsesSchemaWithOptionalChecks } from "@calcom/features/bookings/lib/getBookingResponsesSchema"; import { getBookingResponsesSchemaWithOptionalChecks } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import type { BookerEvent } from "@calcom/features/bookings/types";
import type { BookerEvent } from "../../../types";
import type { BookerState } from "../../types";
const useSkipConfirmStep = ( const useSkipConfirmStep = (
bookingForm: UseBookingFormReturnType["bookingForm"], bookingForm: UseBookingFormReturnType["bookingForm"],
bookerState: BookerState,
isInstantMeeting: boolean,
bookingFields?: BookerEvent["bookingFields"] bookingFields?: BookerEvent["bookingFields"]
) => { ) => {
const bookingFormValues = bookingForm.getValues(); const bookingFormValues = bookingForm.getValues();
@@ -34,8 +38,8 @@ const useSkipConfirmStep = (
} }
}; };
checkSkipStep(); bookerState === "selecting_time" && !isInstantMeeting && checkSkipStep();
}, [bookingFormValues, bookingFields, rescheduleUid]); }, [bookingFormValues, bookingFields, rescheduleUid, bookerState]);
return canSkip; return canSkip;
}; };
@@ -1,7 +1,7 @@
// We do not need to worry about importing framer-motion here as it is lazy imported in Booker. // We do not need to worry about importing framer-motion here as it is lazy imported in Booker.
import * as HoverCard from "@radix-ui/react-hover-card"; import * as HoverCard from "@radix-ui/react-hover-card";
import { AnimatePresence, m } from "framer-motion"; import { AnimatePresence, m } from "framer-motion";
import { useCallback, useMemo, useState } from "react"; import { useMemo } from "react";
import { useIsPlatform } from "@calcom/atoms/monorepo"; import { useIsPlatform } from "@calcom/atoms/monorepo";
import type { IOutOfOfficeData } from "@calcom/core/getUserAvailability"; import type { IOutOfOfficeData } from "@calcom/core/getUserAvailability";
@@ -9,7 +9,7 @@ import dayjs from "@calcom/dayjs";
import { OutOfOfficeInSlots } from "@calcom/features/bookings/Booker/components/OutOfOfficeInSlots"; import { OutOfOfficeInSlots } from "@calcom/features/bookings/Booker/components/OutOfOfficeInSlots";
import type { IUseBookingLoadingStates } from "@calcom/features/bookings/Booker/components/hooks/useBookings"; import type { IUseBookingLoadingStates } from "@calcom/features/bookings/Booker/components/hooks/useBookings";
import type { BookerEvent } from "@calcom/features/bookings/types"; import type { BookerEvent } from "@calcom/features/bookings/types";
import type { Slots } from "@calcom/features/schedules"; import type { Slot } from "@calcom/features/schedules";
import { classNames } from "@calcom/lib"; import { classNames } from "@calcom/lib";
import { getPaymentAppData } from "@calcom/lib/getPaymentAppData"; import { getPaymentAppData } from "@calcom/lib/getPaymentAppData";
import { useLocale } from "@calcom/lib/hooks/useLocale"; import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -37,7 +37,7 @@ export type AvailableTimesProps = {
} & Omit<SlotItemProps, "slot">; } & Omit<SlotItemProps, "slot">;
type SlotItemProps = { type SlotItemProps = {
slot: Slots[string][number]; slot: Slot;
seatsPerTimeSlot?: number | null; seatsPerTimeSlot?: number | null;
selectedSlots?: string[]; selectedSlots?: string[];
onTimeSelect: TOnTimeSelect; onTimeSelect: TOnTimeSelect;
@@ -52,6 +52,7 @@ type SlotItemProps = {
skipConfirmStep?: boolean; skipConfirmStep?: boolean;
shouldRenderCaptcha?: boolean; shouldRenderCaptcha?: boolean;
watchedCfToken?: string; watchedCfToken?: string;
handleSlotClick?: (slot: Slot, isOverlapping: boolean) => void;
}; };
const SlotItem = ({ const SlotItem = ({
@@ -68,6 +69,7 @@ const SlotItem = ({
skipConfirmStep, skipConfirmStep,
shouldRenderCaptcha, shouldRenderCaptcha,
watchedCfToken, watchedCfToken,
handleSlotClick,
}: SlotItemProps) => { }: SlotItemProps) => {
const { t } = useLocale(); const { t } = useLocale();
@@ -106,26 +108,6 @@ const SlotItem = ({
offset, offset,
}); });
const [showConfirm, setShowConfirm] = useState(false);
const onButtonClick = useCallback(() => {
if (!showConfirm && ((overlayCalendarToggled && isOverlapping) || skipConfirmStep)) {
setShowConfirm(true);
return;
}
onTimeSelect(slot.time, slot?.attendees || 0, seatsPerTimeSlot, slot.bookingUid);
}, [
overlayCalendarToggled,
isOverlapping,
showConfirm,
onTimeSelect,
slot.time,
slot?.attendees,
slot.bookingUid,
seatsPerTimeSlot,
skipConfirmStep,
]);
return ( return (
<AnimatePresence> <AnimatePresence>
<div className="flex gap-2"> <div className="flex gap-2">
@@ -143,7 +125,7 @@ const SlotItem = ({
data-testid="time" data-testid="time"
data-disabled={bookingFull} data-disabled={bookingFull}
data-time={slot.time} data-time={slot.time}
onClick={onButtonClick} onClick={() => handleSlotClick && handleSlotClick(slot, isOverlapping)}
className={classNames( className={classNames(
`hover:border-brand-default min-h-9 mb-2 flex h-auto w-full flex-grow flex-col justify-center py-2`, `hover:border-brand-default min-h-9 mb-2 flex h-auto w-full flex-grow flex-col justify-center py-2`,
selectedSlots?.includes(slot.time) && "border-brand-default", selectedSlots?.includes(slot.time) && "border-brand-default",
@@ -176,47 +158,40 @@ const SlotItem = ({
</p> </p>
)} )}
</Button> </Button>
{showConfirm && ( {!!slot.showConfirmButton && (
<HoverCard.Root> <HoverCard.Root>
<HoverCard.Trigger asChild> <HoverCard.Trigger asChild>
<m.div initial={{ width: 0 }} animate={{ width: "auto" }} exit={{ width: 0 }}> <m.div key={slot.time} initial={{ width: 0 }} animate={{ width: "auto" }} exit={{ width: 0 }}>
{skipConfirmStep ? ( <Button
<Button variant={layout === "column_view" ? "icon" : "button"}
type="button" StartIcon={layout === "column_view" ? "chevron-right" : undefined}
onClick={() => type="button"
onTimeSelect(slot.time, slot?.attendees || 0, seatsPerTimeSlot, slot.bookingUid) onClick={() =>
} onTimeSelect(slot.time, slot?.attendees || 0, seatsPerTimeSlot, slot.bookingUid)
data-testid="skip-confirm-book-button" }
disabled={ data-testid="skip-confirm-book-button"
(!!shouldRenderCaptcha && !watchedCfToken) || disabled={
loadingStates?.creatingBooking || (!!shouldRenderCaptcha && !watchedCfToken) ||
loadingStates?.creatingRecurringBooking || loadingStates?.creatingBooking ||
isVerificationCodeSending || loadingStates?.creatingRecurringBooking ||
loadingStates?.creatingInstantBooking isVerificationCodeSending ||
} loadingStates?.creatingInstantBooking
color="primary" }
loading={ color="primary"
(selectedTimeslot === slot.time && loadingStates?.creatingBooking) || loading={
loadingStates?.creatingRecurringBooking || (selectedTimeslot === slot.time && loadingStates?.creatingBooking) ||
isVerificationCodeSending || loadingStates?.creatingRecurringBooking ||
loadingStates?.creatingInstantBooking isVerificationCodeSending ||
}> loadingStates?.creatingInstantBooking
{renderConfirmNotVerifyEmailButtonCond }>
? isPaidEvent {layout == "column_view"
? t("pay_and_book") ? ""
: t("confirm") : renderConfirmNotVerifyEmailButtonCond
: t("verify_email_email_button")} ? isPaidEvent
</Button> ? t("pay_and_book")
) : ( : t("confirm")
<Button : t("verify_email_email_button")}
variant={layout === "column_view" ? "icon" : "button"} </Button>
StartIcon={layout === "column_view" ? "chevron-right" : undefined}
onClick={() =>
onTimeSelect(slot.time, slot?.attendees || 0, seatsPerTimeSlot, slot.bookingUid)
}>
{layout !== "column_view" && t("confirm")}
</Button>
)}
</m.div> </m.div>
</HoverCard.Trigger> </HoverCard.Trigger>
{isOverlapping && ( {isOverlapping && (
+1 -1
View File
@@ -1,3 +1,3 @@
export * from "./components"; export * from "./components";
export type { Slots } from "./lib/use-schedule"; export type { Slots, Slot } from "./lib/use-schedule";
export { useSchedule, useSlotsForDate, useNonEmptyScheduleDays } from "./lib/use-schedule"; export { useSchedule, useSlotsForDate, useNonEmptyScheduleDays } from "./lib/use-schedule";
@@ -1,4 +1,4 @@
export { useSchedule } from "./useSchedule"; export { useSchedule } from "./useSchedule";
export { useSlotsForDate } from "./useSlotsForDate"; export { useSlotsForDate } from "./useSlotsForDate";
export { useNonEmptyScheduleDays } from "./useNonEmptyScheduleDays"; export { useNonEmptyScheduleDays } from "./useNonEmptyScheduleDays";
export type { Slots, GetSchedule } from "./types"; export type { Slots, GetSchedule, Slot } from "./types";
@@ -2,4 +2,6 @@ import type { RouterOutputs } from "@calcom/trpc/react";
export type Slots = RouterOutputs["viewer"]["public"]["slots"]["getSchedule"]["slots"]; export type Slots = RouterOutputs["viewer"]["public"]["slots"]["getSchedule"]["slots"];
export type Slot = Slots[string][number] & { showConfirmButton?: boolean };
export type GetSchedule = RouterOutputs["viewer"]["public"]["slots"]["getSchedule"]; export type GetSchedule = RouterOutputs["viewer"]["public"]["slots"]["getSchedule"];
@@ -1,6 +1,6 @@
import { useMemo } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import type { Slots } from "./types"; import type { Slots, Slot } from "./types";
/** /**
* Gets slots for a specific date from the schedule cache. * Gets slots for a specific date from the schedule cache.
@@ -18,14 +18,35 @@ export const useSlotsForDate = (date: string | null, slots?: Slots) => {
}; };
export const useSlotsForAvailableDates = (dates: (string | null)[], slots?: Slots) => { export const useSlotsForAvailableDates = (dates: (string | null)[], slots?: Slots) => {
const slotsForDates = useMemo(() => { const [slotsPerDay, setSlotsPerDay] = useState<{ date: string | null; slots: Slots[string] }[]>([]);
if (slots === undefined) return [];
return dates const toggleConfirmButton = useCallback((selectedSlot: Slot) => {
setSlotsPerDay((prevSlotsPerDay) =>
prevSlotsPerDay.map(({ date, slots }) => ({
date,
slots: slots.map((slot) => ({
...slot,
showConfirmButton: slot.time === selectedSlot.time ? !selectedSlot?.showConfirmButton : false,
})),
}))
);
}, []);
useEffect(() => {
if (slots === undefined) {
setSlotsPerDay([]);
return;
}
const updatedSlots = dates
.filter((date) => date !== null) .filter((date) => date !== null)
.map((date) => ({ .map((date) => ({
slots: slots[`${date}`] || [], slots: slots[`${date}`] || [],
date, date,
})); }));
}, [dates, slots]);
return slotsForDates; setSlotsPerDay(updatedSlots);
}, [JSON.stringify(dates), JSON.stringify(slots)]);
return { slotsPerDay, setSlotsPerDay, toggleConfirmButton } as const;
}; };
@@ -521,8 +521,8 @@ export const BookerPlatformWrapper = (
onOverlaySwitchStateChange={onOverlaySwitchStateChange} onOverlaySwitchStateChange={onOverlaySwitchStateChange}
extraOptions={extraOptions ?? {}} extraOptions={extraOptions ?? {}}
bookings={{ bookings={{
handleBookEvent: () => { handleBookEvent: (timeSlot?: string) => {
handleBookEvent(); handleBookEvent(timeSlot);
return; return;
}, },
expiryTime: undefined, expiryTime: undefined,
@@ -1,3 +1,4 @@
import { useIsPlatform } from "@calcom/atoms/monorepo";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime"; import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm"; import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm";
import { useBookerStore } from "@calcom/features/bookings/Booker/store"; import { useBookerStore } from "@calcom/features/bookings/Booker/store";
@@ -7,9 +8,11 @@ import type { BookerEvent } from "@calcom/features/bookings/types";
import { useLocale } from "@calcom/lib/hooks/useLocale"; import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RoutingFormSearchParams } from "@calcom/platform-types"; import type { RoutingFormSearchParams } from "@calcom/platform-types";
import type { BookingCreateBody } from "@calcom/prisma/zod-utils"; import type { BookingCreateBody } from "@calcom/prisma/zod-utils";
import { showToast } from "@calcom/ui";
import type { UseCreateBookingInput } from "./useCreateBooking"; import type { UseCreateBookingInput } from "./useCreateBooking";
type Callbacks = { onSuccess?: () => void; onError?: (err: any) => void };
type UseHandleBookingProps = { type UseHandleBookingProps = {
bookingForm: UseBookingFormReturnType["bookingForm"]; bookingForm: UseBookingFormReturnType["bookingForm"];
event?: { event?: {
@@ -20,9 +23,9 @@ type UseHandleBookingProps = {
}; };
metadata: Record<string, string>; metadata: Record<string, string>;
hashedLink?: string | null; hashedLink?: string | null;
handleBooking: (input: UseCreateBookingInput) => void; handleBooking: (input: UseCreateBookingInput, callbacks?: Callbacks) => void;
handleInstantBooking: (input: BookingCreateBody) => void; handleInstantBooking: (input: BookingCreateBody, callbacks?: Callbacks) => void;
handleRecBooking: (input: BookingCreateBody[]) => void; handleRecBooking: (input: BookingCreateBody[], callbacks?: Callbacks) => void;
locationUrl?: string; locationUrl?: string;
routingFormSearchParams?: RoutingFormSearchParams; routingFormSearchParams?: RoutingFormSearchParams;
}; };
@@ -38,6 +41,7 @@ export const useHandleBookEvent = ({
locationUrl, locationUrl,
routingFormSearchParams, routingFormSearchParams,
}: UseHandleBookingProps) => { }: UseHandleBookingProps) => {
const isPlatform = useIsPlatform();
const setFormValues = useBookerStore((state) => state.setFormValues); const setFormValues = useBookerStore((state) => state.setFormValues);
const storeTimeSlot = useBookerStore((state) => state.selectedTimeslot); const storeTimeSlot = useBookerStore((state) => state.selectedTimeslot);
const duration = useBookerStore((state) => state.selectedDuration); const duration = useBookerStore((state) => state.selectedDuration);
@@ -54,10 +58,15 @@ export const useHandleBookEvent = ({
const teamMemberEmail = useBookerStore((state) => state.teamMemberEmail); const teamMemberEmail = useBookerStore((state) => state.teamMemberEmail);
const crmOwnerRecordType = useBookerStore((state) => state.crmOwnerRecordType); const crmOwnerRecordType = useBookerStore((state) => state.crmOwnerRecordType);
const crmAppSlug = useBookerStore((state) => state.crmAppSlug); const crmAppSlug = useBookerStore((state) => state.crmAppSlug);
const handleError = (err: any) => {
const errorMessage = err?.message ? t(err.message) : t("can_you_try_again");
showToast(errorMessage, "error");
};
const handleBookEvent = (inputTimeSlot?: string) => { const handleBookEvent = (inputTimeSlot?: string) => {
const values = bookingForm.getValues(); const values = bookingForm.getValues();
const timeslot = inputTimeSlot ?? storeTimeSlot; const timeslot = inputTimeSlot ?? storeTimeSlot;
const callbacks = inputTimeSlot && !isPlatform ? { onError: handleError } : undefined;
if (timeslot) { if (timeslot) {
// Clears form values stored in store, so old values won't stick around. // Clears form values stored in store, so old values won't stick around.
setFormValues({}); setFormValues({});
@@ -101,11 +110,11 @@ export const useHandleBookEvent = ({
}; };
if (isInstantMeeting) { if (isInstantMeeting) {
handleInstantBooking(mapBookingToMutationInput(bookingInput)); handleInstantBooking(mapBookingToMutationInput(bookingInput), callbacks);
} else if (event.data?.recurringEvent?.freq && recurringEventCount && !rescheduleUid) { } else if (event.data?.recurringEvent?.freq && recurringEventCount && !rescheduleUid) {
handleRecBooking(mapRecurringBookingToMutationInput(bookingInput, recurringEventCount)); handleRecBooking(mapRecurringBookingToMutationInput(bookingInput, recurringEventCount), callbacks);
} else { } else {
handleBooking({ ...mapBookingToMutationInput(bookingInput), locationUrl }); handleBooking({ ...mapBookingToMutationInput(bookingInput), locationUrl }, callbacks);
} }
// Clears form values stored in store, so old values won't stick around. // Clears form values stored in store, so old values won't stick around.
setFormValues({}); setFormValues({});