All files / src/hooks/queries useAdminQueries.ts

92.62% Statements 113/122
83.33% Branches 95/114
88.88% Functions 48/54
91.34% Lines 95/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430            27x         2x                 1x                             1x                                   82x     41x 39x               218x     95x 93x                 531x     179x 165x             175x     83x     81x             175x     80x 78x             53x     35x 28x               309x     87x     83x                 5x     2x 2x             5x     2x 2x                 5x     2x 2x                         85x     44x 42x                 6x     3x       3x     3x 5x   3x   5x           3x   5x     3x   5x       3x                                             160x 160x 160x 160x 150x     160x     93x         91x     242x 242x     242x                   138x 138x 138x   138x     88x         85x     227x 231x     227x                                     4x 4x 4x 4x 4x 4x 4x 4x   4x     2x 2x                             4x 4x 4x 4x   4x     2x 2x                                                                                                   6x 6x   6x     3x         3x     9x 9x     9x          
import { useQuery, useInfiniteQuery } from "@tanstack/react-query";
import { adminApi } from "../../lib/api";
import { adminAuthApi } from "../../lib/api/admin-auth";
import { queryKeys } from "../../lib/query-keys";
import type { RoomCategoryWithStats, RoomCategoryMedia } from "../../lib/api";
 
const PAGE_SIZE = 20;
 
// ─── Dashboard ──────────────────────────────────────────────────────────────
 
export function useAdminDashboard() {
	return useQuery({
		queryKey: queryKeys.admin.dashboard(),
		queryFn: async () => {
			const [
				prosRes,
				publishedProsRes,
				pendingProsRes,
				projectsRes,
				publishedProjectsRes,
			] = await Promise.all([
				adminApi.listPros({ limit: "5" }),
				adminApi.listPros({ limit: "1", status: "published" }),
				// Issue #613: surface pros that finished onboarding but are still
				// in draft, so an admin can flip them to published. Excludes
				// partial onboarding shells (no businessName) per #593.
				adminApi.listPros({
					limit: "1",
					status: "draft",
					includeIncomplete: "false",
				}),
				adminApi.listProjects({ limit: "1" }),
				adminApi.listProjects({ limit: "1", status: "published" }),
			]);
 
			return {
				stats: {
					totalPros: prosRes.meta?.total ?? 0,
					publishedPros: publishedProsRes.meta?.total ?? 0,
					pendingPros: pendingProsRes.meta?.total ?? 0,
					totalProjects: projectsRes.meta?.total ?? 0,
					publishedProjects: publishedProjectsRes.meta?.total ?? 0,
				},
				recentPros: (prosRes.data || []).slice(0, 5),
			};
		},
		staleTime: 1000 * 60 * 2,
	});
}
 
// ─── Taxonomy ───────────────────────────────────────────────────────────────
 
export function useAdminTaxonomy(type: string, includeInactive: boolean) {
	return useQuery({
		queryKey: queryKeys.admin.taxonomy(type),
		queryFn: async () => {
			const response = await adminApi.listTaxonomy(type, includeInactive);
			return response.data || [];
		},
	});
}
 
// ─── Pro Lookup (shared) ─────────────────────────────────────────────────
 
export function useAdminProLookup() {
	return useQuery({
		queryKey: queryKeys.admin.proLookup(),
		queryFn: async () => {
			const response = await adminApi.listPros({ limit: "500" });
			return response.data || [];
		},
		staleTime: 1000 * 60 * 5,
	});
}
 
// ─── Pro Detail ──────────────────────────────────────────────────────────
 
export function useAdminPro(proId: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.pros.detail(proId ?? ""),
		queryFn: async () => {
			const response = await adminApi.getPro(proId as string);
			return response.data;
		},
		enabled: !!proId,
	});
}
 
export function useAdminProProjects(proId: string | null) {
	return useQuery({
		queryKey: [...queryKeys.admin.pros.detail(proId ?? ""), "projects"],
		queryFn: async () => {
			const response = await adminApi.listProjects({
				proId: proId as string,
			});
			return response.data || [];
		},
		enabled: !!proId,
	});
}
 
export function useAdminProTeam(proId: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.pros.team(proId ?? ""),
		queryFn: async () => {
			const response = await adminApi.getProTeam(proId as string);
			return response.data || [];
		},
		enabled: !!proId,
	});
}
 
export function useAdminProStats(proId: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.pros.stats(proId ?? ""),
		queryFn: async () => {
			const response = await adminApi.getProStats(proId as string);
			return response.data;
		},
		enabled: !!proId,
		staleTime: 1000 * 60 * 2,
	});
}
 
export function useAdminProCompanyProfile(proId: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.pros.companyProfile(proId ?? ""),
		queryFn: async () => {
			const response = await adminApi.getCompanyProfile(
				proId as string,
			);
			return response.data;
		},
		enabled: !!proId,
	});
}
 
// ─── User Security ──────────────────────────────────────────────────────────
 
export function useAdminUserSessions(userId: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.users.sessions(userId ?? ""),
		queryFn: async () => {
			const res = await adminAuthApi.getUserSessions(userId as string);
			return res.data ?? [];
		},
		enabled: !!userId,
	});
}
 
export function useAdminUserAccounts(userId: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.users.accounts(userId ?? ""),
		queryFn: async () => {
			const res = await adminAuthApi.getUserAccounts(userId as string);
			return res.data ?? [];
		},
		enabled: !!userId,
	});
}
 
// ─── Pro Search (debounced) ─────────────────────────────────────────────────
 
export function useAdminProSearch(search: string) {
	return useQuery({
		queryKey: queryKeys.admin.pros.list({ search }),
		queryFn: async () => {
			const result = await adminApi.listPros({ search });
			return (result.data || []).map((p) => ({
				id: p.id,
				businessName: p.businessName,
			}));
		},
		enabled: search.length >= 2,
		staleTime: 1000 * 60 * 2,
	});
}
 
// ─── User Detail ────────────────────────────────────────────────────────────
 
export function useAdminUser(userId: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.users.detail(userId ?? ""),
		queryFn: async () => {
			const response = await adminApi.getUser(userId as string);
			return response.data;
		},
		enabled: !!userId,
	});
}
 
// ─── Platform Analytics ─────────────────────────────────────────────────────
 
export function useAdminPlatformAnalytics() {
	return useQuery({
		queryKey: queryKeys.admin.analytics(),
		queryFn: async () => {
			const prosRes = await adminApi.listPros({
				status: "published",
				limit: "20",
			});
			const pros = prosRes.data || [];
 
			// Get stats for top 20 pros
			const statsPromises = pros.map((v) =>
				adminApi.getProStats(v.id).catch(() => ({ data: null })),
			);
			const statsResults = await Promise.all(statsPromises);
 
			const proStats = pros.map((pro, i) => ({
				pro,
				stats: statsResults[i]?.data ?? null,
			}));
 
			// Compute platform stats from pro summary data
			const totalInquiries = proStats.reduce(
				(sum, vs) =>
					sum + (vs.stats?.summary?.totalInquiries ?? 0),
				0,
			);
			const totalPageViews = proStats.reduce(
				(sum, vs) =>
					sum + (vs.stats?.summary?.totalPageViews ?? 0),
				0,
			);
 
			return {
				pros: proStats,
				platformStats: {
					totalPros: prosRes.meta?.total ?? pros.length,
					totalInquiries,
					totalPageViews,
				},
			};
		},
		staleTime: 1000 * 60 * 2,
	});
}
 
// ─── Paginated Lists (useInfiniteQuery) ─────────────────────────────────────
 
export function useAdminProsList(filters: {
	status?: string;
	search?: string;
	// Issue #593: admin page opts OUT of incomplete onboarding shells by
	// default. Other callers (dashboard counts, search typeahead, analytics)
	// don't pass this and see unchanged behavior.
	includeIncomplete?: boolean;
}) {
	const filterParams: Record<string, string> = {};
	if (filters.status) filterParams.status = filters.status;
	if (filters.search) filterParams.search = filters.search;
	if (filters.includeIncomplete !== undefined) {
		filterParams.includeIncomplete = String(filters.includeIncomplete);
	}
 
	return useInfiniteQuery({
		queryKey: queryKeys.admin.pros.list(filterParams),
		queryFn: async ({ pageParam = 0 }) => {
			const response = await adminApi.listPros({
				limit: PAGE_SIZE.toString(),
				offset: pageParam.toString(),
				...filterParams,
			});
			return response;
		},
		getNextPageParam: (lastPage, allPages) => {
			const loaded = allPages.reduce(
				(sum, p) => sum + (p?.data?.length || 0),
				0,
			);
			return loaded < (lastPage.meta?.total || 0) ? loaded : undefined;
		},
		initialPageParam: 0,
	});
}
 
export function useAdminProjectsList(filters: {
	status?: string;
	search?: string;
}) {
	const filterParams: Record<string, string> = {};
	if (filters.status) filterParams.status = filters.status;
	if (filters.search) filterParams.search = filters.search;
 
	return useInfiniteQuery({
		queryKey: queryKeys.admin.projects.list(filterParams),
		queryFn: async ({ pageParam = 0 }) => {
			const response = await adminApi.listProjects({
				limit: PAGE_SIZE.toString(),
				offset: pageParam.toString(),
				...filterParams,
			});
			return response;
		},
		getNextPageParam: (lastPage, allPages) => {
			const loaded = allPages.reduce(
				(sum, p) => sum + (p?.data?.length || 0),
				0,
			);
			return loaded < (lastPage.meta?.total || 0) ? loaded : undefined;
		},
		initialPageParam: 0,
	});
}
 
// ─── Communications ──────────────────────────────────────────────────────────
 
export type CommunicationsFilters = {
	channel?: string;
	status?: string;
	eventType?: string;
	environment?: string;
	search?: string;
	limit?: number;
	offset?: number;
};
 
export function useAdminCommunications(filters: CommunicationsFilters) {
	const filterParams: Record<string, string | number> = {};
	if (filters.channel) filterParams.channel = filters.channel;
	if (filters.status) filterParams.status = filters.status;
	if (filters.eventType) filterParams.eventType = filters.eventType;
	if (filters.environment) filterParams.environment = filters.environment;
	if (filters.search) filterParams.search = filters.search;
	if (filters.limit) filterParams.limit = filters.limit;
	if (filters.offset !== undefined) filterParams.offset = filters.offset;
 
	return useQuery({
		queryKey: queryKeys.admin.communications.list(filterParams),
		queryFn: async () => {
			const response = await adminApi.list(filters);
			return response.data;
		},
		staleTime: 1000 * 60 * 2,
	});
}
 
// ─── Feedback ───────────────────────────────────────────────────────────────
 
export type FeedbackFilters = {
	page?: number;
	limit?: number;
	status?: string;
};
 
export function useAdminFeedback(filters: FeedbackFilters) {
	const filterParams: Record<string, string | number> = {};
	if (filters.page) filterParams.page = filters.page;
	if (filters.limit) filterParams.limit = filters.limit;
	if (filters.status) filterParams.status = filters.status;
 
	return useQuery({
		queryKey: queryKeys.admin.feedback.list(filterParams),
		queryFn: async () => {
			const response = await adminApi.listFeedback(filters);
			return response;
		},
		staleTime: 1000 * 60 * 2,
	});
}
 
// ─── Room Categories ─────────────────────────────────────────────────────────
 
export function useAdminRoomCategories() {
	return useQuery({
		queryKey: queryKeys.admin.roomCategories.list(),
		queryFn: async () => {
			const response = await adminApi.listRoomCategoriesWithStats();
			return (response.data ?? []) as RoomCategoryWithStats[];
		},
		staleTime: 1000 * 60 * 5,
	});
}
 
export function useAdminRoomCategory(code: string | null) {
	return useQuery({
		queryKey: queryKeys.admin.roomCategories.detail(code ?? ""),
		queryFn: async () => {
			const response = await adminApi.getRoomCategory(code as string);
			return response.data as RoomCategoryWithStats;
		},
		enabled: !!code,
		staleTime: 1000 * 60 * 5,
	});
}
 
export function useAdminRoomCategoryMedia(
	code: string | null,
	sortBy: "recent" | "popular" = "recent",
) {
	return useQuery({
		queryKey: queryKeys.admin.roomCategories.media(code ?? "", sortBy),
		queryFn: async () => {
			const response = await adminApi.listMediaForRoomType(code as string, {
				sortBy,
				limit: 100,
			});
			return (response.data ?? []) as RoomCategoryMedia[];
		},
		enabled: !!code,
		staleTime: 1000 * 60 * 2,
	});
}
 
export function useAdminUsersList(filters: { search?: string }) {
	const filterParams: Record<string, string> = {};
	if (filters.search) filterParams.search = filters.search;
 
	return useInfiniteQuery({
		queryKey: queryKeys.admin.users.list(filterParams),
		queryFn: async ({ pageParam = 0 }) => {
			const response = await adminApi.listUsers({
				limit: PAGE_SIZE.toString(),
				offset: pageParam.toString(),
				...filterParams,
			});
			return response;
		},
		getNextPageParam: (lastPage, allPages) => {
			const loaded = allPages.reduce(
				(sum, p) => sum + (p?.data?.length || 0),
				0,
			);
			return loaded < (lastPage.meta?.total || 0) ? loaded : undefined;
		},
		initialPageParam: 0,
	});
}