diff --git a/backend/controllers/authController.js b/backend/controllers/authController.js index 6bd53da..1ce2115 100644 --- a/backend/controllers/authController.js +++ b/backend/controllers/authController.js @@ -27,6 +27,30 @@ const getMeta = (req) => ({ // ─── Auth Response Helper ───────────────────────────────────────────────────── +/** + * The user shape the client receives, including earned achievements. + * + * Achievements are stored on the progress document rather than the user, so they + * are read here instead of in each handler. This is additive: every field + * `toSafeJSON()` already returned is passed through untouched, so no existing + * client behaviour changes. + * + * A learner with no progress document yet has genuinely earned nothing, so an + * empty list is the truthful answer rather than an error. + */ +const userWithAchievements = async (user) => { + const base = user.toSafeJSON(); + + if (!isDBConnected()) return { ...base, achievements: [] }; + + const progress = await UserProgress.findOne({ user: user._id }) + .select("achievements") + .lean() + .catch(() => null); + + return { ...base, achievements: progress?.achievements ?? [] }; +}; + const sendAuthResponse = async (res, user, req) => { const accessToken = createToken(user); const family = uuidv4(); @@ -35,7 +59,7 @@ const sendAuthResponse = async (res, user, req) => { res.cookie("refreshToken", refreshToken, REFRESH_COOKIE_OPTIONS); res.json({ - user: user.toSafeJSON(), + user: await userWithAchievements(user), token: accessToken, }); }; @@ -95,7 +119,7 @@ export const login = async (req, res) => { }; export const me = async (req, res) => { - res.json({ user: req.user.toSafeJSON() }); + res.json({ user: await userWithAchievements(req.user) }); }; /** diff --git a/backend/services/progressService.js b/backend/services/progressService.js index 62166b8..c552485 100644 --- a/backend/services/progressService.js +++ b/backend/services/progressService.js @@ -54,6 +54,39 @@ export const normalizeTopic = (topic) => { return canonicalNormalize(topic); }; +/** Consecutive-day counts that earn a streak achievement. */ +const STREAK_MILESTONES = [3, 7, 14, 30, 50, 100]; + +/** + * Loads the learner's progress document, or null when none exists yet. + * + * A brand-new learner who has studied for three days but never sat an assessment + * has no progress document, so there is nothing to attach an achievement to. That + * is a legitimate state, not an error. + */ +const loadProgress = async (userId, session) => { + const progress = await withSession(UserProgress.findOne({ user: userId }), session); + return progress ?? null; +}; + +/** + * Attaches an achievement to a progress document, at most once. + * + * Idempotent by id, so replaying the same attempt or re-running the same day + * cannot produce a duplicate. Returns whether this call was the one that awarded + * it, so the caller can fire a notification only on the transition. + */ +const awardAchievement = async (progress, achievement, { session } = {}) => { + if (!progress) return false; + + const existing = progress.achievements ?? []; + if (existing.some((a) => a.id === achievement.id)) return false; + + progress.achievements = [...existing, achievement]; + await saveDoc(progress, session); + return true; +}; + export const updateUserProgressFromAttempt = async ({ userId, quiz, attempt, session }) => { const progress = await UserProgress.findOneAndUpdate( { user: userId }, @@ -120,19 +153,21 @@ export const updateUserProgressFromAttempt = async ({ userId, quiz, attempt, ses // Check achievements if (progress.totals.quizzesTaken === 1) { - const hasFirstQuiz = progress.achievements?.some(a => a.id === "first_quiz"); - if (!hasFirstQuiz) { - if (!progress.achievements) progress.achievements = []; - progress.achievements.push({ + const awarded = await awardAchievement( + progress, + { id: "first_quiz", title: "First Steps", description: "Completed your first assessment.", unlockedAt: now, - }); + }, + { session } + ); + if (awarded) { await Notification.create( [{ user: userId, - title: "Achievement Unlocked! 🏆", + title: "Achievement unlocked", message: "You've earned the 'First Steps' achievement.", type: "achievement" }], @@ -165,12 +200,27 @@ export const updateStudyStreak = async (userId, { session } = {}) => { await saveDoc(user, session); - // Streak Notifications - if (current > 1 && [3, 7, 14, 30, 50, 100].includes(current)) { + // Streak milestones: notify, and persist the milestone as a real achievement. + // + // The Profile page lists achievements, so a milestone that only ever produced a + // notification was invisible there — the section could never show a streak. The + // notification is unchanged in substance; the achievement is the addition. + if (current > 1 && STREAK_MILESTONES.includes(current)) { + const awarded = await awardAchievement( + await loadProgress(userId, session), + { + id: `streak_${current}`, + title: `${current} Day Streak`, + description: `Studied for ${current} consecutive days.`, + unlockedAt: new Date(), + }, + { session } + ); + await Notification.create( [{ user: userId, - title: `${current} Day Streak! 🔥`, + title: `${current} day streak`, message: `You've studied for ${current} consecutive days. Keep it up!`, type: "success" }], diff --git a/backend/tests/unit/attemptProcessing.test.js b/backend/tests/unit/attemptProcessing.test.js index 7cb9906..fa472b2 100644 --- a/backend/tests/unit/attemptProcessing.test.js +++ b/backend/tests/unit/attemptProcessing.test.js @@ -1421,7 +1421,92 @@ describe("updateStudyStreak", () => { await updateStudyStreak(USER_ID); } expect(store.users.get(USER_ID).streak.current).toBe(3); - expect(store.notifications.map((n) => n.title)).toContain("3 Day Streak! 🔥"); + expect(store.notifications.map((n) => n.title)).toContain("3 day streak"); + }); + + // ── Achievements the Profile page lists ─────────────────────────────────── + // + // The Profile page once rendered two hard-coded achievement cards, so a + // brand-new account was shown "First Quiz Completed" and "3 Day Streak" while + // its streak read 0. These pin the persisted truth the page now renders. + + test("a learner with no progress document earns no streak achievement", async () => { + // No progress document at all: studied, but never sat an assessment. + store.progress.delete(USER_ID); + + jest.setSystemTime(new Date("2026-04-28T09:00:00.000Z")); + await updateStudyStreak(USER_ID); + jest.setSystemTime(new Date("2026-04-29T09:00:00.000Z")); + await updateStudyStreak(USER_ID); + jest.setSystemTime(new Date("2026-04-30T09:00:00.000Z")); + await updateStudyStreak(USER_ID); + + // The streak itself is still tracked on the user. + expect(store.users.get(USER_ID).streak.current).toBe(3); + // ...but there is nothing to attach an achievement to, and no crash. + expect(store.progress.has(USER_ID)).toBe(false); + }); + + test("a milestone streak persists a streak achievement", async () => { + store.progress.set(USER_ID, newProgress(USER_ID)); + + for (const day of ["2026-04-28", "2026-04-29", "2026-04-30"]) { + jest.setSystemTime(new Date(`${day}T09:00:00.000Z`)); + await updateStudyStreak(USER_ID); + } + + const progress = store.progress.get(USER_ID); + const streakAchievement = progress.achievements.find((a) => a.id === "streak_3"); + + expect(streakAchievement).toBeDefined(); + expect(streakAchievement.title).toBe("3 Day Streak"); + expect(streakAchievement.description).toBe("Studied for 3 consecutive days."); + expect(streakAchievement.unlockedAt).toBeInstanceOf(Date); + }); + + test("no streak achievement before the milestone", async () => { + store.progress.set(USER_ID, newProgress(USER_ID)); + + for (const day of ["2026-04-28", "2026-04-29"]) { + jest.setSystemTime(new Date(`${day}T09:00:00.000Z`)); + await updateStudyStreak(USER_ID); + } + + expect(store.users.get(USER_ID).streak.current).toBe(2); + expect(store.progress.get(USER_ID).achievements).toEqual([]); + }); + + test("reprocessing the milestone does not duplicate the achievement", async () => { + store.progress.set(USER_ID, newProgress(USER_ID)); + + for (const day of ["2026-04-28", "2026-04-29", "2026-04-30"]) { + jest.setSystemTime(new Date(`${day}T09:00:00.000Z`)); + await updateStudyStreak(USER_ID); + } + + const afterFirst = store.progress.get(USER_ID).achievements.map((a) => a.id); + expect(afterFirst).toContain("streak_3"); + + // Same day again, and then a replayed earlier day: neither may re-award. + jest.setSystemTime(new Date("2026-04-30T18:00:00.000Z")); + await updateStudyStreak(USER_ID); + jest.setSystemTime(new Date("2026-04-30T21:00:00.000Z")); + await updateStudyStreak(USER_ID); + + expect(store.progress.get(USER_ID).achievements.map((a) => a.id)).toEqual(afterFirst); + }); + + test("a four-day streak does not re-award the three-day achievement", async () => { + store.progress.set(USER_ID, newProgress(USER_ID)); + + for (const day of ["2026-04-28", "2026-04-29", "2026-04-30", "2026-05-01"]) { + jest.setSystemTime(new Date(`${day}T09:00:00.000Z`)); + await updateStudyStreak(USER_ID); + } + + // 4 is not a milestone, so only the earlier 3-day award stands. + expect(store.users.get(USER_ID).streak.current).toBe(4); + expect(store.progress.get(USER_ID).achievements.map((a) => a.id)).toEqual(["streak_3"]); }); test("does not reset a multi-day streak when called twice on the same day", async () => { diff --git a/src/context/AuthContext.tsx b/src/context/AuthContext.tsx index cc56b86..2c4ae67 100644 --- a/src/context/AuthContext.tsx +++ b/src/context/AuthContext.tsx @@ -5,6 +5,18 @@ interface User { id: string; name: string; email: string; + /** + * Achievements the backend has actually awarded. Optional because a stored + * user from an older session will not carry it, and because a response from a + * deployment predating the field simply omits it — both must read as "none + * earned" rather than breaking. + */ + achievements?: Array<{ + id: string; + title: string; + description?: string; + unlockedAt?: string; + }>; profile?: { program?: string; semester?: string; diff --git a/src/pages/Profile.tsx b/src/pages/Profile.tsx index 0d1c5a3..f539930 100644 --- a/src/pages/Profile.tsx +++ b/src/pages/Profile.tsx @@ -16,6 +16,15 @@ const Profile = () => { const [semester, setSemester] = useState(user?.profile?.semester || ""); const [loading, setLoading] = useState(false); + /** + * Achievements awarded by the backend, newest first. Defaults to an empty list + * so a response without the field renders the empty state rather than claiming + * achievements that were never earned. + */ + const achievements = [...(user?.achievements ?? [])].sort( + (a, b) => new Date(b.unlockedAt ?? 0).getTime() - new Date(a.unlockedAt ?? 0).getTime(), + ); + const handleUpdate = async (e: React.FormEvent) => { e.preventDefault(); setLoading(true); @@ -113,26 +122,52 @@ const Profile = () => { -
-
+ {achievements.length === 0 ? ( + /* Truthful empty state. It used to render two hard-coded + achievements here, so a brand-new account was told it had + completed a quiz and held a 3-day streak while the streak + figures directly above read 0. Only what the backend has + actually awarded is listed now. */ +
- +
-

First Quiz Completed

-

You completed your first diagnostic assessment.

+

No achievements yet

+

+ Complete your first assessment to unlock your first achievement. Study on + three consecutive days to unlock a streak milestone. +

-
-
- -
-
-

3 Day Streak

-

You studied for 3 consecutive days.

-
+ ) : ( +
+ {achievements.map((achievement) => ( +
+
+ {achievement.id.startsWith("streak_") ? ( + + ) : ( + + )} +
+
+

{achievement.title}

+ {achievement.description && ( +

+ {achievement.description} +

+ )} + {achievement.unlockedAt && ( +

+ {new Date(achievement.unlockedAt).toLocaleDateString()} +

+ )} +
+
+ ))}
-
+ )}
diff --git a/src/test/profileAchievements.test.tsx b/src/test/profileAchievements.test.tsx new file mode 100644 index 0000000..eec10cb --- /dev/null +++ b/src/test/profileAchievements.test.tsx @@ -0,0 +1,179 @@ +/** + * Profile achievements + * ==================== + * + * The Profile page rendered two hard-coded achievement cards — "First Quiz + * Completed" and "3 Day Streak" — as literal JSX. A brand-new production account + * was therefore told it had completed an assessment and held a three-day streak + * while the streak figures directly above it read 0. + * + * The page now lists only what the backend has actually awarded, and shows an + * honest empty state with an unlock hint when nothing has been earned. + */ + +import { render, screen } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const updateProfile = vi.fn(); + +vi.mock("@/components/AppLayout", () => ({ + AppLayout: ({ children }: { children: React.ReactNode }) =>
{children}
, +})); + +vi.mock("react-router-dom", () => ({ useNavigate: () => vi.fn() })); + +vi.mock("@/lib/api", () => ({ + apiFetch: vi.fn().mockResolvedValue({ ok: true, json: async () => ({ user: {} }) }), + API_ROOT: "http://localhost:5001/api/v1", +})); + +vi.mock("@/context/AuthContext", () => ({ + useAuth: () => ({ user: mockUser }), +})); + +import Profile from "@/pages/Profile"; + +type Achievement = { + id: string; + title: string; + description?: string; + unlockedAt?: string; +}; + +let mockUser: { + _id?: string; + name: string; + email: string; + streak?: { current: number; longest: number; lastStudyDate: string }; + achievements?: Achievement[]; +}; + +beforeEach(() => { + mockUser = { + _id: "u1", + name: "Ada Lovelace", + email: "ada@example.com", + streak: { current: 0, longest: 0, lastStudyDate: "" }, + }; +}); + +describe("a learner who has earned nothing", () => { + it("says so instead of showing achievements", () => { + render(); + + expect(screen.getByText("No achievements yet")).toBeInTheDocument(); + }); + + it("explains how to unlock the first one", () => { + render(); + + // Motivating, and truthful: a hint, not a claim. + expect( + screen.getByText(/complete your first assessment to unlock/i), + ).toBeInTheDocument(); + }); + + it("shows none of the previously hard-coded entries", () => { + render(); + + expect(screen.queryByText("First Quiz Completed")).not.toBeInTheDocument(); + expect(screen.queryByText("3 Day Streak")).not.toBeInTheDocument(); + expect(screen.queryByText(/completed your first diagnostic/i)).not.toBeInTheDocument(); + }); + + it("treats a missing achievements field as none earned", () => { + // A user object stored before the field existed must not crash or invent any. + delete mockUser.achievements; + render(); + + expect(screen.getByText("No achievements yet")).toBeInTheDocument(); + }); +}); + +describe("a learner with real achievements", () => { + it("renders the persisted titles and descriptions", () => { + mockUser.achievements = [ + { + id: "first_quiz", + title: "First Steps", + description: "Completed your first assessment.", + unlockedAt: "2026-04-28T09:00:00.000Z", + }, + { + id: "streak_3", + title: "3 Day Streak", + description: "Studied for 3 consecutive days.", + unlockedAt: "2026-04-30T09:00:00.000Z", + }, + ]; + + render(); + + expect(screen.getByText("First Steps")).toBeInTheDocument(); + expect(screen.getByText("Completed your first assessment.")).toBeInTheDocument(); + expect(screen.getByText("3 Day Streak")).toBeInTheDocument(); + expect(screen.queryByText("No achievements yet")).not.toBeInTheDocument(); + }); + + it("uses assessment vocabulary, never quiz", () => { + mockUser.achievements = [ + { + id: "first_quiz", + title: "First Steps", + description: "Completed your first assessment.", + }, + ]; + + const { container } = render(); + + expect(container.textContent).not.toMatch(/\bquiz\b/i); + }); + + it("lists the most recently unlocked first", () => { + mockUser.achievements = [ + { id: "first_quiz", title: "Older", unlockedAt: "2026-04-28T09:00:00.000Z" }, + { id: "streak_3", title: "Newer", unlockedAt: "2026-04-30T09:00:00.000Z" }, + ]; + + render(); + + const titles = screen + .getAllByText(/Older|Newer/) + .map((el) => el.textContent); + expect(titles).toEqual(["Newer", "Older"]); + }); + + it("renders an achievement that carries no description", () => { + mockUser.achievements = [{ id: "x", title: "Bare" }]; + render(); + + expect(screen.getByText("Bare")).toBeInTheDocument(); + }); +}); + +describe("streak figures and achievements cannot disagree", () => { + it("shows a real 3-day streak with the matching achievement", () => { + mockUser.streak = { current: 3, longest: 3, lastStudyDate: "2026-04-30" }; + mockUser.achievements = [ + { id: "streak_3", title: "3 Day Streak", description: "Studied for 3 consecutive days." }, + ]; + + const { container } = render(); + + // Both the current and the longest streak read 3, so there are two figures. + expect(screen.getAllByText("3")).toHaveLength(2); + expect(container.textContent).toContain("Current active streak"); + expect(container.textContent).toContain("Longest streak"); + expect(screen.getByText("3 Day Streak")).toBeInTheDocument(); + }); + + it("does not show a streak achievement when the streak is zero", () => { + mockUser.streak = { current: 0, longest: 0, lastStudyDate: "" }; + mockUser.achievements = []; + + render(); + + expect(screen.queryByText("3 Day Streak")).not.toBeInTheDocument(); + expect(screen.getByText("No achievements yet")).toBeInTheDocument(); + }); +});