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 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 | 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 15x 153x 15x 153x 15x 153x 9x 160x | import { useMemo, useState } from "react";
import { Link } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { StatCard, AnalyticsEmptyState } from "../../components/analytics";
import type { Pro } from "../../lib/api";
import { adminApi } from "../../lib/api";
import { useAdminPlatformAnalytics } from "../../hooks/queries/useAdminQueries";
import { queryKeys } from "../../lib/query-keys";
import {
TrendingUp,
Eye,
MousePointerClick,
MessageCircle,
Mail,
Store,
BarChart3,
RefreshCw,
} 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" : "";
const statCards = [
{
name: "Total Views",
value: platformStats?.totalViews7d ?? 0,
subtext: "Last 7 days",
icon: Eye,
color: "text-primary-600",
bgColor: "bg-blue-50",
},
{
name: "Total Clicks",
value: platformStats?.totalClicks7d ?? 0,
subtext: "Last 7 days",
icon: MousePointerClick,
color: "text-green-600",
bgColor: "bg-green-50",
},
{
name: "WhatsApp Clicks",
value: platformStats?.totalWhatsappClicks ?? 0,
subtext: "All time",
icon: MessageCircle,
color: "text-purple-600",
bgColor: "bg-purple-50",
},
{
name: "Total Leads",
value: platformStats?.totalInquiries ?? 0,
subtext: "All time",
icon: Mail,
color: "text-orange-600",
bgColor: "bg-orange-50",
},
];
return (
<div className="space-y-8">
{/* Header */}
<div className="flex items-start justify-between">
<div>
<h1 className="text-2xl font-bold text-foreground-default flex items-center gap-2">
<BarChart3 className="h-6 w-6" />
Platform Analytics
</h1>
<p className="mt-1 text-foreground-muted">
Overview of all pro performance and platform engagement.
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={handleSync}
isLoading={isSyncing}
>
<RefreshCw className="h-4 w-4 mr-1.5" />
Sync Analytics
</Button>
</div>
{syncResult && (
<div className="p-3 text-sm text-notification-success-text bg-notification-success-bg border border-notification-success-border rounded-lg">
{syncResult}
</div>
)}
{syncError && (
<div className="p-3 text-sm text-notification-error-text bg-notification-error-bg border border-notification-error-border rounded-lg">
{syncError}
</div>
)}
{error && (
<div className="p-4 text-sm text-notification-error-text bg-notification-error-bg border border-notification-error-border rounded-lg">
{error}
</div>
)}
{/* Stat Cards */}
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
{statCards.map((stat) => (
<StatCard key={stat.name} {...stat} isLoading={isLoading} />
))}
</div>
{/* Top Pros Grid */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Top Pros by Views */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Eye className="h-5 w-5 text-primary-600" />
Top Pros by Views (7 days)
</CardTitle>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="space-y-4">
{[1, 2, 3, 4, 5].map((i) => (
<div key={i} className="flex items-center justify-between">
<div className="h-4 w-32 bg-background-muted rounded animate-pulse" />
<div className="h-4 w-16 bg-background-muted rounded animate-pulse" />
</div>
))}
</div>
) : platformStats?.topProsByViews &&
platformStats.topProsByViews.length > 0 ? (
<div className="space-y-3">
{platformStats.topProsByViews.map((pro, index) => (
<Link
key={pro.id}
to="/admin/pros/$proId/analytics"
params={{ proId: pro.id }}
className="flex items-center justify-between p-2 rounded-lg hover:bg-background-muted transition-colors"
>
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-foreground-subtle w-5">
{index + 1}.
</span>
<Store className="h-4 w-4 text-foreground-subtle" />
<span className="text-sm font-medium text-foreground-default truncate max-w-[180px]">
{pro.businessName}
</span>
</div>
<span className="text-sm text-foreground-muted">
{pro.stats?.views7d.toLocaleString()} views
</span>
</Link>
))}
</div>
) : (
<AnalyticsEmptyState icon={Eye} />
)}
</CardContent>
</Card>
{/* Top Pros by Clicks */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<MousePointerClick className="h-5 w-5 text-green-600" />
Top Pros by Clicks (7 days)
</CardTitle>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="space-y-4">
{[1, 2, 3, 4, 5].map((i) => (
<div key={i} className="flex items-center justify-between">
<div className="h-4 w-32 bg-background-muted rounded animate-pulse" />
<div className="h-4 w-16 bg-background-muted rounded animate-pulse" />
</div>
))}
</div>
) : platformStats?.topProsByClicks &&
platformStats.topProsByClicks.length > 0 ? (
<div className="space-y-3">
{platformStats.topProsByClicks.map((pro, index) => (
<Link
key={pro.id}
to="/admin/pros/$proId/analytics"
params={{ proId: pro.id }}
className="flex items-center justify-between p-2 rounded-lg hover:bg-background-muted transition-colors"
>
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-foreground-subtle w-5">
{index + 1}.
</span>
<Store className="h-4 w-4 text-foreground-subtle" />
<span className="text-sm font-medium text-foreground-default truncate max-w-[180px]">
{pro.businessName}
</span>
</div>
<span className="text-sm text-foreground-muted">
{pro.stats?.clicks7d.toLocaleString()} clicks
</span>
</Link>
))}
</div>
) : (
<AnalyticsEmptyState icon={MousePointerClick} />
)}
</CardContent>
</Card>
{/* Top Pros by Leads */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Mail className="h-5 w-5 text-orange-600" />
Top Pros by Leads
</CardTitle>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="space-y-4">
{[1, 2, 3, 4, 5].map((i) => (
<div key={i} className="flex items-center justify-between">
<div className="h-4 w-32 bg-background-muted rounded animate-pulse" />
<div className="h-4 w-16 bg-background-muted rounded animate-pulse" />
</div>
))}
</div>
) : pros.length > 0 ? (
<div className="space-y-3">
{(platformStats?.topProsByLeads ?? []).map((pro, index) => (
<Link
key={pro.id}
to="/admin/pros/$proId"
params={{ proId: pro.id }}
className="flex items-center justify-between p-2 rounded-lg hover:bg-background-muted transition-colors"
>
<div className="flex items-center gap-3">
<span className="text-sm font-medium text-foreground-subtle w-5">
{index + 1}.
</span>
<Store className="h-4 w-4 text-foreground-subtle" />
<span className="text-sm font-medium text-foreground-default truncate max-w-[180px]">
{pro.businessName}
</span>
</div>
<span className="text-sm text-foreground-muted">
{pro.stats?.totalInquiries.toLocaleString()}{" "}
leads
</span>
</Link>
))}
</div>
) : (
<AnalyticsEmptyState icon={Mail} />
)}
</CardContent>
</Card>
{/* Quick Links */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<TrendingUp className="h-5 w-5 text-foreground-muted" />
Pro Analytics
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-foreground-muted mb-4">
View detailed analytics for individual pros.
</p>
{isLoading ? (
<div className="space-y-2">
{[1, 2, 3].map((i) => (
<div
key={i}
className="h-10 bg-background-muted rounded animate-pulse"
/>
))}
</div>
) : pros.length > 0 ? (
<div className="space-y-2">
{pros.slice(0, 5).map((pro) => (
<Link
key={pro.id}
to="/admin/pros/$proId/analytics"
params={{ proId: pro.id }}
className="flex items-center justify-between p-3 border border-border-default rounded-lg hover:bg-background-muted hover:border-border-default transition-colors"
>
<div className="flex items-center gap-2">
<Store className="h-4 w-4 text-foreground-subtle" />
<span className="text-sm font-medium text-foreground-default">
{pro.businessName}
</span>
</div>
<span className="text-xs text-primary-600">
View Analytics →
</span>
</Link>
))}
<Link
to="/admin/pros"
className="block text-center text-sm text-primary-600 hover:text-blue-800 mt-3"
>
View all pros →
</Link>
</div>
) : (
<p className="text-sm text-foreground-muted text-center py-4">
No pros found
</p>
)}
</CardContent>
</Card>
</div>
</div>
);
}
|