Download src/app/api/stats/route.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 7.49 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/stats/route.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/app/api/stats/route.ts
-
curl -L -o route.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/app/api/stats/route.ts
7.49 kB
| import { NextRequest, NextResponse } from "next/server"; | |
| import { prisma } from "@/lib/db"; | |
| import { withApiError } from "@/lib/api-error"; | |
| /** Valid time windows for the XP chart (in days). */ | |
| const VALID_WINDOWS = [7, 30, 90] as const; | |
| type ChartWindow = (typeof VALID_WINDOWS)[number]; | |
| function parseWindowDays(raw: string | null): ChartWindow { | |
| const n = parseInt(raw ?? "", 10); | |
| return (VALID_WINDOWS as readonly number[]).includes(n) | |
| ? (n as ChartWindow) | |
| : 30; | |
| } | |
| /** Maximum number of activities returned per page. */ | |
| const MAX_ACTIVITY_LIMIT = 50; | |
| /** Default number of activities returned per page. */ | |
| const DEFAULT_ACTIVITY_LIMIT = 25; | |
| /** Valid category values for filtering. */ | |
| const VALID_CATEGORIES = new Set([ | |
| "chess", | |
| "reading", | |
| "feynman", | |
| "logic", | |
| "critical-thinking", | |
| "quests", | |
| ]); | |
| function parseActivityPagination( | |
| rawOffset: string | null, | |
| rawLimit: string | null, | |
| ): { offset: number; limit: number } { | |
| const offset = Math.max(0, parseInt(rawOffset ?? "0", 10) || 0); | |
| const parsed = parseInt(rawLimit ?? String(DEFAULT_ACTIVITY_LIMIT), 10); | |
| const limit = Number.isFinite(parsed) && parsed > 0 | |
| ? Math.min(parsed, MAX_ACTIVITY_LIMIT) | |
| : DEFAULT_ACTIVITY_LIMIT; | |
| return { offset, limit }; | |
| } | |
| /** | |
| * Parse the ?activityCategory query param. | |
| * Returns the category string if valid, or null for "all" / invalid values. | |
| */ | |
| function parseActivityCategory(raw: string | null): string | null { | |
| if (!raw || raw === "all") return null; | |
| return VALID_CATEGORIES.has(raw) ? raw : null; | |
| } | |
| /** | |
| * GET /api/stats | |
| * | |
| * Returns aggregated stats for the Stats page: | |
| * - dailyXp: XP earned per day (configurable window: 7, 30, or 90 days; default 30) | |
| * - windowDays: the resolved time window used for dailyXp | |
| * - categoryBreakdown: total XP and exercise count per category | |
| * - recentActivities: paginated activity slice (default first 25) | |
| * - activityTotal: total number of activities across all time (for pagination) | |
| * - summary: overall totals | |
| * | |
| * Query params: | |
| * ?days=7|30|90 — chart time window (default: 30; invalid values fall back to 30) | |
| * ?activityOffset=N — skip N activities (default: 0) | |
| * ?activityLimit=N — return up to N activities (default: 25; max: 50) | |
| * ?activityCategory=<cat> — filter activity log to one category (default: all) | |
| * valid values: chess, reading, feynman, logic, critical-thinking, quests | |
| * "all" or missing/invalid values → no filter applied | |
| */ | |
| export const GET = withApiError(async (request: NextRequest) => { | |
| const { searchParams } = new URL(request.url); | |
| const windowDays = parseWindowDays(searchParams.get("days")); | |
| const { offset: activityOffset, limit: activityLimit } = | |
| parseActivityPagination( | |
| searchParams.get("activityOffset"), | |
| searchParams.get("activityLimit"), | |
| ); | |
| const activityCategory = parseActivityCategory(searchParams.get("activityCategory")); | |
| const user = await prisma.user.findFirst({ | |
| where: { id: 1 }, | |
| include: { categorySkills: true }, | |
| }); | |
| if (!user) { | |
| return NextResponse.json({ error: "No user found", status: 404 }, { status: 404 }); | |
| } | |
| // Daily logs for the selected window | |
| const windowStart = new Date(); | |
| windowStart.setUTCDate(windowStart.getUTCDate() - windowDays); | |
| windowStart.setUTCHours(0, 0, 0, 0); | |
| const dailyLogs = await prisma.dailyLog.findMany({ | |
| where: { | |
| userId: 1, | |
| date: { gte: windowStart }, | |
| }, | |
| orderBy: { date: "asc" }, | |
| }); | |
| // All activities for category breakdown and summary stats | |
| const allActivities = await prisma.activity.findMany({ | |
| where: { userId: 1 }, | |
| orderBy: { createdAt: "desc" }, | |
| }); | |
| // Category breakdown | |
| const categoryBreakdown: Record< | |
| string, | |
| { totalXp: number; count: number; avgScore: number; totalDuration: number } | |
| > = {}; | |
| // Track scored-activity counts separately to compute accurate averages | |
| const categoryScoreCount: Record<string, number> = {}; | |
| for (const a of allActivities) { | |
| if (!categoryBreakdown[a.category]) { | |
| categoryBreakdown[a.category] = { | |
| totalXp: 0, | |
| count: 0, | |
| avgScore: 0, | |
| totalDuration: 0, | |
| }; | |
| categoryScoreCount[a.category] = 0; | |
| } | |
| const cat = categoryBreakdown[a.category]; | |
| cat.totalXp += a.totalXp; | |
| cat.count += 1; | |
| if (a.score !== null) { | |
| cat.avgScore += a.score; | |
| categoryScoreCount[a.category] += 1; | |
| } | |
| if (a.durationSecs !== null) cat.totalDuration += a.durationSecs; | |
| } | |
| // Compute averages — divide by number of scored activities, not total count | |
| for (const [category, cat] of Object.entries(categoryBreakdown)) { | |
| const scoredCount = categoryScoreCount[category] ?? 0; | |
| if (scoredCount > 0) { | |
| cat.avgScore = Math.round((cat.avgScore / scoredCount) * 100) / 100; | |
| } else { | |
| cat.avgScore = 0; | |
| } | |
| } | |
| // Filtered activity pool for the log (category breakdown and summary use full allActivities) | |
| const filteredActivities = activityCategory | |
| ? allActivities.filter( | |
| (a) => a.category.toLowerCase() === activityCategory, | |
| ) | |
| : allActivities; | |
| // Paginated activity slice (from filtered pool) | |
| const activityTotal = filteredActivities.length; | |
| const recentActivities = filteredActivities | |
| .slice(activityOffset, activityOffset + activityLimit) | |
| .map((a) => ({ | |
| id: a.id, | |
| category: a.category, | |
| exerciseType: a.exerciseType, | |
| description: a.description, | |
| baseXp: a.baseXp, | |
| qualityBonus: a.qualityBonus, | |
| isCriticalHit: a.isCriticalHit, | |
| totalXp: a.totalXp, | |
| score: a.score, | |
| durationSecs: a.durationSecs, | |
| createdAt: a.createdAt, | |
| })); | |
| // Summary stats | |
| const totalExercises = allActivities.length; | |
| const totalXpEarned = allActivities.reduce((sum, a) => sum + a.totalXp, 0); | |
| const totalDuration = allActivities.reduce( | |
| (sum, a) => sum + (a.durationSecs ?? 0), | |
| 0 | |
| ); | |
| const criticalHits = allActivities.filter((a) => a.isCriticalHit).length; | |
| const goalDaysMet = dailyLogs.filter((l) => l.goalMet).length; | |
| // Correct solves: activities with a non-null score > 0 | |
| const correctSolves = allActivities.filter( | |
| (a) => a.score !== null && a.score > 0, | |
| ).length; | |
| // Scored exercises: activities that have any score (null excluded) | |
| const scoredExercises = allActivities.filter((a) => a.score !== null).length; | |
| const correctSolveRate = | |
| scoredExercises > 0 | |
| ? Math.round((correctSolves / scoredExercises) * 1000) / 10 | |
| : 0; | |
| return NextResponse.json({ | |
| windowDays, | |
| /** The active activity category filter. null means "all categories". */ | |
| activityCategory: activityCategory ?? null, | |
| dailyXp: dailyLogs.map( | |
| (l: { date: Date; xpEarned: number; activityCount: number; goalMet: boolean }) => ({ | |
| date: l.date, | |
| xpEarned: l.xpEarned, | |
| activityCount: l.activityCount, | |
| goalMet: l.goalMet, | |
| }) | |
| ), | |
| categoryBreakdown, | |
| recentActivities, | |
| activityTotal, | |
| summary: { | |
| totalExercises, | |
| totalXpEarned, | |
| totalDuration, | |
| criticalHits, | |
| criticalHitRate: | |
| totalExercises > 0 | |
| ? Math.round((criticalHits / totalExercises) * 1000) / 10 | |
| : 0, | |
| correctSolves, | |
| correctSolveRate, | |
| goalDaysMet, | |
| currentStreak: user.streak, | |
| longestStreak: user.longestStreak, | |
| level: user.level, | |
| }, | |
| }); | |
| }); | |