All files / src/pages/admin pro-analytics.tsx

100% Statements 32/32
95% Branches 57/60
100% Functions 19/19
100% Lines 31/31

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                                                        66x   66x 66x   66x 66x 66x 66x     66x 176x 60x 176x 174x         126x       66x                                                                       66x 66x 66x   50x 49x 39x       66x                                                             264x                                                                     73x                                                                               170x                 30x                                               136x                       98x                                             102x                       74x                                             170x                 47x                                  
import { useParams } from "@tanstack/react-router";
 
import {
	Card,
	CardContent,
	CardHeader,
	CardTitle,
} from "../../components/ui/card";
import { Breadcrumb } from "../../components/ui/breadcrumb";
import {
	StatCard,
	AnalyticsEmptyState,
	BreakdownBar,
	RankedListItem,
} from "../../components/analytics";
import {
	TrendingUp,
	Eye,
	MousePointerClick,
	MessageCircle,
	Mail,
} from "lucide-react";
import {
	useAdminPro,
	useAdminProStats,
} from "../../hooks/queries/useAdminQueries";
 
export function AdminProAnalyticsPage() {
	const { proId } = useParams({ strict: false });
 
	const { data: proData, isLoading: proLoading } = useAdminPro(proId ?? null);
	const { data: statsData, isLoading: statsLoading, error: statsError } = useAdminProStats(proId ?? null);
 
	const pro = proData ?? null;
	const stats = statsData ?? null;
	const isLoading = proLoading || statsLoading;
	const error = statsError ? "Failed to load analytics data" : "";
 
	// Helper to convert breakdown objects to sorted arrays with percentages
	const toBreakdownArray = (obj: Record<string, number>) => {
		const total = Object.values(obj).reduce((sum, val) => sum + val, 0);
		return Object.entries(obj)
			.filter(([key]) => key !== "unknown")
			.map(([key, count]) => ({
				name: key,
				count,
				percentage: total > 0 ? Math.round((count / total) * 100) : 0,
			}))
			.sort((a, b) => b.count - a.count)
			.slice(0, 5);
	};
 
	const statCards = [
		{
			name: "Profile Views",
			value: stats?.summary?.views7d ?? 0,
			subtext: "Last 7 days",
			icon: Eye,
			color: "text-primary-600",
			bgColor: "bg-blue-50",
		},
		{
			name: "Project Clicks",
			value: stats?.summary?.clicks7d ?? 0,
			subtext: "Last 7 days",
			icon: MousePointerClick,
			color: "text-green-600",
			bgColor: "bg-green-50",
		},
		{
			name: "WhatsApp Clicks",
			value: stats?.summary?.totalWhatsappClicks ?? 0,
			subtext: "All time",
			icon: MessageCircle,
			color: "text-purple-600",
			bgColor: "bg-purple-50",
		},
		{
			name: "Leads",
			value: stats?.summary?.totalInquiries ?? 0,
			subtext: "All time",
			icon: Mail,
			color: "text-orange-600",
			bgColor: "bg-orange-50",
		},
	];
 
	// Prepare breakdown data
	const trafficSources = stats?.sources ? toBreakdownArray(stats.sources) : [];
	const deviceBreakdown = stats?.devices ? toBreakdownArray(stats.devices) : [];
	const cityBreakdown = stats?.cities
		? Object.entries(stats.cities)
				.filter(([key]) => key !== "unknown")
				.map(([city, count]) => ({ city, count }))
				.sort((a, b) => b.count - a.count)
				.slice(0, 5)
		: [];
 
	return (
		<div className="space-y-8">
				{/* Breadcrumb */}
				<Breadcrumb
					items={[
						{ label: "Pros", href: "/admin/pros" },
						{ label: pro?.businessName || "Pro", href: `/admin/pros/${proId}` },
						{ label: "Analytics" },
					]}
				/>
 
				{/* Header */}
				<div>
					<h1 className="text-2xl font-bold text-foreground-default">
						{isLoading ? "Loading..." : pro?.businessName || "Pro"}{" "}
						Analytics
					</h1>
					<p className="mt-1 text-foreground-muted">
						Track pro performance and customer engagement.
					</p>
				</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>
 
				{/* Main Analytics Grid */}
				<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
					{/* Views & Clicks Trend */}
					<Card className="lg:col-span-2">
						<CardHeader>
							<CardTitle className="flex items-center gap-2">
								<TrendingUp className="h-5 w-5 text-foreground-muted" />
								Views & Clicks Trend
							</CardTitle>
						</CardHeader>
						<CardContent>
							{isLoading ? (
								<div className="h-64 bg-background-muted rounded animate-pulse" />
							) : stats?.daily && stats.daily.length > 0 ? (
								<div className="h-64 overflow-x-auto">
									<table className="w-full text-sm">
										<thead>
											<tr className="text-left text-foreground-muted border-b">
												<th className="pb-2 font-medium">Date</th>
												<th className="pb-2 font-medium text-right">Views</th>
												<th className="pb-2 font-medium text-right">Clicks</th>
												<th className="pb-2 font-medium text-right">
													Sessions
												</th>
											</tr>
										</thead>
										<tbody>
											{stats.daily
												.slice(-7)
												.reverse()
												.map((day) => (
													<tr key={day.date} className="border-b last:border-0">
														<td className="py-2 text-foreground-default">
															{new Date(day.date).toLocaleDateString("en-IN", {
																month: "short",
																day: "numeric",
															})}
														</td>
														<td className="py-2 text-right text-foreground-muted">
															{day.pageViews}
														</td>
														<td className="py-2 text-right text-foreground-muted">
															{day.projectClicks +
																day.whatsappClicks +
																day.callClicks}
														</td>
														<td className="py-2 text-right text-foreground-muted">
															{day.uniqueSessions}
														</td>
													</tr>
												))}
										</tbody>
									</table>
								</div>
							) : (
								<div className="h-64 flex items-center justify-center">
									<AnalyticsEmptyState icon={Eye} />
								</div>
							)}
						</CardContent>
					</Card>
 
					{/* Top Projects */}
					<Card>
						<CardHeader>
							<CardTitle>Top Projects</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>
							) : stats?.topProjects && stats.topProjects.length > 0 ? (
								<div className="space-y-4">
									{stats.topProjects.map((project, index) => (
										<RankedListItem
											key={project.id}
											rank={index + 1}
											label={project.title}
											value={`${project.views.toLocaleString()} views`}
											href={`/admin/projects/${project.id}`}
										/>
									))}
								</div>
							) : (
								<AnalyticsEmptyState icon={Eye} />
							)}
						</CardContent>
					</Card>
 
					{/* Traffic Sources */}
					<Card>
						<CardHeader>
							<CardTitle>Traffic Sources</CardTitle>
						</CardHeader>
						<CardContent>
							{isLoading ? (
								<div className="space-y-4">
									{[1, 2, 3, 4].map((i) => (
										<div key={i} className="space-y-2">
											<div className="flex items-center justify-between">
												<div className="h-3 w-24 bg-background-muted rounded animate-pulse" />
												<div className="h-3 w-12 bg-background-muted rounded animate-pulse" />
											</div>
											<div className="h-2 bg-background-muted rounded-full animate-pulse" />
										</div>
									))}
								</div>
							) : trafficSources.length > 0 ? (
								<div className="space-y-4">
									{trafficSources.map((source) => (
										<BreakdownBar
											key={source.name}
											name={source.name}
											percentage={source.percentage}
											color="bg-blue-600"
										/>
									))}
								</div>
							) : (
								<AnalyticsEmptyState icon={TrendingUp} />
							)}
						</CardContent>
					</Card>
 
					{/* Devices */}
					<Card>
						<CardHeader>
							<CardTitle>Devices</CardTitle>
						</CardHeader>
						<CardContent>
							{isLoading ? (
								<div className="space-y-4">
									{[1, 2, 3].map((i) => (
										<div key={i} className="space-y-2">
											<div className="flex items-center justify-between">
												<div className="h-3 w-20 bg-background-muted rounded animate-pulse" />
												<div className="h-3 w-12 bg-background-muted rounded animate-pulse" />
											</div>
											<div className="h-2 bg-background-muted rounded-full animate-pulse" />
										</div>
									))}
								</div>
							) : deviceBreakdown.length > 0 ? (
								<div className="space-y-4">
									{deviceBreakdown.map((device) => (
										<BreakdownBar
											key={device.name}
											name={device.name}
											percentage={device.percentage}
											color="bg-purple-600"
										/>
									))}
								</div>
							) : (
								<AnalyticsEmptyState icon={MousePointerClick} />
							)}
						</CardContent>
					</Card>
 
					{/* Top Cities */}
					<Card>
						<CardHeader>
							<CardTitle>Top Cities</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-24 bg-background-muted rounded animate-pulse" />
											<div className="h-4 w-16 bg-background-muted rounded animate-pulse" />
										</div>
									))}
								</div>
							) : cityBreakdown.length > 0 ? (
								<div className="space-y-4">
									{cityBreakdown.map((city, index) => (
										<RankedListItem
											key={city.city}
											rank={index + 1}
											label={city.city}
											value={`${city.count.toLocaleString()} visits`}
										/>
									))}
								</div>
							) : (
								<AnalyticsEmptyState icon={Eye} />
							)}
						</CardContent>
					</Card>
				</div>
			</div>
	);
}