container.remove(), 250);
+ window.setTimeout(() => {
+ try {
+ if (typeof container.hidePopover === "function") container.hidePopover();
+ } catch {
+ // Already hidden.
+ }
+ container.remove();
+ }, 250);
}
diff --git a/packages/learning-ui/src/lib/sound-feedback.ts b/packages/learning-ui/src/lib/sound-feedback.ts
index 798f893e0..97b9fccee 100644
--- a/packages/learning-ui/src/lib/sound-feedback.ts
+++ b/packages/learning-ui/src/lib/sound-feedback.ts
@@ -46,11 +46,11 @@ const DEDUPE_MS = 160;
/**
* Learner gesture feedback. Synthesized by default; optional local files in
- * FEEDBACK_AUDIO. Opt out with localStorage `buildment:sound=off`.
+ * FEEDBACK_AUDIO. Opt out with localStorage `buildment:sound=off`. Reduced motion is about
+ * animation, so it turns off confetti but not sound.
*/
export function isSoundEnabled(): boolean {
if (typeof window === "undefined") return false;
- if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return false;
try { return localStorage.getItem("buildment:sound") !== "off"; } catch { return true; }
}
diff --git a/server/src/controllers/learner.ts b/server/src/controllers/learner.ts
index 29d883bab..433e5326a 100644
--- a/server/src/controllers/learner.ts
+++ b/server/src/controllers/learner.ts
@@ -19,6 +19,7 @@ import { loadGamificationSummary, updateGamificationPreferences } from "../servi
import { loadLeaderboard } from "../services/gamification/leaderboard.js";
import { loadLeaderboardHub } from "../services/gamification/leaderboard-categories.js";
import { listRewards, purchaseReward as purchaseRewardService, setActiveReward as setActiveRewardService, useReward as useRewardService } from "../services/gamification/rewards.js";
+import { claimAchievement } from "../services/gamification/achievements.js";
import { claimQuest as claimQuestService, loadWeeklyQuests } from "../services/gamification/quests.js";
import { listUserHighlights } from "../services/chapters/highlights.js";
import { listLearnerNotebookSolvedWork } from "../services/learner/notebook.js";
@@ -152,6 +153,11 @@ export async function questsClaim(req: Request, res: Response) {
ok(res, await claimQuestService(req.user!.id, String(req.params.questId)));
}
+// POST /api/v1/learner/achievements/:achievementId/claim
+export async function achievementClaim(req: Request, res: Response) {
+ ok(res, await claimAchievement(req.user!.id, String(req.params.achievementId)));
+}
+
// GET /api/v1/learner/public-profile
export async function publicProfileGet(req: Request, res: Response) {
ok(res, await getPublicProfileSettings(req.user!.id));
diff --git a/server/src/routes/v1/learner.ts b/server/src/routes/v1/learner.ts
index 330139c65..7c6873825 100644
--- a/server/src/routes/v1/learner.ts
+++ b/server/src/routes/v1/learner.ts
@@ -43,6 +43,7 @@ router.post("/rewards/:rewardId/purchase", learner.purchaseReward);
router.post("/rewards/:rewardId/use", learner.rewardsUse);
router.get("/quests", learner.quests);
router.post("/quests/:questId/claim", learner.questsClaim);
+router.post("/achievements/:achievementId/claim", learner.achievementClaim);
router.patch("/rewards/active", validateBody(rewardsActiveBody), learner.rewardsActive);
router.get("/profile", learner.profile);
router.get("/highlights", learner.highlights);
diff --git a/server/src/services/engagement/events.ts b/server/src/services/engagement/events.ts
index 40f4f02c4..f56b8394b 100644
--- a/server/src/services/engagement/events.ts
+++ b/server/src/services/engagement/events.ts
@@ -16,6 +16,8 @@ import { xpKeys } from "../../shared/gamification/xp.js";
import type { TrackEventBody } from "../../validations/engagement.js";
import { gamificationFeatures } from "../gamification/flags.js";
import { settleWeeklyGoal } from "../gamification/habit.js";
+import { loadCareerProgress } from "../gamification/career.js";
+import type { CareerTier } from "../../shared/api/gamification.js";
import { utcDateOnly } from "../progress/heartbeat.js";
import { loadLearnerHabit } from "../progress/learner-habit.js";
import { latestQuizAttempt } from "./quiz-facts.js";
@@ -194,6 +196,29 @@ const courseCompleted = (courseId: string): Draft => ({
dedupeKey: `course_completed:${courseId}`,
});
+/**
+ * Records the first time the learner is seen at a career tier above Intern on a given surface.
+ * `"event"` (course completion toast) and `"profile"` (profile page celebration modal) each fire at
+ * most once per tier so finishing a course does not suppress the `/profile` celebration.
+ */
+export async function recordCareerTierUp(
+ userId: string,
+ platform: EngagementPlatform,
+ tier: CareerTier,
+ surface: "event" | "profile" = "event"
+): Promise
{
+ if (tier === "INTERN") return null;
+ const dedupeKey = surface === "profile" ? `career_tier_up:profile:${tier}` : `career_tier_up:${tier}`;
+ const event = await record(userId, platform, {
+ type: "career_tier_up",
+ courseId: null,
+ chapterId: null,
+ payload: { tier },
+ dedupeKey,
+ });
+ return event.isNew ? event : null;
+}
+
/**
* Checks one reported moment against the database, stores it, and returns it with what it caused:
* the events it led to (a weekly goal met, a new level) and the XP it earned.
@@ -275,6 +300,13 @@ async function addGamification(
if (levelUp.isNew) events.push(levelUp);
}
+ // Only a finished course can move the career tier, so only then is it worth the extra reads.
+ if (features.career && reported.some((event) => event.isNew && event.type === "course_completed")) {
+ const career = await loadCareerProgress(userId);
+ const promoted = await recordCareerTierUp(userId, platform, career.tier);
+ if (promoted) events.push(promoted);
+ }
+
const xp = Math.max(0, earned?._sum.amount ?? 0);
return xp > 0 ? { events, rewards: { xp } } : { events };
}
diff --git a/server/src/services/gamification/achievements.ts b/server/src/services/gamification/achievements.ts
index aba633d34..547a89502 100644
--- a/server/src/services/gamification/achievements.ts
+++ b/server/src/services/gamification/achievements.ts
@@ -2,9 +2,11 @@ import { prisma } from "../../db/prisma.js";
import { ACHIEVEMENTS, achievementProgress, rewardForTier } from "../../shared/gamification/achievements.js";
import { LEAGUE_TIER_ORDER } from "../../shared/gamification/leagues.js";
import { dateToDayKey, dayKeyToDate } from "../../shared/lib/local-date.js";
-import type { AchievementView } from "../../shared/api/public-profile.js";
+import type { AchievementClaim, AchievementClaimResult, AchievementView } from "../../shared/api/public-profile.js";
+import { BadRequestError, NotFoundError } from "../../utils/errors.js";
import { loadRecords } from "./records.js";
-import { earnCredits } from "./credits.js";
+import { creditBalance, earnCredits } from "./credits.js";
+import { gamificationFeatures } from "./flags.js";
// Computes achievement-card progress from existing data. Pure reads; reuses the records service for
// streak/perfect/league so there is one source of truth for those bests.
@@ -78,15 +80,9 @@ export async function loadAchievements(userId: string): Promise:` source keys). Returns what was newly paid this call.
- */
-export async function grantAchievementRewards(
- userId: string,
- achievements: AchievementView[]
-): Promise<{ count: number; credits: number }> {
- const existing = new Set(
+/** Reached tiers whose credits are still waiting to be claimed, per achievement. */
+export async function pendingAchievementClaims(userId: string, achievements: AchievementView[]): Promise {
+ const paid = new Set(
(
await prisma.creditEntry.findMany({
where: { userId, sourceKey: { startsWith: "achievement:" } },
@@ -94,26 +90,41 @@ export async function grantAchievementRewards(
})
).map((row) => row.sourceKey)
);
-
- const pending: Array<{ key: string; amount: number }> = [];
+ const claims: AchievementClaim[] = [];
for (const a of achievements) {
- for (let i = 0; i <= a.tier; i++) {
- const key = `achievement:${a.id}:${i}`;
- if (!existing.has(key)) pending.push({ key, amount: rewardForTier(i) });
- }
+ const tiers: number[] = [];
+ for (let i = 0; i <= a.tier; i++) if (!paid.has(achievementCreditKey(a.id, i))) tiers.push(i);
+ if (tiers.length > 0) claims.push({ id: a.id, tiers, credits: tiers.reduce((sum, i) => sum + rewardForTier(i), 0) });
}
- if (pending.length === 0) return { count: 0, credits: 0 };
+ return claims;
+}
+
+/**
+ * Pays every reached, unpaid tier of one achievement. Idempotent through the credit ledger
+ * (`achievement::` source keys), so a double click pays once.
+ */
+export async function claimAchievement(userId: string, achievementId: string): Promise {
+ if (!ACHIEVEMENTS.some((def) => def.id === achievementId)) throw new NotFoundError("Achievement not found");
+ if (!gamificationFeatures().credits) throw new BadRequestError("Build Credits are turned off.");
+ const achievement = (await loadAchievements(userId)).find((a) => a.id === achievementId)!;
+ const [pending] = await pendingAchievementClaims(userId, [achievement]);
+ if (!pending) throw new BadRequestError("Nothing to claim for this achievement yet.");
- let count = 0;
let credits = 0;
+ const tiers: number[] = [];
await prisma.$transaction(async (tx) => {
- for (const p of pending) {
- const paid = await earnCredits(tx, userId, p.key, p.amount);
- if (paid) {
- count += 1;
- credits += p.amount;
+ for (const tier of pending.tiers) {
+ const amount = rewardForTier(tier);
+ if (await earnCredits(tx, userId, achievementCreditKey(achievementId, tier), amount)) {
+ credits += amount;
+ tiers.push(tier);
}
}
});
- return { count, credits };
+ const label = achievement.tiers[Math.max(...pending.tiers)]?.label ?? null;
+ return { id: achievementId, title: achievement.title, tierLabel: label, tiers, credits, balance: await creditBalance(userId) };
+}
+
+function achievementCreditKey(id: string, tier: number): string {
+ return `achievement:${id}:${tier}`;
}
diff --git a/server/src/services/learner/dashboard-model.ts b/server/src/services/learner/dashboard-model.ts
index 828b16018..3c429009f 100644
--- a/server/src/services/learner/dashboard-model.ts
+++ b/server/src/services/learner/dashboard-model.ts
@@ -168,6 +168,7 @@ export function buildMenteeDashboardViewModel(args: {
habit?: LearnerHabit;
gamification?: GamificationSummary;
leaderboard?: LeaderboardHubView | null;
+ unclaimedAchievements?: { count: number; totalCredits: number; ids: string[] } | null;
}): MenteeDashboardViewModel {
const gamification = args.gamification ?? GAMIFICATION_OFF;
const showXp = gamification.features.xp && !gamification.hidden;
@@ -414,5 +415,6 @@ export function buildMenteeDashboardViewModel(args: {
},
gamification,
leaderboard: args.leaderboard ?? null,
+ ...(args.unclaimedAchievements ? { unclaimedAchievements: args.unclaimedAchievements } : {}),
};
}
diff --git a/server/src/services/learner/load-mentee-dashboard.ts b/server/src/services/learner/load-mentee-dashboard.ts
index c8e4c3b5c..b8a15d0e4 100644
--- a/server/src/services/learner/load-mentee-dashboard.ts
+++ b/server/src/services/learner/load-mentee-dashboard.ts
@@ -3,6 +3,8 @@ import { prisma } from "../../db/prisma.js";
import { dateToDayKey, localDayKey, shiftDayKey, dayKeyToDate } from "../../shared/lib/local-date.js";
import { loadGamificationSummary } from "../gamification/summary.js";
import { loadLeaderboardHub } from "../gamification/leaderboard-categories.js";
+import { loadAchievements, pendingAchievementClaims } from "../gamification/achievements.js";
+import { gamificationFeatures } from "../gamification/flags.js";
import { loadLearnerHabit } from "../progress/learner-habit.js";
import { releaseForEnrollment, releaseModulesWithBlocks } from "../courses/releases.js";
import { buildMenteeDashboardViewModel } from "./dashboard-model.js";
@@ -201,6 +203,23 @@ export async function loadMenteeDashboard(args: {
loadLeaderboardCard(args.learnerId),
]);
+ let unclaimedAchievements: { count: number; totalCredits: number; ids: string[] } | null = null;
+ if (gamificationFeatures().credits && !gamification.hidden) {
+ try {
+ const achievements = await loadAchievements(args.learnerId);
+ const claims = await pendingAchievementClaims(args.learnerId, achievements);
+ if (claims.length > 0) {
+ unclaimedAchievements = {
+ count: claims.length,
+ totalCredits: claims.reduce((sum, claim) => sum + claim.credits, 0),
+ ids: claims.map((claim) => `${claim.id}:${claim.tiers.join("-")}`).sort(),
+ };
+ }
+ } catch {
+ /* Discovery banner is best-effort; never fail dashboard load. */
+ }
+ }
+
const byDay = new Map();
for (const row of dailyRows) {
const key = dateToDayKey(row.date);
@@ -260,5 +279,6 @@ export async function loadMenteeDashboard(args: {
habit,
gamification,
leaderboard,
+ unclaimedAchievements,
});
}
diff --git a/server/src/services/profile/public-profile.ts b/server/src/services/profile/public-profile.ts
index 0e4b83320..f41a0848c 100644
--- a/server/src/services/profile/public-profile.ts
+++ b/server/src/services/profile/public-profile.ts
@@ -9,9 +9,13 @@ import { REWARD_BY_ID, type RewardId } from "../../shared/gamification/rewards.j
import { BadRequestError, NotFoundError } from "../../utils/errors.js";
import { loadLearnerHabit } from "../progress/learner-habit.js";
import { loadRecords } from "../gamification/records.js";
-import { loadAchievements, grantAchievementRewards } from "../gamification/achievements.js";
+import { loadAchievements, pendingAchievementClaims } from "../gamification/achievements.js";
import { creditBalance } from "../gamification/credits.js";
import { gamificationFeatures } from "../gamification/flags.js";
+import { loadCareerProgress } from "../gamification/career.js";
+import { recordCareerTierUp } from "../engagement/events.js";
+import { loadLeaderboardHub } from "../gamification/leaderboard-categories.js";
+import type { ProfileStanding } from "../../shared/api/public-profile.js";
// The public Career Identity page. A learner opts in (profilePublic) and gets a unique handle; an
// unauthenticated GET /api/v1/public/profiles/:slug returns the curated card. Only safe fields are
@@ -104,16 +108,22 @@ export async function loadOwnProfile(userId: string): Promise
await prisma.user.update({ where: { id: user.id }, data: { publicSlug: slug } });
}
- const view = await buildProfileView(user, slug);
+ // Career progress runs first: it can raise the stored tier, and the view below should show that tier.
+ const career = gamificationFeatures().career ? await loadCareerProgress(userId) : null;
+ const view = await buildProfileView(career ? { ...user, careerTier: career.tier } : user, slug);
const creditsOn = gamificationFeatures().credits;
- const achievementRewards =
- creditsOn && view.achievements ? await grantAchievementRewards(userId, view.achievements) : { count: 0, credits: 0 };
+ const [achievementClaims, promoted] = await Promise.all([
+ creditsOn && view.achievements ? pendingAchievementClaims(userId, view.achievements) : Promise.resolve([]),
+ career && !view.hidden ? recordCareerTierUp(userId, "web", career.tier, "profile") : Promise.resolve(null),
+ ]);
return {
...view,
isOwner: true,
profilePublic: user.profilePublic,
creditsBalance: creditsOn ? await creditBalance(userId) : null,
- achievementRewards,
+ achievementClaims,
+ careerPromotion: promoted ? { tier: career!.tier } : null,
+ career,
};
}
@@ -125,6 +135,7 @@ const PROFILE_SELECT = {
leagueTier: true,
careerTier: true,
gamificationHidden: true,
+ leaderboardOptIn: true,
profilePublic: true,
publicSlug: true,
activeCosmetic: true,
@@ -139,12 +150,39 @@ type ProfileUser = {
leagueTier: PublicProfileView["leagueTier"];
careerTier: PublicProfileView["careerTier"];
gamificationHidden: boolean;
+ leaderboardOptIn: boolean;
activeCosmetic: string | null;
profile: { headline: string | null; learningInPublic: boolean } | null;
};
+/**
+ * The learner's standing for the profile header: this week's league rank, the all-time XP rank
+ * and top-three finishes. Read-only, and only for learners who joined the leaderboards, so a
+ * profile never shows a rank its owner did not choose to share on the boards.
+ */
+export async function loadProfileStanding(user: Pick): Promise {
+ if (user.gamificationHidden || !user.leaderboardOptIn || !gamificationFeatures().leaderboards) return null;
+ const [weekly, allTime, topThreeFinishes] = await Promise.all([
+ loadLeaderboardHub(user.id, { category: "weekly_xp", scope: "global" }),
+ loadLeaderboardHub(user.id, { category: "all_time_xp", scope: "global" }),
+ prisma.leaderboardPlacement.count({ where: { userId: user.id } }),
+ ]);
+ const league = weekly.status === "ready" && weekly.league
+ ? {
+ tier: weekly.league.tier,
+ rank: weekly.league.rank,
+ groupSize: weekly.league.groupSize,
+ promotionZone: weekly.league.promotionZone,
+ nextTier: weekly.league.nextTier,
+ }
+ : null;
+ const all = allTime.status === "ready" && allTime.you.rank > 0 ? { rank: allTime.you.rank, total: allTime.groupSize } : null;
+ if (!league && !all && topThreeFinishes === 0) return null;
+ return { league, allTime: all, topThreeFinishes };
+}
+
async function buildProfileView(user: ProfileUser, slug: string): Promise {
- const [coursesCompleted, habit, records, achievements, current] = await Promise.all([
+ const [coursesCompleted, habit, records, achievements, current, standing] = await Promise.all([
prisma.enrollment.count({ where: { userId: user.id, status: "COMPLETED" } }),
loadLearnerHabit(user.id, { applyFreezes: false }),
user.gamificationHidden ? Promise.resolve(null) : loadRecords(user.id),
@@ -154,6 +192,7 @@ async function buildProfileView(user: ProfileUser, slug: string): Promise. XP/league/streak are hidden when the learner has
@@ -37,7 +37,29 @@ export type PublicProfileView = {
/** Personal records (persistent bests), or null when game elements are hidden. */
records: ProfileRecords | null;
/** Achievement cards, or null when game elements are hidden. */
- achievements: AchievementView[] | null;
+ achievements: AchievementView[] | null; /**
+ * Where the learner stands against other learners, for the profile header. Null when game
+ * elements are hidden or the learner has not joined the leaderboards: a rank is only shown for
+ * people who chose to appear on the boards.
+ */
+ standing: ProfileStanding | null;
+};
+
+export type ProfileStanding = {
+ /** This week's league: rank within the learner's own tier, and how many learners are in it. */
+ league: {
+ tier: LeagueTier;
+ rank: number;
+ groupSize: number;
+ /** Ranks at or better than this go up a tier at the Monday reset; 0 when nobody does. */
+ promotionZone: number;
+ /** Null in the top tier. */
+ nextTier: LeagueTier | null;
+ } | null;
+ /** All-time XP rank among every learner on the leaderboards. */
+ allTime: { rank: number; total: number } | null;
+ /** Weekly course boards the learner finished in the top three. */
+ topThreeFinishes: number;
};
export type AchievementViewTier = { label: string; target: number };
@@ -80,6 +102,24 @@ export type OwnerProfileView = PublicProfileView & {
isOwner: true;
profilePublic: boolean;
creditsBalance: number | null;
- /** Credits granted this visit from newly reached achievement tiers. */
- achievementRewards: { count: number; credits: number };
+ /** Reached achievement tiers whose credits wait for the learner to claim them; empty when credits are off. */
+ achievementClaims: AchievementClaim[];
+ /** Set the first time the owner is seen at a new career tier, so the page can celebrate it once. */
+ careerPromotion: { tier: CareerTier } | null;
+ /** Progress toward the next career tier, including the average score. Owner-only; null when career levels are off. */
+ career: CareerProgress | null;
+};
+
+/** One achievement with reached tiers that have not been paid yet. */
+export type AchievementClaim = { id: string; tiers: number[]; credits: number };
+
+/** POST /api/v1/learner/achievements/:achievementId/claim */
+export type AchievementClaimResult = {
+ id: string;
+ title: string;
+ /** Label of the highest tier this claim paid, e.g. "Gold". */
+ tierLabel: string | null;
+ tiers: number[];
+ credits: number;
+ balance: number;
};
diff --git a/server/src/shared/engagement/engine.ts b/server/src/shared/engagement/engine.ts
index 970dcfaf1..73be18f07 100644
--- a/server/src/shared/engagement/engine.ts
+++ b/server/src/shared/engagement/engine.ts
@@ -41,6 +41,8 @@ export type MascotReaction = {
voice?: string;
/** XP the moment earned, shown beside the line; absent when XP is off or hidden. */
xp?: number;
+ /** New XP level reached when `ruleId === "level-up"`. */
+ level?: number;
/** A next step the learner may take from the bubble. */
action?: MascotAction;
};
@@ -55,6 +57,8 @@ export type EngagementEngineOptions = {
platform: EngagementPlatform;
transport: (request: TrackEventRequest) => Promise;
present: (reaction: MascotReaction) => void;
+ /** Receives all newly recorded events in a batch, including lower-priority ones that did not win the mascot bubble. */
+ onEvents?: (events: readonly RecordedEngagementEvent[], rewards?: TrackEventResult["rewards"], shownRuleId?: string | null) => void;
storage?: EngagementStore;
now?: () => number;
/** Picks among a rule's lines; injectable so tests are deterministic. */
@@ -119,8 +123,16 @@ export function createEngagementEngine(options: EngagementEngineOptions): Engage
/** Picks, casts and presents the reaction to a batch of events, or returns null for none. */
function respond(events: readonly RecordedEngagementEvent[], rewards?: TrackEventResult["rewards"]): MascotReaction | null {
+ const fresh = events.filter((candidate) => candidate.isNew);
const rules = options.rules ?? ENGAGEMENT_RULES;
const rule = pickRule(matchingRules(events, rules));
+ if (fresh.length > 0) {
+ try {
+ options.onEvents?.(fresh, rewards, rule?.id ?? null);
+ } catch {
+ // Side-listeners must never block the primary mascot reaction.
+ }
+ }
if (!rule) return null;
if (rule.cooldownMs) storage.set(COOLDOWN_PREFIX + rule.id, String(now()));
@@ -147,6 +159,7 @@ export function createEngagementEngine(options: EngagementEngineOptions): Engage
message: rule.messages[line]!,
...(rule.clip ? { voice: dotClipUrl(rule.clip) } : {}),
...(rewards?.xp ? { xp: rewards.xp } : {}),
+ ...(event?.type === "level_up" ? { level: event.payload.level } : {}),
...(action ? { action } : {}),
};
options.present(reaction);
diff --git a/server/src/shared/engagement/mascot-messages.en.json b/server/src/shared/engagement/mascot-messages.en.json
index 623909a54..870145642 100644
--- a/server/src/shared/engagement/mascot-messages.en.json
+++ b/server/src/shared/engagement/mascot-messages.en.json
@@ -12,6 +12,7 @@
"quiz-repeat-miss": ["Let's look again!"],
"chapter-lingering": ["Need a hint?"],
"level-up": ["Level up!"],
+ "career-tier-up": ["New career tier!"],
"weekly-goal-met-with-freeze": ["Goal met! You earned a freeze!"],
"weekly-goal-met": ["Weekly goal met!"],
"daily-goal-met": ["Daily goal done!"],
diff --git a/server/src/shared/engagement/rules.ts b/server/src/shared/engagement/rules.ts
index fb010aa55..ea7a4f969 100644
--- a/server/src/shared/engagement/rules.ts
+++ b/server/src/shared/engagement/rules.ts
@@ -161,6 +161,15 @@ export const ENGAGEMENT_RULES: readonly EngagementRule[] = [
matches: (event) => event.type === "chapter_lingering",
action: () => ({ label: "Ask a mentor", intent: "ask-help" }),
},
+ {
+ id: "career-tier-up",
+ priority: 95,
+ role: "celebrator",
+ state: "graduation",
+ messages: lines("career-tier-up"),
+ matches: (event) => event.type === "career_tier_up",
+ action: () => ({ label: "See your path", href: "/profile" }),
+ },
{
id: "level-up",
priority: 90,
diff --git a/server/tests/api/rewards-marketplace.test.ts b/server/tests/api/rewards-marketplace.test.ts
index d3504a7b6..78c91fb70 100644
--- a/server/tests/api/rewards-marketplace.test.ts
+++ b/server/tests/api/rewards-marketplace.test.ts
@@ -3,7 +3,8 @@ import request from "supertest";
import { createApp } from "../../src/app.js";
import { prisma } from "../../src/db/prisma.js";
import { earnCredits } from "../../src/services/gamification/credits.js";
-import { createCourseFixture } from "../helpers/fixtures.js";
+import { recordCareerTierUp } from "../../src/services/engagement/events.js";
+import { completeChapter, createCourseFixture } from "../helpers/fixtures.js";
const app = createApp();
let fx: Awaited>;
@@ -79,5 +80,50 @@ describe("rewards marketplace & public career identity", () => {
learningInPublic: true,
cosmetic: "sparkle",
});
+ // The quiz average is owner-only; the public card never carries it.
+ expect(pub.body.data).not.toHaveProperty("career");
+
+ const own = await request(app).get("/api/v1/learner/my-profile").set(auth());
+ expect(own.status).toBe(200);
+ expect(own.body.data.career).toMatchObject({ tier: "INTERN", nextTier: "JUNIOR", requiredForNext: { courses: 2, minScore: 70 } });
+ expect(own.body.data.careerTier).toBe(own.body.data.career.tier);
+ expect(own.body.data.careerPromotion).toBeNull();
+ });
+
+ it("waits for the learner to claim achievement credits, and pays each tier once", async () => {
+ await completeChapter(fx.enrollment.id, fx.chapterA.id);
+
+ const before = await request(app).get("/api/v1/learner/my-profile").set(auth());
+ expect(before.status).toBe(200);
+ expect(before.body.data.achievementClaims).toContainEqual({ id: "chapters", tiers: [0], credits: 20 });
+ const balance = before.body.data.creditsBalance as number;
+
+ // Opening the profile no longer pays on its own.
+ const again = await request(app).get("/api/v1/learner/my-profile").set(auth());
+ expect(again.body.data.creditsBalance).toBe(balance);
+
+ const claim = await request(app).post("/api/v1/learner/achievements/chapters/claim").set(auth());
+ expect(claim.status).toBe(200);
+ expect(claim.body.data).toMatchObject({ id: "chapters", tiers: [0], credits: 20, balance: balance + 20 });
+
+ const repeat = await request(app).post("/api/v1/learner/achievements/chapters/claim").set(auth());
+ expect(repeat.status).toBe(400);
+ const unknown = await request(app).post("/api/v1/learner/achievements/not-a-thing/claim").set(auth());
+ expect(unknown.status).toBe(404);
+
+ const after = await request(app).get("/api/v1/learner/my-profile").set(auth());
+ expect(after.body.data.achievementClaims.some((c: { id: string }) => c.id === "chapters")).toBe(false);
+ });
+
+ it("celebrates a career tier once, and never the starting tier", async () => {
+ expect(await recordCareerTierUp(fx.learner.id, "web", "INTERN")).toBeNull();
+ const first = await recordCareerTierUp(fx.learner.id, "web", "JUNIOR");
+ expect(first).toMatchObject({ type: "career_tier_up", payload: { tier: "JUNIOR" }, isNew: true });
+ expect(await recordCareerTierUp(fx.learner.id, "web", "JUNIOR")).toBeNull();
+
+ // The profile page celebrates independently once per tier so finishing a course does not suppress it.
+ const profileFirst = await recordCareerTierUp(fx.learner.id, "web", "JUNIOR", "profile");
+ expect(profileFirst).toMatchObject({ type: "career_tier_up", payload: { tier: "JUNIOR" }, isNew: true });
+ expect(await recordCareerTierUp(fx.learner.id, "web", "JUNIOR", "profile")).toBeNull();
});
});
diff --git a/server/tests/unit/shared/engagement/engine.test.ts b/server/tests/unit/shared/engagement/engine.test.ts
index cf294ce31..a0125428a 100644
--- a/server/tests/unit/shared/engagement/engine.test.ts
+++ b/server/tests/unit/shared/engagement/engine.test.ts
@@ -218,4 +218,28 @@ describe("engagement engine", () => {
});
await expect(brokenUi.track({ type: "enrolled", courseId: "course" })).resolves.toBeNull();
});
+
+ it("delivers all fresh events to onEvents even when a higher-priority rule wins the mascot bubble", async () => {
+ const batches: Array<{ types: string[]; ruleId: string | null | undefined; xp?: number }> = [];
+ const engine = createEngagementEngine({
+ platform: "web",
+ transport: async () => ({
+ events: [
+ recorded({ type: "course_completed", courseId: "c", chapterId: null }),
+ recorded({ type: "level_up", payload: { level: 4 } }),
+ recorded({ type: "weekly_goal_met", payload: { freezeEarned: true } }),
+ ],
+ rewards: { xp: 50 },
+ }),
+ present: () => undefined,
+ onEvents: (events, rewards, shownRuleId) => {
+ batches.push({ types: events.map((e) => e.type), ruleId: shownRuleId, xp: rewards?.xp });
+ },
+ });
+ const reaction = await engine.track({ type: "chapter_completed", chapterId: "chapter" });
+ expect(reaction).toMatchObject({ ruleId: "course-graduation" });
+ expect(batches).toEqual([
+ { types: ["course_completed", "level_up", "weekly_goal_met"], ruleId: "course-graduation", xp: 50 },
+ ]);
+ });
});