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 | 31x 31x 31x 31x 31x 16x 16x 16x 16x 16x 14x 12x 1x 1x 15x 31x 16x 16x 31x 24x 24x 14x 10x 4x 31x 31x 31x 31x 31x 31x 7x 5x 2x 31x 62x 62x 2x 80x 2x 64x 5x 48x 5x 80x 5x | import { useState, useEffect, useCallback } from "react";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "../components/ui/card";
import {
StatCard,
AnalyticsEmptyState,
BreakdownBar,
RankedListItem,
} from "../components/analytics";
import { usePro } from "../lib/pro-context";
import { StickyPageHeader } from "../components/ui/sticky-page-header";
import { proApi } from "../lib/api";
import {
TrendingUp,
Eye,
MousePointerClick,
MessageCircle,
Mail,
Download,
BarChart3,
} from "lucide-react";
import { Button } from "../components/ui/button";
import { downloadCsv } from "../lib/csv";
type ProStats = {
// Summary stats
summary: {
totalPageViews: number;
totalProjectClicks: number;
totalWhatsappClicks: number;
totalCallClicks: number;
totalInquiries: number;
views7d: number;
views30d: number;
clicks7d: number;
clicks30d: number;
lastViewAt: string | null;
lastClickAt: string | null;
};
// Daily trend data
daily: {
date: string;
pageViews: number;
projectClicks: number;
imageClicks: number;
whatsappClicks: number;
callClicks: number;
inquiryClicks: number;
uniqueSessions: number;
}[];
// Top projects
topProjects: {
id: string;
title: string;
slug: string | null;
views: number;
}[];
// Breakdowns
sources: Record<string, number>;
devices: Record<string, number>;
cities: Record<string, number>;
};
export function AnalyticsPage() {
const { proId } = usePro();
const [stats, setStats] = useState<ProStats | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState("");
const loadAnalytics = useCallback(async () => {
Iif (!proId) return;
setIsLoading(true);
setError("");
try {
const response = await proApi.getProStats(proId);
if (response.data) {
setStats(response.data);
}
} catch (err) {
console.error("Failed to load analytics:", err);
setError("Failed to load analytics data");
} finally {
setIsLoading(false);
}
}, [proId]);
useEffect(() => {
Eif (proId) {
loadAnalytics();
}
}, [proId, loadAnalytics]);
// 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 handleExportCsv = () => {
if (!stats?.daily || stats.daily.length === 0) return;
const csvData = stats.daily.map((day) => ({
Date: day.date,
"Page Views": day.pageViews,
"Project Clicks": day.projectClicks,
"Image Clicks": day.imageClicks,
"WhatsApp Clicks": day.whatsappClicks,
"Call Clicks": day.callClicks,
"Contact Clicks": day.inquiryClicks,
"Unique Sessions": day.uniqueSessions,
}));
downloadCsv(csvData, "analytics-report");
};
const recentStatCards = [
{
name: "Profile Views",
value: stats?.summary?.views7d ?? 0,
subtext: "Last 7 days",
icon: Eye,
color: "text-blue-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",
},
];
const allTimeStatCards = [
{
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-6">
<StickyPageHeader>
<div className="flex items-center justify-between w-full">
<h1 className="text-2xl font-bold text-foreground-default flex items-center gap-2">
<BarChart3 className="h-6 w-6" />
Analytics
</h1>
{stats?.daily && stats.daily.length > 0 && (
<Button variant="outline" size="sm" onClick={handleExportCsv}>
<Download className="h-4 w-4" />
Export CSV
</Button>
)}
</div>
</StickyPageHeader>
{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 lg:grid-cols-2 gap-6">
<div className="space-y-3">
<h2 className="text-sm font-medium text-foreground-muted uppercase tracking-wide">Last 7 Days</h2>
<div className="grid grid-cols-2 gap-3 sm:gap-6">
{recentStatCards.map((stat) => (
<StatCard key={stat.name} {...stat} isLoading={isLoading} />
))}
</div>
</div>
<div className="space-y-3">
<h2 className="text-sm font-medium text-foreground-muted uppercase tracking-wide">All Time</h2>
<div className="grid grid-cols-2 gap-3 sm:gap-6">
{allTimeStatCards.map((stat) => (
<StatCard key={stat.name} {...stat} isLoading={isLoading} />
))}
</div>
</div>
</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-subtle 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={`/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>
);
}
|