RotNot / src /app /api /profile /route.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
5.18 kB
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { xpForLevel } from "@/config/xp";
import { withApiError } from "@/lib/api-error";
import {
getPlayerStats,
getBestRating,
type ChessComPlayerStats,
} from "@/lib/chesscom";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface ChessComStatsResult {
bestRating: number | null;
rapid: number | null;
blitz: number | null;
bullet: number | null;
daily: number | null;
rapidBest: number | null;
blitzBest: number | null;
bulletBest: number | null;
puzzleRushBest: number | null;
tacticsHighest: number | null;
}
export const GET = withApiError(async () => {
const user = await prisma.user.findFirst({
where: { id: 1 },
include: {
categorySkills: true,
unlocks: { include: { node: true } },
},
});
if (!user) {
return NextResponse.json({ error: "No user found", status: 404 }, { status: 404 });
}
// All skill tree nodes
const allNodes = await prisma.skillTreeNode.findMany({
orderBy: [{ category: "asc" }, { levelRequired: "asc" }],
});
// Activity count and time totals
const activities = await prisma.activity.findMany({
where: { userId: 1 },
select: { category: true, durationSecs: true, createdAt: true, totalXp: true },
});
const totalExercises = activities.length;
const totalTimeSecs = activities.reduce((s: number, a: { durationSecs: number | null }) => s + (a.durationSecs ?? 0), 0);
const totalXpAllTime = activities.reduce((s: number, a: { totalXp: number }) => s + a.totalXp, 0);
// Per-category exercise counts
const exercisesByCat: Record<string, number> = {};
for (const a of activities) {
exercisesByCat[a.category] = (exercisesByCat[a.category] ?? 0) + 1;
}
// Streak info
const longestStreak = user.longestStreak;
const currentStreak = user.streak;
const unlockedNodeIds = new Set(user.unlocks.map((u: { nodeId: number }) => u.nodeId));
// Last 90 days of daily activity for streak calendar heatmap
const ninetyDaysAgo = new Date();
ninetyDaysAgo.setUTCDate(ninetyDaysAgo.getUTCDate() - 89);
ninetyDaysAgo.setUTCHours(0, 0, 0, 0);
const dailyLogs = await prisma.dailyLog.findMany({
where: { userId: 1, date: { gte: ninetyDaysAgo } },
orderBy: { date: "asc" },
select: { date: true, xpEarned: true, activityCount: true, goalMet: true },
});
// Chess.com ratings (optional — only fetched when username is set)
let chesscomStats: ChessComStatsResult | null = null;
if (user.chesscomUsername) {
const raw: ChessComPlayerStats | null = await getPlayerStats(user.chesscomUsername);
if (raw) {
chesscomStats = {
bestRating: getBestRating(raw),
rapid: raw.chess_rapid?.last?.rating ?? null,
blitz: raw.chess_blitz?.last?.rating ?? null,
bullet: raw.chess_bullet?.last?.rating ?? null,
daily: raw.chess_daily?.last?.rating ?? null,
rapidBest: raw.chess_rapid?.best?.rating ?? null,
blitzBest: raw.chess_blitz?.best?.rating ?? null,
bulletBest: raw.chess_bullet?.best?.rating ?? null,
puzzleRushBest: raw.puzzle_rush?.best?.score ?? null,
tacticsHighest: raw.tactics?.highest?.rating ?? null,
};
}
}
return NextResponse.json({
user: {
id: user.id,
name: user.name,
level: user.level,
totalXp: user.totalXp,
currentXp: user.currentXp,
xpToNextLevel: xpForLevel(user.level + 1),
title: user.title,
dailyGoalXp: user.dailyGoalXp,
streak: currentStreak,
longestStreak,
streakFreezes: user.streakFreezes,
lichessUsername: user.lichessUsername,
chesscomUsername: user.chesscomUsername,
createdAt: user.createdAt,
},
stats: {
totalExercises,
totalTimeSecs,
totalXpAllTime,
exercisesByCat,
},
categorySkills: user.categorySkills.map((cs: { category: string; level: number; totalXp: number; currentXp: number; xpToNext: number }) => ({
category: cs.category,
level: cs.level,
totalXp: cs.totalXp,
currentXp: cs.currentXp,
xpToNext: cs.xpToNext,
})),
skillTree: allNodes.map((n: { id: number; category: string; name: string; description: string; levelRequired: number; parentNodeId: number | null; nodeType: string }) => ({
id: n.id,
category: n.category,
name: n.name,
description: n.description,
levelRequired: n.levelRequired,
parentNodeId: n.parentNodeId,
nodeType: n.nodeType,
unlocked: unlockedNodeIds.has(n.id),
})),
unlocks: user.unlocks.map((u: { nodeId: number; node: { name: string }; unlockedAt: Date }) => ({
nodeId: u.nodeId,
nodeName: u.node.name,
unlockedAt: u.unlockedAt,
})),
chesscomStats,
dailyActivity: dailyLogs.map((l: { date: Date; xpEarned: number; activityCount: number; goalMet: boolean }) => ({
date: l.date,
xpEarned: l.xpEarned,
activityCount: l.activityCount,
goalMet: l.goalMet,
})),
});
});