feat(bookings): improve bookings redesign (#25251)
* use booking.uid instead of booking.id for url param * show timezone on calendar * fix type * restore horizontal tab and remove header and subtitle * clean up sidebar items * fix event propagation from attendees * fetch all statuses except for cancelled on calendar view * clean up styles of the badges on BookingListItem * fix useMediaQuery * add close button to the header * add assignment reason to the details sheet * use separator row * use ToggleGroup for the top bookings tab * move ViewToggleButton * resize the action button * remove wrong prop * fix type error * fix type error * hide view toggle button on mobile (and fix the breakpoint) * remove unused e2e tests * fix e2e tests * hide toggle button when feature flag is off * update skeleton * improve attendees on booking list item and slide over * improve attendee dropdown * fix type error * move query to containers * select attendee email * infinite fetching for calendar view * update styles * fix compatibility * fix: add backward compatibility for status field in getAllUserBookings * increase calendar height * fix type error * support Member filter only for admin / owners * add debug log (TEMP) * add event border color * show Reject / Accept buttons on BookingDetailsSheet * move description section to the top * update When section * update style of Who section * add CancelBookingDialog WIP * fix CancelBookingDialog * increase clickable area * add schedule info section WIP * fix flaky reject button * fixing reschedule info WIP * add fromReschedule index to Booking * improve rescheduled information * improve reassignment * fix type error * fix unit test * respect user's weekStart value on the booking calendar view * update debug log * improve payment section * clean up * fix log message * reposition filters on list view * fix bookings controller api2 e2e test * clean up file by extracting logic into custom hooks * rename files * merge BookingCalendar into its container * extract logic into separate hook files * remove redundant logic * rearrange items on calendar view * add WeekPicker * extract filter button * responsive header on list view * horizontal scroll for ToggleGroup WIP * fix type error * fix cancelling recurring event * address feedback * fix e2e tests * fix unit test * fix e2e tests * make hover style more visible for ToggleGroup * fix margin on CancelBookingDialog * update styles on the slide over (mostly font weight) * update style of CancelBookingDialog * update styles * update margin top for the header * refactor getBookingDetails handler * fix gap in who section * auto-filter the current user on the calendar view * calculate calendar height considering top banners * improve booking details sheet interaction without overlay * update calendar event styles * update reject dialog style * put uid first in the query params * fix class name * memoize functions in useMediaQuery * query attendee with id instead of email * update margins * replace TRPCError with ErrorWithCode * move calculation outside loop * remove dead code
This commit is contained in:
1 parent
41b71d845c
commit
3986d61f40
90 files changed
+3741
-2079
No files matched your search
@@ -0,0 +1,223 @@
|
||||
"use client";
|
||||
|
||||
import { useReactTable, getCoreRowModel, getSortedRowModel } from "@tanstack/react-table";
|
||||
import React, { useMemo, useEffect } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { DataTableFilters } from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
import { useBookingCalendarData } from "~/bookings/hooks/useBookingCalendarData";
|
||||
import { useBookingFilters } from "~/bookings/hooks/useBookingFilters";
|
||||
import { useCalendarAllowedFilters } from "~/bookings/hooks/useCalendarAllowedFilters";
|
||||
import { useCurrentWeekStart } from "~/bookings/hooks/useCurrentWeekStart";
|
||||
import { useFacetedUniqueValues } from "~/bookings/hooks/useFacetedUniqueValues";
|
||||
|
||||
import { buildFilterColumns, getFilterColumnVisibility } from "../columns/filterColumns";
|
||||
import { getWeekStart } from "../lib/weekUtils";
|
||||
import { BookingDetailsSheetStoreProvider } from "../store/bookingDetailsSheetStore";
|
||||
import type { RowData, BookingListingStatus, BookingsGetOutput } from "../types";
|
||||
import { BookingCalendarView } from "./BookingCalendarView";
|
||||
import { BookingDetailsSheet } from "./BookingDetailsSheet";
|
||||
import { ViewToggleButton } from "./ViewToggleButton";
|
||||
import { WeekPicker } from "./WeekPicker";
|
||||
|
||||
// For calendar view, fetch all statuses except cancelled
|
||||
const STATUSES: BookingListingStatus[] = ["upcoming", "unconfirmed", "recurring", "past"];
|
||||
|
||||
interface BookingCalendarContainerProps {
|
||||
status: BookingListingStatus;
|
||||
permissions: {
|
||||
canReadOthersBookings: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
interface BookingCalendarInnerProps extends BookingCalendarContainerProps {
|
||||
data?: {
|
||||
bookings: BookingsGetOutput["bookings"];
|
||||
recurringInfo: BookingsGetOutput["recurringInfo"];
|
||||
totalCount: BookingsGetOutput["totalCount"];
|
||||
};
|
||||
allowedFilterIds: string[];
|
||||
isPending: boolean;
|
||||
hasError: boolean;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
function BookingCalendarInner({
|
||||
status,
|
||||
permissions,
|
||||
data,
|
||||
allowedFilterIds,
|
||||
hasError,
|
||||
errorMessage,
|
||||
}: BookingCalendarInnerProps) {
|
||||
const { t } = useLocale();
|
||||
const user = useMeQuery().data;
|
||||
const { currentWeekStart, setCurrentWeekStart, userWeekStart } = useCurrentWeekStart();
|
||||
|
||||
const goToPreviousWeek = () => {
|
||||
setCurrentWeekStart(currentWeekStart.subtract(1, "week"));
|
||||
};
|
||||
|
||||
const goToNextWeek = () => {
|
||||
setCurrentWeekStart(currentWeekStart.add(1, "week"));
|
||||
};
|
||||
|
||||
const goToToday = () => {
|
||||
setCurrentWeekStart(getWeekStart(dayjs(), userWeekStart));
|
||||
};
|
||||
|
||||
const ErrorView = errorMessage ? (
|
||||
<Alert severity="error" title={t("something_went_wrong")} message={errorMessage} />
|
||||
) : undefined;
|
||||
|
||||
const columns = useMemo(() => {
|
||||
return buildFilterColumns({ t, permissions, status }).filter((column) =>
|
||||
allowedFilterIds.includes(column.id || "")
|
||||
);
|
||||
}, [allowedFilterIds, t, permissions, status]);
|
||||
|
||||
const getFacetedUniqueValues = useFacetedUniqueValues();
|
||||
|
||||
const rowData = useBookingCalendarData({ data, status });
|
||||
|
||||
const table = useReactTable<RowData>({
|
||||
data: rowData,
|
||||
columns,
|
||||
initialState: {
|
||||
columnVisibility: getFilterColumnVisibility(),
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedUniqueValues,
|
||||
});
|
||||
|
||||
// Extract bookings from table data
|
||||
const bookings = useMemo(() => {
|
||||
return rowData
|
||||
.filter((row): row is Extract<RowData, { type: "data" }> => row.type === "data")
|
||||
.map((row) => row.booking);
|
||||
}, [rowData]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<WeekPicker
|
||||
currentWeekStart={currentWeekStart}
|
||||
userWeekStart={userWeekStart}
|
||||
onDateChange={setCurrentWeekStart}
|
||||
/>
|
||||
{allowedFilterIds.length > 0 && <DataTableFilters.FilterBar table={table} />}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button color="secondary" onClick={goToToday} className="capitalize">
|
||||
{t("today")}
|
||||
</Button>
|
||||
<ButtonGroup combined>
|
||||
<Button color="secondary" onClick={goToPreviousWeek}>
|
||||
<span className="sr-only">{t("view_previous_week")}</span>
|
||||
<Icon name="chevron-left" className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button color="secondary" onClick={goToNextWeek}>
|
||||
<span className="sr-only">{t("view_next_week")}</span>
|
||||
<Icon name="chevron-right" className="h-4 w-4" />
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
<ViewToggleButton />
|
||||
</div>
|
||||
</div>
|
||||
{hasError && ErrorView ? (
|
||||
ErrorView
|
||||
) : (
|
||||
<BookingCalendarView
|
||||
bookings={bookings}
|
||||
currentWeekStart={currentWeekStart}
|
||||
onWeekStartChange={setCurrentWeekStart}
|
||||
/>
|
||||
)}
|
||||
|
||||
<BookingDetailsSheet
|
||||
userTimeZone={user?.timeZone}
|
||||
userTimeFormat={user?.timeFormat === null ? undefined : user?.timeFormat}
|
||||
userId={user?.id}
|
||||
userEmail={user?.email}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function BookingCalendarContainer(props: BookingCalendarContainerProps) {
|
||||
const { canReadOthersBookings } = props.permissions;
|
||||
const { userIds } = useBookingFilters();
|
||||
const { currentWeekStart } = useCurrentWeekStart();
|
||||
|
||||
const allowedFilterIds = useCalendarAllowedFilters({
|
||||
canReadOthersBookings,
|
||||
});
|
||||
|
||||
const query = trpc.viewer.bookings.get.useInfiniteQuery(
|
||||
{
|
||||
limit: 100, // Use max limit for calendar view
|
||||
filters: {
|
||||
statuses: STATUSES,
|
||||
userIds,
|
||||
// Always fetch only the current week for calendar view
|
||||
afterStartDate: currentWeekStart.startOf("day").toISOString(),
|
||||
beforeEndDate: currentWeekStart.add(6, "day").endOf("day").toISOString(),
|
||||
},
|
||||
},
|
||||
{
|
||||
getNextPageParam: (lastPage) => lastPage.nextCursor,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes - data is considered fresh
|
||||
gcTime: 30 * 60 * 1000, // 30 minutes - cache retention time
|
||||
}
|
||||
);
|
||||
|
||||
// Automatically fetch all pages until no more data
|
||||
const { hasNextPage, isFetchingNextPage, fetchNextPage } = query;
|
||||
useEffect(() => {
|
||||
if (hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||
|
||||
// Flatten all pages into a single data object
|
||||
const data = useMemo(() => {
|
||||
if (!query.data?.pages) return undefined;
|
||||
|
||||
// Combine all bookings from all pages
|
||||
const allBookings = query.data.pages.flatMap((page) => page.bookings);
|
||||
|
||||
// recurringInfo is the same across all pages (queried globally by user, not per page)
|
||||
const recurringInfo = query.data.pages[0]?.recurringInfo ?? [];
|
||||
|
||||
// totalCount is the same across all pages
|
||||
const totalCount = query.data.pages[0]?.totalCount ?? 0;
|
||||
|
||||
return { bookings: allBookings, recurringInfo, totalCount };
|
||||
}, [query.data?.pages]);
|
||||
|
||||
const bookings = useMemo(() => data?.bookings ?? [], [data?.bookings]);
|
||||
|
||||
return (
|
||||
<BookingDetailsSheetStoreProvider bookings={bookings}>
|
||||
<BookingCalendarInner
|
||||
{...props}
|
||||
data={data}
|
||||
allowedFilterIds={allowedFilterIds}
|
||||
isPending={query.isPending}
|
||||
hasError={!!query.error}
|
||||
errorMessage={query.error?.message}
|
||||
/>
|
||||
</BookingDetailsSheetStoreProvider>
|
||||
);
|
||||
}
|
||||
+16
-73
@@ -6,44 +6,27 @@ import dayjs from "@calcom/dayjs";
|
||||
import { useTimePreferences } from "@calcom/features/bookings/lib";
|
||||
import { Calendar } from "@calcom/features/calendars/weeklyview";
|
||||
import type { CalendarEvent } from "@calcom/features/calendars/weeklyview/types/events";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { useBanners } from "@calcom/features/shell/banners/useBanners";
|
||||
import { useGetTheme } from "@calcom/lib/hooks/useTheme";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ButtonGroup } from "@calcom/ui/components/buttonGroup";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
import { useBookingDetailsSheetStore } from "../store/bookingDetailsSheetStore";
|
||||
import type { BookingOutput } from "../types";
|
||||
|
||||
type BookingsCalendarViewProps = {
|
||||
type BookingCalendarViewProps = {
|
||||
bookings: BookingOutput[];
|
||||
currentWeekStart: dayjs.Dayjs;
|
||||
onWeekStartChange: (weekStart: dayjs.Dayjs) => void;
|
||||
isPending?: boolean;
|
||||
};
|
||||
|
||||
export function BookingsCalendarView({
|
||||
export function BookingCalendarView({
|
||||
bookings,
|
||||
currentWeekStart,
|
||||
onWeekStartChange,
|
||||
isPending = false,
|
||||
}: BookingsCalendarViewProps) {
|
||||
const setSelectedBookingId = useBookingDetailsSheetStore((state) => state.setSelectedBookingId);
|
||||
const { t } = useLocale();
|
||||
}: BookingCalendarViewProps) {
|
||||
const setSelectedBookingUid = useBookingDetailsSheetStore((state) => state.setSelectedBookingUid);
|
||||
const { timezone } = useTimePreferences();
|
||||
const { resolvedTheme, forcedTheme } = useGetTheme();
|
||||
|
||||
const goToPreviousWeek = () => {
|
||||
onWeekStartChange(currentWeekStart.subtract(1, "week"));
|
||||
};
|
||||
|
||||
const goToNextWeek = () => {
|
||||
onWeekStartChange(currentWeekStart.add(1, "week"));
|
||||
};
|
||||
|
||||
const goToToday = () => {
|
||||
onWeekStartChange(dayjs().startOf("week"));
|
||||
};
|
||||
const { bannersHeight } = useBanners();
|
||||
|
||||
const startDate = useMemo(() => currentWeekStart.toDate(), [currentWeekStart]);
|
||||
const endDate = useMemo(() => currentWeekStart.add(6, "day").toDate(), [currentWeekStart]);
|
||||
@@ -84,58 +67,17 @@ export function BookingsCalendarView({
|
||||
options: {
|
||||
status: booking.status,
|
||||
...(eventTypeColor && { color: eventTypeColor }),
|
||||
bookingId: booking.id,
|
||||
bookingUid: booking.uid,
|
||||
},
|
||||
};
|
||||
});
|
||||
}, [bookings, currentWeekStart, resolvedTheme, forcedTheme]);
|
||||
|
||||
const weekStart = currentWeekStart;
|
||||
const weekEnd = currentWeekStart.add(6, "day");
|
||||
const startMonth = weekStart.format("MMM");
|
||||
const endMonth = weekEnd.format("MMM");
|
||||
const year = weekEnd.format("YYYY");
|
||||
|
||||
const weekRange =
|
||||
startMonth === endMonth ? (
|
||||
<>
|
||||
<span className="text-emphasis">{`${startMonth} ${weekStart.format("D")} - ${weekEnd.format(
|
||||
"D"
|
||||
)}`}</span>
|
||||
<span className="text-muted">, {year}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-emphasis">{`${weekStart.format("MMM D")} - ${weekEnd.format("MMM D")}`}</span>
|
||||
<span className="text-muted">, {year}</span>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="border-subtle flex h-[calc(100vh-260px)] min-h-[600px] flex-col rounded-2xl border">
|
||||
<div className="mx-4 mt-4 flex items-center justify-between py-1.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="text-xl font-semibold">{weekRange}</h2>
|
||||
{isPending && <Icon name="refresh-cw" className="text-muted h-4 w-4 animate-spin" />}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button color="secondary" onClick={goToToday} className="capitalize leading-4">
|
||||
{t("today")}
|
||||
</Button>
|
||||
<ButtonGroup combined>
|
||||
<Button color="secondary" onClick={goToPreviousWeek}>
|
||||
<span className="sr-only">{t("view_previous_week")}</span>
|
||||
<Icon name="chevron-left" className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button color="secondary" onClick={goToNextWeek}>
|
||||
<span className="sr-only">{t("view_next_week")}</span>
|
||||
<Icon name="chevron-right" className="h-4 w-4" />
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden rounded-2xl">
|
||||
<>
|
||||
<div
|
||||
className="border-subtle flex flex-1 flex-col overflow-y-auto overflow-x-hidden rounded-2xl border"
|
||||
style={{ height: `calc(100vh - 6rem - ${bannersHeight}px)` }}>
|
||||
<Calendar
|
||||
timezone={timezone}
|
||||
sortEvents
|
||||
@@ -150,14 +92,15 @@ export function BookingsCalendarView({
|
||||
showBorder={false}
|
||||
borderColor="subtle"
|
||||
onEventClick={(event) => {
|
||||
const bookingId = event.options?.bookingId;
|
||||
if (bookingId) {
|
||||
setSelectedBookingId(bookingId);
|
||||
const bookingUid = event.options?.bookingUid;
|
||||
if (bookingUid) {
|
||||
setSelectedBookingUid(bookingUid);
|
||||
}
|
||||
}}
|
||||
showTimezone
|
||||
hideHeader
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useMemo } from "react";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -8,9 +9,16 @@ import { useBookingLocation } from "@calcom/features/bookings/hooks";
|
||||
import { shouldShowFieldInCustomResponses } from "@calcom/lib/bookings/SystemField";
|
||||
import { formatPrice } from "@calcom/lib/currencyConversions";
|
||||
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
|
||||
import { getUserAvatarUrl } from "@calcom/lib/getAvatarUrl";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { getEveryFreqFor } from "@calcom/lib/recurringStrings";
|
||||
import { bookingMetadataSchema, eventTypeBookingFields } from "@calcom/prisma/zod-utils";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
import {
|
||||
bookingMetadataSchema,
|
||||
eventTypeBookingFields,
|
||||
EventTypeMetaDataSchema,
|
||||
} from "@calcom/prisma/zod-utils";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import type { RecurringEvent } from "@calcom/types/Calendar";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
@@ -26,9 +34,14 @@ import {
|
||||
SheetTitle,
|
||||
} from "@calcom/ui/components/sheet";
|
||||
|
||||
import assignmentReasonBadgeTitleMap from "@lib/booking/assignmentReasonBadgeTitleMap";
|
||||
|
||||
import { AcceptBookingButton } from "../../../components/booking/AcceptBookingButton";
|
||||
import { RejectBookingButton } from "../../../components/booking/RejectBookingButton";
|
||||
import { BookingActionsDropdown } from "../../../components/booking/actions/BookingActionsDropdown";
|
||||
import { BookingActionsStoreProvider } from "../../../components/booking/actions/BookingActionsStoreProvider";
|
||||
import type { BookingListingStatus } from "../../../components/booking/types";
|
||||
import { usePaymentStatus } from "../hooks/usePaymentStatus";
|
||||
import {
|
||||
useBookingDetailsSheetStore,
|
||||
useBookingDetailsSheetStoreApi,
|
||||
@@ -86,35 +99,52 @@ function BookingDetailsSheetInner({
|
||||
}: BookingDetailsSheetInnerProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
// Fetch additional booking details for reschedule information
|
||||
const { data: bookingDetails } = trpc.viewer.bookings.getBookingDetails.useQuery(
|
||||
{ uid: booking.uid },
|
||||
{
|
||||
enabled: Boolean(booking.rescheduled || booking.fromReschedule),
|
||||
// Keep data fresh but don't refetch too aggressively
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
}
|
||||
);
|
||||
|
||||
// Get navigation state directly from the store
|
||||
const hasNext = useBookingDetailsSheetStore((state) => state.hasNext());
|
||||
const hasPrevious = useBookingDetailsSheetStore((state) => state.hasPrevious());
|
||||
const setSelectedBookingId = useBookingDetailsSheetStore((state) => state.setSelectedBookingId);
|
||||
const setSelectedBookingUid = useBookingDetailsSheetStore((state) => state.setSelectedBookingUid);
|
||||
|
||||
const handleClose = () => {
|
||||
setSelectedBookingId(null);
|
||||
setSelectedBookingUid(null);
|
||||
};
|
||||
|
||||
const storeApi = useBookingDetailsSheetStoreApi();
|
||||
|
||||
const handleNext = () => {
|
||||
const nextId = storeApi.getState().getNextBookingId();
|
||||
if (nextId !== null) {
|
||||
setSelectedBookingId(nextId);
|
||||
const nextUid = storeApi.getState().getNextBookingUid();
|
||||
if (nextUid !== null) {
|
||||
setSelectedBookingUid(nextUid);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePrevious = () => {
|
||||
const prevId = storeApi.getState().getPreviousBookingId();
|
||||
if (prevId !== null) {
|
||||
setSelectedBookingId(prevId);
|
||||
const prevUid = storeApi.getState().getPreviousBookingUid();
|
||||
if (prevUid !== null) {
|
||||
setSelectedBookingUid(prevUid);
|
||||
}
|
||||
};
|
||||
|
||||
const startTime = dayjs(booking.startTime).tz(userTimeZone);
|
||||
const endTime = dayjs(booking.endTime).tz(userTimeZone);
|
||||
|
||||
const getStatusBadge = () => {
|
||||
const statusBadge = useMemo(() => {
|
||||
if (booking.rescheduled) {
|
||||
return {
|
||||
variant: "red" as const,
|
||||
label: t("rescheduled"),
|
||||
};
|
||||
}
|
||||
|
||||
switch (booking.status) {
|
||||
case "ACCEPTED":
|
||||
return { variant: "green" as const, label: t("confirmed") };
|
||||
@@ -127,9 +157,9 @@ function BookingDetailsSheetInner({
|
||||
default:
|
||||
return { variant: "gray" as const, label: booking.status };
|
||||
}
|
||||
};
|
||||
}, [booking.status, booking.rescheduled, t]);
|
||||
|
||||
const statusBadge = getStatusBadge();
|
||||
const isPending = booking.status === BookingStatus.PENDING;
|
||||
|
||||
const parsedMetadata = bookingMetadataSchema.safeParse(booking.metadata ?? null);
|
||||
const bookingMetadata = parsedMetadata.success ? parsedMetadata.data : null;
|
||||
@@ -148,16 +178,41 @@ function BookingDetailsSheetInner({
|
||||
.map(([question, answer]) => [question, answer] as [string, unknown])
|
||||
: [];
|
||||
|
||||
const reason = booking.assignmentReason?.[0];
|
||||
const reasonTitle = reason && assignmentReasonBadgeTitleMap(reason.reasonEnum);
|
||||
|
||||
return (
|
||||
<Sheet open={true} onOpenChange={handleClose}>
|
||||
<SheetContent className="overflow-y-auto">
|
||||
<SheetHeader
|
||||
showCloseButton={false}
|
||||
rightContent={
|
||||
<Sheet open={true} onOpenChange={handleClose} modal={false}>
|
||||
<SheetContent
|
||||
className="overflow-y-auto"
|
||||
hideOverlay
|
||||
onInteractOutside={(e) => {
|
||||
// Check if the click is on a booking list item
|
||||
const target = e.target as HTMLElement;
|
||||
const isBookingListItem = target.closest("[data-booking-list-item]");
|
||||
|
||||
if (isBookingListItem) {
|
||||
// Prevent closing when clicking a booking list item
|
||||
// The item's onClick will handle opening the sheet with the new booking
|
||||
e.preventDefault();
|
||||
}
|
||||
// If clicking elsewhere, allow the default behavior (close the sheet)
|
||||
}}>
|
||||
<SheetHeader showCloseButton={false} className="mt-0 w-full">
|
||||
<div className="flex items-center justify-between gap-x-4">
|
||||
<div className="flex min-w-0 flex-col gap-y-1">
|
||||
<BookingHeaderBadges
|
||||
statusBadge={statusBadge}
|
||||
reasonTitle={reasonTitle}
|
||||
booking={booking}
|
||||
recurringInfo={recurringInfo}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="icon"
|
||||
color="minimal"
|
||||
size="sm"
|
||||
color="secondary"
|
||||
StartIcon="chevron-up"
|
||||
disabled={!hasPrevious}
|
||||
onClick={(e) => {
|
||||
@@ -167,7 +222,8 @@ function BookingDetailsSheetInner({
|
||||
/>
|
||||
<Button
|
||||
variant="icon"
|
||||
color="minimal"
|
||||
size="sm"
|
||||
color="secondary"
|
||||
StartIcon="chevron-down"
|
||||
disabled={!hasNext}
|
||||
onClick={(e) => {
|
||||
@@ -175,33 +231,45 @@ function BookingDetailsSheetInner({
|
||||
handleNext();
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="icon"
|
||||
size="sm"
|
||||
color="secondary"
|
||||
StartIcon="x"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
handleClose();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant={statusBadge.variant} className="capitalize">
|
||||
{statusBadge.label}
|
||||
</Badge>
|
||||
{booking.eventType.team && <Badge variant="gray">{booking.eventType.team.name}</Badge>}
|
||||
{recurringInfo && (
|
||||
<Badge variant="gray">
|
||||
<Icon name="repeat" className="mr-1 h-3 w-3" />
|
||||
{recurringInfo.count}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</SheetHeader>
|
||||
|
||||
<SheetBody className="stack-y-6">
|
||||
<div className="stack-y-6">
|
||||
<div className="stack-y-1">
|
||||
<SheetTitle className="text-2xl font-semibold">{booking.title}</SheetTitle>
|
||||
<p className="text-subtle text-sm">
|
||||
{startTime.format("dddd, MMMM D, YYYY h:mma")} - {endTime.format("h:mma")} (
|
||||
{userTimeZone || startTime.format("Z")})
|
||||
</p>
|
||||
<SheetBody className="-mt-3">
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<SheetTitle className="text-emphasis flex items-center gap-3 text-xl font-semibold">
|
||||
<div className="bg-emphasis w-0.5 shrink-0 self-stretch rounded-lg"></div>
|
||||
<span>{booking.title}</span>
|
||||
</SheetTitle>
|
||||
</div>
|
||||
|
||||
<RescheduleRequestMessage booking={booking} />
|
||||
<WhenSection
|
||||
rescheduled={booking.rescheduled || false}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
timeZone={userTimeZone}
|
||||
previousBooking={bookingDetails?.previousBooking}
|
||||
/>
|
||||
|
||||
<OldRescheduledBookingInfo
|
||||
booking={booking}
|
||||
rescheduledToBooking={bookingDetails?.rescheduledToBooking}
|
||||
/>
|
||||
|
||||
<NewRescheduledBookingInfo booking={booking} />
|
||||
|
||||
<CancelledBookingInfo booking={booking} />
|
||||
|
||||
<WhoSection booking={booking} />
|
||||
|
||||
@@ -209,49 +277,64 @@ function BookingDetailsSheetInner({
|
||||
|
||||
<RecurringInfoSection recurringInfo={recurringInfo} />
|
||||
|
||||
<PaymentSection booking={booking} />
|
||||
<AssignmentReasonSection booking={booking} />
|
||||
|
||||
{booking.payment?.[0] && <PaymentSection booking={booking} payment={booking.payment[0]} />}
|
||||
|
||||
<SlotsSection booking={booking} />
|
||||
|
||||
<AdditionalNotesSection booking={booking} />
|
||||
|
||||
<CustomQuestionsSection
|
||||
customResponses={customResponses}
|
||||
bookingFields={booking.eventType?.bookingFields}
|
||||
/>
|
||||
|
||||
<DescriptionSection booking={booking} />
|
||||
</div>
|
||||
</SheetBody>
|
||||
|
||||
<SheetFooter className="bg-muted border-subtle -mx-4 -mb-4 border-t pt-0 sm:-mx-6 sm:-my-6">
|
||||
<div className="flex w-full flex-row items-center justify-between gap-2 px-4 pb-4 pt-4">
|
||||
<Button color="secondary" StartIcon="x" onClick={handleClose}>
|
||||
{t("close")}
|
||||
</Button>
|
||||
<div className="flex w-full min-w-0 flex-row flex-wrap items-center justify-end gap-2 px-4 pb-4 pt-4">
|
||||
{isPending ? (
|
||||
<>
|
||||
<RejectBookingButton
|
||||
bookingId={booking.id}
|
||||
bookingUid={booking.uid}
|
||||
recurringEventId={booking.recurringEventId}
|
||||
isRecurring={!!booking.recurringEventId}
|
||||
/>
|
||||
<AcceptBookingButton
|
||||
bookingId={booking.id}
|
||||
bookingUid={booking.uid}
|
||||
recurringEventId={booking.recurringEventId}
|
||||
isRecurring={!!booking.recurringEventId}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
!booking.rescheduled && (
|
||||
<JoinMeetingButton
|
||||
location={booking.location}
|
||||
metadata={booking.metadata}
|
||||
bookingStatus={booking.status}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<JoinMeetingButton
|
||||
location={booking.location}
|
||||
metadata={booking.metadata}
|
||||
bookingStatus={booking.status}
|
||||
/>
|
||||
|
||||
<BookingActionsDropdown
|
||||
booking={{
|
||||
...booking,
|
||||
listingStatus: booking.status.toLowerCase() as BookingListingStatus,
|
||||
recurringInfo: undefined,
|
||||
loggedInUser: {
|
||||
userId,
|
||||
userTimeZone,
|
||||
userTimeFormat: userTimeFormat ?? null,
|
||||
userEmail,
|
||||
},
|
||||
isToday: false,
|
||||
}}
|
||||
usePortal={false}
|
||||
context="details"
|
||||
/>
|
||||
</div>
|
||||
<BookingActionsDropdown
|
||||
booking={{
|
||||
...booking,
|
||||
listingStatus: booking.status.toLowerCase() as BookingListingStatus,
|
||||
recurringInfo: undefined,
|
||||
loggedInUser: {
|
||||
userId,
|
||||
userTimeZone,
|
||||
userTimeFormat: userTimeFormat ?? null,
|
||||
userEmail,
|
||||
},
|
||||
isToday: false,
|
||||
}}
|
||||
usePortal={false}
|
||||
context="details"
|
||||
/>
|
||||
</div>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
@@ -259,17 +342,62 @@ function BookingDetailsSheetInner({
|
||||
);
|
||||
}
|
||||
|
||||
function RescheduleRequestMessage({ booking }: { booking: BookingOutput }) {
|
||||
function WhenSection({
|
||||
rescheduled,
|
||||
startTime,
|
||||
endTime,
|
||||
timeZone,
|
||||
previousBooking,
|
||||
}: {
|
||||
rescheduled: boolean;
|
||||
startTime: dayjs.Dayjs;
|
||||
endTime: dayjs.Dayjs;
|
||||
timeZone?: string;
|
||||
previousBooking?: { uid: string; startTime: Date; endTime: Date } | null;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
if (booking.status !== "CANCELLED" || !booking.rescheduled) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Section title={t("when")}>
|
||||
{previousBooking?.startTime && previousBooking?.endTime && (
|
||||
<div className="text-default flex flex-col text-sm line-through opacity-60">
|
||||
<DisplayTimestamp
|
||||
startTime={previousBooking.startTime}
|
||||
endTime={previousBooking.endTime}
|
||||
timeZone={timeZone}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={classNames(
|
||||
"text-emphasis flex flex-col text-sm font-medium",
|
||||
rescheduled && "line-through"
|
||||
)}>
|
||||
<DisplayTimestamp startTime={startTime} endTime={endTime} timeZone={timeZone} />
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function DisplayTimestamp({
|
||||
startTime,
|
||||
endTime,
|
||||
timeZone,
|
||||
}: {
|
||||
startTime: Date | dayjs.Dayjs;
|
||||
endTime: Date | dayjs.Dayjs;
|
||||
timeZone?: string;
|
||||
}) {
|
||||
const start = startTime instanceof Date ? dayjs(startTime).tz(timeZone) : startTime;
|
||||
const end = endTime instanceof Date ? dayjs(endTime).tz(timeZone) : endTime;
|
||||
|
||||
return (
|
||||
<Badge startIcon="send" size="md" variant="gray" data-testid="request_reschedule_sent">
|
||||
{t("reschedule_request_sent")}
|
||||
</Badge>
|
||||
<>
|
||||
<span>{start.format("dddd, MMMM D, YYYY")}</span>
|
||||
<span>
|
||||
{start.format("h:mma")} - {end.format("h:mma")} ({timeZone || start.format("Z")})
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -277,35 +405,52 @@ function WhoSection({ booking }: { booking: BookingOutput }) {
|
||||
const { t } = useLocale();
|
||||
return (
|
||||
<Section title={t("who")}>
|
||||
<div className="stack-y-4">
|
||||
<div className="mt-2 flex flex-col gap-3">
|
||||
{booking.user && (
|
||||
<div className="flex items-center gap-4">
|
||||
<Avatar
|
||||
size="md"
|
||||
imageSrc={getPlaceholderAvatar(null, booking.user.name)}
|
||||
alt={booking.user.name || ""}
|
||||
imageSrc={
|
||||
booking.user.avatarUrl
|
||||
? getUserAvatarUrl(booking.user)
|
||||
: getPlaceholderAvatar(null, booking.user.name || booking.user.email)
|
||||
}
|
||||
alt={booking.user.name || booking.user.email || ""}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-emphasis truncate text-sm font-medium">{booking.user.name}</p>
|
||||
<Badge variant="blue" size="sm">
|
||||
<p className="text-emphasis truncate text-sm leading-[1.2]">
|
||||
{booking.user.name || booking.user.email}
|
||||
</p>
|
||||
<Badge variant="purple" size="sm" className="capitalize">
|
||||
{t("host")}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-default truncate text-sm">{booking.user.email}</p>
|
||||
<p className="text-default truncate text-sm leading-[1.2]">{booking.user.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{booking.attendees.map((attendee, idx) => (
|
||||
<div key={idx} className="flex items-center gap-4">
|
||||
<Avatar size="md" imageSrc={getPlaceholderAvatar(null, attendee.name)} alt={attendee.name} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-emphasis truncate text-sm font-medium">{attendee.name}</p>
|
||||
<p className="text-default truncate text-sm">{attendee.email}</p>
|
||||
{booking.attendees.map((attendee, idx) => {
|
||||
const name = attendee.user?.name || attendee.name || attendee.user?.email || attendee.email;
|
||||
return (
|
||||
<div key={idx} className="flex items-center gap-4">
|
||||
<Avatar
|
||||
size="md"
|
||||
imageSrc={
|
||||
attendee.user?.avatarUrl
|
||||
? getUserAvatarUrl(attendee.user)
|
||||
: getPlaceholderAvatar(null, name)
|
||||
}
|
||||
alt={name}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-emphasis truncate text-sm leading-[1.2]">{name}</p>
|
||||
<p className="text-default truncate text-sm leading-[1.2]">{attendee.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
@@ -321,6 +466,10 @@ function WhereSection({ booking, meta }: { booking: BookingOutput; meta: Booking
|
||||
bookingStatus: booking.status,
|
||||
});
|
||||
|
||||
if (booking.rescheduled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!locationToDisplay) {
|
||||
return null;
|
||||
}
|
||||
@@ -345,7 +494,7 @@ function WhereSection({ booking, meta }: { booking: BookingOutput; meta: Booking
|
||||
/>
|
||||
)}
|
||||
<div className="flex min-w-0 items-baseline gap-1">
|
||||
<span className="text-default shrink-0">{provider?.label}:</span>
|
||||
<span className="text-emphasis shrink-0 font-medium">{provider?.label}:</span>
|
||||
<a
|
||||
href={locationToDisplay}
|
||||
target="_blank"
|
||||
@@ -372,7 +521,7 @@ function RecurringInfoSection({
|
||||
|
||||
return (
|
||||
<Section title={t("recurring_event")}>
|
||||
<p className="text-default text-sm">
|
||||
<p className="text-emphasis text-sm font-medium">
|
||||
{getEveryFreqFor({
|
||||
t,
|
||||
recurringEvent: recurringInfo.recurringEvent,
|
||||
@@ -383,19 +532,60 @@ function RecurringInfoSection({
|
||||
);
|
||||
}
|
||||
|
||||
function PaymentSection({ booking }: { booking: BookingOutput }) {
|
||||
function AssignmentReasonSection({ booking }: { booking: BookingOutput }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
if (!booking.paid || !Array.isArray(booking.payment) || booking.payment.length === 0) {
|
||||
if (!booking.assignmentReason || booking.assignmentReason.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const payment = booking.payment[0];
|
||||
// we fetch only one assignment reason.
|
||||
const reason = booking.assignmentReason[0];
|
||||
if (!reason.reasonString) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Section title={t("assignment_reason")}>
|
||||
<div className="text-emphasis text-sm font-medium">{reason.reasonString}</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function PaymentSection({
|
||||
booking,
|
||||
payment,
|
||||
}: {
|
||||
booking: BookingOutput;
|
||||
payment: NonNullable<BookingOutput["payment"]>[number];
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
// Get refund policy from event type metadata
|
||||
const parsedEventTypeMetadata = booking.eventType?.metadata
|
||||
? EventTypeMetaDataSchema.safeParse(booking.eventType.metadata)
|
||||
: null;
|
||||
const eventTypeMetadata = parsedEventTypeMetadata?.success ? parsedEventTypeMetadata.data : null;
|
||||
|
||||
const refundPolicy = eventTypeMetadata?.apps?.stripe?.refundPolicy;
|
||||
const refundDaysCount = eventTypeMetadata?.apps?.stripe?.refundDaysCount;
|
||||
|
||||
const paymentStatusMessage = usePaymentStatus({
|
||||
bookingStatus: booking.status,
|
||||
startTime: booking.startTime,
|
||||
eventTypeTeamId: booking.eventType?.teamId,
|
||||
userId: booking.user?.id,
|
||||
payment,
|
||||
refundPolicy,
|
||||
refundDaysCount,
|
||||
});
|
||||
|
||||
const formattedPrice = formatPrice(payment.amount, payment.currency);
|
||||
|
||||
return (
|
||||
<Section title={t("payment")}>
|
||||
<p className="text-default text-sm">{formattedPrice}</p>
|
||||
<p className="text-emphasis text-sm font-medium">{formattedPrice}</p>
|
||||
{paymentStatusMessage && <p className="text-subtle text-xs">{paymentStatusMessage}</p>}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@@ -416,7 +606,7 @@ function SlotsSection({ booking }: { booking: BookingOutput }) {
|
||||
|
||||
return (
|
||||
<Section title={t("slots")}>
|
||||
<p className="text-default text-sm">{t("slots_taken", { takenSeats, totalSeats })}</p>
|
||||
<p className="text-emphasis text-sm font-medium">{t("slots_taken", { takenSeats, totalSeats })}</p>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
@@ -470,7 +660,7 @@ function CustomQuestionsSection({
|
||||
const title: string = fieldLabels.get(fieldNameStr) ?? fieldNameStr;
|
||||
return (
|
||||
<Section key={idx} title={title}>
|
||||
<p className="text-default text-sm">{String(answer)}</p>
|
||||
<p className="text-emphasis text-sm font-medium">{String(answer)}</p>
|
||||
</Section>
|
||||
);
|
||||
})}
|
||||
@@ -478,7 +668,124 @@ function CustomQuestionsSection({
|
||||
);
|
||||
}
|
||||
|
||||
function DescriptionSection({ booking }: { booking: BookingOutput }) {
|
||||
// Old booking that was rescheduled away
|
||||
function OldRescheduledBookingInfo({
|
||||
booking,
|
||||
rescheduledToBooking,
|
||||
}: {
|
||||
booking: BookingOutput;
|
||||
rescheduledToBooking?: { uid: string } | null;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
// Only show for old rescheduled bookings
|
||||
if (!booking.rescheduled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cancellationReason = booking.cancellationReason || booking.rejectionReason;
|
||||
const rescheduledBy = booking.rescheduledBy;
|
||||
const cancelledBy = booking.cancelledBy;
|
||||
|
||||
return (
|
||||
<>
|
||||
{rescheduledToBooking?.uid && (
|
||||
<Section title={t("rescheduled")}>
|
||||
<Link href={`/booking/${rescheduledToBooking.uid}`}>
|
||||
<div className="text-default flex items-center gap-1 text-sm underline">
|
||||
{t("view_booking")}
|
||||
<Icon name="external-link" className="h-4 w-4" />
|
||||
</div>
|
||||
</Link>
|
||||
</Section>
|
||||
)}
|
||||
{rescheduledBy && (
|
||||
<Section title={t("rescheduled_by")}>
|
||||
<p className="text-emphasis text-sm font-medium">{rescheduledBy}</p>
|
||||
</Section>
|
||||
)}
|
||||
{cancellationReason && (
|
||||
<Section title={t("reason")}>
|
||||
<p className="text-emphasis whitespace-pre-wrap text-sm font-medium">{cancellationReason}</p>
|
||||
</Section>
|
||||
)}
|
||||
{cancelledBy && (
|
||||
<Section title={t("cancelled_by")}>
|
||||
<p className="text-emphasis text-sm font-medium">{cancelledBy}</p>
|
||||
</Section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// New booking that replaced an old one
|
||||
function NewRescheduledBookingInfo({ booking }: { booking: BookingOutput }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
// Only show for new bookings that replaced an old one
|
||||
if (!booking.fromReschedule) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cancellationReason = booking.cancellationReason || booking.rejectionReason;
|
||||
const rescheduledBy = booking.rescheduler;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Section title={t("rescheduled_by")}>
|
||||
{rescheduledBy && <p className="text-emphasis text-sm font-medium">{rescheduledBy}</p>}
|
||||
<Link href={`/booking/${booking.fromReschedule}`}>
|
||||
<div className="text-default flex items-center gap-1 text-sm underline">
|
||||
{t("original_booking")}
|
||||
<Icon name="external-link" className="h-4 w-4" />
|
||||
</div>
|
||||
</Link>
|
||||
</Section>
|
||||
{cancellationReason && (
|
||||
<Section title={t("reschedule_reason")}>
|
||||
<p className="text-emphasis whitespace-pre-wrap text-sm font-medium">{cancellationReason}</p>
|
||||
</Section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Purely cancelled or rejected (not rescheduled)
|
||||
function CancelledBookingInfo({ booking }: { booking: BookingOutput }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
// Only show for cancelled/rejected bookings that were NOT rescheduled
|
||||
const isCancelled = booking.status === BookingStatus.CANCELLED || booking.status === BookingStatus.REJECTED;
|
||||
const wasRescheduled = booking.rescheduled === true;
|
||||
|
||||
if (!isCancelled || wasRescheduled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cancellationReason = booking.cancellationReason || booking.rejectionReason;
|
||||
const cancelledBy = booking.cancelledBy;
|
||||
|
||||
if (!cancellationReason && !cancelledBy) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{cancelledBy && (
|
||||
<Section title={t("cancelled_by")}>
|
||||
<p className="text-emphasis text-sm font-medium">{cancelledBy}</p>
|
||||
</Section>
|
||||
)}
|
||||
{cancellationReason && (
|
||||
<Section title={t("reason")}>
|
||||
<p className="text-emphasis whitespace-pre-wrap text-sm font-medium">{cancellationReason}</p>
|
||||
</Section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function AdditionalNotesSection({ booking }: { booking: BookingOutput }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
if (!booking.description) {
|
||||
@@ -486,12 +793,54 @@ function DescriptionSection({ booking }: { booking: BookingOutput }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<Section title={t("description")}>
|
||||
<p className="text-default whitespace-pre-wrap text-sm">{booking.description}</p>
|
||||
<Section title={t("additional_notes")}>
|
||||
<p className="text-emphasis whitespace-pre-wrap text-sm font-medium">{booking.description}</p>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function BookingHeaderBadges({
|
||||
statusBadge,
|
||||
reasonTitle,
|
||||
booking,
|
||||
recurringInfo,
|
||||
}: {
|
||||
statusBadge: { variant: "red" | "green" | "orange" | "gray"; label: string };
|
||||
reasonTitle: string | undefined;
|
||||
booking: BookingOutput;
|
||||
recurringInfo: { count: number; recurringEvent: RecurringEvent } | null;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
const payment = booking.payment?.[0];
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<Badge variant={statusBadge.variant} className="capitalize">
|
||||
{statusBadge.label}
|
||||
</Badge>
|
||||
{reasonTitle && (
|
||||
<Badge variant="gray" className="capitalize">
|
||||
{reasonTitle}
|
||||
</Badge>
|
||||
)}
|
||||
{booking.eventType.team && <Badge variant="gray">{booking.eventType.team.name}</Badge>}
|
||||
{booking.paid && !payment ? (
|
||||
<Badge variant="orange">{t("error_collecting_card")}</Badge>
|
||||
) : booking.paid ? (
|
||||
<Badge variant="green" data-testid="paid_badge">
|
||||
{payment?.paymentOption === "HOLD" ? t("card_held") : t("paid")}
|
||||
</Badge>
|
||||
) : null}
|
||||
{recurringInfo && (
|
||||
<Badge variant="gray">
|
||||
<Icon name="repeat" className="mr-1 h-3 w-3" />
|
||||
{recurringInfo.count}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({
|
||||
title,
|
||||
className,
|
||||
@@ -502,8 +851,8 @@ function Section({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className={classNames("stack-y-1", className)}>
|
||||
<h3 className="text-subtle text-xs font-semibold">{title}</h3>
|
||||
<div className={classNames("flex flex-col gap-1", className)}>
|
||||
<h3 className="text-subtle text-xs font-medium">{title}</h3>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
|
||||
+5
-16
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { Table as ReactTable } from "@tanstack/react-table";
|
||||
|
||||
import { DataTableWrapper, DataTableFilters, DataTableSegment } from "@calcom/features/data-table";
|
||||
import { DataTableWrapper } from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
|
||||
@@ -18,7 +18,7 @@ const descriptionByStatus: Record<BookingListingStatus, string> = {
|
||||
unconfirmed: "unconfirmed_bookings",
|
||||
};
|
||||
|
||||
type BookingsListViewProps = {
|
||||
type BookingListViewProps = {
|
||||
status: BookingListingStatus;
|
||||
table: ReactTable<RowData>;
|
||||
isPending: boolean;
|
||||
@@ -27,14 +27,14 @@ type BookingsListViewProps = {
|
||||
hasError?: boolean;
|
||||
};
|
||||
|
||||
export function BookingsList({
|
||||
export function BookingList({
|
||||
status,
|
||||
table,
|
||||
isPending,
|
||||
totalRowCount,
|
||||
ErrorView,
|
||||
hasError,
|
||||
}: BookingsListViewProps) {
|
||||
}: BookingListViewProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
@@ -48,18 +48,7 @@ export function BookingsList({
|
||||
totalRowCount={totalRowCount}
|
||||
variant="compact"
|
||||
paginationMode="standard"
|
||||
ToolbarLeft={
|
||||
<>
|
||||
<DataTableFilters.FilterBar table={table} />
|
||||
</>
|
||||
}
|
||||
ToolbarRight={
|
||||
<>
|
||||
<DataTableFilters.ClearFiltersButton />
|
||||
<DataTableSegment.SaveButton />
|
||||
<DataTableSegment.Select />
|
||||
</>
|
||||
}
|
||||
separatorClassName="py-4 pl-6 text-xs uppercase leading-4"
|
||||
LoaderView={<SkeletonLoader />}
|
||||
EmptyView={
|
||||
<div className="flex items-center justify-center pt-2 xl:pt-0">
|
||||
@@ -0,0 +1,266 @@
|
||||
"use client";
|
||||
|
||||
import { useReactTable, getCoreRowModel, getSortedRowModel } from "@tanstack/react-table";
|
||||
import { useRouter } from "next/navigation";
|
||||
import React, { useState, useMemo, useEffect, useCallback } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import {
|
||||
useDataTable,
|
||||
DataTableFilters,
|
||||
DataTableSegment,
|
||||
useDisplayedFilterCount,
|
||||
} from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { Badge } from "@calcom/ui/components/badge";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { ToggleGroup } from "@calcom/ui/components/form";
|
||||
import { WipeMyCalActionButton } from "@calcom/web/components/apps/wipemycalother/wipeMyCalActionButton";
|
||||
|
||||
import { useBookingFilters } from "~/bookings/hooks/useBookingFilters";
|
||||
import { useBookingListColumns } from "~/bookings/hooks/useBookingListColumns";
|
||||
import { useBookingListData } from "~/bookings/hooks/useBookingListData";
|
||||
import { useBookingStatusTab } from "~/bookings/hooks/useBookingStatusTab";
|
||||
import { useFacetedUniqueValues } from "~/bookings/hooks/useFacetedUniqueValues";
|
||||
|
||||
import {
|
||||
BookingDetailsSheetStoreProvider,
|
||||
useBookingDetailsSheetStore,
|
||||
} from "../store/bookingDetailsSheetStore";
|
||||
import type { RowData, BookingListingStatus, BookingsGetOutput } from "../types";
|
||||
import { BookingDetailsSheet } from "./BookingDetailsSheet";
|
||||
import { BookingList } from "./BookingList";
|
||||
import { ViewToggleButton } from "./ViewToggleButton";
|
||||
|
||||
interface FilterButtonProps {
|
||||
table: ReturnType<typeof useReactTable<RowData>>;
|
||||
displayedFilterCount: number;
|
||||
setShowFilters: (value: boolean | ((prev: boolean) => boolean)) => void;
|
||||
}
|
||||
|
||||
function FilterButton({ table, displayedFilterCount, setShowFilters }: FilterButtonProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
if (displayedFilterCount === 0) {
|
||||
return <DataTableFilters.AddFilterButton table={table} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
color="secondary"
|
||||
StartIcon="list-filter"
|
||||
className="h-full"
|
||||
size="sm"
|
||||
onClick={() => setShowFilters((value) => !value)}>
|
||||
{t("filter")}
|
||||
<Badge variant="gray" className="ml-1">
|
||||
{displayedFilterCount}
|
||||
</Badge>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
interface BookingListContainerProps {
|
||||
status: BookingListingStatus;
|
||||
permissions: {
|
||||
canReadOthersBookings: boolean;
|
||||
};
|
||||
bookingsV3Enabled: boolean;
|
||||
}
|
||||
|
||||
interface BookingListInnerProps extends BookingListContainerProps {
|
||||
data?: BookingsGetOutput;
|
||||
isPending: boolean;
|
||||
hasError: boolean;
|
||||
errorMessage?: string;
|
||||
totalRowCount?: number;
|
||||
}
|
||||
|
||||
function BookingListInner({
|
||||
status,
|
||||
permissions,
|
||||
bookingsV3Enabled,
|
||||
data,
|
||||
isPending,
|
||||
hasError,
|
||||
errorMessage,
|
||||
totalRowCount,
|
||||
}: BookingListInnerProps) {
|
||||
const { t } = useLocale();
|
||||
const user = useMeQuery().data;
|
||||
const setSelectedBookingUid = useBookingDetailsSheetStore((state) => state.setSelectedBookingUid);
|
||||
const router = useRouter();
|
||||
const [showFilters, setShowFilters] = useState(true);
|
||||
|
||||
const ErrorView = errorMessage ? (
|
||||
<Alert severity="error" title={t("something_went_wrong")} message={errorMessage} />
|
||||
) : undefined;
|
||||
|
||||
const handleBookingClick = useCallback(
|
||||
(bookingUid: string) => {
|
||||
setSelectedBookingUid(bookingUid);
|
||||
},
|
||||
[setSelectedBookingUid]
|
||||
);
|
||||
|
||||
const columns = useBookingListColumns({
|
||||
user,
|
||||
status,
|
||||
canReadOthersBookings: permissions.canReadOthersBookings,
|
||||
bookingsV3Enabled,
|
||||
handleBookingClick,
|
||||
});
|
||||
|
||||
const finalData = useBookingListData({ data, status, userTimeZone: user?.timeZone });
|
||||
|
||||
const getFacetedUniqueValues = useFacetedUniqueValues();
|
||||
|
||||
const displayedFilterCount = useDisplayedFilterCount();
|
||||
const { currentTab, tabOptions } = useBookingStatusTab();
|
||||
|
||||
useEffect(() => {
|
||||
if (displayedFilterCount === 0) {
|
||||
// reset to true, so it shows filters as soon as any filter is applied
|
||||
setShowFilters(true);
|
||||
}
|
||||
}, [displayedFilterCount]);
|
||||
|
||||
const table = useReactTable<RowData>({
|
||||
data: finalData,
|
||||
columns,
|
||||
initialState: {
|
||||
columnVisibility: {
|
||||
eventTypeId: false,
|
||||
teamId: false,
|
||||
userId: false,
|
||||
attendeeName: false,
|
||||
attendeeEmail: false,
|
||||
dateRange: false,
|
||||
bookingUid: false,
|
||||
},
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedUniqueValues,
|
||||
});
|
||||
|
||||
const isEmpty = !data?.bookings || data.bookings.length === 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{/* Desktop: full width on first row, Mobile: full width on first row with horizontal scroll */}
|
||||
<div className="w-full md:w-auto">
|
||||
<div className="overflow-x-auto md:overflow-visible">
|
||||
<ToggleGroup
|
||||
value={currentTab}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const selectedTab = tabOptions.find((tab) => tab.value === value);
|
||||
if (selectedTab?.href) {
|
||||
router.push(selectedTab.href);
|
||||
}
|
||||
}}
|
||||
options={tabOptions}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Desktop: second item on first row, Mobile: first item on second row */}
|
||||
<FilterButton
|
||||
table={table}
|
||||
displayedFilterCount={displayedFilterCount}
|
||||
setShowFilters={setShowFilters}
|
||||
/>
|
||||
|
||||
{/* Desktop: auto-pushed to right via flex-grow spacer, Mobile: continue on second row */}
|
||||
<div className="hidden grow md:block" />
|
||||
|
||||
<DataTableSegment.Select shortLabel />
|
||||
{bookingsV3Enabled && <ViewToggleButton />}
|
||||
</div>
|
||||
{displayedFilterCount > 0 && showFilters && (
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<DataTableFilters.ActiveFilters table={table} />
|
||||
<DataTableFilters.AddFilterButton table={table} variant="minimal" />
|
||||
|
||||
{/* Desktop: auto-pushed to right via flex-grow spacer */}
|
||||
<div className="hidden flex-grow md:block" />
|
||||
|
||||
<DataTableFilters.ClearFiltersButton />
|
||||
<DataTableSegment.SaveButton />
|
||||
</div>
|
||||
)}
|
||||
{status === "upcoming" && !isEmpty && (
|
||||
<WipeMyCalActionButton className="mt-4" bookingStatus={status} bookingsEmpty={isEmpty} />
|
||||
)}
|
||||
<div className="mt-4">
|
||||
<BookingList
|
||||
status={status}
|
||||
table={table}
|
||||
isPending={isPending}
|
||||
totalRowCount={totalRowCount}
|
||||
ErrorView={ErrorView}
|
||||
hasError={hasError}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{bookingsV3Enabled && (
|
||||
<BookingDetailsSheet
|
||||
userTimeZone={user?.timeZone}
|
||||
userTimeFormat={user?.timeFormat === null ? undefined : user?.timeFormat}
|
||||
userId={user?.id}
|
||||
userEmail={user?.email}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function BookingListContainer(props: BookingListContainerProps) {
|
||||
const { limit, offset } = useDataTable();
|
||||
const { eventTypeIds, teamIds, userIds, dateRange, attendeeName, attendeeEmail, bookingUid } =
|
||||
useBookingFilters();
|
||||
|
||||
const query = trpc.viewer.bookings.get.useQuery(
|
||||
{
|
||||
limit,
|
||||
offset,
|
||||
filters: {
|
||||
statuses: [props.status],
|
||||
eventTypeIds,
|
||||
teamIds,
|
||||
userIds,
|
||||
attendeeName,
|
||||
attendeeEmail,
|
||||
bookingUid,
|
||||
afterStartDate: dateRange?.startDate
|
||||
? dayjs(dateRange?.startDate).startOf("day").toISOString()
|
||||
: undefined,
|
||||
beforeEndDate: dateRange?.endDate ? dayjs(dateRange?.endDate).endOf("day").toISOString() : undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes - data is considered fresh
|
||||
gcTime: 30 * 60 * 1000, // 30 minutes - cache retention time
|
||||
}
|
||||
);
|
||||
|
||||
const bookings = useMemo(() => query.data?.bookings ?? [], [query.data?.bookings]);
|
||||
|
||||
return (
|
||||
<BookingDetailsSheetStoreProvider bookings={bookings}>
|
||||
<BookingListInner
|
||||
{...props}
|
||||
data={query.data}
|
||||
isPending={query.isPending}
|
||||
hasError={!!query.error}
|
||||
errorMessage={query.error?.message}
|
||||
totalRowCount={query.data?.totalCount}
|
||||
/>
|
||||
</BookingDetailsSheetStoreProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { Table as ReactTable } from "@tanstack/react-table";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import {
|
||||
DataTableFilters,
|
||||
DataTableSegment,
|
||||
useDataTable,
|
||||
ColumnFilterType,
|
||||
} from "@calcom/features/data-table";
|
||||
import { CUSTOM_PRESET } from "@calcom/features/data-table/lib/dateRange";
|
||||
|
||||
import type { RowData, BookingListingStatus, BookingOutput } from "../types";
|
||||
import { BookingsCalendarView } from "./BookingsCalendarView";
|
||||
|
||||
type BookingsCalendarProps = {
|
||||
status: BookingListingStatus;
|
||||
table: ReactTable<RowData>;
|
||||
isPending?: boolean;
|
||||
currentWeekStart: dayjs.Dayjs;
|
||||
setCurrentWeekStart: (
|
||||
value: dayjs.Dayjs | ((old: dayjs.Dayjs) => dayjs.Dayjs | null) | null
|
||||
) => Promise<URLSearchParams>;
|
||||
bookings: BookingOutput[];
|
||||
ErrorView?: React.ReactNode;
|
||||
hasError?: boolean;
|
||||
};
|
||||
|
||||
const COLUMN_IDS_TO_HIDE = ["dateRange"];
|
||||
|
||||
export function BookingsCalendar({
|
||||
table,
|
||||
isPending = false,
|
||||
currentWeekStart,
|
||||
setCurrentWeekStart,
|
||||
bookings,
|
||||
ErrorView,
|
||||
hasError,
|
||||
}: BookingsCalendarProps) {
|
||||
const { updateFilter } = useDataTable();
|
||||
|
||||
const handleWeekStartChange = useCallback(
|
||||
(newWeekStart: dayjs.Dayjs) => {
|
||||
setCurrentWeekStart(newWeekStart);
|
||||
|
||||
// Always set the date range to match the current week exactly
|
||||
const startDate = newWeekStart.toDate();
|
||||
const endDate = newWeekStart.add(6, "day").toDate();
|
||||
|
||||
updateFilter("dateRange", {
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
data: {
|
||||
startDate: startDate.toISOString(),
|
||||
endDate: endDate.toISOString(),
|
||||
preset: CUSTOM_PRESET.value,
|
||||
},
|
||||
});
|
||||
},
|
||||
[updateFilter, setCurrentWeekStart]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<DataTableFilters.FilterBar table={table} columnIdsToHide={COLUMN_IDS_TO_HIDE} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<DataTableFilters.ClearFiltersButton />
|
||||
<DataTableSegment.SaveButton />
|
||||
<DataTableSegment.Select />
|
||||
</div>
|
||||
</div>
|
||||
{hasError && ErrorView ? (
|
||||
ErrorView
|
||||
) : (
|
||||
<BookingsCalendarView
|
||||
bookings={bookings}
|
||||
currentWeekStart={currentWeekStart}
|
||||
onWeekStartChange={handleWeekStartChange}
|
||||
isPending={isPending}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useReactTable, getCoreRowModel, getSortedRowModel } from "@tanstack/react-table";
|
||||
import { createParser, useQueryState } from "nuqs";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
|
||||
import { useFacetedUniqueValues } from "~/bookings/hooks/useFacetedUniqueValues";
|
||||
|
||||
import { buildFilterColumns, getFilterColumnVisibility } from "../columns/filterColumns";
|
||||
import { BookingDetailsSheetStoreProvider } from "../store/bookingDetailsSheetStore";
|
||||
import type { RowData, BookingListingStatus, BookingsGetOutput, BookingOutput } from "../types";
|
||||
import { BookingDetailsSheet } from "./BookingDetailsSheet";
|
||||
import { BookingsCalendar } from "./BookingsCalendar";
|
||||
|
||||
const weekStartParser = createParser({
|
||||
parse: (value: string) => {
|
||||
const parsed = dayjs(value);
|
||||
return parsed.isValid() ? parsed.startOf("week") : dayjs().startOf("week");
|
||||
},
|
||||
serialize: (value: dayjs.Dayjs) => value.format("YYYY-MM-DD"),
|
||||
});
|
||||
|
||||
interface BookingsCalendarContainerProps {
|
||||
status: BookingListingStatus;
|
||||
permissions: {
|
||||
canReadOthersBookings: boolean;
|
||||
};
|
||||
data?: BookingsGetOutput;
|
||||
isPending?: boolean;
|
||||
ErrorView?: React.ReactNode;
|
||||
hasError?: boolean;
|
||||
}
|
||||
|
||||
export function BookingsCalendarContainer({
|
||||
status,
|
||||
permissions,
|
||||
data,
|
||||
isPending = false,
|
||||
ErrorView,
|
||||
hasError,
|
||||
}: BookingsCalendarContainerProps) {
|
||||
const { t } = useLocale();
|
||||
const user = useMeQuery().data;
|
||||
|
||||
const [currentWeekStart, setCurrentWeekStart] = useQueryState(
|
||||
"weekStart",
|
||||
weekStartParser.withDefault(dayjs().startOf("week"))
|
||||
);
|
||||
|
||||
const columns = useMemo(() => {
|
||||
return buildFilterColumns({ t, permissions, status });
|
||||
}, [t, permissions, status]);
|
||||
|
||||
const getFacetedUniqueValues = useFacetedUniqueValues();
|
||||
|
||||
/**
|
||||
* Transform raw booking data into RowData format for the calendar view
|
||||
* - Deduplicates recurring bookings for recurring/unconfirmed/cancelled tabs
|
||||
* - Attaches recurring info and isToday flag to each booking
|
||||
*/
|
||||
const rowData = useMemo<RowData[]>(() => {
|
||||
if (!data?.bookings) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// For recurring/unconfirmed/cancelled tabs: track recurring series to show only one representative booking per series
|
||||
// Key: recurringEventId, Value: array of all bookings in that series
|
||||
const shownBookings: Record<string, BookingOutput[]> = {};
|
||||
|
||||
const filterBookings = (booking: BookingOutput) => {
|
||||
// Deduplicate recurring bookings for specific status tabs
|
||||
// This ensures we show only ONE booking per recurring series instead of all occurrences
|
||||
if (status === "recurring" || status == "unconfirmed" || status === "cancelled") {
|
||||
// Non-recurring bookings are always shown
|
||||
if (!booking.recurringEventId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If we've already encountered this recurring series
|
||||
if (
|
||||
shownBookings[booking.recurringEventId] !== undefined &&
|
||||
shownBookings[booking.recurringEventId].length > 0
|
||||
) {
|
||||
// Store this occurrence but DON'T display it (return false to filter out)
|
||||
shownBookings[booking.recurringEventId].push(booking);
|
||||
return false;
|
||||
}
|
||||
|
||||
// First occurrence of this recurring series - show it and start tracking
|
||||
shownBookings[booking.recurringEventId] = [booking];
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
return data.bookings.filter(filterBookings).map((booking) => {
|
||||
const bookingDate = dayjs(booking.startTime).tz(user?.timeZone);
|
||||
const today = dayjs().tz(user?.timeZone).format("YYYY-MM-DD");
|
||||
const bookingDateStr = bookingDate.format("YYYY-MM-DD");
|
||||
|
||||
return {
|
||||
type: "data" as const,
|
||||
booking,
|
||||
isToday: bookingDateStr === today,
|
||||
recurringInfo: data.recurringInfo.find((info) => info.recurringEventId === booking.recurringEventId),
|
||||
};
|
||||
});
|
||||
}, [data, status, user?.timeZone]);
|
||||
|
||||
const table = useReactTable<RowData>({
|
||||
data: rowData,
|
||||
columns,
|
||||
initialState: {
|
||||
columnVisibility: getFilterColumnVisibility(),
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedUniqueValues,
|
||||
});
|
||||
|
||||
// Extract bookings from table data and filter by current week
|
||||
const bookings = useMemo(() => {
|
||||
const weekStart = currentWeekStart;
|
||||
const weekEnd = currentWeekStart.add(6, "day");
|
||||
|
||||
return rowData
|
||||
.filter((row): row is Extract<RowData, { type: "data" }> => row.type === "data")
|
||||
.map((row) => row.booking)
|
||||
.filter((booking) => {
|
||||
const bookingStart = dayjs(booking.startTime);
|
||||
return (
|
||||
(bookingStart.isAfter(weekStart) || bookingStart.isSame(weekStart, "day")) &&
|
||||
bookingStart.isBefore(weekEnd.endOf("day"))
|
||||
);
|
||||
});
|
||||
}, [rowData, currentWeekStart]);
|
||||
|
||||
return (
|
||||
<BookingDetailsSheetStoreProvider bookings={bookings}>
|
||||
<BookingsCalendar
|
||||
status={status}
|
||||
table={table}
|
||||
isPending={isPending}
|
||||
currentWeekStart={currentWeekStart}
|
||||
setCurrentWeekStart={setCurrentWeekStart}
|
||||
bookings={bookings}
|
||||
ErrorView={ErrorView}
|
||||
hasError={hasError}
|
||||
/>
|
||||
|
||||
<BookingDetailsSheet
|
||||
userTimeZone={user?.timeZone}
|
||||
userTimeFormat={user?.timeFormat === null ? undefined : user?.timeFormat}
|
||||
userId={user?.id}
|
||||
userEmail={user?.email}
|
||||
/>
|
||||
</BookingDetailsSheetStoreProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,346 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useReactTable, getCoreRowModel, getSortedRowModel, createColumnHelper } from "@tanstack/react-table";
|
||||
import { useMemo, useCallback } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { ColumnFilterType } from "@calcom/features/data-table";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
import BookingListItem from "@calcom/web/components/booking/BookingListItem";
|
||||
|
||||
import { useFacetedUniqueValues } from "~/bookings/hooks/useFacetedUniqueValues";
|
||||
|
||||
import {
|
||||
BookingDetailsSheetStoreProvider,
|
||||
useBookingDetailsSheetStore,
|
||||
} from "../store/bookingDetailsSheetStore";
|
||||
import type { RowData, BookingListingStatus, BookingsGetOutput, BookingOutput } from "../types";
|
||||
import { BookingDetailsSheet } from "./BookingDetailsSheet";
|
||||
import { BookingsList } from "./BookingsList";
|
||||
|
||||
interface BookingsListContainerProps {
|
||||
status: BookingListingStatus;
|
||||
permissions: {
|
||||
canReadOthersBookings: boolean;
|
||||
};
|
||||
data?: BookingsGetOutput;
|
||||
isPending: boolean;
|
||||
enableDetailsSheet: boolean;
|
||||
totalRowCount?: number;
|
||||
ErrorView?: React.ReactNode;
|
||||
hasError?: boolean;
|
||||
}
|
||||
|
||||
function BookingsListInner({
|
||||
status,
|
||||
permissions,
|
||||
data,
|
||||
isPending,
|
||||
enableDetailsSheet,
|
||||
totalRowCount,
|
||||
ErrorView,
|
||||
hasError,
|
||||
}: BookingsListContainerProps) {
|
||||
const { t } = useLocale();
|
||||
const user = useMeQuery().data;
|
||||
const setSelectedBookingId = useBookingDetailsSheetStore((state) => state.setSelectedBookingId);
|
||||
|
||||
const handleBookingClick = useCallback(
|
||||
(bookingId: number) => {
|
||||
setSelectedBookingId(bookingId);
|
||||
},
|
||||
[setSelectedBookingId]
|
||||
);
|
||||
|
||||
// Define table columns for filtering (hidden columns used for filter UI)
|
||||
const columns = useMemo(() => {
|
||||
const columnHelper = createColumnHelper<RowData>();
|
||||
|
||||
return [
|
||||
columnHelper.accessor((row) => row.type === "data" && row.booking.eventType.id, {
|
||||
id: "eventTypeId",
|
||||
header: t("event_type"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.MULTI_SELECT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row.type === "data" && row.booking.eventType.team?.id, {
|
||||
id: "teamId",
|
||||
header: t("team"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.MULTI_SELECT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row.type === "data" && row.booking.user?.id, {
|
||||
id: "userId",
|
||||
header: t("member"),
|
||||
enableColumnFilter: permissions.canReadOthersBookings,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.MULTI_SELECT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row, {
|
||||
id: "attendeeName",
|
||||
header: t("attendee_name"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.TEXT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row, {
|
||||
id: "attendeeEmail",
|
||||
header: t("attendee_email_variable"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.TEXT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row, {
|
||||
id: "dateRange",
|
||||
header: t("date_range"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
dateRangeOptions: {
|
||||
range: status === "past" ? "past" : "custom",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row.type === "data" && row.booking.uid, {
|
||||
id: "bookingUid",
|
||||
header: t("booking_uid"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.TEXT,
|
||||
textOptions: {
|
||||
allowedOperators: ["equals"],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.display({
|
||||
id: "customView",
|
||||
cell: (props) => {
|
||||
if (props.row.original.type === "data") {
|
||||
const { booking, recurringInfo, isToday } = props.row.original;
|
||||
return (
|
||||
<BookingListItem
|
||||
key={booking.id}
|
||||
isToday={isToday}
|
||||
loggedInUser={{
|
||||
userId: user?.id,
|
||||
userTimeZone: user?.timeZone,
|
||||
userTimeFormat: user?.timeFormat,
|
||||
userEmail: user?.email,
|
||||
}}
|
||||
listingStatus={status}
|
||||
recurringInfo={recurringInfo}
|
||||
{...(enableDetailsSheet && { onClick: () => handleBookingClick(booking.id) })}
|
||||
{...booking}
|
||||
/>
|
||||
);
|
||||
} else if (props.row.original.type === "today") {
|
||||
return (
|
||||
<p className="text-subtle bg-subtle w-full py-4 pl-6 text-xs font-semibold uppercase leading-4">
|
||||
{t("today")}
|
||||
</p>
|
||||
);
|
||||
} else if (props.row.original.type === "next") {
|
||||
return (
|
||||
<p className="text-subtle bg-subtle w-full py-4 pl-6 text-xs font-semibold uppercase leading-4">
|
||||
{t("next")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
},
|
||||
}),
|
||||
];
|
||||
}, [user, status, t, permissions.canReadOthersBookings, enableDetailsSheet, handleBookingClick]);
|
||||
|
||||
/**
|
||||
* Transform raw bookings into flat list (excluding today's bookings for "upcoming" status)
|
||||
* - Deduplicates recurring bookings for recurring/unconfirmed/cancelled tabs
|
||||
* - For "upcoming" status, filters out today's bookings (they're shown in separate "Today" section)
|
||||
*/
|
||||
const flatData = useMemo<RowData[]>(() => {
|
||||
// For recurring/unconfirmed/cancelled tabs: track recurring series to show only one representative booking per series
|
||||
// Key: recurringEventId, Value: array of all bookings in that series
|
||||
const shownBookings: Record<string, BookingOutput[]> = {};
|
||||
|
||||
const filterBookings = (booking: BookingOutput) => {
|
||||
// Deduplicate recurring bookings for specific status tabs
|
||||
// This ensures we show only ONE booking per recurring series instead of all occurrences
|
||||
if (status === "recurring" || status == "unconfirmed" || status === "cancelled") {
|
||||
// Non-recurring bookings are always shown
|
||||
if (!booking.recurringEventId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If we've already encountered this recurring series
|
||||
if (
|
||||
shownBookings[booking.recurringEventId] !== undefined &&
|
||||
shownBookings[booking.recurringEventId].length > 0
|
||||
) {
|
||||
// Store this occurrence but DON'T display it (return false to filter out)
|
||||
shownBookings[booking.recurringEventId].push(booking);
|
||||
return false;
|
||||
}
|
||||
|
||||
// First occurrence of this recurring series - show it and start tracking
|
||||
shownBookings[booking.recurringEventId] = [booking];
|
||||
} else if (status === "upcoming") {
|
||||
// For "upcoming" tab, exclude today's bookings (they're shown separately in the "Today" section)
|
||||
return (
|
||||
dayjs(booking.startTime).tz(user?.timeZone).format("YYYY-MM-DD") !==
|
||||
dayjs().tz(user?.timeZone).format("YYYY-MM-DD")
|
||||
);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
return (
|
||||
data?.bookings.filter(filterBookings).map((booking) => ({
|
||||
type: "data",
|
||||
booking,
|
||||
recurringInfo: data?.recurringInfo.find((info) => info.recurringEventId === booking.recurringEventId),
|
||||
isToday: false,
|
||||
})) || []
|
||||
);
|
||||
}, [data, status, user?.timeZone]);
|
||||
|
||||
// Extract today's bookings for the "Today" section (only used in "upcoming" status)
|
||||
const bookingsToday = useMemo<RowData[]>(() => {
|
||||
return (data?.bookings ?? [])
|
||||
.filter(
|
||||
(booking: BookingOutput) =>
|
||||
dayjs(booking.startTime).tz(user?.timeZone).format("YYYY-MM-DD") ===
|
||||
dayjs().tz(user?.timeZone).format("YYYY-MM-DD")
|
||||
)
|
||||
.map((booking) => ({
|
||||
type: "data" as const,
|
||||
booking,
|
||||
recurringInfo: data?.recurringInfo.find((info) => info.recurringEventId === booking.recurringEventId),
|
||||
isToday: true,
|
||||
}));
|
||||
}, [data, user?.timeZone]);
|
||||
|
||||
// Combine data with section separators for "upcoming" tab
|
||||
const finalData = useMemo<RowData[]>(() => {
|
||||
// For other statuses, just return the flat list
|
||||
if (status !== "upcoming") {
|
||||
return flatData;
|
||||
}
|
||||
|
||||
// For "upcoming" status, organize into "Today" and "Next" sections
|
||||
const merged: RowData[] = [];
|
||||
if (bookingsToday.length > 0) {
|
||||
merged.push({ type: "today" as const }, ...bookingsToday);
|
||||
}
|
||||
if (flatData.length > 0) {
|
||||
merged.push({ type: "next" as const }, ...flatData);
|
||||
}
|
||||
return merged;
|
||||
}, [bookingsToday, flatData, status]);
|
||||
|
||||
const getFacetedUniqueValues = useFacetedUniqueValues();
|
||||
|
||||
const table = useReactTable<RowData>({
|
||||
data: finalData,
|
||||
columns,
|
||||
initialState: {
|
||||
columnVisibility: {
|
||||
eventTypeId: false,
|
||||
teamId: false,
|
||||
userId: false,
|
||||
attendeeName: false,
|
||||
attendeeEmail: false,
|
||||
dateRange: false,
|
||||
bookingUid: false,
|
||||
},
|
||||
},
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: getSortedRowModel(),
|
||||
getFacetedUniqueValues,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<BookingsList
|
||||
status={status}
|
||||
table={table}
|
||||
isPending={isPending}
|
||||
totalRowCount={totalRowCount}
|
||||
ErrorView={ErrorView}
|
||||
hasError={hasError}
|
||||
/>
|
||||
|
||||
{enableDetailsSheet && (
|
||||
<BookingDetailsSheet
|
||||
userTimeZone={user?.timeZone}
|
||||
userTimeFormat={user?.timeFormat === null ? undefined : user?.timeFormat}
|
||||
userId={user?.id}
|
||||
userEmail={user?.email}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function BookingsListContainer({
|
||||
status,
|
||||
permissions,
|
||||
data,
|
||||
isPending,
|
||||
enableDetailsSheet,
|
||||
totalRowCount,
|
||||
ErrorView,
|
||||
hasError,
|
||||
}: BookingsListContainerProps) {
|
||||
// Extract bookings from data for BookingDetailsSheet
|
||||
const bookings = useMemo(() => data?.bookings ?? [], [data]);
|
||||
|
||||
return (
|
||||
<BookingDetailsSheetStoreProvider bookings={bookings}>
|
||||
<BookingsListInner
|
||||
status={status}
|
||||
permissions={permissions}
|
||||
data={data}
|
||||
isPending={isPending}
|
||||
enableDetailsSheet={enableDetailsSheet}
|
||||
totalRowCount={totalRowCount}
|
||||
ErrorView={ErrorView}
|
||||
hasError={hasError}
|
||||
/>
|
||||
</BookingDetailsSheetStoreProvider>
|
||||
);
|
||||
}
|
||||
@@ -54,11 +54,7 @@ export function JoinMeetingButton({
|
||||
onClick={handleClick}>
|
||||
{provider?.iconUrl && (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={provider.iconUrl}
|
||||
className="h-4 w-4 flex-shrink-0 rounded-sm"
|
||||
alt={`${provider.label} logo`}
|
||||
/>
|
||||
<img src={provider.iconUrl} className="h-4 w-4 shrink-0 rounded-sm" alt={`${provider.label} logo`} />
|
||||
)}
|
||||
{provider?.label ? t("join_event_location", { eventLocationType: provider.label }) : t("join_meeting")}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"use client";
|
||||
|
||||
import { useQueryState } from "nuqs";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import useMediaQuery from "@calcom/lib/hooks/useMediaQuery";
|
||||
import { ToggleGroup } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
|
||||
import { viewParser, type BookingView } from "../lib/viewParser";
|
||||
|
||||
export function ViewToggleButton() {
|
||||
const { t } = useLocale();
|
||||
const [view, setView] = useQueryState(
|
||||
"view",
|
||||
viewParser.withDefault("list").withOptions({ clearOnDefault: true })
|
||||
);
|
||||
const isMobile = useMediaQuery("(max-width: 768px)");
|
||||
|
||||
useEffect(() => {
|
||||
// Force list view on mobile
|
||||
if (isMobile && view === "calendar") {
|
||||
setView("list");
|
||||
}
|
||||
}, [isMobile, view, setView]);
|
||||
|
||||
if (isMobile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="hidden sm:block">
|
||||
<ToggleGroup
|
||||
value={view}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
setView(value as BookingView);
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
value: "list",
|
||||
label: "",
|
||||
tooltip: t("list_view"),
|
||||
iconLeft: <Icon name="menu" className="h-4 w-4" />,
|
||||
},
|
||||
{
|
||||
value: "calendar",
|
||||
label: "",
|
||||
tooltip: t("calendar_view"),
|
||||
iconLeft: <Icon name="calendar" className="h-4 w-4" />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { DatePicker } from "@calcom/ui/components/form";
|
||||
|
||||
import { getWeekStart } from "../lib/weekUtils";
|
||||
|
||||
interface WeekPickerProps {
|
||||
currentWeekStart: dayjs.Dayjs;
|
||||
userWeekStart: number;
|
||||
onDateChange: (date: dayjs.Dayjs) => void;
|
||||
}
|
||||
|
||||
export function WeekPicker({ currentWeekStart, userWeekStart, onDateChange }: WeekPickerProps) {
|
||||
const [selectedDate, setSelectedDate] = useState<Date>(currentWeekStart.toDate());
|
||||
useEffect(() => {
|
||||
setSelectedDate(currentWeekStart.toDate());
|
||||
}, [currentWeekStart]);
|
||||
|
||||
const handleDateChange = (date: Date) => {
|
||||
setSelectedDate(date);
|
||||
const selectedDayjs = dayjs(date);
|
||||
const newWeekStart = getWeekStart(selectedDayjs, userWeekStart);
|
||||
onDateChange(newWeekStart);
|
||||
};
|
||||
|
||||
const weekStart = currentWeekStart;
|
||||
const weekEnd = currentWeekStart.add(6, "day");
|
||||
const startMonth = weekStart.format("MMM");
|
||||
const endMonth = weekEnd.format("MMM");
|
||||
const year = weekEnd.format("YYYY");
|
||||
|
||||
const weekRange =
|
||||
startMonth === endMonth
|
||||
? `${startMonth} ${weekStart.format("D")} - ${weekEnd.format("D")}, ${year}`
|
||||
: `${weekStart.format("MMM D")} - ${weekEnd.format("MMM D")}, ${year}`;
|
||||
|
||||
return <DatePicker date={selectedDate} onDatesChange={handleDateChange} minDate={null} label={weekRange} />;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
|
||||
import type { BookingListingStatus, BookingOutput, BookingsGetOutput, RowData } from "../types";
|
||||
|
||||
interface UseBookingCalendarDataParams {
|
||||
data?: {
|
||||
bookings: BookingsGetOutput["bookings"];
|
||||
recurringInfo: BookingsGetOutput["recurringInfo"];
|
||||
totalCount: BookingsGetOutput["totalCount"];
|
||||
};
|
||||
status: BookingListingStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom hook to transform raw booking data into RowData format for the calendar view
|
||||
* - Deduplicates recurring bookings for recurring/unconfirmed/cancelled tabs
|
||||
* - Attaches recurring info and isToday flag to each booking
|
||||
*/
|
||||
export function useBookingCalendarData({ data, status }: UseBookingCalendarDataParams) {
|
||||
const user = useMeQuery().data;
|
||||
|
||||
const rowData = useMemo<RowData[]>(() => {
|
||||
if (!data?.bookings) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// For recurring/unconfirmed/cancelled tabs: track recurring series to show only one representative booking per series
|
||||
// Key: recurringEventId, Value: array of all bookings in that series
|
||||
const shownBookings: Record<string, BookingOutput[]> = {};
|
||||
|
||||
const filterBookings = (booking: BookingOutput) => {
|
||||
// Deduplicate recurring bookings for specific status tabs
|
||||
// This ensures we show only ONE booking per recurring series instead of all occurrences
|
||||
if (status === "recurring" || status == "unconfirmed" || status === "cancelled") {
|
||||
// Non-recurring bookings are always shown
|
||||
if (!booking.recurringEventId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If we've already encountered this recurring series
|
||||
if (
|
||||
shownBookings[booking.recurringEventId] !== undefined &&
|
||||
shownBookings[booking.recurringEventId].length > 0
|
||||
) {
|
||||
// Store this occurrence but DON'T display it (return false to filter out)
|
||||
shownBookings[booking.recurringEventId].push(booking);
|
||||
return false;
|
||||
}
|
||||
|
||||
// First occurrence of this recurring series - show it and start tracking
|
||||
shownBookings[booking.recurringEventId] = [booking];
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
return data.bookings.filter(filterBookings).map((booking) => {
|
||||
const bookingDate = dayjs(booking.startTime).tz(user?.timeZone);
|
||||
const today = dayjs().tz(user?.timeZone).format("YYYY-MM-DD");
|
||||
const bookingDateStr = bookingDate.format("YYYY-MM-DD");
|
||||
|
||||
return {
|
||||
type: "data" as const,
|
||||
booking,
|
||||
isToday: bookingDateStr === today,
|
||||
recurringInfo: data.recurringInfo.find((info) => info.recurringEventId === booking.recurringEventId),
|
||||
};
|
||||
});
|
||||
}, [data, status, user?.timeZone]);
|
||||
|
||||
return rowData;
|
||||
}
|
||||
@@ -4,29 +4,29 @@ import type { BookingOutput } from "../types";
|
||||
|
||||
export function useBookingCursor({
|
||||
bookings,
|
||||
selectedBookingId,
|
||||
setSelectedBookingId,
|
||||
selectedBookingUid,
|
||||
setSelectedBookingUid,
|
||||
}: {
|
||||
bookings: BookingOutput[];
|
||||
selectedBookingId: number | null;
|
||||
setSelectedBookingId: (bookingId: number | null) => void;
|
||||
selectedBookingUid: string | null;
|
||||
setSelectedBookingUid: (bookingUid: string | null) => void;
|
||||
}) {
|
||||
const currentIndex = useMemo(
|
||||
() => bookings.findIndex((booking) => selectedBookingId && booking.id === selectedBookingId),
|
||||
[bookings, selectedBookingId]
|
||||
() => bookings.findIndex((booking) => selectedBookingUid && booking.uid === selectedBookingUid),
|
||||
[bookings, selectedBookingUid]
|
||||
);
|
||||
|
||||
const onPrevious = useCallback(() => {
|
||||
if (currentIndex >= 1) {
|
||||
setSelectedBookingId(bookings[currentIndex - 1].id);
|
||||
setSelectedBookingUid(bookings[currentIndex - 1].uid);
|
||||
}
|
||||
}, [bookings, currentIndex, setSelectedBookingId]);
|
||||
}, [bookings, currentIndex, setSelectedBookingUid]);
|
||||
|
||||
const onNext = useCallback(() => {
|
||||
if (currentIndex >= 0 && currentIndex < bookings.length - 1) {
|
||||
setSelectedBookingId(bookings[currentIndex + 1].id);
|
||||
setSelectedBookingUid(bookings[currentIndex + 1].uid);
|
||||
}
|
||||
}, [bookings, currentIndex, setSelectedBookingId]);
|
||||
}, [bookings, currentIndex, setSelectedBookingUid]);
|
||||
|
||||
return {
|
||||
onPrevious,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
useFilterValue,
|
||||
ZMultiSelectFilterValue,
|
||||
ZDateRangeFilterValue,
|
||||
ZTextFilterValue,
|
||||
} from "@calcom/features/data-table";
|
||||
|
||||
export function useBookingFilters() {
|
||||
const eventTypeIds = useFilterValue("eventTypeId", ZMultiSelectFilterValue)?.data as number[] | undefined;
|
||||
const teamIds = useFilterValue("teamId", ZMultiSelectFilterValue)?.data as number[] | undefined;
|
||||
const userIds = useFilterValue("userId", ZMultiSelectFilterValue)?.data as number[] | undefined;
|
||||
const dateRange = useFilterValue("dateRange", ZDateRangeFilterValue)?.data;
|
||||
const attendeeName = useFilterValue("attendeeName", ZTextFilterValue);
|
||||
const attendeeEmail = useFilterValue("attendeeEmail", ZTextFilterValue);
|
||||
const bookingUid = useFilterValue("bookingUid", ZTextFilterValue)?.data?.operand as string | undefined;
|
||||
|
||||
return {
|
||||
eventTypeIds,
|
||||
teamIds,
|
||||
userIds,
|
||||
dateRange,
|
||||
attendeeName,
|
||||
attendeeEmail,
|
||||
bookingUid,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { ColumnFilterType } from "@calcom/features/data-table";
|
||||
import { isSeparatorRow } from "@calcom/features/data-table/lib/separator";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
import BookingListItem from "@calcom/web/components/booking/BookingListItem";
|
||||
|
||||
import type { RowData, BookingListingStatus } from "../types";
|
||||
|
||||
export function useBookingListColumns({
|
||||
user,
|
||||
status,
|
||||
canReadOthersBookings,
|
||||
bookingsV3Enabled,
|
||||
handleBookingClick,
|
||||
}: {
|
||||
user: ReturnType<typeof useMeQuery>["data"];
|
||||
status: BookingListingStatus;
|
||||
canReadOthersBookings: boolean;
|
||||
bookingsV3Enabled: boolean;
|
||||
handleBookingClick: (bookingUid: string) => void;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return useMemo(() => {
|
||||
const columnHelper = createColumnHelper<RowData>();
|
||||
|
||||
return [
|
||||
columnHelper.accessor((row) => !isSeparatorRow(row) && row.booking.eventType.id, {
|
||||
id: "eventTypeId",
|
||||
header: t("event_type"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.MULTI_SELECT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => !isSeparatorRow(row) && row.booking.eventType.team?.id, {
|
||||
id: "teamId",
|
||||
header: t("team"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.MULTI_SELECT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => !isSeparatorRow(row) && row.booking.user?.id, {
|
||||
id: "userId",
|
||||
header: t("member"),
|
||||
enableColumnFilter: canReadOthersBookings,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.MULTI_SELECT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row, {
|
||||
id: "attendeeName",
|
||||
header: t("attendee_name"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.TEXT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row, {
|
||||
id: "attendeeEmail",
|
||||
header: t("attendee_email_variable"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.TEXT,
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => row, {
|
||||
id: "dateRange",
|
||||
header: t("date_range"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.DATE_RANGE,
|
||||
dateRangeOptions: {
|
||||
range: status === "past" ? "past" : "custom",
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor((row) => !isSeparatorRow(row) && row.booking.uid, {
|
||||
id: "bookingUid",
|
||||
header: t("booking_uid"),
|
||||
enableColumnFilter: true,
|
||||
enableSorting: false,
|
||||
cell: () => null,
|
||||
meta: {
|
||||
filter: {
|
||||
type: ColumnFilterType.TEXT,
|
||||
textOptions: {
|
||||
allowedOperators: ["equals"],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
columnHelper.display({
|
||||
id: "customView",
|
||||
cell: (props) => {
|
||||
const row = props.row.original;
|
||||
|
||||
// Separator rows are handled automatically by DataTable
|
||||
if (isSeparatorRow(row)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { booking, recurringInfo, isToday } = row;
|
||||
return (
|
||||
<BookingListItem
|
||||
key={booking.id}
|
||||
isToday={isToday}
|
||||
loggedInUser={{
|
||||
userId: user?.id,
|
||||
userTimeZone: user?.timeZone,
|
||||
userTimeFormat: user?.timeFormat,
|
||||
userEmail: user?.email,
|
||||
}}
|
||||
listingStatus={status}
|
||||
recurringInfo={recurringInfo}
|
||||
{...(bookingsV3Enabled && { onClick: () => handleBookingClick(booking.uid) })}
|
||||
{...booking}
|
||||
/>
|
||||
);
|
||||
},
|
||||
}),
|
||||
];
|
||||
}, [user, status, t, canReadOthersBookings, bookingsV3Enabled, handleBookingClick]);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
import type {
|
||||
RowData,
|
||||
BookingRowData,
|
||||
BookingListingStatus,
|
||||
BookingOutput,
|
||||
BookingsGetOutput,
|
||||
} from "../types";
|
||||
|
||||
/**
|
||||
* Transform raw bookings into final data structure with separators
|
||||
* - Deduplicates recurring bookings for recurring/unconfirmed/cancelled tabs
|
||||
* - For "upcoming" status, organizes into "Today" and "Next" sections
|
||||
*/
|
||||
export function useBookingListData({
|
||||
data,
|
||||
status,
|
||||
userTimeZone,
|
||||
}: {
|
||||
data?: BookingsGetOutput;
|
||||
status: BookingListingStatus;
|
||||
userTimeZone?: string;
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
/**
|
||||
* Transform raw bookings into flat list (excluding today's bookings for "upcoming" status)
|
||||
* - Deduplicates recurring bookings for recurring/unconfirmed/cancelled tabs
|
||||
* - For "upcoming" status, filters out today's bookings (they're shown in separate "Today" section)
|
||||
*/
|
||||
const flatData = useMemo<BookingRowData[]>(() => {
|
||||
const todayDateString = dayjs().tz(userTimeZone).format("YYYY-MM-DD");
|
||||
|
||||
// For recurring/unconfirmed/cancelled tabs: track recurring series to show only one representative booking per series
|
||||
// Key: recurringEventId, Value: array of all bookings in that series
|
||||
const shownBookings: Record<string, BookingOutput[]> = {};
|
||||
|
||||
const filterBookings = (booking: BookingOutput) => {
|
||||
// Deduplicate recurring bookings for specific status tabs
|
||||
// This ensures we show only ONE booking per recurring series instead of all occurrences
|
||||
if (status === "recurring" || status == "unconfirmed" || status === "cancelled") {
|
||||
// Non-recurring bookings are always shown
|
||||
if (!booking.recurringEventId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If we've already encountered this recurring series
|
||||
if (
|
||||
shownBookings[booking.recurringEventId] !== undefined &&
|
||||
shownBookings[booking.recurringEventId].length > 0
|
||||
) {
|
||||
// Store this occurrence but DON'T display it (return false to filter out)
|
||||
shownBookings[booking.recurringEventId].push(booking);
|
||||
return false;
|
||||
}
|
||||
|
||||
// First occurrence of this recurring series - show it and start tracking
|
||||
shownBookings[booking.recurringEventId] = [booking];
|
||||
} else if (status === "upcoming") {
|
||||
// For "upcoming" tab, exclude today's bookings (they're shown separately in the "Today" section)
|
||||
return dayjs(booking.startTime).tz(userTimeZone).format("YYYY-MM-DD") !== todayDateString;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
return (
|
||||
data?.bookings.filter(filterBookings).map((booking) => ({
|
||||
type: "data" as const,
|
||||
booking,
|
||||
recurringInfo: data?.recurringInfo.find((info) => info.recurringEventId === booking.recurringEventId),
|
||||
isToday: false,
|
||||
})) || []
|
||||
);
|
||||
}, [data, status, userTimeZone]);
|
||||
|
||||
// Extract today's bookings for the "Today" section (only used in "upcoming" status)
|
||||
const bookingsToday = useMemo<BookingRowData[]>(() => {
|
||||
const todayDateString = dayjs().tz(userTimeZone).format("YYYY-MM-DD");
|
||||
|
||||
return (data?.bookings ?? [])
|
||||
.filter(
|
||||
(booking: BookingOutput) =>
|
||||
dayjs(booking.startTime).tz(userTimeZone).format("YYYY-MM-DD") === todayDateString
|
||||
)
|
||||
.map((booking) => ({
|
||||
type: "data" as const,
|
||||
booking,
|
||||
recurringInfo: data?.recurringInfo.find((info) => info.recurringEventId === booking.recurringEventId),
|
||||
isToday: true,
|
||||
}));
|
||||
}, [data, userTimeZone]);
|
||||
|
||||
// Combine data with section separators for "upcoming" tab
|
||||
const finalData = useMemo<RowData[]>(() => {
|
||||
// For other statuses, just return the flat list
|
||||
if (status !== "upcoming") {
|
||||
return flatData;
|
||||
}
|
||||
|
||||
// For "upcoming" status, organize into "Today" and "Next" sections
|
||||
const merged: RowData[] = [];
|
||||
if (bookingsToday.length > 0) {
|
||||
merged.push({ type: "separator" as const, label: t("today") }, ...bookingsToday);
|
||||
}
|
||||
if (flatData.length > 0) {
|
||||
merged.push({ type: "separator" as const, label: t("next") }, ...flatData);
|
||||
}
|
||||
return merged;
|
||||
}, [bookingsToday, flatData, status, t]);
|
||||
|
||||
return finalData;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useSearchParams, usePathname } from "next/navigation";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
|
||||
export function useBookingStatusTab() {
|
||||
const { t } = useLocale();
|
||||
const searchParams = useSearchParams();
|
||||
const pathname = usePathname();
|
||||
|
||||
const tabOptions = useMemo(() => {
|
||||
const queryString = searchParams?.toString() || "";
|
||||
|
||||
const baseTabConfigs = [
|
||||
{
|
||||
value: "upcoming",
|
||||
label: "upcoming",
|
||||
path: "/bookings/upcoming",
|
||||
dataTestId: "upcoming",
|
||||
},
|
||||
{
|
||||
value: "unconfirmed",
|
||||
label: "unconfirmed",
|
||||
path: "/bookings/unconfirmed",
|
||||
dataTestId: "unconfirmed",
|
||||
},
|
||||
{
|
||||
value: "recurring",
|
||||
label: "recurring",
|
||||
path: "/bookings/recurring",
|
||||
dataTestId: "recurring",
|
||||
},
|
||||
{
|
||||
value: "past",
|
||||
label: "past",
|
||||
path: "/bookings/past",
|
||||
dataTestId: "past",
|
||||
},
|
||||
{
|
||||
value: "cancelled",
|
||||
label: "cancelled",
|
||||
path: "/bookings/cancelled",
|
||||
dataTestId: "cancelled",
|
||||
},
|
||||
];
|
||||
|
||||
return baseTabConfigs.map((tabConfig) => ({
|
||||
value: tabConfig.value,
|
||||
label: t(tabConfig.label),
|
||||
dataTestId: tabConfig.dataTestId,
|
||||
href: queryString ? `${tabConfig.path}?${queryString}` : tabConfig.path,
|
||||
}));
|
||||
}, [searchParams, t]);
|
||||
|
||||
const currentTab = useMemo(() => {
|
||||
const pathMatch = pathname?.match(/\/bookings\/(\w+)/);
|
||||
return pathMatch?.[1] || "upcoming";
|
||||
}, [pathname]);
|
||||
|
||||
return {
|
||||
currentTab,
|
||||
tabOptions,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useMemo, useEffect, useRef } from "react";
|
||||
|
||||
import { ColumnFilterType, useDataTable } from "@calcom/features/data-table";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
|
||||
/**
|
||||
* Custom hook to manage allowed filters for calendar view
|
||||
* - Users without permission to read others' bookings: no filters
|
||||
* - Users with permission to read others' bookings: userId filter with their own ID as default
|
||||
*/
|
||||
export function useCalendarAllowedFilters({ canReadOthersBookings }: { canReadOthersBookings: boolean }) {
|
||||
const { data: user } = useMeQuery();
|
||||
const { updateFilter, clearAll } = useDataTable();
|
||||
const allowedFilterIds = useMemo(() => (canReadOthersBookings ? ["userId"] : []), [canReadOthersBookings]);
|
||||
const hasInitialized = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || hasInitialized.current) return;
|
||||
|
||||
hasInitialized.current = true;
|
||||
|
||||
// Clear all filters first (in case coming from list view with different filters)
|
||||
clearAll();
|
||||
|
||||
// Then set the appropriate filter for users with permission
|
||||
if (canReadOthersBookings) {
|
||||
updateFilter("userId", {
|
||||
type: ColumnFilterType.MULTI_SELECT,
|
||||
data: [user.id],
|
||||
});
|
||||
}
|
||||
}, [user, canReadOthersBookings, updateFilter, clearAll]);
|
||||
|
||||
return allowedFilterIds;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { createParser, useQueryState } from "nuqs";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import { weekdayToWeekIndex } from "@calcom/lib/dayjs";
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
|
||||
import { getWeekStart } from "../lib/weekUtils";
|
||||
|
||||
/**
|
||||
* Parser for the weekStart query parameter
|
||||
* This parser simply parses the date from the URL and ensures it's at the start of the day.
|
||||
* The week start logic based on user preference is applied when determining the default value.
|
||||
*/
|
||||
const weekStartParser = createParser({
|
||||
parse: (value: string) => {
|
||||
const parsed = dayjs(value);
|
||||
return parsed.isValid() ? parsed.startOf("day") : dayjs().startOf("day");
|
||||
},
|
||||
serialize: (value: dayjs.Dayjs) => value.format("YYYY-MM-DD"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Custom hook to manage the current week start based on user preferences
|
||||
* @returns Object containing currentWeekStart state and userWeekStart preference
|
||||
*/
|
||||
export function useCurrentWeekStart() {
|
||||
const user = useMeQuery().data;
|
||||
|
||||
// Get the user's preferred week start day (0-6, where 0 = Sunday)
|
||||
const userWeekStart = weekdayToWeekIndex(user?.weekStart);
|
||||
|
||||
const [currentWeekStart, setCurrentWeekStart] = useQueryState(
|
||||
"weekStart",
|
||||
weekStartParser.withDefault(getWeekStart(dayjs(), userWeekStart))
|
||||
);
|
||||
|
||||
return {
|
||||
currentWeekStart,
|
||||
setCurrentWeekStart,
|
||||
userWeekStart,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { RefundPolicy } from "@calcom/lib/payment/types";
|
||||
import { BookingStatus } from "@calcom/prisma/enums";
|
||||
|
||||
interface Payment {
|
||||
success: boolean;
|
||||
refunded: boolean;
|
||||
paymentOption?: string | null;
|
||||
}
|
||||
|
||||
interface UsePaymentStatusParams {
|
||||
bookingStatus: BookingStatus;
|
||||
startTime: Date | string;
|
||||
eventTypeTeamId?: number | null;
|
||||
userId?: number | null;
|
||||
payment: Payment;
|
||||
refundPolicy?: string | null;
|
||||
refundDaysCount?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to determine the appropriate payment status message for a booking
|
||||
* based on payment status and refund policy.
|
||||
*/
|
||||
export function usePaymentStatus({
|
||||
bookingStatus,
|
||||
startTime,
|
||||
eventTypeTeamId,
|
||||
userId,
|
||||
payment,
|
||||
refundPolicy,
|
||||
refundDaysCount,
|
||||
}: UsePaymentStatusParams) {
|
||||
const { t } = useLocale();
|
||||
|
||||
const message = useMemo(() => {
|
||||
const isCancelled = bookingStatus === BookingStatus.CANCELLED || bookingStatus === BookingStatus.REJECTED;
|
||||
|
||||
if (!isCancelled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Payment not completed and not refunded
|
||||
if (!payment.success && !payment.refunded) {
|
||||
return t("booking_with_payment_cancelled");
|
||||
}
|
||||
|
||||
// Payment completed but not refunded
|
||||
if (payment.success && !payment.refunded) {
|
||||
// Handle missing team or event type owner (same in processPaymentRefund.ts)
|
||||
if (!eventTypeTeamId && !userId) {
|
||||
return t("booking_with_payment_cancelled_no_refund");
|
||||
}
|
||||
|
||||
// Handle DAYS policy with expired refund window
|
||||
if (refundPolicy === RefundPolicy.DAYS && refundDaysCount) {
|
||||
const bookingStartTime = new Date(startTime);
|
||||
const cancelTime = new Date();
|
||||
const daysDiff = Math.floor(
|
||||
(cancelTime.getTime() - bookingStartTime.getTime()) / (1000 * 60 * 60 * 24)
|
||||
);
|
||||
|
||||
if (daysDiff > refundDaysCount) {
|
||||
return t("booking_with_payment_cancelled_refund_window_expired");
|
||||
}
|
||||
return t("booking_with_payment_cancelled_already_paid");
|
||||
}
|
||||
|
||||
// Handle NEVER policy
|
||||
if (refundPolicy === RefundPolicy.NEVER) {
|
||||
return t("booking_with_payment_cancelled_no_refund");
|
||||
}
|
||||
|
||||
// Handle ALWAYS policy or default
|
||||
return t("booking_with_payment_cancelled_already_paid");
|
||||
}
|
||||
|
||||
// Payment refunded
|
||||
if (payment.refunded) {
|
||||
return t("booking_with_payment_cancelled_refunded");
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [bookingStatus, startTime, eventTypeTeamId, userId, payment, refundPolicy, refundDaysCount, t]);
|
||||
|
||||
return message;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useQueryState } from "nuqs";
|
||||
|
||||
export function useSelectedBookingUid() {
|
||||
return useQueryState("uid", {
|
||||
defaultValue: null,
|
||||
parse: (value) => (value ? value : null),
|
||||
serialize: (value) => (value ? String(value) : ""),
|
||||
clearOnDefault: true,
|
||||
});
|
||||
}
|
||||
@@ -1 +1,3 @@
|
||||
export const validStatuses = ["upcoming", "recurring", "past", "cancelled", "unconfirmed"] as const;
|
||||
|
||||
export type BookingListingStatus = (typeof validStatuses)[number];
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Dayjs } from "@calcom/dayjs";
|
||||
|
||||
/**
|
||||
* Gets the start of the week for a given date based on the user's preferred week start day.
|
||||
* This is useful when dayjs's built-in startOf('week') doesn't respect user preferences.
|
||||
*
|
||||
* @param date - The date to get the week start for
|
||||
* @param weekStart - The day the week starts on (0 = Sunday, 1 = Monday, etc.)
|
||||
* @returns The start of the week as a dayjs object
|
||||
*
|
||||
* @example
|
||||
* // If today is Thursday (day 4) and user prefers Monday start (1):
|
||||
* const weekStart = getWeekStart(dayjs(), 1); // Returns the Monday of current week
|
||||
*/
|
||||
export const getWeekStart = (date: Dayjs, weekStart: number = 0): Dayjs => {
|
||||
const currentDay = date.day();
|
||||
const diff = (currentDay - weekStart + 7) % 7;
|
||||
return date.subtract(diff, "day").startOf("day");
|
||||
};
|
||||
@@ -3,23 +3,23 @@
|
||||
import React from "react";
|
||||
import { createStore, useStore } from "zustand";
|
||||
|
||||
import { useSelectedBookingId } from "../hooks/useSelectedBookingId";
|
||||
import { useSelectedBookingUid } from "../hooks/useSelectedBookingUid";
|
||||
import type { BookingOutput } from "../types";
|
||||
|
||||
interface BookingDetailsSheetStore {
|
||||
// State
|
||||
selectedBookingId: number | null;
|
||||
selectedBookingUid: string | null;
|
||||
bookings: BookingOutput[];
|
||||
|
||||
// Actions
|
||||
setSelectedBookingId: (id: number | null) => void;
|
||||
setSelectedBookingUid: (uid: string | null) => void;
|
||||
setBookings: (bookings: BookingOutput[]) => void;
|
||||
clearSelection: () => void;
|
||||
|
||||
// Computed getters (used via selectors)
|
||||
getSelectedBooking: () => BookingOutput | null;
|
||||
getNextBookingId: () => number | null;
|
||||
getPreviousBookingId: () => number | null;
|
||||
getNextBookingUid: () => string | null;
|
||||
getPreviousBookingUid: () => string | null;
|
||||
hasNext: () => boolean;
|
||||
hasPrevious: () => boolean;
|
||||
}
|
||||
@@ -29,54 +29,54 @@ type BookingDetailsSheetStoreType = ReturnType<typeof createBookingDetailsSheetS
|
||||
const createBookingDetailsSheetStore = (initialBookings: BookingOutput[] = []) => {
|
||||
return createStore<BookingDetailsSheetStore>((set, get) => ({
|
||||
// Initial state
|
||||
selectedBookingId: null,
|
||||
selectedBookingUid: null,
|
||||
bookings: initialBookings,
|
||||
|
||||
// Actions
|
||||
setSelectedBookingId: (id) => set({ selectedBookingId: id }),
|
||||
setSelectedBookingUid: (uid) => set({ selectedBookingUid: uid }),
|
||||
setBookings: (bookings) => set({ bookings }),
|
||||
clearSelection: () => set({ selectedBookingId: null }),
|
||||
clearSelection: () => set({ selectedBookingUid: null }),
|
||||
|
||||
// Computed getters
|
||||
getSelectedBooking: () => {
|
||||
const state = get();
|
||||
if (!state.selectedBookingId) return null;
|
||||
return state.bookings.find((booking) => booking.id === state.selectedBookingId) ?? null;
|
||||
if (!state.selectedBookingUid) return null;
|
||||
return state.bookings.find((booking) => booking.uid === state.selectedBookingUid) ?? null;
|
||||
},
|
||||
|
||||
getNextBookingId: () => {
|
||||
getNextBookingUid: () => {
|
||||
const state = get();
|
||||
if (!state.selectedBookingId) return null;
|
||||
if (!state.selectedBookingUid) return null;
|
||||
|
||||
const currentIndex = state.bookings.findIndex((booking) => booking.id === state.selectedBookingId);
|
||||
const currentIndex = state.bookings.findIndex((booking) => booking.uid === state.selectedBookingUid);
|
||||
if (currentIndex === -1 || currentIndex >= state.bookings.length - 1) return null;
|
||||
|
||||
return state.bookings[currentIndex + 1].id;
|
||||
return state.bookings[currentIndex + 1].uid;
|
||||
},
|
||||
|
||||
getPreviousBookingId: () => {
|
||||
getPreviousBookingUid: () => {
|
||||
const state = get();
|
||||
if (!state.selectedBookingId) return null;
|
||||
if (!state.selectedBookingUid) return null;
|
||||
|
||||
const currentIndex = state.bookings.findIndex((booking) => booking.id === state.selectedBookingId);
|
||||
const currentIndex = state.bookings.findIndex((booking) => booking.uid === state.selectedBookingUid);
|
||||
if (currentIndex <= 0) return null;
|
||||
|
||||
return state.bookings[currentIndex - 1].id;
|
||||
return state.bookings[currentIndex - 1].uid;
|
||||
},
|
||||
|
||||
hasNext: () => {
|
||||
const state = get();
|
||||
if (!state.selectedBookingId) return false;
|
||||
if (!state.selectedBookingUid) return false;
|
||||
|
||||
const currentIndex = state.bookings.findIndex((booking) => booking.id === state.selectedBookingId);
|
||||
const currentIndex = state.bookings.findIndex((booking) => booking.uid === state.selectedBookingUid);
|
||||
return currentIndex >= 0 && currentIndex < state.bookings.length - 1;
|
||||
},
|
||||
|
||||
hasPrevious: () => {
|
||||
const state = get();
|
||||
if (!state.selectedBookingId) return false;
|
||||
if (!state.selectedBookingUid) return false;
|
||||
|
||||
const currentIndex = state.bookings.findIndex((booking) => booking.id === state.selectedBookingId);
|
||||
const currentIndex = state.bookings.findIndex((booking) => booking.uid === state.selectedBookingUid);
|
||||
return currentIndex > 0;
|
||||
},
|
||||
}));
|
||||
@@ -92,7 +92,7 @@ export function BookingDetailsSheetStoreProvider({
|
||||
bookings: BookingOutput[];
|
||||
}) {
|
||||
const [store] = React.useState(() => createBookingDetailsSheetStore(bookings));
|
||||
const [selectedBookingIdFromUrl, setSelectedBookingIdToUrl] = useSelectedBookingId();
|
||||
const [selectedBookingUidFromUrl, setSelectedBookingUidToUrl] = useSelectedBookingUid();
|
||||
|
||||
// Update bookings when they change
|
||||
React.useEffect(() => {
|
||||
@@ -102,22 +102,22 @@ export function BookingDetailsSheetStoreProvider({
|
||||
// Sync Store → URL
|
||||
React.useEffect(() => {
|
||||
const unsubscribe = store.subscribe((state) => {
|
||||
const storeId = state.selectedBookingId;
|
||||
if (storeId !== selectedBookingIdFromUrl) {
|
||||
setSelectedBookingIdToUrl(storeId);
|
||||
const storeUid = state.selectedBookingUid;
|
||||
if (storeUid !== selectedBookingUidFromUrl) {
|
||||
setSelectedBookingUidToUrl(storeUid);
|
||||
}
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, [selectedBookingIdFromUrl, setSelectedBookingIdToUrl, store]);
|
||||
}, [selectedBookingUidFromUrl, setSelectedBookingUidToUrl, store]);
|
||||
|
||||
// Sync URL → Store
|
||||
React.useEffect(() => {
|
||||
const currentStoreId = store.getState().selectedBookingId;
|
||||
if (currentStoreId !== selectedBookingIdFromUrl) {
|
||||
store.getState().setSelectedBookingId(selectedBookingIdFromUrl);
|
||||
const currentStoreUid = store.getState().selectedBookingUid;
|
||||
if (currentStoreUid !== selectedBookingUidFromUrl) {
|
||||
store.getState().setSelectedBookingUid(selectedBookingUidFromUrl);
|
||||
}
|
||||
}, [selectedBookingIdFromUrl, store]);
|
||||
}, [selectedBookingUidFromUrl, store]);
|
||||
|
||||
return (
|
||||
<BookingDetailsSheetStoreContext.Provider value={store}>
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import type { DataTableRow } from "@calcom/features/data-table/lib/separator";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
|
||||
import type { validStatuses } from "~/bookings/lib/validStatuses";
|
||||
import type { validStatuses } from "./lib/validStatuses";
|
||||
|
||||
export type BookingsGetOutput = RouterOutputs["viewer"]["bookings"]["get"];
|
||||
|
||||
export type BookingOutput = RouterOutputs["viewer"]["bookings"]["get"]["bookings"][0];
|
||||
|
||||
export type BookingAttendee = BookingOutput["attendees"][0];
|
||||
|
||||
export type RecurringInfo = {
|
||||
recurringEventId: string | null;
|
||||
count: number;
|
||||
@@ -13,15 +16,13 @@ export type RecurringInfo = {
|
||||
bookings: { [key: string]: Date[] };
|
||||
};
|
||||
|
||||
export type RowData =
|
||||
| {
|
||||
type: "data";
|
||||
booking: BookingOutput;
|
||||
isToday: boolean;
|
||||
recurringInfo?: RecurringInfo;
|
||||
}
|
||||
| {
|
||||
type: "today" | "next";
|
||||
};
|
||||
export type BookingRowData = {
|
||||
type: "data";
|
||||
booking: BookingOutput;
|
||||
isToday: boolean;
|
||||
recurringInfo?: RecurringInfo;
|
||||
};
|
||||
|
||||
export type RowData = DataTableRow<BookingRowData>;
|
||||
|
||||
export type BookingListingStatus = (typeof validStatuses)[number];
|
||||
@@ -36,7 +36,6 @@ import { useRouterQuery } from "@calcom/lib/hooks/useRouterQuery";
|
||||
import useTheme from "@calcom/lib/hooks/useTheme";
|
||||
import isSmsCalEmail from "@calcom/lib/isSmsCalEmail";
|
||||
import { markdownToSafeHTML } from "@calcom/lib/markdownToSafeHTML";
|
||||
import { RefundPolicy } from "@calcom/lib/payment/types";
|
||||
import { getEveryFreqFor } from "@calcom/lib/recurringStrings";
|
||||
import { getIs24hClockFromLocalStorage, isBrowserLocale24h } from "@calcom/lib/timeFormat";
|
||||
import { CURRENT_TIMEZONE } from "@calcom/lib/timezoneConstants";
|
||||
@@ -57,6 +56,7 @@ import CancelBooking from "@calcom/web/components/booking/CancelBooking";
|
||||
import EventReservationSchema from "@calcom/web/components/schemas/EventReservationSchema";
|
||||
import { timeZone } from "@calcom/web/lib/clock";
|
||||
|
||||
import { usePaymentStatus } from "../hooks/usePaymentStatus";
|
||||
import type { PageProps } from "./bookings-single-view.getServerSideProps";
|
||||
|
||||
const stringToBoolean = z
|
||||
@@ -384,6 +384,22 @@ export default function Success(props: PageProps) {
|
||||
const canCancel = !eventType?.disableCancelling;
|
||||
const canReschedule = !eventType?.disableRescheduling;
|
||||
|
||||
const paymentStatusMessage = usePaymentStatus({
|
||||
bookingStatus: bookingInfo.status,
|
||||
startTime: bookingInfo.startTime,
|
||||
eventTypeTeamId: eventType?.teamId,
|
||||
userId: eventType?.owner?.id,
|
||||
payment: props.paymentStatus
|
||||
? {
|
||||
success: props.paymentStatus.success,
|
||||
refunded: props.paymentStatus.refunded,
|
||||
paymentOption: props.paymentStatus.paymentOption,
|
||||
}
|
||||
: { success: false, refunded: false },
|
||||
refundPolicy: eventType?.metadata?.apps?.stripe?.refundPolicy,
|
||||
refundDaysCount: eventType?.metadata?.apps?.stripe?.refundDaysCount,
|
||||
});
|
||||
|
||||
const successPageHeadline = (() => {
|
||||
if (isAwaitingPayment && !isCancelled) {
|
||||
return props.paymentStatus?.paymentOption === "HOLD"
|
||||
@@ -462,7 +478,8 @@ export default function Success(props: PageProps) {
|
||||
<div
|
||||
className={classNames(
|
||||
"inline-block transform overflow-hidden rounded-lg border sm:my-8 sm:max-w-xl",
|
||||
!isBackgroundTransparent && " bg-default dark:bg-cal-muted border-booker border-booker-width",
|
||||
!isBackgroundTransparent &&
|
||||
" bg-default dark:bg-cal-muted border-booker border-booker-width",
|
||||
"px-8 pb-4 pt-5 text-left align-bottom transition-all sm:w-full sm:py-8 sm:align-middle"
|
||||
)}
|
||||
role="dialog"
|
||||
@@ -519,47 +536,7 @@ export default function Success(props: PageProps) {
|
||||
</div>
|
||||
{props.paymentStatus &&
|
||||
(bookingInfo.status === BookingStatus.CANCELLED ||
|
||||
bookingInfo.status === BookingStatus.REJECTED) && (
|
||||
<h4>
|
||||
{!props.paymentStatus.success &&
|
||||
!props.paymentStatus.refunded &&
|
||||
t("booking_with_payment_cancelled")}
|
||||
{props.paymentStatus.success &&
|
||||
!props.paymentStatus.refunded &&
|
||||
(() => {
|
||||
const refundPolicy = eventType?.metadata?.apps?.stripe?.refundPolicy;
|
||||
const refundDaysCount = eventType?.metadata?.apps?.stripe?.refundDaysCount;
|
||||
|
||||
// Handle missing team or event type owner (same in processPaymentRefund.ts)
|
||||
if (!eventType?.teamId && !eventType?.owner) {
|
||||
return t("booking_with_payment_cancelled_no_refund");
|
||||
}
|
||||
|
||||
// Handle DAYS policy with expired refund window
|
||||
else if (refundPolicy === RefundPolicy.DAYS && refundDaysCount) {
|
||||
const startTime = new Date(bookingInfo.startTime);
|
||||
const cancelTime = new Date();
|
||||
const daysDiff = Math.floor(
|
||||
(cancelTime.getTime() - startTime.getTime()) / (1000 * 60 * 60 * 24)
|
||||
);
|
||||
|
||||
if (daysDiff > refundDaysCount) {
|
||||
return t("booking_with_payment_cancelled_refund_window_expired");
|
||||
}
|
||||
}
|
||||
// Handle NEVER policy
|
||||
else if (refundPolicy === RefundPolicy.NEVER) {
|
||||
return t("booking_with_payment_cancelled_no_refund");
|
||||
}
|
||||
|
||||
// Handle ALWAYS policy
|
||||
else {
|
||||
return t("booking_with_payment_cancelled_already_paid");
|
||||
}
|
||||
})()}
|
||||
{props.paymentStatus.refunded && t("booking_with_payment_cancelled_refunded")}
|
||||
</h4>
|
||||
)}
|
||||
bookingInfo.status === BookingStatus.REJECTED) && <h4>{paymentStatusMessage}</h4>}
|
||||
|
||||
<div className="border-subtle text-default mt-8 grid grid-cols-3 gap-x-4 border-t pt-8 text-left rtl:text-right sm:gap-x-0">
|
||||
{(isCancelled || reschedule) && cancellationReason && (
|
||||
@@ -711,7 +688,7 @@ export default function Success(props: PageProps) {
|
||||
<>
|
||||
<div className="mt-9 font-medium">{t("additional_notes")}</div>
|
||||
<div className="col-span-2 mb-2 mt-9">
|
||||
<p className="whitespace-pre-line wrap-break-word">{bookingInfo.description}</p>
|
||||
<p className="wrap-break-word whitespace-pre-line">{bookingInfo.description}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -738,7 +715,7 @@ export default function Success(props: PageProps) {
|
||||
<div className="col-span-2 mb-2 mt-2">
|
||||
{Object.entries(utmParams).filter(([_, value]) => Boolean(value)).length >
|
||||
0 ? (
|
||||
<ul className="list-disc stack-y-1 p-1 pl-5 sm:w-80">
|
||||
<ul className="stack-y-1 list-disc p-1 pl-5 sm:w-80">
|
||||
{Object.entries(utmParams)
|
||||
.filter(([_, value]) => Boolean(value))
|
||||
.map(([key, value]) => (
|
||||
@@ -892,6 +869,7 @@ export default function Success(props: PageProps) {
|
||||
currentUserEmail={currentUserEmail}
|
||||
isHost={isHost}
|
||||
internalNotePresets={props.internalNotePresets}
|
||||
renderContext="booking-single-view"
|
||||
/>
|
||||
</>
|
||||
))}
|
||||
@@ -1053,7 +1031,7 @@ export default function Success(props: PageProps) {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="my-4 stack-y-1 text-center">
|
||||
<div className="stack-y-1 my-4 text-center">
|
||||
<h2 className="font-cal text-lg">{t("submitted_feedback")}</h2>
|
||||
<p className="text-sm">{rateValue < 4 ? t("how_can_we_improve") : t("most_liked")}</p>
|
||||
</div>
|
||||
|
||||
@@ -1,37 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { useSearchParams, usePathname } from "next/navigation";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useQueryState } from "nuqs";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import {
|
||||
DataTableProvider,
|
||||
type SystemFilterSegment,
|
||||
useDataTable,
|
||||
ColumnFilterType,
|
||||
useFilterValue,
|
||||
ZMultiSelectFilterValue,
|
||||
ZDateRangeFilterValue,
|
||||
ZTextFilterValue,
|
||||
} from "@calcom/features/data-table";
|
||||
import { DataTableProvider, type SystemFilterSegment, ColumnFilterType } from "@calcom/features/data-table";
|
||||
import { useSegments } from "@calcom/features/data-table/hooks/useSegments";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import type { HorizontalTabItemProps } from "@calcom/ui/components/navigation";
|
||||
import { HorizontalTabs } from "@calcom/ui/components/navigation";
|
||||
import { WipeMyCalActionButton } from "@calcom/web/components/apps/wipemycalother/wipeMyCalActionButton";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
|
||||
import type { validStatuses } from "~/bookings/lib/validStatuses";
|
||||
import { viewParser } from "~/bookings/lib/viewParser";
|
||||
import { BookingListContainer } from "../components/BookingListContainer";
|
||||
import type { validStatuses } from "../lib/validStatuses";
|
||||
import { viewParser } from "../lib/viewParser";
|
||||
|
||||
import { BookingsListContainer } from "../components/BookingsListContainer";
|
||||
|
||||
const BookingsCalendarContainer = dynamic(() =>
|
||||
import("../components/BookingsCalendarContainer").then((mod) => ({
|
||||
default: mod.BookingsCalendarContainer,
|
||||
const BookingCalendarContainer = dynamic(() =>
|
||||
import("../components/BookingCalendarContainer").then((mod) => ({
|
||||
default: mod.BookingCalendarContainer,
|
||||
}))
|
||||
);
|
||||
|
||||
@@ -87,134 +72,19 @@ function BookingsContent({ status, permissions, bookingsV3Enabled }: BookingsPro
|
||||
const [_view] = useQueryState("view", viewParser.withDefault("list"));
|
||||
// Force view to be "list" if calendar view is disabled
|
||||
const view = bookingsV3Enabled ? _view : "list";
|
||||
const { t } = useLocale();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const tabs: HorizontalTabItemProps[] = useMemo(() => {
|
||||
const queryString = searchParams?.toString() || "";
|
||||
|
||||
const baseTabConfigs = [
|
||||
{
|
||||
name: "upcoming",
|
||||
path: "/bookings/upcoming",
|
||||
"data-testid": "upcoming",
|
||||
},
|
||||
{
|
||||
name: "unconfirmed",
|
||||
path: "/bookings/unconfirmed",
|
||||
"data-testid": "unconfirmed",
|
||||
},
|
||||
{
|
||||
name: "recurring",
|
||||
path: "/bookings/recurring",
|
||||
"data-testid": "recurring",
|
||||
},
|
||||
{
|
||||
name: "past",
|
||||
path: "/bookings/past",
|
||||
"data-testid": "past",
|
||||
},
|
||||
{
|
||||
name: "cancelled",
|
||||
path: "/bookings/cancelled",
|
||||
"data-testid": "cancelled",
|
||||
},
|
||||
];
|
||||
|
||||
return baseTabConfigs.map((tabConfig) => ({
|
||||
name: tabConfig.name,
|
||||
href: queryString ? `${tabConfig.path}?${queryString}` : tabConfig.path,
|
||||
"data-testid": tabConfig["data-testid"],
|
||||
}));
|
||||
}, [searchParams]);
|
||||
|
||||
const eventTypeIds = useFilterValue("eventTypeId", ZMultiSelectFilterValue)?.data as number[] | undefined;
|
||||
const teamIds = useFilterValue("teamId", ZMultiSelectFilterValue)?.data as number[] | undefined;
|
||||
const userIds = useFilterValue("userId", ZMultiSelectFilterValue)?.data as number[] | undefined;
|
||||
const dateRange = useFilterValue("dateRange", ZDateRangeFilterValue)?.data;
|
||||
const attendeeName = useFilterValue("attendeeName", ZTextFilterValue);
|
||||
const attendeeEmail = useFilterValue("attendeeEmail", ZTextFilterValue);
|
||||
const bookingUid = useFilterValue("bookingUid", ZTextFilterValue)?.data?.operand as string | undefined;
|
||||
|
||||
const { limit, offset } = useDataTable();
|
||||
|
||||
// Only apply pagination for list view, calendar view needs all bookings
|
||||
const shouldPaginate = view === "list";
|
||||
const queryLimit = shouldPaginate ? limit : 100; // Use max limit for calendar view
|
||||
const queryOffset = shouldPaginate ? offset : 0; // Reset offset for calendar view
|
||||
|
||||
const query = trpc.viewer.bookings.get.useQuery(
|
||||
{
|
||||
limit: queryLimit,
|
||||
offset: queryOffset,
|
||||
filters: {
|
||||
status,
|
||||
eventTypeIds,
|
||||
teamIds,
|
||||
userIds,
|
||||
attendeeName,
|
||||
attendeeEmail,
|
||||
bookingUid,
|
||||
afterStartDate: dateRange?.startDate
|
||||
? dayjs(dateRange?.startDate).startOf("day").toISOString()
|
||||
: undefined,
|
||||
beforeEndDate: dateRange?.endDate ? dayjs(dateRange?.endDate).endOf("day").toISOString() : undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes - data is considered fresh
|
||||
gcTime: 30 * 60 * 1000, // 30 minutes - cache retention time
|
||||
}
|
||||
);
|
||||
|
||||
const isEmpty = useMemo(() => !query.data?.bookings.length, [query.data]);
|
||||
const isPending = query.isPending;
|
||||
const totalRowCount = query.data?.totalCount;
|
||||
const hasError = !!query.error;
|
||||
|
||||
const errorView = query.error ? (
|
||||
<Alert severity="error" title={t("something_went_wrong")} message={query.error.message} />
|
||||
) : undefined;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
<div className="flex flex-row flex-wrap justify-between lg:hidden">
|
||||
<HorizontalTabs
|
||||
tabs={tabs.map((tab) => ({
|
||||
...tab,
|
||||
name: t(tab.name),
|
||||
}))}
|
||||
<div className={classNames(view === "calendar" && "-mb-8")}>
|
||||
{view === "list" && (
|
||||
<BookingListContainer
|
||||
status={status}
|
||||
permissions={permissions}
|
||||
bookingsV3Enabled={bookingsV3Enabled}
|
||||
/>
|
||||
</div>
|
||||
<main className="w-full">
|
||||
<div className="flex w-full flex-col">
|
||||
{status === "upcoming" && !isEmpty && (
|
||||
<WipeMyCalActionButton bookingStatus={status} bookingsEmpty={isEmpty} />
|
||||
)}
|
||||
{view === "list" && (
|
||||
<BookingsListContainer
|
||||
status={status}
|
||||
permissions={permissions}
|
||||
data={query.data}
|
||||
isPending={isPending}
|
||||
totalRowCount={totalRowCount}
|
||||
enableDetailsSheet={bookingsV3Enabled}
|
||||
ErrorView={errorView}
|
||||
hasError={hasError}
|
||||
/>
|
||||
)}
|
||||
{bookingsV3Enabled && view === "calendar" && (
|
||||
<BookingsCalendarContainer
|
||||
status={status}
|
||||
permissions={permissions}
|
||||
data={query.data}
|
||||
isPending={isPending}
|
||||
ErrorView={errorView}
|
||||
hasError={hasError}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
)}
|
||||
{bookingsV3Enabled && view === "calendar" && (
|
||||
<BookingCalendarContainer status={status} permissions={permissions} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user