fix: extract trpc and react-awesome-query-builder from atoms (#17801)

* wip

* fix: externalize react-awesome-query-builder

* fix: move useSession to webWrapper

* fixup! Merge branch 'main' into fix-platform-event-types-segment

* fixup! fixup! Merge branch 'main' into fix-platform-event-types-segment

* fixup! fixup! fixup! Merge branch 'main' into fix-platform-event-types-segment

* fixup! fixup! fixup! fixup! Merge branch 'main' into fix-platform-event-types-segment
This commit is contained in:
Morgan authored and GitHub committed 2024-11-23 12:29:16 +00:00
1 parent 9bb66035c8
commit c2a3d8b8df
16 files changed
+97 -37

No files matched your search

+179
View File
@@ -0,0 +1,179 @@
import { render, screen, waitFor } from "@testing-library/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";
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,
options: [
{ id: "1", value: "Sales", slug: "sales" },
{ id: "2", value: "Engineering", slug: "engineering" },
],
},
],
isPending: false,
});
};
// Mock the TRPC hooks
vi.mock("@calcom/trpc", () => ({
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 defaultProps = {
teamId: 1,
queryValue: null as AttributesQueryValue | null,
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.queryByText("loading")).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.getByText("loading")).toBeInTheDocument();
});
});
it("shows matching team members when query value is provided", async () => {
mockGetMatchingTeamMembers({
isPending: false,
data: {
mainWarnings: null,
fallbackWarnings: null,
troubleshooter: undefined,
result: [
{
id: 1,
name: "John Doe",
email: "[email protected]",
},
],
},
});
const queryValue = {
id: "root",
type: "group",
} as AttributesQueryValue;
render(<Segment {...defaultProps} queryValue={queryValue} />);
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();
});
});
});
+175
View File
@@ -0,0 +1,175 @@
"use client";
import { useCallback, useState } from "react";
import { Query, Builder, Utils as QbUtils } from "react-awesome-query-builder";
import type { ImmutableTree, BuilderProps } from "react-awesome-query-builder";
import type { JsonTree } from "react-awesome-query-builder";
import {
withRaqbSettingsAndWidgets,
ConfigFor,
} from "@calcom/app-store/routing-forms/components/react-awesome-query-builder/config/uiConfig";
import { getQueryBuilderConfigForAttributes } from "@calcom/app-store/routing-forms/lib/getQueryBuilderConfig";
import { classNames as cn } from "@calcom/lib";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { isEqual } from "@calcom/lib/isEqual";
import { buildStateFromQueryValue } from "@calcom/lib/raqb/raqbUtils";
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
import { trpc, type RouterOutputs } from "@calcom/trpc";
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,
}: {
attributes: Attributes;
teamId: number;
queryValue: AttributesQueryValue | null;
onQueryValueChange: ({ queryValue }: { queryValue: AttributesQueryValue }) => void;
className?: string;
}) {
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} />
</div>
</div>
);
}
function MatchingTeamMembers({
teamId,
queryValue,
}: {
teamId: number;
queryValue: AttributesQueryValue | null;
}) {
const { t } = useLocale();
const { data: matchingTeamMembersWithResult, isPending } =
trpc.viewer.attributes.findTeamMembersMatchingAttributeLogic.useQuery({
teamId,
attributesQueryValue: queryValue,
_enablePerf: true,
});
if (isPending) return <span>{t("loading")}</span>;
if (!matchingTeamMembersWithResult) return <span>{t("something_went_wrong")}</span>;
const { result: matchingTeamMembers } = matchingTeamMembersWithResult;
if (!matchingTeamMembers || !queryValue) {
return (
<div className="border-subtle bg-muted mt-4 space-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>
);
}
return (
<div className="border-subtle bg-muted mt-4 space-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 })}</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,
}: {
teamId: number;
queryValue: AttributesQueryValue | null;
onQueryValueChange: ({ queryValue }: { queryValue: AttributesQueryValue }) => void;
className?: string;
}) {
const { attributes, isPending } = useAttributes(teamId);
const { t } = useLocale();
if (isPending) return <span>Loading...</span>;
if (!attributes) {
console.log("Error fetching attributes");
return <span>{t("something_went_wrong")}</span>;
}
return (
<SegmentWithAttributes
teamId={teamId}
attributes={attributes}
queryValue={queryValue}
onQueryValueChange={onQueryValueChange}
className={className}
/>
);
}
@@ -1,15 +1,19 @@
import type { ComponentProps, Dispatch, SetStateAction } from "react";
import { useMemo, type ComponentProps, type Dispatch, type SetStateAction } from "react";
import { useFormContext } from "react-hook-form";
import { Controller } from "react-hook-form";
import type { Options } from "react-select";
import {
useIsPlatform,
AddMembersWithSwitchWebWrapper,
AddMembersWithSwitchPlatformWrapper,
} from "@calcom/atoms/monorepo";
import { Segment } from "@calcom/features/Segment";
import type { FormValues, Host, TeamMember } from "@calcom/features/eventtypes/lib/types";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { AttributesQueryValue } from "@calcom/lib/raqb/types";
import { trpc } from "@calcom/trpc";
import { Label, SettingsToggle } from "@calcom/ui";
import { Segment } from "../../../../apps/web/components/Segment";
import AssignAllTeamMembers from "./AssignAllTeamMembers";
import CheckedTeamSelect from "./CheckedTeamSelect";
import type { CheckedSelectOption } from "./CheckedTeamSelect";
@@ -122,7 +126,7 @@ function MembersSegmentWithToggle({
const onQueryValueChange = ({ queryValue }: { queryValue: AttributesQueryValue }) => {
setRrSegmentQueryValue(queryValue);
};
const isPlatform = useIsPlatform();
return (
<Controller<FormValues>
name="assignRRMembersUsingSegment"
@@ -136,19 +140,21 @@ function MembersSegmentWithToggle({
onCheckedChange={(active) => {
setAssignRRMembersUsingSegment(active);
}}>
<Segment
teamId={teamId}
queryValue={rrSegmentQueryValue}
onQueryValueChange={onQueryValueChange}
className={className}
/>
{!isPlatform && (
<Segment
teamId={teamId}
queryValue={rrSegmentQueryValue}
onQueryValueChange={onQueryValueChange}
className={className}
/>
)}
</SettingsToggle>
)}
/>
);
}
type AddMembersWithSwitchProps = {
export type AddMembersWithSwitchProps = {
teamMembers: TeamMember[];
value: Host[];
onChange: (hosts: Host[]) => void;
@@ -213,7 +219,7 @@ function useSegmentState() {
};
}
function AddMembersWithSwitch({
export function AddMembersWithSwitch({
teamMembers,
value,
onChange,
@@ -243,11 +249,6 @@ function AddMembersWithSwitch({
isAssigningAllTeamMembersApplicable: automaticAddAllEnabled,
isSegmentApplicable,
});
const utils = trpc.useUtils();
utils.viewer.appRoutingForms.getAttributesForTeam.prefetch({
teamId,
});
const onAssignAllTeamMembersInactive = () => {
setAssignRRMembersUsingSegment(false);
@@ -318,10 +319,15 @@ const AddMembersWithSwitchWrapper = ({
}: AddMembersWithSwitchProps & {
containerClassName?: string;
}) => {
const isPlatform = useIsPlatform();
const AddMembersWithSwitchWrapped = useMemo(
() => (isPlatform ? AddMembersWithSwitchPlatformWrapper : AddMembersWithSwitchWebWrapper),
[isPlatform]
);
return (
<div className="rounded-md ">
<div className={`flex flex-col rounded-md pb-2 pt-6 ${containerClassName}`}>
<AddMembersWithSwitch {...props} />
<AddMembersWithSwitchWrapped {...props} />
</div>
</div>
);
@@ -1,3 +1,5 @@
"use client";
import { useAutoAnimate } from "@formkit/auto-animate/react";
import { useState } from "react";
import type { Props } from "react-select";
@@ -4,7 +4,8 @@ import { FormProvider, useForm } from "react-hook-form";
import { describe, expect, it, vi } from "vitest";
import type { Host, TeamMember } from "../../lib/types";
import AddMembersWithSwitch from "../AddMembersWithSwitch";
import type { AddMembersWithSwitchProps } from "../AddMembersWithSwitch";
import { AddMembersWithSwitch } from "../AddMembersWithSwitch";
// Mock matchMedia
vi.mock("@formkit/auto-animate/react", () => ({
@@ -12,7 +13,7 @@ vi.mock("@formkit/auto-animate/react", () => ({
}));
// Mock Segment component
vi.mock("@calcom/web/components/Segment", () => ({
vi.mock("@calcom/features/Segment", () => ({
Segment: vi.fn().mockImplementation(({ onQueryValueChange }) => (
<div data-testid="mock-segment">
<button onClick={() => onQueryValueChange({ queryValue: { id: "test" } })}>Update Query</button>
@@ -60,7 +61,7 @@ const renderComponent = ({
hosts: [],
},
}: {
componentProps: Parameters<typeof AddMembersWithSwitch>[0];
componentProps: AddMembersWithSwitchProps;
formDefaultValues?: Record<string, unknown>;
}) => {
const Wrapper = ({ children }: { children: React.ReactNode }) => {
@@ -26,6 +26,7 @@ export type EventTeamAssignmentTabBaseProps = Pick<
"teamMembers" | "team" | "eventType"
> & {
orgId: number | null;
isSegmentApplicable: boolean;
};
export const mapMemberToChildrenOption = (
@@ -227,6 +228,7 @@ const RoundRobinHosts = ({
assignAllTeamMembers,
setAssignAllTeamMembers,
teamId,
isSegmentApplicable,
}: {
orgId: number | null;
value: Host[];
@@ -235,6 +237,7 @@ const RoundRobinHosts = ({
assignAllTeamMembers: boolean;
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
teamId: number;
isSegmentApplicable: boolean;
}) => {
const { t } = useLocale();
@@ -278,7 +281,7 @@ const RoundRobinHosts = ({
onChange={onChange}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
isSegmentApplicable={!!orgId}
isSegmentApplicable={isSegmentApplicable}
automaticAddAllEnabled={true}
isRRWeightsEnabled={isRRWeightsEnabled}
isFixed={false}
@@ -347,12 +350,14 @@ const Hosts = ({
teamMembers,
assignAllTeamMembers,
setAssignAllTeamMembers,
isSegmentApplicable,
}: {
orgId: number | null;
teamId: number;
teamMembers: TeamMember[];
assignAllTeamMembers: boolean;
setAssignAllTeamMembers: Dispatch<SetStateAction<boolean>>;
isSegmentApplicable: boolean;
}) => {
const {
control,
@@ -439,6 +444,7 @@ const Hosts = ({
}}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
isSegmentApplicable={isSegmentApplicable}
/>
</>
),
@@ -455,6 +461,7 @@ export const EventTeamAssignmentTab = ({
teamMembers,
eventType,
orgId,
isSegmentApplicable,
}: EventTeamAssignmentTabBaseProps) => {
const { t } = useLocale();
@@ -572,6 +579,7 @@ export const EventTeamAssignmentTab = ({
</div>
<Hosts
orgId={orgId}
isSegmentApplicable={isSegmentApplicable}
teamId={team.id}
assignAllTeamMembers={assignAllTeamMembers}
setAssignAllTeamMembers={setAssignAllTeamMembers}
@@ -1,4 +1,3 @@
import { useSession } from "next-auth/react";
import { useState } from "react";
import { Controller, useFormContext } from "react-hook-form";
import type { UseFormGetValues, UseFormSetValue, Control, FormState } from "react-hook-form";
@@ -19,12 +18,13 @@ export type EventSetupTabProps = Pick<
EventTypeSetupProps,
"eventType" | "locationOptions" | "team" | "teamMembers" | "destinationCalendar"
>;
export const EventSetupTab = (props: EventSetupTabProps & { urlPrefix: string; hasOrgBranding: boolean }) => {
export const EventSetupTab = (
props: EventSetupTabProps & { urlPrefix: string; hasOrgBranding: boolean; orgId?: number }
) => {
const { t } = useLocale();
const session = useSession();
const isPlatform = useIsPlatform();
const formMethods = useFormContext<FormValues>();
const { eventType, team, urlPrefix, hasOrgBranding } = props;
const { eventType, team, urlPrefix, hasOrgBranding, orgId } = props;
const [multipleDuration, setMultipleDuration] = useState(
formMethods.getValues("metadata")?.multipleDuration
);
@@ -105,8 +105,8 @@ export const EventSetupTab = (props: EventSetupTabProps & { urlPrefix: string; h
onCheckedChange={(value) => {
formMethods.setValue("autoTranslateDescriptionEnabled", value, { shouldDirty: true });
}}
disabled={!session.data?.user.org?.id}
tooltip={!session.data?.user.org?.id ? t("orgs_upgrade_to_enable_feature") : undefined}
disabled={!orgId}
tooltip={!orgId ? t("orgs_upgrade_to_enable_feature") : undefined}
/>
</div>
<TextField