Skip to content

Scheduling infrastructure for absolutely everyone.

feat: overlay calendar v2 and troubleshooter v2 (#30354)

Kartik Saini1dbaf8e7b424
diff --git a/apps/web/modules/bookings/components/AvailableTimes.tsx b/apps/web/modules/bookings/components/AvailableTimes.tsx
index ec7c1c2f0ca..fb128599652 100644
--- a/apps/web/modules/bookings/components/AvailableTimes.tsx
+++ b/apps/web/modules/bookings/components/AvailableTimes.tsx
@@ -127,11 +127,12 @@ const SlotItem = ({
const selectedTimeslot = useBookerStoreContext((state) => state.selectedTimeslot);
- const { isOverlapping, overlappingTimeEnd, overlappingTimeStart } = useCheckOverlapWithOverlay({
- start: computedDateWithUsersTimezone,
- selectedDuration: eventData?.length ?? 0,
- offset,
- });
+ const { isOverlapping, overlappingTimeEnd, overlappingTimeStart, overlappingTitle } =
+ useCheckOverlapWithOverlay({
+ start: computedDateWithUsersTimezone,
+ selectedDuration: eventData?.length ?? 0,
+ offset,
+ });
const onButtonClick = () => {
if (handleSlotClick) {
@@ -239,7 +240,7 @@ const SlotItem = ({
<HoverCard.Content side="top" align="end" sideOffset={2}>
<div className="text-emphasis bg-inverted w-(--booker-timeslots-width) rounded-md p-3">
<div className="flex items-center gap-2">
- <p>Busy</p>
+ <p>{overlappingTitle || t("busy_time.busy")}</p>
</div>
<p className="text-muted">
{overlappingTimeStart} - {overlappingTimeEnd}
diff --git a/apps/web/modules/bookings/components/Booker.tsx b/apps/web/modules/bookings/components/Booker.tsx
index f2f6179d942..30851479ec9 100644
--- a/apps/web/modules/bookings/components/Booker.tsx
+++ b/apps/web/modules/bookings/components/Booker.tsx
@@ -59,6 +59,7 @@ const BookerComponent = ({
entity,
onOverlayClickNoCalendar,
onClickOverlayContinue,
+ overlaySocialLoginProviders,
onOverlaySwitchStateChange,
sessionUsername,
rescheduleUid,
@@ -385,6 +386,7 @@ const BookerComponent = ({
onToggleCalendar={onToggleCalendar}
hasSession={hasSession}
handleClickContinue={onClickOverlayContinue}
+ socialLoginProviders={overlaySocialLoginProviders}
handleSwitchStateChange={onOverlaySwitchStateChange}
handleClickNoCalendar={() => {
onOverlayClickNoCalendar();
diff --git a/apps/web/modules/bookings/components/BookerWebWrapper.tsx b/apps/web/modules/bookings/components/BookerWebWrapper.tsx
index cab3548d48a..af276539edd 100644
--- a/apps/web/modules/bookings/components/BookerWebWrapper.tsx
+++ b/apps/web/modules/bookings/components/BookerWebWrapper.tsx
@@ -8,6 +8,7 @@ import {
useBookerStoreContext,
useInitializeBookerStoreContext,
} from "@calcom/features/bookings/Booker/BookerStoreProvider";
+import { useOverlayCalendarStore } from "@calcom/features/bookings/Booker/components/OverlayCalendar/store";
import { useBookerLayout } from "@calcom/features/bookings/Booker/hooks/useBookerLayout";
import { useBookingForm } from "@calcom/features/bookings/Booker/hooks/useBookingForm";
import { useInitializeBookerStore } from "@calcom/features/bookings/Booker/store";
@@ -17,17 +18,22 @@ import { DEFAULT_DARK_BRAND_COLOR, DEFAULT_LIGHT_BRAND_COLOR, WEBAPP_URL } from
import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
import { localStorage } from "@calcom/lib/webstorage";
import { useEvent, useScheduleForEvent } from "@calcom/web/modules/schedules/hooks/useEvent";
+import { useNonEmptyScheduleDays } from "@calcom/web/modules/schedules/hooks/useNonEmptyScheduleDays";
+import { useQuery } from "@tanstack/react-query";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
-import { useSession } from "next-auth/react";
+import { getProviders, signIn, useSession } from "next-auth/react";
import { useCallback, useEffect, useMemo } from "react";
import { shallow } from "zustand/shallow";
import { useBookings } from "../hooks/useBookings";
-import { useCalendars } from "../hooks/useCalendars";
+import { getLastVisibleDate, useCalendars } from "../hooks/useCalendars";
import { useSlots } from "../hooks/useSlots";
import { useVerifyCode } from "../hooks/useVerifyCode";
import { useVerifyEmail } from "../hooks/useVerifyEmail";
+import type { OverlaySocialLoginProvider } from "../types";
import { Booker as BookerComponent } from "./Booker";
+const OVERLAY_SOCIAL_LOGIN_PROVIDERS: OverlaySocialLoginProvider[] = ["google", "azure-ad"];
+
export type BookerWebWrapperAtomProps = BookerProps & {
eventData?: NonNullable<Awaited<ReturnType<typeof getPublicEvent>>>;
};
@@ -120,7 +126,6 @@ const BookerWebWrapperComponent = (props: BookerWebWrapperAtomProps): JSX.Elemen
extraOptions: routerQuery,
prefillFormParams,
});
- const calendars = useCalendars({ hasSession });
const verifyEmail = useVerifyEmail({
email: bookerForm.formEmail,
name: bookerForm.formName,
@@ -151,6 +156,16 @@ const BookerWebWrapperComponent = (props: BookerWebWrapperAtomProps): JSX.Elemen
bookerLayout,
...(props.entity.orgSlug ? { orgSlug: props.entity.orgSlug } : {}),
});
+ const availableDays = useNonEmptyScheduleDays(schedule?.data?.slots);
+ const calendars = useCalendars({
+ hasSession,
+ lastVisibleDate: getLastVisibleDate({
+ selectedDate,
+ layout: bookerLayout.layout,
+ extraDays: bookerLayout.extraDays,
+ availableDays,
+ }),
+ });
const bookings = useBookings({
event,
hashedLink: props.hashedLink,
@@ -200,13 +215,34 @@ const BookerWebWrapperComponent = (props: BookerWebWrapperAtomProps): JSX.Elemen
if (hasSession) onOverlaySwitchStateChange(true);
}, [hasSession]);
+ // Which social logins exist depends on how the instance is configured, so we only offer the available ones.
+ // Fetched once the modal opens to not add a request to every booking page visit.
+ const isOverlayContinueModalOpen = useOverlayCalendarStore((state) => state.continueWithProviderModal);
+ const { data: authProviders } = useQuery({
+ queryKey: ["authProviders"],
+ queryFn: () => getProviders(),
+ enabled: isOverlayContinueModalOpen,
+ staleTime: Number.POSITIVE_INFINITY,
+ });
+ const overlaySocialLoginProviders = OVERLAY_SOCIAL_LOGIN_PROVIDERS.filter(
+ (provider) => authProviders?.[provider]
+ );
+
return (
<BookerComponent
{...props}
onOverlayClickNoCalendar={() => {
router.push("/apps/categories/calendar");
}}
- onClickOverlayContinue={() => {
+ overlaySocialLoginProviders={overlaySocialLoginProviders}
+ onClickOverlayContinue={(socialLoginProvider) => {
+ if (socialLoginProvider) {
+ // Signing in with Google/Microsoft also connects that calendar, so we can come straight back here
+ signIn(socialLoginProvider, {
+ callbackUrl: `${window.location.pathname}${window.location.search}`,
+ });
+ return;
+ }
const newUrl = new URL(`${WEBAPP_URL}/login`);
newUrl.searchParams.set("callbackUrl", window.location.pathname);
newUrl.searchParams.set("overlayCalendar", "true");
diff --git a/apps/web/modules/bookings/components/LargeCalendar.tsx b/apps/web/modules/bookings/components/LargeCalendar.tsx
index 744c1f724f6..95594e1ef54 100644
--- a/apps/web/modules/bookings/components/LargeCalendar.tsx
+++ b/apps/web/modules/bookings/components/LargeCalendar.tsx
@@ -7,6 +7,7 @@ import { useBookerTime } from "@calcom/features/bookings/Booker/hooks/useBookerT
import type { BookerEvent } from "@calcom/features/bookings/types";
import { Calendar } from "@calcom/web/modules/calendars/weeklyview/components/Calendar";
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
+import { useLocale } from "@calcom/lib/hooks/useLocale";
import { localStorage } from "@calcom/lib/webstorage";
import type { useScheduleForEventReturnType } from "@calcom/web/modules/schedules/hooks/useEvent";
@@ -26,6 +27,7 @@ export const LargeCalendar = ({
data?: Pick<BookerEvent, "length"> | null;
};
}) => {
+ const { t } = useLocale();
const selectedDate = useBookerStoreContext((state) => state.selectedDate);
const setSelectedTimeslot = useBookerStoreContext((state) => state.setSelectedTimeslot);
const selectedEventDuration = useBookerStoreContext((state) => state.selectedDuration);
@@ -54,14 +56,14 @@ export const LargeCalendar = ({
id,
start: dayjs(event.start).toDate(),
end: dayjs(event.end).toDate(),
- title: "Busy",
+ title: event.title || t("busy_time.busy"),
options: {
status: "ACCEPTED",
borderOnly: true,
},
} as CalendarEvent;
});
- }, [overlayEvents, displayOverlay]);
+ }, [overlayEvents, displayOverlay, t]);
return (
<div className="h-full [--calendar-dates-sticky-offset:66px]">
diff --git a/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendar.tsx b/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendar.tsx
index 6f62658ad55..0b235902b2d 100644
--- a/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendar.tsx
+++ b/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendar.tsx
@@ -12,7 +12,8 @@ type OverlayCalendarProps = Pick<
> & {
handleClickNoCalendar: () => void;
hasSession: boolean;
- handleClickContinue: () => void;
+ handleClickContinue: WrappedBookerPropsMain["onClickOverlayContinue"];
+ socialLoginProviders?: WrappedBookerPropsMain["overlaySocialLoginProviders"];
handleSwitchStateChange: (state: boolean) => void;
};
@@ -24,6 +25,7 @@ export const OverlayCalendar = ({
handleClickNoCalendar,
handleSwitchStateChange,
handleClickContinue,
+ socialLoginProviders,
hasSession,
}: OverlayCalendarProps): JSX.Element | null => {
const isPlatform = useIsPlatform();
@@ -60,6 +62,7 @@ export const OverlayCalendar = ({
open={isOpenOverlayContinueModal && !isOverlayCalendarEnabled}
onClose={handleCloseContinueModal}
onContinue={handleClickContinue}
+ socialLoginProviders={socialLoginProviders}
/>
)}
<OverlayCalendarSettingsModal
diff --git a/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendarContinueModal.test.tsx b/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendarContinueModal.test.tsx
new file mode 100644
index 00000000000..6ef7f72c441
--- /dev/null
+++ b/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendarContinueModal.test.tsx
@@ -0,0 +1,50 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { OverlayCalendarContinueModal } from "./OverlayCalendarContinueModal";
+
+vi.mock("@calcom/lib/hooks/useLocale", () => ({
+ useLocale: () => ({
+ t: (key: string, options?: { appName?: string }) =>
+ options?.appName ? `${key} ${options.appName}` : key,
+ }),
+}));
+
+// The dialog itself depends on the app router, only its content matters here
+vi.mock("@calcom/features/components/controlled-dialog", () => ({
+ Dialog: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+vi.mock("@calcom/ui/components/dialog", () => ({
+ DialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogFooter: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+
+describe("OverlayCalendarContinueModal", () => {
+ it("only offers the social logins that are available", () => {
+ const onContinue = vi.fn();
+ render(<OverlayCalendarContinueModal open onContinue={onContinue} socialLoginProviders={["google"]} />);
+
+ expect(screen.getByTestId("overlay-calendar-continue-button")).toBeInTheDocument();
+ expect(screen.queryByTestId("overlay-calendar-microsoft-button")).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByTestId("overlay-calendar-google-button"));
+ expect(onContinue).toHaveBeenCalledWith("google");
+ });
+
+ it("continues with the regular login when no social login is chosen", () => {
+ const onContinue = vi.fn();
+ render(
+ <OverlayCalendarContinueModal
+ open
+ onContinue={onContinue}
+ socialLoginProviders={["google", "azure-ad"]}
+ />
+ );
+
+ expect(screen.getByTestId("overlay-calendar-microsoft-button")).toHaveTextContent(
+ "continue_with Microsoft"
+ );
+
+ fireEvent.click(screen.getByTestId("overlay-calendar-continue-button"));
+ expect(onContinue).toHaveBeenCalledWith();
+ });
+});
diff --git a/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendarContinueModal.tsx b/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendarContinueModal.tsx
index 310ca7f8454..77a85996d89 100644
--- a/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendarContinueModal.tsx
+++ b/apps/web/modules/bookings/components/OverlayCalendar/OverlayCalendarContinueModal.tsx
@@ -3,11 +3,25 @@ import { APP_NAME } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
+import type { OverlaySocialLoginProvider } from "../../types";
+
+const SOCIAL_LOGIN_BUTTONS: Record<
+ OverlaySocialLoginProvider,
+ { name: string; icon: string; testId: string }
+> = {
+ google: { name: "Google", icon: "/google-icon-colored.svg", testId: "overlay-calendar-google-button" },
+ "azure-ad": {
+ name: "Microsoft",
+ icon: "/microsoft-logo.svg",
+ testId: "overlay-calendar-microsoft-button",
+ },
+};
interface IOverlayCalendarContinueModalProps {
open?: boolean;
onClose?: (state: boolean) => void;
- onContinue: () => void;
+ onContinue: (socialLoginProvider?: OverlaySocialLoginProvider) => void;
+ socialLoginProviders?: OverlaySocialLoginProvider[];
}
export function OverlayCalendarContinueModal(props: IOverlayCalendarContinueModalProps) {
@@ -29,6 +43,22 @@ export function OverlayCalendarContinueModal(props: IOverlayCalendarContinueModa
StartIcon="calendar-search">
{t("continue_with", { appName: APP_NAME })}
</Button>
+ {props.socialLoginProviders?.map((provider) => {
+ const { name, icon, testId } = SOCIAL_LOGIN_BUTTONS[provider];
+ return (
+ <Button
+ key={provider}
+ color="secondary"
+ data-testid={testId}
+ onClick={() => {
+ props.onContinue(provider);
+ }}
+ className="gap w-full items-center justify-center font-semibold"
+ CustomStartIcon={<img className="mr-2 size-4" src={icon} alt="" />}>
+ {t("continue_with", { appName: name })}
+ </Button>
+ );
+ })}
</div>
<DialogFooter>
{/* Agh modal hacks */}
diff --git a/apps/web/modules/bookings/hooks/useCalendars.test.ts b/apps/web/modules/bookings/hooks/useCalendars.test.ts
new file mode 100644
index 00000000000..d09566f4b11
--- /dev/null
+++ b/apps/web/modules/bookings/hooks/useCalendars.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from "vitest";
+import { getLastVisibleDate, getOverlayDateRange } from "./useCalendars";
+
+describe("getLastVisibleDate", () => {
+ const weekdays = [
+ "2026-10-19",
+ "2026-10-20",
+ "2026-10-21",
+ "2026-10-22",
+ "2026-10-23",
+ "2026-10-26",
+ "2026-10-27",
+ ];
+
+ it("returns null without a selected date", () => {
+ expect(
+ getLastVisibleDate({ selectedDate: null, layout: "week_view", extraDays: 7, availableDays: [] })
+ ).toBeNull();
+ });
+
+ it("shows only the selected date in month view", () => {
+ expect(
+ getLastVisibleDate({
+ selectedDate: "2026-10-24",
+ layout: "month_view",
+ extraDays: 0,
+ availableDays: weekdays,
+ })
+ ).toBe("2026-10-24");
+ });
+
+ it("shows consecutive days in week view", () => {
+ expect(
+ getLastVisibleDate({
+ selectedDate: "2026-10-21",
+ layout: "week_view",
+ extraDays: 7,
+ availableDays: weekdays,
+ })
+ ).toBe("2026-10-27");
+ });
+
+ it("skips days without availability in column view", () => {
+ expect(
+ getLastVisibleDate({
+ selectedDate: "2026-10-19",
+ layout: "column_view",
+ extraDays: 6,
+ availableDays: weekdays,
+ })
+ ).toBe("2026-10-26");
+ });
+
+ it("ignores available days before the selected date in column view", () => {
+ expect(
+ getLastVisibleDate({
+ selectedDate: "2026-10-22",
+ layout: "column_view",
+ extraDays: 6,
+ availableDays: weekdays,
+ })
+ ).toBe("2026-10-27");
+ });
+
+ it("falls back to the selected date in column view when nothing is available", () => {
+ expect(
+ getLastVisibleDate({
+ selectedDate: "2026-10-19",
+ layout: "column_view",
+ extraDays: 6,
+ availableDays: [],
+ })
+ ).toBe("2026-10-19");
+ });
+});
+
+describe("getOverlayDateRange", () => {
+ it("returns no range without a selected date", () => {
+ expect(getOverlayDateRange(null, "2026-10-27")).toEqual({ dateFrom: null, dateTo: null });
+ });
+
+ it("covers the whole selected day when it is the only visible one", () => {
+ expect(getOverlayDateRange("2026-10-24", null)).toEqual({
+ dateFrom: "2026-10-24T00:00:00+00:00",
+ dateTo: "2026-10-24T23:59:59+00:00",
+ });
+ });
+
+ it("covers every day up to the last visible one", () => {
+ expect(getOverlayDateRange("2026-10-21", "2026-10-27")).toEqual({
+ dateFrom: "2026-10-21T00:00:00+00:00",
+ dateTo: "2026-10-27T23:59:59+00:00",
+ });
+ });
+
+ it("never ends before the selected date", () => {
+ expect(getOverlayDateRange("2026-10-21", "2026-10-19").dateTo).toBe("2026-10-21T23:59:59+00:00");
+ });
+});
diff --git a/apps/web/modules/bookings/hooks/useCalendars.ts b/apps/web/modules/bookings/hooks/useCalendars.ts
index 9bed978b3b5..f3a4463feb1 100644
--- a/apps/web/modules/bookings/hooks/useCalendars.ts
+++ b/apps/web/modules/bookings/hooks/useCalendars.ts
@@ -1,21 +1,55 @@
-import { useSearchParams } from "next/navigation";
-import { useEffect, useState } from "react";
-import { shallow } from "zustand/shallow";
-
+import dayjs from "@calcom/dayjs";
+import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
import { useOverlayCalendarStore } from "@calcom/features/bookings/Booker/components/OverlayCalendar/store";
-import { useBookerStore } from "@calcom/features/bookings/Booker/store";
import type { ToggledConnectedCalendars } from "@calcom/features/bookings/Booker/types";
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";
type UseCalendarsProps = {
hasSession: boolean;
+ lastVisibleDate: string | null;
+};
+
+// Week view shows extraDays consecutive days, column view the next extraDays days that have availability
+export const getLastVisibleDate = ({
+ selectedDate,
+ layout,
+ extraDays,
+ availableDays,
+}: {
+ selectedDate: string | null;
+ layout: string;
+ extraDays: number;
+ availableDays: string[];
+}) => {
+ if (!selectedDate) return null;
+ if (layout === "column_view") {
+ const shownDays = availableDays
+ .filter((day) => !dayjs(day).isBefore(selectedDate, "day"))
+ .slice(0, Math.max(extraDays, 1));
+ return shownDays[shownDays.length - 1] ?? selectedDate;
+ }
+ return dayjs(selectedDate)
+ .add(Math.max(extraDays - 1, 0), "day")
+ .format("YYYY-MM-DD");
+};
+
+// dateTo must be the end of the last day, a bare date would be read as midnight at its start
+export const getOverlayDateRange = (selectedDate: string | null, lastVisibleDate: string | null) => {
+ if (!selectedDate) return { dateFrom: null, dateTo: null };
+ const firstDay = dayjs(selectedDate).startOf("day");
+ const lastDay = dayjs.max(firstDay, dayjs(lastVisibleDate ?? selectedDate)).endOf("day");
+ return { dateFrom: firstDay.format(), dateTo: lastDay.format() };
};
-export const useCalendars = ({ hasSession }: UseCalendarsProps) => {
+export const useCalendars = ({ hasSession, lastVisibleDate }: UseCalendarsProps) => {
const searchParams = useSearchParams();
- const selectedDate = useBookerStore((state) => state.selectedDate);
+ // The date picker writes to the context store, the legacy global store only knows the date from the URL at load
+ const selectedDate = useBookerStoreContext((state) => state.selectedDate);
const { timezone } = useTimePreferences();
const switchEnabled =
searchParams?.get("overlayCalendar") === "true" ||
@@ -31,11 +65,12 @@ export const useCalendars = ({ hasSession }: UseCalendarsProps) => {
shallow
);
+ const { dateFrom, dateTo } = getOverlayDateRange(selectedDate, lastVisibleDate);
const { data: overlayBusyDates, isError } = trpc.viewer.availability.calendarOverlay.useQuery(
{
loggedInUsersTz: timezone || "Europe/London",
- dateFrom: selectedDate,
- dateTo: selectedDate,
+ dateFrom,
+ dateTo,
calendarsToLoad: Array.from(set).map((item) => ({
credentialId: item.credentialId,
externalId: item.externalId,
diff --git a/apps/web/modules/bookings/hooks/useOverlayCalendar.test.ts b/apps/web/modules/bookings/hooks/useOverlayCalendar.test.ts
new file mode 100644
index 00000000000..e64a84e37e2
--- /dev/null
+++ b/apps/web/modules/bookings/hooks/useOverlayCalendar.test.ts
@@ -0,0 +1,96 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { WrappedBookerPropsMain } from "../types";
+import { useOverlayCalendar } from "./useOverlayCalendar";
+
+vi.mock("@calcom/features/bookings/lib", () => ({
+ useTimePreferences: () => ({ timezone: "UTC" }),
+}));
+
+type ConnectedCalendars = WrappedBookerPropsMain["calendars"]["connectedCalendars"];
+
+const buildConnectedCalendars = (
+ calendars: NonNullable<ConnectedCalendars[number]["calendars"]>
+): ConnectedCalendars => [
+ {
+ credentialId: 1,
+ cacheUpdatedAt: null,
+ integration: { slug: "google-calendar", logo: "" },
+ calendars,
+ },
+];
+
+const renderOverlayCalendar = (connectedCalendars: ConnectedCalendars) => {
+ const onToggleCalendar = vi.fn();
+ const hook = renderHook(
+ (props: { connectedCalendars: ConnectedCalendars }) =>
+ useOverlayCalendar({ ...props, overlayBusyDates: undefined, onToggleCalendar }),
+ { initialProps: { connectedCalendars } }
+ );
+ return { ...hook, onToggleCalendar };
+};
+
+describe("useOverlayCalendar", () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ it("starts with the calendars that are checked for conflicts", () => {
+ const { result, onToggleCalendar } = renderOverlayCalendar(
+ buildConnectedCalendars([
+ { externalId: "primary", primary: true, isSelected: false },
+ { externalId: "work", primary: false, isSelected: true },
+ ])
+ );
+
+ expect(result.current.checkIsCalendarToggled("work", 1)).toBe(true);
+ expect(result.current.checkIsCalendarToggled("primary", 1)).toBe(false);
+ expect(onToggleCalendar).toHaveBeenCalledTimes(1);
+ expect(Array.from(onToggleCalendar.mock.calls[0][0])).toEqual([{ credentialId: 1, externalId: "work" }]);
+ });
+
+ it("falls back to the primary calendar when it isn't known which calendars are checked for conflicts", () => {
+ const { result } = renderOverlayCalendar(
+ buildConnectedCalendars([
+ { externalId: "primary", primary: true },
+ { externalId: "work", primary: false },
+ ])
+ );
+
+ expect(result.current.checkIsCalendarToggled("primary", 1)).toBe(true);
+ expect(result.current.checkIsCalendarToggled("work", 1)).toBe(false);
+ });
+
+ it("waits for the connected calendars to load", () => {
+ const { result, rerender, onToggleCalendar } = renderOverlayCalendar([]);
+ expect(onToggleCalendar).not.toHaveBeenCalled();
+
+ rerender({
+ connectedCalendars: buildConnectedCalendars([{ externalId: "work", primary: false, isSelected: true }]),
+ });
+
+ expect(result.current.checkIsCalendarToggled("work", 1)).toBe(true);
+ expect(onToggleCalendar).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the calendars the user toggled before", () => {
+ window.localStorage.setItem(
+ "toggledConnectedCalendars",
+ JSON.stringify([{ credentialId: 1, externalId: "personal" }])
+ );
+
+ const { result, onToggleCalendar } = renderOverlayCalendar(
+ buildConnectedCalendars([
+ { externalId: "personal", primary: false, isSelected: false },
+ { externalId: "work", primary: false, isSelected: true },
+ ])
+ );
+
+ expect(result.current.checkIsCalendarToggled("personal", 1)).toBe(true);
+ expect(result.current.checkIsCalendarToggled("work", 1)).toBe(false);
+ expect(onToggleCalendar).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/modules/bookings/hooks/useOverlayCalendar.ts b/apps/web/modules/bookings/hooks/useOverlayCalendar.ts
index e259660ce4f..31cda82696d 100644
--- a/apps/web/modules/bookings/hooks/useOverlayCalendar.ts
+++ b/apps/web/modules/bookings/hooks/useOverlayCalendar.ts
@@ -24,7 +24,7 @@ export const useOverlayCalendar = ({
handleToggleConnectedCalendar: (externalCalendarId: string, credentialId: number) => void;
checkIsCalendarToggled: (externalId: string, credentialId: number) => boolean;
} => {
- const { set, toggleValue, hasItem } = useLocalSet<ToggledConnectedCalendars>(
+ const { set, addValue, toggleValue, hasItem } = useLocalSet<ToggledConnectedCalendars>(
"toggledConnectedCalendars",
[]
);
@@ -60,15 +60,16 @@ export const useOverlayCalendar = ({
}, [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);
- }
- });
- });
+ // Wait for the connected calendars to load, otherwise we'd initialise with nothing
+ if (connectedCalendars?.length && set.size === 0 && !initalised) {
+ // Start with the calendars the user checks for conflicts, that's what they consider themselves busy with
+ const defaultCalendars = connectedCalendars.flatMap((item) =>
+ (item.calendars ?? [])
+ .filter((cal) => cal.isSelected ?? cal.primary)
+ .map((cal) => ({ credentialId: item.credentialId, externalId: cal.externalId }))
+ );
+ defaultCalendars.forEach(addValue);
+ onToggleCalendar(new Set(defaultCalendars));
setInitalised(true);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/apps/web/modules/bookings/types.ts b/apps/web/modules/bookings/types.ts
index 2922d932c20..0c32e795ce7 100644
--- a/apps/web/modules/bookings/types.ts
+++ b/apps/web/modules/bookings/types.ts
@@ -43,6 +43,8 @@ export type { UseSlotsReturnType } from "./hooks/useSlots";
export type { UseVerifyCodeReturnType } from "./hooks/useVerifyCode";
export type { UseVerifyEmailReturnType } from "./hooks/useVerifyEmail";
+export type OverlaySocialLoginProvider = "google" | "azure-ad";
+
export type WrappedBookerPropsMain = {
sessionUsername?: string | null;
rescheduleUid: string | null;
@@ -52,7 +54,8 @@ export type WrappedBookerPropsMain = {
fromUserNameRedirected: string;
hasSession: boolean;
onOverlayClickNoCalendar: () => void;
- onClickOverlayContinue: () => void;
+ onClickOverlayContinue: (socialLoginProvider?: OverlaySocialLoginProvider) => void;
+ overlaySocialLoginProviders?: OverlaySocialLoginProvider[];
onOverlaySwitchStateChange: (state: boolean) => void;
extraOptions: Record<string, string | string[]>;
bookings: UseBookingsReturnType;
@@ -66,6 +69,7 @@ export type WrappedBookerPropsMain = {
integrationTitle?: string;
externalId: string;
primary: boolean | null;
+ isSelected?: boolean;
}[];
credentialId: number;
delegationCredentialId?: string | null;
diff --git a/apps/web/modules/calendars/weeklyview/components/event/Event.tsx b/apps/web/modules/calendars/weeklyview/components/event/Event.tsx
index dd34d9875ea..c05d5b1ddf9 100644
--- a/apps/web/modules/calendars/weeklyview/components/event/Event.tsx
+++ b/apps/web/modules/calendars/weeklyview/components/event/Event.tsx
@@ -73,6 +73,10 @@ export function Event({
const Component = onEventClick ? "button" : "div";
+ // Events spanning several days need the date, the time alone would be ambiguous
+ const timeFormat = dayjs(event.start).isSame(event.end, "day") ? "HH:mm" : "MMM D, HH:mm";
+ const eventTime = `${dayjs(event.start).format(timeFormat)} - ${dayjs(event.end).format(timeFormat)}`;
+
const dayOfWeek = dayjs(event.start).day();
const tooltipSide = dayOfWeek >= 1 && dayOfWeek <= 4 ? "right" : "left";
@@ -86,11 +90,7 @@ export function Event({
)}
<div className="flex-1">
<div className="font-semibold leading-tight">{event.title}</div>
- {!event.options?.hideTime && (
- <div className="text-inverted-muted mt-1 text-xs">
- {dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
- </div>
- )}
+ {!event.options?.hideTime && <div className="text-inverted-muted mt-1 text-xs">{eventTime}</div>}
{event.description && (
<div className="text-inverted-muted mt-1 text-xs leading-snug">{event.description}</div>
)}
@@ -140,7 +140,7 @@ export function Event({
<span>{event.title}</span>
{!event.options?.hideTime && (
<p className="text-subtle mt-1 w-full whitespace-nowrap text-left text-[10px] leading-none">
- {dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
+ {eventTime}
</p>
)}
</div>
@@ -150,7 +150,7 @@ export function Event({
)}
{displayType !== "single-line" && !event.options?.hideTime && (
<p className="text-subtle mt-1 whitespace-nowrap text-left text-[10px] leading-none">
- {dayjs(event.start).format("HH:mm")} - {dayjs(event.end).format("HH:mm")}
+ {eventTime}
</p>
)}
{displayType === "full" && event.description && (
diff --git a/apps/web/modules/calendars/weeklyview/components/event/EventList.tsx b/apps/web/modules/calendars/weeklyview/components/event/EventList.tsx
index 6821a423d7e..ad7b8092651 100644
--- a/apps/web/modules/calendars/weeklyview/components/event/EventList.tsx
+++ b/apps/web/modules/calendars/weeklyview/components/event/EventList.tsx
@@ -1,15 +1,16 @@
import { useEffect, useMemo, useState } from "react";
import { shallow } from "zustand/shallow";
-import dayjs from "@calcom/dayjs";
+import type { Dayjs } from "@calcom/dayjs";
import classNames from "@calcom/ui/classNames";
import { useCalendarStore } from "@calcom/features/calendars/weeklyview/state/store";
+import { getEventSegmentForDay } from "@calcom/features/calendars/weeklyview/utils";
import { calculateEventLayouts, createLayoutMap } from "@calcom/features/calendars/weeklyview/utils/overlap";
import { Event } from "./Event";
type Props = {
- day: dayjs.Dayjs;
+ day: Dayjs;
};
export function EventList({ day }: Props) {
@@ -25,12 +26,16 @@ export function EventList({ day }: Props) {
const [hoveredEventId, setHoveredEventId] = useState<number | null>(null);
- const dayEvents = useMemo(() => {
- return events.filter((event) => {
- return dayjs(event.start).isSame(day, "day") && !event.options?.allDay;
+ const daySegments = useMemo(() => {
+ return events.flatMap((event) => {
+ if (event.options?.allDay) return [];
+ const segment = getEventSegmentForDay(event, day);
+ return segment ? [{ event, segment }] : [];
});
}, [events, day]);
+ const dayEvents = useMemo(() => daySegments.map(({ event }) => event), [daySegments]);
+
const layoutMap = useMemo(() => {
const layouts = calculateEventLayouts(dayEvents);
return createLayoutMap(layouts);
@@ -38,10 +43,9 @@ export function EventList({ day }: Props) {
const eventCalculations = useMemo(() => {
return new Map(
- dayEvents.map((event) => {
- const eventStart = dayjs(event.start);
- const eventEnd = dayjs(event.end);
- const eventDuration = eventEnd.diff(eventStart, "minutes");
+ daySegments.map(({ event, segment }) => {
+ const eventStart = segment.start;
+ const eventDuration = segment.end.diff(eventStart, "minutes");
const eventStartHour = eventStart.hour();
const eventStartDiff = (eventStartHour - (startHour || 0)) * 60 + eventStart.minute();
@@ -55,7 +59,7 @@ export function EventList({ day }: Props) {
];
})
);
- }, [dayEvents, startHour]);
+ }, [daySegments, startHour]);
// Find which overlap group the hovered event belongs to
const hoveredEventLayout = hoveredEventId ? layoutMap.get(hoveredEventId) : null;
diff --git a/apps/web/modules/troubleshooter/components/LargeCalendar.tsx b/apps/web/modules/troubleshooter/components/LargeCalendar.tsx
index 86f49dff1ef..2503b3a47e6 100644
--- a/apps/web/modules/troubleshooter/components/LargeCalendar.tsx
+++ b/apps/web/modules/troubleshooter/components/LargeCalendar.tsx
@@ -67,10 +67,11 @@ export const LargeCalendar = ({ extraDays }: { extraDays: number }) => {
// .toDate(),
const calendarEvents = busyEvents?.busy.map((event, idx) => {
- const translatedTitle = event.title ? t(event.title) : t("busy_time.busy");
+ // Only our own "busy_time.*" titles are translation keys, booking and calendar event titles are shown as is
+ const title = event.title?.startsWith("busy_time.") ? t(event.title) : event.title;
return {
id: idx,
- title: translatedTitle,
+ title: title || t("busy_time.busy"),
start: new Date(event.start),
end: new Date(event.end),
source: event.source,
diff --git a/packages/app-store/googlecalendar/lib/CalendarService.ts b/packages/app-store/googlecalendar/lib/CalendarService.ts
index 1aa622dfa57..87839dcd2d7 100644
--- a/packages/app-store/googlecalendar/lib/CalendarService.ts
+++ b/packages/app-store/googlecalendar/lib/CalendarService.ts
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { MeetLocationType } from "@calcom/app-store/constants";
+import dayjs from "@calcom/dayjs";
import { getDestinationCalendarRepository } from "@calcom/features/di/containers/DestinationCalendar";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import { getLocation, getRichDescription } from "@calcom/lib/CalEventParser";
@@ -725,6 +726,89 @@ class GoogleCalendarService implements Calendar {
}
}
+ /**
+ * Lists the events that block availability in a calendar, including their titles.
+ * The FreeBusy API used by getAvailability doesn't return titles, so the events themselves are listed here.
+ */
+ private async fetchBusyEventsWithTitles(
+ calendarId: string,
+ dateFrom: string,
+ dateTo: string
+ ): Promise<EventBusyDate[]> {
+ const calendar = await this.authedCalendar();
+ const busyEvents: EventBusyDate[] = [];
+ let pageToken: string | undefined;
+
+ do {
+ const { json: events } = await this.auth.authManager.request(
+ async () =>
+ new AxiosLikeResponseToFetchResponse(
+ await calendar.events.list({
+ calendarId,
+ timeMin: dateFrom,
+ timeMax: dateTo,
+ // Expands recurring events into the instances that fall within the date range
+ singleEvents: true,
+ maxResults: 2500, // 2500 is max
+ pageToken,
+ fields:
+ "timeZone,nextPageToken,items(summary,start,end,transparency,attendees(self,responseStatus))",
+ })
+ )
+ );
+
+ for (const event of events.items ?? []) {
+ // FreeBusy ignores events marked as "free" and the ones the user declined, so we do the same here
+ if (event.transparency === "transparent") continue;
+ if (event.attendees?.some((attendee) => attendee.self && attendee.responseStatus === "declined")) {
+ continue;
+ }
+
+ // All-day events only have a date, they start and end at midnight in the timezone of the calendar
+ const start =
+ event.start?.dateTime ??
+ (event.start?.date ? dayjs.tz(event.start.date, events.timeZone ?? "UTC").toISOString() : null);
+ const end =
+ event.end?.dateTime ??
+ (event.end?.date ? dayjs.tz(event.end.date, events.timeZone ?? "UTC").toISOString() : null);
+ if (!start || !end) continue;
+
+ busyEvents.push({ start, end, ...(event.summary ? { title: event.summary } : {}) });
+ }
+
+ pageToken = events.nextPageToken ?? undefined;
+ } while (pageToken);
+
+ return busyEvents;
+ }
+
+ async getAvailabilityWithTitles(params: GetAvailabilityParams): Promise<EventBusyDate[]> {
+ const { dateFrom, dateTo, selectedCalendars, fallbackToPrimary } = params;
+
+ const selectedCalendarIds = selectedCalendars
+ .filter((e) => e.integration === this.integrationName)
+ .map((e) => e.externalId);
+
+ // Early return if only other integrations are selected
+ if (selectedCalendarIds.length === 0 && selectedCalendars.length > 0) {
+ return [];
+ }
+
+ try {
+ const calendarIds = await this.getCalendarIds(selectedCalendarIds, fallbackToPrimary);
+ const busyEventsPerCalendar = await Promise.all(
+ calendarIds.map((calendarId) => this.fetchBusyEventsWithTitles(calendarId, dateFrom, dateTo))
+ );
+ return busyEventsPerCalendar.flat();
+ } catch (error) {
+ this.log.error(
+ "There was an error getting events from google calendar: ",
+ safeStringify({ error, selectedCalendars })
+ );
+ throw error;
+ }
+ }
+
async listCalendars(): Promise<IntegrationCalendar[]> {
this.log.debug("Listing calendars");
const calendar = await this.authedCalendar();
diff --git a/packages/app-store/googlecalendar/lib/__mocks__/googleapis.ts b/packages/app-store/googlecalendar/lib/__mocks__/googleapis.ts
index 35164df022e..577650d2cb9 100644
--- a/packages/app-store/googlecalendar/lib/__mocks__/googleapis.ts
+++ b/packages/app-store/googlecalendar/lib/__mocks__/googleapis.ts
@@ -4,6 +4,7 @@ const setCredentialsMock = vi.fn();
const freebusyQueryMock = vi.fn();
const calendarListMock = vi.fn();
const calendarsGetMock = vi.fn();
+const eventsListMock = vi.fn();
const calendarMockImplementation = {
channels: {
stop: vi.fn().mockResolvedValue(undefined),
@@ -15,6 +16,7 @@ const calendarMockImplementation = {
get: calendarsGetMock,
},
events: {
+ list: eventsListMock,
watch: vi.fn().mockResolvedValue({
data: {
kind: "api#channel",
@@ -130,6 +132,7 @@ export {
setCredentialsMock,
freebusyQueryMock,
calendarListMock,
+ eventsListMock,
getLastCreatedJWT,
getLastCreatedOAuth2Client,
setLastCreatedJWT,
diff --git a/packages/app-store/googlecalendar/lib/__tests__/CalendarService.test.ts b/packages/app-store/googlecalendar/lib/__tests__/CalendarService.test.ts
index d703b64a056..b769c02c3bf 100644
--- a/packages/app-store/googlecalendar/lib/__tests__/CalendarService.test.ts
+++ b/packages/app-store/googlecalendar/lib/__tests__/CalendarService.test.ts
@@ -8,6 +8,7 @@ import {
adminMock,
calendarListMock,
calendarMock,
+ eventsListMock,
freebusyQueryMock,
setCredentialsMock,
setLastCreatedJWT,
@@ -124,6 +125,106 @@ describe("getAvailability", () => {
});
});
+describe("getAvailabilityWithTitles", () => {
+ const selectedCalendar = { integration: "google_calendar", externalId: "[email protected]" };
+
+ test("returns the events that block availability with their titles", async () => {
+ const calendarService = BuildCalendarService(mockCredential);
+ setFullMockOAuthManagerRequest();
+ eventsListMock
+ .mockResolvedValueOnce({
+ data: {
+ timeZone: "Asia/Kolkata",
+ nextPageToken: "page2",
+ items: [
+ {
+ summary: "Standup",
+ start: { dateTime: "2024-01-10T10:00:00+05:30" },
+ end: { dateTime: "2024-01-10T10:30:00+05:30" },
+ },
+ {
+ summary: "Marked as free",
+ transparency: "transparent",
+ start: { dateTime: "2024-01-10T11:00:00+05:30" },
+ end: { dateTime: "2024-01-10T12:00:00+05:30" },
+ },
+ {
+ summary: "Declined by me",
+ attendees: [{ self: true, responseStatus: "declined" }],
+ start: { dateTime: "2024-01-10T13:00:00+05:30" },
+ end: { dateTime: "2024-01-10T14:00:00+05:30" },
+ },
+ {
+ summary: "Declined by someone else",
+ attendees: [{ responseStatus: "declined" }, { self: true, responseStatus: "accepted" }],
+ start: { dateTime: "2024-01-10T15:00:00+05:30" },
+ end: { dateTime: "2024-01-10T16:00:00+05:30" },
+ },
+ ],
+ },
+ })
+ .mockResolvedValueOnce({
+ data: {
+ timeZone: "Asia/Kolkata",
+ items: [
+ // All-day events only have a date and start at midnight in the timezone of the calendar
+ { summary: "Conference", start: { date: "2024-01-11" }, end: { date: "2024-01-13" } },
+ // Private event on a shared calendar, Google doesn't return a title for those
+ {
+ start: { dateTime: "2024-01-12T09:00:00+05:30" },
+ end: { dateTime: "2024-01-12T10:00:00+05:30" },
+ },
+ ],
+ },
+ });
+
+ const result = await calendarService.getAvailabilityWithTitles?.({
+ dateFrom: "2024-01-10T00:00:00Z",
+ dateTo: "2024-01-14T00:00:00Z",
+ selectedCalendars: [selectedCalendar],
+ mode: "overlay",
+ });
+
+ expect(result).toEqual([
+ { start: "2024-01-10T10:00:00+05:30", end: "2024-01-10T10:30:00+05:30", title: "Standup" },
+ {
+ start: "2024-01-10T15:00:00+05:30",
+ end: "2024-01-10T16:00:00+05:30",
+ title: "Declined by someone else",
+ },
+ { start: "2024-01-10T18:30:00.000Z", end: "2024-01-12T18:30:00.000Z", title: "Conference" },
+ { start: "2024-01-12T09:00:00+05:30", end: "2024-01-12T10:00:00+05:30" },
+ ]);
+ expect(eventsListMock).toHaveBeenCalledTimes(2);
+ expect(eventsListMock).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ calendarId: "[email protected]",
+ timeMin: "2024-01-10T00:00:00Z",
+ timeMax: "2024-01-14T00:00:00Z",
+ singleEvents: true,
+ pageToken: undefined,
+ })
+ );
+ expect(eventsListMock).toHaveBeenNthCalledWith(2, expect.objectContaining({ pageToken: "page2" }));
+ });
+
+ test("returns nothing when only calendars of other integrations are selected", async () => {
+ const calendarService = BuildCalendarService(mockCredential);
+ setFullMockOAuthManagerRequest();
+
+ const result = await calendarService.getAvailabilityWithTitles?.({
+ dateFrom: "2024-01-10T00:00:00Z",
+ dateTo: "2024-01-14T00:00:00Z",
+ selectedCalendars: [{ integration: "office365_calendar", externalId: "other" }],
+ mode: "overlay",
+ });
+
+ expect(result).toEqual([]);
+ expect(eventsListMock).not.toHaveBeenCalled();
+ });
+});
+
describe("getPrimaryCalendar", () => {
test("should fetch primary calendar using 'primary' keyword", async () => {
const calendarService = createGoogleCalendarServiceWithGoogleType(mockCredential);
diff --git a/packages/app-store/office365calendar/lib/CalendarService.ts b/packages/app-store/office365calendar/lib/CalendarService.ts
index 881972b98a4..0aa16903479 100644
--- a/packages/app-store/office365calendar/lib/CalendarService.ts
+++ b/packages/app-store/office365calendar/lib/CalendarService.ts
@@ -51,6 +51,7 @@ interface BodyValue {
end: { dateTime: string };
evt: { showAs: string };
start: { dateTime: string };
+ subject?: string;
}
class Office365CalendarService implements Calendar {
@@ -366,6 +367,17 @@ class Office365CalendarService implements Calendar {
}
async getAvailability(params: GetAvailabilityParams): Promise<EventBusyDate[]> {
+ return this.fetchBusyTimes(params, "showAs,start,end");
+ }
+
+ async getAvailabilityWithTitles(params: GetAvailabilityParams): Promise<EventBusyDate[]> {
+ return this.fetchBusyTimes(params, "showAs,start,end,subject");
+ }
+
+ private async fetchBusyTimes(
+ params: GetAvailabilityParams,
+ selectFields: string
+ ): Promise<EventBusyDate[]> {
const { dateFrom, dateTo, selectedCalendars } = params;
const dateFromParsed = new Date(dateFrom);
const dateToParsed = new Date(dateTo);
@@ -376,7 +388,7 @@ class Office365CalendarService implements Calendar {
// Request maximum page size (999) to minimize pagination rounds
// Microsoft Graph allows up to 999 items per page for calendarView
- const calendarSelectParams = "$select=showAs,start,end&$top=999";
+ const calendarSelectParams = `$select=${selectFields}&$top=999`;
try {
const selectedCalendarIds = selectedCalendars.reduce((calendarIds, calendar) => {
@@ -701,6 +713,7 @@ class Office365CalendarService implements Calendar {
return acc.concat({
start: `${evt.start.dateTime}Z`,
end: `${evt.end.dateTime}Z`,
+ ...(evt.subject ? { title: evt.subject } : {}),
});
}, [])
);
diff --git a/packages/app-store/office365calendar/lib/__tests__/CalendarService.test.ts b/packages/app-store/office365calendar/lib/__tests__/CalendarService.test.ts
new file mode 100644
index 00000000000..59ae45ba02d
--- /dev/null
+++ b/packages/app-store/office365calendar/lib/__tests__/CalendarService.test.ts
@@ -0,0 +1,106 @@
+import type { CredentialForCalendarServiceWithTenantId } from "@calcom/types/Credential";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import BuildCalendarService from "../CalendarService";
+
+const { requestRawMock } = vi.hoisted(() => ({ requestRawMock: vi.fn() }));
+
+vi.mock("../../../_utils/oauth/OAuthManager", () => ({
+ OAuthManager: vi.fn().mockImplementation(function () {
+ return { requestRaw: requestRawMock };
+ }),
+}));
+vi.mock("../../../_utils/oauth/oAuthManagerHelper", () => ({
+ oAuthManagerHelper: { credentialSyncVariables: {} },
+}));
+vi.mock("../getOfficeAppKeys", () => ({ getOfficeAppKeys: vi.fn() }));
+vi.mock("@calcom/features/webhooks/lib/triggerDelegationCredentialErrorWebhook", () => ({
+ triggerDelegationCredentialErrorWebhook: vi.fn(),
+}));
+
+const credential: CredentialForCalendarServiceWithTenantId = {
+ id: 1,
+ userId: 1,
+ appId: "office365-calendar",
+ type: "office365_calendar",
+ key: { access_token: "access_token", refresh_token: "refresh_token", expires_in: Date.now() + 86400 },
+ user: { email: "[email protected]" },
+ delegationCredentialId: null,
+ delegatedTo: null,
+ invalid: false,
+ teamId: null,
+ encryptedKey: null,
+};
+
+const availabilityParams = {
+ dateFrom: "2024-01-10T00:00:00Z",
+ dateTo: "2024-01-11T00:00:00Z",
+ selectedCalendars: [{ integration: "office365_calendar", externalId: "calendar-id" }],
+ mode: "overlay" as const,
+};
+
+const mockCalendarView = () => {
+ requestRawMock.mockResolvedValueOnce(
+ // The batch response is only parsed when it comes back gzip encoded, which is what Microsoft Graph sends
+ new Response(
+ JSON.stringify({
+ responses: [
+ {
+ id: "0",
+ status: 200,
+ body: {
+ value: [
+ {
+ showAs: "busy",
+ subject: "Standup",
+ start: { dateTime: "2024-01-10T10:00:00.0000000" },
+ end: { dateTime: "2024-01-10T10:30:00.0000000" },
+ },
+ {
+ showAs: "free",
+ subject: "Marked as free",
+ start: { dateTime: "2024-01-10T11:00:00.0000000" },
+ end: { dateTime: "2024-01-10T12:00:00.0000000" },
+ },
+ {
+ showAs: "tentative",
+ start: { dateTime: "2024-01-10T13:00:00.0000000" },
+ end: { dateTime: "2024-01-10T14:00:00.0000000" },
+ },
+ ],
+ },
+ },
+ ],
+ }),
+ { headers: { "content-encoding": "gzip" } }
+ )
+ );
+};
+
+const getRequestedUrl = () => JSON.parse(requestRawMock.mock.calls[0][0].options.body).requests[0].url;
+
+describe("Office365CalendarService", () => {
+ beforeEach(() => {
+ requestRawMock.mockReset();
+ });
+
+ test("getAvailabilityWithTitles returns the busy events with their titles", async () => {
+ mockCalendarView();
+
+ const result = await BuildCalendarService(credential).getAvailabilityWithTitles?.(availabilityParams);
+
+ expect(result).toEqual([
+ { start: "2024-01-10T10:00:00.0000000Z", end: "2024-01-10T10:30:00.0000000Z", title: "Standup" },
+ { start: "2024-01-10T13:00:00.0000000Z", end: "2024-01-10T14:00:00.0000000Z" },
+ ]);
+ expect(getRequestedUrl()).toContain("/me/calendars/calendar-id/calendarView");
+ expect(getRequestedUrl()).toContain("$select=showAs,start,end,subject&");
+ });
+
+ test("getAvailability doesn't ask Microsoft for the titles", async () => {
+ mockCalendarView();
+
+ await BuildCalendarService(credential).getAvailability(availabilityParams);
+
+ expect(getRequestedUrl()).toContain("$select=showAs,start,end&");
+ });
+});
diff --git a/packages/features/bookings/lib/useCheckOverlapWithOverlay.test.ts b/packages/features/bookings/lib/useCheckOverlapWithOverlay.test.ts
new file mode 100644
index 00000000000..812b36be1a6
--- /dev/null
+++ b/packages/features/bookings/lib/useCheckOverlapWithOverlay.test.ts
@@ -0,0 +1,55 @@
+/**
+ * @vitest-environment jsdom
+ */
+import dayjs from "@calcom/dayjs";
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it } from "vitest";
+import { useOverlayCalendarStore } from "../Booker/components/OverlayCalendar/store";
+import { useCheckOverlapWithOverlay } from "./useCheckOverlapWithOverlay";
+
+const checkSlot = (start: string) =>
+ renderHook(() => useCheckOverlapWithOverlay({ start: dayjs(start), selectedDuration: 30, offset: 0 }))
+ .result.current;
+
+describe("useCheckOverlapWithOverlay", () => {
+ beforeEach(() => {
+ useOverlayCalendarStore.setState({
+ overlayBusyDates: [
+ { start: new Date("2024-01-10T10:00:00"), end: new Date("2024-01-10T11:00:00"), title: "Standup" },
+ { start: new Date("2024-01-11T14:00:00"), end: new Date("2024-01-13T16:00:00"), title: "Conference" },
+ { start: new Date("2024-01-15T10:00:00"), end: new Date("2024-01-15T11:00:00") },
+ ],
+ });
+ });
+
+ it("returns the title and time of the event a slot overlaps with", () => {
+ expect(checkSlot("2024-01-10T10:30:00")).toEqual({
+ isOverlapping: true,
+ overlappingTimeStart: "10:00",
+ overlappingTimeEnd: "11:00",
+ overlappingTitle: "Standup",
+ });
+ });
+
+ it("includes the date for events spanning several days", () => {
+ expect(checkSlot("2024-01-12T09:00:00")).toEqual({
+ isOverlapping: true,
+ overlappingTimeStart: "Jan 11, 14:00",
+ overlappingTimeEnd: "Jan 13, 16:00",
+ overlappingTitle: "Conference",
+ });
+ });
+
+ it("returns no title for busy times without one", () => {
+ expect(checkSlot("2024-01-15T10:00:00")).toMatchObject({ isOverlapping: true, overlappingTitle: null });
+ });
+
+ it("doesn't overlap when the slot is free", () => {
+ expect(checkSlot("2024-01-10T12:00:00")).toEqual({
+ isOverlapping: false,
+ overlappingTimeStart: null,
+ overlappingTimeEnd: null,
+ overlappingTitle: null,
+ });
+ });
+});
diff --git a/packages/features/bookings/lib/useCheckOverlapWithOverlay.tsx b/packages/features/bookings/lib/useCheckOverlapWithOverlay.tsx
index ba994ee7f7f..52cb5e604b9 100644
--- a/packages/features/bookings/lib/useCheckOverlapWithOverlay.tsx
+++ b/packages/features/bookings/lib/useCheckOverlapWithOverlay.tsx
@@ -3,12 +3,6 @@ import dayjs from "@calcom/dayjs";
import { useOverlayCalendarStore } from "../Booker/components/OverlayCalendar/store";
-function getCurrentTime(date: Date) {
- const hours = date.getHours().toString().padStart(2, "0");
- const minutes = date.getMinutes().toString().padStart(2, "0");
- return `${hours}:${minutes}`;
-}
-
export function useCheckOverlapWithOverlay({
start,
selectedDuration,
@@ -22,6 +16,7 @@ export function useCheckOverlapWithOverlay({
let overlappingTimeStart: string | null = null;
let overlappingTimeEnd: string | null = null;
+ let overlappingTitle: string | null = null;
const isOverlapping =
overlayBusyDates &&
@@ -35,15 +30,19 @@ export function useCheckOverlapWithOverlay({
start.add(offset, "hours") < busyDateEnd &&
selectedEndTime > busyDateStart;
- overlappingTimeStart = isOverlapping ? getCurrentTime(busyDateStart.toDate()) : null;
- overlappingTimeEnd = isOverlapping ? getCurrentTime(busyDateEnd.toDate()) : null;
+ // Busy times spanning several days need the date, the time alone would be ambiguous
+ const timeFormat = busyDateStart.isSame(busyDateEnd, "day") ? "HH:mm" : "MMM D, HH:mm";
+ overlappingTimeStart = isOverlapping ? busyDateStart.format(timeFormat) : null;
+ overlappingTimeEnd = isOverlapping ? busyDateEnd.format(timeFormat) : null;
+ overlappingTitle = isOverlapping ? (busyDate.title ?? null) : null;
return isOverlapping;
});
- return { isOverlapping, overlappingTimeStart, overlappingTimeEnd } as {
+ return { isOverlapping, overlappingTimeStart, overlappingTimeEnd, overlappingTitle } as {
isOverlapping: boolean;
overlappingTimeStart: string | null;
overlappingTimeEnd: string | null;
+ overlappingTitle: string | null;
};
}
diff --git a/packages/features/calendar-subscription/lib/telemetry/CalendarTelemetryWrapper.ts b/packages/features/calendar-subscription/lib/telemetry/CalendarTelemetryWrapper.ts
index 00051b06048..810b7c9a070 100644
--- a/packages/features/calendar-subscription/lib/telemetry/CalendarTelemetryWrapper.ts
+++ b/packages/features/calendar-subscription/lib/telemetry/CalendarTelemetryWrapper.ts
@@ -181,6 +181,10 @@ export class CalendarTelemetryWrapper implements Calendar {
return results ?? [];
}
+ getAvailabilityWithTitles(params: GetAvailabilityParams): Promise<EventBusyDate[]> {
+ return this.deps.originalCalendar.getAvailabilityWithTitles?.(params) ?? this.getAvailability(params);
+ }
+
fetchAvailabilityAndSetCache?(selectedCalendars: IntegrationCalendar[]): Promise<unknown> {
return this.deps.originalCalendar.fetchAvailabilityAndSetCache?.(selectedCalendars) || Promise.resolve();
}
diff --git a/packages/features/calendar-subscription/lib/telemetry/__tests__/CalendarTelemetryWrapper.test.ts b/packages/features/calendar-subscription/lib/telemetry/__tests__/CalendarTelemetryWrapper.test.ts
new file mode 100644
index 00000000000..28acd959880
--- /dev/null
+++ b/packages/features/calendar-subscription/lib/telemetry/__tests__/CalendarTelemetryWrapper.test.ts
@@ -0,0 +1,45 @@
+import type { Calendar, EventBusyDate, GetAvailabilityParams } from "@calcom/types/Calendar";
+import { describe, expect, test, vi } from "vitest";
+import { CalendarTelemetryWrapper } from "../CalendarTelemetryWrapper";
+
+const params: GetAvailabilityParams = {
+ dateFrom: "2024-01-10T00:00:00Z",
+ dateTo: "2024-01-11T00:00:00Z",
+ selectedCalendars: [{ integration: "google_calendar", externalId: "[email protected]" }],
+ mode: "overlay",
+};
+const busyTimes: EventBusyDate[] = [{ start: "2024-01-10T10:00:00Z", end: "2024-01-10T10:30:00Z" }];
+
+const wrap = (originalCalendar: Partial<Calendar>) =>
+ new CalendarTelemetryWrapper({
+ originalCalendar: originalCalendar as Calendar,
+ calendarType: "google",
+ cacheSupported: false,
+ cacheEnabled: false,
+ credentialId: 1,
+ mode: "overlay",
+ });
+
+describe("CalendarTelemetryWrapper.getAvailabilityWithTitles", () => {
+ test("returns the titles of calendars that support them", async () => {
+ const busyTimesWithTitles = [{ ...busyTimes[0], title: "Standup" }];
+ const getAvailability = vi.fn();
+ const getAvailabilityWithTitles = vi.fn().mockResolvedValue(busyTimesWithTitles);
+
+ const result = await wrap({ getAvailability, getAvailabilityWithTitles }).getAvailabilityWithTitles(
+ params
+ );
+
+ expect(result).toEqual(busyTimesWithTitles);
+ expect(getAvailabilityWithTitles).toHaveBeenCalledWith(params);
+ expect(getAvailability).not.toHaveBeenCalled();
+ });
+
+ test("falls back to getAvailability for calendars that can't provide titles", async () => {
+ const getAvailability = vi.fn().mockResolvedValue(busyTimes);
+
+ const result = await wrap({ getAvailability }).getAvailabilityWithTitles(params);
+
+ expect(result).toEqual(busyTimes);
+ });
+});
diff --git a/packages/features/calendars/lib/getCalendarsEvents.test.ts b/packages/features/calendars/lib/getCalendarsEvents.test.ts
index d760171e970..61ca5a7d49e 100644
--- a/packages/features/calendars/lib/getCalendarsEvents.test.ts
+++ b/packages/features/calendars/lib/getCalendarsEvents.test.ts
@@ -21,6 +21,7 @@ const mockedSymmetricDecrypt = vi.mocked(symmetricDecrypt);
const mockGoogleGetAvailability = vi.fn().mockResolvedValue([]);
const mockGoogleGetAvailabilityWithTimeZones = vi.fn().mockResolvedValue([]);
+const mockGoogleGetAvailabilityWithTitles = vi.fn().mockResolvedValue([]);
const mockOfficeGetAvailability = vi.fn().mockResolvedValue([]);
const mockOfficeGetAvailabilityWithTimeZones = vi.fn().mockResolvedValue([]);
@@ -35,6 +36,7 @@ vi.mock("@calcom/app-store/calendar.services.generated", () => {
deleteEvent: vi.fn().mockResolvedValue({}),
getAvailability: mockGoogleGetAvailability,
getAvailabilityWithTimeZones: mockGoogleGetAvailabilityWithTimeZones,
+ getAvailabilityWithTitles: mockGoogleGetAvailabilityWithTitles,
listCalendars: vi.fn().mockResolvedValue([]),
}),
}),
@@ -348,6 +350,103 @@ describe("getCalendarsEvents", () => {
});
});
+ describe("Event titles", () => {
+ const busyTimes: EventBusyDate[] = [{ start: new Date(2010, 11, 2, 4), end: new Date(2010, 11, 2, 16) }];
+ const busyTimesWithTitles: EventBusyDate[] = [{ ...busyTimes[0], title: "Dentist" }];
+ let selectedGoogleCalendar: SelectedCalendar;
+
+ beforeEach(() => {
+ mockGoogleGetAvailability.mockClear();
+ mockGoogleGetAvailabilityWithTitles.mockClear();
+ mockOfficeGetAvailability.mockClear();
+ selectedGoogleCalendar = buildSelectedCalendar({
+ credentialId: 100,
+ externalId: "externalId",
+ integration: "google_calendar",
+ userId: 200,
+ id: "id",
+ });
+ });
+
+ it("should include event titles in overlay mode", async () => {
+ mockGoogleGetAvailabilityWithTitles.mockResolvedValueOnce(busyTimesWithTitles);
+
+ const result = await getCalendarsEvents(
+ [buildRegularCredential(credential)],
+ "2010-12-01",
+ "2010-12-04",
+ [selectedGoogleCalendar],
+ "overlay"
+ );
+
+ expect(mockGoogleGetAvailabilityWithTitles).toHaveBeenCalledWith({
+ dateFrom: "2010-12-01",
+ dateTo: "2010-12-04",
+ selectedCalendars: [selectedGoogleCalendar],
+ mode: "overlay",
+ fallbackToPrimary: false,
+ });
+ expect(mockGoogleGetAvailability).not.toHaveBeenCalled();
+ expect(result).toEqual([[{ ...busyTimesWithTitles[0], source: "exampleApp" }]]);
+ });
+
+ it("should never fetch event titles outside of overlay mode", async () => {
+ mockGoogleGetAvailability.mockResolvedValue(busyTimes);
+
+ for (const mode of ["slots", "booking", "none"] as const) {
+ const result = await getCalendarsEvents(
+ [buildRegularCredential(credential)],
+ "2010-12-01",
+ "2010-12-04",
+ [selectedGoogleCalendar],
+ mode
+ );
+ expect(result).toEqual([[{ ...busyTimes[0], source: "exampleApp" }]]);
+ }
+
+ expect(mockGoogleGetAvailabilityWithTitles).not.toHaveBeenCalled();
+ mockGoogleGetAvailability.mockResolvedValue([]);
+ });
+
+ it("should use getAvailability in overlay mode for calendars that can't provide titles", async () => {
+ mockOfficeGetAvailability.mockResolvedValueOnce(busyTimes);
+ const selectedOfficeCalendar = buildSelectedCalendar({
+ credentialId: 100,
+ externalId: "externalId",
+ integration: "office365_calendar",
+ userId: 200,
+ id: "id",
+ });
+
+ const result = await getCalendarsEvents(
+ [buildRegularCredential({ ...credential, type: "office365_calendar" })],
+ "2010-12-01",
+ "2010-12-04",
+ [selectedOfficeCalendar],
+ "overlay"
+ );
+
+ expect(mockOfficeGetAvailability).toHaveBeenCalledTimes(1);
+ expect(result).toEqual([[{ ...busyTimes[0], source: "exampleApp" }]]);
+ });
+
+ it("should fall back to getAvailability when fetching event titles fails", async () => {
+ mockGoogleGetAvailabilityWithTitles.mockRejectedValueOnce(new Error("Not Found"));
+ mockGoogleGetAvailability.mockResolvedValueOnce(busyTimes);
+
+ const result = await getCalendarsEvents(
+ [buildRegularCredential(credential)],
+ "2010-12-01",
+ "2010-12-04",
+ [selectedGoogleCalendar],
+ "overlay"
+ );
+
+ expect(mockGoogleGetAvailability).toHaveBeenCalledTimes(1);
+ expect(result).toEqual([[{ ...busyTimes[0], source: "exampleApp" }]]);
+ });
+ });
+
describe("Delegation Credentials", () => {
it("should allow getAvailability call even without any selected calendars with allowFallbackToPrimary=true", async () => {
const startDate = "2010-12-01";
diff --git a/packages/features/calendars/lib/getCalendarsEvents.ts b/packages/features/calendars/lib/getCalendarsEvents.ts
index c63933fca90..fc3cd49cafc 100644
--- a/packages/features/calendars/lib/getCalendarsEvents.ts
+++ b/packages/features/calendars/lib/getCalendarsEvents.ts
@@ -181,13 +181,25 @@ const getCalendarsEvents = async (
selectedCalendars: passedSelectedCalendars.map(getPiiFreeSelectedCalendar),
})
);
- const eventBusyDates = await calendarService.getAvailability({
+ const availabilityParams = {
dateFrom,
dateTo,
selectedCalendars: passedSelectedCalendars,
mode,
fallbackToPrimary: allowFallbackToPrimary,
- });
+ };
+ // "overlay" mode is only used when the calendar owner looks at their own calendars, so titles can be included.
+ // Titles are a nice-to-have, losing them must never cost the owner their busy times.
+ const eventBusyDates =
+ mode === "overlay" && calendarService.getAvailabilityWithTitles
+ ? await calendarService.getAvailabilityWithTitles(availabilityParams).catch((error) => {
+ log.warn(
+ "getAvailabilityWithTitles failed, falling back to getAvailability",
+ safeStringify({ credentialId: credential?.id, error })
+ );
+ return calendarService.getAvailability(availabilityParams);
+ })
+ : await calendarService.getAvailability(availabilityParams);
performance.mark("eventBusyDatesEnd");
performance.measure(
`[getAvailability for ${selectedCalendarIds.join(", ")}][$1]'`,
diff --git a/packages/features/calendars/weeklyview/utils/index.test.ts b/packages/features/calendars/weeklyview/utils/index.test.ts
new file mode 100644
index 00000000000..cb0ef882465
--- /dev/null
+++ b/packages/features/calendars/weeklyview/utils/index.test.ts
@@ -0,0 +1,47 @@
+import dayjs from "@calcom/dayjs";
+import { describe, expect, it } from "vitest";
+import { getEventSegmentForDay } from "./index";
+
+const day = dayjs("2024-01-10T00:00:00");
+const segment = (start: string, end: string, forDay = day) => {
+ const result = getEventSegmentForDay({ start: new Date(start), end: new Date(end) }, forDay);
+ return result && [result.start.format("YYYY-MM-DD HH:mm"), result.end.format("YYYY-MM-DD HH:mm")];
+};
+
+describe("getEventSegmentForDay", () => {
+ it("returns an event within the day as is", () => {
+ expect(segment("2024-01-10T09:00:00", "2024-01-10T10:00:00")).toEqual([
+ "2024-01-10 09:00",
+ "2024-01-10 10:00",
+ ]);
+ });
+
+ it("returns null for events on other days", () => {
+ expect(segment("2024-01-09T09:00:00", "2024-01-09T10:00:00")).toBeNull();
+ expect(segment("2024-01-11T09:00:00", "2024-01-11T10:00:00")).toBeNull();
+ });
+
+ it("splits a multi-day event into one segment per day it covers", () => {
+ const event = ["2024-01-09T14:00:00", "2024-01-11T16:00:00"] as const;
+
+ expect(segment(...event, day.subtract(1, "day"))).toEqual(["2024-01-09 14:00", "2024-01-10 00:00"]);
+ expect(segment(...event, day)).toEqual(["2024-01-10 00:00", "2024-01-11 00:00"]);
+ expect(segment(...event, day.add(1, "day"))).toEqual(["2024-01-11 00:00", "2024-01-11 16:00"]);
+ expect(segment(...event, day.add(2, "day"))).toBeNull();
+ });
+
+ it("doesn't spill an all-day event that ends at midnight into the next day", () => {
+ const event = ["2024-01-10T00:00:00", "2024-01-11T00:00:00"] as const;
+
+ expect(segment(...event, day)).toEqual(["2024-01-10 00:00", "2024-01-11 00:00"]);
+ expect(segment(...event, day.add(1, "day"))).toBeNull();
+ });
+
+ it("keeps events without a duration on the day they start", () => {
+ expect(segment("2024-01-10T00:00:00", "2024-01-10T00:00:00")).toEqual([
+ "2024-01-10 00:00",
+ "2024-01-10 00:00",
+ ]);
+ expect(segment("2024-01-10T00:00:00", "2024-01-10T00:00:00", day.subtract(1, "day"))).toBeNull();
+ });
+});
diff --git a/packages/features/calendars/weeklyview/utils/index.ts b/packages/features/calendars/weeklyview/utils/index.ts
index c31e97ca6de..1f30f315ccd 100644
--- a/packages/features/calendars/weeklyview/utils/index.ts
+++ b/packages/features/calendars/weeklyview/utils/index.ts
@@ -113,3 +113,21 @@ export function calculateHourSizeInPx(
const offsetFromTop = gridElementRef?.getBoundingClientRect().top ?? 65;
return (window.innerHeight - offsetFromTop - gapOnBottom) / (endHour - startHour);
}
+
+/**
+ * Returns the part of an event that falls on the given day, or null when the event doesn't touch that day.
+ * Events spanning midnight (multi-day, all-day) are rendered as one segment per day they cover.
+ */
+export function getEventSegmentForDay(event: { start: Date | string; end: Date | string }, day: dayjs.Dayjs) {
+ const dayStart = day.startOf("day");
+ const dayEnd = dayStart.add(1, "day");
+ const eventStart = dayjs(event.start);
+ const eventEnd = dayjs(event.end);
+
+ const startsBeforeDayEnds = eventStart.isBefore(dayEnd);
+ // An event ending exactly at midnight belongs to the previous day only
+ const endsAfterDayStarts = eventEnd.isAfter(dayStart) || !eventStart.isBefore(dayStart);
+ if (!startsBeforeDayEnds || !endsAfterDayStarts) return null;
+
+ return { start: dayjs.max(eventStart, dayStart), end: dayjs.min(eventEnd, dayEnd) };
+}
diff --git a/packages/trpc/server/routers/viewer/availability/user.handler.test.ts b/packages/trpc/server/routers/viewer/availability/user.handler.test.ts
new file mode 100644
index 00000000000..4b50c48b5ce
--- /dev/null
+++ b/packages/trpc/server/routers/viewer/availability/user.handler.test.ts
@@ -0,0 +1,50 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { TrpcSessionUser } from "../../../types";
+import { userHandler } from "./user.handler";
+import type { TUserInputSchema } from "./user.schema";
+
+const { findUsersForAvailabilityCheckMock, getUserAvailabilityMock } = vi.hoisted(() => ({
+ findUsersForAvailabilityCheckMock: vi.fn(),
+ getUserAvailabilityMock: vi.fn(),
+}));
+
+vi.mock("@calcom/features/availability/lib/findUsersForAvailabilityCheck", () => ({
+ findUsersForAvailabilityCheck: findUsersForAvailabilityCheckMock,
+}));
+vi.mock("@calcom/features/di/containers/GetUserAvailability", () => ({
+ getUserAvailabilityService: () => ({
+ getUserAvailabilityIncludingBusyTimesFromLimits: getUserAvailabilityMock,
+ }),
+}));
+
+const input = { username: "pro" } as TUserInputSchema;
+const ctx = { user: { id: 1 } as NonNullable<TrpcSessionUser> };
+
+describe("availability.user handler", () => {
+ beforeEach(() => {
+ findUsersForAvailabilityCheckMock.mockReset();
+ getUserAvailabilityMock.mockReset();
+ });
+
+ it("includes calendar event titles when the user looks at their own availability", async () => {
+ findUsersForAvailabilityCheckMock.mockResolvedValue({ id: 1 });
+
+ await userHandler({ ctx, input });
+
+ expect(getUserAvailabilityMock.mock.calls[0][0]).toMatchObject({ username: "pro", mode: "overlay" });
+ });
+
+ it("doesn't include calendar event titles of another user, even with the same username", async () => {
+ findUsersForAvailabilityCheckMock.mockResolvedValue({ id: 2 });
+
+ await userHandler({ ctx, input });
+
+ expect(getUserAvailabilityMock.mock.calls[0][0]).not.toHaveProperty("mode");
+ });
+
+ it("throws when the user doesn't exist", async () => {
+ findUsersForAvailabilityCheckMock.mockResolvedValue(null);
+
+ await expect(userHandler({ ctx, input })).rejects.toThrow("User not found");
+ });
+});
diff --git a/packages/trpc/server/routers/viewer/availability/user.handler.ts b/packages/trpc/server/routers/viewer/availability/user.handler.ts
index 78ce3e9a961..ba7a778b872 100644
--- a/packages/trpc/server/routers/viewer/availability/user.handler.ts
+++ b/packages/trpc/server/routers/viewer/availability/user.handler.ts
@@ -19,12 +19,20 @@ function getUser(username: string) {
});
}
-export const userHandler = async ({ input }: UserOptions) => {
+export const userHandler = async ({ ctx, input }: UserOptions) => {
const userAvailabilityService = getUserAvailabilityService();
const user = await getUser(input.username);
if (!user) throw new TRPCError({ code: "NOT_FOUND", message: "User not found" });
+ // Titles of calendar events are private. Only the owner gets them, anyone else just sees busy times.
+ // Compared by id because usernames aren't unique across organizations.
+ const isOwnAvailability = user.id === ctx.user.id;
return userAvailabilityService.getUserAvailabilityIncludingBusyTimesFromLimits(
- { returnDateOverrides: true, bypassBusyCalendarTimes: false, ...input },
+ {
+ returnDateOverrides: true,
+ bypassBusyCalendarTimes: false,
+ ...input,
+ ...(isOwnAvailability ? { mode: "overlay" as const } : {}),
+ },
{
user,
}
diff --git a/packages/types/BufferedBusyTime.d.ts b/packages/types/BufferedBusyTime.d.ts
index 0f0f8d35226..38b07f460a8 100644
--- a/packages/types/BufferedBusyTime.d.ts
+++ b/packages/types/BufferedBusyTime.d.ts
@@ -1,4 +1,5 @@
export interface BufferedBusyTime {
start: string | Date;
end: string | Date;
+ title?: string;
}
diff --git a/packages/types/Calendar.d.ts b/packages/types/Calendar.d.ts
index 2d025fbfd13..e23f6130e78 100644
--- a/packages/types/Calendar.d.ts
+++ b/packages/types/Calendar.d.ts
@@ -58,6 +58,7 @@ export type EventBusyDate = {
end: Date | string;
source?: string | null;
timeZone?: string;
+ title?: string;
};
export type EventBusyDetails = EventBusyDate & {
@@ -265,7 +266,8 @@ export interface IntegrationCalendar extends Ensure<Partial<_SelectedCalendar>,
/**
* Mode for calendar fetch operations to control caching behavior:
* - "slots": For getting actual calendar availability (uses cache when available)
- * - "overlay": For getting overlay calendar availability (does not use cache)
+ * - "overlay": For the calendar owner looking at their own calendars, e.g. overlay calendar and troubleshooter
+ * (does not use cache, includes event titles from calendars that support getAvailabilityWithTitles)
* - "booking": For booking confirmation (does not use cache)
* - "none": For operations that don't use getAvailability (e.g., deleteEvent, listCalendars)
*/
@@ -312,6 +314,9 @@ export interface Calendar {
// for OOO calibration (only google calendar for now)
getAvailabilityWithTimeZones?(params: GetAvailabilityParams): Promise<EventBusyDate[]>;
+ // Event titles are private, the result must only ever be shown to the owner of the calendar
+ getAvailabilityWithTitles?(params: GetAvailabilityParams): Promise<EventBusyDate[]>;
+
fetchAvailabilityAndSetCache?(selectedCalendars: IntegrationCalendar[]): Promise<unknown>;
listCalendars(event?: CalendarEvent): Promise<IntegrationCalendar[]>;