Skip to content

Scheduling infrastructure for absolutely everyone.

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

Hariom Balharaa7fd7890a70c
diff --git a/apps/web/app/(use-page-wrapper)/(main-nav)/booking/[uid]/logs/page.tsx b/apps/web/app/(use-page-wrapper)/(main-nav)/booking/[uid]/logs/page.tsx
index 5d5a072db4d..ebe3c5c11b6 100644
--- a/apps/web/app/(use-page-wrapper)/(main-nav)/booking/[uid]/logs/page.tsx
+++ b/apps/web/app/(use-page-wrapper)/(main-nav)/booking/[uid]/logs/page.tsx
@@ -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>
);
};
diff --git a/apps/web/app/(use-page-wrapper)/(main-nav)/bookings/[status]/page.tsx b/apps/web/app/(use-page-wrapper)/(main-nav)/bookings/[status]/page.tsx
index 2176941549f..aad91983df0 100644
--- a/apps/web/app/(use-page-wrapper)/(main-nav)/bookings/[status]/page.tsx
+++ b/apps/web/app/(use-page-wrapper)/(main-nav)/bookings/[status]/page.tsx
@@ -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>
);
diff --git a/apps/web/modules/bookings/components/BookingDetailsSheet.tsx b/apps/web/modules/bookings/components/BookingDetailsSheet.tsx
index 8dd1a554f61..b6bef505af3 100644
--- a/apps/web/modules/bookings/components/BookingDetailsSheet.tsx
+++ b/apps/web/modules/bookings/components/BookingDetailsSheet.tsx
@@ -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>
diff --git a/apps/web/modules/bookings/components/BookingListContainer.tsx b/apps/web/modules/bookings/components/BookingListContainer.tsx
index 6a01a5878ce..470272f81fb 100644
--- a/apps/web/modules/bookings/components/BookingListContainer.tsx
+++ b/apps/web/modules/bookings/components/BookingListContainer.tsx
@@ -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}
/>
)}
</>
diff --git a/apps/web/modules/bookings/hooks/useActiveSegmentFromUrl.ts b/apps/web/modules/bookings/hooks/useActiveSegmentFromUrl.ts
new file mode 100644
index 00000000000..12dd1c2d715
--- /dev/null
+++ b/apps/web/modules/bookings/hooks/useActiveSegmentFromUrl.ts
@@ -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";
+ },
+ });
+}
+
diff --git a/apps/web/modules/bookings/store/bookingDetailsSheetStore.tsx b/apps/web/modules/bookings/store/bookingDetailsSheetStore.tsx
index 21e5bed8fc9..7f4e45f6e82 100644
--- a/apps/web/modules/bookings/store/bookingDetailsSheetStore.tsx
+++ b/apps/web/modules/bookings/store/bookingDetailsSheetStore.tsx
@@ -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}>
diff --git a/apps/web/modules/bookings/views/bookings-view.tsx b/apps/web/modules/bookings/views/bookings-view.tsx
index 0eafa81e7c9..f1404099977 100644
--- a/apps/web/modules/bookings/views/bookings-view.tsx
+++ b/apps/web/modules/bookings/views/bookings-view.tsx
@@ -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" && (
diff --git a/apps/web/public/static/locales/en/common.json b/apps/web/public/static/locales/en/common.json
index 53d118a1a8a..6c3adf50dbf 100644
--- a/apps/web/public/static/locales/en/common.json
+++ b/apps/web/public/static/locales/en/common.json
@@ -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}}",
diff --git a/apps/web/modules/booking/logs/views/booking-logs-view.tsx b/packages/features/booking-audit/client/components/BookingHistory.tsx
similarity index 97%
rename from apps/web/modules/booking/logs/views/booking-logs-view.tsx
rename to packages/features/booking-audit/client/components/BookingHistory.tsx
index d47fb528b1e..d5f020a3e50 100644
--- a/apps/web/modules/booking/logs/views/booking-logs-view.tsx
+++ b/packages/features/booking-audit/client/components/BookingHistory.tsx
@@ -1,10 +1,6 @@
-/**
- * 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";
@@ -17,7 +13,7 @@ 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 {
+interface BookingHistoryProps {
bookingUid: string;
}
@@ -76,7 +72,6 @@ const ACTION_ICON_MAP: Record<string, IconName> = {
ATTENDEE_NO_SHOW_UPDATED: "ban",
} as const;
-
const ACTOR_ROLE_LABEL_MAP: Record<AuditActorType, string | null> = {
GUEST: "guest",
ATTENDEE: "attendee",
@@ -361,8 +356,7 @@ function useBookingLogsFilters(
return { filteredLogs, actorOptions };
}
-export default function BookingLogsView({ bookingUid }: BookingLogsViewProps) {
- const router = useRouter();
+export function BookingHistory({ bookingUid }: BookingHistoryProps) {
const [searchTerm, setSearchTerm] = useState("");
const [actorFilter, setActorFilter] = useState<string | null>(null);
const { t } = useLocale();
@@ -384,9 +378,6 @@ export default function BookingLogsView({ bookingUid }: BookingLogsViewProps) {
<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>
);
diff --git a/packages/features/booking-audit/client/components/BookingHistoryPage.tsx b/packages/features/booking-audit/client/components/BookingHistoryPage.tsx
new file mode 100644
index 00000000000..b983a95f144
--- /dev/null
+++ b/packages/features/booking-audit/client/components/BookingHistoryPage.tsx
@@ -0,0 +1,15 @@
+"use client";
+
+import { BookingHistory } from "./BookingHistory";
+
+interface BookingHistoryPageProps {
+ bookingUid: string;
+}
+
+/**
+ * BookingHistoryPage - Wrapper component for standalone page context
+ * Adds page-specific styling and layout for the booking history view
+ */
+export function BookingHistoryPage({ bookingUid }: BookingHistoryPageProps) {
+ return <BookingHistory bookingUid={bookingUid} />;
+}
diff --git a/packages/features/flags/features.repository.interface.ts b/packages/features/flags/features.repository.interface.ts
index fcbca26d25c..9a18dc0a7b1 100644
--- a/packages/features/flags/features.repository.interface.ts
+++ b/packages/features/flags/features.repository.interface.ts
@@ -7,6 +7,7 @@ import type { AppFlags, FeatureState } from "./config";
export interface IFeaturesRepository {
checkIfFeatureIsEnabledGlobally(slug: keyof AppFlags): Promise<boolean>;
checkIfUserHasFeature(userId: number, slug: string): Promise<boolean>;
+ getUserFeaturesStatus(userId: number, slugs: string[]): Promise<Record<string, boolean>>;
checkIfUserHasFeatureNonHierarchical(userId: number, slug: string): Promise<boolean>;
checkIfTeamHasFeature(teamId: number, slug: keyof AppFlags): Promise<boolean>;
getTeamsWithFeatureEnabled(slug: keyof AppFlags): Promise<number[]>;
diff --git a/packages/features/flags/features.repository.mock.ts b/packages/features/flags/features.repository.mock.ts
index b081076f148..eb08314ab27 100644
--- a/packages/features/flags/features.repository.mock.ts
+++ b/packages/features/flags/features.repository.mock.ts
@@ -6,6 +6,10 @@ export class MockFeaturesRepository implements IFeaturesRepository {
return slug === "mock-feature";
}
+ async getUserFeaturesStatus(userId: number, slugs: string[]): Promise<Record<string, boolean>> {
+ return Object.fromEntries(slugs.map((slug) => [slug, slug === "mock-feature"]));
+ }
+
async checkIfUserHasFeatureNonHierarchical(userId: number, slug: string) {
return slug === "mock-feature";
}
diff --git a/packages/features/flags/features.repository.ts b/packages/features/flags/features.repository.ts
index 7cdced31229..76f3651cf8b 100644
--- a/packages/features/flags/features.repository.ts
+++ b/packages/features/flags/features.repository.ts
@@ -19,7 +19,7 @@ export class FeaturesRepository implements IFeaturesRepository {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private static featuresCache: { data: any[]; expiry: number } | null = null;
- constructor(private prismaClient: PrismaClient) {}
+ constructor(private prismaClient: PrismaClient) { }
private clearCache() {
FeaturesRepository.featuresCache = null;
@@ -151,6 +151,62 @@ export class FeaturesRepository implements IFeaturesRepository {
}
}
+ /**
+ * Checks if a specific user has access to multiple features in a single operation.
+ *
+ * @param userId - The ID of the user to check
+ * @param slugs - Array of feature identifiers to check
+ * @returns Promise<Record<string, boolean>> - A record mapping each slug to its enabled status
+ * @throws Error if the feature access check fails
+ */
+ async getUserFeaturesStatus(userId: number, slugs: string[]): Promise<Record<string, boolean>> {
+ try {
+ if (slugs.length === 0) {
+ return {};
+ }
+
+ const featuresStatus: Record<string, boolean> = Object.fromEntries(slugs.map((slug) => [slug, false]));
+
+ const userFeatures = await this.prismaClient.userFeatures.findMany({
+ where: {
+ userId,
+ featureId: {
+ in: slugs,
+ },
+ },
+ select: {
+ featureId: true,
+ enabled: true,
+ },
+ });
+
+ const featuresConfiguredForUser = new Set<string>();
+ const slugsToCheckAtTeamLevel: string[] = [];
+
+ for (const userFeature of userFeatures) {
+ featuresStatus[userFeature.featureId] = userFeature.enabled;
+ featuresConfiguredForUser.add(userFeature.featureId);
+ }
+
+ for (const slug of slugs) {
+ // If the feature is not configured for the user, check team-level
+ if (!featuresConfiguredForUser.has(slug)) {
+ slugsToCheckAtTeamLevel.push(slug);
+ }
+ }
+
+ await Promise.all(slugsToCheckAtTeamLevel.map(async (slug) => {
+ const hasTeamFeature = await this.checkIfUserBelongsToTeamWithFeature(userId, slug);
+ featuresStatus[slug] = hasTeamFeature;
+ }))
+
+ return featuresStatus;
+ } catch (err) {
+ captureException(err);
+ throw err;
+ }
+ }
+
/**
* Checks if a specific user has access to a feature, ignoring hierarchical (parent) teams.
* Only checks direct user assignments and direct team memberships — does not traverse parents.
diff --git a/packages/ui/components/segmented-control/SegmentedControl.tsx b/packages/ui/components/segmented-control/SegmentedControl.tsx
new file mode 100644
index 00000000000..0e5d59617ef
--- /dev/null
+++ b/packages/ui/components/segmented-control/SegmentedControl.tsx
@@ -0,0 +1,74 @@
+import classNames from "@calcom/ui/classNames";
+
+export type SegmentedControlData<T extends string> = T | { value: T; label: string };
+
+export interface SegmentedControlProps<T extends string> {
+ data: SegmentedControlData<T>[];
+ value: T;
+ onChange: (value: T) => void;
+ disabled?: boolean;
+ className?: string;
+ "data-testid"?: string;
+}
+
+const SegmentedControl = function <T extends string>({
+ data,
+ value,
+ onChange,
+ disabled = false,
+ className,
+ "data-testid": dataTestId,
+ ...props
+}: SegmentedControlProps<T>) {
+ const handleChange = (newValue: T) => {
+ if (!disabled) {
+ onChange(newValue);
+ }
+ };
+
+ return (
+ <div
+ className={classNames("max-w-full", className)}
+ data-testid={dataTestId}
+ {...props}>
+ <div
+ className="no-scrollbar flex space-x-0.5 overflow-x-scroll rounded-lg bg-subtle p-0.5"
+ role="radiogroup">
+ {data.map((item, idx) => {
+ const itemValue = typeof item === "string" ? item : item.value;
+ const itemLabel = typeof item === "string" ? item : item.label;
+ const isActive = value === itemValue;
+ const inputId = `segmented-control-${itemValue}-${idx}`;
+
+ return (
+ <label
+ key={itemValue}
+ htmlFor={inputId}
+ className={classNames(
+ "inline-flex h-fit w-full items-center justify-center whitespace-nowrap rounded-lg p-1 text-md font-medium leading-none transition md:mb-0",
+ "not-disabled:hover:shadow-outline-gray-hover not-disabled:active:shadow-outline-gray-active",
+ isActive
+ ? "bg-default text-emphasis shadow-outline-gray-rested ring-inset ring-subtle"
+ : "text-subtle",
+ disabled ? "pointer-events-none opacity-30" : "cursor-pointer"
+ )}>
+ <input
+ type="radio"
+ id={inputId}
+ value={itemValue}
+ checked={isActive}
+ onChange={() => handleChange(itemValue)}
+ disabled={disabled}
+ className="sr-only"
+ aria-checked={isActive}
+ />
+ <span>{itemLabel}</span>
+ </label>
+ );
+ })}
+ </div>
+ </div>
+ );
+};
+
+export default SegmentedControl;
diff --git a/packages/ui/components/segmented-control/index.ts b/packages/ui/components/segmented-control/index.ts
new file mode 100644
index 00000000000..a620a2f8bd9
--- /dev/null
+++ b/packages/ui/components/segmented-control/index.ts
@@ -0,0 +1,2 @@
+export { default as SegmentedControl } from "./SegmentedControl";
+export type { SegmentedControlProps, SegmentedControlData } from "./SegmentedControl";
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 69c509241b2..c14f58dbf08 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -57,7 +57,8 @@
"./components/unpublished-entity": "./components/unpublished-entity/index.ts",
"./components/table/TableNew": "./components/table/TableNew.tsx",
"./components/app-list-card/AppListCard": "./components/app-list-card/AppListCard.tsx",
- "./components/section": "./components/section/index.ts"
+ "./components/section": "./components/section/index.ts",
+ "./components/segmented-control": "./components/segmented-control/index.ts"
},
"license": "MIT",
"scripts": {