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 | export const dynamic = "force-dynamic"; /** * Analytics Overview API Route * * Provides analytics data for the admin dashboard. * GET - Get analytics overview metrics */ import { NextRequest, NextResponse } from 'next/server'; import { withAdmin, withErrorHandling, successResponse, ApiSuccessResponse, ApiErrorResponse } from "@/lib/api"; import { prisma } from "@/lib/prisma"; /** * Get start date based on range string */ function getStartDate(range: string): Date { const now = new Date(); switch (range) { case "1d": return new Date(now.getTime() - 24 * 60 * 60 * 1000); case "7d": return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); case "30d": return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000); case "90d": return new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000); default: return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000); } } /** * GET /api/admin/analytics/overview * Get analytics overview data * Query params: range (1d|7d|30d|90d) */ async function handleGet( request: NextRequest ): Promise<NextResponse<ApiSuccessResponse<{ pageViews: number; uniqueVisitors: number; sessions: number; avgSessionDuration: number; avgPageViewsPerSession: number; bounceRate: number; topPages: Array<{ path: string; count: number }>; topEvents: Array<{ eventName: string; count: number }>; conversions: Array<{ eventName: string; count: number }>; deviceBreakdown: Array<{ deviceType: string; count: number }>; trafficSources: Array<{ source: string; count: number }>; dailyStats: Array<{ date: string; pageViews: number; uniqueVisitors: number; sessions: number; avgSessionDuration: number; bounceRate: number; }>; }> | ApiErrorResponse>> { const { searchParams } = new URL(request.url); const range = searchParams.get("range") || "7d"; const startDate = getStartDate(range); // Get overview metrics in parallel const [ pageViewCount, sessionStats, uniqueVisitors, topPages, topEvents, conversionEvents, deviceBreakdown, trafficSources, ] = await Promise.all([ // Total page views prisma.analyticsPageView.count({ where: { createdAt: { gte: startDate } } }), // Session metrics prisma.analyticsSession.aggregate({ where: { startedAt: { gte: startDate } }, _count: true, _avg: { duration: true, pageViews: true } }), // Unique visitors (distinct visitorIds) prisma.analyticsSession.findMany({ where: { startedAt: { gte: startDate } }, select: { visitorId: true }, distinct: ["visitorId"] }), // Top pages prisma.analyticsPageView.groupBy({ by: ["path"], where: { createdAt: { gte: startDate } }, _count: { path: true }, orderBy: { _count: { path: "desc" } }, take: 10 }), // Top events prisma.analyticsEvent.groupBy({ by: ["eventName"], where: { createdAt: { gte: startDate } }, _count: { eventName: true }, orderBy: { _count: { eventName: "desc" } }, take: 10 }), // Conversion events - check both direct event names AND funnel step events // Funnel events are stored with eventName="funnel_step" and step_id in properties prisma.$queryRaw<Array<{ step_id: string; count: bigint }>>` SELECT JSON_UNQUOTE(JSON_EXTRACT(properties, '$.step_id')) as step_id, COUNT(*) as count FROM analytics_events WHERE created_at >= ${startDate} AND event_type = 'funnel' AND event_name = 'funnel_step' AND JSON_EXTRACT(properties, '$.step_id') IN ('purchase', 'add_to_cart', 'signup_completed', 'begin_checkout') GROUP BY step_id `, // Device breakdown prisma.analyticsSession.groupBy({ by: ["deviceType"], where: { startedAt: { gte: startDate } }, _count: { deviceType: true } }), // Traffic sources prisma.analyticsSession.groupBy({ by: ["source"], where: { startedAt: { gte: startDate }, source: { not: null } }, _count: { source: true }, orderBy: { _count: { source: "desc" } }, take: 5 }), ]); // Calculate bounce rate const bouncedSessions = await prisma.analyticsSession.count({ where: { startedAt: { gte: startDate }, pageViews: 1 } }); const bounceRate = sessionStats._count > 0 ? Math.round((bouncedSessions / sessionStats._count) * 100) : 0; // Get daily breakdown for charts const dailyStatsFromDb = await prisma.analyticsDaily.findMany({ where: { date: { gte: startDate } }, orderBy: { date: "asc" } }); // Define type for daily stats we need type DailyStatsEntry = { date: Date; pageViews: number; uniqueVisitors: number; sessions: number; avgSessionDuration: number; bounceRate: number; }; let dailyStats: DailyStatsEntry[]; // If no daily stats exist, generate from page views and sessions if (dailyStatsFromDb.length === 0) { const pageViewsByDay = await prisma.$queryRaw<Array<{ date: string; count: bigint; visitors: bigint }>>` SELECT DATE(created_at) as date, COUNT(*) as count, COUNT(DISTINCT visitor_id) as visitors FROM analytics_page_views WHERE created_at >= ${startDate} GROUP BY DATE(created_at) ORDER BY date ASC `; const sessionsByDay = await prisma.$queryRaw<Array<{ date: string; count: bigint; avg_duration: number | null }>>` SELECT DATE(started_at) as date, COUNT(*) as count, AVG(duration) as avg_duration FROM analytics_sessions WHERE started_at >= ${startDate} GROUP BY DATE(started_at) ORDER BY date ASC `; // Merge the data const dateMap = new Map<string, DailyStatsEntry>(); for (const pv of pageViewsByDay) { const dateStr = typeof pv.date === 'string' ? pv.date : new Date(pv.date).toISOString().split('T')[0]; dateMap.set(dateStr, { date: new Date(dateStr), pageViews: Number(pv.count), uniqueVisitors: Number(pv.visitors), sessions: 0, avgSessionDuration: 0, bounceRate: 0 }); } for (const s of sessionsByDay) { const dateStr = typeof s.date === 'string' ? s.date : new Date(s.date).toISOString().split('T')[0]; const existing = dateMap.get(dateStr) || { date: new Date(dateStr), pageViews: 0, uniqueVisitors: 0, sessions: 0, avgSessionDuration: 0, bounceRate: 0 }; existing.sessions = Number(s.count); existing.avgSessionDuration = Math.round(s.avg_duration || 0); dateMap.set(dateStr, existing); } dailyStats = Array.from(dateMap.values()).sort((a, b) => a.date.getTime() - b.date.getTime()); } else { dailyStats = dailyStatsFromDb.map((d) => ({ date: d.date, pageViews: d.pageViews, uniqueVisitors: d.uniqueVisitors, sessions: d.sessions, avgSessionDuration: d.avgSessionDuration, bounceRate: d.bounceRate })); } return successResponse({ pageViews: pageViewCount, uniqueVisitors: uniqueVisitors.length, sessions: sessionStats._count, avgSessionDuration: Math.round(sessionStats._avg.duration || 0), avgPageViewsPerSession: Math.round((sessionStats._avg.pageViews || 0) * 10) / 10, bounceRate, topPages: topPages.map((p) => ({ path: p.path, count: p._count.path })), topEvents: topEvents.map((e) => ({ eventName: e.eventName, count: e._count.eventName })), conversions: conversionEvents.map((c) => ({ eventName: c.step_id, count: Number(c.count) })), deviceBreakdown: deviceBreakdown.map((d) => ({ deviceType: d.deviceType || "unknown", count: d._count.deviceType })), trafficSources: trafficSources.map((s) => ({ source: s.source || "direct", count: s._count.source })), dailyStats: dailyStats.map((d) => ({ date: d.date.toISOString().split("T")[0], pageViews: d.pageViews, uniqueVisitors: d.uniqueVisitors, sessions: d.sessions, avgSessionDuration: d.avgSessionDuration, bounceRate: d.bounceRate })) }); } export const GET = withErrorHandling(withAdmin(handleGet)); |