All files / src/pages/admin analytics.tsx

100% Statements 52/52
83.78% Branches 62/74
100% Functions 21/21
100% Lines 48/48

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                                                                                        60x 60x 60x 60x 60x     4x 4x 4x 4x 4x 2x 1x 1x       2x   2x       4x         60x 161x       60x 52x   161x                       48x 161x                                             48x 144x 721x 721x 232x     721x     48x 161x       48x 161x           48x 161x       48x               60x       60x                                             60x                                                           240x                                       153x                                     153x                                     153x                                                   9x                   160x                                                                                                                         180x                       45x                                                       459x                                          
import { useMemo, useState } from "react";
import { Link } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
 
import { Card } from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { Alert } from "../../components/ui/alert";
import { AnalyticsEmptyState } from "../../components/analytics";
import { AdminMetric, AdminMetrics } from "../../components/admin/AdminMetric";
import { AdminBand, AdminPageHead } from "../../components/admin/AdminPageHead";
import type { Pro } from "../../lib/api";
import { adminApi } from "../../lib/api";
import { useAdminPlatformAnalytics } from "../../hooks/queries/useAdminQueries";
import { queryKeys } from "../../lib/query-keys";
import {
	BarChart3,
	Eye,
	type LucideIcon,
	Mail,
	MousePointerClick,
	RefreshCw,
	TrendingUp,
} from "lucide-react";
 
type ProWithStats = Pro & {
	stats?: {
		views7d: number;
		clicks7d: number;
		totalInquiries: number;
		totalWhatsappClicks: number;
	};
};
 
type PlatformStats = {
	totalViews7d: number;
	totalClicks7d: number;
	totalWhatsappClicks: number;
	totalInquiries: number;
	topProsByViews: ProWithStats[];
	topProsByClicks: ProWithStats[];
	topProsByLeads: ProWithStats[];
};
 
export function AdminAnalyticsPage() {
	const queryClient = useQueryClient();
	const { data, isLoading, error: queryError } = useAdminPlatformAnalytics();
	const [isSyncing, setIsSyncing] = useState(false);
	const [syncResult, setSyncResult] = useState<string | null>(null);
	const [syncError, setSyncError] = useState<string | null>(null);
 
	async function handleSync() {
		setIsSyncing(true);
		setSyncResult(null);
		setSyncError(null);
		try {
			const res = await adminApi.triggerSync();
			if (res.data) {
				const d = res.data;
				setSyncResult(
					`Synced: ${d.pros} pros, ${d.projects} projects for ${d.date}`,
				);
			}
			queryClient.invalidateQueries({ queryKey: queryKeys.admin.analytics() });
		} catch (err) {
			setSyncError(
				err instanceof Error ? err.message : "Analytics sync failed",
			);
		} finally {
			setIsSyncing(false);
		}
	}
 
	// Derive pros and platformStats from query data
	const pros: Pro[] = useMemo(
		() => data?.pros?.map((vs) => vs.pro) ?? [],
		[data],
	);
 
	const platformStats: PlatformStats | null = useMemo(() => {
		if (!data?.pros) return null;
 
		const prosWithStats: ProWithStats[] = data.pros.map((vs) => ({
			...vs.pro,
			stats: vs.stats?.summary
				? {
						views7d: vs.stats.summary.views7d || 0,
						clicks7d: vs.stats.summary.clicks7d || 0,
						totalInquiries: vs.stats.summary.totalInquiries || 0,
						totalWhatsappClicks: vs.stats.summary.totalWhatsappClicks || 0,
					}
				: undefined,
		}));
 
		const totals = prosWithStats.reduce(
			(acc, v) => ({
				totalViews7d: acc.totalViews7d + (v.stats?.views7d || 0),
				totalClicks7d: acc.totalClicks7d + (v.stats?.clicks7d || 0),
				totalWhatsappClicks:
					acc.totalWhatsappClicks + (v.stats?.totalWhatsappClicks || 0),
				totalInquiries: acc.totalInquiries + (v.stats?.totalInquiries || 0),
			}),
			{
				totalViews7d: 0,
				totalClicks7d: 0,
				totalWhatsappClicks: 0,
				totalInquiries: 0,
			},
		);
 
		// #359: after Sync Analytics, admins reported pros with lower view counts
		// appearing above those with higher counts. Root cause: when two pros had
		// equal view/click counts, the sort had no tie-breaker — JS Array.sort is
		// stable but the refetched data arrives in a DB-dependent order, so the
		// relative order of equal-value pros shifted between renders. A
		// deterministic tie-break (businessName, then id) keeps the ranking
		// consistent across refetches.
		const makeDescComparator =
			(key: "views7d" | "clicks7d" | "totalInquiries") =>
			(a: ProWithStats, b: ProWithStats) => {
				const delta = (b.stats?.[key] || 0) - (a.stats?.[key] || 0);
				if (delta !== 0) return delta;
				const nameCmp = (a.businessName || a.id).localeCompare(
					b.businessName || b.id,
				);
				return nameCmp !== 0 ? nameCmp : a.id.localeCompare(b.id);
			};
 
		const sortedByViews = [...prosWithStats]
			.filter((v) => v.stats)
			.sort(makeDescComparator("views7d"))
			.slice(0, 5);
 
		const sortedByClicks = [...prosWithStats]
			.filter((v) => v.stats)
			.sort(makeDescComparator("clicks7d"))
			.slice(0, 5);
 
		// Top Pros by Leads used the same dataset — also pre-sort it here so
		// the render loop doesn't mutate `topProsByViews` via in-place `.sort()`.
		const sortedByLeads = [...prosWithStats]
			.filter((v) => v.stats)
			.sort(makeDescComparator("totalInquiries"))
			.slice(0, 5);
 
		return {
			...totals,
			topProsByViews: sortedByViews,
			topProsByClicks: sortedByClicks,
			topProsByLeads: sortedByLeads,
		};
	}, [data]);
 
	const error = queryError ? "Failed to load analytics data" : "";
 
	// Four figures, each with the window it covers printed under it. No icon
	// chips: the Job Book leads with figures, not with decoration.
	const statCards = [
		{
			name: "Total Views",
			value: platformStats?.totalViews7d ?? 0,
			subtext: "Last 7 days",
		},
		{
			name: "Total Clicks",
			value: platformStats?.totalClicks7d ?? 0,
			subtext: "Last 7 days",
		},
		{
			name: "WhatsApp Clicks",
			value: platformStats?.totalWhatsappClicks ?? 0,
			subtext: "All time",
		},
		{
			name: "Total Leads",
			value: platformStats?.totalInquiries ?? 0,
			subtext: "All time",
		},
	];
 
	return (
		<div className="space-y-8">
			<AdminPageHead
				title={
					<>
						<BarChart3 aria-hidden="true" className="size-5" />
						Platform Analytics
					</>
				}
				description="Overview of all pro performance and platform engagement."
				actions={
					<Button
						variant="outline"
						size="sm"
						onClick={handleSync}
						isLoading={isSyncing}
					>
						<RefreshCw aria-hidden="true" />
						Sync Analytics
					</Button>
				}
			/>
 
			{syncResult && <Alert variant="success">{syncResult}</Alert>}
			{syncError && <Alert variant="error">{syncError}</Alert>}
			{error && <Alert variant="error">{error}</Alert>}
 
			{/* Figures lead: a label, a 2px rule and a tabular number. */}
			<AdminMetrics>
				{statCards.map((stat) => (
					<AdminMetric
						key={stat.name}
						label={stat.name}
						value={stat.value.toLocaleString("en-IN")}
						note={stat.subtext}
						isLoading={isLoading}
					/>
				))}
			</AdminMetrics>
 
			{/* Top Pros Grid */}
			<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
				{/* Top Pros by Views */}
				<RankedPanel
					icon={Eye}
					title="Top Pros by Views (7 days)"
					isLoading={isLoading}
					isEmpty={!platformStats?.topProsByViews?.length}
				>
					{(platformStats?.topProsByViews ?? []).map((pro, index) => (
						<RankedRow
							key={pro.id}
							rank={index + 1}
							label={pro.businessName}
							value={`${(pro.stats?.views7d ?? 0).toLocaleString("en-IN")} views`}
							proId={pro.id}
							to="/admin/pros/$proId/analytics"
						/>
					))}
				</RankedPanel>
 
				{/* Top Pros by Clicks */}
				<RankedPanel
					icon={MousePointerClick}
					title="Top Pros by Clicks (7 days)"
					isLoading={isLoading}
					isEmpty={!platformStats?.topProsByClicks?.length}
				>
					{(platformStats?.topProsByClicks ?? []).map((pro, index) => (
						<RankedRow
							key={pro.id}
							rank={index + 1}
							label={pro.businessName}
							value={`${(pro.stats?.clicks7d ?? 0).toLocaleString("en-IN")} clicks`}
							proId={pro.id}
							to="/admin/pros/$proId/analytics"
						/>
					))}
				</RankedPanel>
 
				{/* Top Pros by Leads */}
				<RankedPanel
					icon={Mail}
					title="Top Pros by Leads"
					isLoading={isLoading}
					isEmpty={pros.length === 0}
				>
					{(platformStats?.topProsByLeads ?? []).map((pro, index) => (
						<RankedRow
							key={pro.id}
							rank={index + 1}
							label={pro.businessName}
							value={`${(pro.stats?.totalInquiries ?? 0).toLocaleString("en-IN")} leads`}
							proId={pro.id}
							to="/admin/pros/$proId"
						/>
					))}
				</RankedPanel>
 
				{/* Quick Links */}
				<section className="space-y-2">
					<div className="flex items-center gap-2">
						<TrendingUp
							aria-hidden="true"
							className="size-4 shrink-0 text-foreground-muted"
						/>
						<AdminBand title="Pro Analytics" quiet className="grow" />
					</div>
					<p className="text-sm text-foreground-muted">
						View detailed analytics for individual pros.
					</p>
					{isLoading ? (
						<div className="space-y-px">
							{[1, 2, 3].map((i) => (
								<div
									key={i}
									className="h-10 animate-pulse bg-background-muted"
								/>
							))}
						</div>
					) : pros.length > 0 ? (
						<Card className="overflow-hidden">
							<ul>
								{pros.slice(0, 5).map((pro) => (
									<li
										key={pro.id}
										className="[&+li]:border-t [&+li]:border-border-default"
									>
										<Link
											to="/admin/pros/$proId/analytics"
											params={{ proId: pro.id }}
											className="flex items-center justify-between gap-3 px-3.5 py-2.5 transition-colors hover:bg-foreground-default/7 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
										>
											<span className="min-w-0 truncate text-sm font-medium text-foreground-default">
												{pro.businessName}
											</span>
											<span className="shrink-0 text-xs font-semibold uppercase tracking-wider text-primary-600">
												View Analytics →
											</span>
										</Link>
									</li>
								))}
							</ul>
							<div className="border-t border-border-strong px-3.5 py-2">
								<Link
									to="/admin/pros"
									className="text-xs font-semibold uppercase tracking-wider text-primary-600 hover:text-primary-700"
								>
									View all pros →
								</Link>
							</div>
						</Card>
					) : (
						<p className="py-4 text-center text-sm text-foreground-muted">
							No pros found
						</p>
					)}
				</section>
			</div>
		</div>
	);
}
 
/**
 * A ruled ranked panel: a `.label` band with its icon, then ruled rows.
 *
 * `components/analytics/RankedListItem.tsx` renders the same row shape but
 * puts the rank in a `rounded-full` chip, which is a pill — the one shape the
 * Job Book forbids. That file belongs to another group this phase, so this
 * page prints its own rows rather than reaching for a pill, and the fix there
 * is reported.
 */
function RankedPanel({
	icon: Icon,
	title,
	isLoading,
	isEmpty,
	children,
}: {
	icon: LucideIcon;
	title: string;
	isLoading: boolean;
	isEmpty: boolean;
	children: React.ReactNode;
}) {
	return (
		<section className="space-y-2">
			<div className="flex items-center gap-2">
				<Icon
					aria-hidden="true"
					className="size-4 shrink-0 text-foreground-muted"
				/>
				<AdminBand title={title} quiet className="grow" />
			</div>
			{isLoading ? (
				<div className="space-y-px">
					{[1, 2, 3, 4, 5].map((i) => (
						<div key={i} className="h-9 animate-pulse bg-background-muted" />
					))}
				</div>
			) : isEmpty ? (
				<AnalyticsEmptyState icon={Icon} />
			) : (
				<Card className="overflow-hidden">
					<ul>{children}</ul>
				</Card>
			)}
		</section>
	);
}
 
/** One ranked row: a tabular rank, the studio, and its figure right-aligned. */
function RankedRow({
	rank,
	label,
	value,
	proId,
	to,
}: {
	rank: number;
	label: string;
	value: string;
	proId: string;
	to: "/admin/pros/$proId" | "/admin/pros/$proId/analytics";
}) {
	return (
		<li className="[&+li]:border-t [&+li]:border-border-default">
			<Link
				to={to}
				params={{ proId }}
				className="flex items-center gap-3 px-3.5 py-2 transition-colors hover:bg-foreground-default/7 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500"
			>
				{/* A printed rank: tabular, right-aligned, no pill. */}
				<span className="w-5 shrink-0 text-right text-xs font-semibold tabular-nums text-foreground-subtle">
					{rank}.
				</span>
				<span className="min-w-0 grow truncate text-sm font-medium text-foreground-default">
					{label}
				</span>
				<span className="shrink-0 text-sm tabular-nums text-foreground-muted">
					{value}
				</span>
			</Link>
		</li>
	);
}