Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions backend/controllers/authController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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,
});
};
Expand Down Expand Up @@ -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) });
};

/**
Expand Down
68 changes: 59 additions & 9 deletions backend/services/progressService.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down Expand Up @@ -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"
}],
Expand Down Expand Up @@ -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"
}],
Expand Down
87 changes: 86 additions & 1 deletion backend/tests/unit/attemptProcessing.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
12 changes: 12 additions & 0 deletions src/context/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
63 changes: 49 additions & 14 deletions src/pages/Profile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -113,26 +122,52 @@ const Profile = () => {
</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4 pt-2">
<div className="flex items-start gap-4">
{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. */
<div className="flex items-start gap-4 pt-2">
<div className="bg-primary/10 p-2 rounded-full">
<Clock className="h-4 w-4 text-primary" />
<Award className="h-4 w-4 text-primary" />
</div>
<div>
<p className="font-medium text-sm">First Quiz Completed</p>
<p className="text-xs text-muted-foreground">You completed your first diagnostic assessment.</p>
<p className="font-medium text-sm">No achievements yet</p>
<p className="text-xs text-muted-foreground">
Complete your first assessment to unlock your first achievement. Study on
three consecutive days to unlock a streak milestone.
</p>
</div>
</div>
<div className="flex items-start gap-4">
<div className="bg-primary/10 p-2 rounded-full">
<Flame className="h-4 w-4 text-primary" />
</div>
<div>
<p className="font-medium text-sm">3 Day Streak</p>
<p className="text-xs text-muted-foreground">You studied for 3 consecutive days.</p>
</div>
) : (
<div className="space-y-4 pt-2">
{achievements.map((achievement) => (
<div key={achievement.id} className="flex items-start gap-4">
<div className="bg-primary/10 p-2 rounded-full">
{achievement.id.startsWith("streak_") ? (
<Flame className="h-4 w-4 text-primary" />
) : (
<Clock className="h-4 w-4 text-primary" />
)}
</div>
<div>
<p className="font-medium text-sm">{achievement.title}</p>
{achievement.description && (
<p className="text-xs text-muted-foreground">
{achievement.description}
</p>
)}
{achievement.unlockedAt && (
<p className="text-[11px] text-muted-foreground/70 mt-0.5 font-mono">
{new Date(achievement.unlockedAt).toLocaleDateString()}
</p>
)}
</div>
</div>
))}
</div>
</div>
)}
</CardContent>
</Card>
</div>
Expand Down
Loading
Loading