refactor: move hooks and stores from packages/features to apps/web/modules (#27221)

* refactor: move booking-audit client components from packages/features to apps/web/modules

This is part of the larger effort to move tRPC-dependent UI components from packages/features to apps/web/modules to eliminate circular dependencies.

Changes:
- Move BookingHistory.tsx and BookingHistoryPage.tsx to apps/web/modules/booking-audit/components/
- Update imports in apps/web to use the new location

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

* refactor: move formbricks client from packages/features to apps/web/modules

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

* refactor: move hooks and stores from packages/features to apps/web/modules

- Move useAppsData hook from packages/features/apps/hooks to apps/web/modules/apps/hooks
- Move onboardingStore from packages/features/ee/organizations/lib to apps/web/modules/ee/organizations/lib
- Move useWelcomeModal hook from packages/features/ee/organizations/hooks to apps/web/modules/ee/organizations/hooks
- Move useAgentsData hook from packages/features/ee/workflows/hooks to apps/web/modules/ee/workflows/hooks
- Update all import paths in consuming files

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

* refactor: move onboardingStore test file to apps/web/modules

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

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
Benny JooandDevin AI authored and GitHub committed 2026-01-26 13:11:14 +00:00
1 parent d93306e32c
commit 0774a41119
30 files changed
+31 -29

No files matched your search

@@ -3,7 +3,7 @@
import { useRouter } from "next/navigation";
import { Controller, useForm } from "react-hook-form";
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
import { useOnboarding } from "@calcom/web/modules/ee/organizations/lib/onboardingStore";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { ImageUploader } from "@calcom/ui/components/image-uploader";
import { TextAreaField } from "@calcom/ui/components/form";
@@ -3,7 +3,7 @@
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
import { useOnboarding } from "@calcom/web/modules/ee/organizations/lib/onboardingStore";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
@@ -22,7 +22,7 @@ import { Label } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { RadioAreaGroup as RadioArea } from "@calcom/ui/components/radio";
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
import { useOnboarding } from "@calcom/web/modules/ee/organizations/lib/onboardingStore";
function extractDomainFromEmail(email: string) {
const match = email.match(/^(?:.*?:\/\/)?.*?([\w-]*(?:\.\w{2,}|\.\w{2,}\.\w{2}))(?:[/?#:]|$)/);
@@ -3,7 +3,7 @@
import { useState } from "react";
import type { OrganizationRepository } from "@calcom/features/ee/organizations/di/OrganizationRepository.module";
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
import { trackFormbricksAction } from "@calcom/web/modules/formbricks/lib/trackFormbricksAction";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
@@ -8,7 +8,7 @@ import { Dialog, DialogContent } from "@calcom/ui/components/dialog";
import { Icon, type IconName } from "@calcom/ui/components/icon";
import { Logo } from "@calcom/ui/components/logo";
import { useWelcomeModal } from "@calcom/features/ee/organizations/hooks/useWelcomeModal";
import { useWelcomeModal } from "@calcom/web/modules/ee/organizations/hooks/useWelcomeModal";
const features = [
"1_parent_team_unlimited_subteams",
@@ -0,0 +1,51 @@
import { parseAsBoolean, useQueryState } from "nuqs";
import { useEffect, useState } from "react";
const STORAGE_KEY = "showNewOrgModal";
export function useWelcomeModal() {
const [newOrganizationModal, setNewOrganizationModal] = useQueryState(
"newOrganizationModal",
parseAsBoolean.withDefault(false)
);
const [isOpen, setIsOpen] = useState(false);
useEffect(() => {
// Check query param first
if (newOrganizationModal) {
setIsOpen(true);
return;
}
// Check sessionStorage as fallback (for cases where we redirect through personal onboarding)
if (typeof window !== "undefined" && sessionStorage.getItem(STORAGE_KEY) === "true") {
setIsOpen(true);
}
}, [newOrganizationModal]);
const closeModal = () => {
setIsOpen(false);
// Remove the query param from URL
setNewOrganizationModal(null);
// Also clear sessionStorage
if (typeof window !== "undefined") {
sessionStorage.removeItem(STORAGE_KEY);
}
};
return {
isOpen,
closeModal,
};
}
/**
* Helper function to set the flag that triggers the welcome modal.
* Use this before redirecting to ensure the modal shows after navigation.
*/
export function setShowNewOrgModalFlag() {
if (typeof window !== "undefined") {
sessionStorage.setItem(STORAGE_KEY, "true");
}
}
@@ -0,0 +1,394 @@
/**
* @vitest-environment jsdom
*/
// @ts-nocheck - Test file with mock type compatibility issues that don't affect test functionality
import { renderHook, act, waitFor } from "@testing-library/react";
import { useSession } from "next-auth/react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { WEBAPP_URL } from "@calcom/lib/constants";
import { UserPermissionRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { useOnboardingStore, useOnboarding } from "./onboardingStore";
// Mock all dependencies
vi.mock("next-auth/react");
vi.mock("next/navigation");
vi.mock("@calcom/trpc/react", () => ({
trpc: {
viewer: {
organizations: {
getOrganizationOnboarding: {
useQuery: vi.fn(),
},
},
},
},
}));
// Mock constants
vi.mock("@calcom/lib/constants", async () => {
const actual = await vi.importActual("@calcom/lib/constants");
return {
...actual,
IS_SELF_HOSTED: false, // Default to false, will be overridden in specific tests
};
});
function renderUseOnboardingStore() {
renderHook(() => useOnboarding(), { wrapper: createWrapper() });
return renderHook(() => useOnboardingStore(), { wrapper: createWrapper() });
}
// Test Data Builders
const createTestSession = (overrides?: {
email?: string;
role?: UserPermissionRole;
status?: "loading" | "authenticated" | "unauthenticated";
}) => {
const status = overrides?.status || "authenticated";
if (status === "loading") {
return {
data: null,
status: "loading" as const,
update: vi.fn(),
};
}
if (status === "unauthenticated") {
return {
data: null,
status: "unauthenticated" as const,
update: vi.fn(),
};
}
return {
data: {
user: {
email: overrides?.email || "[email protected]",
role: overrides?.role || UserPermissionRole.USER,
},
},
status: "authenticated" as const,
update: vi.fn(),
};
};
const createTestOrganizationOnboarding = (overrides?: {
isComplete?: boolean;
id?: string;
billingPeriod?: string;
pricePerSeat?: number;
seats?: number;
orgOwnerEmail?: string;
name?: string;
slug?: string;
bio?: string;
logo?: string;
}) => ({
id: overrides?.id || "test-onboarding-id",
isComplete: overrides?.isComplete ?? false,
billingPeriod: overrides?.billingPeriod || "MONTHLY",
pricePerSeat: overrides?.pricePerSeat ?? 20,
seats: overrides?.seats ?? 5,
orgOwnerEmail: overrides?.orgOwnerEmail || "[email protected]",
name: overrides?.name || "Test Organization",
slug: overrides?.slug || "test-org",
bio: overrides?.bio || "Test bio",
logo: overrides?.logo || "test-logo.png",
});
function mockOrganizationOnboardingFromDB(data: ReturnType<typeof createTestOrganizationOnboarding> | null) {
const organizationOnboarding = data ? createTestOrganizationOnboarding(data) : null;
(trpc.viewer.organizations.getOrganizationOnboarding.useQuery as ReturnType<typeof vi.fn>).mockReturnValue({
data: organizationOnboarding,
isPending: false,
isLoading: false,
error: null,
refetch: vi.fn(),
});
}
const createTestSearchParams = (params?: Record<string, string>) => {
return new URLSearchParams(params);
};
// Mock localStorage
const localStorageMock = {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn(),
clear: vi.fn(),
};
Object.defineProperty(window, "localStorage", {
value: localStorageMock,
writable: true,
});
// Mock implementations
const mockRouterPush = vi.fn().mockImplementation((...args: string[]) => {
console.trace();
console.log("mockRouterPush called", args[0]);
});
const mockUseSession = vi.mocked(useSession);
vi.mocked(useRouter).mockReturnValue({
push: mockRouterPush,
replace: vi.fn(),
back: vi.fn(),
forward: vi.fn(),
refresh: vi.fn(),
prefetch: vi.fn(),
});
const mockUsePathname = vi.mocked(usePathname);
const mockUseSearchParams = vi.mocked(useSearchParams);
// Test wrapper for React hooks - no wrapper needed for this test
const createWrapper = () => undefined;
describe("OnboardingStore", () => {
beforeEach(() => {
// Reset the store and let React do any side effects
act(() => {
useOnboardingStore.getState().reset();
});
// Reset localStorage mock
localStorageMock.clear.mockClear();
localStorageMock.getItem.mockClear();
localStorageMock.setItem.mockClear();
localStorageMock.removeItem.mockClear();
mockRouterPush.mockClear();
// Setup default mocks
mockUsePathname.mockReturnValue("/settings/organizations/new");
mockUseSearchParams.mockReturnValue(createTestSearchParams());
(
trpc.viewer.organizations.getOrganizationOnboarding.useQuery as ReturnType<typeof vi.fn>
).mockReturnValue({
data: undefined,
isPending: false,
isLoading: false,
error: null,
refetch: vi.fn(),
});
});
afterEach(() => {
act(() => {
useOnboardingStore.getState().reset();
});
vi.clearAllMocks();
mockRouterPush.mockClear();
localStorageMock.clear.mockClear();
localStorageMock.getItem.mockClear();
localStorageMock.setItem.mockClear();
localStorageMock.removeItem.mockClear();
});
describe("Zustand Store Actions - Complex Logic", () => {
describe("Reset Functionality", () => {
it("should reset to initial state when called without parameters", () => {
const { result } = renderHook(() => useOnboardingStore(), { wrapper: createWrapper() });
// Set some values
act(() => {
result.current.setName("Test Org");
result.current.setSlug("test-org");
result.current.setBillingPeriod("ANNUALLY" as const);
result.current.setSeats(15);
result.current.addInvitedMember({ email: "[email protected]", name: "Test User" });
});
// Reset
act(() => {
result.current.reset();
});
expect(result.current.name).toBe("");
expect(result.current.slug).toBe("");
expect(result.current.billingPeriod).toBeUndefined();
expect(result.current.seats).toBeNull();
expect(result.current.invitedMembers).toEqual([]);
});
it("should set specific state when called with parameters", () => {
const { result } = renderHook(() => useOnboardingStore(), { wrapper: createWrapper() });
const newState = {
name: "Partial Reset Org",
slug: "partial-reset",
seats: 25,
};
act(() => {
result.current.reset(newState);
});
expect(result.current.name).toBe("Partial Reset Org");
expect(result.current.slug).toBe("partial-reset");
expect(result.current.seats).toBe(25);
});
it("should clear localStorage when resetting without parameters", () => {
const { result } = renderHook(() => useOnboardingStore(), { wrapper: createWrapper() });
// Set some values to trigger localStorage save
act(() => {
result.current.setName("Test Org");
});
// Reset
act(() => {
result.current.reset();
});
// Verify localStorage removeItem was called
expect(localStorageMock.removeItem).toHaveBeenCalledWith("org-creation-onboarding");
});
});
});
describe("useOnboarding Hook", () => {
beforeEach(() => {
mockUseSession.mockReturnValue(createTestSession());
});
describe("Authentication Handling", () => {
it("should redirect to login when session is unauthenticated", async () => {
mockUseSession.mockReturnValue(createTestSession({ status: "unauthenticated" }));
mockUsePathname.mockReturnValue("/settings/organizations/new");
mockUseSearchParams.mockReturnValue(createTestSearchParams());
renderHook(() => useOnboarding(), { wrapper: createWrapper() });
await waitFor(() => {
expect(mockRouterPush).toHaveBeenCalledWith(
`/auth/login?callbackUrl=${WEBAPP_URL}/settings/organizations/new`
);
});
mockRouterPush.mockClear();
expect(mockRouterPush).not.toHaveBeenCalled();
});
it("should not redirect when session is authenticated", () => {
expect(mockRouterPush).not.toHaveBeenCalled();
mockUseSession.mockReturnValue(createTestSession({ status: "authenticated" }));
renderHook(() => useOnboarding(), { wrapper: createWrapper() });
expect(mockRouterPush).not.toHaveBeenCalled();
});
});
describe("Organization Onboarding State Sync", () => {
it("should return organization onboarding data when available", () => {
const organizationOnboarding = createTestOrganizationOnboarding({
name: "Test Org",
slug: "test-org",
});
(
trpc.viewer.organizations.getOrganizationOnboarding.useQuery as ReturnType<typeof vi.fn>
).mockReturnValue({
data: organizationOnboarding,
isPending: false,
isLoading: false,
error: null,
refetch: vi.fn(),
});
const { result } = renderHook(() => useOnboarding(), { wrapper: createWrapper() });
expect(result.current.dbOnboarding).toEqual(organizationOnboarding);
expect(result.current.isLoadingOrgOnboarding).toBe(false);
});
it("should set onboardingData from DB to zustand if not set already", async () => {
const organizationOnboarding = createTestOrganizationOnboarding({
id: "sync-test-id",
name: "Synced Organization",
slug: "synced-org",
bio: "Synced bio content",
logo: "synced-logo.png",
billingPeriod: "ANNUALLY",
pricePerSeat: 25,
seats: 10,
orgOwnerEmail: "[email protected]",
});
(
trpc.viewer.organizations.getOrganizationOnboarding.useQuery as ReturnType<typeof vi.fn>
).mockReturnValue({
data: organizationOnboarding,
isPending: false,
isLoading: false,
error: null,
refetch: vi.fn(),
});
renderHook(() => useOnboarding(), { wrapper: createWrapper() });
const { result: storeResult } = renderHook(() => useOnboardingStore(), { wrapper: createWrapper() });
await waitFor(() => {
expect(storeResult.current.onboardingId).toBe("sync-test-id");
});
expect(storeResult.current.name).toBe("Synced Organization");
expect(storeResult.current.slug).toBe("synced-org");
expect(storeResult.current.bio).toBe("Synced bio content");
expect(storeResult.current.logo).toBe("synced-logo.png");
expect(storeResult.current.billingPeriod).toBe("ANNUALLY");
expect(storeResult.current.pricePerSeat).toBe(25);
expect(storeResult.current.seats).toBe(10);
expect(storeResult.current.orgOwnerEmail).toBe("[email protected]");
});
it("should sync onboardingData from DB to zustand if set already", async () => {
mockOrganizationOnboardingFromDB(
createTestOrganizationOnboarding({
id: "onboarding1",
name: "Onboarding 1 Organization",
slug: "onboarding1-org",
bio: "Onboarding 1 bio content",
logo: "onboarding1-logo.png",
billingPeriod: "MONTHLY",
pricePerSeat: 15,
seats: 5,
orgOwnerEmail: "[email protected]",
})
);
// Load the store to set the initial state
const { result: storeResultBefore } = renderUseOnboardingStore();
expect(storeResultBefore.current.name).toBe("Onboarding 1 Organization");
expect(storeResultBefore.current.slug).toBe("onboarding1-org");
mockOrganizationOnboardingFromDB(
createTestOrganizationOnboarding({
id: "sync-test-id",
name: "Synced Organization",
slug: "synced-org",
bio: "Synced bio content",
logo: "synced-logo.png",
billingPeriod: "ANNUALLY",
pricePerSeat: 25,
seats: 10,
orgOwnerEmail: "[email protected]",
})
);
// Load the store to sync the new data
const { result: storeResultAfter } = renderUseOnboardingStore();
// Verify the data is synced
expect(storeResultAfter.current.name).toBe("Synced Organization");
expect(storeResultAfter.current.slug).toBe("synced-org");
});
});
});
});
@@ -0,0 +1,191 @@
import { useSession } from "next-auth/react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { useEffect } from "react";
import { create } from "zustand";
import { persist, StorageValue } from "zustand/middleware";
import { WEBAPP_URL, IS_TEAM_BILLING_ENABLED_CLIENT } from "@calcom/lib/constants";
import { localStorage } from "@calcom/lib/webstorage";
import { BillingPeriod, UserPermissionRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
interface OnboardingAdminStoreState {
billingPeriod?: BillingPeriod;
pricePerSeat?: number | null;
seats?: number | null;
orgOwnerEmail?: string;
}
interface OnboardingUserStoreState {
name: string;
slug: string;
logo?: string | null;
bio?: string | null;
brandColor?: string | null;
bannerUrl?: string | null;
onboardingId: string | null;
invitedMembers: { email: string; name?: string }[];
teams: { id: number; name: string; slug: string | null; isBeingMigrated: boolean }[];
}
interface OnboardingStoreState extends OnboardingAdminStoreState, OnboardingUserStoreState {
// Actions for admin state
setBillingPeriod: (billingPeriod: BillingPeriod) => void;
setPricePerSeat: (price: number | null) => void;
setSeats: (seats: number | null) => void;
setOrgOwnerEmail: (email: string) => void;
// Actions for user state
setName: (name: string) => void;
setSlug: (slug: string) => void;
setLogo: (logo: string) => void;
setBio: (bio: string) => void;
setBrandColor: (brandColor: string) => void;
setBannerUrl: (bannerUrl: string) => void;
addInvitedMember: (member: { email: string; name?: string }) => void;
removeInvitedMember: (email: string) => void;
setOnboardingId: (onboardingId: string) => void;
// Actions for team state
setTeams: (teams: { id: number; name: string; slug: string | null; isBeingMigrated: boolean }[]) => void;
// Reset state
reset: (state?: Partial<OnboardingStoreState>) => void;
}
const initialState: OnboardingAdminStoreState & OnboardingUserStoreState = {
// User state
name: "",
slug: "",
logo: "",
bio: "",
brandColor: "",
bannerUrl: "",
orgOwnerEmail: "",
seats: null,
pricePerSeat: null,
billingPeriod: undefined,
onboardingId: null,
invitedMembers: [],
teams: [],
};
export const useOnboardingStore = create<OnboardingStoreState>()(
persist(
(set, get) => ({
...initialState,
// Admin actions
setBillingPeriod: (billingPeriod) => set({ billingPeriod }),
setPricePerSeat: (pricePerSeat) => set({ pricePerSeat }),
setSeats: (seats) => set({ seats }),
setOrgOwnerEmail: (orgOwnerEmail) => set({ orgOwnerEmail }),
// User actions
setName: (name) => set({ name }),
setSlug: (slug) => set({ slug }),
setLogo: (logo) => set({ logo }),
setBio: (bio) => set({ bio }),
setBrandColor: (brandColor) => set({ brandColor }),
setBannerUrl: (bannerUrl) => set({ bannerUrl }),
setOnboardingId: (onboardingId) => set({ onboardingId }),
addInvitedMember: (member) =>
set((state) => ({
invitedMembers: [...state.invitedMembers, member],
})),
removeInvitedMember: (email) =>
set((state) => ({
invitedMembers: state.invitedMembers.filter((member) => member.email !== email),
})),
// Team actions
setTeams: (teams) => set({ teams }),
reset: (state) => {
if (state) {
set(state);
} else {
// Clear the localStorage entry for this store
if (typeof window !== "undefined") {
localStorage.removeItem("org-creation-onboarding");
}
set(initialState);
}
},
}),
{
name: "org-creation-onboarding",
}
)
);
export const useOnboarding = () => {
const session = useSession();
const router = useRouter();
const path = usePathname();
const isAdmin = session.data?.user?.role === UserPermissionRole.ADMIN;
const isBillingEnabled = process.env.NEXT_PUBLIC_IS_E2E ? false : IS_TEAM_BILLING_ENABLED_CLIENT;
const searchParams = useSearchParams();
const { data: organizationOnboarding, isPending: isLoadingOrgOnboarding } =
trpc.viewer.organizations.getOrganizationOnboarding.useQuery();
const { reset } = useOnboardingStore();
useEffect(() => {
if (isLoadingOrgOnboarding) {
return;
}
// Admin on handover page should never touch the store
// The DB query returns admin's own onboarding, not the one being handed over
if (isAdmin && path?.includes("/handover")) {
return;
}
if (organizationOnboarding?.isComplete) {
reset();
}
if (organizationOnboarding) {
// Admin creating for someone else - don't sync from DB, let them proceed to handover
if (isAdmin && organizationOnboarding?.orgOwnerEmail !== session.data?.user.email) {
return;
}
// Always sync from DB to ensure UI reflects latest changes
reset({
onboardingId: organizationOnboarding.id,
billingPeriod: organizationOnboarding.billingPeriod as BillingPeriod,
pricePerSeat: organizationOnboarding.pricePerSeat,
seats: organizationOnboarding.seats,
orgOwnerEmail: organizationOnboarding.orgOwnerEmail,
name: organizationOnboarding.name,
slug: organizationOnboarding.slug,
bio: organizationOnboarding.bio,
logo: organizationOnboarding.logo,
brandColor: organizationOnboarding.brandColor,
bannerUrl: organizationOnboarding.bannerUrl,
invitedMembers: [],
teams: [],
});
}
// Note: We no longer redirect if onboardingId is missing, as regular users
// don't create the onboarding record until the final step
}, [organizationOnboarding, isLoadingOrgOnboarding, isAdmin, reset, path]);
useEffect(() => {
if (session.status === "loading") {
return;
}
if (!session.data) {
const searchString = !searchParams ? "" : `${searchParams.toString()}`;
router.push(`/auth/login?callbackUrl=${WEBAPP_URL}${path}${searchString ? `?${searchString}` : ""}`);
}
}, [session, router, path, searchParams]);
return {
useOnboardingStore,
isLoadingOrgOnboarding,
dbOnboarding: organizationOnboarding,
isBillingEnabled,
};
};
@@ -5,7 +5,7 @@ import { useState } from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { z } from "zod";
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
import { useOnboarding } from "@calcom/web/modules/ee/organizations/lib/onboardingStore";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import slugify from "@calcom/lib/slugify";
import { trpc } from "@calcom/trpc/react";
@@ -5,8 +5,8 @@ import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { setShowNewOrgModalFlag } from "@calcom/features/ee/organizations/hooks/useWelcomeModal";
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
import { setShowNewOrgModalFlag } from "@calcom/web/modules/ee/organizations/hooks/useWelcomeModal";
import { useOnboarding } from "@calcom/web/modules/ee/organizations/lib/onboardingStore";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
@@ -3,7 +3,7 @@
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
import { useOnboarding } from "@calcom/web/modules/ee/organizations/lib/onboardingStore";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { trpc } from "@calcom/trpc/react";
import { Button } from "@calcom/ui/components/button";
@@ -3,7 +3,7 @@
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { useOnboarding } from "@calcom/features/ee/organizations/lib/onboardingStore";
import { useOnboarding } from "@calcom/web/modules/ee/organizations/lib/onboardingStore";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Alert } from "@calcom/ui/components/alert";
import { SkeletonContainer, SkeletonText } from "@calcom/ui/components/skeleton";
@@ -9,7 +9,7 @@ import { z } from "zod";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
import { trackFormbricksAction } from "@calcom/web/modules/formbricks/lib/trackFormbricksAction";
import { IS_TEAM_BILLING_ENABLED_CLIENT, WEBAPP_URL } from "@calcom/lib/constants";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
import { useLocale } from "@calcom/lib/hooks/useLocale";
@@ -1,6 +1,6 @@
import { useState } from "react";
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
import { trackFormbricksAction } from "@calcom/web/modules/formbricks/lib/trackFormbricksAction";
import type { MembershipRole } from "@calcom/prisma/enums";
import { trpc } from "@calcom/trpc/react";
import { showToast } from "@calcom/ui/components/toast";
@@ -1,6 +1,6 @@
import { useState } from "react";
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
import { trackFormbricksAction } from "@calcom/web/modules/formbricks/lib/trackFormbricksAction";
import {
ORG_SELF_SERVE_ENABLED,
ORG_MINIMUM_PUBLISHED_TEAMS_SELF_SERVE_HELPER_DIALOGUE,
@@ -11,7 +11,7 @@ import { z } from "zod";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import { getTeamUrlSync } from "@calcom/features/ee/organizations/lib/getTeamUrlSync";
import { trackFormbricksAction } from "@calcom/features/formbricks/formbricks-client";
import { trackFormbricksAction } from "@calcom/web/modules/formbricks/lib/trackFormbricksAction";
import SectionBottomActions from "@calcom/features/settings/SectionBottomActions";
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
import { getPlaceholderAvatar } from "@calcom/lib/defaultAvatarImage";
@@ -3,7 +3,7 @@ import type { Dispatch, SetStateAction } from "react";
import { useState, useEffect } from "react";
import type { UseFormReturn } from "react-hook-form";
import { useAgentsData } from "@calcom/features/ee/workflows/hooks/useAgentsData";
import { useAgentsData } from "@calcom/web/modules/ee/workflows/hooks/useAgentsData";
import {
isCalAIAction,
isSMSAction,
@@ -0,0 +1,106 @@
import { useMemo } from "react";
import type { UseFormReturn } from "react-hook-form";
import { useWatch } from "react-hook-form";
import type { FormValues } from "@calcom/features/ee/workflows/lib/types";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
type AgentData = RouterOutputs["viewer"]["aiVoiceAgent"]["get"];
interface AgentQuery {
data: AgentData | undefined;
isPending: boolean;
isLoading: boolean;
error: Error | null;
}
interface UseAgentsDataReturn {
outboundAgentQueries: AgentQuery[];
inboundAgentQueries: AgentQuery[];
}
const emptyQuery: AgentQuery = { data: undefined, isPending: false, isLoading: false, error: null };
/**
* Custom hook to fetch and manage agent data for workflow steps.
*
* @param form - React Hook Form instance for workflow form values
* @returns Object containing outbound and inbound agent queries with proper typing
*/
export function useAgentsData(form: UseFormReturn<FormValues>): UseAgentsDataReturn {
const watchedSteps = useWatch({
control: form.control,
name: "steps",
});
const allAgentIds = useMemo(() => {
const outboundAgentIds = (watchedSteps || []).map((step) => step?.agentId || null);
const inboundAgentIds = (watchedSteps || []).map((step) => step?.inboundAgentId || null);
return { outboundAgentIds, inboundAgentIds };
}, [watchedSteps]);
const uniqueAgentIds = useMemo((): string[] => {
const allIds = [...allAgentIds.outboundAgentIds, ...allAgentIds.inboundAgentIds];
const validIds: string[] = [];
for (const id of allIds) {
if (id && typeof id === "string") {
validIds.push(id);
}
}
return Array.from(new Set(validIds));
}, [allAgentIds]);
const uniqueAgentQueries = trpc.useQueries((t) =>
uniqueAgentIds.map((agentId) => {
return t.viewer.aiVoiceAgent.get(
{ id: agentId },
{
enabled: true,
staleTime: 5 * 60 * 1000,
}
);
})
);
const agentDataMap = useMemo(() => {
const map = new Map<string, AgentQuery>();
uniqueAgentIds.forEach((agentId, index) => {
const query = uniqueAgentQueries[index];
if (query) {
map.set(agentId, {
data: query.data,
isPending: query.isPending,
isLoading: query.isLoading,
error: query.error,
});
}
});
return map;
}, [uniqueAgentIds, uniqueAgentQueries]);
const outboundAgentQueries = useMemo((): AgentQuery[] => {
return allAgentIds.outboundAgentIds.map((agentId) => {
if (!agentId) {
return emptyQuery;
}
return agentDataMap.get(agentId) || emptyQuery;
});
}, [allAgentIds.outboundAgentIds, agentDataMap]);
const inboundAgentQueries = useMemo((): AgentQuery[] => {
return allAgentIds.inboundAgentIds.map((agentId) => {
if (!agentId) {
return emptyQuery;
}
return agentDataMap.get(agentId) || emptyQuery;
});
}, [allAgentIds.inboundAgentIds, agentDataMap]);
return {
outboundAgentQueries,
inboundAgentQueries,
};
}