File size: 34,667 Bytes
9580dce | 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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 | /**
* Tests for GET /api/stats
*
* Covers:
* - 404 when no user found
* - response shape: windowDays, dailyXp, categoryBreakdown, recentActivities, summary
* - dailyXp: maps dailyLogs to { date, xpEarned, activityCount, goalMet }
* - categoryBreakdown: accumulates totalXp, count, avgScore, totalDuration per category
* - avgScore: averaged correctly over SCORED activities only (null scores excluded from denominator)
* - recentActivities: limited to first 25, maps all fields
* - summary: totalExercises, totalXpEarned, criticalHits, criticalHitRate, goalDaysMet
* - summary: correctSolves and correctSolveRate (score > 0 out of scored exercises)
* - summary: streak and level from user
* - empty data cases
* - DB errors propagate as 500
* - ?days param: windowDays 7/30/90 (default 30), invalid values fall back to 30
* - ?days param: DB gte boundary verified for 7-day and 90-day windows
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
// ---------------------------------------------------------------------------
// Mock prisma
// ---------------------------------------------------------------------------
const mockUserFindFirst = vi.fn();
const mockDailyLogFindMany = vi.fn();
const mockActivityFindMany = vi.fn();
vi.mock("@/lib/db", () => ({
prisma: {
user: { findFirst: (...args: unknown[]) => mockUserFindFirst(...args) },
dailyLog: { findMany: (...args: unknown[]) => mockDailyLogFindMany(...args) },
activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args) },
},
}));
import { GET } from "../route";
// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------
const baseUser = {
id: 1,
name: "Player One",
level: 5,
streak: 3,
longestStreak: 10,
categorySkills: [],
};
function makeActivity(overrides: Partial<{
id: number; category: string; exerciseType: string; description: string;
baseXp: number; qualityBonus: number; isCriticalHit: boolean; totalXp: number;
score: number | null; durationSecs: number | null; createdAt: Date;
}> = {}) {
return {
id: 1,
category: "CHESS",
exerciseType: "chess-puzzle",
description: "Solved a puzzle",
baseXp: 30,
qualityBonus: 10,
isCriticalHit: false,
totalXp: 40,
score: 0.8,
durationSecs: 120,
createdAt: new Date("2026-03-24T10:00:00Z"),
...overrides,
};
}
function makeDailyLog(overrides: Partial<{
date: Date; xpEarned: number; activityCount: number; goalMet: boolean;
}> = {}) {
return {
date: new Date("2026-03-24T00:00:00Z"),
xpEarned: 80,
activityCount: 3,
goalMet: false,
...overrides,
};
}
function makeGet(params?: Record<string, string>): NextRequest {
const url = new URL("http://localhost/api/stats");
if (params) {
for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, v);
}
}
return new NextRequest(url.toString());
}
async function json(res: Response): Promise<unknown> {
return res.json();
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe("GET /api/stats", () => {
beforeEach(() => {
vi.clearAllMocks();
mockDailyLogFindMany.mockResolvedValue([]);
mockActivityFindMany.mockResolvedValue([]);
});
it("returns 404 when no user found", async () => {
mockUserFindFirst.mockResolvedValue(null);
const res = await GET(makeGet());
expect(res.status).toBe(404);
});
it("returns 200 with full response shape", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
const res = await GET(makeGet());
expect(res.status).toBe(200);
const body = await json(res) as Record<string, unknown>;
expect(body).toHaveProperty("windowDays");
expect(body).toHaveProperty("dailyXp");
expect(body).toHaveProperty("categoryBreakdown");
expect(body).toHaveProperty("recentActivities");
expect(body).toHaveProperty("summary");
});
it("maps dailyXp from logs", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockDailyLogFindMany.mockResolvedValue([
makeDailyLog({ xpEarned: 100, activityCount: 4, goalMet: true }),
makeDailyLog({ date: new Date("2026-03-23T00:00:00Z"), xpEarned: 50, activityCount: 2, goalMet: false }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const dailyXp = body.dailyXp as Array<Record<string, unknown>>;
expect(dailyXp).toHaveLength(2);
expect(dailyXp[0]).toMatchObject({ xpEarned: 100, activityCount: 4, goalMet: true });
expect(dailyXp[1]).toMatchObject({ xpEarned: 50, activityCount: 2, goalMet: false });
expect(dailyXp[0]).toHaveProperty("date");
});
it("builds categoryBreakdown accumulating XP and count", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, category: "CHESS", totalXp: 40, score: 0.8, durationSecs: 120 }),
makeActivity({ id: 2, category: "CHESS", totalXp: 30, score: 0.6, durationSecs: 90 }),
makeActivity({ id: 3, category: "FEYNMAN", totalXp: 50, score: 1.0, durationSecs: 300 }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const breakdown = body.categoryBreakdown as Record<string, Record<string, number>>;
expect(breakdown.CHESS.totalXp).toBe(70);
expect(breakdown.CHESS.count).toBe(2);
expect(breakdown.CHESS.totalDuration).toBe(210);
expect(breakdown.FEYNMAN.totalXp).toBe(50);
expect(breakdown.FEYNMAN.count).toBe(1);
});
it("computes avgScore as mean of non-null scores", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, category: "CHESS", score: 0.8 }),
makeActivity({ id: 2, category: "CHESS", score: 0.6 }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const breakdown = body.categoryBreakdown as Record<string, Record<string, number>>;
// (0.8 + 0.6) / 2 = 0.7, rounded to 2dp
expect(breakdown.CHESS.avgScore).toBe(0.7);
});
it("ignores null scores in avgScore denominator — divides by scored count only", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, category: "CHESS", score: 0.8 }),
makeActivity({ id: 2, category: "CHESS", score: null }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const breakdown = body.categoryBreakdown as Record<string, Record<string, number>>;
// 1 scored activity with score=0.8 → avgScore = 0.8/1 = 0.8 (not 0.8/2 = 0.4)
expect(breakdown.CHESS.avgScore).toBe(0.8);
});
it("returns avgScore 0 when no scored activities in a category", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, category: "CHESS", score: null }),
makeActivity({ id: 2, category: "CHESS", score: null }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const breakdown = body.categoryBreakdown as Record<string, Record<string, number>>;
expect(breakdown.CHESS.avgScore).toBe(0);
});
it("limits recentActivities to 25", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
const activities = Array.from({ length: 30 }, (_, i) =>
makeActivity({ id: i + 1 })
);
mockActivityFindMany.mockResolvedValue(activities);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const recent = body.recentActivities as unknown[];
expect(recent).toHaveLength(25);
});
it("maps all recentActivity fields", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 42, category: "FEYNMAN", exerciseType: "explain", description: "Black holes", baseXp: 30, qualityBonus: 10, isCriticalHit: true, totalXp: 80, score: 0.9, durationSecs: 180 }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const recent = body.recentActivities as Array<Record<string, unknown>>;
expect(recent[0]).toMatchObject({
id: 42,
category: "FEYNMAN",
exerciseType: "explain",
description: "Black holes",
baseXp: 30,
qualityBonus: 10,
isCriticalHit: true,
totalXp: 80,
score: 0.9,
durationSecs: 180,
});
expect(recent[0]).toHaveProperty("createdAt");
});
it("counts totalExercises in summary", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1 }),
makeActivity({ id: 2 }),
makeActivity({ id: 3 }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.totalExercises).toBe(3);
});
it("sums totalXpEarned in summary", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, totalXp: 40 }),
makeActivity({ id: 2, totalXp: 60 }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.totalXpEarned).toBe(100);
});
it("counts criticalHits in summary", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, isCriticalHit: true }),
makeActivity({ id: 2, isCriticalHit: false }),
makeActivity({ id: 3, isCriticalHit: true }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.criticalHits).toBe(2);
});
it("computes criticalHitRate as percentage", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, isCriticalHit: true }),
makeActivity({ id: 2, isCriticalHit: false }),
makeActivity({ id: 3, isCriticalHit: false }),
makeActivity({ id: 4, isCriticalHit: false }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
// 1/4 = 25.0
expect(summary.criticalHitRate).toBe(25);
});
it("returns criticalHitRate 0 when no activities", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.criticalHitRate).toBe(0);
});
// ── Correct Solve Rate ────────────────────────────────────────────────────
it("counts correctSolves as activities with score > 0", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, score: 0.8 }),
makeActivity({ id: 2, score: 0.0 }), // zero score = incorrect
makeActivity({ id: 3, score: 1.0 }),
makeActivity({ id: 4, score: null }), // no score = unscored
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
// Only id=1 (0.8) and id=3 (1.0) are correct solves
expect(summary.correctSolves).toBe(2);
});
it("computes correctSolveRate as percentage of scored exercises", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, score: 1.0 }), // correct
makeActivity({ id: 2, score: 0.8 }), // correct
makeActivity({ id: 3, score: 0.0 }), // incorrect
makeActivity({ id: 4, score: null }), // unscored — excluded from denominator
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
// 2 correct out of 3 scored = 66.7%
expect(summary.correctSolveRate).toBe(66.7);
});
it("returns correctSolveRate 100 when all scored exercises correct", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, score: 0.9 }),
makeActivity({ id: 2, score: 1.0 }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.correctSolveRate).toBe(100);
});
it("returns correctSolveRate 0 when no scored activities", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, score: null }),
makeActivity({ id: 2, score: null }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.correctSolveRate).toBe(0);
expect(summary.correctSolves).toBe(0);
});
it("returns correctSolveRate 0 when no activities at all", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.correctSolveRate).toBe(0);
});
it("summary includes correctSolves and correctSolveRate fields", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([makeActivity({ id: 1, score: 0.7 })]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary).toHaveProperty("correctSolves");
expect(summary).toHaveProperty("correctSolveRate");
});
it("counts goalDaysMet from daily logs", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockDailyLogFindMany.mockResolvedValue([
makeDailyLog({ goalMet: true }),
makeDailyLog({ goalMet: false }),
makeDailyLog({ goalMet: true }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.goalDaysMet).toBe(2);
});
it("includes streak and longestStreak from user", async () => {
mockUserFindFirst.mockResolvedValue({ ...baseUser, streak: 7, longestStreak: 14 });
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.currentStreak).toBe(7);
expect(summary.longestStreak).toBe(14);
});
it("includes user level in summary", async () => {
mockUserFindFirst.mockResolvedValue({ ...baseUser, level: 8 });
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.level).toBe(8);
});
it("handles null durationSecs gracefully", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([
makeActivity({ id: 1, durationSecs: null }),
makeActivity({ id: 2, durationSecs: 60 }),
]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
expect(summary.totalDuration).toBe(60);
});
it("returns empty collections when no activity", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
mockActivityFindMany.mockResolvedValue([]);
mockDailyLogFindMany.mockResolvedValue([]);
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
expect(body.dailyXp).toEqual([]);
expect(body.categoryBreakdown).toEqual({});
expect(body.recentActivities).toEqual([]);
});
it("queries daily logs from last 30 days ordered asc", async () => {
mockUserFindFirst.mockResolvedValue(baseUser);
await GET(makeGet());
const call = mockDailyLogFindMany.mock.calls[0][0];
expect(call).toMatchObject({
where: { userId: 1, date: { gte: expect.any(Date) } },
orderBy: { date: "asc" },
});
// gte is UTC midnight ~30 days ago; tolerance ±24h for midnight truncation
const gteDate: Date = call.where.date.gte;
const nowMs = Date.now();
const diffMs = nowMs - gteDate.getTime();
const thirtyDaysMs = 30 * 24 * 60 * 60 * 1000;
const oneDayMs = 24 * 60 * 60 * 1000;
expect(diffMs).toBeGreaterThanOrEqual(thirtyDaysMs - oneDayMs);
expect(diffMs).toBeLessThanOrEqual(thirtyDaysMs + oneDayMs);
});
it("propagates DB errors as 500", async () => {
mockUserFindFirst.mockRejectedValue(new Error("DB down"));
const res = await GET(makeGet());
expect(res.status).toBe(500);
});
});
// ---------------------------------------------------------------------------
// ?days query parameter
// ---------------------------------------------------------------------------
describe("GET /api/stats — ?days query param", () => {
beforeEach(() => {
vi.clearAllMocks();
mockUserFindFirst.mockResolvedValue(baseUser);
mockDailyLogFindMany.mockResolvedValue([]);
mockActivityFindMany.mockResolvedValue([]);
});
it("defaults to windowDays=30 when ?days is omitted", async () => {
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
expect(body.windowDays).toBe(30);
});
it("returns windowDays=7 when ?days=7", async () => {
const res = await GET(makeGet({ days: "7" }));
const body = await json(res) as Record<string, unknown>;
expect(body.windowDays).toBe(7);
});
it("returns windowDays=30 when ?days=30", async () => {
const res = await GET(makeGet({ days: "30" }));
const body = await json(res) as Record<string, unknown>;
expect(body.windowDays).toBe(30);
});
it("returns windowDays=90 when ?days=90", async () => {
const res = await GET(makeGet({ days: "90" }));
const body = await json(res) as Record<string, unknown>;
expect(body.windowDays).toBe(90);
});
it("falls back to windowDays=30 for invalid ?days value (e.g. 14)", async () => {
const res = await GET(makeGet({ days: "14" }));
const body = await json(res) as Record<string, unknown>;
expect(body.windowDays).toBe(30);
});
it("falls back to windowDays=30 for non-numeric ?days", async () => {
const res = await GET(makeGet({ days: "week" }));
const body = await json(res) as Record<string, unknown>;
expect(body.windowDays).toBe(30);
});
it("queries daily logs with gte set to UTC midnight ~7 days ago when ?days=7", async () => {
await GET(makeGet({ days: "7" }));
const call = mockDailyLogFindMany.mock.calls[0][0];
const gteDate: Date = call.where.date.gte;
// The route zeroes time to UTC midnight; gte is at midnight of (today - 7 days).
// Tolerance: ±24h accounts for the midnight truncation at any time of day.
expect(gteDate).toBeInstanceOf(Date);
const nowMs = Date.now();
const diffMs = nowMs - gteDate.getTime();
const sevenDaysMs = 7 * 24 * 60 * 60 * 1000;
const oneDayMs = 24 * 60 * 60 * 1000;
expect(diffMs).toBeGreaterThanOrEqual(sevenDaysMs - oneDayMs);
expect(diffMs).toBeLessThanOrEqual(sevenDaysMs + oneDayMs);
});
it("queries daily logs with gte set to UTC midnight ~90 days ago when ?days=90", async () => {
await GET(makeGet({ days: "90" }));
const call = mockDailyLogFindMany.mock.calls[0][0];
const gteDate: Date = call.where.date.gte;
expect(gteDate).toBeInstanceOf(Date);
const nowMs = Date.now();
const diffMs = nowMs - gteDate.getTime();
const ninetyDaysMs = 90 * 24 * 60 * 60 * 1000;
const oneDayMs = 24 * 60 * 60 * 1000;
expect(diffMs).toBeGreaterThanOrEqual(ninetyDaysMs - oneDayMs);
expect(diffMs).toBeLessThanOrEqual(ninetyDaysMs + oneDayMs);
});
it("response includes windowDays alongside dailyXp, summary, etc.", async () => {
const res = await GET(makeGet({ days: "7" }));
const body = await json(res) as Record<string, unknown>;
expect(body).toHaveProperty("windowDays", 7);
expect(body).toHaveProperty("dailyXp");
expect(body).toHaveProperty("summary");
expect(body).toHaveProperty("categoryBreakdown");
expect(body).toHaveProperty("recentActivities");
});
});
// ---------------------------------------------------------------------------
// Activity pagination (?activityOffset / ?activityLimit)
// ---------------------------------------------------------------------------
describe("GET /api/stats — activity pagination", () => {
// Build a pool of 60 activities with sequential IDs
const POOL = Array.from({ length: 60 }, (_, i) =>
makeActivity({ id: i + 1, totalXp: 10 + i, createdAt: new Date(Date.now() - i * 1000) }),
);
beforeEach(() => {
vi.clearAllMocks();
mockUserFindFirst.mockResolvedValue(baseUser);
mockDailyLogFindMany.mockResolvedValue([]);
mockActivityFindMany.mockResolvedValue(POOL);
});
it("returns activityTotal equal to all activities in the pool", async () => {
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
expect(body.activityTotal).toBe(60);
});
it("returns first 25 activities by default (no offset/limit params)", async () => {
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(25);
expect(activities[0].id).toBe(1); // most recent (index 0 in pool)
expect(activities[24].id).toBe(25);
});
it("respects activityOffset — skips the first N activities", async () => {
const res = await GET(makeGet({ activityOffset: "25" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(25);
expect(activities[0].id).toBe(26);
expect(activities[24].id).toBe(50);
});
it("respects activityLimit — returns fewer activities than default", async () => {
const res = await GET(makeGet({ activityLimit: "10" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(10);
});
it("respects both activityOffset and activityLimit together", async () => {
const res = await GET(makeGet({ activityOffset: "10", activityLimit: "5" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(5);
expect(activities[0].id).toBe(11);
expect(activities[4].id).toBe(15);
});
it("caps activityLimit at MAX (50)", async () => {
const res = await GET(makeGet({ activityLimit: "9999" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(50); // pool has 60, but cap is 50
});
it("returns fewer than limit when near end of pool", async () => {
const res = await GET(makeGet({ activityOffset: "55", activityLimit: "25" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(5); // only 5 left (55..59)
});
it("returns empty array when offset equals pool size", async () => {
const res = await GET(makeGet({ activityOffset: "60" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(0);
});
it("returns empty array when offset exceeds pool size", async () => {
const res = await GET(makeGet({ activityOffset: "100" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(0);
});
it("treats invalid activityOffset as 0", async () => {
const res = await GET(makeGet({ activityOffset: "abc" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(25);
expect((activities[0] as Record<string, unknown>).id).toBe(1);
});
it("treats invalid activityLimit as default (25)", async () => {
const res = await GET(makeGet({ activityLimit: "banana" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(25);
});
it("treats negative activityOffset as 0", async () => {
const res = await GET(makeGet({ activityOffset: "-10" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities[0].id).toBe(1);
});
it("activityTotal is stable regardless of pagination params", async () => {
const [r1, r2] = await Promise.all([
GET(makeGet({ activityOffset: "0", activityLimit: "10" })),
GET(makeGet({ activityOffset: "50", activityLimit: "10" })),
]);
const b1 = await json(r1) as Record<string, unknown>;
const b2 = await json(r2) as Record<string, unknown>;
expect(b1.activityTotal).toBe(60);
expect(b2.activityTotal).toBe(60);
});
it("response always contains activityTotal field", async () => {
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
expect(body).toHaveProperty("activityTotal");
expect(typeof body.activityTotal).toBe("number");
});
});
// ---------------------------------------------------------------------------
// ?activityCategory filter
// ---------------------------------------------------------------------------
describe("GET /api/stats — ?activityCategory filter", () => {
const CHESS_ACTIVITY = makeActivity({
id: 1,
category: "chess",
exerciseType: "chess-puzzle",
totalXp: 40,
});
const READING_ACTIVITY = makeActivity({
id: 2,
category: "reading",
exerciseType: "comprehension",
totalXp: 50,
});
const FEYNMAN_ACTIVITY = makeActivity({
id: 3,
category: "feynman",
exerciseType: "explain",
totalXp: 60,
});
const MIXED_POOL = [CHESS_ACTIVITY, READING_ACTIVITY, FEYNMAN_ACTIVITY];
beforeEach(() => {
vi.clearAllMocks();
mockUserFindFirst.mockResolvedValue(baseUser);
mockDailyLogFindMany.mockResolvedValue([]);
mockActivityFindMany.mockResolvedValue(MIXED_POOL);
});
it("returns only chess activities when activityCategory=chess", async () => {
const res = await GET(makeGet({ activityCategory: "chess" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(1);
expect(activities[0].id).toBe(1);
expect(activities[0].category).toBe("chess");
});
it("returns only reading activities when activityCategory=reading", async () => {
const res = await GET(makeGet({ activityCategory: "reading" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(1);
expect(activities[0].category).toBe("reading");
});
it("returns all activities when activityCategory=all", async () => {
const res = await GET(makeGet({ activityCategory: "all" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(3);
});
it("returns all activities when ?activityCategory is omitted", async () => {
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(3);
});
it("treats an invalid category value as 'all' (returns all activities)", async () => {
const res = await GET(makeGet({ activityCategory: "basketweaving" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(3);
});
it("activityTotal reflects the filtered count, not the full pool", async () => {
const res = await GET(makeGet({ activityCategory: "chess" }));
const body = await json(res) as Record<string, unknown>;
expect(body.activityTotal).toBe(1);
});
it("activityTotal is full pool size when no filter", async () => {
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
expect(body.activityTotal).toBe(3);
});
it("activityCategory field in response is the active category when filtered", async () => {
const res = await GET(makeGet({ activityCategory: "feynman" }));
const body = await json(res) as Record<string, unknown>;
expect(body.activityCategory).toBe("feynman");
});
it("activityCategory field in response is null when no filter", async () => {
const res = await GET(makeGet());
const body = await json(res) as Record<string, unknown>;
expect(body.activityCategory).toBeNull();
});
it("activityCategory field in response is null when activityCategory=all", async () => {
const res = await GET(makeGet({ activityCategory: "all" }));
const body = await json(res) as Record<string, unknown>;
expect(body.activityCategory).toBeNull();
});
it("activityCategory field in response is null for invalid category", async () => {
const res = await GET(makeGet({ activityCategory: "invalid" }));
const body = await json(res) as Record<string, unknown>;
expect(body.activityCategory).toBeNull();
});
it("category breakdown is not affected by activityCategory filter (uses full pool)", async () => {
const res = await GET(makeGet({ activityCategory: "chess" }));
const body = await json(res) as Record<string, unknown>;
const breakdown = body.categoryBreakdown as Record<string, Record<string, unknown>>;
// All 3 categories still appear in breakdown
expect(breakdown).toHaveProperty("chess");
expect(breakdown).toHaveProperty("reading");
expect(breakdown).toHaveProperty("feynman");
});
it("summary stats are not affected by activityCategory filter (uses full pool)", async () => {
const res = await GET(makeGet({ activityCategory: "chess" }));
const body = await json(res) as Record<string, unknown>;
const summary = body.summary as Record<string, unknown>;
// All 3 activities counted in summary despite chess-only filter
expect(summary.totalExercises).toBe(3);
});
it("category filter is case-insensitive (DB category stored as lowercase)", async () => {
// Activity has category "chess" (lowercase), param is "chess" — should match
const res = await GET(makeGet({ activityCategory: "chess" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(1);
});
it("filter works with hyphenated category (critical-thinking)", async () => {
const ctActivity = makeActivity({
id: 10,
category: "critical-thinking",
exerciseType: "flaw-finder",
totalXp: 70,
});
mockActivityFindMany.mockResolvedValue([...MIXED_POOL, ctActivity]);
const res = await GET(makeGet({ activityCategory: "critical-thinking" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(1);
expect(activities[0].id).toBe(10);
});
it("returns empty activities (not 404) when filter matches no activities", async () => {
const res = await GET(makeGet({ activityCategory: "quests" }));
expect(res.status).toBe(200);
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(0);
expect(body.activityTotal).toBe(0);
});
it("pagination still works within a filtered set", async () => {
// Build 5 chess activities + 2 reading
const pool = [
...Array.from({ length: 5 }, (_, i) =>
makeActivity({ id: i + 1, category: "chess", totalXp: 10 }),
),
makeActivity({ id: 10, category: "reading", totalXp: 10 }),
makeActivity({ id: 11, category: "reading", totalXp: 10 }),
];
mockActivityFindMany.mockResolvedValue(pool);
const res = await GET(makeGet({ activityCategory: "chess", activityOffset: "2", activityLimit: "2" }));
const body = await json(res) as Record<string, unknown>;
const activities = body.recentActivities as Array<Record<string, unknown>>;
expect(activities).toHaveLength(2);
expect(activities[0].id).toBe(3); // 3rd chess activity (0-indexed: [2])
expect(body.activityTotal).toBe(5); // only chess total
});
});
|