feat: integrate BookingHistory with Bookings V3 design (#26301)

* Integrate BookingHistory with Bookings V3 design

* Enhance booking features by integrating booking audit functionality

- Updated the booking page to retrieve user feature statuses for "bookings-v3" and "booking-audit".
- Modified BookingDetailsSheet and BookingListContainer components to accept and utilize the new bookingAuditEnabled prop.
- Adjusted the BookingHistory display logic to conditionally render based on the bookingAuditEnabled state.
- Refactored SegmentedControl to support generic types for better type safety.

This change improves the user experience by allowing conditional access to booking audit features based on user permissions.

* Refactor BookingDetailsSheet to manage active segment state with Zustand store

- Removed local state management for active segment in BookingDetailsSheet and integrated Zustand store for better state synchronization.
- Introduced useActiveSegmentFromUrl hook to sync active segment with URL query parameters.
- Updated BookingDetailsSheet to handle derived active segment logic based on bookingAuditEnabled state.
- Adjusted SegmentedControl to ensure it defaults to "info" when activeSegment is null.

This refactor enhances the maintainability and responsiveness of the booking details component.

* refactor: rename useBiDirectionalSyncBetweenZustandAndNuqs to useBiDirectionalSyncBetweenStoreAndUrl

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

---------

Co-authored-by: Udit Takkar <[email protected]>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-01-05 16:21:35 +05:30
1 parent 87cf3210dc
commit a7fd7890a7
16 files changed
+308 -70

No files matched your search

@@ -11,7 +11,7 @@ import { getServerSession } from "@calcom/features/auth/lib/getServerSession";
import { buildLegacyRequest } from "@lib/buildLegacyCtx";
import BookingLogsView from "~/booking/logs/views/booking-logs-view";
import { BookingHistoryPage } from "@calcom/features/booking-audit/client/components/BookingHistoryPage";
export const generateMetadata = async ({ params }: { params: Promise<{ uid: string }> }) =>
await _generateMetadata(
@@ -39,7 +39,7 @@ const Page = async ({ params }: PageProps) => {
return (
<ShellMainAppDir heading={t("booking_history")} subtitle={t("booking_history_description")}>
<BookingLogsView bookingUid={bookingUid} />
<BookingHistoryPage bookingUid={bookingUid} />
</ShellMainAppDir>
);
};
@@ -55,9 +55,12 @@ const Page = async ({ params }: PageProps) => {
}
const featuresRepository = new FeaturesRepository(prisma);
const bookingsV3Enabled = session?.user?.id
? await featuresRepository.checkIfUserHasFeature(session.user.id, "bookings-v3")
: false;
const featureFlags = session?.user?.id
? await featuresRepository.getUserFeaturesStatus(session.user.id, ["bookings-v3", "booking-audit"])
: { "bookings-v3": false, "booking-audit": false };
const bookingsV3Enabled = featureFlags["bookings-v3"] ?? false;
const bookingAuditEnabled = featureFlags["booking-audit"] ?? false;
return (
<ShellMainAppDir
@@ -69,6 +72,7 @@ const Page = async ({ params }: PageProps) => {
userId={session?.user?.id}
permissions={{ canReadOthersBookings }}
bookingsV3Enabled={bookingsV3Enabled}
bookingAuditEnabled={bookingAuditEnabled}
/>
</ShellMainAppDir>
);
@@ -1,419 +0,0 @@
/**
* TODO: Move it to features/booking-audit
*/
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import dayjs from "@calcom/dayjs";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
import { Icon, type IconName } from "@calcom/ui/components/icon";
import { SkeletonText } from "@calcom/ui/components/skeleton";
import { FilterSearchField, Select } from "@calcom/ui/components/form";
import { Avatar } from "@calcom/ui/components/avatar";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import type { AuditActorType } from "@calcom/features/booking-audit/lib/repository/IAuditActorRepository";
interface BookingLogsViewProps {
bookingUid: string;
}
type TranslationComponent = {
type: "link";
href: string;
};
type TranslationWithParams = {
key: string;
params?: Record<string, string | number>;
components?: TranslationComponent[];
};
type AuditLog = {
id: string;
action: string;
type: string;
timestamp: string;
source: string;
displayJson?: Record<string, unknown> | null;
actionDisplayTitle: TranslationWithParams;
displayFields?: Array<{ labelKey: string; valueKey: string }> | null;
actor: {
type: AuditActorType;
displayName: string | null;
displayEmail: string | null;
displayAvatar: string | null;
};
};
interface BookingLogsFiltersProps {
searchTerm: string;
onSearchChange: (value: string) => void;
actorFilter: string | null;
onActorFilterChange: (value: string | null) => void;
actorOptions: Array<{ label: string; value: string }>;
}
interface BookingLogsTimelineProps {
logs: AuditLog[];
}
const ACTION_ICON_MAP: Record<string, IconName> = {
CREATED: "calendar",
CANCELLED: "ban",
REJECTED: "ban",
ACCEPTED: "check",
RESCHEDULED: "pencil",
RESCHEDULE_REQUESTED: "pencil",
REASSIGNMENT: "user-check",
ATTENDEE_ADDED: "user-check",
ATTENDEE_REMOVED: "user-check",
LOCATION_CHANGED: "map-pin",
HOST_NO_SHOW_UPDATED: "ban",
ATTENDEE_NO_SHOW_UPDATED: "ban",
} as const;
const ACTOR_ROLE_LABEL_MAP: Record<AuditActorType, string | null> = {
GUEST: "guest",
ATTENDEE: "attendee",
SYSTEM: null,
USER: null,
APP: null,
} as const;
function BookingLogsFilters({
searchTerm,
onSearchChange,
actorFilter,
onActorFilterChange,
actorOptions,
}: BookingLogsFiltersProps) {
const { t } = useLocale();
return (
<div className="flex flex-wrap gap-2 items-start">
<div className="flex-1 min-w-[200px]">
<FilterSearchField
size="sm"
value={searchTerm}
onChange={(e) => onSearchChange(e.target.value)}
containerClassName=""
/>
</div>
<div className="min-w-[140px]">
<Select
size="sm"
value={actorFilter ? { label: `${t("actor")}: ${actorFilter}`, value: actorFilter } : { label: `${t("actor")}: ${t("all")}`, value: "" }}
onChange={(option) => {
if (!option) return;
onActorFilterChange(option.value || null);
}}
options={[{ label: t("all"), value: "" }, ...actorOptions]}
/>
</div>
</div>
);
}
/**
* Renders the action display title with support for Trans component interpolation
* Handles translations with embedded components (e.g., links) for proper i18n support
*/
function ActionTitle({ actionDisplayTitle }: { actionDisplayTitle: TranslationWithParams }) {
const { t } = useLocale();
if (actionDisplayTitle.components?.length) {
return (
<ServerTrans
t={t}
i18nKey={actionDisplayTitle.key}
values={actionDisplayTitle.params}
components={actionDisplayTitle.components.map((comp) =>
comp.type === "link" ? (
<Link
key={comp.href}
href={comp.href}
className="text-emphasis underline hover:no-underline"
/>
) : (
<span key={comp.href} />
)
)}
/>
);
}
return <>{t(actionDisplayTitle.key, actionDisplayTitle.params)}</>;
}
interface JsonViewerProps {
data: Record<string, unknown> | null;
}
function JsonViewer({ data }: JsonViewerProps) {
if (!data || Object.keys(data).length === 0) {
return null;
}
const jsonString = JSON.stringify(data, null, 2);
const lines = jsonString.split("\n");
const lineCount = lines.length;
const lineNumberWidth = Math.max(2, Math.ceil(Math.log10(lineCount)) + 1);
return (
<div className="bg-default p-3 rounded-md text-[10px] overflow-x-auto font-mono">
{lines.map((line, idx) => (
<div key={idx} className="flex gap-2">
<span
className="text-subtle select-none text-right shrink-0"
style={{ minWidth: `${lineNumberWidth}ch` }}
>
{idx + 1}
</span>
<span className="text-default whitespace-pre">{line || " "}</span>
</div>
))}
</div>
);
}
function BookingLogsTimeline({ logs }: BookingLogsTimelineProps) {
const { t } = useLocale();
const [expandedLogIds, setExpandedLogIds] = useState<Set<string>>(new Set());
const [showJsonMap, setShowJsonMap] = useState<Record<string, boolean>>({});
const toggleExpand = (logId: string) => {
setExpandedLogIds((prev) => {
const newSet = new Set(prev);
if (newSet.has(logId)) {
newSet.delete(logId);
} else {
newSet.add(logId);
}
return newSet;
});
};
const toggleJson = (logId: string) => {
setShowJsonMap((prev) => ({
...prev,
[logId]: !prev[logId],
}));
};
if (logs.length === 0) {
return (
<div className="text-center py-12">
<p className="text-muted">{t("no_audit_logs_found")}</p>
</div>
);
}
return (
<div className="flex flex-col gap-0.5">
{logs.map((log, index) => {
const isLast = index === logs.length - 1;
const isExpanded = expandedLogIds.has(log.id);
const showJson = showJsonMap[log.id] || false;
const actorRole = ACTOR_ROLE_LABEL_MAP[log.actor.type] ?? null;
return (
<div key={log.id} className="flex gap-1">
<div className="flex flex-col items-center self-stretch">
<div className="pt-2 shrink-0">
<div className="bg-subtle rounded-[3.556px] p-1 flex items-center justify-center w-4 h-4">
<Icon name={ACTION_ICON_MAP[log.action] ?? "sparkles"} className="h-3 w-3 text-subtle" />
</div>
</div>
{!isLast && (
<div className="w-px bg-subtle flex-1 min-h-0" />
)}
</div>
<div className="flex-1 rounded-lg py-2">
<div className="px-3 mb-2">
<div className="flex items-start justify-between gap-3">
<div className="flex-1 min-w-0">
<h3 className="text-sm font-medium text-emphasis leading-4">
<ActionTitle actionDisplayTitle={log.actionDisplayTitle} />
</h3>
<div className="flex items-center gap-1 mt-1 text-xs text-subtle">
{log.actor.displayAvatar && (
<Avatar
size="xs"
imageSrc={log.actor.displayAvatar}
alt={log.actor.displayName || ""}
/>
)}
<span>
{log.actor.displayName}
{actorRole && <span>{` (${t(actorRole)})`}</span>}
</span>
<span>•</span>
<span>{dayjs(log.timestamp).fromNow()}</span>
</div>
</div>
</div>
</div>
<div className="px-3">
<div className="bg-muted rounded-lg border border-muted">
<div className="py-1">
<Button
color="minimal"
size="sm"
onClick={() => toggleExpand(log.id)}
StartIcon={isExpanded ? "chevron-down" : "chevron-right"}
className="justify-start text-xs font-medium text-subtle h-6">
{isExpanded ? t("hide_details") : t("show_details")}
</Button>
</div>
{isExpanded && (
<div className="bg-default rounded-lg m-0.5 text-xs">
{/* Render displayFields if available, otherwise show type */}
{log.displayFields && log.displayFields.length > 0 ? (
log.displayFields.map((field, idx) => (
<div key={idx} className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
<span className="font-medium text-emphasis min-w-[80px]">{t(field.labelKey)}</span>
<span className="text-[#096638] font-medium">{t(field.valueKey)}</span>
</div>
))
) : null}
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
<span className="font-medium text-emphasis min-w-[80px]">{t("actor")}</span>
<span className="text-default">{log.actor.displayName || log.actor.type}</span>
</div>
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
<span className="font-medium text-emphasis min-w-[80px]">{t("source")}</span>
<span className="text-default">{log.source}</span>
</div>
<div className="flex items-start gap-2 py-2 px-3 border-b border-subtle">
<span className="font-medium text-emphasis min-w-[80px]">
{t("timestamp")}
</span>
<span className="text-default">
{dayjs(log.timestamp).format("YYYY-MM-DD HH:mm:ss")}
</span>
</div>
{log.displayJson && Object.keys(log.displayJson).length > 0 && (
<div>
<div className="flex flex-col items-start gap-2 py-1 px-3 border-b border-subtle">
<Button
color="minimal"
size="sm"
onClick={() => toggleJson(log.id)}
StartIcon={showJson ? "chevron-down" : "chevron-right"}
className="-ml-3 h-6 px-2 font-medium text-xs">
{t("json")}
</Button>
</div>
<div>
{showJson && <JsonViewer data={log.displayJson} />}
</div>
</div>
)}
</div>
)}
</div>
</div>
</div>
</div>
);
})}
</div>
);
}
function useBookingLogsFilters(
auditLogs: AuditLog[],
searchTerm: string,
actorFilter: string | null
) {
const filteredLogs = auditLogs.filter((log) => {
const matchesSearch =
!searchTerm ||
log.action.toLowerCase().includes(searchTerm.toLowerCase()) ||
log.actor.displayName?.toLowerCase().includes(searchTerm.toLowerCase());
const matchesActor = !actorFilter || log.actor.displayName === actorFilter;
return matchesSearch && matchesActor;
});
const uniqueActorNames = Array.from(
new Set(
auditLogs
.map((log) => log.actor.displayName)
.filter((name): name is string => Boolean(name))
)
);
const actorOptions = uniqueActorNames.map((actorName) => ({
label: actorName,
value: actorName,
}));
return { filteredLogs, actorOptions };
}
export default function BookingLogsView({ bookingUid }: BookingLogsViewProps) {
const router = useRouter();
const [searchTerm, setSearchTerm] = useState("");
const [actorFilter, setActorFilter] = useState<string | null>(null);
const { t } = useLocale();
const { data, isLoading, error } = trpc.viewer.bookings.getAuditLogs.useQuery({
bookingUid,
});
const auditLogs = data?.auditLogs || [];
const { filteredLogs, actorOptions } = useBookingLogsFilters(
auditLogs,
searchTerm,
actorFilter
);
if (error) {
return (
<div className="flex items-center justify-center py-12">
<div className="text-center">
<p className="text-red-600 font-medium">{t("error_loading_booking_logs")}</p>
<p className="text-sm text-gray-500 mt-2">{error.message}</p>
<Button className="mt-4" onClick={() => router.back()}>
{t("go_back")}
</Button>
</div>
</div>
);
}
if (isLoading) {
return (
<div className="space-y-4">
<SkeletonText className="h-12 w-full" />
<SkeletonText className="h-24 w-full" />
<SkeletonText className="h-24 w-full" />
<SkeletonText className="h-24 w-full" />
</div>
);
}
return (
<div className="space-y-6">
<BookingLogsFilters
searchTerm={searchTerm}
onSearchChange={setSearchTerm}
actorFilter={actorFilter}
onActorFilterChange={setActorFilter}
actorOptions={actorOptions}
/>
<BookingLogsTimeline logs={filteredLogs} />
</div>
);
}
@@ -45,7 +45,8 @@ import { usePaymentStatus } from "../hooks/usePaymentStatus";
import { useBookingDetailsSheetStore } from "../store/bookingDetailsSheetStore";
import type { BookingOutput } from "../types";
import { JoinMeetingButton } from "./JoinMeetingButton";
import { BookingHistory } from "@calcom/features/booking-audit/client/components/BookingHistory";
import { SegmentedControl } from "@calcom/ui/components/segmented-control";
type BookingMetaData = z.infer<typeof bookingMetadataSchema>;
interface BookingDetailsSheetProps {
@@ -53,6 +54,7 @@ interface BookingDetailsSheetProps {
userTimeFormat?: number;
userId?: number;
userEmail?: string;
bookingAuditEnabled?: boolean;
}
export function BookingDetailsSheet({
@@ -60,6 +62,7 @@ export function BookingDetailsSheet({
userTimeFormat,
userId,
userEmail,
bookingAuditEnabled = false,
}: BookingDetailsSheetProps) {
const booking = useBookingDetailsSheetStore((state) => state.getSelectedBooking());
@@ -74,6 +77,7 @@ export function BookingDetailsSheet({
userTimeFormat={userTimeFormat}
userId={userId}
userEmail={userEmail}
bookingAuditEnabled={bookingAuditEnabled}
/>
</BookingActionsStoreProvider>
);
@@ -85,6 +89,26 @@ interface BookingDetailsSheetInnerProps {
userTimeFormat?: number;
userId?: number;
userEmail?: string;
bookingAuditEnabled?: boolean;
}
function useActiveSegment(bookingAuditEnabled: boolean) {
const [activeSegment, setActiveSegmentInStore] = useBookingDetailsSheetStore((state) => [state.activeSegment, state.setActiveSegment]);
const getDerivedActiveSegment = ({ activeSegment, bookingAuditEnabled }: { activeSegment: "info" | "history" | null, bookingAuditEnabled: boolean }) => {
if (!bookingAuditEnabled && activeSegment === "history") {
return "info";
}
return activeSegment ?? "info";
}
const derivedActiveSegment = getDerivedActiveSegment({ activeSegment, bookingAuditEnabled });
const setDerivedActiveSegment = (segment: "info" | "history") => {
setActiveSegmentInStore(getDerivedActiveSegment({ activeSegment: segment, bookingAuditEnabled }));
};
return [derivedActiveSegment, setDerivedActiveSegment] as const;
}
function BookingDetailsSheetInner({
@@ -93,8 +117,10 @@ function BookingDetailsSheetInner({
userTimeFormat,
userId,
userEmail,
bookingAuditEnabled = false,
}: BookingDetailsSheetInnerProps) {
const { t } = useLocale();
const [activeSegment, setActiveSegment] = useActiveSegment(bookingAuditEnabled);
// Fetch additional booking details for reschedule information
const { data: bookingDetails } = trpc.viewer.bookings.getBookingDetails.useQuery(
@@ -117,6 +143,7 @@ function BookingDetailsSheetInner({
navigatePrevious: state.navigatePrevious,
isTransitioning: state.isTransitioning,
setSelectedBookingUid: state.setSelectedBookingUid,
setActiveSegment: state.setActiveSegment,
canGoNext: hasNextInArray || (isLastInArray && state.capabilities?.canNavigateToNextPeriod()),
canGoPrev: hasPreviousInArray || (isFirstInArray && state.capabilities?.canNavigateToPreviousPeriod()),
};
@@ -124,6 +151,7 @@ function BookingDetailsSheetInner({
const handleClose = () => {
navigation.setSelectedBookingUid(null);
navigation.setActiveSegment(null);
};
const handleNext = () => {
@@ -167,15 +195,15 @@ function BookingDetailsSheetInner({
const recurringInfo =
booking.recurringEventId && booking.eventType?.recurringEvent
? {
count: booking.eventType.recurringEvent.count,
recurringEvent: booking.eventType.recurringEvent,
}
count: booking.eventType.recurringEvent.count,
recurringEvent: booking.eventType.recurringEvent,
}
: null;
const customResponses = booking.responses
? Object.entries(booking.responses as Record<string, unknown>)
.filter(([fieldName]) => shouldShowFieldInCustomResponses(fieldName))
.map(([question, answer]) => [question, answer] as [string, unknown])
.filter(([fieldName]) => shouldShowFieldInCustomResponses(fieldName))
.map(([question, answer]) => [question, answer] as [string, unknown])
: [];
const reason = booking.assignmentReason?.[0];
@@ -254,43 +282,59 @@ function BookingDetailsSheetInner({
</SheetTitle>
</div>
<WhenSection
rescheduled={booking.rescheduled || false}
startTime={startTime}
endTime={endTime}
timeZone={userTimeZone}
previousBooking={bookingDetails?.previousBooking}
/>
{bookingAuditEnabled && (
<SegmentedControl
data={[{ value: "info", label: t("info") }, { value: "history", label: t("history") }]}
value={activeSegment}
onChange={(value) => setActiveSegment(value)}
/>
)}
<OldRescheduledBookingInfo
booking={booking}
rescheduledToBooking={bookingDetails?.rescheduledToBooking}
/>
{activeSegment === "info" && (
<>
<WhenSection
rescheduled={booking.rescheduled || false}
startTime={startTime}
endTime={endTime}
timeZone={userTimeZone}
previousBooking={bookingDetails?.previousBooking}
/>
<NewRescheduledBookingInfo booking={booking} />
<OldRescheduledBookingInfo
booking={booking}
rescheduledToBooking={bookingDetails?.rescheduledToBooking}
/>
<CancelledBookingInfo booking={booking} />
<NewRescheduledBookingInfo booking={booking} />
<WhoSection booking={booking} />
<CancelledBookingInfo booking={booking} />
<WhereSection booking={booking} meta={bookingMetadata} />
<WhoSection booking={booking} />
<RecurringInfoSection recurringInfo={recurringInfo} />
<WhereSection booking={booking} meta={bookingMetadata} />
<AssignmentReasonSection booking={booking} />
<RecurringInfoSection recurringInfo={recurringInfo} />
{booking.payment?.[0] && <PaymentSection booking={booking} payment={booking.payment[0]} />}
<AssignmentReasonSection booking={booking} />
<SlotsSection booking={booking} />
{booking.payment?.[0] && <PaymentSection booking={booking} payment={booking.payment[0]} />}
<AdditionalNotesSection booking={booking} />
<SlotsSection booking={booking} />
<CustomQuestionsSection
customResponses={customResponses}
bookingFields={booking.eventType?.bookingFields}
/>
<AdditionalNotesSection booking={booking} />
<TrackingSection tracking={bookingDetails?.tracking} />
<CustomQuestionsSection
customResponses={customResponses}
bookingFields={booking.eventType?.bookingFields}
/>
<TrackingSection tracking={bookingDetails?.tracking} />
</>
)}
{bookingAuditEnabled && activeSegment === "history" && (
<BookingHistory bookingUid={booking.uid} />
)}
</div>
</SheetBody>
@@ -71,6 +71,7 @@ interface BookingListContainerProps {
canReadOthersBookings: boolean;
};
bookingsV3Enabled: boolean;
bookingAuditEnabled: boolean;
}
interface BookingListInnerProps extends BookingListContainerProps {
@@ -87,6 +88,7 @@ function BookingListInner({
permissions,
bookings,
bookingsV3Enabled,
bookingAuditEnabled,
data,
isPending,
hasError,
@@ -221,6 +223,7 @@ function BookingListInner({
userTimeFormat={user?.timeFormat === null ? undefined : user?.timeFormat}
userId={user?.id}
userEmail={user?.email}
bookingAuditEnabled={bookingAuditEnabled}
/>
)}
</>
@@ -0,0 +1,13 @@
import { useQueryState } from "nuqs";
export function useActiveSegmentFromUrl() {
return useQueryState<"info" | "history">("activeSegment", {
defaultValue: "info",
parse: (value) => {
if (!value) return "info";
if (value === "history") return "history";
return "info";
},
});
}
@@ -3,6 +3,7 @@
import React, { useEffect, useRef, useState } from "react";
import { createStore, useStore } from "zustand";
import { useActiveSegmentFromUrl } from "../hooks/useActiveSegmentFromUrl";
import { useSelectedBookingUid } from "../hooks/useSelectedBookingUid";
import type { BookingOutput } from "../types";
@@ -44,6 +45,7 @@ export interface NavigationCapabilities {
interface BookingDetailsSheetStore {
// Core state (view-agnostic)
selectedBookingUid: string | null;
activeSegment: "info" | "history" | null;
bookings: BookingOutput[];
isTransitioning: boolean;
pendingSelection: PendingSelectionType;
@@ -53,6 +55,7 @@ interface BookingDetailsSheetStore {
// Core actions
setSelectedBookingUid: (uid: string | null) => void;
setActiveSegment: (segment: "info" | "history" | null) => void;
setBookings: (bookings: BookingOutput[]) => void;
setCapabilities: (capabilities: NavigationCapabilities | null) => void;
clearSelection: () => void;
@@ -78,6 +81,7 @@ const createBookingDetailsSheetStore = (initialBookings: BookingOutput[] = []) =
return createStore<BookingDetailsSheetStore>((set, get) => ({
// Initial state
selectedBookingUid: null,
activeSegment: null,
bookings: initialBookings,
isTransitioning: false,
pendingSelection: null,
@@ -87,6 +91,9 @@ const createBookingDetailsSheetStore = (initialBookings: BookingOutput[] = []) =
setSelectedBookingUid: (uid) => {
set({ selectedBookingUid: uid });
},
setActiveSegment: (segment) => {
set({ activeSegment: segment });
},
setBookings: (bookings) => set({ bookings }),
setCapabilities: (capabilities) => set({ capabilities }),
clearSelection: () => set({ selectedBookingUid: null }),
@@ -169,6 +176,45 @@ const createBookingDetailsSheetStore = (initialBookings: BookingOutput[] = []) =
const BookingDetailsSheetStoreContext = React.createContext<BookingDetailsSheetStoreType | null>(null);
// TODO: To Avoid this useEffect based double sync, we should return a wrapper store over Zustand and Nuqs.
// Certain states that are stored in query params would be fully powered by Nuqs and other states would be fully powered by Zustand and the wrapper store provides a generic interface to work with both
function useBiDirectionalSyncBetweenStoreAndUrl({ store }: { store: BookingDetailsSheetStoreType }) {
const [selectedBookingUidFromUrl, setSelectedBookingUidToUrl] = useSelectedBookingUid();
const [activeSegmentFromUrl, setActiveSegmentToUrl] = useActiveSegmentFromUrl();
const isSyncedFromUrlToStoreRef = useRef(false);
// Sync Store → URL
useEffect(() => {
// We can't sync from Store to URL if URL hasn't first been synced to Store
// This is to prevent override of any user configuration provided by URL query params. Think about page being refreshed
if (!isSyncedFromUrlToStoreRef.current) return;
const unsubscribe = store.subscribe((state) => {
if (state.selectedBookingUid !== selectedBookingUidFromUrl) {
setSelectedBookingUidToUrl(state.selectedBookingUid);
}
if (state.activeSegment !== activeSegmentFromUrl) {
setActiveSegmentToUrl(state.activeSegment);
}
});
return unsubscribe;
}, [selectedBookingUidFromUrl, activeSegmentFromUrl, store]);
// Sync URL → Store
useEffect(() => {
const state = store.getState();
if (selectedBookingUidFromUrl !== state.selectedBookingUid) {
state.setSelectedBookingUid(selectedBookingUidFromUrl);
}
if (activeSegmentFromUrl !== state.activeSegment) {
state.setActiveSegment(activeSegmentFromUrl);
}
isSyncedFromUrlToStoreRef.current = true;
}, [selectedBookingUidFromUrl, activeSegmentFromUrl, store]);
}
export function BookingDetailsSheetStoreProvider({
children,
bookings,
@@ -179,7 +225,6 @@ export function BookingDetailsSheetStoreProvider({
capabilities?: NavigationCapabilities | null;
}) {
const [store] = useState(() => createBookingDetailsSheetStore(bookings));
const [selectedBookingUidFromUrl, setSelectedBookingUidToUrl] = useSelectedBookingUid();
const previousBookingsRef = useRef<BookingOutput[]>(bookings);
// Update bookings in store
@@ -198,25 +243,7 @@ export function BookingDetailsSheetStoreProvider({
store.getState().setCapabilities(capabilities ?? null);
}, [capabilities, store]);
// Sync Store → URL
useEffect(() => {
const unsubscribe = store.subscribe((state) => {
const storeUid = state.selectedBookingUid;
if (storeUid !== selectedBookingUidFromUrl) {
setSelectedBookingUidToUrl(storeUid);
}
});
return unsubscribe;
}, [selectedBookingUidFromUrl, setSelectedBookingUidToUrl, store]);
// Sync URL → Store
useEffect(() => {
const currentStoreUid = store.getState().selectedBookingUid;
if (currentStoreUid !== selectedBookingUidFromUrl) {
store.getState().setSelectedBookingUid(selectedBookingUidFromUrl);
}
}, [selectedBookingUidFromUrl, store]);
useBiDirectionalSyncBetweenStoreAndUrl({ store });
return (
<BookingDetailsSheetStoreContext.Provider value={store}>
@@ -27,6 +27,7 @@ type BookingsProps = {
canReadOthersBookings: boolean;
};
bookingsV3Enabled: boolean;
bookingAuditEnabled: boolean;
};
function useSystemSegments(userId?: number) {
@@ -68,7 +69,7 @@ export default function Bookings(props: BookingsProps) {
);
}
function BookingsContent({ status, permissions, bookingsV3Enabled }: BookingsProps) {
function BookingsContent({ status, permissions, bookingsV3Enabled, bookingAuditEnabled }: BookingsProps) {
const [view] = useBookingsView({ bookingsV3Enabled });
useBookingsShellHeadingVisibility({ visible: view === "list" });
@@ -80,6 +81,7 @@ function BookingsContent({ status, permissions, bookingsV3Enabled }: BookingsPro
status={status}
permissions={permissions}
bookingsV3Enabled={bookingsV3Enabled}
bookingAuditEnabled={bookingAuditEnabled}
/>
)}
{bookingsV3Enabled && view === "calendar" && (
@@ -403,6 +403,7 @@
"set_up_later": "Set up later",
"current_time": "Current time",
"details": "Details",
"info": "Info",
"welcome": "Welcome",
"welcome_back": "Welcome back",
"welcome_to_calcom": "Welcome to {{appName}}",