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:
1 parent
d93306e32c
commit
0774a41119
30 files changed
+31
-29
No files matched your search
@@ -1,58 +0,0 @@
|
||||
import { useFormContext } from "react-hook-form";
|
||||
|
||||
import type { GetAppData, SetAppData } from "@calcom/app-store/EventTypeAppContext";
|
||||
import type { EventTypeAppsList } from "@calcom/app-store/utils";
|
||||
import type { FormValues } from "@calcom/features/eventtypes/lib/types";
|
||||
|
||||
const useAppsData = () => {
|
||||
const formMethods = useFormContext<FormValues>();
|
||||
const allAppsData = formMethods.watch("metadata")?.apps || {};
|
||||
|
||||
const setAllAppsData = (_allAppsData: typeof allAppsData) => {
|
||||
formMethods.setValue(
|
||||
"metadata",
|
||||
{
|
||||
...formMethods.getValues("metadata"),
|
||||
apps: _allAppsData,
|
||||
},
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
};
|
||||
|
||||
const getAppDataGetter = (appId: EventTypeAppsList): GetAppData => {
|
||||
return function (key) {
|
||||
const appData = allAppsData[appId as keyof typeof allAppsData] || {};
|
||||
if (key) {
|
||||
return appData[key as keyof typeof appData];
|
||||
}
|
||||
return appData;
|
||||
};
|
||||
};
|
||||
|
||||
const eventTypeFormMetadata = formMethods.getValues("metadata");
|
||||
|
||||
const getAppDataSetter = (
|
||||
appId: EventTypeAppsList,
|
||||
appCategories: string[],
|
||||
credentialId?: number
|
||||
): SetAppData => {
|
||||
return function (key, value) {
|
||||
// Always get latest data available in Form because consequent calls to setData would update the Form but not allAppsData(it would update during next render)
|
||||
const allAppsDataFromForm = formMethods.getValues("metadata")?.apps || {};
|
||||
const appData = allAppsDataFromForm[appId];
|
||||
setAllAppsData({
|
||||
...allAppsDataFromForm,
|
||||
[appId]: {
|
||||
...appData,
|
||||
[key]: value,
|
||||
credentialId,
|
||||
appCategories,
|
||||
},
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
return { getAppDataGetter, getAppDataSetter, eventTypeFormMetadata };
|
||||
};
|
||||
|
||||
export default useAppsData;
|
||||
@@ -1,427 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import dayjs from "@calcom/dayjs";
|
||||
import type { AuditActorType } from "@calcom/features/booking-audit/lib/repository/IAuditActorRepository";
|
||||
import ServerTrans from "@calcom/lib/components/ServerTrans";
|
||||
import { useLocale } from "@calcom/lib/hooks/useLocale";
|
||||
import { trpc } from "@calcom/trpc/react";
|
||||
import { Avatar } from "@calcom/ui/components/avatar";
|
||||
import { Button } from "@calcom/ui/components/button";
|
||||
import { FilterSearchField, Select } from "@calcom/ui/components/form";
|
||||
import { Icon, type IconName } from "@calcom/ui/components/icon";
|
||||
import { SkeletonText } from "@calcom/ui/components/skeleton";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
|
||||
interface BookingHistoryProps {
|
||||
bookingUid: string;
|
||||
}
|
||||
|
||||
type TranslationComponent = {
|
||||
type: "link";
|
||||
href: string;
|
||||
};
|
||||
|
||||
type TranslationWithParams = {
|
||||
key: string;
|
||||
params?: Record<string, string | number>;
|
||||
components?: TranslationComponent[];
|
||||
};
|
||||
|
||||
type AuditLog = {
|
||||
id: string;
|
||||
action: string;
|
||||
type: string;
|
||||
timestamp: string;
|
||||
source: string;
|
||||
displayJson?: Record<string, unknown> | null;
|
||||
actionDisplayTitle: TranslationWithParams;
|
||||
displayFields?: Array<{ labelKey: string; valueKey: string }> | null;
|
||||
actor: {
|
||||
type: AuditActorType;
|
||||
displayName: string | null;
|
||||
displayEmail: string | null;
|
||||
displayAvatar: string | null;
|
||||
};
|
||||
impersonatedBy?: {
|
||||
displayName: string;
|
||||
displayEmail: string | null;
|
||||
displayAvatar: string | null;
|
||||
} | null;
|
||||
hasError?: boolean;
|
||||
};
|
||||
|
||||
interface BookingLogsFiltersProps {
|
||||
searchTerm: string;
|
||||
onSearchChange: (value: string) => void;
|
||||
actorFilter: string | null;
|
||||
onActorFilterChange: (value: string | null) => void;
|
||||
actorOptions: Array<{ label: string; value: string }>;
|
||||
}
|
||||
|
||||
interface BookingLogsTimelineProps {
|
||||
logs: AuditLog[];
|
||||
}
|
||||
|
||||
const ACTION_ICON_MAP: Record<string, IconName> = {
|
||||
CREATED: "calendar",
|
||||
CANCELLED: "ban",
|
||||
REJECTED: "ban",
|
||||
ACCEPTED: "check",
|
||||
RESCHEDULED: "pencil",
|
||||
RESCHEDULE_REQUESTED: "pencil",
|
||||
REASSIGNMENT: "user-check",
|
||||
ATTENDEE_ADDED: "user-check",
|
||||
ATTENDEE_REMOVED: "user-check",
|
||||
LOCATION_CHANGED: "map-pin",
|
||||
HOST_NO_SHOW_UPDATED: "ban",
|
||||
ATTENDEE_NO_SHOW_UPDATED: "ban",
|
||||
} as const;
|
||||
|
||||
const ACTOR_ROLE_LABEL_MAP: Record<AuditActorType, string | null> = {
|
||||
GUEST: "guest",
|
||||
ATTENDEE: "attendee",
|
||||
SYSTEM: null,
|
||||
USER: null,
|
||||
APP: null,
|
||||
} as const;
|
||||
|
||||
function BookingLogsFilters({
|
||||
searchTerm,
|
||||
onSearchChange,
|
||||
actorFilter,
|
||||
onActorFilterChange,
|
||||
actorOptions,
|
||||
}: BookingLogsFiltersProps) {
|
||||
const { t } = useLocale();
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 items-start">
|
||||
<div className="flex-1 min-w-[200px]">
|
||||
<FilterSearchField
|
||||
size="sm"
|
||||
value={searchTerm}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
containerClassName=""
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-w-[140px]">
|
||||
<Select
|
||||
size="sm"
|
||||
value={
|
||||
actorFilter
|
||||
? { label: `${t("actor")}: ${actorFilter}`, value: actorFilter }
|
||||
: { label: `${t("actor")}: ${t("all")}`, value: "" }
|
||||
}
|
||||
onChange={(option) => {
|
||||
if (!option) return;
|
||||
onActorFilterChange(option.value || null);
|
||||
}}
|
||||
options={[{ label: t("all"), value: "" }, ...actorOptions]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the action display title with support for Trans component interpolation
|
||||
* Handles translations with embedded components (e.g., links) for proper i18n support
|
||||
*/
|
||||
function ActionTitle({ actionDisplayTitle }: { actionDisplayTitle: TranslationWithParams }) {
|
||||
const { t } = useLocale();
|
||||
|
||||
if (actionDisplayTitle.components?.length) {
|
||||
return (
|
||||
<ServerTrans
|
||||
t={t}
|
||||
i18nKey={actionDisplayTitle.key}
|
||||
values={actionDisplayTitle.params}
|
||||
components={actionDisplayTitle.components.map((comp) =>
|
||||
comp.type === "link" ? (
|
||||
<Link key={comp.href} href={comp.href} className="text-emphasis underline hover:no-underline" />
|
||||
) : (
|
||||
<span key={comp.href} />
|
||||
)
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <>{t(actionDisplayTitle.key, actionDisplayTitle.params)}</>;
|
||||
}
|
||||
|
||||
interface JsonViewerProps {
|
||||
data: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
function JsonViewer({ data }: JsonViewerProps) {
|
||||
if (!data || Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const jsonString = JSON.stringify(data, null, 2);
|
||||
const lines = jsonString.split("\n");
|
||||
const lineCount = lines.length;
|
||||
const lineNumberWidth = Math.max(2, Math.ceil(Math.log10(lineCount)) + 1);
|
||||
|
||||
return (
|
||||
<div className="bg-default p-3 rounded-md text-[10px] overflow-x-auto font-mono">
|
||||
{lines.map((line, idx) => (
|
||||
<div key={idx} className="flex gap-2">
|
||||
<span
|
||||
className="text-subtle select-none text-right shrink-0"
|
||||
style={{ minWidth: `${lineNumberWidth}ch` }}>
|
||||
{idx + 1}
|
||||
</span>
|
||||
<span className="text-default whitespace-pre-wrap break-all">{line || " "}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BookingLogsTimeline({ logs }: BookingLogsTimelineProps) {
|
||||
const { t } = useLocale();
|
||||
const [expandedLogIds, setExpandedLogIds] = useState<Set<string>>(new Set());
|
||||
const [showJsonMap, setShowJsonMap] = useState<Record<string, boolean>>({});
|
||||
|
||||
const toggleExpand = (logId: string) => {
|
||||
setExpandedLogIds((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(logId)) {
|
||||
newSet.delete(logId);
|
||||
} else {
|
||||
newSet.add(logId);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleJson = (logId: string) => {
|
||||
setShowJsonMap((prev) => ({
|
||||
...prev,
|
||||
[logId]: !prev[logId],
|
||||
}));
|
||||
};
|
||||
|
||||
if (logs.length === 0) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-muted">{t("no_audit_logs_found")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
{logs.map((log, index) => {
|
||||
const isLast = index === logs.length - 1;
|
||||
const isExpanded = expandedLogIds.has(log.id);
|
||||
const showJson = showJsonMap[log.id] || false;
|
||||
const actorRole = ACTOR_ROLE_LABEL_MAP[log.actor.type] ?? null;
|
||||
return (
|
||||
<div key={log.id} className="flex gap-1">
|
||||
<div className="flex flex-col items-center self-stretch">
|
||||
<div className="pt-2 shrink-0">
|
||||
<div className="bg-subtle rounded-[3.556px] p-1 flex items-center justify-center w-4 h-4">
|
||||
<Icon name={log.hasError ? "triangle-alert" : (ACTION_ICON_MAP[log.action] ?? "sparkles")} className={`h-3 w-3 ${log.hasError ? "text-attention" : "text-subtle"}`} />
|
||||
</div>
|
||||
</div>
|
||||
{!isLast && <div className="w-px bg-subtle flex-1 min-h-0" />}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 rounded-lg py-2">
|
||||
<div className="px-3 mb-2">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-sm font-medium leading-4 text-emphasis">
|
||||
<ActionTitle actionDisplayTitle={log.actionDisplayTitle} />
|
||||
</h3>
|
||||
<div className="flex items-center gap-1 mt-1 text-xs text-subtle">
|
||||
{log.actor.displayAvatar && (
|
||||
<Avatar
|
||||
size="xs"
|
||||
imageSrc={log.actor.displayAvatar}
|
||||
alt={log.actor.displayName || ""}
|
||||
/>
|
||||
)}
|
||||
<span>
|
||||
{log.actor.displayName}
|
||||
{actorRole && <span>{` (${t(actorRole)})`}</span>}
|
||||
</span>
|
||||
<span>•</span>
|
||||
<span>{dayjs(log.timestamp).fromNow()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="px-3">
|
||||
<div className="bg-muted rounded-lg border border-muted">
|
||||
<div className="py-1">
|
||||
<Button
|
||||
color="minimal"
|
||||
size="sm"
|
||||
onClick={() => toggleExpand(log.id)}
|
||||
StartIcon={isExpanded ? "chevron-down" : "chevron-right"}
|
||||
className="justify-start text-xs font-medium text-subtle h-6">
|
||||
{isExpanded ? t("hide_details") : t("show_details")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="bg-default rounded-lg m-0.5 text-xs">
|
||||
{/* Render displayFields if available, otherwise show type */}
|
||||
{log.displayFields && log.displayFields.length > 0
|
||||
? log.displayFields.map((field, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">
|
||||
{t(field.labelKey)}
|
||||
</span>
|
||||
<span className="text-[#096638] font-medium">{t(field.valueKey)}</span>
|
||||
</div>
|
||||
))
|
||||
: null}
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">{t("actor")}</span>
|
||||
<span className="text-default">{log.actor.displayName || log.actor.type}</span>
|
||||
</div>
|
||||
{log.impersonatedBy && (
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">
|
||||
{t("booking_audit_action.actor_impersonated_by", {
|
||||
actor: log.actor.displayName,
|
||||
})}
|
||||
</span>
|
||||
<span className="text-default">{log.impersonatedBy.displayName}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-start gap-2 py-2 border-b px-3 border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">
|
||||
{t("booking_audit_action.source")}
|
||||
</span>
|
||||
<span className="text-default">{log.source}</span>
|
||||
</div>
|
||||
<div className="flex items-start gap-2 py-2 px-3 border-b border-subtle">
|
||||
<span className="font-medium text-emphasis w-[140px]">{t("timestamp")}</span>
|
||||
<span className="text-default">
|
||||
{dayjs(log.timestamp).format("YYYY-MM-DD HH:mm:ss")}
|
||||
</span>
|
||||
</div>
|
||||
{log.displayJson && Object.keys(log.displayJson).length > 0 && (
|
||||
<div>
|
||||
<div className="flex flex-col items-start gap-2 py-1 px-3 border-b border-subtle">
|
||||
<Button
|
||||
color="minimal"
|
||||
size="sm"
|
||||
onClick={() => toggleJson(log.id)}
|
||||
StartIcon={showJson ? "chevron-down" : "chevron-right"}
|
||||
className="-ml-3 h-6 px-2 font-medium text-xs">
|
||||
{t("json")}
|
||||
</Button>
|
||||
</div>
|
||||
<div>{showJson && <JsonViewer data={log.displayJson} />}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useBookingLogsFilters(auditLogs: AuditLog[], searchTerm: string, actorFilter: string | null) {
|
||||
const filteredLogs = auditLogs.filter((log) => {
|
||||
const doesMatchDisplayFields = (): boolean => {
|
||||
return log.displayFields?.some((field) => {
|
||||
return field.valueKey?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
field.labelKey?.toLowerCase().includes(searchTerm.toLowerCase());
|
||||
}) ?? false;
|
||||
};
|
||||
|
||||
const doesMatchActionDisplayTitle = (): boolean => {
|
||||
return log.actionDisplayTitle.key?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
Object.values(log.actionDisplayTitle.params ?? {}).some((param) => param?.toString().toLowerCase().includes(searchTerm.toLowerCase()));
|
||||
};
|
||||
|
||||
const matchesSearch =
|
||||
!searchTerm ||
|
||||
log.action.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
log.actor.displayName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
doesMatchDisplayFields() ||
|
||||
doesMatchActionDisplayTitle();
|
||||
|
||||
const matchesActor = !actorFilter || log.actor.displayName === actorFilter;
|
||||
|
||||
return matchesSearch && matchesActor;
|
||||
});
|
||||
|
||||
const uniqueActorNames = Array.from(
|
||||
new Set(auditLogs.map((log) => log.actor.displayName).filter((name): name is string => Boolean(name)))
|
||||
);
|
||||
|
||||
const actorOptions = uniqueActorNames.map((actorName) => ({
|
||||
label: actorName,
|
||||
value: actorName,
|
||||
}));
|
||||
|
||||
return { filteredLogs, actorOptions };
|
||||
}
|
||||
|
||||
export function BookingHistory({ bookingUid }: BookingHistoryProps) {
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [actorFilter, setActorFilter] = useState<string | null>(null);
|
||||
const { t } = useLocale();
|
||||
const { data, isLoading, error } = trpc.viewer.bookings.getBookingHistory.useQuery({
|
||||
bookingUid,
|
||||
});
|
||||
|
||||
const auditLogs = data?.auditLogs || [];
|
||||
|
||||
const { filteredLogs, actorOptions } = useBookingLogsFilters(auditLogs, searchTerm, actorFilter);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="text-center">
|
||||
<p className="text-red-600 font-medium">{t("error_loading_booking_logs")}</p>
|
||||
<p className="text-sm text-gray-500 mt-2">{error.message}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<SkeletonText className="h-12 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
<SkeletonText className="h-24 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<BookingLogsFilters
|
||||
searchTerm={searchTerm}
|
||||
onSearchChange={setSearchTerm}
|
||||
actorFilter={actorFilter}
|
||||
onActorFilterChange={setActorFilter}
|
||||
actorOptions={actorOptions}
|
||||
/>
|
||||
|
||||
<BookingLogsTimeline logs={filteredLogs} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { BookingHistory } from "./BookingHistory";
|
||||
|
||||
interface BookingHistoryPageProps {
|
||||
bookingUid: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* BookingHistoryPage - Wrapper component for standalone page context
|
||||
* Adds page-specific styling and layout for the booking history view
|
||||
*/
|
||||
export function BookingHistoryPage({ bookingUid }: BookingHistoryPageProps) {
|
||||
return <BookingHistory bookingUid={bookingUid} />;
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,394 +0,0 @@
|
||||
/**
|
||||
* @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");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,191 +0,0 @@
|
||||
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,
|
||||
};
|
||||
};
|
||||
@@ -1,106 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import formbricks from "@formbricks/js/app";
|
||||
import { useSession } from "next-auth/react";
|
||||
import { useEffect } from "react";
|
||||
|
||||
import useMeQuery from "@calcom/trpc/react/hooks/useMeQuery";
|
||||
|
||||
export const initFormbricks = ({
|
||||
userId,
|
||||
attributes,
|
||||
}: {
|
||||
userId: string;
|
||||
attributes: { [key: string]: string | null | undefined };
|
||||
}) => {
|
||||
const filteredAttributes: Record<string, string | number> = {};
|
||||
Object.entries(attributes).forEach(([key, value]) => {
|
||||
if (value !== null && value !== undefined) {
|
||||
filteredAttributes[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
if (process.env.NEXT_PUBLIC_FORMBRICKS_HOST_URL && process.env.NEXT_PUBLIC_FORMBRICKS_ENVIRONMENT_ID) {
|
||||
formbricks.init({
|
||||
environmentId: process.env.NEXT_PUBLIC_FORMBRICKS_ENVIRONMENT_ID,
|
||||
apiHost: process.env.NEXT_PUBLIC_FORMBRICKS_HOST_URL,
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
userId,
|
||||
attributes: filteredAttributes,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const trackFormbricksAction = (eventName: string, properties: Record<string, string> = {}) => {
|
||||
if (process.env.NEXT_PUBLIC_FORMBRICKS_HOST_URL && process.env.NEXT_PUBLIC_FORMBRICKS_ENVIRONMENT_ID) {
|
||||
formbricks.track(eventName, properties);
|
||||
}
|
||||
};
|
||||
|
||||
export const useFormbricks = () => {
|
||||
const { data: user, isLoading } = useMeQuery();
|
||||
const { data: session, status } = useSession();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && user && session) {
|
||||
initFormbricks({
|
||||
userId: user.id.toString(),
|
||||
attributes: {
|
||||
name: user?.name,
|
||||
email: user.email,
|
||||
username: user?.username,
|
||||
belongsToActiveTeam: session.user.belongsToActiveTeam?.toString(),
|
||||
isOrganizationAdmin: user.organization?.isOrgAdmin?.toString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}, [isLoading, user, status, session]);
|
||||
};
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
EventTypeForAppCard,
|
||||
} from "@calcom/app-store/_components/EventTypeAppCardInterface";
|
||||
import type { EventTypeAppsList } from "@calcom/app-store/utils";
|
||||
import useAppsData from "@calcom/features/apps/hooks/useAppsData";
|
||||
import useAppsData from "@calcom/web/modules/apps/hooks/useAppsData";
|
||||
import type { EventTypeSetupProps } from "@calcom/features/eventtypes/lib/types";
|
||||
import { EmptyScreen } from "@calcom/ui/components/empty-screen";
|
||||
|
||||
|
||||
Reference in new issue
Block a user