refactor: move Booker hooks from packages/features to apps/web/modules (#27343)

* refactor: move Booker hooks from packages/features to apps/web/modules

Migrate the following Booker hooks:
- useOverlayCalendar
- useSkipConfirmStep
- useInitializeWeekStart
- useIsQuickAvailabilityCheckFeatureEnabled
- useDecoyBooking

These hooks are only imported by apps/web files, making them safe to move
without creating circular dependencies.

Part of the tRPC-driven UI migration from packages/features to apps/web/modules.

Co-Authored-By: [email protected] <[email protected]>

* fix: revert useIsQuickAvailabilityCheckFeatureEnabled move and fix import paths

- Reverted useIsQuickAvailabilityCheckFeatureEnabled.ts back to packages/features since it's imported by useSlots.ts in packages/features (would create circular dependency)
- Fixed import paths in useOverlayCalendar.ts to use @calcom/features paths
- Fixed import paths in useSkipConfirmStep.ts to use @calcom/features paths
- Updated Booker.tsx to import useIsQuickAvailabilityCheckFeatureEnabled from original location

Co-Authored-By: [email protected] <[email protected]>

* fix: use @calcom/web alias for hook imports to fix vitest resolution

Co-Authored-By: [email protected] <[email protected]>

* refactor

* migrate more hooks

* fix

* mv types

* fix

* fix

* fix

* fix

* revert: remove formatting-only changes to make PR easier to review

Co-Authored-By: [email protected] <[email protected]>

* fix

* fix

* fix

* revert: restore original import ordering in moved hooks

Co-Authored-By: [email protected] <[email protected]>

* fix imports

* fix

* fix

* wip

* wip

* wip

* wip

* wip

* wip

* fix: add isBrowser guard to useSlotsViewOnSmallScreen hook

Address Cubic AI review feedback (confidence 9/10) by adding the isBrowser
guard to the useSlotsViewOnSmallScreen hook to follow the file's client-only
contract and avoid executing during SSR/prerendering.

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-01-31 07:33:33 -03:00
1 parent 5476c38f3b
commit 73f51920c5
46 files changed
+214 -214

No files matched your search

@@ -33,7 +33,7 @@ import type {
setNonStylesConfig,
} from "./types";
import { useCompatSearchParams } from "./useCompatSearchParams";
export { useBookerEmbedEvents } from "./embed-iframe/react-hooks";
export { useBookerEmbedEvents, useSlotsViewOnSmallScreen } from "./embed-iframe/react-hooks";
// We don't import it from Booker/types because the types from this module are published to npm and we can't import packages that aren't published
type BookerState = "loading" | "selecting_date" | "selecting_time" | "booking";
@@ -3,7 +3,9 @@
* All hooks defined in this file must be client side hooks and must not be executed in server side.
* So, they should start with isBrowser check.
*/
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import { sdkActionManager } from "../sdk-event";
import { useEmbedUiConfig, useIsEmbed } from "../embed-iframe";
import { embedStore, getEventHasFired, setEventHasFired, getReloadInitiated, setReloadInitiated } from "./lib/embedStore";
import { isBrowser, isPrerendering } from "./lib/utils";
@@ -114,3 +116,13 @@ export const useBookerEmbedEvents = ({
}
};
export const useSlotsViewOnSmallScreen = () => {
const isEmbed = useIsEmbed();
const isMobile = useMediaQuery("(max-width: 768px)");
const embedUiConfig = useEmbedUiConfig();
if (!isBrowser || !isEmbed || !isMobile) return false;
return embedUiConfig.useSlotsViewOnSmallScreen ?? false;
};
@@ -1,583 +0,0 @@
"use client";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useRef, useState, useEffect } from "react";
import { shallow } from "zustand/shallow";
import { createPaymentLink } from "@calcom/app-store/stripepayment/lib/client";
import { useHandleBookEvent } from "@calcom/atoms/hooks/bookings/useHandleBookEvent";
import dayjs from "@calcom/dayjs";
import { sdkActionManager } from "@calcom/embed-core/embed-iframe";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { updateQueryParam, getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import { storeDecoyBooking } from "@calcom/features/bookings/lib/client/decoyBookingStore";
import { createBooking } from "@calcom/features/bookings/lib/create-booking";
import { createInstantBooking } from "@calcom/features/bookings/lib/create-instant-booking";
import { createRecurringBooking } from "@calcom/features/bookings/lib/create-recurring-booking";
import type { GetBookingType } from "@calcom/features/bookings/lib/get-booking";
import type { BookerEvent } from "@calcom/features/bookings/types";
import { getFullName } from "@calcom/features/form-builder/utils";
import { ErrorCode } from "@calcom/lib/errorCodes";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localStorage } from "@calcom/lib/webstorage";
import { BookingStatus } from "@calcom/prisma/enums";
import { bookingMetadataSchema } from "@calcom/prisma/zod-utils";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
import { useBookingSuccessRedirect } from "../../../lib/bookingSuccessRedirect";
import type { UseBookingFormReturnType } from "./useBookingForm";
export interface IUseBookings {
event: {
data?:
| (Pick<
BookerEvent,
| "id"
| "slug"
| "subsetOfHosts"
| "requiresConfirmation"
| "isDynamic"
| "metadata"
| "forwardParamsSuccessRedirect"
| "successRedirectUrl"
| "length"
| "recurringEvent"
| "schedulingType"
> & {
subsetOfUsers: Pick<
BookerEvent["subsetOfUsers"][number],
"name" | "username" | "avatarUrl" | "weekStart" | "profile" | "bookerUrl"
>[];
})
| null;
};
hashedLink?: string | null;
bookingForm: UseBookingFormReturnType["bookingForm"];
metadata: Record<string, string>;
teamMemberEmail?: string | null;
isBookingDryRun?: boolean;
}
const getBaseBookingEventPayload = (booking: {
title?: string;
startTime: string;
endTime: string;
eventTypeId?: number | null;
status?: BookingStatus;
paymentRequired: boolean;
isRecurring: boolean;
videoCallUrl?: string;
}) => {
return {
title: booking.title,
startTime: booking.startTime,
endTime: booking.endTime,
eventTypeId: booking.eventTypeId,
status: booking.status,
paymentRequired: booking.paymentRequired,
isRecurring: booking.isRecurring,
videoCallUrl: booking.videoCallUrl,
};
};
const getBookingSuccessfulEventPayload = (booking: {
title?: string;
startTime: string;
endTime: string;
eventTypeId?: number | null;
status?: BookingStatus;
paymentRequired: boolean;
uid?: string;
isRecurring: boolean;
videoCallUrl?: string;
}) => {
return {
uid: booking.uid,
...getBaseBookingEventPayload(booking),
};
};
const getRescheduleBookingSuccessfulEventPayload = getBookingSuccessfulEventPayload;
export const getDryRunBookingSuccessfulEventPayload = getBaseBookingEventPayload;
export const getDryRunRescheduleBookingSuccessfulEventPayload = getDryRunBookingSuccessfulEventPayload;
export interface IUseBookingLoadingStates {
creatingBooking: boolean;
creatingRecurringBooking: boolean;
creatingInstantBooking: boolean;
}
export interface IUseBookingErrors {
hasDataErrors: boolean;
dataErrors: unknown;
}
export type UseBookingsReturnType = ReturnType<typeof useBookings>;
const STORAGE_KEY = "instantBookingData";
const COOLDOWN_STORAGE_KEY = "instantBookingCooldownByEvent";
const COOLDOWN_WINDOW_MS = 10 * 60 * 1000; // 10 minutes
type InstantBookingCooldownMap = Record<string, number>;
const readInstantCooldownMap = (): InstantBookingCooldownMap => {
try {
const raw = localStorage.getItem(COOLDOWN_STORAGE_KEY);
return raw ? (JSON.parse(raw) as InstantBookingCooldownMap) : {};
} catch {
return {};
}
};
const writeInstantCooldownMap = (map: InstantBookingCooldownMap) => {
try {
localStorage.setItem(COOLDOWN_STORAGE_KEY, JSON.stringify(map));
} catch {
// don't do anything
}
};
const getInstantCooldownRemainingMs = (eventTypeId?: number | null): number => {
if (!eventTypeId) return 0;
const map = readInstantCooldownMap();
const lastTs = map[String(eventTypeId)];
if (!lastTs) return 0;
const remaining = lastTs + COOLDOWN_WINDOW_MS - Date.now();
return remaining > 0 ? remaining : 0;
};
const setInstantCooldownNow = (eventTypeId?: number | null) => {
if (!eventTypeId) return;
const map = readInstantCooldownMap();
map[String(eventTypeId)] = Date.now();
writeInstantCooldownMap(map);
};
const storeInLocalStorage = ({
eventTypeId,
expiryTime,
bookingId,
}: {
eventTypeId: number;
expiryTime: Date;
bookingId: number;
}) => {
const value = JSON.stringify({ eventTypeId, expiryTime, bookingId });
localStorage.setItem(STORAGE_KEY, value);
};
export const useBookings = ({ event, hashedLink, bookingForm, metadata, isBookingDryRun }: IUseBookings) => {
const router = useRouter();
const eventSlug = useBookerStoreContext((state) => state.eventSlug);
const eventTypeId = useBookerStoreContext((state) => state.eventId);
const isInstantMeeting = useBookerStoreContext((state) => state.isInstantMeeting);
const [rescheduleUid, setRescheduleUid] = useBookerStoreContext(
(state) => [state.rescheduleUid, state.setRescheduleUid],
shallow
);
const rescheduledBy = useBookerStoreContext((state) => state.rescheduledBy);
const [bookingData, setBookingData] = useBookerStoreContext(
(state) => [state.bookingData, state.setBookingData],
shallow
);
const timeslot = useBookerStoreContext((state) => state.selectedTimeslot);
const { t } = useLocale();
const bookingSuccessRedirect = useBookingSuccessRedirect();
const bookerFormErrorRef = useRef<HTMLDivElement>(null);
const [instantMeetingTokenExpiryTime, setExpiryTime] = useState<Date | undefined>();
const [instantVideoMeetingUrl, setInstantVideoMeetingUrl] = useState<string | undefined>();
const duration = useBookerStoreContext((state) => state.selectedDuration);
const isRescheduling = !!rescheduleUid && !!bookingData;
const bookingId = parseInt(getQueryParam("bookingId") ?? "0");
useEffect(() => {
if (!isInstantMeeting) return;
const storedInfo = localStorage.getItem(STORAGE_KEY);
if (storedInfo) {
const parsedInfo = JSON.parse(storedInfo);
const parsedInstantBookingInfo =
parsedInfo.eventTypeId === eventTypeId &&
isInstantMeeting &&
new Date(parsedInfo.expiryTime) > new Date()
? parsedInfo
: null;
if (parsedInstantBookingInfo) {
setExpiryTime(parsedInstantBookingInfo.expiryTime);
updateQueryParam("bookingId", parsedInstantBookingInfo.bookingId);
}
}
}, [eventTypeId, isInstantMeeting]);
const instantConnectCooldownMs = getInstantCooldownRemainingMs(eventTypeId);
const _instantBooking = trpc.viewer.bookings.getInstantBookingLocation.useQuery(
{
bookingId: bookingId,
},
{
enabled: !!bookingId,
refetchInterval: 2000,
refetchIntervalInBackground: true,
}
);
useEffect(
function refactorMeWithoutEffect() {
const data = _instantBooking.data;
if (!data || !data.booking) return;
try {
const locationVideoCallUrl: string | undefined = bookingMetadataSchema.parse(
data.booking?.metadata || {}
)?.videoCallUrl;
if (locationVideoCallUrl) {
setInstantVideoMeetingUrl(locationVideoCallUrl);
} else {
showToast(t("something_went_wrong_on_our_end"), "error");
}
} catch {
showToast(t("something_went_wrong_on_our_end"), "error");
}
},
[_instantBooking.data]
);
const createBookingMutation = useMutation({
mutationFn: createBooking,
onSuccess: (booking) => {
if (booking.isDryRun) {
if (isRescheduling) {
sdkActionManager?.fire(
"dryRunRescheduleBookingSuccessfulV2",
getDryRunRescheduleBookingSuccessfulEventPayload({
...booking,
isRecurring: false,
})
);
} else {
sdkActionManager?.fire(
"dryRunBookingSuccessfulV2",
getDryRunBookingSuccessfulEventPayload({
...booking,
isRecurring: false,
})
);
}
router.push("/booking/dry-run-successful");
return;
}
if ("isShortCircuitedBooking" in booking && booking.isShortCircuitedBooking) {
if (!booking.uid) {
console.error("Decoy booking missing uid");
return;
}
const bookingData = {
uid: booking.uid,
title: booking.title ?? null,
startTime: booking.startTime,
endTime: booking.endTime,
booker: booking.attendees?.[0] ?? null,
host: booking.user ?? null,
location: booking.location ?? null,
};
storeDecoyBooking(bookingData);
router.push(`/booking-successful/${booking.uid}`);
return;
}
const { uid, paymentUid } = booking;
const fullName = getFullName(bookingForm.getValues("responses.name"));
const users = event.data?.subsetOfHosts?.length
? event.data?.subsetOfHosts.map((host) => host.user)
: event.data?.subsetOfUsers;
const validDuration = event.data?.isDynamic
? duration || event.data?.length
: duration && event.data?.metadata?.multipleDuration?.includes(duration)
? duration
: event.data?.length;
if (isRescheduling) {
sdkActionManager?.fire("rescheduleBookingSuccessful", {
booking: booking,
eventType: event.data,
date: booking?.startTime?.toString() || "",
duration: validDuration,
organizer: {
name: users?.[0]?.name || "Nameless",
email: booking?.userPrimaryEmail || booking.user?.email || "Email-less",
timeZone: booking.user?.timeZone || "Europe/London",
},
confirmed: !(booking.status === BookingStatus.PENDING && event.data?.requiresConfirmation),
});
sdkActionManager?.fire(
"rescheduleBookingSuccessfulV2",
getRescheduleBookingSuccessfulEventPayload({
...booking,
isRecurring: false,
})
);
} else {
sdkActionManager?.fire("bookingSuccessful", {
booking: booking,
eventType: event.data,
date: booking?.startTime?.toString() || "",
duration: validDuration,
organizer: {
name: users?.[0]?.name || "Nameless",
email: booking?.userPrimaryEmail || booking.user?.email || "Email-less",
timeZone: booking.user?.timeZone || "Europe/London",
},
confirmed: !(booking.status === BookingStatus.PENDING && event.data?.requiresConfirmation),
});
sdkActionManager?.fire(
"bookingSuccessfulV2",
getBookingSuccessfulEventPayload({
...booking,
isRecurring: false,
})
);
}
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 booking ? (booking.seatReferenceUid as string) : null,
formerTime:
isRescheduling && bookingData?.startTime ? dayjs(bookingData.startTime).toString() : undefined,
rescheduledBy, // ensure further reschedules performed on the success page are recorded correctly
};
bookingSuccessRedirect({
successRedirectUrl: event?.data?.successRedirectUrl || "",
query,
booking: booking,
forwardParamsSuccessRedirect:
event?.data?.forwardParamsSuccessRedirect === undefined
? true
: event?.data?.forwardParamsSuccessRedirect,
});
},
onError: (err) => {
if (bookerFormErrorRef?.current) {
bookerFormErrorRef.current.scrollIntoView({ behavior: "smooth" });
}
const error = err as Error & {
data: { rescheduleUid: string; startTime: string; attendees: string[]; seatUid?: string };
traceId?: string;
};
if (error.message === ErrorCode.BookerLimitExceededReschedule && error.data?.rescheduleUid) {
setRescheduleUid(error.data?.seatUid ?? error.data?.rescheduleUid);
setBookingData({
uid: error.data?.rescheduleUid,
startTime: error.data?.startTime,
attendees: error.data?.attendees,
} as unknown as GetBookingType);
}
},
});
const createInstantBookingMutation = useMutation({
mutationFn: createInstantBooking,
onSuccess: (responseData) => {
if (eventTypeId) {
storeInLocalStorage({
eventTypeId,
expiryTime: responseData.expires,
bookingId: responseData.bookingId,
});
setInstantCooldownNow(eventTypeId);
}
updateQueryParam("bookingId", responseData.bookingId);
setExpiryTime(responseData.expires);
},
onError: (err) => {
console.error("Error creating instant booking", err);
if (bookerFormErrorRef?.current) {
bookerFormErrorRef.current.scrollIntoView({ behavior: "smooth" });
}
},
});
const createRecurringBookingMutation = useMutation({
mutationFn: createRecurringBooking,
onSuccess: async (bookings) => {
const booking = bookings[0] || {};
if (booking.isDryRun) {
if (isRescheduling) {
sdkActionManager?.fire("dryRunRescheduleBookingSuccessfulV2", {
...getDryRunRescheduleBookingSuccessfulEventPayload({
...booking,
isRecurring: true,
}),
allBookings: bookings.map((booking) => ({
startTime: booking.startTime,
endTime: booking.endTime,
})),
});
} else {
sdkActionManager?.fire("dryRunBookingSuccessfulV2", {
...getDryRunBookingSuccessfulEventPayload({
...booking,
isRecurring: true,
}),
allBookings: bookings.map((booking) => ({
startTime: booking.startTime,
endTime: booking.endTime,
})),
});
}
router.push("/booking/dry-run-successful");
return;
}
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,
};
if (isRescheduling) {
// NOTE: It is recommended to define the event payload in the argument itself to provide a better type safety.
sdkActionManager?.fire("rescheduleBookingSuccessfulV2", {
...getRescheduleBookingSuccessfulEventPayload({
...booking,
isRecurring: true,
}),
allBookings: bookings.map((booking) => ({
startTime: booking.startTime,
endTime: booking.endTime,
})),
});
} else {
sdkActionManager?.fire("bookingSuccessfulV2", {
...getBookingSuccessfulEventPayload({
...booking,
isRecurring: true,
}),
allBookings: bookings.map((booking) => ({
startTime: booking.startTime,
endTime: booking.endTime,
})),
});
}
bookingSuccessRedirect({
successRedirectUrl: event?.data?.successRedirectUrl || "",
query,
booking,
forwardParamsSuccessRedirect:
event?.data?.forwardParamsSuccessRedirect === undefined
? true
: event?.data?.forwardParamsSuccessRedirect,
});
},
onError: (err, _, ctx) => {
console.error("Error creating recurring booking", err);
// eslint-disable-next-line @calcom/eslint/no-scroll-into-view-embed -- It is only called when user takes an action in embed
bookerFormErrorRef && bookerFormErrorRef.current?.scrollIntoView({ behavior: "smooth" });
},
});
const handleBookEvent = useHandleBookEvent({
event,
bookingForm,
hashedLink,
metadata,
handleInstantBooking: (variables: Parameters<typeof createInstantBookingMutation.mutate>[0]) => {
const remaining = getInstantCooldownRemainingMs(eventTypeId);
if (remaining > 0) {
showToast(
t("please_try_again_later_or_book_another_slot", { remaining: Math.ceil(remaining / 60000) }),
"error"
);
return;
}
createInstantBookingMutation.mutate(variables);
},
handleRecBooking: createRecurringBookingMutation.mutate,
handleBooking: createBookingMutation.mutate,
isBookingDryRun,
});
const errors = {
hasDataErrors: Boolean(
createBookingMutation.isError ||
createRecurringBookingMutation.isError ||
createInstantBookingMutation.isError
),
dataErrors:
createBookingMutation.error ||
createRecurringBookingMutation.error ||
createInstantBookingMutation.error,
};
// A redirect is triggered on mutation success, so keep the loading state while it is happening.
const loadingStates = {
creatingBooking: createBookingMutation.isPending || createBookingMutation.isSuccess,
creatingRecurringBooking:
createRecurringBookingMutation.isPending || createRecurringBookingMutation.isSuccess,
creatingInstantBooking: createInstantBookingMutation.isPending,
};
return {
handleBookEvent,
expiryTime: instantMeetingTokenExpiryTime,
bookingForm,
bookerFormErrorRef,
errors,
loadingStates,
instantVideoMeetingUrl,
instantConnectCooldownMs,
};
};
@@ -1,72 +0,0 @@
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { localStorage } from "@calcom/lib/webstorage";
import { trpc } from "@calcom/trpc/react";
import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { shallow } from "zustand/shallow";
import { useBookerStore } from "../../store";
import type { ToggledConnectedCalendars } from "../../types";
import { useOverlayCalendarStore } from "../OverlayCalendar/store";
type UseCalendarsProps = {
hasSession: boolean;
};
export const useCalendars = ({ hasSession }: UseCalendarsProps) => {
const searchParams = useSearchParams();
const selectedDate = useBookerStore((state) => state.selectedDate);
const { timezone } = useTimePreferences();
const switchEnabled =
searchParams?.get("overlayCalendar") === "true" ||
localStorage?.getItem("overlayCalendarSwitchDefault") === "true";
const [set, setSet] = useState<Set<ToggledConnectedCalendars>>(() => {
const storedValue = localStorage.getItem("toggledConnectedCalendars");
return storedValue ? new Set(JSON.parse(storedValue)) : new Set([]);
});
const [calendarSettingsOverlay] = useOverlayCalendarStore(
(state) => [state.calendarSettingsOverlayModal, state.setCalendarSettingsOverlayModal],
shallow
);
const { data: overlayBusyDates, isError } = trpc.viewer.availability.calendarOverlay.useQuery(
{
loggedInUsersTz: timezone || "Europe/London",
dateFrom: selectedDate,
dateTo: selectedDate,
calendarsToLoad: Array.from(set).map((item) => ({
credentialId: item.credentialId,
externalId: item.externalId,
})),
},
{
enabled: hasSession && set.size > 0 && switchEnabled,
}
);
useEffect(
function refactorMeWithoutEffect() {
if (!isError) return;
setSet(new Set([]));
},
[isError]
);
const { data, isPending } = trpc.viewer.calendars.connectedCalendars.useQuery(
{
skipSync: true,
},
{
enabled: !!calendarSettingsOverlay || Boolean(searchParams?.get("overlayCalendar")),
}
);
return {
overlayBusyDates,
isOverlayCalendarEnabled: switchEnabled,
connectedCalendars: data?.connectedCalendars || [],
loadingConnectedCalendar: isPending,
onToggleCalendar: setSet,
};
};
@@ -1,30 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { getDecoyBooking } from "@calcom/features/bookings/lib/client/decoyBookingStore";
import type { DecoyBookingData } from "@calcom/features/bookings/lib/client/decoyBookingStore";
/**
* Hook to retrieve and manage decoy booking data from localStorage
* @param uid - The booking uid
* @returns The booking data or null if not found/expired
*/
export function useDecoyBooking(uid: string) {
const router = useRouter();
const [bookingData, setBookingData] = useState<DecoyBookingData | null>(null);
useEffect(() => {
const data = getDecoyBooking(uid);
if (!data) {
router.push("/404");
return;
}
setBookingData(data);
}, [uid, router]);
return bookingData;
}
@@ -1,28 +0,0 @@
import { useEffect } from "react";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useSlotsViewOnSmallScreen } from "@calcom/features/bookings/Booker/components/hooks/useSlotsViewOnSmallScreen";
export const useInitializeWeekStart = (
isPlatform: boolean,
isCalendarView: boolean
) => {
const slotsViewOnSmallScreen = useSlotsViewOnSmallScreen();
const today = dayjs();
const weekStart = today.startOf("week").format("YYYY-MM-DD");
const setSelectedDate = useBookerStoreContext(
(state) => state.setSelectedDate
);
useEffect(() => {
// don't auto-select date if slots view on small screen is enabled
// auto-selecting would open the slots modal in that case which the user would most probably have to close
if (slotsViewOnSmallScreen) return;
if (isPlatform && isCalendarView) {
setSelectedDate({ date: weekStart, omitUpdatingParams: true });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
};
@@ -1,17 +0,0 @@
import { useEffect, useRef } from "react";
import { PUBLIC_QUICK_AVAILABILITY_ROLLOUT } from "@calcom/lib/constants";
import { isVisitorWithinPercentage } from "../../utils/isFeatureEnabledForVisitor";
export const useIsQuickAvailabilityCheckFeatureEnabled = () => {
const isQuickAvailabilityCheckFeatureEnabledRef = useRef(
isVisitorWithinPercentage({ percentage: PUBLIC_QUICK_AVAILABILITY_ROLLOUT })
);
useEffect(() => {
console.log("QuickAvailabilityCheck feature enabled:", isQuickAvailabilityCheckFeatureEnabledRef.current);
}, []);
return isQuickAvailabilityCheckFeatureEnabledRef.current;
};
@@ -1,96 +0,0 @@
import dayjs from "@calcom/dayjs";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { useEffect, useState } from "react";
import { shallow } from "zustand/shallow";
import type { ToggledConnectedCalendars, WrappedBookerPropsMain } from "../../types";
import { useOverlayCalendarStore } from "../OverlayCalendar/store";
import { useLocalSet } from "./useLocalSet";
export const useOverlayCalendar = ({
connectedCalendars,
overlayBusyDates,
onToggleCalendar,
}: Pick<
WrappedBookerPropsMain["calendars"],
"overlayBusyDates" | "onToggleCalendar" | "connectedCalendars"
>): {
isOpenOverlayContinueModal: boolean;
isOpenOverlaySettingsModal: boolean;
handleCloseContinueModal: (val: boolean) => void;
handleCloseSettingsModal: (val: boolean) => void;
handleToggleConnectedCalendar: (externalCalendarId: string, credentialId: number) => void;
checkIsCalendarToggled: (externalId: string, credentialId: number) => boolean;
} => {
const { set, toggleValue, hasItem } = useLocalSet<ToggledConnectedCalendars>(
"toggledConnectedCalendars",
[]
);
const [initalised, setInitalised] = useState(false);
const [continueWithProvider, setContinueWithProvider] = useOverlayCalendarStore(
(state) => [state.continueWithProviderModal, state.setContinueWithProviderModal],
shallow
);
const [calendarSettingsOverlay, setCalendarSettingsOverlay] = useOverlayCalendarStore(
(state) => [state.calendarSettingsOverlayModal, state.setCalendarSettingsOverlayModal],
shallow
);
const setOverlayBusyDates = useOverlayCalendarStore((state) => state.setOverlayBusyDates);
const { timezone } = useTimePreferences();
useEffect(() => {
if (overlayBusyDates) {
const nowDate = dayjs();
const usersTimezoneDate = nowDate.tz(timezone);
const offset = (usersTimezoneDate.utcOffset() - nowDate.utcOffset()) / 60;
const offsettedArray = overlayBusyDates.map((item) => {
return {
...item,
start: dayjs(item.start).add(offset, "hours").toDate(),
end: dayjs(item.end).add(offset, "hours").toDate(),
};
});
setOverlayBusyDates(offsettedArray);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [overlayBusyDates]);
useEffect(() => {
if (connectedCalendars && set.size === 0 && !initalised) {
connectedCalendars.forEach((item) => {
item.calendars?.forEach((cal) => {
const id = { credentialId: item.credentialId, externalId: cal.externalId };
if (cal.primary) {
toggleValue(id);
}
});
});
setInitalised(true);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hasItem, set, initalised]);
const handleToggleConnectedCalendar = (externalCalendarId: string, credentialId: number): void => {
const calendarsToLoad = toggleValue({
credentialId: credentialId,
externalId: externalCalendarId,
});
setOverlayBusyDates([]);
onToggleCalendar(calendarsToLoad);
};
return {
isOpenOverlayContinueModal: continueWithProvider,
isOpenOverlaySettingsModal: calendarSettingsOverlay,
handleCloseContinueModal: (val: boolean) => setContinueWithProvider(val),
handleCloseSettingsModal: (val: boolean) => setCalendarSettingsOverlay(val),
handleToggleConnectedCalendar,
checkIsCalendarToggled: (externalId: string, credentialId: number) => {
return hasItem({
credentialId: credentialId,
externalId: externalId,
});
},
};
};
@@ -1,49 +0,0 @@
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import { getBookingResponsesSchemaWithOptionalChecks } from "@calcom/features/bookings/lib/getBookingResponsesSchema";
import { useEffect, useState } from "react";
import type { BookerEvent } from "../../../types";
import type { BookerState } from "../../types";
const useSkipConfirmStep = (
bookingForm: UseBookingFormReturnType["bookingForm"],
bookerState: BookerState,
isInstantMeeting: boolean,
isWeekView: boolean,
bookingFields?: BookerEvent["bookingFields"],
locations?: BookerEvent["locations"]
) => {
const bookingFormValues = bookingForm.getValues();
const [canSkip, setCanSkip] = useState(false);
const rescheduleUid = useBookerStore((state) => state.rescheduleUid);
useEffect(() => {
const checkSkipStep = async () => {
if (!bookingFields || (locations && locations.length > 1)) {
setCanSkip(false);
return;
}
try {
const responseSchema = getBookingResponsesSchemaWithOptionalChecks({
bookingFields,
view: rescheduleUid ? "reschedule" : "booking",
});
const responseSafeParse = await responseSchema.safeParseAsync(bookingFormValues.responses);
setCanSkip(responseSafeParse.success);
} catch (error) {
setCanSkip(false);
}
};
const isSkipConfirmStepSupported = !isInstantMeeting && !isWeekView;
if (bookerState === "selecting_time" && isSkipConfirmStepSupported) {
checkSkipStep();
}
}, [bookingFormValues, bookingFields, rescheduleUid, bookerState, isWeekView, isInstantMeeting]);
return canSkip;
};
export default useSkipConfirmStep;
@@ -1,169 +0,0 @@
import { useEffect, useRef } from "react";
import { shallow } from "zustand/shallow";
import dayjs from "@calcom/dayjs";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useSlotReservationId } from "@calcom/features/bookings/Booker/useSlotReservationId";
import { isBookingDryRun } from "@calcom/features/bookings/Booker/utils/isBookingDryRun";
import {
MINUTES_TO_BOOK,
PUBLIC_QUERY_RESERVATION_INTERVAL_SECONDS,
PUBLIC_QUERY_RESERVATION_STALE_TIME_SECONDS,
} from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { trpc } from "@calcom/trpc/react";
import type { TIsAvailableOutputSchema } from "@calcom/trpc/server/routers/viewer/slots/isAvailable.schema";
import { useIsQuickAvailabilityCheckFeatureEnabled } from "./useIsQuickAvailabilityCheckFeatureEnabled";
export type QuickAvailabilityCheck = TIsAvailableOutputSchema["slots"][number];
const useQuickAvailabilityChecks = ({
eventTypeId,
eventDuration,
timeslotsAsISOString,
slotReservationId,
}: {
eventTypeId: number | undefined;
eventDuration: number;
timeslotsAsISOString: string[];
slotReservationId: string | undefined | null;
}) => {
// Maintain a cache to ensure previous state is maintained as the request is fetched
// It is important because tentatively selecting a new timeslot will cause a new request which is uncached.
const cachedQuickAvailabilityChecksRef = useRef<QuickAvailabilityCheck[]>([]);
const isQuickAvailabilityCheckFeatureEnabled = useIsQuickAvailabilityCheckFeatureEnabled();
if (!isQuickAvailabilityCheckFeatureEnabled) {
return cachedQuickAvailabilityChecksRef.current;
}
// Create array of slots with their UTC start and end dates
const slotsToCheck = timeslotsAsISOString.map((slot) => {
const slotDayjs = dayjs(slot);
return {
utcStartIso: slotDayjs.utc().toISOString(),
utcEndIso: slotDayjs.add(eventDuration, "minutes").utc().toISOString(),
};
});
const isAvailableQuery = trpc.viewer.slots.isAvailable.useQuery(
{
slots: slotsToCheck,
// enabled flag can't be true if eventTypeId is nullish
eventTypeId: eventTypeId!,
},
{
refetchInterval: PUBLIC_QUERY_RESERVATION_INTERVAL_SECONDS * 1000,
refetchOnWindowFocus: true,
// We must have slotReservationId because it is possible that slotReservationId is set right after isAvailable request is made and we accidentally could consider the slot as unavailable.
// isAvailable request also prevents querying reserved slots if uid is not set. We are safe from both sides.
// TODO: We should move to creating uuid client side for reservation and not waiting for server to set uid cookie.
enabled: !!(eventTypeId && timeslotsAsISOString.length > 0 && slotReservationId),
staleTime: PUBLIC_QUERY_RESERVATION_STALE_TIME_SECONDS * 1000,
}
);
const quickAvailabilityChecks = isAvailableQuery.data?.slots;
// Only valid slots response should override the cache. In worst case, we let the actual booking flow(book/event call) decide whether to go ahead with the booking or not.
if (quickAvailabilityChecks && quickAvailabilityChecks.length > 0) {
cachedQuickAvailabilityChecksRef.current = quickAvailabilityChecks;
}
return quickAvailabilityChecks || cachedQuickAvailabilityChecksRef.current;
};
export type UseSlotsReturnType = ReturnType<typeof useSlots>;
export const useSlots = (event: { id: number; length: number } | null) => {
const selectedDuration = useBookerStoreContext((state) => state.selectedDuration);
const searchParams = useCompatSearchParams();
const [selectedTimeslot, setSelectedTimeslot, tentativeSelectedTimeslots, setTentativeSelectedTimeslots] =
useBookerStoreContext(
(state) => [
state.selectedTimeslot,
state.setSelectedTimeslot,
state.tentativeSelectedTimeslots,
state.setTentativeSelectedTimeslots,
],
shallow
);
const [slotReservationId, setSlotReservationId] = useSlotReservationId();
const reserveSlotMutation = trpc.viewer.slots.reserveSlot.useMutation({
trpc: {
context: {
skipBatch: true,
},
},
onSuccess: (data) => {
setSlotReservationId(data.uid);
},
});
const removeSelectedSlot = trpc.viewer.slots.removeSelectedSlotMark.useMutation({
trpc: { context: { skipBatch: true } },
});
const handleRemoveSlot = () => {
if (event?.id && slotReservationId) {
removeSelectedSlot.mutate({ uid: slotReservationId });
}
};
const eventTypeId = event?.id;
const eventDuration = selectedDuration || event?.length || 0;
const allSelectedTimeslots = [...tentativeSelectedTimeslots, selectedTimeslot].filter(
(slot): slot is string => slot !== null
);
const allUniqueSelectedTimeslots = Array.from(new Set(allSelectedTimeslots));
const quickAvailabilityChecks = useQuickAvailabilityChecks({
eventTypeId,
eventDuration,
timeslotsAsISOString: allUniqueSelectedTimeslots,
slotReservationId,
});
// In case of skipConfirm flow selectedTimeslot would never be set and instead we could have multiple tentatively selected timeslots, so we pick the latest one from it.
const timeSlotToBeBooked = selectedTimeslot ?? allSelectedTimeslots.at(-1);
const handleReserveSlot = () => {
if (eventTypeId && timeSlotToBeBooked && eventDuration) {
reserveSlotMutation.mutate({
slotUtcStartDate: dayjs(timeSlotToBeBooked).utc().toISOString(),
eventTypeId,
slotUtcEndDate: dayjs(timeSlotToBeBooked).utc().add(eventDuration, "minutes").toISOString(),
_isDryRun: isBookingDryRun(searchParams),
});
}
};
useEffect(() => {
handleReserveSlot();
const interval = setInterval(() => {
handleReserveSlot();
}, parseInt(MINUTES_TO_BOOK) * 60 * 1000 - 2000);
return () => {
handleRemoveSlot();
clearInterval(interval);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [event?.id, timeSlotToBeBooked]);
return {
setSelectedTimeslot,
setTentativeSelectedTimeslots,
selectedTimeslot,
tentativeSelectedTimeslots,
slotReservationId,
allSelectedTimeslots,
/**
* Faster but not that accurate as getSchedule, but doesn't give false positive, so it is usable
*/
quickAvailabilityChecks,
};
};
@@ -1,13 +0,0 @@
import { useIsEmbed, useEmbedUiConfig } from "@calcom/embed-core/embed-iframe";
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
export const useSlotsViewOnSmallScreen = () => {
const isEmbed = useIsEmbed();
const isMobile = useMediaQuery("(max-width: 768px)");
const embedUiConfig = useEmbedUiConfig();
if (!isEmbed || !isMobile) return false;
return embedUiConfig.useSlotsViewOnSmallScreen ?? false;
};
@@ -1,74 +0,0 @@
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
export type UseVerifyCodeReturnType = ReturnType<typeof useVerifyCode>;
type UseVerifyCodeProps = {
onSuccess: (isVerified: boolean) => void;
};
export const useVerifyCode = ({ onSuccess }: UseVerifyCodeProps) => {
const { t } = useLocale();
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState("");
const [value, setValue] = useState("");
const [hasVerified, setHasVerified] = useState(false);
const verifyCodeMutationUserSessionRequired = trpc.viewer.organizations.verifyCode.useMutation({
onSuccess: (data) => {
setIsPending(false);
onSuccess(data);
},
onError: (err) => {
setIsPending(false);
setHasVerified(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
}
},
});
const verifyCodeMutationUserSessionNotRequired = trpc.viewer.auth.verifyCodeUnAuthenticated.useMutation({
onSuccess: (data) => {
setIsPending(false);
onSuccess(data);
},
onError: (err) => {
setIsPending(false);
setHasVerified(false);
if (err.message === "invalid_code") {
setError(t("code_provided_invalid"));
}
},
});
const verifyCodeWithSessionRequired = (code: string, email: string) => {
verifyCodeMutationUserSessionRequired.mutate({
code,
email,
});
};
const verifyCodeWithSessionNotRequired = (code: string, email: string) => {
verifyCodeMutationUserSessionNotRequired.mutate({
code,
email,
});
};
return {
verifyCodeWithSessionRequired,
verifyCodeWithSessionNotRequired,
isPending,
setIsPending,
error,
value,
hasVerified,
setValue,
setHasVerified,
resetErrors: () => setError(""),
};
};
@@ -1,77 +0,0 @@
import { useSession } from "next-auth/react";
import { useState } from "react";
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import { useDebounce } from "@calcom/lib/hooks/useDebounce";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
export interface IUseVerifyEmailProps {
email: string;
onVerifyEmail?: () => void;
name?: string | { firstName: string; lastname?: string };
requiresBookerEmailVerification?: boolean;
}
export type UseVerifyEmailReturnType = ReturnType<typeof useVerifyEmail>;
export const useVerifyEmail = ({
email,
name,
requiresBookerEmailVerification,
onVerifyEmail,
}: IUseVerifyEmailProps) => {
const [isEmailVerificationModalVisible, setEmailVerificationModalVisible] = useState(false);
const verifiedEmail = useBookerStore((state) => state.verifiedEmail);
const setVerifiedEmail = useBookerStore((state) => state.setVerifiedEmail);
const isRescheduling = useBookerStore((state) => Boolean(state.rescheduleUid && state.bookingData));
const debouncedEmail = useDebounce(email, 600);
const { data: session } = useSession();
const { t, i18n } = useLocale();
const sendEmailVerificationByCodeMutation = trpc.viewer.auth.sendVerifyEmailCode.useMutation({
onSuccess: () => {
setEmailVerificationModalVisible(true);
showToast(t("email_sent"), "success");
},
onError: () => {
showToast(t("email_not_sent"), "error");
},
});
const { data: isEmailVerificationRequired } =
trpc.viewer.public.checkIfUserEmailVerificationRequired.useQuery(
{
userSessionEmail: session?.user.email || "",
email: debouncedEmail,
},
{
enabled: !!debouncedEmail && !isRescheduling,
}
);
const handleVerifyEmail = () => {
onVerifyEmail?.();
sendEmailVerificationByCodeMutation.mutate({
email,
username: typeof name === "string" ? name : name?.firstName,
language: i18n.language || "en",
});
};
const isVerificationCodeSending = sendEmailVerificationByCodeMutation.isPending;
const renderConfirmNotVerifyEmailButtonCond =
isRescheduling ||
(!requiresBookerEmailVerification && !isEmailVerificationRequired) ||
(email && verifiedEmail && verifiedEmail === email);
return {
handleVerifyEmail,
isEmailVerificationModalVisible,
setEmailVerificationModalVisible,
setVerifiedEmail,
renderConfirmNotVerifyEmailButtonCond: Boolean(renderConfirmNotVerifyEmailButtonCond),
isVerificationCodeSending,
};
};
@@ -27,4 +27,4 @@ export const useAvailableTimeSlots = ({ schedule, eventDuration }: UseAvailableT
return availableTimeslots;
}, [schedule, eventDuration]);
};
};
@@ -5,45 +5,32 @@ import {
useEmbedType,
useEmbedUiConfig,
useIsEmbed,
useSlotsViewOnSmallScreen,
} from "@calcom/embed-core/embed-iframe";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { extraDaysConfig } from "@calcom/features/bookings/Booker/config";
import type { BookerLayout } from "@calcom/features/bookings/Booker/types";
import { validateLayout } from "@calcom/features/bookings/Booker/utils/layout";
import { getQueryParam } from "@calcom/features/bookings/Booker/utils/query-param";
import type { BookerEvent } from "@calcom/features/bookings/types";
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
import type { BookerLayouts } from "@calcom/prisma/zod-utils";
import { defaultBookerLayoutSettings } from "@calcom/prisma/zod-utils";
import { useSlotsViewOnSmallScreen } from "@calcom/features/bookings/Booker/components/hooks/useSlotsViewOnSmallScreen";
import { extraDaysConfig } from "../../config";
import type { BookerLayout } from "../../types";
import { validateLayout } from "../../utils/layout";
import { getQueryParam } from "../../utils/query-param";
export type UseBookerLayoutType = ReturnType<typeof useBookerLayout>;
export const useBookerLayout = (
profileBookerLayouts:
| BookerEvent["profile"]["bookerLayouts"]
| undefined
| null
profileBookerLayouts: BookerEvent["profile"]["bookerLayouts"] | undefined | null
) => {
const [_layout, setLayout] = useBookerStoreContext(
(state) => [state.layout, state.setLayout],
shallow
);
const [_layout, setLayout] = useBookerStoreContext((state) => [state.layout, state.setLayout], shallow);
const isEmbed = useIsEmbed();
const isMobile = useMediaQuery("(max-width: 768px)");
const isTablet = useMediaQuery("(max-width: 1024px)");
const embedUiConfig = useEmbedUiConfig();
// 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 extraDays = isTablet
? extraDaysConfig[layout].tablet
: extraDaysConfig[layout].desktop;
const layout = isEmbed ? (isMobile ? "mobile" : validateLayout(embedUiConfig.layout) || _layout) : _layout;
const extraDays = isTablet ? extraDaysConfig[layout].tablet : extraDaysConfig[layout].desktop;
const embedType = useEmbedType();
// Floating Button and Element Click both are modal and thus have dark background
const hasDarkBackground = isEmbed && embedType !== "inline";
@@ -72,9 +59,7 @@ export const useBookerLayout = (
bookerLayouts?.enabledLayouts?.length &&
layout !== _layout
) {
const validLayout = bookerLayouts.enabledLayouts.find(
(userLayout) => userLayout === layout
);
const validLayout = bookerLayouts.enabledLayouts.find((userLayout) => userLayout === layout);
if (validLayout) setLayout(validLayout);
}
}, [bookerLayouts, setLayout, _layout, isEmbed, isMobile]);
@@ -99,8 +84,8 @@ export const useBookerLayout = (
const hideEventTypeDetails = isEmbed
? embedUiConfig.hideEventTypeDetails
: typeof hideEventTypeDetailsParam === "string"
? hideEventTypeDetailsParam === "true"
: false;
? hideEventTypeDetailsParam === "true"
: false;
const slotsViewOnSmallScreen = useSlotsViewOnSmallScreen();
@@ -118,4 +103,4 @@ export const useBookerLayout = (
slotsViewOnSmallScreen,
bookerLayouts,
};
};
};
@@ -1,9 +1,7 @@
import { shallow } from "zustand/shallow";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useTimePreferences } from "../../../lib/timePreferences";
import { getBookerTimezone } from "../../utils/getBookerTimezone";
import { getBookerTimezone } from "@calcom/features/bookings/Booker/utils/getBookerTimezone";
import { useTimePreferences } from "@calcom/features/bookings/lib/timePreferences";
import { shallow } from "zustand/shallow";
export const useBookerTime = () => {
const [timezoneFromBookerStore] = useBookerStoreContext((state) => [state.timezone], shallow);
@@ -19,4 +17,4 @@ export const useBookerTime = () => {
timezoneFromBookerStore,
timezoneFromTimePreferences,
};
};
};
@@ -127,4 +127,4 @@ export const useBookingForm = ({
formErrors: errors,
errors,
};
};
};
@@ -291,4 +291,4 @@ describe("useInitialFormValues - Autofill Disable Feature", () => {
expect(result.current.values.responses?.phone).toBeUndefined();
});
});
});
});
@@ -85,7 +85,7 @@ export function useInitialFormValues({
eventType?.owner?.profile?.organization?.organizationSettings?.disableAutofillOnBookingPage ??
false;
useEffect(() => {
(async function () {
(async () => {
if (Object.keys(formValues).length) {
setInitialValuesState({
values: formValues,
@@ -118,11 +118,11 @@ export function useInitialFormValues({
const defaultUserValues = (() => {
const rescheduledEmail =
rescheduleUid && bookingData && bookingData.attendees.length > 0
? bookingData.attendees[0].email ?? ""
? (bookingData.attendees[0].email ?? "")
: "";
const rescheduledName =
rescheduleUid && bookingData && bookingData.attendees.length > 0
? bookingData.attendees[0].name ?? ""
? (bookingData.attendees[0].name ?? "")
: "";
if (isAutofillDisabledByOrg) {
@@ -133,8 +133,8 @@ export function useInitialFormValues({
}
return {
email: rescheduledEmail || (parsedQuery["email"] ? parsedQuery["email"] : email ?? ""),
name: rescheduledName || (parsedQuery["name"] ? parsedQuery["name"] : name ?? username ?? ""),
email: rescheduledEmail || (parsedQuery["email"] ? parsedQuery["email"] : (email ?? "")),
name: rescheduledName || (parsedQuery["name"] ? parsedQuery["name"] : (name ?? username ?? "")),
};
})();
@@ -212,4 +212,4 @@ export function useInitialFormValues({
]);
return initialValuesState;
}
}
@@ -68,4 +68,4 @@ export function useLocalSet<T extends HasExternalId>(key: string, initialValue:
};
return { set, addValue, removeById, toggleValue, hasItem, clearSet };
}
}
+8 -79
View File
@@ -1,13 +1,8 @@
import type { UseBookerLayoutType } from "@calcom/features/bookings/Booker/components/hooks/useBookerLayout";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm";
import type { UseBookingsReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookings";
import type { UseSlotsReturnType } from "@calcom/features/bookings/Booker/components/hooks/useSlots";
import type { UseVerifyCodeReturnType } from "@calcom/features/bookings/Booker/components/hooks/useVerifyCode";
import type { UseVerifyEmailReturnType } from "@calcom/features/bookings/Booker/components/hooks/useVerifyEmail";
import type { useScheduleForEventReturnType } from "@calcom/features/bookings/Booker/utils/event";
import type { BookerEventQuery } from "@calcom/features/bookings/types";
import type { IntlSupportedTimeZones } from "@calcom/lib/timeZones";
import type { EventBusyDate } from "@calcom/types/Calendar";
import type { TIsAvailableOutputSchema } from "@calcom/trpc/server/routers/viewer/slots/isAvailable.schema";
import type React from "react";
import type { GetBookingType } from "../lib/get-booking";
@@ -110,79 +105,6 @@ export type ToggledConnectedCalendars = {
externalId: string;
};
export type WrappedBookerPropsMain = {
sessionUsername?: string | null;
rescheduleUid: string | null;
rescheduledBy: string | null;
bookingUid: string | null;
isRedirect: boolean;
fromUserNameRedirected: string;
hasSession: boolean;
onGoBackInstantMeeting: () => void;
onConnectNowInstantMeeting: () => void;
onOverlayClickNoCalendar: () => void;
onClickOverlayContinue: () => void;
onOverlaySwitchStateChange: (state: boolean) => void;
extraOptions: Record<string, string | string[]>;
bookings: UseBookingsReturnType;
slots: UseSlotsReturnType;
calendars: {
overlayBusyDates?: EventBusyDate[];
isOverlayCalendarEnabled: boolean;
connectedCalendars: {
calendars?: {
name?: string;
integrationTitle?: string;
externalId: string;
primary: boolean | null;
}[];
credentialId: number;
delegationCredentialId?: string | null;
cacheUpdatedAt: null;
error?: {
message: string | null;
};
primary?: {
email?: string;
};
integration: {
slug: string;
name?: string | undefined;
title?: string;
logo: string;
};
}[];
loadingConnectedCalendar: boolean;
onToggleCalendar: (calendarsToLoad: Set<ToggledConnectedCalendars>) => void;
};
bookerForm: UseBookingFormReturnType;
event: BookerEventQuery;
schedule: useScheduleForEventReturnType;
bookerLayout: UseBookerLayoutType;
verifyEmail: UseVerifyEmailReturnType;
customClassNames?: CustomClassNames;
isBookingDryRun?: boolean;
renderCaptcha?: boolean;
confirmButtonDisabled?: boolean;
};
export type WrappedBookerPropsForPlatform = WrappedBookerPropsMain & {
isPlatform: true;
verifyCode: undefined;
customClassNames?: CustomClassNames;
timeZones?: Timezone[];
roundRobinHideOrgAndTeam?: boolean;
hideOrgTeamAvatar?: boolean;
};
export type WrappedBookerPropsForWeb = WrappedBookerPropsMain & {
isPlatform: false;
verifyCode: UseVerifyCodeReturnType;
timeZones?: Timezone[];
roundRobinHideOrgAndTeam?: boolean;
hideOrgTeamAvatar?: boolean;
};
export type WrappedBookerProps = WrappedBookerPropsForPlatform | WrappedBookerPropsForWeb;
export type VIEW_TYPE = "MONTH_VIEW" | "WEEK_VIEW" | "COLUMN_VIEW";
export type BookerState = "loading" | "selecting_date" | "selecting_time" | "booking";
@@ -221,3 +143,10 @@ export type DatePickerClassNames = {
datePickerDatesActive?: string;
datePickerToggle?: string;
};
export type QuickAvailabilityCheck = {
status: "available" | "reserved" | "minBookNoticeViolation" | "slotInPast";
utcStartIso: string;
utcEndIso: string;
realStatus?: "available" | "reserved" | "minBookNoticeViolation" | "slotInPast" | undefined;
};
@@ -5,7 +5,7 @@ import { useSchedule } from "@calcom/features/schedules/lib/use-schedule/useSche
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { trpc } from "@calcom/trpc/react";
import { useBookerTime } from "../components/hooks/useBookerTime";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
export type useEventReturnType = ReturnType<typeof useEvent>;
export type useScheduleForEventReturnType = ReturnType<typeof useScheduleForEvent>;
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { QuickAvailabilityCheck } from "../components/hooks/useSlots";
import type { QuickAvailabilityCheck } from "../types";
import { isTimeSlotAvailable } from "./isTimeslotAvailable";
describe("isTimeSlotAvailable", () => {
@@ -1,6 +1,6 @@
import dayjs from "@calcom/dayjs";
import type { QuickAvailabilityCheck } from "../components/hooks/useSlots";
import type { QuickAvailabilityCheck } from "../types";
import { isSlotEquivalent, isValidISOFormat } from "./isSlotEquivalent";
type Maybe<T> = T | undefined;
@@ -17,7 +17,7 @@ import { SkeletonText } from "@calcom/ui/components/skeleton";
import { Tooltip } from "@calcom/ui/components/tooltip";
import NoAvailabilityDialog from "./NoAvailabilityDialog";
import { useSlotsViewOnSmallScreen } from "@calcom/features/bookings/Booker/components/hooks/useSlotsViewOnSmallScreen";
import { useSlotsViewOnSmallScreen } from "@calcom/embed-core/embed-iframe";
export type DatePickerProps = {
/** which day of the week to render the calendar. Usually Sunday (=0) or Monday (=1) - default: Sunday */
@@ -7,9 +7,9 @@ import {
useBookerStoreContext,
useInitializeBookerStoreContext,
} from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useBookerLayout } from "@calcom/features/bookings/Booker/components/hooks/useBookerLayout";
import { useBookingForm } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm";
import { useLocalSet } from "@calcom/features/bookings/Booker/components/hooks/useLocalSet";
import { useBookerLayout } from "@calcom/features/bookings/Booker/hooks/useBookerLayout";
import { useBookingForm } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { useLocalSet } from "@calcom/features/bookings/Booker/hooks/useLocalSet";
import { useInitializeBookerStore } from "@calcom/features/bookings/Booker/store";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import type { ConnectedDestinationCalendars } from "@calcom/features/calendars/lib/getConnectedDestinationCalendars";
@@ -7,8 +7,8 @@ import {
} from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { Header } from "@calcom/web/modules/bookings/components/Header";
import { BookerSection } from "@calcom/web/modules/bookings/components/Section";
import { useAvailableTimeSlots } from "@calcom/features/bookings/Booker/components/hooks/useAvailableTimeSlots";
import { useBookerLayout } from "@calcom/features/bookings/Booker/components/hooks/useBookerLayout";
import { useAvailableTimeSlots } from "@calcom/features/bookings/Booker/hooks/useAvailableTimeSlots";
import { useBookerLayout } from "@calcom/features/bookings/Booker/hooks/useBookerLayout";
import { useTimePreferences } from "@calcom/features/bookings/lib";
import { LargeCalendar } from "@calcom/web/modules/calendar-view/components/LargeCalendar";
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
@@ -2,8 +2,8 @@ import { useSearchParams } from "next/navigation";
import { useIsPlatform } from "@calcom/atoms/hooks/useIsPlatform";
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useBookerTime } from "@calcom/features/bookings/Booker/components/hooks/useBookerTime";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/components/hooks/useBookingForm";
import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerTime";
import type { UseBookingFormReturnType } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { mapBookingToMutationInput, mapRecurringBookingToMutationInput } from "@calcom/features/bookings/lib";
import type { BookingCreateBody } from "@calcom/features/bookings/lib/bookingCreateBodySchema";
import type { BookerEvent } from "@calcom/features/bookings/types";