/** * Unit tests for getPerformanceSummary (DB-backed). * * Covers: * - User-level fields: streakDays, longestStreak * - All 6 categories always present in response * - Per-category: attempts, totalXp, avgScore, avgDurationSecs, * successRate, level, label, trend * - Overall weighted score computation * - Active days deduplication (same-day activities count once) * - lastActivityAt ISO string / null when no activities * - DB query params: userId filter, chronological ordering * - Error propagation (findUniqueOrThrow throws → function throws) * - Category skill level defaults to 1 when no skill row exists */ import { describe, it, expect, vi, beforeEach } from "vitest"; // ── Mock Prisma ────────────────────────────────────────────────────────────── const mockUserFindUniqueOrThrow = vi.fn(); const mockActivityFindMany = vi.fn(); vi.mock("@/lib/db", () => ({ prisma: { user: { findUniqueOrThrow: (...args: unknown[]) => mockUserFindUniqueOrThrow(...args), }, activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args), }, }, })); // Import after mock hoisting import { getPerformanceSummary } from "../performance"; import { CATEGORIES, CATEGORY_LABELS } from "@/config/xp"; // ── Helpers ────────────────────────────────────────────────────────────────── function makeUser(overrides: Record = {}) { return { id: 1, name: "Player One", streak: 5, longestStreak: 14, level: 3, totalXp: 1200, currentXp: 200, xpToNextLevel: 350, title: "Budding Thinker", dailyGoalXp: 100, streakFreezes: 2, lichessUsername: null, chesscomUsername: null, createdAt: new Date("2026-01-01T00:00:00Z"), categorySkills: [], ...overrides, }; } function makeCategorySkill(category: string, level: number) { return { id: Math.floor(Math.random() * 10000), userId: 1, category, level, totalXp: level * 100, currentXp: 50, xpToNext: 200, }; } function makeActivity( overrides: Partial<{ id: number; userId: number; category: string; exerciseType: string; description: string; baseXp: number; qualityBonus: number; isCriticalHit: boolean; totalXp: number; score: number | null; durationSecs: number | null; metadata: string | null; createdAt: Date; }> = {}, ) { return { id: Math.floor(Math.random() * 100000), userId: 1, category: "chess", exerciseType: "puzzle", description: "Lichess puzzle", baseXp: 20, qualityBonus: 10, isCriticalHit: false, totalXp: 30, score: 0.8, durationSecs: 120, metadata: null, createdAt: new Date("2026-03-20T10:00:00Z"), ...overrides, }; } // ── Tests ──────────────────────────────────────────────────────────────────── describe("getPerformanceSummary", () => { beforeEach(() => { vi.clearAllMocks(); }); // ── User-level fields ────────────────────────────────────────────────────── describe("user fields", () => { it("returns streakDays from user.streak", async () => { mockUserFindUniqueOrThrow.mockResolvedValue( makeUser({ streak: 7, longestStreak: 30 }), ); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.streakDays).toBe(7); }); it("returns longestStreak from user.longestStreak", async () => { mockUserFindUniqueOrThrow.mockResolvedValue( makeUser({ streak: 2, longestStreak: 45 }), ); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.longestStreak).toBe(45); }); it("queries user with correct userId", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); await getPerformanceSummary(42); expect(mockUserFindUniqueOrThrow).toHaveBeenCalledWith( expect.objectContaining({ where: { id: 42 } }), ); }); it("queries user with categorySkills included", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); await getPerformanceSummary(1); expect(mockUserFindUniqueOrThrow).toHaveBeenCalledWith( expect.objectContaining({ include: { categorySkills: true }, }), ); }); it("propagates findUniqueOrThrow errors", async () => { mockUserFindUniqueOrThrow.mockRejectedValue(new Error("User not found")); mockActivityFindMany.mockResolvedValue([]); await expect(getPerformanceSummary(999)).rejects.toThrow("User not found"); }); }); // ── DB query params ──────────────────────────────────────────────────────── describe("DB query params", () => { it("queries activities with correct userId", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); await getPerformanceSummary(7); expect(mockActivityFindMany).toHaveBeenCalledWith( expect.objectContaining({ where: { userId: 7 } }), ); }); it("queries activities ordered by createdAt ascending (for trend calc)", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); await getPerformanceSummary(1); expect(mockActivityFindMany).toHaveBeenCalledWith( expect.objectContaining({ orderBy: { createdAt: "asc" } }), ); }); }); // ── Category shape ───────────────────────────────────────────────────────── describe("category shape", () => { it("always returns all 6 categories", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.categories).toHaveLength(7); const returnedCats = result.categories.map((c) => c.category).sort(); expect(returnedCats).toEqual([...CATEGORIES].sort()); }); it("uses canonical category labels", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); for (const cat of result.categories) { expect(cat.label).toBe(CATEGORY_LABELS[cat.category]); } }); it("defaults level to 1 when no CategorySkill row exists", async () => { mockUserFindUniqueOrThrow.mockResolvedValue( makeUser({ categorySkills: [] }), ); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); for (const cat of result.categories) { expect(cat.level).toBe(1); } }); it("reads level from CategorySkill when present", async () => { mockUserFindUniqueOrThrow.mockResolvedValue( makeUser({ categorySkills: [ makeCategorySkill("chess", 8), makeCategorySkill("feynman", 5), ], }), ); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); const chess = result.categories.find((c) => c.category === "chess")!; const feynman = result.categories.find((c) => c.category === "feynman")!; expect(chess.level).toBe(8); expect(feynman.level).toBe(5); }); }); // ── Empty state ──────────────────────────────────────────────────────────── describe("empty activity state", () => { it("returns 0 attempts for all categories", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); for (const cat of result.categories) { expect(cat.attempts).toBe(0); } }); it("returns 0 totalXp for all categories", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); for (const cat of result.categories) { expect(cat.totalXp).toBe(0); } }); it("returns 0 avgScore for all categories", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); for (const cat of result.categories) { expect(cat.avgScore).toBe(0); } }); it("returns null avgDurationSecs for all categories", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); for (const cat of result.categories) { expect(cat.avgDurationSecs).toBeNull(); } }); it("returns 0 successRate for all categories", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); for (const cat of result.categories) { expect(cat.successRate).toBe(0); } }); it("returns trend='new' for all categories", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); for (const cat of result.categories) { expect(cat.trend).toBe("new"); } }); it("returns overallScore=0", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.overallScore).toBe(0); }); it("returns totalExercises=0", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.totalExercises).toBe(0); }); it("returns activeDays=0", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.activeDays).toBe(0); }); it("returns lastActivityAt=null", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.lastActivityAt).toBeNull(); }); }); // ── Per-category aggregation ─────────────────────────────────────────────── describe("per-category aggregation", () => { it("counts attempts per category", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", score: 0.8, totalXp: 30 }), makeActivity({ category: "chess", score: 0.7, totalXp: 25 }), makeActivity({ category: "reading", score: 0.9, totalXp: 40 }), ]); const result = await getPerformanceSummary(1); const chess = result.categories.find((c) => c.category === "chess")!; const reading = result.categories.find((c) => c.category === "reading")!; const logic = result.categories.find((c) => c.category === "logic")!; expect(chess.attempts).toBe(2); expect(reading.attempts).toBe(1); expect(logic.attempts).toBe(0); }); it("sums totalXp per category", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", totalXp: 30 }), makeActivity({ category: "chess", totalXp: 45 }), makeActivity({ category: "feynman", totalXp: 80 }), ]); const result = await getPerformanceSummary(1); const chess = result.categories.find((c) => c.category === "chess")!; const feynman = result.categories.find((c) => c.category === "feynman")!; expect(chess.totalXp).toBe(75); expect(feynman.totalXp).toBe(80); }); it("computes avgScore from non-null scores only", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", score: 0.8 }), makeActivity({ category: "chess", score: 0.6 }), makeActivity({ category: "chess", score: null }), ]); const result = await getPerformanceSummary(1); const chess = result.categories.find((c) => c.category === "chess")!; // (0.8 + 0.6) / 2 = 0.7 expect(chess.avgScore).toBe(0.7); }); it("rounds avgScore to 2 decimal places", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", score: 0.333 }), makeActivity({ category: "chess", score: 0.667 }), makeActivity({ category: "chess", score: 0.5 }), ]); const result = await getPerformanceSummary(1); const chess = result.categories.find((c) => c.category === "chess")!; // (0.333 + 0.667 + 0.5) / 3 = 0.5 expect(chess.avgScore).toBe(0.5); }); it("returns avgScore=0 when all scores are null", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", score: null }), makeActivity({ category: "chess", score: null }), ]); const result = await getPerformanceSummary(1); const chess = result.categories.find((c) => c.category === "chess")!; expect(chess.avgScore).toBe(0); }); it("computes avgDurationSecs from non-null durations", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "reading", durationSecs: 300 }), makeActivity({ category: "reading", durationSecs: 500 }), makeActivity({ category: "reading", durationSecs: null }), ]); const result = await getPerformanceSummary(1); const reading = result.categories.find((c) => c.category === "reading")!; // (300 + 500) / 2 = 400 expect(reading.avgDurationSecs).toBe(400); }); it("returns null avgDurationSecs when all durations are null", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", durationSecs: null }), ]); const result = await getPerformanceSummary(1); const chess = result.categories.find((c) => c.category === "chess")!; expect(chess.avgDurationSecs).toBeNull(); }); it("rounds avgDurationSecs to nearest integer", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "logic", durationSecs: 100 }), makeActivity({ category: "logic", durationSecs: 101 }), makeActivity({ category: "logic", durationSecs: 102 }), ]); const result = await getPerformanceSummary(1); const logic = result.categories.find((c) => c.category === "logic")!; // (100 + 101 + 102) / 3 = 101 expect(logic.avgDurationSecs).toBe(101); }); it("computes successRate using score >= 0.6 threshold", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "feynman", score: 0.9 }), // pass makeActivity({ category: "feynman", score: 0.6 }), // pass (boundary) makeActivity({ category: "feynman", score: 0.59 }), // fail makeActivity({ category: "feynman", score: 0.3 }), // fail ]); const result = await getPerformanceSummary(1); const feynman = result.categories.find((c) => c.category === "feynman")!; // 2 out of 4 pass → 50% expect(feynman.successRate).toBe(50); }); it("computes trend from scored activities in chronological order", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); // Older scores low, recent scores high → improving mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "quests", score: 0.3, createdAt: new Date("2026-03-01T10:00:00Z"), }), makeActivity({ category: "quests", score: 0.3, createdAt: new Date("2026-03-10T10:00:00Z"), }), makeActivity({ category: "quests", score: 0.9, createdAt: new Date("2026-03-20T10:00:00Z"), }), makeActivity({ category: "quests", score: 0.85, createdAt: new Date("2026-03-21T10:00:00Z"), }), ]); const result = await getPerformanceSummary(1); const quests = result.categories.find((c) => c.category === "quests")!; expect(quests.trend).toBe("improving"); }); it("returns trend='new' for categories with fewer than 3 scored activities", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "critical-thinking", score: 0.7 }), makeActivity({ category: "critical-thinking", score: 0.8 }), ]); const result = await getPerformanceSummary(1); const ct = result.categories.find( (c) => c.category === "critical-thinking", )!; expect(ct.trend).toBe("new"); }); }); // ── Overall score ────────────────────────────────────────────────────────── describe("overallScore", () => { it("computes weighted average of category successRates", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); // chess: 2 activities, both pass → successRate=100 // reading: 2 activities, 1 pass, 1 fail → successRate=50 // Total 4 activities weighted: (100*2 + 50*2) / 4 = 75 mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", score: 0.8 }), makeActivity({ category: "chess", score: 0.9 }), makeActivity({ category: "reading", score: 0.9 }), makeActivity({ category: "reading", score: 0.3 }), ]); const result = await getPerformanceSummary(1); expect(result.overallScore).toBe(75); }); it("returns 0 overallScore when no activities", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.overallScore).toBe(0); }); it("rounds overallScore to 1 decimal place", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); // chess: 3 activities, 2 pass → successRate = 66.7 // Only chess has activities → overallScore = 66.7 mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", score: 0.8 }), makeActivity({ category: "chess", score: 0.9 }), makeActivity({ category: "chess", score: 0.3 }), ]); const result = await getPerformanceSummary(1); expect(result.overallScore).toBe(66.7); }); }); // ── totalExercises ───────────────────────────────────────────────────────── describe("totalExercises", () => { it("sums all category attempts", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess" }), makeActivity({ category: "chess" }), makeActivity({ category: "reading" }), makeActivity({ category: "feynman" }), makeActivity({ category: "feynman" }), makeActivity({ category: "feynman" }), ]); const result = await getPerformanceSummary(1); expect(result.totalExercises).toBe(6); }); it("returns 0 when no activities", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.totalExercises).toBe(0); }); }); // ── Active days ──────────────────────────────────────────────────────────── describe("activeDays", () => { it("counts distinct UTC calendar days", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ createdAt: new Date("2026-03-18T08:00:00Z") }), makeActivity({ createdAt: new Date("2026-03-18T20:00:00Z") }), // same day makeActivity({ createdAt: new Date("2026-03-19T10:00:00Z") }), makeActivity({ createdAt: new Date("2026-03-21T15:00:00Z") }), ]); const result = await getPerformanceSummary(1); // 2026-03-18, 2026-03-19, 2026-03-21 → 3 distinct days expect(result.activeDays).toBe(3); }); it("returns 0 active days when no activities", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.activeDays).toBe(0); }); it("counts each unique day once regardless of number of activities", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); // 5 activities all on the same day mockActivityFindMany.mockResolvedValue([ makeActivity({ createdAt: new Date("2026-03-20T01:00:00Z") }), makeActivity({ createdAt: new Date("2026-03-20T05:00:00Z") }), makeActivity({ createdAt: new Date("2026-03-20T09:00:00Z") }), makeActivity({ createdAt: new Date("2026-03-20T14:00:00Z") }), makeActivity({ createdAt: new Date("2026-03-20T23:59:00Z") }), ]); const result = await getPerformanceSummary(1); expect(result.activeDays).toBe(1); }); it("uses UTC dates (not local), preventing timezone double-counting", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); // 23:00 UTC on Mar 19 and 01:00 UTC on Mar 20 are different UTC days mockActivityFindMany.mockResolvedValue([ makeActivity({ createdAt: new Date("2026-03-19T23:00:00Z") }), makeActivity({ createdAt: new Date("2026-03-20T01:00:00Z") }), ]); const result = await getPerformanceSummary(1); expect(result.activeDays).toBe(2); }); }); // ── lastActivityAt ───────────────────────────────────────────────────────── describe("lastActivityAt", () => { it("returns ISO string of the last activity when activities exist", async () => { const lastDate = new Date("2026-03-21T15:30:00.000Z"); mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ createdAt: new Date("2026-03-18T10:00:00Z") }), makeActivity({ createdAt: new Date("2026-03-20T12:00:00Z") }), makeActivity({ createdAt: lastDate }), ]); const result = await getPerformanceSummary(1); expect(result.lastActivityAt).toBe(lastDate.toISOString()); }); it("returns null when no activities exist", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([]); const result = await getPerformanceSummary(1); expect(result.lastActivityAt).toBeNull(); }); it("returns the chronologically last entry (activities sorted asc by DB query)", async () => { // DB returns activities in ascending order; last item = most recent const first = new Date("2026-03-01T10:00:00Z"); const middle = new Date("2026-03-10T10:00:00Z"); const last = new Date("2026-03-20T10:00:00Z"); mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ createdAt: first }), makeActivity({ createdAt: middle }), makeActivity({ createdAt: last }), ]); const result = await getPerformanceSummary(1); expect(result.lastActivityAt).toBe(last.toISOString()); }); }); // ── Multi-category mix ───────────────────────────────────────────────────── describe("multi-category scenario", () => { it("correctly isolates metrics per category with mixed activity pool", async () => { mockUserFindUniqueOrThrow.mockResolvedValue( makeUser({ streak: 3, longestStreak: 10, categorySkills: [ makeCategorySkill("chess", 4), makeCategorySkill("logic", 2), ], }), ); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess", score: 0.9, totalXp: 40, durationSecs: 180 }), makeActivity({ category: "chess", score: 0.4, totalXp: 20, durationSecs: 60 }), makeActivity({ category: "logic", score: 0.8, totalXp: 35, durationSecs: null }), makeActivity({ category: "logic", score: 0.7, totalXp: 30, durationSecs: null }), makeActivity({ category: "logic", score: 0.6, totalXp: 25, durationSecs: null }), ]); const result = await getPerformanceSummary(1); const chess = result.categories.find((c) => c.category === "chess")!; expect(chess.attempts).toBe(2); expect(chess.totalXp).toBe(60); expect(chess.avgScore).toBe(0.65); // (0.9+0.4)/2 expect(chess.avgDurationSecs).toBe(120); // (180+60)/2 expect(chess.successRate).toBe(50); // 1/2 pass expect(chess.level).toBe(4); const logic = result.categories.find((c) => c.category === "logic")!; expect(logic.attempts).toBe(3); expect(logic.totalXp).toBe(90); expect(logic.avgScore).toBeCloseTo(0.7, 1); // (0.8+0.7+0.6)/3 expect(logic.avgDurationSecs).toBeNull(); expect(logic.successRate).toBe(100); // all >= 0.6 expect(logic.level).toBe(2); // Reading category has no activities const reading = result.categories.find((c) => c.category === "reading")!; expect(reading.attempts).toBe(0); expect(reading.level).toBe(1); // default }); it("computes correct totalExercises across all categories", async () => { mockUserFindUniqueOrThrow.mockResolvedValue(makeUser()); mockActivityFindMany.mockResolvedValue([ makeActivity({ category: "chess" }), makeActivity({ category: "reading" }), makeActivity({ category: "feynman" }), makeActivity({ category: "logic" }), makeActivity({ category: "critical-thinking" }), makeActivity({ category: "quests" }), ]); const result = await getPerformanceSummary(1); expect(result.totalExercises).toBe(6); expect(result.streakDays).toBe(5); // from default user }); }); });