refactor: remove 6 @calcom/trpc imports from packages/features (#27727)
* migrate booker layout selector * move schedule hooks and types * migrate feature opt in components * migrate feedback dialog * update * migrate schedule hooks * migrate useSegments * update * update import paths * fix import paths * mv useTimesForSchedule back to features * fix
This commit is contained in:
1 parent
aa5e90ab2a
commit
e64fad8e34
43 files changed
+68
-45
No files matched your search
@@ -1,209 +0,0 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import type { Mock } from "vitest";
|
||||
|
||||
import { Segment } from "@calcom/features/Segment";
|
||||
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
|
||||
import { AttributeType } from "@calcom/prisma/enums";
|
||||
import { trpc, type RouterOutputs } from "@calcom/trpc/react";
|
||||
|
||||
type Attributes = RouterOutputs["viewer"]["appRoutingForms"]["getAttributesForTeam"];
|
||||
type MatchingTeamMembersData = RouterOutputs["viewer"]["attributes"]["findTeamMembersMatchingAttributeLogic"];
|
||||
const mockGetAttributesForTeam = (
|
||||
arg: { data: Attributes; isPending: false } | { data: undefined; isPending: true }
|
||||
) => {
|
||||
(
|
||||
trpc.viewer.appRoutingForms.getAttributesForTeam.useQuery as Mock<
|
||||
typeof trpc.viewer.appRoutingForms.getAttributesForTeam.useQuery
|
||||
>
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
.mockReturnValue(arg as any);
|
||||
};
|
||||
|
||||
const mockGetMatchingTeamMembers = (
|
||||
arg:
|
||||
| {
|
||||
data: MatchingTeamMembersData;
|
||||
isPending: false;
|
||||
}
|
||||
| {
|
||||
data: undefined;
|
||||
isPending: true;
|
||||
}
|
||||
) => {
|
||||
(
|
||||
trpc.viewer.attributes.findTeamMembersMatchingAttributeLogic.useQuery as Mock<
|
||||
typeof trpc.viewer.attributes.findTeamMembersMatchingAttributeLogic.useQuery
|
||||
>
|
||||
)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
.mockReturnValue(arg as any);
|
||||
};
|
||||
|
||||
const mockAttributesWithSingleSelect = () => {
|
||||
return mockGetAttributesForTeam({
|
||||
data: [
|
||||
{
|
||||
id: "a",
|
||||
slug: "department",
|
||||
name: "Department",
|
||||
type: AttributeType.SINGLE_SELECT,
|
||||
isWeightsEnabled: false,
|
||||
options: [
|
||||
{ id: "1", value: "Sales", slug: "sales", contains: [], isGroup: false },
|
||||
{ id: "2", value: "Engineering", slug: "engineering", contains: [], isGroup: false },
|
||||
],
|
||||
},
|
||||
],
|
||||
isPending: false,
|
||||
});
|
||||
};
|
||||
|
||||
// Mock the TRPC hooks
|
||||
vi.mock("@calcom/trpc/react", () => ({
|
||||
trpc: {
|
||||
viewer: {
|
||||
appRoutingForms: {
|
||||
getAttributesForTeam: {
|
||||
useQuery: vi.fn(),
|
||||
},
|
||||
},
|
||||
attributes: {
|
||||
findTeamMembersMatchingAttributeLogic: {
|
||||
useQuery: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock useLocale hook
|
||||
vi.mock("@calcom/lib/hooks/useLocale", () => ({
|
||||
useLocale: () => ({
|
||||
t: (key: string) => key,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("Segment", () => {
|
||||
const defaultQueryValue = {
|
||||
id: "root",
|
||||
type: "group",
|
||||
children1: {
|
||||
"rule-1": {
|
||||
type: "rule",
|
||||
properties: {
|
||||
field: "department",
|
||||
operator: "select_equals",
|
||||
value: ["Sales"],
|
||||
},
|
||||
},
|
||||
},
|
||||
} as AttributesQueryValue;
|
||||
|
||||
const defaultProps = {
|
||||
teamId: 1,
|
||||
queryValue: defaultQueryValue,
|
||||
onQueryValueChange: vi.fn(),
|
||||
className: "test-class",
|
||||
};
|
||||
beforeEach(() => {
|
||||
mockAttributesWithSingleSelect();
|
||||
});
|
||||
|
||||
it("renders query builder when attributes are loaded", async () => {
|
||||
mockGetMatchingTeamMembers({
|
||||
data: {
|
||||
mainWarnings: null,
|
||||
fallbackWarnings: null,
|
||||
troubleshooter: undefined,
|
||||
result: [
|
||||
{
|
||||
id: 1,
|
||||
name: "John Doe",
|
||||
email: "[email protected]",
|
||||
},
|
||||
],
|
||||
},
|
||||
isPending: false,
|
||||
});
|
||||
render(<Segment {...defaultProps} />);
|
||||
|
||||
await waitFor(() => {
|
||||
// Query builder container should be present
|
||||
expect(screen.getByTestId("query-builder-container")).toBeInTheDocument();
|
||||
expect(screen.queryByTestId("segment_loading_state")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("renders in loading state when matching team members are not loaded", async () => {
|
||||
mockGetMatchingTeamMembers({
|
||||
data: undefined,
|
||||
isPending: true,
|
||||
});
|
||||
render(<Segment {...defaultProps} />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("segment_loading_state")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows no filter selected message when empty query value is provided", async () => {
|
||||
mockGetMatchingTeamMembers({
|
||||
isPending: true,
|
||||
data: undefined,
|
||||
});
|
||||
|
||||
const emptyQueryValue = {
|
||||
id: "root",
|
||||
type: "group",
|
||||
children1: {},
|
||||
} as AttributesQueryValue;
|
||||
|
||||
render(<Segment {...defaultProps} queryValue={emptyQueryValue} />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("no_filter_set")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows matching team members when valid query value is provided", async () => {
|
||||
mockGetMatchingTeamMembers({
|
||||
isPending: false,
|
||||
data: {
|
||||
mainWarnings: null,
|
||||
fallbackWarnings: null,
|
||||
troubleshooter: undefined,
|
||||
result: [
|
||||
{
|
||||
id: 1,
|
||||
name: "John Doe",
|
||||
email: "[email protected]",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
render(<Segment {...defaultProps} queryValue={defaultQueryValue} />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("John Doe")).toBeInTheDocument();
|
||||
expect(screen.getByText("([email protected])")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it("shows no filter message when no query is set", async () => {
|
||||
mockGetMatchingTeamMembers({
|
||||
data: {
|
||||
mainWarnings: null,
|
||||
fallbackWarnings: null,
|
||||
troubleshooter: undefined,
|
||||
result: [] as MatchingTeamMembersData["result"],
|
||||
},
|
||||
isPending: false,
|
||||
});
|
||||
render(<Segment {...defaultProps} queryValue={null} />);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("no_filter_set")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,219 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { buildStateFromQueryValue } from "@calcom/app-store/_utils/raqb/raqbUtils.client";
|
||||
import {
|
||||
ConfigFor,
|
||||
withRaqbSettingsAndWidgets,
|
||||
} from "@calcom/app-store/routing-forms/components/react-awesome-query-builder/config/uiConfig";
|
||||
import { getQueryBuilderConfigForAttributes } from "@calcom/app-store/routing-forms/lib/getQueryBuilderConfig";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { isEqual } from "@calcom/lib/isEqual";
|
||||
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
|
||||
import { type RouterOutputs, trpc } from "@calcom/trpc/react";
|
||||
import cn from "@calcom/ui/classNames";
|
||||
import { useCallback, useState } from "react";
|
||||
import type { BuilderProps, ImmutableTree, JsonTree } from "react-awesome-query-builder";
|
||||
import { Builder, Utils as QbUtils, Query } from "react-awesome-query-builder";
|
||||
|
||||
export type Attributes = RouterOutputs["viewer"]["appRoutingForms"]["getAttributesForTeam"];
|
||||
export function useAttributes(teamId: number) {
|
||||
const { data: attributes, isPending } = trpc.viewer.appRoutingForms.getAttributesForTeam.useQuery({
|
||||
teamId,
|
||||
});
|
||||
return {
|
||||
attributes,
|
||||
isPending,
|
||||
};
|
||||
}
|
||||
|
||||
function SegmentWithAttributes({
|
||||
attributes,
|
||||
teamId,
|
||||
queryValue: initialQueryValue,
|
||||
onQueryValueChange,
|
||||
className,
|
||||
filterMemberIds,
|
||||
}: {
|
||||
attributes: Attributes;
|
||||
teamId: number;
|
||||
queryValue: AttributesQueryValue | null;
|
||||
onQueryValueChange: ({ queryValue }: { queryValue: AttributesQueryValue }) => void;
|
||||
className?: string;
|
||||
filterMemberIds?: number[];
|
||||
}) {
|
||||
const attributesQueryBuilderConfig = getQueryBuilderConfigForAttributes({
|
||||
attributes,
|
||||
});
|
||||
|
||||
const [queryValue, setQueryValue] = useState(initialQueryValue);
|
||||
const attributesQueryBuilderConfigWithRaqbSettingsAndWidgets = withRaqbSettingsAndWidgets({
|
||||
config: attributesQueryBuilderConfig,
|
||||
configFor: ConfigFor.Attributes,
|
||||
});
|
||||
|
||||
const queryBuilderData = buildStateFromQueryValue({
|
||||
queryValue: queryValue as JsonTree,
|
||||
config: attributesQueryBuilderConfigWithRaqbSettingsAndWidgets,
|
||||
});
|
||||
|
||||
const renderBuilder = useCallback(
|
||||
(props: BuilderProps) => (
|
||||
<div className="query-builder-container" data-testid="query-builder-container">
|
||||
<div className="query-builder qb-lite">
|
||||
<Builder {...props} />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
function onChange(immutableTree: ImmutableTree) {
|
||||
const jsonTree = QbUtils.getTree(immutableTree) as AttributesQueryValue;
|
||||
|
||||
// IMPORTANT: RAQB calls onChange even without explicit user action. It just identifies if the props have changed or not. isEqual ensures that we don't end up having infinite re-renders.
|
||||
if (!isEqual(jsonTree, queryValue)) {
|
||||
setQueryValue(jsonTree);
|
||||
onQueryValueChange({
|
||||
queryValue: jsonTree,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
// cal-query-builder class has special styling through global CSS, allowing us to customize RAQB
|
||||
<div>
|
||||
<div className={cn("cal-query-builder", className)}>
|
||||
<Query
|
||||
{...attributesQueryBuilderConfigWithRaqbSettingsAndWidgets}
|
||||
value={queryBuilderData.state.tree}
|
||||
onChange={onChange}
|
||||
renderBuilder={renderBuilder}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-4 text-sm">
|
||||
<MatchingTeamMembers teamId={teamId} queryValue={queryValue} filterMemberIds={filterMemberIds} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MatchingTeamMembers({
|
||||
teamId,
|
||||
queryValue,
|
||||
filterMemberIds,
|
||||
}: {
|
||||
teamId: number;
|
||||
queryValue: AttributesQueryValue | null;
|
||||
filterMemberIds?: number[];
|
||||
}) {
|
||||
const { t } = useLocale();
|
||||
|
||||
// Check if queryValue has valid children properties value
|
||||
const hasValidValue = queryValue?.children1
|
||||
? Object.values(queryValue.children1).some(
|
||||
(child) => child.properties?.value?.[0] !== undefined && child.properties?.value?.[0] !== null
|
||||
)
|
||||
: false;
|
||||
|
||||
const { data: matchingTeamMembersWithResult, isPending } =
|
||||
trpc.viewer.attributes.findTeamMembersMatchingAttributeLogic.useQuery(
|
||||
{
|
||||
teamId,
|
||||
attributesQueryValue: queryValue,
|
||||
_enablePerf: true,
|
||||
},
|
||||
{
|
||||
enabled: hasValidValue,
|
||||
}
|
||||
);
|
||||
|
||||
if (!hasValidValue) {
|
||||
return (
|
||||
<div className="border-subtle bg-cal-muted mt-4 stack-y-3 rounded-md border p-4">
|
||||
<div className="text-subtle flex items-center text-sm font-medium">
|
||||
<span>{t("no_filter_set")}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isPending) {
|
||||
return (
|
||||
<div
|
||||
className="border-subtle bg-cal-muted mt-4 stack-y-3 rounded-md border p-4"
|
||||
data-testid="segment_loading_state">
|
||||
<div className="text-emphasis flex items-center text-sm font-medium">
|
||||
<div className="bg-subtle h-4 w-32 animate-pulse rounded" />
|
||||
</div>
|
||||
<ul className="divide-subtle divide-y">
|
||||
{[...Array(3)].map((_, index) => (
|
||||
<li key={index} className="flex items-center py-2">
|
||||
<div className="flex flex-1 items-center space-x-2 text-sm">
|
||||
<div className="bg-subtle h-4 w-24 animate-pulse rounded" />
|
||||
<div className="bg-subtle h-4 w-32 animate-pulse rounded" />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!matchingTeamMembersWithResult) return <span>{t("something_went_wrong")}</span>;
|
||||
const { result: allMatchingTeamMembers } = matchingTeamMembersWithResult;
|
||||
|
||||
const matchingTeamMembers = filterMemberIds
|
||||
? allMatchingTeamMembers?.filter((member) => filterMemberIds.includes(member.id))
|
||||
: allMatchingTeamMembers;
|
||||
|
||||
return (
|
||||
<div className="border-subtle bg-cal-muted mt-4 stack-y-3 rounded-md border p-4">
|
||||
<div className="text-emphasis flex items-center text-sm font-medium">
|
||||
<span>{t("x_matching_members", { x: matchingTeamMembers?.length ?? 0 })}</span>
|
||||
</div>
|
||||
<ul className="divide-subtle divide-y">
|
||||
{matchingTeamMembers?.map((member) => (
|
||||
<li key={member.id} className="flex items-center py-2">
|
||||
<div className="flex flex-1 items-center space-x-2 text-sm">
|
||||
<span className="font-medium">{member.name}</span>
|
||||
<span className="text-subtle">({member.email})</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Segment({
|
||||
teamId,
|
||||
queryValue,
|
||||
onQueryValueChange,
|
||||
className,
|
||||
filterMemberIds,
|
||||
}: {
|
||||
teamId: number;
|
||||
queryValue: AttributesQueryValue | null;
|
||||
onQueryValueChange: ({ queryValue }: { queryValue: AttributesQueryValue }) => void;
|
||||
className?: string;
|
||||
filterMemberIds?: number[];
|
||||
}) {
|
||||
const { attributes, isPending } = useAttributes(teamId);
|
||||
const { t } = useLocale();
|
||||
if (isPending) return <span>Loading...</span>;
|
||||
if (!attributes) {
|
||||
console.error("Error fetching attributes");
|
||||
return <span>{t("something_went_wrong")}</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<SegmentWithAttributes
|
||||
teamId={teamId}
|
||||
attributes={attributes}
|
||||
queryValue={queryValue}
|
||||
onQueryValueChange={onQueryValueChange}
|
||||
className={className}
|
||||
filterMemberIds={filterMemberIds}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { shallow } from "zustand/shallow";
|
||||
|
||||
import { useBookerStoreContext } from "@calcom/features/bookings/Booker/BookerStoreProvider";
|
||||
import { useSchedule } from "@calcom/features/schedules/lib/use-schedule/useSchedule";
|
||||
import { useSchedule } from "~/schedules/hooks/useSchedule";
|
||||
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import { recalculateDateRange } from "../lib/dateRange";
|
||||
import { type UseSegments, SYSTEM_SEGMENT_PREFIX } from "../lib/types";
|
||||
import { isDateRangeFilterValue } from "../lib/utils";
|
||||
|
||||
export const useSegments: UseSegments = ({ tableIdentifier, providedSegments, systemSegments }) => {
|
||||
const { data: rawSegments, isSuccess } = trpc.viewer.filterSegments.list.useQuery(
|
||||
{
|
||||
tableIdentifier,
|
||||
},
|
||||
{
|
||||
enabled: !providedSegments, // Only fetch if segments are not provided
|
||||
}
|
||||
);
|
||||
const { mutate: setPreference } = trpc.viewer.filterSegments.setPreference.useMutation();
|
||||
|
||||
const preferredSegmentId = useMemo(() => rawSegments?.preferredSegmentId || null, [rawSegments]);
|
||||
|
||||
const segments = useMemo(() => {
|
||||
const userSegments = providedSegments || rawSegments?.segments || [];
|
||||
|
||||
const processedSystemSegments = (systemSegments || []).map((segment) => ({
|
||||
perPage: 10,
|
||||
tableIdentifier,
|
||||
...segment,
|
||||
id: `${SYSTEM_SEGMENT_PREFIX}${segment.id}`,
|
||||
type: "system" as const,
|
||||
activeFilters: segment.activeFilters.map((filter) => {
|
||||
if (isDateRangeFilterValue(filter.v)) {
|
||||
return {
|
||||
...filter,
|
||||
v: recalculateDateRange(filter.v),
|
||||
};
|
||||
}
|
||||
return filter;
|
||||
}),
|
||||
}));
|
||||
|
||||
const processedUserSegments = userSegments.map((segment) => ({
|
||||
...segment,
|
||||
type: "user" as const,
|
||||
activeFilters: segment.activeFilters.map((filter) => {
|
||||
if (isDateRangeFilterValue(filter.v)) {
|
||||
return {
|
||||
...filter,
|
||||
v: recalculateDateRange(filter.v),
|
||||
};
|
||||
}
|
||||
return filter;
|
||||
}),
|
||||
}));
|
||||
|
||||
return [...processedSystemSegments, ...processedUserSegments];
|
||||
}, [rawSegments, providedSegments, systemSegments, tableIdentifier]);
|
||||
|
||||
return {
|
||||
segments,
|
||||
preferredSegmentId,
|
||||
isSuccess: Boolean(providedSegments) || isSuccess,
|
||||
setPreference,
|
||||
isSegmentEnabled: true,
|
||||
};
|
||||
};
|
||||
@@ -1,67 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { OptInFeatureConfig } from "@calcom/features/feature-opt-in/config";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import Image from "next/image";
|
||||
import type { ReactElement } from "react";
|
||||
|
||||
interface FeatureOptInBannerProps {
|
||||
featureConfig: OptInFeatureConfig;
|
||||
onDismiss: () => void;
|
||||
onOpenDialog: () => void;
|
||||
}
|
||||
|
||||
export function FeatureOptInBanner({
|
||||
featureConfig,
|
||||
onDismiss,
|
||||
onOpenDialog,
|
||||
}: FeatureOptInBannerProps): ReactElement {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="feature-opt-in-banner"
|
||||
className="bg-default border-subtle fixed bottom-5 right-5 z-50 max-w-xs rounded-lg border shadow-lg group">
|
||||
<div className="p-4">
|
||||
<h3 data-testid="feature-opt-in-banner-title" className="text-emphasis text-lg font-semibold">
|
||||
{t(featureConfig.i18n.title)}
|
||||
</h3>
|
||||
<p className="text-subtle mt-1 text-base">{t(featureConfig.i18n.description)}</p>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onDismiss}
|
||||
variant="icon"
|
||||
StartIcon="x"
|
||||
color="minimal"
|
||||
className="absolute top-1.5 right-1.5 opacity-0 pointer-events-none transition-opacity group-hover:opacity-100 group-hover:pointer-events-auto"
|
||||
aria-label={t("close")}></Button>
|
||||
|
||||
<Button
|
||||
data-testid="feature-opt-in-banner-try-it"
|
||||
className="mt-3"
|
||||
size="sm"
|
||||
color="secondary"
|
||||
onClick={onOpenDialog}>
|
||||
{t("try_it")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="p-1">
|
||||
<div
|
||||
className="relative w-full"
|
||||
style={{ aspectRatio: featureConfig.bannerImage.width / featureConfig.bannerImage.height }}>
|
||||
<Image
|
||||
src={featureConfig.bannerImage.src}
|
||||
alt={t(featureConfig.i18n.title)}
|
||||
fill
|
||||
className="object-contain"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default FeatureOptInBanner;
|
||||
@@ -1,104 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { OptInFeatureConfig } from "@calcom/features/feature-opt-in/config";
|
||||
import { FeedbackDialog } from "@calcom/features/feedback/components/FeedbackDialog";
|
||||
import type { ReactElement } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { FeatureOptInBanner } from "./FeatureOptInBanner";
|
||||
import type { FeatureOptInMutations } from "./FeatureOptInConfirmDialog";
|
||||
import { FeatureOptInConfirmDialog } from "./FeatureOptInConfirmDialog";
|
||||
|
||||
type UserRoleContext = {
|
||||
isOrgAdmin: boolean;
|
||||
orgId: number | null;
|
||||
adminTeamIds: number[];
|
||||
adminTeamNames: { id: number; name: string }[];
|
||||
};
|
||||
|
||||
type FeedbackState = {
|
||||
showFeedbackDialog: boolean;
|
||||
feedbackDialogProps: {
|
||||
surveyId: string;
|
||||
ratingQuestionId: string;
|
||||
commentQuestionId: string;
|
||||
titleKey?: string;
|
||||
descriptionKey?: string;
|
||||
showOn?: "all" | "desktop" | "mobile";
|
||||
} | null;
|
||||
onFeedbackComplete: () => void;
|
||||
};
|
||||
|
||||
type FeatureOptInTrackingData = {
|
||||
enableFor: "user" | "organization" | "teams";
|
||||
teamCount?: number;
|
||||
autoOptIn: boolean;
|
||||
};
|
||||
|
||||
type FeatureOptInBannerState = {
|
||||
shouldShow: boolean;
|
||||
isLoading: boolean;
|
||||
featureConfig: OptInFeatureConfig | null;
|
||||
canOptIn: boolean;
|
||||
blockingReason: string | null;
|
||||
userRoleContext: UserRoleContext | null;
|
||||
isDialogOpen: boolean;
|
||||
openDialog: () => void;
|
||||
closeDialog: () => void;
|
||||
dismiss: () => void;
|
||||
markOptedIn: () => void;
|
||||
mutations: FeatureOptInMutations;
|
||||
feedback: FeedbackState;
|
||||
trackFeatureEnabled: (data: FeatureOptInTrackingData) => void;
|
||||
};
|
||||
|
||||
interface FeatureOptInBannerWrapperProps {
|
||||
state: FeatureOptInBannerState;
|
||||
}
|
||||
|
||||
function FeatureOptInBannerWrapper({ state }: FeatureOptInBannerWrapperProps): ReactElement | null {
|
||||
if (!state.featureConfig) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{state.shouldShow &&
|
||||
typeof document !== "undefined" &&
|
||||
createPortal(
|
||||
<FeatureOptInBanner
|
||||
featureConfig={state.featureConfig}
|
||||
onDismiss={state.dismiss}
|
||||
onOpenDialog={state.openDialog}
|
||||
/>,
|
||||
document.body
|
||||
)}
|
||||
{state.userRoleContext && (
|
||||
<FeatureOptInConfirmDialog
|
||||
isOpen={state.isDialogOpen}
|
||||
onClose={state.closeDialog}
|
||||
onDismissBanner={state.dismiss}
|
||||
onOptInSuccess={state.markOptedIn}
|
||||
featureConfig={state.featureConfig}
|
||||
userRoleContext={state.userRoleContext}
|
||||
mutations={state.mutations}
|
||||
onTrackFeatureEnabled={state.trackFeatureEnabled}
|
||||
/>
|
||||
)}
|
||||
{state.feedback.feedbackDialogProps && (
|
||||
<FeedbackDialog
|
||||
isOpen={state.feedback.showFeedbackDialog}
|
||||
onClose={state.feedback.onFeedbackComplete}
|
||||
onSubmitSuccess={state.feedback.onFeedbackComplete}
|
||||
surveyId={state.feedback.feedbackDialogProps.surveyId}
|
||||
ratingQuestionId={state.feedback.feedbackDialogProps.ratingQuestionId}
|
||||
commentQuestionId={state.feedback.feedbackDialogProps.commentQuestionId}
|
||||
titleKey={state.feedback.feedbackDialogProps.titleKey}
|
||||
descriptionKey={state.feedback.feedbackDialogProps.descriptionKey}
|
||||
showOn={state.feedback.feedbackDialogProps.showOn}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default FeatureOptInBannerWrapper;
|
||||
@@ -1,322 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { OptInFeatureConfig } from "@calcom/features/feature-opt-in/config";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@coss/ui/components/button";
|
||||
import { Checkbox } from "@coss/ui/components/checkbox";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "@coss/ui/components/dialog";
|
||||
import { Label } from "@coss/ui/components/label";
|
||||
import { Menu, MenuCheckboxItem, MenuPopup, MenuSeparator, MenuTrigger } from "@coss/ui/components/menu";
|
||||
import { toastManager } from "@coss/ui/components/toast";
|
||||
import { BuildingIcon, ChevronDownIcon, UserIcon, UsersIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import type { ReactElement } from "react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { FeatureOptInSuccessDialog } from "./FeatureOptInSuccessDialog";
|
||||
|
||||
type UserRoleContext = {
|
||||
isOrgAdmin: boolean;
|
||||
orgId: number | null;
|
||||
adminTeamIds: number[];
|
||||
adminTeamNames: { id: number; name: string }[];
|
||||
};
|
||||
|
||||
export type FeatureOptInMutations = {
|
||||
setUserState: (params: { slug: string; state: "enabled" }) => Promise<unknown>;
|
||||
setTeamState: (params: { teamId: number; slug: string; state: "enabled" }) => Promise<unknown>;
|
||||
setOrganizationState: (params: { slug: string; state: "enabled" }) => Promise<unknown>;
|
||||
setUserAutoOptIn: (params: { autoOptIn: boolean }) => Promise<unknown>;
|
||||
setTeamAutoOptIn: (params: { teamId: number; autoOptIn: boolean }) => Promise<unknown>;
|
||||
setOrganizationAutoOptIn: (params: { autoOptIn: boolean }) => Promise<unknown>;
|
||||
invalidateQueries: () => void;
|
||||
};
|
||||
|
||||
type FeatureOptInTrackingData = {
|
||||
enableFor: "user" | "organization" | "teams";
|
||||
teamCount?: number;
|
||||
autoOptIn: boolean;
|
||||
};
|
||||
|
||||
interface FeatureOptInConfirmDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onDismissBanner: () => void;
|
||||
onOptInSuccess?: () => void;
|
||||
featureConfig: OptInFeatureConfig;
|
||||
userRoleContext: UserRoleContext;
|
||||
mutations: FeatureOptInMutations;
|
||||
onTrackFeatureEnabled?: (data: FeatureOptInTrackingData) => void;
|
||||
}
|
||||
|
||||
export function FeatureOptInConfirmDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onDismissBanner,
|
||||
onOptInSuccess,
|
||||
featureConfig,
|
||||
userRoleContext,
|
||||
mutations,
|
||||
onTrackFeatureEnabled,
|
||||
}: FeatureOptInConfirmDialogProps): ReactElement {
|
||||
const { t } = useLocale();
|
||||
const router = useRouter();
|
||||
|
||||
const { isOrgAdmin, orgId, adminTeamIds, adminTeamNames } = userRoleContext;
|
||||
const hasAdminTeams = adminTeamIds.length > 0;
|
||||
const canEnableForOrg = isOrgAdmin && orgId !== null;
|
||||
const canEnableForTeams = hasAdminTeams;
|
||||
const showSelector = canEnableForOrg || canEnableForTeams;
|
||||
|
||||
const [enableForUser, setEnableForUser] = useState(true);
|
||||
const [enableForOrg, setEnableForOrg] = useState(false);
|
||||
const [selectedTeamIds, setSelectedTeamIds] = useState<number[]>([]);
|
||||
const [autoOptIn, setAutoOptIn] = useState(false);
|
||||
const [isSuccess, setIsSuccess] = useState(false);
|
||||
const [shouldInvalidate, setShouldInvalidate] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const hasTeamsSelected = selectedTeamIds.length > 0;
|
||||
const hasAnySelection = enableForUser || enableForOrg || hasTeamsSelected;
|
||||
|
||||
const getSelectedText = (): string => {
|
||||
const parts: string[] = [];
|
||||
if (enableForUser) parts.push(t("just_for_me"));
|
||||
if (enableForOrg) parts.push(t("entire_organization"));
|
||||
if (hasTeamsSelected) {
|
||||
const teamNames = adminTeamNames
|
||||
.filter((team) => selectedTeamIds.includes(team.id))
|
||||
.map((team) => team.name);
|
||||
parts.push(...teamNames);
|
||||
}
|
||||
return parts.length > 0 ? parts.join(", ") : t("select");
|
||||
};
|
||||
|
||||
const handleUserChange = (checked: boolean): void => {
|
||||
setEnableForUser(checked);
|
||||
if (checked) {
|
||||
setEnableForOrg(false);
|
||||
setSelectedTeamIds([]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOrgChange = (checked: boolean): void => {
|
||||
setEnableForOrg(checked);
|
||||
if (checked) {
|
||||
setEnableForUser(false);
|
||||
setSelectedTeamIds([]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTeamChange = (teamId: number, checked: boolean): void => {
|
||||
if (checked) {
|
||||
setSelectedTeamIds((prev) => [...prev, teamId]);
|
||||
setEnableForUser(false);
|
||||
setEnableForOrg(false);
|
||||
} else {
|
||||
setSelectedTeamIds((prev) => prev.filter((id) => id !== teamId));
|
||||
}
|
||||
};
|
||||
|
||||
const getAutoOptInText = (): string => {
|
||||
if (enableForOrg) {
|
||||
return t("auto_opt_in_future_features_org");
|
||||
}
|
||||
if (hasTeamsSelected) {
|
||||
return t("auto_opt_in_future_features_teams");
|
||||
}
|
||||
return t("auto_opt_in_future_features_user");
|
||||
};
|
||||
|
||||
const handleConfirm = async (): Promise<void> => {
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const promises: Promise<unknown>[] = [];
|
||||
|
||||
if (enableForOrg && orgId) {
|
||||
promises.push(mutations.setOrganizationState({ slug: featureConfig.slug, state: "enabled" }));
|
||||
if (autoOptIn) {
|
||||
promises.push(mutations.setOrganizationAutoOptIn({ autoOptIn: true }));
|
||||
}
|
||||
}
|
||||
|
||||
if (hasTeamsSelected) {
|
||||
selectedTeamIds.forEach((teamId) => {
|
||||
promises.push(mutations.setTeamState({ teamId, slug: featureConfig.slug, state: "enabled" }));
|
||||
if (autoOptIn) {
|
||||
promises.push(mutations.setTeamAutoOptIn({ teamId, autoOptIn: true }));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (enableForUser) {
|
||||
promises.push(mutations.setUserState({ slug: featureConfig.slug, state: "enabled" }));
|
||||
if (autoOptIn) {
|
||||
promises.push(mutations.setUserAutoOptIn({ autoOptIn: true }));
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(promises);
|
||||
|
||||
const enableFor = enableForOrg ? "organization" : hasTeamsSelected ? "teams" : "user";
|
||||
onTrackFeatureEnabled?.({
|
||||
enableFor,
|
||||
teamCount: hasTeamsSelected ? selectedTeamIds.length : undefined,
|
||||
autoOptIn,
|
||||
});
|
||||
|
||||
setIsSuccess(true);
|
||||
setShouldInvalidate(true);
|
||||
onOptInSuccess?.();
|
||||
} catch (_error) {
|
||||
toastManager.add({ title: t("error_enabling_feature"), type: "error" });
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getSettingsRedirectPath = (): string => {
|
||||
if (enableForOrg) {
|
||||
return "/settings/organizations/features";
|
||||
}
|
||||
if (hasTeamsSelected && selectedTeamIds.length > 0) {
|
||||
return `/settings/teams/${selectedTeamIds[0]}/features`;
|
||||
}
|
||||
return "/settings/my-account/features";
|
||||
};
|
||||
|
||||
const handleViewSettings = (): void => {
|
||||
resetAndClose();
|
||||
router.push(getSettingsRedirectPath());
|
||||
};
|
||||
|
||||
const handleDismiss = (): void => {
|
||||
resetAndClose();
|
||||
};
|
||||
|
||||
const resetAndClose = (): void => {
|
||||
if (shouldInvalidate) {
|
||||
mutations.invalidateQueries();
|
||||
setShouldInvalidate(false);
|
||||
}
|
||||
setIsSuccess(false);
|
||||
setEnableForUser(true);
|
||||
setEnableForOrg(false);
|
||||
setSelectedTeamIds([]);
|
||||
setAutoOptIn(false);
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (isSuccess) {
|
||||
return (
|
||||
<FeatureOptInSuccessDialog
|
||||
isOpen={isOpen}
|
||||
onClose={resetAndClose}
|
||||
onDismiss={handleDismiss}
|
||||
onViewSettings={handleViewSettings}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={resetAndClose}>
|
||||
<DialogPopup className="sm:max-w-lg" data-testid="feature-opt-in-confirm-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle data-testid="feature-opt-in-confirm-dialog-title">
|
||||
{t(featureConfig.i18n.name)}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{t(featureConfig.i18n.description)}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel>
|
||||
<div className="space-y-4">
|
||||
{showSelector && (
|
||||
<div className="space-y-2">
|
||||
<Label>{t("enable_for")}</Label>
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="border-default bg-default text-default hover:bg-muted flex w-full items-center justify-between rounded-md border px-3 py-2 text-sm"
|
||||
/>
|
||||
}>
|
||||
<span className="truncate leading-normal">{getSelectedText()}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="ml-2 h-4 w-4 shrink-0" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup className="w-56" align="start">
|
||||
<MenuCheckboxItem
|
||||
checked={enableForUser}
|
||||
onCheckedChange={(checked) => handleUserChange(checked)}>
|
||||
<span className="flex items-center gap-2">
|
||||
<UserIcon className="h-4 w-4" />
|
||||
{t("just_for_me")}
|
||||
</span>
|
||||
</MenuCheckboxItem>
|
||||
|
||||
{canEnableForOrg && (
|
||||
<>
|
||||
<MenuSeparator />
|
||||
<MenuCheckboxItem
|
||||
checked={enableForOrg}
|
||||
onCheckedChange={(checked) => handleOrgChange(checked)}>
|
||||
<span className="flex items-center gap-2">
|
||||
<BuildingIcon className="h-4 w-4" />
|
||||
{t("entire_organization")}
|
||||
</span>
|
||||
</MenuCheckboxItem>
|
||||
</>
|
||||
)}
|
||||
|
||||
{canEnableForTeams && adminTeamNames.length > 0 && (
|
||||
<>
|
||||
<MenuSeparator />
|
||||
{adminTeamNames.map((team) => (
|
||||
<MenuCheckboxItem
|
||||
key={team.id}
|
||||
checked={selectedTeamIds.includes(team.id)}
|
||||
onCheckedChange={(checked) => handleTeamChange(team.id, checked)}>
|
||||
<span className="flex items-center gap-2">
|
||||
<UsersIcon className="h-4 w-4" />
|
||||
{team.name}
|
||||
</span>
|
||||
</MenuCheckboxItem>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Label className="hover:bg-subtle flex cursor-pointer items-center gap-2 rounded-md p-1">
|
||||
<Checkbox checked={autoOptIn} onCheckedChange={(checked) => setAutoOptIn(checked === true)} />
|
||||
<span className="text-default text-sm">{getAutoOptInText()}</span>
|
||||
</Label>
|
||||
</div>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button variant="outline" />} onClick={resetAndClose} disabled={isSubmitting}>
|
||||
{t("cancel")}
|
||||
</DialogClose>
|
||||
<Button
|
||||
data-testid="feature-opt-in-confirm-dialog-enable"
|
||||
onClick={handleConfirm}
|
||||
disabled={isSubmitting || !hasAnySelection}>
|
||||
{t("enable")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default FeatureOptInConfirmDialog;
|
||||
@@ -1,53 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { Button } from "@coss/ui/components/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "@coss/ui/components/dialog";
|
||||
import type { ReactElement } from "react";
|
||||
|
||||
interface FeatureOptInSuccessDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onDismiss: () => void;
|
||||
onViewSettings: () => void;
|
||||
}
|
||||
|
||||
export function FeatureOptInSuccessDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onDismiss,
|
||||
onViewSettings,
|
||||
}: FeatureOptInSuccessDialogProps): ReactElement {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogPopup className="sm:max-w-md" data-testid="feature-opt-in-success-dialog">
|
||||
<DialogHeader>
|
||||
<DialogTitle data-testid="feature-opt-in-success-dialog-title">
|
||||
{t("feature_enabled_successfully")}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{t("feature_enabled_description")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button variant="outline" />} onClick={onDismiss}>
|
||||
{t("dismiss")}
|
||||
</DialogClose>
|
||||
<Button data-testid="feature-opt-in-success-dialog-view-settings" onClick={onViewSettings}>
|
||||
{t("view_settings")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default FeatureOptInSuccessDialog;
|
||||
@@ -1,192 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { FeatureState } from "@calcom/features/flags/config";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Alert } from "@calcom/ui/components/alert";
|
||||
import { SettingsToggle, ToggleGroup } from "@calcom/ui/components/form";
|
||||
import { Icon } from "@calcom/ui/components/icon";
|
||||
import { SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
import { Tooltip } from "@calcom/ui/components/tooltip";
|
||||
import type { ReactElement } from "react";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { getOptInFeatureConfig } from "../config";
|
||||
import type { NormalizedFeature, UseFeatureOptInResult } from "../types";
|
||||
|
||||
interface FeaturesSettingsProps {
|
||||
/** The hook result - can be from useUserFeatureOptIn, useTeamFeatureOptIn, or useOrganizationFeatureOptIn */
|
||||
featureOptIn: UseFeatureOptInResult;
|
||||
/** Whether the user can edit the feature settings. If false, all toggles will be disabled. */
|
||||
canEdit?: boolean;
|
||||
}
|
||||
|
||||
interface ToggleOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
function isEnabledViaAutoOptIn(feature: NormalizedFeature, autoOptIn: boolean): boolean {
|
||||
return feature.currentState === "inherit" && autoOptIn && feature.globalEnabled;
|
||||
}
|
||||
|
||||
function handleValueChange(
|
||||
val: string | undefined,
|
||||
slug: string,
|
||||
setFeatureState: (slug: string, state: FeatureState) => void
|
||||
): void {
|
||||
if (!val) return;
|
||||
setFeatureState(slug, val as FeatureState);
|
||||
}
|
||||
|
||||
function LoadingSkeleton(): ReactElement {
|
||||
return (
|
||||
<div className="border-subtle rounded-b-lg border-x border-b px-4 py-8 sm:px-6">
|
||||
<div className="space-y-4">
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
<SkeletonText className="h-8 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyState({ message }: { message: string }): ReactElement {
|
||||
return <Alert severity="neutral" title={message} />;
|
||||
}
|
||||
|
||||
function FeatureItem({
|
||||
feature,
|
||||
toggleOptions,
|
||||
getBlockedWarning,
|
||||
isBlockedByHigherLevel,
|
||||
autoOptIn,
|
||||
setFeatureState,
|
||||
canEdit,
|
||||
t,
|
||||
}: {
|
||||
feature: NormalizedFeature;
|
||||
toggleOptions: ToggleOption[];
|
||||
getBlockedWarning: (feature: NormalizedFeature) => string | null;
|
||||
isBlockedByHigherLevel: (feature: NormalizedFeature) => boolean;
|
||||
autoOptIn: boolean;
|
||||
setFeatureState: (slug: string, state: FeatureState) => void;
|
||||
canEdit: boolean;
|
||||
t: (key: string) => string;
|
||||
}): ReactElement | null {
|
||||
const config = getOptInFeatureConfig(feature.slug);
|
||||
|
||||
const blockedWarning = getBlockedWarning(feature);
|
||||
const enabledViaAutoOptInFlag = isEnabledViaAutoOptIn(feature, autoOptIn);
|
||||
const blockedByHigherLevel = isBlockedByHigherLevel(feature);
|
||||
const isDisabled = blockedByHigherLevel || !canEdit;
|
||||
|
||||
const finalToggleOptions = useMemo(() => {
|
||||
if (!isDisabled) {
|
||||
return toggleOptions;
|
||||
}
|
||||
return toggleOptions.map((option) => ({
|
||||
...option,
|
||||
disabled: true,
|
||||
}));
|
||||
}, [toggleOptions, isDisabled]);
|
||||
|
||||
if (!config) return null;
|
||||
|
||||
return (
|
||||
<div key={feature.slug}>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h3
|
||||
className={classNames(
|
||||
"text-emphasis flex items-center text-sm font-medium",
|
||||
blockedWarning && "text-subtle line-through"
|
||||
)}>
|
||||
{t(config.i18n.name)}
|
||||
{blockedWarning && (
|
||||
<Tooltip side="top" content={blockedWarning}>
|
||||
<span>
|
||||
<Icon name="circle-alert" className="text-error ml-1 h-4 w-4" />
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{enabledViaAutoOptInFlag && (
|
||||
<Tooltip side="top" content={t("enabled_via_auto_opt_in")}>
|
||||
<span>
|
||||
<Icon name="circle-check" className="text-success ml-1 h-4 w-4" />
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</h3>
|
||||
<p className="text-subtle text-sm">{t(config.i18n.description)}</p>
|
||||
</div>
|
||||
<ToggleGroup
|
||||
value={feature.currentState}
|
||||
onValueChange={(val: string | undefined): void =>
|
||||
handleValueChange(val, feature.slug, setFeatureState)
|
||||
}
|
||||
options={finalToggleOptions}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function FeaturesSettings({ featureOptIn, canEdit = true }: FeaturesSettingsProps): ReactElement {
|
||||
const { t } = useLocale();
|
||||
const {
|
||||
features,
|
||||
autoOptIn,
|
||||
isLoading,
|
||||
setFeatureState,
|
||||
setAutoOptIn,
|
||||
isAutoOptInMutationPending,
|
||||
toggleLabels,
|
||||
autoOptInDescription,
|
||||
getBlockedWarning,
|
||||
isBlockedByHigherLevel,
|
||||
} = featureOptIn;
|
||||
|
||||
if (isLoading) return <LoadingSkeleton />;
|
||||
|
||||
const toggleOptions: ToggleOption[] = [
|
||||
{ value: "disabled", label: toggleLabels.disabled },
|
||||
{ value: "enabled", label: toggleLabels.enabled },
|
||||
{ value: "inherit", label: toggleLabels.inherit },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="border-subtle rounded-b-lg border-x border-b px-4 py-8 sm:px-6">
|
||||
{features.length === 0 && <EmptyState message={t("no_opt_in_features_available")} />}
|
||||
{features.length > 0 && (
|
||||
<div className="space-y-6">
|
||||
{features.map((feature) => (
|
||||
<FeatureItem
|
||||
key={feature.slug}
|
||||
feature={feature}
|
||||
toggleOptions={toggleOptions}
|
||||
getBlockedWarning={getBlockedWarning}
|
||||
isBlockedByHigherLevel={isBlockedByHigherLevel}
|
||||
autoOptIn={autoOptIn}
|
||||
setFeatureState={setFeatureState}
|
||||
canEdit={canEdit}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<SettingsToggle
|
||||
toggleSwitchAtTheEnd={true}
|
||||
title={t("auto_opt_in_experimental")}
|
||||
description={autoOptInDescription}
|
||||
disabled={isAutoOptInMutationPending || !canEdit}
|
||||
checked={autoOptIn}
|
||||
onCheckedChange={setAutoOptIn}
|
||||
switchContainerClassName="mt-6"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default FeaturesSettings;
|
||||
@@ -1,186 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Button } from "@coss/ui/components/button";
|
||||
import { Textarea } from "@coss/ui/components/textarea";
|
||||
import { toastManager } from "@coss/ui/components/toast";
|
||||
import { cn } from "@coss/ui/lib/utils";
|
||||
import { XIcon } from "lucide-react";
|
||||
import type { ReactElement } from "react";
|
||||
import { useState } from "react";
|
||||
import { RATING_OPTIONS } from "../../bookings/lib/rating";
|
||||
|
||||
export interface FeedbackDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSubmitSuccess?: () => void;
|
||||
surveyId: string;
|
||||
ratingQuestionId: string;
|
||||
commentQuestionId: string;
|
||||
titleKey?: string;
|
||||
descriptionKey?: string;
|
||||
/** Where to show the dialog: "all" | "desktop" | "mobile". Defaults to "all". */
|
||||
showOn?: "all" | "desktop" | "mobile";
|
||||
}
|
||||
|
||||
/**
|
||||
* Bottom-right positioned feedback card (non-blocking).
|
||||
* Styled similar to the feature opt-in banner.
|
||||
*/
|
||||
export function FeedbackDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSubmitSuccess,
|
||||
surveyId,
|
||||
ratingQuestionId,
|
||||
commentQuestionId,
|
||||
titleKey = "feedback_dialog_title",
|
||||
descriptionKey = "feedback_dialog_description",
|
||||
showOn = "all",
|
||||
}: FeedbackDialogProps): ReactElement | null {
|
||||
const { t } = useLocale();
|
||||
const [selectedRating, setSelectedRating] = useState<number | null>(null);
|
||||
const [comment, setComment] = useState("");
|
||||
const [isSuccess, setIsSuccess] = useState(false);
|
||||
|
||||
const submitFeedbackMutation = trpc.viewer.feedback.submitFeedback.useMutation({
|
||||
onSuccess: () => {
|
||||
setIsSuccess(true);
|
||||
onSubmitSuccess?.();
|
||||
},
|
||||
onError: () => {
|
||||
toastManager.add({ title: t("error_submitting_feedback"), type: "error" });
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (): Promise<void> => {
|
||||
if (selectedRating === null) return;
|
||||
|
||||
await submitFeedbackMutation.mutateAsync({
|
||||
surveyId,
|
||||
data: {
|
||||
[ratingQuestionId]: selectedRating,
|
||||
[commentQuestionId]: comment,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleSkip = (): void => {
|
||||
resetAndClose();
|
||||
};
|
||||
|
||||
const resetAndClose = (): void => {
|
||||
setSelectedRating(null);
|
||||
setComment("");
|
||||
setIsSuccess(false);
|
||||
onClose();
|
||||
};
|
||||
|
||||
if (!isOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Visibility classes based on showOn
|
||||
const visibilityClass = showOn === "desktop" ? "hidden sm:block" : showOn === "mobile" ? "sm:hidden" : "";
|
||||
const showMobileBackdrop = showOn !== "desktop";
|
||||
|
||||
if (isSuccess) {
|
||||
return (
|
||||
<>
|
||||
{/* Mobile-only backdrop */}
|
||||
{showMobileBackdrop && (
|
||||
<div className="fixed inset-0 z-40 bg-black/50 sm:hidden" onClick={resetAndClose} />
|
||||
)}
|
||||
<div
|
||||
data-testid="feedback-success-dialog"
|
||||
className={cn(
|
||||
"bg-default border-subtle fixed bottom-24 left-5 right-5 z-50 rounded-lg border shadow-lg sm:bottom-5 sm:left-auto sm:max-w-sm",
|
||||
visibilityClass
|
||||
)}>
|
||||
<div className="relative p-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetAndClose}
|
||||
className="absolute top-2 right-2 rounded-md p-1 hover:bg-subtle"
|
||||
aria-label={t("close")}>
|
||||
<XIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<h3 className="text-emphasis text-lg font-semibold">{t("feedback_submitted_title")}</h3>
|
||||
<p className="text-subtle mt-1 text-sm">{t("feedback_submitted_description")}</p>
|
||||
<div className="mt-4 flex justify-end">
|
||||
<Button size="sm" onClick={resetAndClose}>
|
||||
{t("done")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile-only backdrop */}
|
||||
{showMobileBackdrop && (
|
||||
<div className="fixed inset-0 z-40 bg-black/50 sm:hidden" onClick={handleSkip} />
|
||||
)}
|
||||
<div
|
||||
data-testid="feedback-dialog"
|
||||
className={cn(
|
||||
"bg-default border-subtle fixed bottom-24 left-5 right-5 z-50 rounded-lg border shadow-lg sm:bottom-5 sm:left-auto sm:max-w-sm",
|
||||
visibilityClass
|
||||
)}>
|
||||
<div className="relative p-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSkip}
|
||||
className="absolute top-2 right-2 rounded-md p-1 hover:bg-subtle"
|
||||
aria-label={t("close")}>
|
||||
<XIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<h3 className="text-emphasis text-lg font-semibold">{t(titleKey)}</h3>
|
||||
<p className="text-subtle mt-1 text-sm">{t(descriptionKey)}</p>
|
||||
|
||||
<div className="mt-4 flex justify-center gap-2">
|
||||
{RATING_OPTIONS.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
onClick={() => setSelectedRating(option.value)}
|
||||
className={cn(
|
||||
"flex h-10 w-10 items-center justify-center rounded-lg text-xl transition-all",
|
||||
selectedRating === option.value ? "bg-emphasis" : "hover:bg-subtle"
|
||||
)}
|
||||
aria-label={`Rating ${option.value}`}>
|
||||
{option.emoji}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Textarea
|
||||
className="mt-3"
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
placeholder={t("feedback_comment_placeholder")}
|
||||
rows={2}
|
||||
/>
|
||||
|
||||
<div className="mt-3 flex justify-end gap-2">
|
||||
<Button size="sm" variant="outline" onClick={handleSkip}>
|
||||
{t("skip")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={selectedRating === null || submitFeedbackMutation.isPending}>
|
||||
{t("submit_feedback")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default FeedbackDialog;
|
||||
File renamed without changes.
+24
-1
@@ -6,7 +6,30 @@ import type { BookerState } from "@calcom/features/bookings/Booker/types";
|
||||
import { getPrefetchMonthCount } from "@calcom/features/bookings/Booker/utils/getPrefetchMonthCount";
|
||||
import { isPrefetchNextMonthEnabled } from "@calcom/features/bookings/Booker/utils/isPrefetchNextMonthEnabled";
|
||||
|
||||
import type { UseScheduleWithCacheArgs } from "./useSchedule";
|
||||
type UseScheduleWithCacheArgs = {
|
||||
username?: string | null;
|
||||
eventSlug?: string | null;
|
||||
eventId?: number | null;
|
||||
month?: string | null;
|
||||
timezone?: string | null;
|
||||
selectedDate?: string | null;
|
||||
duration?: number | null;
|
||||
dayCount?: number | null;
|
||||
rescheduleUid?: string | null;
|
||||
isTeamEvent?: boolean;
|
||||
orgSlug?: string;
|
||||
teamMemberEmail?: string | null;
|
||||
useApiV2?: boolean;
|
||||
enabled?: boolean;
|
||||
/***
|
||||
* Required when prefetching is needed
|
||||
*/
|
||||
bookerLayout?: {
|
||||
layout: string;
|
||||
extraDays: number;
|
||||
columnViewExtraDays: { current: number };
|
||||
};
|
||||
};
|
||||
|
||||
type UseTimesForScheduleProps = Pick<
|
||||
UseScheduleWithCacheArgs,
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
|
||||
export type Slots = RouterOutputs["viewer"]["slots"]["getSchedule"]["slots"];
|
||||
|
||||
export type Slot = Slots[string][number] & { showConfirmButton?: boolean };
|
||||
|
||||
export type GetSchedule = RouterOutputs["viewer"]["slots"]["getSchedule"];
|
||||
@@ -1,47 +0,0 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import axios from "axios";
|
||||
|
||||
import type {
|
||||
GetAvailableSlotsInput_2024_04_15,
|
||||
ApiResponse,
|
||||
ApiSuccessResponse,
|
||||
} from "@calcom/platform-types";
|
||||
import type { GetAvailableSlotsResponse } from "@calcom/trpc/server/routers/viewer/slots/util";
|
||||
|
||||
export const QUERY_KEY = "get-available-slots";
|
||||
|
||||
export const useApiV2AvailableSlots = ({
|
||||
enabled,
|
||||
...rest
|
||||
}: GetAvailableSlotsInput_2024_04_15 & { enabled: boolean }) => {
|
||||
const availableSlots = useQuery({
|
||||
queryKey: [
|
||||
QUERY_KEY,
|
||||
rest.startTime,
|
||||
rest.endTime,
|
||||
rest.eventTypeId,
|
||||
rest.eventTypeSlug,
|
||||
rest.isTeamEvent ?? false,
|
||||
rest.teamId ?? false,
|
||||
rest.usernameList,
|
||||
rest.routedTeamMemberIds,
|
||||
rest.skipContactOwner,
|
||||
rest.teamMemberEmail,
|
||||
rest.embedConnectVersion ?? false,
|
||||
],
|
||||
queryFn: () => {
|
||||
return axios
|
||||
.get<ApiResponse<GetAvailableSlotsResponse>>("/api/v2/slots/available", {
|
||||
params: rest,
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.data.status === "success") {
|
||||
return (res.data as ApiSuccessResponse<GetAvailableSlotsResponse>).data;
|
||||
}
|
||||
throw new Error(res.data.error.message);
|
||||
});
|
||||
},
|
||||
enabled: enabled,
|
||||
});
|
||||
return availableSlots;
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import type { Slots } from "../use-schedule/types";
|
||||
|
||||
export const getNonEmptyScheduleDays = (slots?: Slots) => {
|
||||
if (typeof slots === "undefined") return [];
|
||||
|
||||
const nonEmptyDays: string[] = [];
|
||||
|
||||
Object.keys(slots).forEach((date) => {
|
||||
if (slots[date].some((slot) => !(slot?.away && !slot.toUser && !slot.showNotePublicly) && slots[date].length > 0)) {
|
||||
nonEmptyDays.push(date);
|
||||
}
|
||||
});
|
||||
|
||||
return nonEmptyDays;
|
||||
};
|
||||
|
||||
export const useNonEmptyScheduleDays = (slots?: Slots) => {
|
||||
const days = useMemo(() => getNonEmptyScheduleDays(slots), [slots]);
|
||||
|
||||
return days;
|
||||
};
|
||||
@@ -1,207 +0,0 @@
|
||||
import { useSearchParams } from "next/navigation";
|
||||
|
||||
import { updateEmbedBookerState } from "@calcom/embed-core/src/embed-iframe";
|
||||
import { sdkActionManager } from "@calcom/embed-core/src/sdk-event";
|
||||
import { useBookerStore } from "@calcom/features/bookings/Booker/store";
|
||||
import { isBookingDryRun } from "@calcom/features/bookings/Booker/utils/isBookingDryRun";
|
||||
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { useTimesForSchedule } from "@calcom/features/schedules/lib/use-schedule/useTimesForSchedule";
|
||||
import { getRoutedTeamMemberIdsFromSearchParams } from "@calcom/lib/bookings/getRoutedTeamMemberIdsFromSearchParams";
|
||||
import { PUBLIC_QUERY_AVAILABLE_SLOTS_INTERVAL_SECONDS } from "@calcom/lib/constants";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
|
||||
import { useApiV2AvailableSlots } from "./useApiV2AvailableSlots";
|
||||
|
||||
export type UseScheduleWithCacheArgs = {
|
||||
username?: string | null;
|
||||
eventSlug?: string | null;
|
||||
eventId?: number | null;
|
||||
month?: string | null;
|
||||
timezone?: string | null;
|
||||
selectedDate?: string | null;
|
||||
duration?: number | null;
|
||||
dayCount?: number | null;
|
||||
rescheduleUid?: string | null;
|
||||
isTeamEvent?: boolean;
|
||||
orgSlug?: string;
|
||||
teamMemberEmail?: string | null;
|
||||
useApiV2?: boolean;
|
||||
enabled?: boolean;
|
||||
/***
|
||||
* Required when prefetching is needed
|
||||
*/
|
||||
bookerLayout?: {
|
||||
layout: string;
|
||||
extraDays: number;
|
||||
columnViewExtraDays: { current: number };
|
||||
};
|
||||
};
|
||||
|
||||
const getAvailabilityLoadedEventPayload = ({
|
||||
eventId,
|
||||
eventSlug,
|
||||
}: {
|
||||
eventId: number;
|
||||
eventSlug: string;
|
||||
}) => {
|
||||
return {
|
||||
eventId,
|
||||
eventSlug,
|
||||
};
|
||||
};
|
||||
|
||||
export const useSchedule = ({
|
||||
month,
|
||||
timezone,
|
||||
username,
|
||||
eventSlug,
|
||||
eventId,
|
||||
selectedDate,
|
||||
duration,
|
||||
dayCount,
|
||||
rescheduleUid,
|
||||
isTeamEvent,
|
||||
orgSlug,
|
||||
teamMemberEmail,
|
||||
useApiV2 = false,
|
||||
enabled: enabledProp = true,
|
||||
bookerLayout,
|
||||
}: UseScheduleWithCacheArgs) => {
|
||||
const bookerState = useBookerStore((state) => state.state);
|
||||
|
||||
const [startTime, endTime] = useTimesForSchedule({
|
||||
month,
|
||||
dayCount,
|
||||
selectedDate,
|
||||
bookerLayout,
|
||||
});
|
||||
const searchParams = useSearchParams();
|
||||
const routedTeamMemberIds = searchParams
|
||||
? getRoutedTeamMemberIdsFromSearchParams(new URLSearchParams(searchParams.toString()))
|
||||
: null;
|
||||
const skipContactOwner = searchParams ? searchParams.get("cal.skipContactOwner") === "true" : false;
|
||||
const utils = trpc.useUtils();
|
||||
const routingFormResponseIdParam = searchParams?.get("cal.routingFormResponseId");
|
||||
const queuedFormResponseId = searchParams?.get("cal.queuedFormResponseId");
|
||||
const email = searchParams?.get("email");
|
||||
// We allow skipping the schedule fetch as a requirement for prerendering in iframe through embed as when the pre-rendered iframe is connected, then we would fetch the availability, which would be upto-date
|
||||
// Also, a reuse through Headless Router could completely change the availability as different team members are selected and thus it is unnecessary to fetch the schedule
|
||||
const skipGetSchedule = searchParams?.get("cal.skipSlotsFetch") === "true";
|
||||
const routingFormResponseId = routingFormResponseIdParam
|
||||
? parseInt(routingFormResponseIdParam, 10)
|
||||
: undefined;
|
||||
const embedConnectVersion = searchParams?.get("cal.embed.connectVersion") || "0";
|
||||
const input = {
|
||||
isTeamEvent,
|
||||
usernameList: getUsernameList(username ?? ""),
|
||||
// Prioritize slug over id, since slug is the first value we get available.
|
||||
// If we have a slug, we don't need to fetch the id.
|
||||
// TODO: are queries using eventTypeId faster? Even tho we lost time fetching the id with the slug.
|
||||
...(eventSlug ? { eventTypeSlug: eventSlug } : { eventTypeId: eventId ?? 0 }),
|
||||
// @TODO: Old code fetched 2 days ago if we were fetching the current month.
|
||||
// Do we want / need to keep that behavior?
|
||||
startTime,
|
||||
// if `prefetchNextMonth` is true, two months are fetched at once.
|
||||
endTime,
|
||||
// We use a placeholder value that is there to keep TS happy, but still invalid to tell us that it shouldn't actually be passed in request(and wouldn't because enabled is false if timezone is nullish)
|
||||
// TODO: Better approach here is to use `skipToken` from react-query which requires an upgrade of react-query
|
||||
timeZone: timezone ?? "PLACEHOLDER_TIMEZONE",
|
||||
duration: duration ? `${duration}` : undefined,
|
||||
rescheduleUid,
|
||||
orgSlug,
|
||||
teamMemberEmail,
|
||||
routedTeamMemberIds,
|
||||
skipContactOwner,
|
||||
...(queuedFormResponseId ? { queuedFormResponseId } : { routingFormResponseId }),
|
||||
email,
|
||||
// Ensures that connectVersion causes a refresh of the data
|
||||
...(embedConnectVersion ? { embedConnectVersion } : {}),
|
||||
_isDryRun: searchParams ? isBookingDryRun(searchParams) : false,
|
||||
};
|
||||
|
||||
const options = {
|
||||
trpc: {
|
||||
context: {
|
||||
skipBatch: true,
|
||||
},
|
||||
},
|
||||
// It allows people who might not have the tab in focus earlier, to get latest available slots
|
||||
// It might not work correctly in iframes, so we have refetchInterval to take care of that.
|
||||
// But where it works, it should give user latest availability even if they come back to tab before refetchInterval.
|
||||
refetchOnWindowFocus: true,
|
||||
// It allows long sitting users to get latest available slots
|
||||
refetchInterval: PUBLIC_QUERY_AVAILABLE_SLOTS_INTERVAL_SECONDS * 1000,
|
||||
enabled:
|
||||
!skipGetSchedule &&
|
||||
Boolean(username) &&
|
||||
Boolean(month) &&
|
||||
Boolean(timezone) &&
|
||||
// Should only wait for one or the other, not both.
|
||||
(Boolean(eventSlug) || Boolean(eventId) || eventId === 0) &&
|
||||
enabledProp,
|
||||
};
|
||||
|
||||
const isCallingApiV2Slots = useApiV2 && Boolean(isTeamEvent) && options.enabled;
|
||||
|
||||
// API V2 query for team events
|
||||
const teamScheduleV2 = useApiV2AvailableSlots({
|
||||
...input,
|
||||
enabled: isCallingApiV2Slots,
|
||||
duration: input.duration ? Number(input.duration) : undefined,
|
||||
routedTeamMemberIds: input.routedTeamMemberIds ?? undefined,
|
||||
teamMemberEmail: input.teamMemberEmail ?? undefined,
|
||||
eventTypeId: eventId ?? undefined,
|
||||
});
|
||||
|
||||
const schedule = trpc.viewer.slots.getSchedule.useQuery(input, {
|
||||
...options,
|
||||
// Only enable if we're not using API V2
|
||||
enabled: options.enabled && !isCallingApiV2Slots,
|
||||
});
|
||||
|
||||
if (isCallingApiV2Slots && !teamScheduleV2.failureReason) {
|
||||
updateEmbedBookerState({
|
||||
bookerState,
|
||||
slotsQuery: teamScheduleV2,
|
||||
});
|
||||
|
||||
if (teamScheduleV2.isSuccess && eventId && eventSlug) {
|
||||
sdkActionManager?.fire(
|
||||
"availabilityLoaded",
|
||||
getAvailabilityLoadedEventPayload({ eventId, eventSlug })
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
...teamScheduleV2,
|
||||
/**
|
||||
* Invalidates the request and resends it regardless of any other configuration including staleTime
|
||||
*/
|
||||
invalidate: () => {
|
||||
return teamScheduleV2.refetch();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
updateEmbedBookerState({
|
||||
bookerState,
|
||||
slotsQuery: schedule,
|
||||
});
|
||||
|
||||
if (schedule.isSuccess && eventId && eventSlug) {
|
||||
sdkActionManager?.fire(
|
||||
"availabilityLoaded",
|
||||
getAvailabilityLoadedEventPayload({ eventId, eventSlug })
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
...schedule,
|
||||
/**
|
||||
* Invalidates the request and resends it regardless of any other configuration including staleTime
|
||||
*/
|
||||
invalidate: () => {
|
||||
return utils.viewer.slots.getSchedule.invalidate(input);
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import type { Slots, Slot } from "./types";
|
||||
|
||||
/**
|
||||
* Gets slots for a specific date from the schedule cache.
|
||||
* @param date Format YYYY-MM-DD
|
||||
* @param scheduleCache Instance of useScheduleWithCache
|
||||
*/
|
||||
|
||||
export const useSlotsForDate = (date: string | null, slots?: Slots) => {
|
||||
const slotsForDate = useMemo(() => {
|
||||
if (!date || typeof slots === "undefined") return [];
|
||||
return slots[date] || [];
|
||||
}, [date, slots]);
|
||||
|
||||
return slotsForDate;
|
||||
};
|
||||
|
||||
export const useSlotsForAvailableDates = (dates: (string | null)[], slots?: Slots) => {
|
||||
const [slotsPerDay, setSlotsPerDay] = useState<{ date: string | null; slots: Slots[string] }[]>([]);
|
||||
|
||||
const toggleConfirmButton = useCallback((selectedSlot: Slot) => {
|
||||
setSlotsPerDay((prevSlotsPerDay) =>
|
||||
prevSlotsPerDay.map(({ date, slots }) => ({
|
||||
date,
|
||||
slots: slots.map((slot) => ({
|
||||
...slot,
|
||||
showConfirmButton: slot.time === selectedSlot.time ? !selectedSlot?.showConfirmButton : false,
|
||||
})),
|
||||
}))
|
||||
);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (slots === undefined) {
|
||||
setSlotsPerDay([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedSlots = dates
|
||||
.filter((date) => date !== null)
|
||||
.map((date) => ({
|
||||
slots: slots[`${date}`] || [],
|
||||
date,
|
||||
}));
|
||||
|
||||
setSlotsPerDay(updatedSlots);
|
||||
}, [JSON.stringify(dates), JSON.stringify(slots)]);
|
||||
|
||||
return { slotsPerDay, setSlotsPerDay, toggleConfirmButton } as const;
|
||||
};
|
||||
@@ -1,256 +0,0 @@
|
||||
import * as RadioGroup from "@radix-ui/react-radio-group";
|
||||
import Link from "next/link";
|
||||
import { useCallback, useState } from "react";
|
||||
import { Controller, useFormContext } from "react-hook-form";
|
||||
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { BookerLayouts, defaultBookerLayoutSettings } from "@calcom/prisma/zod-utils";
|
||||
import { bookerLayoutOptions, type BookerLayoutSettings } from "@calcom/prisma/zod-utils";
|
||||
import type { RouterOutputs } from "@calcom/trpc/react";
|
||||
import classNames from "@calcom/ui/classNames";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { Label } from "@calcom/ui/components/form";
|
||||
import { CheckboxField } from "@calcom/ui/components/form";
|
||||
|
||||
import SectionBottomActions from "./SectionBottomActions";
|
||||
|
||||
type BookerLayoutSelectorProps = {
|
||||
title?: string;
|
||||
description?: string;
|
||||
name?: string;
|
||||
/**
|
||||
* If this boolean is set, it will show the user settings if the event does not have any settings (is null).
|
||||
* In that case it also will NOT register itself in the form, so that way when submitting the form, the
|
||||
* values won't be overridden. Because as long as the event's value is null, it will fallback to the user's
|
||||
* settings.
|
||||
*/
|
||||
fallbackToUserSettings?: boolean;
|
||||
/**
|
||||
* isDark boolean should be passed in when the user selected 'dark mode' in the theme settings in profile/appearance.
|
||||
* So it's not based on the user's system settings, but on the user's preference for the booker.
|
||||
* This boolean is then used to show a dark version of the layout image. It's only easthetic, no functionality is attached
|
||||
* to this boolean.
|
||||
*/
|
||||
isDark?: boolean;
|
||||
isLoading?: boolean;
|
||||
isDisabled?: boolean;
|
||||
isOuterBorder?: boolean;
|
||||
user?: Partial<Pick<RouterOutputs["viewer"]["me"]["get"], "defaultBookerLayouts">>;
|
||||
isUserLoading?: boolean;
|
||||
};
|
||||
|
||||
const defaultFieldName = "metadata.bookerLayouts";
|
||||
|
||||
export const BookerLayoutSelector = ({
|
||||
title,
|
||||
description,
|
||||
name,
|
||||
fallbackToUserSettings,
|
||||
isDark,
|
||||
isDisabled = false,
|
||||
isOuterBorder = false,
|
||||
isLoading = false,
|
||||
user,
|
||||
isUserLoading,
|
||||
}: BookerLayoutSelectorProps) => {
|
||||
const { control, getValues } = useFormContext();
|
||||
const { t } = useLocale();
|
||||
// Only fallback if event current does not have any settings, and the fallbackToUserSettings boolean is set.
|
||||
const shouldShowUserSettings = (fallbackToUserSettings && !getValues(name || defaultFieldName)) || false;
|
||||
|
||||
return (
|
||||
<div className={classNames(isOuterBorder && "border-subtle rounded-lg border p-6")}>
|
||||
<div className={classNames(isOuterBorder ? "pb-5" : "border-subtle rounded-t-xl border p-6")}>
|
||||
<Label className={classNames("mb-1 font-semibold", isOuterBorder ? "text-sm" : "text-base")}>
|
||||
{title ? title : t("layout")}
|
||||
</Label>
|
||||
<p className="text-subtle max-w-full wrap-break-word text-sm leading-tight">
|
||||
{description ? description : t("bookerlayout_description")}
|
||||
</p>
|
||||
</div>
|
||||
<Controller
|
||||
// If the event does not have any settings, we don't want to register this field in the form.
|
||||
// That way the settings won't get saved into the event on save, but remain null. Thus keep using
|
||||
// the global user's settings.
|
||||
control={shouldShowUserSettings ? undefined : control}
|
||||
name={name || defaultFieldName}
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<>
|
||||
<BookerLayoutFields
|
||||
showUserSettings={shouldShowUserSettings}
|
||||
settings={value}
|
||||
onChange={onChange}
|
||||
isDark={isDark}
|
||||
isOuterBorder={isOuterBorder}
|
||||
user={user}
|
||||
isUserLoading={isUserLoading}
|
||||
/>
|
||||
{!isOuterBorder && (
|
||||
<SectionBottomActions align="end">
|
||||
<Button loading={isLoading} type="submit" disabled={isDisabled} color="primary">
|
||||
{t("update")}
|
||||
</Button>
|
||||
</SectionBottomActions>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
type BookerLayoutFieldsProps = {
|
||||
settings: BookerLayoutSettings;
|
||||
onChange: (settings: BookerLayoutSettings) => void;
|
||||
showUserSettings: boolean;
|
||||
isDark?: boolean;
|
||||
isOuterBorder?: boolean;
|
||||
user?: Partial<Pick<RouterOutputs["viewer"]["me"]["get"], "defaultBookerLayouts">>;
|
||||
isUserLoading?: boolean;
|
||||
};
|
||||
|
||||
type BookerLayoutState = { [key in BookerLayouts]: boolean };
|
||||
|
||||
const BookerLayoutFields = ({
|
||||
settings,
|
||||
onChange,
|
||||
showUserSettings,
|
||||
isDark,
|
||||
isOuterBorder,
|
||||
user,
|
||||
isUserLoading,
|
||||
}: BookerLayoutFieldsProps) => {
|
||||
const { t } = useLocale();
|
||||
const [isOverridingSettings, setIsOverridingSettings] = useState(false);
|
||||
|
||||
const disableFields = showUserSettings && !isOverridingSettings;
|
||||
const shownSettings = disableFields ? user?.defaultBookerLayouts : settings;
|
||||
const defaultLayout = shownSettings?.defaultLayout || BookerLayouts.MONTH_VIEW;
|
||||
|
||||
// Converts the settings array into a boolean object, which can be used as form values.
|
||||
const toggleValues: BookerLayoutState = bookerLayoutOptions.reduce((layouts, layout) => {
|
||||
layouts[layout] = !shownSettings?.enabledLayouts
|
||||
? defaultBookerLayoutSettings.enabledLayouts.indexOf(layout) > -1
|
||||
: shownSettings.enabledLayouts.indexOf(layout) > -1;
|
||||
return layouts;
|
||||
}, {} as BookerLayoutState);
|
||||
|
||||
const onLayoutToggleChange = useCallback(
|
||||
(changedLayout: BookerLayouts, checked: boolean) => {
|
||||
const newEnabledLayouts = Object.keys(toggleValues).filter((layout) => {
|
||||
if (changedLayout === layout) return checked === true;
|
||||
return toggleValues[layout as BookerLayouts] === true;
|
||||
}) as BookerLayouts[];
|
||||
|
||||
const isDefaultLayoutToggledOff = newEnabledLayouts.indexOf(defaultLayout) === -1;
|
||||
const firstEnabledLayout = newEnabledLayouts[0];
|
||||
|
||||
onChange({
|
||||
enabledLayouts: newEnabledLayouts,
|
||||
// If default layout is toggled off, we set the default layout to the first enabled layout
|
||||
// if there's none enabled, we set it to month view.
|
||||
defaultLayout: isDefaultLayoutToggledOff
|
||||
? firstEnabledLayout || BookerLayouts.MONTH_VIEW
|
||||
: defaultLayout,
|
||||
});
|
||||
},
|
||||
[defaultLayout, onChange, toggleValues]
|
||||
);
|
||||
|
||||
const onDefaultLayoutChange = useCallback(
|
||||
(newDefaultLayout: BookerLayouts) => {
|
||||
onChange({
|
||||
enabledLayouts: Object.keys(toggleValues).filter(
|
||||
(layout) => toggleValues[layout as BookerLayouts] === true
|
||||
) as BookerLayouts[],
|
||||
defaultLayout: newDefaultLayout,
|
||||
});
|
||||
},
|
||||
[toggleValues, onChange]
|
||||
);
|
||||
|
||||
const onOverrideSettings = () => {
|
||||
setIsOverridingSettings(true);
|
||||
// Sent default layout settings to form, otherwise it would still have 'null' as it's value.
|
||||
if (user?.defaultBookerLayouts) onChange(user.defaultBookerLayouts);
|
||||
};
|
||||
return (
|
||||
<div className={classNames("stack-y-5", !isOuterBorder && "border-subtle border-x px-6 py-8")}>
|
||||
<div
|
||||
className={classNames(
|
||||
"flex flex-col gap-5 transition-opacity sm:flex-row sm:gap-3",
|
||||
disableFields && "pointer-events-none opacity-40",
|
||||
disableFields && isUserLoading && "animate-pulse"
|
||||
)}>
|
||||
{bookerLayoutOptions.map((layout) => (
|
||||
<div className="w-full" key={layout}>
|
||||
<label>
|
||||
<img
|
||||
className="mb-3 w-full max-w-none cursor-pointer"
|
||||
src={`/bookerlayout_${layout}${isDark ? "_dark" : ""}.svg`}
|
||||
alt="Layout preview"
|
||||
/>
|
||||
<CheckboxField
|
||||
value={layout}
|
||||
name={`bookerlayout_${layout}`}
|
||||
description={t(`bookerlayout_${layout}`)}
|
||||
checked={toggleValues[layout]}
|
||||
onChange={(ev) => onLayoutToggleChange(layout, ev.target.checked)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
hidden={Object.values(toggleValues).filter((value) => value === true).length <= 1}
|
||||
className={classNames(
|
||||
"transition-opacity",
|
||||
disableFields && "pointer-events-none opacity-40",
|
||||
disableFields && isUserLoading && "animate-pulse"
|
||||
)}>
|
||||
<Label>{t("bookerlayout_default_title")}</Label>
|
||||
<RadioGroup.Root
|
||||
key={defaultLayout}
|
||||
className="border-subtle flex w-full gap-2 rounded-md border p-1"
|
||||
defaultValue={defaultLayout}
|
||||
onValueChange={(layout: BookerLayouts) => onDefaultLayoutChange(layout)}>
|
||||
{bookerLayoutOptions.map((layout) => (
|
||||
<RadioGroup.Item
|
||||
className="aria-checked:bg-emphasis hover:[&:not(:disabled)]:bg-subtle focus:[&:not(:disabled)]:bg-subtle w-full rounded-[4px] p-1 text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-40"
|
||||
disabled={toggleValues[layout] === false}
|
||||
key={layout}
|
||||
value={layout}>
|
||||
{t(`bookerlayout_${layout}`)}
|
||||
<RadioGroup.Indicator />
|
||||
</RadioGroup.Item>
|
||||
))}
|
||||
</RadioGroup.Root>
|
||||
</div>
|
||||
{disableFields && (
|
||||
<p className="text-sm">
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey="bookerlayout_override_global_settings"
|
||||
components={[
|
||||
<Link
|
||||
key="appearance-link"
|
||||
target="_blank"
|
||||
href="/settings/my-account/appearance"
|
||||
className="underline">
|
||||
Appearance
|
||||
</Link>,
|
||||
<Button
|
||||
key="override-button"
|
||||
onClick={onOverrideSettings}
|
||||
color="minimal"
|
||||
className="h-fit p-0 font-normal underline hover:bg-transparent focus-visible:bg-transparent">
|
||||
Override
|
||||
</Button>,
|
||||
]}
|
||||
/>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -14,7 +14,7 @@ import { useInitializeBookerStore } from "@calcom/features/bookings/Booker/store
|
||||
import { useTimePreferences } from "@calcom/features/bookings/lib";
|
||||
import type { ConnectedDestinationCalendars } from "@calcom/features/calendars/lib/getConnectedDestinationCalendars";
|
||||
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { useTimesForSchedule } from "@calcom/features/schedules/lib/use-schedule/useTimesForSchedule";
|
||||
import { useTimesForSchedule } from "@calcom/features/schedules/hooks/useTimesForSchedule";
|
||||
import { getRoutedTeamMemberIdsFromSearchParams } from "@calcom/lib/bookings/getRoutedTeamMemberIdsFromSearchParams";
|
||||
import { localStorage } from "@calcom/lib/webstorage";
|
||||
import { BookerLayouts } from "@calcom/prisma/zod-utils";
|
||||
|
||||
@@ -12,7 +12,7 @@ import { useBookerLayout } from "@calcom/features/bookings/Booker/hooks/useBooke
|
||||
import { useTimePreferences } from "@calcom/features/bookings/lib";
|
||||
import { LargeCalendar } from "@calcom/web/modules/calendar-view/components/LargeCalendar";
|
||||
import { getUsernameList } from "@calcom/features/eventtypes/lib/defaultEvents";
|
||||
import { useTimesForSchedule } from "@calcom/features/schedules/lib/use-schedule/useTimesForSchedule";
|
||||
import { useTimesForSchedule } from "@calcom/features/schedules/hooks/useTimesForSchedule";
|
||||
|
||||
import { formatUsername } from "../booker/BookerPlatformWrapper";
|
||||
import type {
|
||||
|
||||
Reference in new issue
Block a user