From 6e44ccf595d5471be874fdf548c8e2718ed7dfde Mon Sep 17 00:00:00 2001 From: Faisal Misbah Date: Wed, 25 Nov 2026 07:52:50 +0500 Subject: [PATCH 1/6] feat: profile career path redesign, achievement claims and shared reward celebrations --- .../src/app/(learn)/(main)/profile/page.tsx | 3 +- .../blocks/capstone-check/CertificateCard.tsx | 11 + .../learn/dashboard/leaderboard-card.tsx | 10 +- .../learn/dashboard/weekly-quests.tsx | 8 +- .../learn/leaderboard/leaderboard-page.tsx | 11 +- .../learn/rewards/rewards-marketplace.tsx | 51 +- .../profile/achievement-claim-button.tsx | 71 ++ .../profile/achievement-share-button.tsx | 2 +- .../profile/career-promotion-celebration.tsx | 24 + .../profile/public-profile-card.tsx | 664 +++++++++++++----- .../src/components/profile/reveal-more.tsx | 46 ++ .../rewards/reward-celebration-dialog.tsx | 88 +++ frontend/src/lib/celebrate.ts | 21 + frontend/src/lib/profile-view.ts | 77 ++ frontend/src/shared/api/engagement.ts | 7 + frontend/src/shared/api/public-profile.ts | 24 +- .../shared/engagement/mascot-messages.en.json | 1 + frontend/src/shared/engagement/rules.ts | 9 + frontend/tests/unit/lib/profile-view.test.ts | 76 ++ .../tests/unit/lib/sound-feedback.test.ts | 7 +- .../learning-ui/src/lib/sound-feedback.ts | 4 +- server/src/controllers/learner.ts | 6 + server/src/routes/v1/learner.ts | 1 + server/src/services/engagement/events.ts | 29 + .../src/services/gamification/achievements.ts | 61 +- server/src/services/profile/public-profile.ts | 18 +- server/src/shared/api/engagement.ts | 7 + server/src/shared/api/public-profile.ts | 24 +- .../shared/engagement/mascot-messages.en.json | 1 + server/src/shared/engagement/rules.ts | 9 + server/tests/api/rewards-marketplace.test.ts | 43 +- 31 files changed, 1144 insertions(+), 270 deletions(-) create mode 100644 frontend/src/components/profile/achievement-claim-button.tsx create mode 100644 frontend/src/components/profile/career-promotion-celebration.tsx create mode 100644 frontend/src/components/profile/reveal-more.tsx create mode 100644 frontend/src/components/rewards/reward-celebration-dialog.tsx create mode 100644 frontend/src/lib/celebrate.ts create mode 100644 frontend/src/lib/profile-view.ts create mode 100644 frontend/tests/unit/lib/profile-view.test.ts diff --git a/frontend/src/app/(learn)/(main)/profile/page.tsx b/frontend/src/app/(learn)/(main)/profile/page.tsx index 669c5007e..5ffee313d 100644 --- a/frontend/src/app/(learn)/(main)/profile/page.tsx +++ b/frontend/src/app/(learn)/(main)/profile/page.tsx @@ -15,9 +15,10 @@ export default async function ProfilePage() {
+

Your learning identity

Profile

- This is what the public sees on your shared profile page. + Who you are becoming, the milestones behind you, and where your learning goes next. Your shared profile page shows the same card, without your quiz average.

diff --git a/frontend/src/blocks/capstone-check/CertificateCard.tsx b/frontend/src/blocks/capstone-check/CertificateCard.tsx index 77514e960..3ab1a4e66 100644 --- a/frontend/src/blocks/capstone-check/CertificateCard.tsx +++ b/frontend/src/blocks/capstone-check/CertificateCard.tsx @@ -8,6 +8,7 @@ import { cn } from "@/lib/utils"; import { Button, buttonVariants } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import type { CertificateView, MyCertificateState } from "@/shared/lib/certificates"; +import { RewardCelebrationDialog, type RewardCelebration } from "@/components/rewards/reward-celebration-dialog"; // Shown under an approved capstone. The learner confirms their name once, then gets the // verify link, Add to LinkedIn and the share image. @@ -17,6 +18,7 @@ export function CertificateCard({ courseSlug }: { courseSlug: string }) { const [name, setName] = useState(""); const [error, setError] = useState(null); const [claiming, setClaiming] = useState(false); + const [celebration, setCelebration] = useState(null); useEffect(() => { let live = true; @@ -44,6 +46,14 @@ export function CertificateCard({ courseSlug }: { courseSlug: string }) { json: { recipientName: name }, }); setState((current) => (current ? { ...current, certificate: result.certificate } : current)); + setCelebration({ + size: "large", + icon: Award, + kicker: "Certificate issued", + title: result.certificate.title, + description: `Issued to ${result.certificate.recipientName}. Anyone can check it with code ${result.certificate.code}.`, + action: { label: "View certificate", href: `/verify/${result.certificate.code}` }, + }); } catch (caught) { setError(caught instanceof ApiError ? caught.message : "Could not issue the certificate. Try again."); } finally { @@ -89,6 +99,7 @@ export function CertificateCard({ courseSlug }: { courseSlug: string }) { {state.eligibility.missing.map((item) =>
  • {item}
  • )} )} + setCelebration(null)} /> ); } diff --git a/frontend/src/components/learn/dashboard/leaderboard-card.tsx b/frontend/src/components/learn/dashboard/leaderboard-card.tsx index c6c38a091..2f54e9275 100644 --- a/frontend/src/components/learn/dashboard/leaderboard-card.tsx +++ b/frontend/src/components/learn/dashboard/leaderboard-card.tsx @@ -1,5 +1,6 @@ "use client"; +import { toast } from "@/components/ui/app-toast"; import { useState, useTransition } from "react"; import { ChevronDown, Trophy } from "lucide-react"; import { Button } from "@/components/ui/button"; @@ -111,18 +112,16 @@ export function LeaderboardCard({ }) { const [view, setView] = useState(initial); const [courseId, setCourseId] = useState(initialCourseId); - const [error, setError] = useState(null); const [pending, startTransition] = useTransition(); if (!view || view.status === "disabled") return null; function run(work: () => Promise) { - setError(null); startTransition(async () => { try { setView(await work()); } catch { - setError("Something went wrong. Please try again."); + toast("Something went wrong. Please try again.", "error"); } }); } @@ -235,11 +234,6 @@ export function LeaderboardCard({
    )} - {error ? ( -

    - {error} -

    - ) : null} ); diff --git a/frontend/src/components/learn/dashboard/weekly-quests.tsx b/frontend/src/components/learn/dashboard/weekly-quests.tsx index fefd9fc2b..81ce45789 100644 --- a/frontend/src/components/learn/dashboard/weekly-quests.tsx +++ b/frontend/src/components/learn/dashboard/weekly-quests.tsx @@ -6,7 +6,7 @@ import { CheckCircle2, Gift, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { InfoTip } from "@/components/ui/info-tip"; import { toast } from "@/components/ui/app-toast"; -import { playFeedback } from "@/lib/sound-feedback"; +import { celebrate } from "@/lib/celebrate"; import type { WeeklyQuestsView } from "@/shared/api/quests"; // Weekly quests: a compact entry at the top of the dashboard; the full mission @@ -42,7 +42,7 @@ export function WeeklyQuests() { if (!open && dialog.open) dialog.close(); }, [open]); - async function claim(id: string) { + async function claim(id: string, anchor: HTMLElement) { setBusy(id); try { const res = await fetch(`/api/v1/learner/quests/${id}/claim`, { method: "POST" }); @@ -51,8 +51,8 @@ export function WeeklyQuests() { toast(json?.message ?? "Could not claim this quest", "error"); return; } + celebrate("small", anchor); setState(json.data); - playFeedback("success"); toast("Quest reward claimed", "success"); router.refresh(); } catch { @@ -157,7 +157,7 @@ export function WeeklyQuests() { disabled={busy === quest.id} loading={busy === quest.id} loadingLabel="Claiming…" - onClick={() => void claim(quest.id)} + onClick={(event) => void claim(quest.id, event.currentTarget)} > Claim diff --git a/frontend/src/components/learn/leaderboard/leaderboard-page.tsx b/frontend/src/components/learn/leaderboard/leaderboard-page.tsx index e7e8bcad6..4c6ded49f 100644 --- a/frontend/src/components/learn/leaderboard/leaderboard-page.tsx +++ b/frontend/src/components/learn/leaderboard/leaderboard-page.tsx @@ -1,5 +1,6 @@ "use client"; +import { toast } from "@/components/ui/app-toast"; import { useState, useTransition } from "react"; import Link from "next/link"; import { ChevronDown, Trophy } from "lucide-react"; @@ -138,17 +139,15 @@ export function LeaderboardPage({ }) { const [selection, setSelection] = useState(initialSelection); const [view, setView] = useState(initial); - const [error, setError] = useState(null); const [pending, startTransition] = useTransition(); const confettiRef = useLeaderboardConfetti(view); function run(work: () => Promise) { - setError(null); startTransition(async () => { try { setView(await work()); } catch { - setError("Something went wrong. Please try again."); + toast("Something went wrong. Please try again.", "error"); } }); } @@ -401,12 +400,6 @@ export function LeaderboardPage({ )} - - {error ? ( -

    - {error} -

    - ) : null} ); diff --git a/frontend/src/components/learn/rewards/rewards-marketplace.tsx b/frontend/src/components/learn/rewards/rewards-marketplace.tsx index f5e07d2c2..ddf607cc2 100644 --- a/frontend/src/components/learn/rewards/rewards-marketplace.tsx +++ b/frontend/src/components/learn/rewards/rewards-marketplace.tsx @@ -5,6 +5,9 @@ import { useRouter } from "next/navigation"; import { Shield, Sparkles, Zap } from "lucide-react"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; +import { toast } from "@/components/ui/app-toast"; +import { celebrate } from "@/lib/celebrate"; +import { RewardCelebrationDialog, type RewardCelebration } from "@/components/rewards/reward-celebration-dialog"; import { CosmeticDot } from "./cosmetic-dot"; type RewardItem = { @@ -35,6 +38,7 @@ export default function RewardsMarketplace() { const [state, setState] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(null); + const [unlocked, setUnlocked] = useState(null); const refresh = useCallback(async () => { try { @@ -50,20 +54,32 @@ export default function RewardsMarketplace() { void refresh(); }, [refresh]); - async function act(kind: "buy" | "equip" | "unequip" | "use", id?: string) { + async function act(kind: "buy" | "equip" | "unequip" | "use", id: string | undefined, anchor: HTMLElement) { + const item = id ? state?.rewards.find((reward) => reward.id === id) : undefined; setBusy(id ?? "active"); - setError(null); try { if (kind === "buy" && id) { const res = await fetch(`/api/v1/learner/rewards/${id}/purchase`, { method: "POST" }); const json = await res.json().catch(() => null); if (!res.ok) { - setError(json?.message ?? "Purchase failed"); + toast(json?.message ?? "Purchase failed", "error"); return; } // The purchase endpoint returns a PurchaseResult ({ balance, owned, quantity }), not the // full rewards view: re-fetch rather than dropping that partial object into `state`, // which would have no `rewards` array and collapse the page to its empty fallback. + if (item?.kind === "cosmetic") { + setUnlocked({ + size: "medium", + icon: Sparkles, + kicker: "Reward unlocked", + title: item.label, + description: "It's yours to keep. Equip it to dress your mascot.", + }); + } else { + celebrate("small", anchor); + toast(item ? `${item.label} added to your pocket` : "Purchase complete", "success"); + } await refresh(); router.refresh(); return; @@ -72,9 +88,11 @@ export default function RewardsMarketplace() { const res = await fetch(`/api/v1/learner/rewards/${id}/use`, { method: "POST" }); const json = await res.json().catch(() => null); if (!res.ok) { - setError(json?.message ?? "Could not use this item"); + toast(json?.message ?? "Could not use this item", "error"); return; } + celebrate("small", anchor); + toast("×2 XP boost is active", "success"); await refresh(); router.refresh(); return; @@ -86,13 +104,19 @@ export default function RewardsMarketplace() { }); const json = await res.json().catch(() => null); if (!res.ok) { - setError(json?.message ?? "Could not update the equipped reward"); + toast(json?.message ?? "Could not update the equipped reward", "error"); return; } + if (kind === "equip") { + celebrate("small", anchor); + toast(item ? `${item.label} equipped` : "Equipped", "success"); + } else { + toast("Cosmetic removed", "success"); + } await refresh(); router.refresh(); } catch (reason) { - setError(reason instanceof Error ? reason.message : "Something went wrong"); + toast(reason instanceof Error ? reason.message : "Something went wrong", "error"); } finally { setBusy(null); } @@ -127,27 +151,27 @@ export default function RewardsMarketplace() {

    {status}

    {isCosmetic && !reward.owned ? ( - ) : isCosmetic && equipped ? ( - ) : isCosmetic ? ( - ) : !reward.owned ? ( - ) : reward.effect === "xp_boost" ? ( - ) : ( - )} @@ -201,9 +225,8 @@ export default function RewardsMarketplace() {
    ) : null} - {error ?

    {error}

    : null} - {section("Cosmetics", "One-time unlocks that dress your mascot. Equip one as the active look.", cosmetics)} + setUnlocked(null)} /> {section("Utility", "Consumables held in your pocket for a temporary edge; they never grant permanent XP or career progress.", consumables)} ); diff --git a/frontend/src/components/profile/achievement-claim-button.tsx b/frontend/src/components/profile/achievement-claim-button.tsx new file mode 100644 index 000000000..ff8871d42 --- /dev/null +++ b/frontend/src/components/profile/achievement-claim-button.tsx @@ -0,0 +1,71 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { Trophy } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { toast } from "@/components/ui/app-toast"; +import { apiFetch, ApiError } from "@/lib/api-client"; +import type { AchievementClaimResult } from "@/shared/api/public-profile"; +import { RewardCelebrationDialog, type RewardCelebration } from "@/components/rewards/reward-celebration-dialog"; + +/** Pays an achievement's reached tiers, then shows the reward card and refreshes the balance. */ +export function AchievementClaimButton({ + achievementId, + credits, + className, +}: { + achievementId: string; + credits: number; + className?: string; +}) { + const router = useRouter(); + const [busy, setBusy] = useState(false); + const [reward, setReward] = useState(null); + + async function claim() { + setBusy(true); + try { + const result = await apiFetch(`/api/v1/learner/achievements/${encodeURIComponent(achievementId)}/claim`, { + method: "POST", + }); + setReward({ + size: "medium", + icon: Trophy, + kicker: "Achievement claimed", + title: result.tierLabel ? `${result.title}: ${result.tierLabel}` : result.title, + description: `Your balance is now ${result.balance.toLocaleString()} Build Credits.`, + credits: result.credits, + action: { label: "Spend in rewards", href: "/rewards" }, + }); + } catch (error) { + toast(error instanceof ApiError ? error.message : "Could not claim this achievement", "error"); + } finally { + setBusy(false); + } + } + + return ( + <> + + { + if (!reward) return; + setReward(null); + router.refresh(); + }} + /> + + ); +} diff --git a/frontend/src/components/profile/achievement-share-button.tsx b/frontend/src/components/profile/achievement-share-button.tsx index f7b41491a..42eeb25cc 100644 --- a/frontend/src/components/profile/achievement-share-button.tsx +++ b/frontend/src/components/profile/achievement-share-button.tsx @@ -11,7 +11,7 @@ export function AchievementShareButton({ title }: { title: string }) { async function share() { const url = typeof window !== "undefined" ? window.location.href : ""; - const line = `I unlocked "${title}" on Buildment`; + const line = `I unlocked "${title}" on Edorax`; if (typeof navigator !== "undefined" && typeof navigator.share === "function") { try { await navigator.share({ title: `${title} · Buildment`, text: line, url }); diff --git a/frontend/src/components/profile/career-promotion-celebration.tsx b/frontend/src/components/profile/career-promotion-celebration.tsx new file mode 100644 index 000000000..937a48611 --- /dev/null +++ b/frontend/src/components/profile/career-promotion-celebration.tsx @@ -0,0 +1,24 @@ +"use client"; + +import { useState } from "react"; +import { Award } from "lucide-react"; +import type { CareerTier } from "@/shared/api/gamification"; +import { CAREER_REQUIREMENTS, CAREER_TIER_LABELS, nextCareerTier } from "@/shared/gamification/career"; +import { RewardCelebrationDialog, type RewardCelebration } from "@/components/rewards/reward-celebration-dialog"; + +/** Opens once when the server reports the owner reached a new career tier for the first time. */ +export function CareerPromotionCelebration({ tier }: { tier: CareerTier }) { + const [reward, setReward] = useState(() => { + const next = nextCareerTier(tier); + return { + size: "large", + icon: Award, + kicker: "New career tier", + title: `You are now ${CAREER_TIER_LABELS[tier]}`, + description: next + ? `Verified mastery got you here. ${CAREER_TIER_LABELS[next]} needs ${CAREER_REQUIREMENTS[next].courses} completed courses and a ${CAREER_REQUIREMENTS[next].minScore}% average.` + : "You reached the highest career tier on Edorax.", + }; + }); + return setReward(null)} />; +} diff --git a/frontend/src/components/profile/public-profile-card.tsx b/frontend/src/components/profile/public-profile-card.tsx index 78c7a164d..5acf86e79 100644 --- a/frontend/src/components/profile/public-profile-card.tsx +++ b/frontend/src/components/profile/public-profile-card.tsx @@ -1,16 +1,23 @@ -import type { AchievementView, PublicProfileView } from "@/shared/api/public-profile"; +import type { AchievementClaim, AchievementView, PublicProfileView } from "@/shared/api/public-profile"; +import type { CareerProgress } from "@/shared/api/gamification"; import Link from "next/link"; import { rewardForTier } from "@/shared/gamification/achievements"; -import { levelProgress } from "@/shared/gamification/levels"; import { Award, BookOpen, + Building2, Calendar, + Check, Clock, + Compass, Flame, GraduationCap, Medal, Moon, + ShieldCheck, + Sparkles, + Sprout, + Star, Sunrise, Target, Timer, @@ -22,104 +29,429 @@ import { AchievementShareButton } from "./achievement-share-button"; import { CAREER_REQUIREMENTS, CAREER_TIER_LABELS, CAREER_TIERS, careerTierIndex } from "@/shared/gamification/career"; import { LEAGUE_TIER_LABELS } from "@/shared/gamification/leagues"; import { CosmeticDot } from "@/components/learn/rewards/cosmetic-dot"; +import { Dot, type DotMood } from "@/components/brand/dot"; import { cn } from "@/lib/utils"; +import { careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, shortDate, type CareerNodeState } from "@/lib/profile-view"; import { ShareProfileButton } from "./share-profile-button"; -import { ShowMore } from "./show-more"; +import { RevealMore } from "./reveal-more"; +import { AchievementClaimButton } from "./achievement-claim-button"; +import { CareerPromotionCelebration } from "./career-promotion-celebration"; import { buttonVariants } from "@/components/ui/button"; +import type { CareerTier } from "@/shared/api/gamification"; type CardProfile = PublicProfileView & { profilePublic?: boolean; creditsBalance?: number | null; - achievementRewards?: { count: number; credits: number }; + achievementClaims?: AchievementClaim[]; + careerPromotion?: { tier: CareerTier } | null; + career?: CareerProgress | null; }; -function Stat({ value, label }: { value: string; label: string }) { +type Claims = Map; + +const TIER_ICONS: Record = { + INTERN: Sprout, + JUNIOR: Sparkles, + MID: ShieldCheck, + SENIOR: Building2, + STAFF: Compass, + PRINCIPAL: Star, +}; + +const ACH_ICONS: Record = { book: BookOpen, cap: GraduationCap, flame: Flame, zap: Zap, target: Target, trophy: Trophy, moon: Moon, sun: Sunrise, calendar: Calendar }; + +function SectionHeading({ id, title, description }: { id: string; title: string; description: string }) { + return ( +
    +

    + {title} +

    +

    {description}

    +
    + ); +} + +function HeroStat({ value, label }: { value: string; label: string }) { + return ( +
    +

    {value}

    +

    {label}

    +
    + ); +} + +function HeroTag({ children, highlight = false }: { children: React.ReactNode; highlight?: boolean }) { + return ( + + {children} + + ); +} + +// One card for the whole page, in two sizes, so records, achievements and the career map share +// corners, the chunky bottom edge, the icon tile and the header row. Each section has one theme +// colour for its icon tiles and progress bars. +type Tone = "cobalt" | "yellow" | "soft"; + +const TONES: Record = { + cobalt: { tile: "bg-primary text-primary-foreground", bar: "bg-primary" }, + yellow: { tile: "bg-[var(--brand-yellow)] text-[#0a0f2c]", bar: "bg-[var(--brand-yellow)]" }, + soft: { tile: "bg-secondary text-primary", bar: "bg-primary/70" }, +}; + +/** The chunky edge every card on the page uses. */ +const CARD_EDGE = "rounded-2xl border-2 border-b-[5px] bg-card"; + +function IconTile({ icon: Icon, tone, size = "large" }: { icon: LucideIcon; tone: Tone; size?: "large" | "compact" }) { + return ( + + + + ); +} + +function ProfileCard({ + tone, + icon, + size = "large", + badge, + muted = false, + children, +}: { + tone: Tone; + icon: LucideIcon; + size?: "large" | "compact"; + /** Shown on the right of the header row. */ + badge?: React.ReactNode; + /** Locked items fade back. */ + muted?: boolean; + children: React.ReactNode; +}) { + return ( +
    +
    + + {badge} +
    +
    {children}
    +
    + ); +} + +function Pill({ children }: { children: React.ReactNode }) { + return {children}; +} + +function CardLabel({ children }: { children: React.ReactNode }) { + return

    {children}

    ; +} + +function ProgressBar({ percent, tone }: { percent: number; tone: Tone }) { return ( -
    -

    {value}

    -

    {label}

    +
    +
    ); } -function Ring({ percent, center, label }: { percent: number; center: string; label: string }) { - const clamped = Math.max(0, Math.min(100, percent)); - const r = 34; - const circumference = 2 * Math.PI * r; - const offset = circumference * (1 - clamped / 100); +/** Dot is drawn as decoration; the text beside it carries the meaning. */ +function DotAside({ mood, size = 44 }: { mood: DotMood; size?: number }) { + return ( + + + + ); +} + +const NODE_BUBBLE: Record = { + done: "bg-primary text-primary-foreground", + current: "size-20 bg-[var(--brand-yellow)] text-[#0a0f2c] ring-4 ring-[var(--brand-yellow)]/25", + next: "bg-secondary text-primary ring-2 ring-primary/40", + locked: "bg-muted text-muted-foreground", +}; + +function CareerMap({ profile, isOwner }: { profile: CardProfile; isOwner: boolean }) { + const currentIndex = careerTierIndex(profile.careerTier); + const nextTier = CAREER_TIERS[currentIndex + 1] ?? null; + const mastery = profile.career ? { completedCourses: profile.career.completedCourses, avgScore: profile.career.avgScore } : null; + const fill = CAREER_TIERS.length > 1 ? (currentIndex / (CAREER_TIERS.length - 1)) * 100 : 100; + return ( -
    - - - - -
    -

    {center}

    -

    {label}

    +
    +
    +
    + +
    +

    Edorax Career Path

    +

    Verified mastery moves you forward, one tier at a time.

    +
    +
    + + {currentIndex + 1} of {CAREER_TIERS.length} milestones + +
    + +
    +
    +
      + {/* The track runs between the first and last node centres; the filled part ends at the current tier. */} + + + + {CAREER_TIERS.map((tier, index) => { + const state = careerNodeState(index, currentIndex); + const Icon = TIER_ICONS[tier]; + return ( +
    1. +
      + + + {state === "done" ? ( + + + + ) : null} + +
      + {state === "current" ? ( + + {isOwner ? "You are here" : "Current tier"} + + ) : null} +

      + {CAREER_TIER_LABELS[tier]} +

      +

      + {state === "done" ? "Reached" : careerRequirementLine(CAREER_REQUIREMENTS[tier])} +

      +
    2. + ); + })} +
    +
    + +
    +
    + +

    + {nextTier ? ( + <> + Next up: {CAREER_TIER_LABELS[nextTier]} +
    + {nextStepCopy(nextTier, CAREER_REQUIREMENTS[nextTier], isOwner ? mastery : null)} + + ) : ( + The highest career tier is reached. + )} +

    +
    + {isOwner && nextTier ? ( + + {profile.currentCourse ? "Continue learning" : "Find a course"} + + ) : null} +
    ); } -function RecordTile({ icon: Icon, label, value, sub }: { icon?: LucideIcon; label: string; value: string; sub?: string }) { +function RecordCard({ + icon, + badge, + label, + value, + unit, + caption, + date, + empty = false, +}: { + icon: LucideIcon; + badge: string; + label: string; + value: string; + unit?: string; + caption: string; + date?: string; + /** No record yet: Dot keeps the learner company instead of a bare "Not yet". */ + empty?: boolean; +}) { return ( -
    -
    - {Icon ? : null} -

    {label}

    + {badge}}> + {label} +

    + {value} {unit ? {unit} : null} +

    +
    + {empty ? : null} +

    {caption}

    + {date ?

    {date}

    : null} +
    + ); +} + +function RecordTile({ icon, label, value, sub }: { icon: LucideIcon; label: string; value: string; sub?: string }) { + return ( + + {label}

    {value}

    {sub ?

    {sub}

    : null} +
    + ); +} + +function Records({ records }: { records: NonNullable }) { + const streak = records.longestStreakDays; + const big = ( +
    + 0 ? "The longest learning run so far." : "A streak starts with one day of learning."} + empty={streak === 0} + /> + +
    ); + return ( +
    + } + preview={big} + > +
    + + + + + 0 ? `${records.longestSessionMinutes} min` : "Not yet"} /> + + +
    +
    +
    + ); } -const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function shortDate(key: string): string { - const [, m, d] = key.split("-"); - const month = MONTHS[Number(m) - 1] ?? m; - return `${month} ${Number(d)}`; +function nextRewardFor(a: AchievementView): number | null { + return a.tier + 1 < a.tiers.length ? rewardForTier(a.tier + 1) : a.nextReward ?? null; } -const ACH_ICONS: Record = { book: BookOpen, cap: GraduationCap, flame: Flame, zap: Zap, target: Target, trophy: Trophy, moon: Moon, sun: Sunrise, calendar: Calendar }; +function achievementPercent(a: AchievementView): number { + return a.nextTarget === null ? 100 : Math.round(a.progress * 100); +} + +function FeaturedAchievement({ a, claim }: { a: AchievementView; claim?: AchievementClaim }) { + const reward = nextRewardFor(a); + const earned = a.tier >= 0 ? a.tiers[a.tier]?.label : null; + const percent = achievementPercent(a); + return ( + {reward !== null ? `Next reward · ${reward} credits` : earned ? `${earned} · earned` : "In progress"}} + > + {a.category} collection +

    {a.title}

    +

    {a.description}

    +
    +
    + {a.nextTarget === null ? "All tiers reached" : `${a.value} / ${a.nextTarget}`} + {percent}% +
    + + {claim ? : null} +
    +
    + ); +} -function AchievementCard({ a }: { a: AchievementView }) { +function AchievementCard({ a, claim }: { a: AchievementView; claim?: AchievementClaim }) { const maxed = a.tier >= 0 && a.nextTarget === null; const locked = a.tier < 0; - const Icon = ACH_ICONS[a.icon] ?? Trophy; const tierLabel = a.tier >= 0 ? a.tiers[a.tier]?.label : "Locked"; const earnedCredits = Array.from({ length: a.tier + 1 }, (_, i) => rewardForTier(i)).reduce((sum, n) => sum + n, 0); - const nextReward = a.tier + 1 < a.tiers.length ? rewardForTier(a.tier + 1) : a.nextReward ?? null; + const nextReward = nextRewardFor(a); return ( -
    -
    - - - -
    -

    {a.title}

    -

    {tierLabel}

    -
    - {!locked ? : null} + : null} + > +

    {a.title}

    +

    {tierLabel}

    +
    + +

    + {maxed ? `Maxed · earned ${earnedCredits}` : `${a.value} / ${a.nextTarget} · +${nextReward ?? 0} credits`} +

    + {claim ? : null}
    -
    -
    + + ); +} + +function Achievements({ achievements, claims }: { achievements: AchievementView[]; claims: Claims }) { + const featured = featuredAchievements(achievements, 2, new Set(claims.keys())); + const heading = ; + const preview = + featured.length > 0 ? ( +
    + {featured.map((a) => ( + + ))}
    -

    - {maxed ? `Maxed · earned ${earnedCredits}` : `${a.value} / ${a.nextTarget} · +${nextReward ?? 0} credits`} -

    -
    + ) : null; + return ( +
    + +
    + {achievements.map((a) => ( + + ))} +
    +
    +
    ); } @@ -130,152 +462,98 @@ export function PublicProfileCard({ profile: CardProfile; variant?: "public" | "owner"; }) { + const isOwner = variant === "owner"; + // The owner page already has a "Profile" h1; on the public page the learner's name is the page title. + const NameHeading = isOwner ? "h2" : "h1"; const headline = [profile.headline, profile.learningInPublic ? "Learning in public" : null].filter(Boolean).join(" · ") || null; - const currentIndex = careerTierIndex(profile.careerTier); - const xp = profile.xpTotal === null ? "Hidden" : profile.xpTotal.toLocaleString(); - const league = profile.leagueTier ? LEAGUE_TIER_LABELS[profile.leagueTier] : "Hidden"; - const isOwner = variant === "owner"; - const xpInfo = profile.xpTotal === null ? null : levelProgress(profile.xpTotal); - const nextTier = CAREER_TIERS[currentIndex + 1] ?? null; - const coursesTarget = nextTier ? CAREER_REQUIREMENTS[nextTier].courses : Math.max(1, profile.coursesCompleted); - const coursesPercent = nextTier ? Math.min(100, Math.round((profile.coursesCompleted / Math.max(1, coursesTarget)) * 100)) : 100; - - const Section = ({ children }: { children: React.ReactNode }) => - isOwner ?
    {children}
    : <>{children}; - - const careerInner = ( - <> -

    EdoraX Career Path

    -
      - {CAREER_TIERS.map((tier, index) => { - const reached = index <= currentIndex; - const current = index === currentIndex; - return ( -
    1. -
      - - - {CAREER_TIER_LABELS[tier]} - -
      - {index < CAREER_TIERS.length - 1 ? ( - - ) : null} -
    2. - ); - })} -
    - - ); + const joined = monthYear(profile.joinedAt); + const earnedAchievements = profile.achievements?.filter((a) => a.tier >= 0).length ?? null; + const claims: Claims = new Map(isOwner ? (profile.achievementClaims ?? []).map((claim) => [claim.id, claim]) : []); + const claimTotal = [...claims.values()].reduce((sum, claim) => sum + claim.credits, 0); + + const stats: { value: string; label: string }[] = []; + if (profile.xpTotal !== null) stats.push({ value: profile.xpTotal.toLocaleString(), label: "Lifetime XP" }); + if (profile.records) stats.push({ value: String(profile.records.longestStreakDays), label: "Best streak" }); + if (earnedAchievements !== null) stats.push({ value: String(earnedAchievements), label: "Achievements" }); + if (stats.length === 0) stats.push({ value: String(profile.coursesCompleted), label: "Courses completed" }); return ( -
    -
    +
    +
    {/* Hero */} -
    -
    -
    -
    -
    - +
    +
    +
    +
    +
    -

    {profile.name}

    - {headline ?

    {headline}

    : null} - - {CAREER_TIER_LABELS[profile.careerTier]} - + {profile.name} + {headline ?

    {headline}

    : null} +
    + + {CAREER_TIER_LABELS[profile.careerTier]} + + + {profile.coursesCompleted} {profile.coursesCompleted === 1 ? "course" : "courses"} completed + + {joined ? ( + + Joined {joined} + + ) : null} + {profile.currentCourse ? ( + + {profile.currentCourse.title} + + ) : null} +
    - -
    -
    - -
    -
    - -
    -
    {careerInner}
    - -
    - {xpInfo ? : } - - +
    +
    + {stats.map((stat) => ( + + ))} +
    + +
    + - {isOwner && profile.currentCourse ? ( -
    -
    -
    -

    Currently learning

    -

    {profile.currentCourse.title}

    -
    - - Continue - -
    -
    -
    -
    -
    - ) : null} + {isOwner && claimTotal > 0 ? ( + + + + {claimTotal} Build Credits are ready to claim from {claims.size}{" "} + {claims.size === 1 ? "achievement" : "achievements"}. + + + ) : null} + {isOwner && profile.careerPromotion ? : null} - {isOwner && profile.achievementRewards && profile.achievementRewards.count > 0 ? ( -
    - You earned {profile.achievementRewards.credits} Build Credits from{" "} - {profile.achievementRewards.count} new achievement{profile.achievementRewards.count === 1 ? "" : "s"}. -
    - ) : null} +
    + + +
    - {profile.records ? ( -
    -

    Records

    - , - , - , - , - , - , - , - 0 ? `${profile.records.longestSessionMinutes} min` : "Not yet"} />, - , - ]} - initial={8} - label="records" - gridClassName="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4" - /> -
    - ) : null} + {profile.records ? : null} - {profile.achievements && profile.achievements.length > 0 ? ( -
    -

    Achievements

    - ( - - ))} - initial={8} - label="achievements" - gridClassName="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4" - /> -
    - ) : null} -
    + {profile.achievements && profile.achievements.length > 0 ? : null} -

    - Verified learning on Buildment. Career tier reflects completed courses and quiz mastery, not time spent. +

    + Verified learning on Edorax. Career tier reflects completed courses and quiz mastery, not time spent.

    diff --git a/frontend/src/components/profile/reveal-more.tsx b/frontend/src/components/profile/reveal-more.tsx new file mode 100644 index 000000000..0d288603b --- /dev/null +++ b/frontend/src/components/profile/reveal-more.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { useId, useState, type ReactNode } from "react"; +import { ChevronDown } from "lucide-react"; +import { cn } from "@/lib/utils"; + +// A section-header toggle that reveals extra content below it in place, e.g. "See all records". +export function RevealMore({ + label, + hideLabel = "Show less", + heading, + preview, + children, +}: { + label: string; + hideLabel?: string; + /** The section heading rendered to the left of the toggle. */ + heading: ReactNode; + /** Always-visible content between the heading and the revealed content. */ + preview?: ReactNode; + children: ReactNode; +}) { + const [open, setOpen] = useState(false); + const panelId = useId(); + return ( + <> +
    + {heading} + +
    + {preview} + + + ); +} diff --git a/frontend/src/components/rewards/reward-celebration-dialog.tsx b/frontend/src/components/rewards/reward-celebration-dialog.tsx new file mode 100644 index 000000000..d64addf5d --- /dev/null +++ b/frontend/src/components/rewards/reward-celebration-dialog.tsx @@ -0,0 +1,88 @@ +"use client"; + +import { useEffect, useRef } from "react"; +import Link from "next/link"; +import { Coins, X, type LucideIcon } from "lucide-react"; +import { Button, buttonVariants } from "@/components/ui/button"; +import { celebrate, type CelebrationSize } from "@/lib/celebrate"; + +export type RewardCelebration = { + size: CelebrationSize; + icon: LucideIcon; + /** Short line above the title, e.g. "Achievement unlocked". */ + kicker: string; + title: string; + description: string; + /** Build Credits this moment paid, shown as a chip. */ + credits?: number; + action?: { label: string; href: string }; +}; + +/** + * The reward card shown for medium and large moments (an achievement claimed, a new career tier, + * a certificate). It plays the matching celebration when it opens. Pass null to close it. + */ +export function RewardCelebrationDialog({ reward, onClose }: { reward: RewardCelebration | null; onClose: () => void }) { + const dialogRef = useRef(null); + const iconRef = useRef(null); + + useEffect(() => { + const dialog = dialogRef.current; + if (!dialog) return; + if (reward && !dialog.open) { + dialog.showModal(); + celebrate(reward.size, iconRef.current); + } + if (!reward && dialog.open) dialog.close(); + }, [reward]); + + const Icon = reward?.icon; + return ( + + {reward && Icon ? ( + <> +
    + +
    + + + +

    {reward.kicker}

    +

    + {reward.title} +

    +

    + {reward.description} +

    + {reward.credits ? ( +

    + +{reward.credits} Build Credits +

    + ) : null} +
    + {reward.action ? ( + + {reward.action.label} + + ) : null} + +
    + + ) : null} +
    + ); +} diff --git a/frontend/src/lib/celebrate.ts b/frontend/src/lib/celebrate.ts new file mode 100644 index 000000000..78b2ff302 --- /dev/null +++ b/frontend/src/lib/celebrate.ts @@ -0,0 +1,21 @@ +"use client"; + +import { fireMiniConfetti } from "@buildment/learning-ui/components/learn/mini-confetti"; +import { playFeedback, type FeedbackKind } from "@/lib/sound-feedback"; + +// One feedback recipe for every reward moment, sized by how big the moment is, so a quest claim, +// an achievement and a certificate feel related. Sound follows the learner's sound setting; +// confetti already stays off when the device asks for reduced motion. + +export type CelebrationSize = "small" | "medium" | "large"; + +export const CELEBRATION_SOUND: Record = { + small: "success", + medium: "celebration", + large: "completion", +}; + +export function celebrate(size: CelebrationSize, anchor?: HTMLElement | null): void { + playFeedback(CELEBRATION_SOUND[size]); + if (anchor) fireMiniConfetti(anchor); +} diff --git a/frontend/src/lib/profile-view.ts b/frontend/src/lib/profile-view.ts new file mode 100644 index 000000000..b8bf80386 --- /dev/null +++ b/frontend/src/lib/profile-view.ts @@ -0,0 +1,77 @@ +import type { AchievementView } from "@/shared/api/public-profile"; +import type { CareerRequirement, CareerTier } from "@/shared/api/gamification"; +import { CAREER_TIER_LABELS } from "@/shared/gamification/career"; + +// Pure presentation helpers for the profile page, kept apart from the JSX so they can be tested. + +export type CareerNodeState = "done" | "current" | "next" | "locked"; + +export function careerNodeState(index: number, currentIndex: number): CareerNodeState { + if (index < currentIndex) return "done"; + if (index === currentIndex) return "current"; + return index === currentIndex + 1 ? "next" : "locked"; +} + +/** "5 courses · 72% average", or a starter line for the first tier. */ +export function careerRequirementLine(requirement: CareerRequirement): string { + if (requirement.courses === 0 && requirement.minScore === 0) return "Where every learner starts."; + const courses = `${requirement.courses} ${requirement.courses === 1 ? "course" : "courses"}`; + return requirement.minScore > 0 ? `${courses} · ${requirement.minScore}% average` : courses; +} + +/** + * What the learner still needs for the next tier. With the owner's own numbers it names the gap; + * without them (the public page, which never carries the quiz average) it states the rule. + */ +export function nextStepCopy( + next: CareerTier, + requirement: CareerRequirement, + mastery: { completedCourses: number; avgScore: number } | null, +): string { + const label = CAREER_TIER_LABELS[next]; + if (!mastery) { + return `${label} needs ${requirement.courses} completed ${requirement.courses === 1 ? "course" : "courses"} and a ${requirement.minScore}% average quiz score.`; + } + const remaining = Math.max(0, requirement.courses - mastery.completedCourses); + const parts: string[] = []; + if (remaining > 0) parts.push(`complete ${remaining} more ${remaining === 1 ? "course" : "courses"}`); + if (mastery.avgScore < requirement.minScore) { + parts.push(`raise your average quiz score from ${mastery.avgScore}% to ${requirement.minScore}%`); + } else if (remaining > 0) { + parts.push(`keep your average quiz score at ${requirement.minScore}% or higher`); + } + if (parts.length === 0) return `You meet the ${label} requirements. Your tier updates when you next finish a course.`; + const sentence = parts.join(" and "); + return `${sentence.charAt(0).toUpperCase()}${sentence.slice(1)}.`; +} + +/** + * The achievements to show large: ones with credits waiting to be claimed first, then those closest + * to their next tier. Maxed ones with nothing to claim are left out. + */ +export function featuredAchievements(achievements: AchievementView[], count = 2, claimable: ReadonlySet = new Set()): AchievementView[] { + return achievements + .filter((achievement) => achievement.nextTarget !== null || claimable.has(achievement.id)) + .map((achievement, order) => ({ achievement, order, claim: claimable.has(achievement.id) ? 1 : 0 })) + .sort( + (a, b) => + b.claim - a.claim || b.achievement.progress - a.achievement.progress || b.achievement.tier - a.achievement.tier || a.order - b.order, + ) + .slice(0, count) + .map(({ achievement }) => achievement); +} + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** "Oct 2026" from an ISO timestamp, in UTC so the server and browser agree. */ +export function monthYear(iso: string): string { + const date = new Date(iso); + if (Number.isNaN(date.getTime())) return ""; + return `${MONTHS[date.getUTCMonth()]} ${date.getUTCFullYear()}`; +} + +/** "Oct 26" from a "2026-10-26" day or week key. */ +export function shortDate(key: string): string { + const [, month, day] = key.split("-"); + return `${MONTHS[Number(month) - 1] ?? month} ${Number(day)}`; +} diff --git a/frontend/src/shared/api/engagement.ts b/frontend/src/shared/api/engagement.ts index 2daae2994..a8d4a2b87 100644 --- a/frontend/src/shared/api/engagement.ts +++ b/frontend/src/shared/api/engagement.ts @@ -1,4 +1,6 @@ // GENERATED from server/src/shared — do not edit here. Run `pnpm sync-shared` in server/. +import type { CareerTier } from "./gamification"; + // Wire contract for engagement events (POST /api/v1/events): the learning moments the app reacts // to, mascot reactions today. The client only names what happened and where; the server checks it // against the database and fills in the facts (quiz attempt and score, days away, first time), so @@ -32,6 +34,8 @@ export const ENGAGEMENT_SERVER_EVENT_TYPES = [ "course_first_chapter", "course_halfway", "course_one_left", + /** The learner reached a new career tier (shared/gamification/career.ts) for the first time. */ + "career_tier_up", ] as const; export type EngagementServerEventType = (typeof ENGAGEMENT_SERVER_EVENT_TYPES)[number]; @@ -80,6 +84,8 @@ export type QuizSubmittedFacts = { export type LevelUpFacts = { level: number }; +export type CareerTierUpFacts = { tier: CareerTier }; + export type WeeklyGoalMetFacts = { /** A streak freeze came with it (the learner had room for one and freezes are on). */ freezeEarned: boolean; @@ -122,6 +128,7 @@ export type RecordedEngagementEvent = RecordedBase & | { type: "session_start"; payload: SessionStartFacts } | { type: "quiz_submitted"; payload: QuizSubmittedFacts } | { type: "level_up"; payload: LevelUpFacts } + | { type: "career_tier_up"; payload: CareerTierUpFacts } | { type: "weekly_goal_met"; payload: WeeklyGoalMetFacts } | { type: "daily_goal_met"; payload: DailyGoalMetFacts } | { type: "course_first_chapter" | "course_halfway" | "course_one_left"; payload: CourseMilestoneFacts } diff --git a/frontend/src/shared/api/public-profile.ts b/frontend/src/shared/api/public-profile.ts index 67d1fee13..04326a244 100644 --- a/frontend/src/shared/api/public-profile.ts +++ b/frontend/src/shared/api/public-profile.ts @@ -1,5 +1,5 @@ // GENERATED from server/src/shared — do not edit here. Run `pnpm sync-shared` in server/. -import type { CareerTier, LeagueTier } from "./gamification"; +import type { CareerProgress, CareerTier, LeagueTier } from "./gamification"; // The public Career Identity page (Phase 5). A learner opts in with a unique handle and the server // exposes only safe, curated fields at /u/. XP/league/streak are hidden when the learner has @@ -81,6 +81,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/frontend/src/shared/engagement/mascot-messages.en.json b/frontend/src/shared/engagement/mascot-messages.en.json index 623909a54..870145642 100644 --- a/frontend/src/shared/engagement/mascot-messages.en.json +++ b/frontend/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/frontend/src/shared/engagement/rules.ts b/frontend/src/shared/engagement/rules.ts index 8c95124e9..f96513f3a 100644 --- a/frontend/src/shared/engagement/rules.ts +++ b/frontend/src/shared/engagement/rules.ts @@ -162,6 +162,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/frontend/tests/unit/lib/profile-view.test.ts b/frontend/tests/unit/lib/profile-view.test.ts new file mode 100644 index 000000000..d230c93e0 --- /dev/null +++ b/frontend/tests/unit/lib/profile-view.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import type { AchievementView } from "../../../src/shared/api/public-profile"; +import { careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy } from "../../../src/lib/profile-view"; + +function achievement(id: string, progress: number, tier: number, nextTarget: number | null): AchievementView { + return { + id, + title: id, + description: "", + category: "courses", + icon: "book", + value: 1, + tier, + nextTarget, + progress, + tiers: [{ label: "Bronze", target: 1 }], + earnedCredits: 0, + nextReward: null, + }; +} + +describe("careerNodeState", () => { + it("marks tiers before, at, right after and beyond the current one", () => { + expect([0, 1, 2, 3].map((index) => careerNodeState(index, 1))).toEqual(["done", "current", "next", "locked"]); + }); +}); + +describe("careerRequirementLine", () => { + it("describes the starting tier and a gated tier", () => { + expect(careerRequirementLine({ courses: 0, minScore: 0 })).toBe("Where every learner starts."); + expect(careerRequirementLine({ courses: 5, minScore: 72 })).toBe("5 courses · 72% average"); + }); +}); + +describe("nextStepCopy", () => { + const mid = { courses: 5, minScore: 72 }; + + it("states the rule without the learner's numbers", () => { + expect(nextStepCopy("MID", mid, null)).toBe("Mid needs 5 completed courses and a 72% average quiz score."); + }); + + it("names the remaining courses and the score gap", () => { + expect(nextStepCopy("MID", mid, { completedCourses: 2, avgScore: 65 })).toBe( + "Complete 3 more courses and raise your average quiz score from 65% to 72%.", + ); + }); + + it("asks to keep the score when only courses are missing", () => { + expect(nextStepCopy("MID", mid, { completedCourses: 4, avgScore: 80 })).toBe( + "Complete 1 more course and keep your average quiz score at 72% or higher.", + ); + }); + + it("says the requirements are met when nothing is missing", () => { + expect(nextStepCopy("MID", mid, { completedCourses: 5, avgScore: 80 })).toMatch(/^You meet the Mid requirements/); + }); +}); + +describe("featuredAchievements", () => { + it("picks the two closest to their next tier and skips maxed ones", () => { + const list = [achievement("a", 0.2, 0, 10), achievement("maxed", 1, 0, null), achievement("b", 0.75, 1, 5), achievement("c", 0.5, -1, 3)]; + expect(featuredAchievements(list).map((a) => a.id)).toEqual(["b", "c"]); + }); + + it("puts achievements with credits to claim first, even when maxed", () => { + const list = [achievement("a", 0.2, 0, 10), achievement("maxed", 1, 0, null), achievement("b", 0.75, 1, 5)]; + expect(featuredAchievements(list, 2, new Set(["maxed", "a"])).map((x) => x.id)).toEqual(["maxed", "a"]); + }); +}); + +describe("monthYear", () => { + it("formats in UTC and tolerates bad input", () => { + expect(monthYear("2026-10-01T00:30:00.000Z")).toBe("Oct 2026"); + expect(monthYear("not a date")).toBe(""); + }); +}); diff --git a/frontend/tests/unit/lib/sound-feedback.test.ts b/frontend/tests/unit/lib/sound-feedback.test.ts index 76aac689e..a1739d962 100644 --- a/frontend/tests/unit/lib/sound-feedback.test.ts +++ b/frontend/tests/unit/lib/sound-feedback.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; -import { FEEDBACK_AUDIO, playFeedback } from "../../../src/lib/sound-feedback"; +import { FEEDBACK_AUDIO, isSoundEnabled, playFeedback } from "../../../src/lib/sound-feedback"; describe("sound-feedback", () => { beforeEach(() => { @@ -52,4 +52,9 @@ describe("sound-feedback", () => { playFeedback("tick"); expect(Audio).toHaveBeenCalledTimes(2); }); + + it("keeps sound on when the device asks for reduced motion", () => { + vi.stubGlobal("window", { matchMedia: () => ({ matches: true }), AudioContext: undefined, webkitAudioContext: undefined }); + expect(isSoundEnabled()).toBe(true); + }); }); 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 2c0c7c188..23472c915 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 type { LeaderboardHubQuery } from "../validations/learner.js"; @@ -150,6 +151,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 01eb9379a..c068653a5 100644 --- a/server/src/routes/v1/learner.ts +++ b/server/src/routes/v1/learner.ts @@ -41,6 +41,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("/public-profile", learner.publicProfileGet); diff --git a/server/src/services/engagement/events.ts b/server/src/services/engagement/events.ts index 40f4f02c4..0110dd1a6 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,26 @@ const courseCompleted = (courseId: string): Draft => ({ dedupeKey: `course_completed:${courseId}`, }); +/** + * Records the first time the learner is seen at a career tier above Intern. Keyed by tier, so the + * profile page and a course completion can both check without celebrating twice. + */ +export async function recordCareerTierUp( + userId: string, + platform: EngagementPlatform, + tier: CareerTier +): Promise { + if (tier === "INTERN") return null; + const event = await record(userId, platform, { + type: "career_tier_up", + courseId: null, + chapterId: null, + payload: { tier }, + dedupeKey: `career_tier_up:${tier}`, + }); + 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 +297,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/profile/public-profile.ts b/server/src/services/profile/public-profile.ts index 0e4b83320..6f185246f 100644 --- a/server/src/services/profile/public-profile.ts +++ b/server/src/services/profile/public-profile.ts @@ -9,9 +9,11 @@ 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"; // 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 +106,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) : 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, }; } diff --git a/server/src/shared/api/engagement.ts b/server/src/shared/api/engagement.ts index fb4b77013..b7e759ebe 100644 --- a/server/src/shared/api/engagement.ts +++ b/server/src/shared/api/engagement.ts @@ -1,3 +1,5 @@ +import type { CareerTier } from "./gamification.js"; + // Wire contract for engagement events (POST /api/v1/events): the learning moments the app reacts // to, mascot reactions today. The client only names what happened and where; the server checks it // against the database and fills in the facts (quiz attempt and score, days away, first time), so @@ -31,6 +33,8 @@ export const ENGAGEMENT_SERVER_EVENT_TYPES = [ "course_first_chapter", "course_halfway", "course_one_left", + /** The learner reached a new career tier (shared/gamification/career.ts) for the first time. */ + "career_tier_up", ] as const; export type EngagementServerEventType = (typeof ENGAGEMENT_SERVER_EVENT_TYPES)[number]; @@ -79,6 +83,8 @@ export type QuizSubmittedFacts = { export type LevelUpFacts = { level: number }; +export type CareerTierUpFacts = { tier: CareerTier }; + export type WeeklyGoalMetFacts = { /** A streak freeze came with it (the learner had room for one and freezes are on). */ freezeEarned: boolean; @@ -121,6 +127,7 @@ export type RecordedEngagementEvent = RecordedBase & | { type: "session_start"; payload: SessionStartFacts } | { type: "quiz_submitted"; payload: QuizSubmittedFacts } | { type: "level_up"; payload: LevelUpFacts } + | { type: "career_tier_up"; payload: CareerTierUpFacts } | { type: "weekly_goal_met"; payload: WeeklyGoalMetFacts } | { type: "daily_goal_met"; payload: DailyGoalMetFacts } | { type: "course_first_chapter" | "course_halfway" | "course_one_left"; payload: CourseMilestoneFacts } diff --git a/server/src/shared/api/public-profile.ts b/server/src/shared/api/public-profile.ts index b6cbef02d..b8ce561b5 100644 --- a/server/src/shared/api/public-profile.ts +++ b/server/src/shared/api/public-profile.ts @@ -1,4 +1,4 @@ -import type { CareerTier, LeagueTier } from "./gamification.js"; +import type { CareerProgress, CareerTier, LeagueTier } from "./gamification.js"; // The public Career Identity page (Phase 5). A learner opts in with a unique handle and the server // exposes only safe, curated fields at /u/. XP/league/streak are hidden when the learner has @@ -80,6 +80,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/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..425e8c55a 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,45 @@ 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(); }); }); From 357991ddba330c9b0a2b292603975cb0c736da7d Mon Sep 17 00:00:00 2001 From: Faisal Misbah <132295428+FaisalMisbah23@users.noreply.github.com> Date: Sat, 28 Nov 2026 18:48:27 +0500 Subject: [PATCH 2/6] fix(profile): fix tier-up celebration dedupe, responsive career map, share links, and branding --- frontend/src/app/u/[slug]/page.tsx | 6 +- .../profile/achievement-share-button.tsx | 12 +- .../profile/public-profile-card.tsx | 239 ++++++++++++------ .../rewards/reward-celebration-dialog.tsx | 3 + frontend/src/lib/profile-view.ts | 13 + frontend/tests/unit/lib/profile-view.test.ts | 33 ++- server/src/services/engagement/events.ts | 11 +- server/src/services/profile/public-profile.ts | 4 +- server/tests/api/rewards-marketplace.test.ts | 5 + 9 files changed, 239 insertions(+), 87 deletions(-) diff --git a/frontend/src/app/u/[slug]/page.tsx b/frontend/src/app/u/[slug]/page.tsx index e06538fcf..c0619e42d 100644 --- a/frontend/src/app/u/[slug]/page.tsx +++ b/frontend/src/app/u/[slug]/page.tsx @@ -21,15 +21,15 @@ async function fetchPublic(slug: string): Promise { function tagline(profile: PublicProfileView): string { return ( [profile.headline, profile.learningInPublic ? "Learning in public" : null].filter(Boolean).join(" · ") || - "A verified learning profile on Buildment." + "A verified learning profile on Edorax." ); } export async function generateMetadata({ params }: { params: Promise }): Promise { const { slug } = await params; const profile = await fetchPublic(slug); - if (!profile) return { title: "Profile not found · Buildment" }; - const title = `${profile.name} · Buildment`; + if (!profile) return { title: "Profile not found · Edorax" }; + const title = `${profile.name} · Edorax`; const description = tagline(profile); return { title, diff --git a/frontend/src/components/profile/achievement-share-button.tsx b/frontend/src/components/profile/achievement-share-button.tsx index 42eeb25cc..fb9425663 100644 --- a/frontend/src/components/profile/achievement-share-button.tsx +++ b/frontend/src/components/profile/achievement-share-button.tsx @@ -6,15 +6,21 @@ import { toast } from "@/components/ui/app-toast"; import { copyToClipboard } from "@/lib/clipboard"; // Shares one earned achievement: native share sheet where available, else copies a line + profile URL. -export function AchievementShareButton({ title }: { title: string }) { +export function AchievementShareButton({ title, shareUrl }: { title: string; shareUrl?: string }) { const [done, setDone] = useState(false); async function share() { - const url = typeof window !== "undefined" ? window.location.href : ""; + const url = shareUrl + ? shareUrl.startsWith("http") + ? shareUrl + : `${typeof window !== "undefined" ? window.location.origin : ""}${shareUrl}` + : typeof window !== "undefined" + ? window.location.href + : ""; const line = `I unlocked "${title}" on Edorax`; if (typeof navigator !== "undefined" && typeof navigator.share === "function") { try { - await navigator.share({ title: `${title} · Buildment`, text: line, url }); + await navigator.share({ title: `${title} · Edorax`, text: line, url }); return; } catch { // cancelled/unsupported → fall through to copy diff --git a/frontend/src/components/profile/public-profile-card.tsx b/frontend/src/components/profile/public-profile-card.tsx index 5acf86e79..14a83a859 100644 --- a/frontend/src/components/profile/public-profile-card.tsx +++ b/frontend/src/components/profile/public-profile-card.tsx @@ -31,7 +31,7 @@ import { LEAGUE_TIER_LABELS } from "@/shared/gamification/leagues"; import { CosmeticDot } from "@/components/learn/rewards/cosmetic-dot"; import { Dot, type DotMood } from "@/components/brand/dot"; import { cn } from "@/lib/utils"; -import { careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, shortDate, type CareerNodeState } from "@/lib/profile-view"; +import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, shortDate, type CareerNodeState } from "@/lib/profile-view"; import { ShareProfileButton } from "./share-profile-button"; import { RevealMore } from "./reveal-more"; import { AchievementClaimButton } from "./achievement-claim-button"; @@ -170,7 +170,7 @@ function DotAside({ mood, size = 44 }: { mood: DotMood; size?: number }) { const NODE_BUBBLE: Record = { done: "bg-primary text-primary-foreground", - current: "size-20 bg-[var(--brand-yellow)] text-[#0a0f2c] ring-4 ring-[var(--brand-yellow)]/25", + current: "size-14 md:size-20 bg-[var(--brand-yellow)] text-[#0a0f2c] ring-4 ring-[var(--brand-yellow)]/25", next: "bg-secondary text-primary ring-2 ring-primary/40", locked: "bg-muted text-muted-foreground", }; @@ -197,48 +197,51 @@ function CareerMap({ profile, isOwner }: { profile: CardProfile; isOwner: boolea
    -
    -
      - {/* The track runs between the first and last node centres; the filled part ends at the current tier. */} - - - - {CAREER_TIERS.map((tier, index) => { - const state = careerNodeState(index, currentIndex); - const Icon = TIER_ICONS[tier]; - return ( -
    1. -
      - - - {state === "done" ? ( - - - - ) : null} - -
      +
        + {/* Desktop horizontal track between node centres; mobile vertical track along node centres. */} + + + + + + + {CAREER_TIERS.map((tier, index) => { + const state = careerNodeState(index, currentIndex); + const Icon = TIER_ICONS[tier]; + return ( +
      1. +
        + + + {state === "done" ? ( + + + + ) : null} + +
        +
        {state === "current" ? ( - + {isOwner ? "You are here" : "Current tier"} ) : null} -

        +

        {CAREER_TIER_LABELS[tier]}

        -

        +

        {state === "done" ? "Reached" : careerRequirementLine(CAREER_REQUIREMENTS[tier])}

        -
      2. - ); - })} -
      -
    +
    + + ); + })} +
    @@ -314,11 +317,13 @@ function RecordTile({ icon, label, value, sub }: { icon: LucideIcon; label: stri ); } -function Records({ records }: { records: NonNullable }) { +function Records({ records, isOwner }: { records: NonNullable; isOwner: boolean }) { const streak = records.longestStreakDays; - const big = ( -
    + const bigItems: React.ReactNode[] = []; + if (isOwner || streak > 0) { + bigItems.push( 0 ? "The longest learning run so far." : "A streak starts with one day of learning."} empty={streak === 0} - /> + />, + ); + } + if (isOwner || records.bestWeeklyXp) { + bigItems.push( + />, + ); + } + if (isOwner || records.bestLeagueFinish) { + bigItems.push( -
    - ); + />, + ); + } + + const detailItems: React.ReactNode[] = []; + if (isOwner || records.mostXpInADay) { + detailItems.push( + , + ); + } + if (isOwner || records.highestLeagueTier) { + detailItems.push( + , + ); + } + if (isOwner || records.bestWeekChapters) { + detailItems.push( + , + ); + } + if (isOwner || records.mostStudyMinutesInADay) { + detailItems.push( + , + ); + } + if (isOwner || records.longestSessionMinutes > 0) { + detailItems.push( + 0 ? `${records.longestSessionMinutes} min` : "Not yet"} + />, + ); + } + if (isOwner || records.perfectQuizzes > 0) { + detailItems.push(); + } + if (isOwner || records.activeDays > 0) { + detailItems.push(); + } + + if (bigItems.length === 0 && detailItems.length === 0) return null; + + const heading = ; + const bigGrid = bigItems.length > 0 ?
    {bigItems}
    : null; + const detailGrid = detailItems.length > 0 ?
    {detailItems}
    : null; + return (
    - } - preview={big} - > -
    - - - - - 0 ? `${records.longestSessionMinutes} min` : "Not yet"} /> - - -
    -
    + {detailGrid && bigGrid ? ( + + {detailGrid} + + ) : ( + <> + {heading} + {bigGrid ?? detailGrid} + + )}
    ); } @@ -394,7 +471,7 @@ function FeaturedAchievement({ a, claim }: { a: AchievementView; claim?: Achieve

    {a.description}

    - {a.nextTarget === null ? "All tiers reached" : `${a.value} / ${a.nextTarget}`} + {achievementProgressCopy(a)} {percent}%
    @@ -404,11 +481,11 @@ function FeaturedAchievement({ a, claim }: { a: AchievementView; claim?: Achieve ); } -function AchievementCard({ a, claim }: { a: AchievementView; claim?: AchievementClaim }) { +function AchievementCard({ a, claim, shareUrl }: { a: AchievementView; claim?: AchievementClaim; shareUrl?: string }) { const maxed = a.tier >= 0 && a.nextTarget === null; const locked = a.tier < 0; const tierLabel = a.tier >= 0 ? a.tiers[a.tier]?.label : "Locked"; - const earnedCredits = Array.from({ length: a.tier + 1 }, (_, i) => rewardForTier(i)).reduce((sum, n) => sum + n, 0); + const earnedCredits = a.earnedCredits; const nextReward = nextRewardFor(a); return ( : null} + badge={!locked && shareUrl ? : null} >

    {a.title}

    {tierLabel}

    - {maxed ? `Maxed · earned ${earnedCredits}` : `${a.value} / ${a.nextTarget} · +${nextReward ?? 0} credits`} + {maxed ? `Maxed · earned ${earnedCredits}` : `${achievementProgressCopy(a)} · +${nextReward ?? 0} credits`}

    {claim ? : null}
    @@ -431,7 +508,7 @@ function AchievementCard({ a, claim }: { a: AchievementView; claim?: Achievement ); } -function Achievements({ achievements, claims }: { achievements: AchievementView[]; claims: Claims }) { +function Achievements({ achievements, claims, shareUrl }: { achievements: AchievementView[]; claims: Claims; shareUrl?: string }) { const featured = featuredAchievements(achievements, 2, new Set(claims.keys())); const heading = ; const preview = @@ -447,7 +524,7 @@ function Achievements({ achievements, claims }: { achievements: AchievementView[
    {achievements.map((a) => ( - + ))}
    @@ -463,6 +540,9 @@ export function PublicProfileCard({ variant?: "public" | "owner"; }) { const isOwner = variant === "owner"; + const Wrapper = isOwner ? "div" : "main"; + const canShare = !isOwner || Boolean(profile.profilePublic); + const publicShareUrl = `/u/${profile.slug}`; // The owner page already has a "Profile" h1; on the public page the learner's name is the page title. const NameHeading = isOwner ? "h2" : "h1"; const headline = @@ -479,7 +559,7 @@ export function PublicProfileCard({ if (stats.length === 0) stats.push({ value: String(profile.coursesCompleted), label: "Courses completed" }); return ( -
    +
    {/* Hero */}
    -
    - +
    +
    {profile.name} @@ -520,7 +600,16 @@ export function PublicProfileCard({ ))}
    - + {canShare ? ( + + ) : ( + + Make profile public to share + + )}
    @@ -548,14 +637,16 @@ export function PublicProfileCard({ - {profile.records ? : null} + {profile.records ? : null} - {profile.achievements && profile.achievements.length > 0 ? : null} + {profile.achievements && profile.achievements.length > 0 ? ( + + ) : null}

    Verified learning on Edorax. Career tier reflects completed courses and quiz mastery, not time spent.

    -
    + ); } diff --git a/frontend/src/components/rewards/reward-celebration-dialog.tsx b/frontend/src/components/rewards/reward-celebration-dialog.tsx index d64addf5d..14d18d22a 100644 --- a/frontend/src/components/rewards/reward-celebration-dialog.tsx +++ b/frontend/src/components/rewards/reward-celebration-dialog.tsx @@ -42,6 +42,9 @@ export function RewardCelebrationDialog({ reward, onClose }: { reward: RewardCel ref={dialogRef} onCancel={onClose} onClose={onClose} + onClick={(event) => { + if (event.target === event.currentTarget) onClose(); + }} aria-labelledby="reward-celebration-title" aria-describedby="reward-celebration-description" className="fixed inset-0 m-auto max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-sm overflow-y-auto rounded-2xl border-2 border-b-[5px] bg-card p-6 text-center text-card-foreground backdrop:bg-foreground/30" diff --git a/frontend/src/lib/profile-view.ts b/frontend/src/lib/profile-view.ts index b8bf80386..ac5627472 100644 --- a/frontend/src/lib/profile-view.ts +++ b/frontend/src/lib/profile-view.ts @@ -1,6 +1,7 @@ import type { AchievementView } from "@/shared/api/public-profile"; import type { CareerRequirement, CareerTier } from "@/shared/api/gamification"; import { CAREER_TIER_LABELS } from "@/shared/gamification/career"; +import { LEAGUE_TIER_LABELS, LEAGUE_TIER_ORDER } from "@/shared/gamification/leagues"; // Pure presentation helpers for the profile page, kept apart from the JSX so they can be tested. @@ -75,3 +76,15 @@ export function shortDate(key: string): string { const [, month, day] = key.split("-"); return `${MONTHS[Number(month) - 1] ?? month} ${Number(day)}`; } + +/** Human-readable progress copy for an achievement card, turning raw league indices into tier names. */ +export function achievementProgressCopy(a: AchievementView): string { + if (a.nextTarget === null) return "All tiers reached"; + if (a.id === "league") { + const currentTier = LEAGUE_TIER_ORDER[Math.max(0, Math.min(LEAGUE_TIER_ORDER.length - 1, a.value))] ?? "BRONZE"; + const currentLabel = LEAGUE_TIER_LABELS[currentTier]; + const nextLabel = a.tiers.find((t) => t.target === a.nextTarget)?.label ?? LEAGUE_TIER_LABELS[LEAGUE_TIER_ORDER[a.nextTarget] ?? "DIAMOND"]; + return `${currentLabel} → ${nextLabel}`; + } + return `${a.value} / ${a.nextTarget}`; +} diff --git a/frontend/tests/unit/lib/profile-view.test.ts b/frontend/tests/unit/lib/profile-view.test.ts index d230c93e0..70839dba2 100644 --- a/frontend/tests/unit/lib/profile-view.test.ts +++ b/frontend/tests/unit/lib/profile-view.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import type { AchievementView } from "../../../src/shared/api/public-profile"; -import { careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy } from "../../../src/lib/profile-view"; +import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy } from "../../../src/lib/profile-view"; function achievement(id: string, progress: number, tier: number, nextTarget: number | null): AchievementView { return { @@ -74,3 +74,34 @@ describe("monthYear", () => { expect(monthYear("not a date")).toBe(""); }); }); + +describe("achievementProgressCopy", () => { + const leagueTiers = [ + { label: "Silver", target: 1 }, + { label: "Gold", target: 2 }, + { label: "Platinum", target: 3 }, + { label: "Diamond", target: 4 }, + ]; + + it("formats numeric progress and maxed achievements", () => { + expect(achievementProgressCopy({ ...achievement("chapters", 0.3, 0, 10), value: 3 })).toBe("3 / 10"); + expect(achievementProgressCopy(achievement("chapters", 1, 7, null))).toBe("All tiers reached"); + }); + + it("formats league progress using tier names instead of raw indices", () => { + expect( + achievementProgressCopy({ + ...achievement("league", 0, -1, 1), + value: 0, + tiers: leagueTiers, + }), + ).toBe("Bronze → Silver"); + expect( + achievementProgressCopy({ + ...achievement("league", 0, 0, 2), + value: 1, + tiers: leagueTiers, + }), + ).toBe("Silver → Gold"); + }); +}); diff --git a/server/src/services/engagement/events.ts b/server/src/services/engagement/events.ts index 0110dd1a6..f56b8394b 100644 --- a/server/src/services/engagement/events.ts +++ b/server/src/services/engagement/events.ts @@ -197,21 +197,24 @@ const courseCompleted = (courseId: string): Draft => ({ }); /** - * Records the first time the learner is seen at a career tier above Intern. Keyed by tier, so the - * profile page and a course completion can both check without celebrating twice. + * 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 + 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: `career_tier_up:${tier}`, + dedupeKey, }); return event.isNew ? event : null; } diff --git a/server/src/services/profile/public-profile.ts b/server/src/services/profile/public-profile.ts index 6f185246f..177d6ed79 100644 --- a/server/src/services/profile/public-profile.ts +++ b/server/src/services/profile/public-profile.ts @@ -112,7 +112,7 @@ export async function loadOwnProfile(userId: string): Promise const creditsOn = gamificationFeatures().credits; const [achievementClaims, promoted] = await Promise.all([ creditsOn && view.achievements ? pendingAchievementClaims(userId, view.achievements) : Promise.resolve([]), - career && !view.hidden ? recordCareerTierUp(userId, "web", career.tier) : Promise.resolve(null), + career && !view.hidden ? recordCareerTierUp(userId, "web", career.tier, "profile") : Promise.resolve(null), ]); return { ...view, @@ -170,7 +170,7 @@ async function buildProfileView(user: ProfileUser, slug: string): Promise { 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(); }); }); From 2269f72745f50c975b564ee5d7febafce977150b Mon Sep 17 00:00:00 2001 From: Faisal Misbah <132295428+FaisalMisbah23@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:58:36 +0500 Subject: [PATCH 3/6] feat(celebrations): add top-layer confetti, level-up, weekly reset, personal best, and exercise celebrations --- .../capstone-check/CapstoneCheckClient.tsx | 13 +- .../learn/dashboard/mentee-dashboard.tsx | 6 + .../unclaimed-achievements-banner.tsx | 67 +++++++ .../learn/dashboard/weekly-quests.tsx | 24 ++- .../learn/leaderboard/leaderboard-page.tsx | 2 + .../leaderboard/use-leaderboard-confetti.ts | 14 +- .../leaderboard/weekly-league-celebration.tsx | 167 ++++++++++++++++++ .../learn/quiz-chapter-session-client.tsx | 4 + .../src/components/mascot/mascot-player.tsx | 104 ++++++++++- frontend/src/lib/celebrate.ts | 5 + frontend/src/lib/engagement/client.ts | 16 +- frontend/src/shared/api/learner.ts | 1 + frontend/src/shared/engagement/engine.ts | 13 ++ .../weekly-league-celebration.test.ts | 124 +++++++++++++ frontend/tests/unit/lib/celebrate.test.ts | 49 +++++ .../blocks/ai-interview/AiInterviewClient.tsx | 47 ++--- .../blocks/exercises/CodeExerciseClient.tsx | 9 +- .../src/blocks/exercises/PredictClient.tsx | 2 + .../src/components/learn/mini-confetti.ts | 18 +- .../src/services/learner/dashboard-model.ts | 2 + .../services/learner/load-mentee-dashboard.ts | 20 +++ server/src/shared/api/learner.ts | 1 + server/src/shared/engagement/engine.ts | 13 ++ .../unit/shared/engagement/engine.test.ts | 24 +++ 24 files changed, 705 insertions(+), 40 deletions(-) create mode 100644 frontend/src/components/learn/dashboard/unclaimed-achievements-banner.tsx create mode 100644 frontend/src/components/learn/leaderboard/weekly-league-celebration.tsx create mode 100644 frontend/tests/unit/leaderboard/weekly-league-celebration.test.ts create mode 100644 frontend/tests/unit/lib/celebrate.test.ts diff --git a/frontend/src/blocks/capstone-check/CapstoneCheckClient.tsx b/frontend/src/blocks/capstone-check/CapstoneCheckClient.tsx index 4289433a1..4cffd3bde 100644 --- a/frontend/src/blocks/capstone-check/CapstoneCheckClient.tsx +++ b/frontend/src/blocks/capstone-check/CapstoneCheckClient.tsx @@ -7,6 +7,7 @@ import { ApiError, apiFetch } from "@/lib/api-client"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; +import { celebrate } from "@/lib/celebrate"; import type { SanitizedCapstoneCheckConfig } from "@/shared/blocks/capstone-check/schema"; import type { AutomatedCheckResult, CapstoneCheckState, CapstoneCheckView } from "@/shared/blocks/capstone-check/report"; import { CertificateCard } from "./CertificateCard"; @@ -162,6 +163,10 @@ export function CapstoneCheckClient({ const [busy, setBusy] = useState<"check" | "send" | null>(null); const [showHistory, setShowHistory] = useState(false); const timer = useRef | null>(null); + const cardRef = useRef(null); + const celebratedCheckIdRef = useRef( + initialState?.checks[0]?.report?.completed ? initialState.checks[0].id : null + ); const running = latest?.status === "QUEUED" || latest?.status === "RUNNING"; @@ -169,6 +174,11 @@ export function CapstoneCheckClient({ try { const result = await apiFetch<{ state: CapstoneCheckState }>(`/api/v1/blocks/${encodeURIComponent(id)}/capstone`); setState(result.state); + const newest = result.state.checks[0]; + if (newest?.report?.completed && newest.id !== celebratedCheckIdRef.current) { + celebratedCheckIdRef.current = newest.id; + celebrate("medium", cardRef.current); + } } catch { // A failed poll is retried on the next tick. } @@ -214,6 +224,7 @@ export function CapstoneCheckClient({ setBusy("send"); try { await apiFetch(`/api/v1/blocks/${encodeURIComponent(id)}/capstone/send`, { method: "POST", json: { checkId: latest.id } }); + celebrate("small", cardRef.current); await refresh(); } catch (caught) { setError(caught instanceof ApiError ? caught.message : "Could not send it. Try again."); @@ -226,7 +237,7 @@ export function CapstoneCheckClient({ const outOfChecks = state.remainingToday <= 0; return ( -
    +

    Capstone check

    {config.title}

    diff --git a/frontend/src/components/learn/dashboard/mentee-dashboard.tsx b/frontend/src/components/learn/dashboard/mentee-dashboard.tsx index fe33c16d9..d6119c73b 100644 --- a/frontend/src/components/learn/dashboard/mentee-dashboard.tsx +++ b/frontend/src/components/learn/dashboard/mentee-dashboard.tsx @@ -19,7 +19,9 @@ import { formatStudyAmount } from "@/lib/format-study-duration"; import { CourseCertificateLink } from "@/components/learn/course-certificate-link"; import { WeeklyGoalEditor } from "@/components/learn/dashboard/weekly-goal-editor"; import { WeeklyQuests } from "@/components/learn/dashboard/weekly-quests"; +import { UnclaimedAchievementsBanner } from "@/components/learn/dashboard/unclaimed-achievements-banner"; import { LeagueGoalCard } from "@/components/learn/dashboard/league-goal-card"; +import { WeeklyLeagueCelebration } from "@/components/learn/leaderboard/weekly-league-celebration"; import { CourseStageLine, LearningMomentum } from "@/components/learn/dashboard/gamification"; import { showsGameElements } from "@/lib/gamification"; import { MascotStill } from "@/components/mascot/mascot-tip"; @@ -496,7 +498,11 @@ export function MenteeDashboard({ model }: { model: MenteeDashboardViewModel }) ) : (
    + {showsGameElements(model.gamification) ? ( + + ) : null} + {model.activity.runningSession ? : null}
    {model.primaryCourse ? : null} diff --git a/frontend/src/components/learn/dashboard/unclaimed-achievements-banner.tsx b/frontend/src/components/learn/dashboard/unclaimed-achievements-banner.tsx new file mode 100644 index 000000000..41a7a91f4 --- /dev/null +++ b/frontend/src/components/learn/dashboard/unclaimed-achievements-banner.tsx @@ -0,0 +1,67 @@ +"use client"; + +import { useEffect, useRef } from "react"; +import Link from "next/link"; +import { ArrowRight, Trophy } from "lucide-react"; +import { buttonVariants } from "@/components/ui/button"; +import { celebrate } from "@/lib/celebrate"; + +const STORAGE_PREFIX = "buildment:achievements-ready:"; + +export type UnclaimedAchievementsInfo = { + count: number; + totalCredits: number; + ids: string[]; +}; + +/** + * Surfaces newly unlocked achievements right on the dashboard (and plays a gentle celebration + * once per newly unlocked set) so learners don't miss rewards waiting on `/profile`. + */ +export function UnclaimedAchievementsBanner({ unclaimed }: { unclaimed: UnclaimedAchievementsInfo | null | undefined }) { + const bannerRef = useRef(null); + + useEffect(() => { + if (!unclaimed || unclaimed.count <= 0) return; + const key = STORAGE_PREFIX + unclaimed.ids.join(","); + try { + if (window.localStorage.getItem(key) === "1") return; + window.localStorage.setItem(key, "1"); + } catch { + /* Ignore storage failures. */ + } + const timer = window.setTimeout(() => { + if (bannerRef.current) celebrate("small", bannerRef.current); + }, 350); + return () => window.clearTimeout(timer); + }, [unclaimed]); + + if (!unclaimed || unclaimed.count <= 0) return null; + + const noun = unclaimed.count === 1 ? "achievement" : "achievements"; + return ( +
    +
    + + + +
    +

    + You unlocked {unclaimed.count} {noun} +

    +

    + +{unclaimed.totalCredits.toLocaleString()} Build Credits ready to claim on your profile. +

    +
    +
    + + Claim on profile + + +
    + ); +} diff --git a/frontend/src/components/learn/dashboard/weekly-quests.tsx b/frontend/src/components/learn/dashboard/weekly-quests.tsx index 81ce45789..e0e33f284 100644 --- a/frontend/src/components/learn/dashboard/weekly-quests.tsx +++ b/frontend/src/components/learn/dashboard/weekly-quests.tsx @@ -2,11 +2,12 @@ import { useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; -import { CheckCircle2, Gift, X } from "lucide-react"; +import { CheckCircle2, Gift, Trophy, X } from "lucide-react"; import { Button } from "@/components/ui/button"; import { InfoTip } from "@/components/ui/info-tip"; import { toast } from "@/components/ui/app-toast"; import { celebrate } from "@/lib/celebrate"; +import { RewardCelebrationDialog, type RewardCelebration } from "@/components/rewards/reward-celebration-dialog"; import type { WeeklyQuestsView } from "@/shared/api/quests"; // Weekly quests: a compact entry at the top of the dashboard; the full mission @@ -17,6 +18,7 @@ export function WeeklyQuests() { const [state, setState] = useState(null); const [busy, setBusy] = useState(null); const [open, setOpen] = useState(false); + const [allCleared, setAllCleared] = useState(null); useEffect(() => { let cancelled = false; @@ -51,9 +53,22 @@ export function WeeklyQuests() { toast(json?.message ?? "Could not claim this quest", "error"); return; } - celebrate("small", anchor); - setState(json.data); - toast("Quest reward claimed", "success"); + const next = json.data as WeeklyQuestsView; + setState(next); + if (next.total > 0 && next.quests.every((quest) => quest.claimed)) { + setOpen(false); + setAllCleared({ + size: "large", + icon: Trophy, + kicker: "Weekly quests cleared", + title: `All ${next.total} quests complete!`, + description: "You cleared every quest for this week. Fresh quests arrive Monday.", + action: { label: "Spend in rewards", href: "/rewards" }, + }); + } else { + celebrate("small", anchor); + toast("Quest reward claimed", "success"); + } router.refresh(); } catch { toast("Could not claim this quest", "error"); @@ -179,6 +194,7 @@ export function WeeklyQuests() { })} + setAllCleared(null)} /> ); } diff --git a/frontend/src/components/learn/leaderboard/leaderboard-page.tsx b/frontend/src/components/learn/leaderboard/leaderboard-page.tsx index 7b3873ddb..63d828fff 100644 --- a/frontend/src/components/learn/leaderboard/leaderboard-page.tsx +++ b/frontend/src/components/learn/leaderboard/leaderboard-page.tsx @@ -22,6 +22,7 @@ import { LeaderboardTabs, type HubSelection } from "./leaderboard-tabs"; import { LeaderboardLeagueCard } from "./leaderboard-league-card"; import { LeaderboardList } from "./leaderboard-list"; import { useLeaderboardConfetti } from "./use-leaderboard-confetti"; +import { WeeklyLeagueCelebration } from "./weekly-league-celebration"; import { formatNumber, formatScore, resetLabel } from "./leaderboard-format"; type CourseOption = { courseId: string; title: string }; @@ -224,6 +225,7 @@ export function LeaderboardPage({ return (
    + {/* Consistent Header with Edorax standards */}
    diff --git a/frontend/src/components/learn/leaderboard/use-leaderboard-confetti.ts b/frontend/src/components/learn/leaderboard/use-leaderboard-confetti.ts index 9ba59a436..f0978e04c 100644 --- a/frontend/src/components/learn/leaderboard/use-leaderboard-confetti.ts +++ b/frontend/src/components/learn/leaderboard/use-leaderboard-confetti.ts @@ -6,9 +6,10 @@ import { playFeedback } from "@/lib/sound-feedback"; import type { LeaderboardHubView } from "@/shared/api/gamification"; /** - * Celebrates the learner exactly once per board: when they reach a podium (top three) on a ready - * board, or when last week's reset promoted them. The returned ref anchors the confetti burst — - * attach it to the podium section so the particles rain over the winners. + * Celebrates the learner exactly once per board when they reach a live podium (top three) on a ready + * board and no modal dialog is open. Monday promotions are celebrated by WeeklyLeagueCelebration. + * The returned ref anchors the confetti burst — attach it to the podium section so the particles + * rain over the winners. */ export function useLeaderboardConfetti(view: LeaderboardHubView | null) { const anchorRef = useRef(null); @@ -18,13 +19,12 @@ export function useLeaderboardConfetti(view: LeaderboardHubView | null) { if (!view || view.status !== "ready") return; const key = `${view.category}|${view.scope}|${view.courseId ?? "global"}`; const onPodium = view.you.rank >= 1 && view.you.rank <= 3 && view.you.score > 0; - const outcome = view.league?.lastWeek?.outcome; - const promoted = outcome === "PROMOTED" || outcome === "PROMOTED_TARGET" || outcome === "PROMOTED_BOTH"; - if ((!onPodium && !promoted) || celebratedKeyRef.current === key) return; + if (!onPodium || celebratedKeyRef.current === key) return; celebratedKeyRef.current = key; const timer = window.setTimeout(() => { + if (document.querySelector("dialog[open], [role='dialog'][aria-modal='true']") !== null) return; if (anchorRef.current) fireMiniConfetti(anchorRef.current); - if (onPodium) playFeedback("celebration"); + playFeedback("celebration"); }, 700); return () => window.clearTimeout(timer); }, [view]); diff --git a/frontend/src/components/learn/leaderboard/weekly-league-celebration.tsx b/frontend/src/components/learn/leaderboard/weekly-league-celebration.tsx new file mode 100644 index 000000000..46a4ccf57 --- /dev/null +++ b/frontend/src/components/learn/leaderboard/weekly-league-celebration.tsx @@ -0,0 +1,167 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { ShieldCheck, Trophy } from "lucide-react"; +import { toast } from "@/components/ui/app-toast"; +import { celebrate } from "@/lib/celebrate"; +import { RewardCelebrationDialog, type RewardCelebration } from "@/components/rewards/reward-celebration-dialog"; +import { LEAGUE_TIER_LABELS, nextLeagueTier } from "@/shared/gamification/leagues"; +import type { LeaderboardHubView } from "@/shared/api/gamification"; +import { formatScore } from "./leaderboard-format"; + +const STORAGE_PREFIX = "buildment:weekly-celebration:"; +const MODAL_SELECTOR = "dialog[open], [role='dialog'][aria-modal='true']"; + +function hasSeen(key: string): boolean { + try { + return window.localStorage.getItem(STORAGE_PREFIX + key) === "1"; + } catch { + return false; + } +} + +function markSeen(key: string): void { + try { + window.localStorage.setItem(STORAGE_PREFIX + key, "1"); + } catch { + /* Private mode or full storage: best effort only. */ + } +} + +export function weeklyLeagueCelebrationFor( + view: LeaderboardHubView | null, + options: { onLeaderboard?: boolean } = {} +): { key: string; reward: RewardCelebration } | null { + if (!view || view.status !== "ready" || !view.weekStart) return null; + + const action = options.onLeaderboard ? undefined : { label: "View league", href: "/leaderboard" }; + const lastWeek = view.league?.lastWeek ?? null; + + if ( + lastWeek && + (lastWeek.outcome === "PROMOTED" || lastWeek.outcome === "PROMOTED_TARGET" || lastWeek.outcome === "PROMOTED_BOTH") + ) { + const to = nextLeagueTier(lastWeek.fromTier) ?? view.league?.tier ?? lastWeek.fromTier; + const toLabel = LEAGUE_TIER_LABELS[to]; + const path = + lastWeek.outcome === "PROMOTED_TARGET" + ? "by reaching your weekly XP goal" + : lastWeek.outcome === "PROMOTED_BOTH" + ? "by finishing in the promotion zone and hitting your weekly goal" + : "by finishing in the promotion zone"; + return { + key: `league-promo:${view.weekStart}:${lastWeek.outcome}`, + reward: { + size: "large", + icon: Trophy, + kicker: "Weekly league", + title: `Promoted to ${toLabel} League`, + description: `You moved up at the Monday reset ${path}.`, + ...(action ? { action } : {}), + }, + }; + } + + const podiumWinner = view.lastWeek?.winners.find((winner) => winner.isYou); + if (podiumWinner && view.lastWeek) { + return { + key: `last-week-podium:${view.lastWeek.weekStart}:${podiumWinner.rank}`, + reward: { + size: "large", + icon: Trophy, + kicker: "Last week's podium", + title: `You finished #${podiumWinner.rank} last week`, + description: `You closed the week with ${formatScore(podiumWinner.score, view.metricLabel)}.`, + ...(action ? { action } : {}), + }, + }; + } + + if (lastWeek && view.league && (lastWeek.outcome === "SHIELD_HELD" || lastWeek.outcome === "RECOVERY_HELD")) { + const tierLabel = LEAGUE_TIER_LABELS[view.league.tier]; + return { + key: `league-held:${view.weekStart}:${lastWeek.outcome}`, + reward: { + size: "medium", + icon: ShieldCheck, + kicker: "League protected", + title: `${tierLabel} League held`, + description: + lastWeek.outcome === "SHIELD_HELD" + ? "Your League Shield protected your place at the Monday reset." + : "Your recovery quest protected your place at the Monday reset.", + ...(action ? { action } : {}), + }, + }; + } + + return null; +} + +export function personalBestCelebrationFor( + view: LeaderboardHubView | null +): { key: string; message: string } | null { + if (!view || view.status !== "ready") return null; + const best = view.you.bestScore; + if (best === null || best <= 0 || view.you.score <= best) return null; + return { + key: `personal-best:${view.category}:${view.scope}:${view.courseId ?? "global"}:${view.weekStart ?? "all"}`, + message: `New personal best! ${formatScore(view.you.score, view.metricLabel)}.`, + }; +} + +/** + * Celebrates Monday weekly league results (promotion, top-3 podium, shield/recovery save) and + * beaten personal records once per week, waiting until any active modal closes first. + */ +export function WeeklyLeagueCelebration({ + view, + onLeaderboard = false, +}: { + view: LeaderboardHubView | null; + onLeaderboard?: boolean; +}) { + const [reward, setReward] = useState(null); + const anchorRef = useRef(null); + + const weekly = weeklyLeagueCelebrationFor(view, { onLeaderboard }); + const personalBest = personalBestCelebrationFor(view); + + useEffect(() => { + if (!weekly && !personalBest) return; + let active = true; + + const tryPresent = () => { + if (!active || document.querySelector(MODAL_SELECTOR) !== null) return; + if (weekly && !hasSeen(weekly.key)) { + markSeen(weekly.key); + setReward(weekly.reward); + return; + } + if (personalBest && !hasSeen(personalBest.key)) { + markSeen(personalBest.key); + celebrate("medium", anchorRef.current); + toast(personalBest.message, "success"); + } + }; + + const timer = window.setTimeout(tryPresent, 450); + const observer = new MutationObserver(() => { + window.setTimeout(tryPresent, 250); + }); + observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["open"] }); + + return () => { + active = false; + window.clearTimeout(timer); + observer.disconnect(); + }; + }, [weekly, personalBest]); + + return ( + <> + + setReward(null)} /> + + ); +} diff --git a/frontend/src/components/learn/quiz-chapter-session-client.tsx b/frontend/src/components/learn/quiz-chapter-session-client.tsx index cddb3e2ed..0f70f4a10 100644 --- a/frontend/src/components/learn/quiz-chapter-session-client.tsx +++ b/frontend/src/components/learn/quiz-chapter-session-client.tsx @@ -6,6 +6,8 @@ import { CheckCircle2, ChevronLeft, ChevronRight, PlayCircle, RotateCcw, X } fro import { Dot } from "@/components/brand/dot"; import { Button } from "@/components/ui/button"; import { playFeedback } from "@/lib/sound-feedback"; +import { firePartyPopper } from "@/lib/party-popper"; +import { fireMiniConfetti } from "@buildment/learning-ui/components/learn/mini-confetti"; import { apiFetch } from "@/lib/api-client"; import { markChapterComplete } from "@/server/actions/progress"; import { cn } from "@/lib/utils"; @@ -268,6 +270,8 @@ export function QuizChapterSessionClient({ if (body.assessment?.passed) { playFeedback("celebration"); + if (isPerfectScore(summary)) firePartyPopper(); + else fireMiniConfetti(document.getElementById("quiz-chapter-session") ?? document.body); if (individualActivityCount === 0) { integrity.finish(); window.dispatchEvent(new Event("buildment:quiz-perfect")); diff --git a/frontend/src/components/mascot/mascot-player.tsx b/frontend/src/components/mascot/mascot-player.tsx index 578c5a57f..b174d7cbc 100644 --- a/frontend/src/components/mascot/mascot-player.tsx +++ b/frontend/src/components/mascot/mascot-player.tsx @@ -3,11 +3,16 @@ import Link from "next/link"; import { useEffect, useRef, useState, useSyncExternalStore } from "react"; import { createPortal } from "react-dom"; -import { ArrowRight, Volume2, VolumeX, X } from "lucide-react"; +import { ArrowRight, Sparkles, Volume2, VolumeX, X } from "lucide-react"; +import { fireMiniConfetti } from "@buildment/learning-ui/components/learn/mini-confetti"; import type { MascotReaction } from "@/shared/engagement/engine"; import { playDotVoice, useDotVoice } from "@/lib/engagement/dot-voice"; +import { subscribeToEngagementEvents } from "@/lib/engagement/client"; import { useMascotReactions } from "@/lib/engagement/use-mascot"; import { requestAskHelp } from "@/lib/engagement/ask-help"; +import { playFeedback } from "@/lib/sound-feedback"; +import { toast } from "@/components/ui/app-toast"; +import { RewardCelebrationDialog, type RewardCelebration } from "@/components/rewards/reward-celebration-dialog"; import { Dot } from "@/components/brand/dot"; import { dotMoodForState } from "@/components/mascot/dot-mood"; import { cn } from "@/lib/utils"; @@ -100,11 +105,17 @@ const ACTION_BUTTON = const BUBBLE_BUTTON = "grid size-8 place-items-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"; -/** One reaction: the character and its speech bubble. Mounted fresh (keyed) for every reaction. */ +/** Celebratory mascot states that deserve confetti / audio cue even without a modal or voice clip. */ +const CELEBRATORY_STATES = new Set(["celebrate", "proud", "perfect", "level_up", "goal", "graduation", "message_good"]); +/** Rules that celebrate even though their mascot state is also used for non-celebratory moments. */ +const CELEBRATORY_RULE_IDS = new Set(["enrolled"]); + +/** One reaction: the character and its speech bubble. Mounted fresh (key) for every reaction. */ function ReactionBubble({ reaction, animate, voiceOn, + bubbleRef, onToggleVoice, onPause, onDismiss, @@ -112,6 +123,7 @@ function ReactionBubble({ reaction: MascotReaction; animate: boolean; voiceOn: boolean; + bubbleRef?: React.RefObject; onToggleVoice: () => void; onPause: (paused: boolean) => void; onDismiss: () => void; @@ -141,6 +153,7 @@ function ReactionBubble({
    (null); const layerRef = useRef(null); + const bubbleRef = useRef(null); const reducedMotion = useReducedMotion(); const [voiceOn, setVoiceOn] = useDotVoice(); const [speaking, setSpeaking] = useState(false); const [held, setHeld] = useState<{ reaction: MascotReaction; seq: number } | null>(null); + const [queuedLevelReward, setQueuedLevelReward] = useState(null); + const [activeLevelReward, setActiveLevelReward] = useState(null); + const [queuedGoalToasts, setQueuedGoalToasts] = useState([]); useMascotReactions((reaction, seq) => { // Dot stays out of a quiz: its reaction (and voice) waits until the quiz closes. Only the @@ -222,6 +239,87 @@ export function MascotPlayer() { setShown({ reaction, seq }); }); + // Catch lower-priority milestones (XP level-ups, daily/weekly goals) even when a higher-priority + // reaction like course-graduation or quiz-perfect won Dot's single speech bubble. + useEffect(() => { + return subscribeToEngagementEvents((events, _rewards, shownRuleId) => { + for (const event of events) { + if (event.type === "level_up") { + setQueuedLevelReward({ + size: "large", + icon: Sparkles, + kicker: "Level up", + title: `You reached Level ${event.payload.level}`, + description: "Every lesson and exercise moves you forward.", + action: { label: "View your profile", href: "/profile" }, + }); + } else if ( + event.type === "weekly_goal_met" && + shownRuleId !== "weekly-goal-met-with-freeze" && + shownRuleId !== "weekly-goal-met" + ) { + const line = event.payload.freezeEarned + ? "Weekly goal met! You earned a Streak Freeze." + : "Weekly goal met!"; + setQueuedGoalToasts((prev) => (prev.includes(line) ? prev : [...prev, line])); + } else if (event.type === "daily_goal_met" && shownRuleId !== "daily-goal-met") { + setQueuedGoalToasts((prev) => (prev.includes("Daily goal done!") ? prev : [...prev, "Daily goal done!"])); + } + } + }); + }, []); + + // Present queued level-up celebration dialog and swallowed goal toasts once quizzes/modals clear. + useEffect(() => { + if (!queuedLevelReward && queuedGoalToasts.length === 0) return; + let active = true; + const flush = () => { + if (!active || quizOpen() || modalOpen()) return; + if (queuedLevelReward) { + const next = queuedLevelReward; + setQueuedLevelReward(null); + setActiveLevelReward(next); + return; + } + if (queuedGoalToasts.length > 0) { + const messages = queuedGoalToasts; + setQueuedGoalToasts([]); + playFeedback("celebration"); + for (const msg of messages) toast(msg, "success"); + } + }; + const timer = window.setTimeout(flush, 350); + const observer = new MutationObserver(() => { + window.setTimeout(flush, 250); + }); + observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["open"] }); + return () => { + active = false; + window.clearTimeout(timer); + observer.disconnect(); + }; + }, [queuedLevelReward, queuedGoalToasts]); + + // Celebratory mascot bubbles get subtle confetti and a chime when they don't already have a voice clip + // or modal party popper. + useEffect(() => { + if (!shown) return; + const { state, voice, ruleId } = shown.reaction; + if ((!CELEBRATORY_STATES.has(state) && !CELEBRATORY_RULE_IDS.has(ruleId)) || ruleId === "level-up") return; + if (!voice) { + try { + playFeedback("celebration"); + } catch { + /* Sound feedback is best effort */ + } + } + if (ruleId === "course-graduation" || reducedMotion) return; + const timer = window.setTimeout(() => { + if (bubbleRef.current) fireMiniConfetti(bubbleRef.current); + }, 80); + return () => window.clearTimeout(timer); + }, [shown, reducedMotion]); + useEffect(() => { if (!held) return; const observer = new MutationObserver(() => { @@ -306,6 +404,7 @@ export function MascotPlayer() { reaction={shown.reaction} animate={!reducedMotion} voiceOn={voiceOn} + bubbleRef={bubbleRef} onToggleVoice={() => setVoiceOn(!voiceOn)} onPause={setPaused} onDismiss={() => { @@ -326,6 +425,7 @@ export function MascotPlayer() { : ""}

    {shown && modalHost?.open ? createPortal(layer, modalHost) : layer} + setActiveLevelReward(null)} /> ); } diff --git a/frontend/src/lib/celebrate.ts b/frontend/src/lib/celebrate.ts index 78b2ff302..31763d065 100644 --- a/frontend/src/lib/celebrate.ts +++ b/frontend/src/lib/celebrate.ts @@ -1,6 +1,7 @@ "use client"; import { fireMiniConfetti } from "@buildment/learning-ui/components/learn/mini-confetti"; +import { firePartyPopper } from "@/lib/party-popper"; import { playFeedback, type FeedbackKind } from "@/lib/sound-feedback"; // One feedback recipe for every reward moment, sized by how big the moment is, so a quest claim, @@ -17,5 +18,9 @@ export const CELEBRATION_SOUND: Record = { export function celebrate(size: CelebrationSize, anchor?: HTMLElement | null): void { playFeedback(CELEBRATION_SOUND[size]); + if (size === "large") { + firePartyPopper(); + return; + } if (anchor) fireMiniConfetti(anchor); } diff --git a/frontend/src/lib/engagement/client.ts b/frontend/src/lib/engagement/client.ts index e12532b89..37cd0d5bd 100644 --- a/frontend/src/lib/engagement/client.ts +++ b/frontend/src/lib/engagement/client.ts @@ -1,5 +1,5 @@ import { apiFetch } from "@/lib/api-client"; -import type { TrackEventResult } from "@/shared/api/engagement"; +import type { RecordedEngagementEvent, TrackEventResult } from "@/shared/api/engagement"; import { createEngagementEngine, type EngagementEngine, @@ -23,11 +23,17 @@ import { onNotificationToast } from "@/lib/notifications/notification-store"; // Components call trackEngagement() after their own action succeeded and never wait on it. type Listener = (reaction: MascotReaction) => void; +type EventBatchListener = ( + events: readonly RecordedEngagementEvent[], + rewards?: TrackEventResult["rewards"], + shownRuleId?: string | null +) => void; const SESSION_KEY = "buildment:engagement:session"; /** The learning log autosaves while the learner types; one note event a minute per chapter is plenty. */ const NOTES_THROTTLE_MS = 60_000; const listeners = new Set(); +const eventListeners = new Set(); const lastNotesSent = new Map(); let engine: EngagementEngine | null = null; /** How many mascot players are announcing live messages (the learn layout mounts one). */ @@ -57,6 +63,9 @@ function getEngine(): EngagementEngine { present: (reaction) => { for (const listener of listeners) listener(reaction); }, + onEvents: (events, rewards, shownRuleId) => { + for (const listener of eventListeners) listener(events, rewards, shownRuleId); + }, storage: browserStore, isReading: () => isReadingPath(window.location.pathname), area: () => pageAreaFor(window.location.pathname), @@ -87,6 +96,11 @@ export function subscribeToMascotReactions(listener: Listener): () => void { return () => listeners.delete(listener); } +export function subscribeToEngagementEvents(listener: EventBatchListener): () => void { + eventListeners.add(listener); + return () => eventListeners.delete(listener); +} + /** * While a mascot player is mounted, the messenger announces the live notifications it has words * for (a mentor's reply, review feedback, a resolved question) instead of a toast. diff --git a/frontend/src/shared/api/learner.ts b/frontend/src/shared/api/learner.ts index 40ee1b06f..79b5dc7dc 100644 --- a/frontend/src/shared/api/learner.ts +++ b/frontend/src/shared/api/learner.ts @@ -110,6 +110,7 @@ export type MenteeDashboardViewModel = { habit: LearnerHabit; gamification: GamificationSummary; leaderboard: LeaderboardHubView | null; + unclaimedAchievements?: { count: number; totalCredits: number; ids: string[] } | null; }; export type LearnerProgressModule = { diff --git a/frontend/src/shared/engagement/engine.ts b/frontend/src/shared/engagement/engine.ts index 5e138fc25..f2e81a53a 100644 --- a/frontend/src/shared/engagement/engine.ts +++ b/frontend/src/shared/engagement/engine.ts @@ -42,6 +42,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; }; @@ -56,6 +58,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. */ @@ -120,8 +124,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())); @@ -148,6 +160,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/frontend/tests/unit/leaderboard/weekly-league-celebration.test.ts b/frontend/tests/unit/leaderboard/weekly-league-celebration.test.ts new file mode 100644 index 000000000..653fcdc90 --- /dev/null +++ b/frontend/tests/unit/leaderboard/weekly-league-celebration.test.ts @@ -0,0 +1,124 @@ +import { describe, expect, it } from "vitest"; +import type { LeaderboardHubView, LeagueInfo } from "@/shared/api/gamification"; +import { + personalBestCelebrationFor, + weeklyLeagueCelebrationFor, +} from "@/components/learn/leaderboard/weekly-league-celebration"; + +function readyView(overrides: Partial> = {}): Extract { + return { + status: "ready", + category: "weekly_xp", + scope: "global", + courseId: null, + courseTitle: null, + metricLabel: "XP", + weekStart: "2026-11-30", + resetsAt: "2026-12-07T00:00:00.000Z", + groupSize: 12, + you: { rank: 5, score: 150, bestScore: 300 }, + entries: [], + lastWeek: null, + league: null, + ...overrides, + }; +} + +function leagueInfo(overrides: Partial = {}): LeagueInfo { + return { + tier: "SILVER", + nextTier: "GOLD", + prevTier: "BRONZE", + rank: 5, + groupSize: 12, + promotionZone: 3, + demotionZone: 10, + goal: 200, + goalMet: false, + inPromotionZone: false, + promotionPath: null, + recovery: null, + lastWeek: null, + ...overrides, + }; +} + +describe("weeklyLeagueCelebrationFor", () => { + it("builds large promotion rewards for Monday rank and goal promotions", () => { + const byRank = weeklyLeagueCelebrationFor( + readyView({ league: leagueInfo({ lastWeek: { outcome: "PROMOTED", fromTier: "BRONZE" } }) }) + ); + expect(byRank?.key).toBe("league-promo:2026-11-30:PROMOTED"); + expect(byRank?.reward).toMatchObject({ + size: "large", + title: "Promoted to Silver League", + action: { label: "View league", href: "/leaderboard" }, + }); + expect(byRank?.reward.description).toContain("promotion zone"); + + const byTarget = weeklyLeagueCelebrationFor( + readyView({ league: leagueInfo({ lastWeek: { outcome: "PROMOTED_TARGET", fromTier: "BRONZE" } }) }), + { onLeaderboard: true } + ); + expect(byTarget?.reward.description).toContain("weekly XP goal"); + expect(byTarget?.reward.action).toBeUndefined(); + + const byBoth = weeklyLeagueCelebrationFor( + readyView({ league: leagueInfo({ lastWeek: { outcome: "PROMOTED_BOTH", fromTier: "BRONZE" } }) }) + ); + expect(byBoth?.reward.description).toContain("promotion zone and hitting your weekly goal"); + }); + + it("celebrates finishing in last week's top 3", () => { + const podium = weeklyLeagueCelebrationFor( + readyView({ + lastWeek: { + weekStart: "2026-11-23", + winners: [{ rank: 2, name: "You", score: 420, isYou: true }], + }, + }) + ); + expect(podium?.key).toBe("last-week-podium:2026-11-23:2"); + expect(podium?.reward).toMatchObject({ + size: "large", + title: "You finished #2 last week", + }); + expect(podium?.reward.description).toContain("420 XP"); + }); + + it("celebrates League Shield and Recovery Quest saves with medium size", () => { + const shield = weeklyLeagueCelebrationFor( + readyView({ league: leagueInfo({ tier: "GOLD", lastWeek: { outcome: "SHIELD_HELD", fromTier: "GOLD" } }) }) + ); + expect(shield?.reward).toMatchObject({ size: "medium", title: "Gold League held" }); + expect(shield?.reward.description).toContain("League Shield"); + + const recovery = weeklyLeagueCelebrationFor( + readyView({ league: leagueInfo({ tier: "GOLD", lastWeek: { outcome: "RECOVERY_HELD", fromTier: "GOLD" } }) }) + ); + expect(recovery?.reward).toMatchObject({ size: "medium", title: "Gold League held" }); + expect(recovery?.reward.description).toContain("recovery quest"); + }); + + it("returns null for HELD, DEMOTED, or missing reset outcomes", () => { + expect(weeklyLeagueCelebrationFor(null)).toBeNull(); + expect( + weeklyLeagueCelebrationFor(readyView({ league: leagueInfo({ lastWeek: { outcome: "HELD", fromTier: "SILVER" } }) })) + ).toBeNull(); + expect( + weeklyLeagueCelebrationFor(readyView({ league: leagueInfo({ lastWeek: { outcome: "DEMOTED", fromTier: "GOLD" } }) })) + ).toBeNull(); + }); +}); + +describe("personalBestCelebrationFor", () => { + it("returns a celebration only when score strictly beats a positive prior best", () => { + expect(personalBestCelebrationFor(readyView({ you: { rank: 1, score: 350, bestScore: 300 } }))).toEqual({ + key: "personal-best:weekly_xp:global:global:2026-11-30", + message: "New personal best! 350 XP.", + }); + expect(personalBestCelebrationFor(readyView({ you: { rank: 2, score: 300, bestScore: 300 } }))).toBeNull(); + expect(personalBestCelebrationFor(readyView({ you: { rank: 1, score: 100, bestScore: 0 } }))).toBeNull(); + expect(personalBestCelebrationFor(readyView({ you: { rank: 1, score: 100, bestScore: null } }))).toBeNull(); + }); +}); diff --git a/frontend/tests/unit/lib/celebrate.test.ts b/frontend/tests/unit/lib/celebrate.test.ts new file mode 100644 index 000000000..2509002c7 --- /dev/null +++ b/frontend/tests/unit/lib/celebrate.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +const { fireMiniConfetti, firePartyPopper, playFeedback } = vi.hoisted(() => ({ + fireMiniConfetti: vi.fn(), + firePartyPopper: vi.fn(), + playFeedback: vi.fn(), +})); + +vi.mock("@buildment/learning-ui/components/learn/mini-confetti", () => ({ + fireMiniConfetti, +})); +vi.mock("@/lib/party-popper", () => ({ + firePartyPopper, +})); +vi.mock("@/lib/sound-feedback", () => ({ + playFeedback, +})); + +import { celebrate } from "@/lib/celebrate"; + +afterEach(() => { + vi.clearAllMocks(); +}); + +describe("celebrate", () => { + it("plays success sound and fires mini confetti on small rewards", () => { + const anchor = {} as HTMLElement; + celebrate("small", anchor); + expect(playFeedback).toHaveBeenCalledWith("success"); + expect(fireMiniConfetti).toHaveBeenCalledWith(anchor); + expect(firePartyPopper).not.toHaveBeenCalled(); + }); + + it("plays celebration sound and fires mini confetti on medium rewards", () => { + const anchor = {} as HTMLElement; + celebrate("medium", anchor); + expect(playFeedback).toHaveBeenCalledWith("celebration"); + expect(fireMiniConfetti).toHaveBeenCalledWith(anchor); + expect(firePartyPopper).not.toHaveBeenCalled(); + }); + + it("plays completion sound and fires party popper on large rewards", () => { + const anchor = {} as HTMLElement; + celebrate("large", anchor); + expect(playFeedback).toHaveBeenCalledWith("completion"); + expect(firePartyPopper).toHaveBeenCalledOnce(); + expect(fireMiniConfetti).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/learning-ui/src/blocks/ai-interview/AiInterviewClient.tsx b/packages/learning-ui/src/blocks/ai-interview/AiInterviewClient.tsx index 78dc25edf..684c9ce14 100644 --- a/packages/learning-ui/src/blocks/ai-interview/AiInterviewClient.tsx +++ b/packages/learning-ui/src/blocks/ai-interview/AiInterviewClient.tsx @@ -1,8 +1,9 @@ "use client"; -import { useState } from "react"; +import { useRef, useState } from "react"; import type { AiInterviewInitialState, AiInterviewSessionView } from "../../shared/api/ai"; import type { SanitizedAiInterviewConfig } from "../../shared/blocks/ai-interview/schema"; +import { fireMiniConfetti } from "../../components/learn/mini-confetti"; import { AiInterviewView, type InterviewBusy } from "./AiInterviewView"; import { friendlyError, type ContextDrafts } from "./interview-model"; @@ -31,6 +32,7 @@ export function AiInterviewClient({ const [answerDraft, setAnswerDraft] = useState(""); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); + const cardRef = useRef(null); async function call(kind: Exclude, path: string, json: unknown): Promise { setBusy(kind); @@ -71,6 +73,7 @@ export function AiInterviewClient({ const next = await call("finishing", "finish", { sessionId: session.id }); if (next) { setSession(next); + if (cardRef.current) fireMiniConfetti(cardRef.current); onFeedback?.("success"); onComplete?.(); } @@ -87,25 +90,27 @@ export function AiInterviewClient({ } return ( - setContextDrafts((drafts) => ({ ...drafts, [field]: value }))} - onAnswerChange={setAnswerDraft} - onStart={start} - onSend={send} - onFinish={finish} - onStartOver={startOver} - onPracticeAgain={() => { - setSession(null); - setError(null); - }} - /> +
    + setContextDrafts((drafts) => ({ ...drafts, [field]: value }))} + onAnswerChange={setAnswerDraft} + onStart={start} + onSend={send} + onFinish={finish} + onStartOver={startOver} + onPracticeAgain={() => { + setSession(null); + setError(null); + }} + /> +
    ); } diff --git a/packages/learning-ui/src/blocks/exercises/CodeExerciseClient.tsx b/packages/learning-ui/src/blocks/exercises/CodeExerciseClient.tsx index ad9a888f2..b79e0aef0 100644 --- a/packages/learning-ui/src/blocks/exercises/CodeExerciseClient.tsx +++ b/packages/learning-ui/src/blocks/exercises/CodeExerciseClient.tsx @@ -14,6 +14,7 @@ import { Button } from "../../components/ui/button"; import { cn } from "../../lib/utils"; import type { SanitizedCodeConfig } from "../../shared/blocks/code/schema"; import { checkpointAttrs } from "../../components/learn/checkpoint-marker"; +import { fireMiniConfetti } from "../../components/learn/mini-confetti"; type CheckResult = { isCorrect: boolean | null; @@ -187,6 +188,7 @@ export function CodeExerciseClient({ const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); const [hintIndex, setHintIndex] = useState(-1); + const cardRef = useRef(null); const hints = config.hints ?? []; const canRetry = result && !result.isCorrect && config.allowRetry; @@ -222,8 +224,10 @@ export function CodeExerciseClient({ if (!onRespond) throw new Error("Code submission is unavailable."); const body = await onRespond({ source }); setResult(body); - if (body.isCorrect === true) onFeedback?.("success"); - else if (body.isCorrect === false) onFeedback?.("error"); + if (body.isCorrect === true) { + if (cardRef.current) fireMiniConfetti(cardRef.current); + onFeedback?.("success"); + } else if (body.isCorrect === false) onFeedback?.("error"); onComplete?.(); } catch (err) { onFeedback?.("error"); @@ -242,6 +246,7 @@ export function CodeExerciseClient({ return (
    container.remove(), 250); + window.setTimeout(() => { + try { + if (typeof container.hidePopover === "function") container.hidePopover(); + } catch { + // Already hidden. + } + container.remove(); + }, 250); } diff --git a/server/src/services/learner/dashboard-model.ts b/server/src/services/learner/dashboard-model.ts index 714b65600..455288ebe 100644 --- a/server/src/services/learner/dashboard-model.ts +++ b/server/src/services/learner/dashboard-model.ts @@ -167,6 +167,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; @@ -412,5 +413,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 9aef24d31..1678d34d6 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 { buildMenteeDashboardViewModel } from "./dashboard-model.js"; import { learnerTimeZone } from "./time-zone.js"; @@ -195,6 +197,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); @@ -232,5 +251,6 @@ export async function loadMenteeDashboard(args: { habit, gamification, leaderboard, + unclaimedAchievements, }); } diff --git a/server/src/shared/api/learner.ts b/server/src/shared/api/learner.ts index 287588286..a9525abd5 100644 --- a/server/src/shared/api/learner.ts +++ b/server/src/shared/api/learner.ts @@ -109,6 +109,7 @@ export type MenteeDashboardViewModel = { habit: LearnerHabit; gamification: GamificationSummary; leaderboard: LeaderboardHubView | null; + unclaimedAchievements?: { count: number; totalCredits: number; ids: string[] } | null; }; export type LearnerProgressModule = { 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/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 }, + ]); + }); }); From 73a51b857b2a145d19bc1f70166826e2a0129bb4 Mon Sep 17 00:00:00 2001 From: Aqib Nawab Date: Thu, 3 Dec 2026 17:54:21 +0500 Subject: [PATCH 4/6] Show where the learner stands in the profile header The header showed course counts and the current course, which the career map below already shows. It now shows rank tiles: the all-time XP rank among learners on the leaderboards (Top N% on a board of 20 or more), this week's league rank, the best league finish and top-three finishes. Ranks come only from the global boards, which list only learners who joined the leaderboards, so a profile never shows a rank its owner did not choose to share. A learner with no rank keeps the old stats, and the owner gets a link to join the leaderboard. --- .../profile/public-profile-card.tsx | 48 +++++++++++++------ frontend/src/lib/profile-view.ts | 40 +++++++++++++++- frontend/src/shared/api/public-profile.ts | 16 ++++++- frontend/tests/unit/lib/profile-view.test.ts | 28 ++++++++++- server/src/services/profile/public-profile.ts | 28 ++++++++++- server/src/shared/api/public-profile.ts | 16 ++++++- 6 files changed, 157 insertions(+), 19 deletions(-) diff --git a/frontend/src/components/profile/public-profile-card.tsx b/frontend/src/components/profile/public-profile-card.tsx index 14a83a859..41fed1d96 100644 --- a/frontend/src/components/profile/public-profile-card.tsx +++ b/frontend/src/components/profile/public-profile-card.tsx @@ -31,7 +31,7 @@ import { LEAGUE_TIER_LABELS } from "@/shared/gamification/leagues"; import { CosmeticDot } from "@/components/learn/rewards/cosmetic-dot"; import { Dot, type DotMood } from "@/components/brand/dot"; import { cn } from "@/lib/utils"; -import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, shortDate, type CareerNodeState } from "@/lib/profile-view"; +import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, shortDate, standingTiles, type CareerNodeState, type StandingTile } from "@/lib/profile-view"; import { ShareProfileButton } from "./share-profile-button"; import { RevealMore } from "./reveal-more"; import { AchievementClaimButton } from "./achievement-claim-button"; @@ -80,6 +80,17 @@ function HeroStat({ value, label }: { value: string; label: string }) { ); } +/** One standing tile in the header: the rank big, what it ranks, and its context. */ +function RankTile({ tile, lead }: { tile: StandingTile; lead: boolean }) { + return ( +
    +

    {tile.value}

    +

    {tile.label}

    +

    {tile.sub}

    +
    + ); +} + function HeroTag({ children, highlight = false }: { children: React.ReactNode; highlight?: boolean }) { return ( [claim.id, claim]) : []); const claimTotal = [...claims.values()].reduce((sum, claim) => sum + claim.credits, 0); + const ranks = standingTiles(profile.standing ?? null, profile.records); const stats: { value: string; label: string }[] = []; if (profile.xpTotal !== null) stats.push({ value: profile.xpTotal.toLocaleString(), label: "Lifetime XP" }); if (profile.records) stats.push({ value: String(profile.records.longestStreakDays), label: "Best streak" }); @@ -578,28 +590,36 @@ export function PublicProfileCard({ {CAREER_TIER_LABELS[profile.careerTier]} - - {profile.coursesCompleted} {profile.coursesCompleted === 1 ? "course" : "courses"} completed - {joined ? ( Joined {joined} ) : null} - {profile.currentCourse ? ( - - {profile.currentCourse.title} - - ) : null}
    -
    - {stats.map((stat) => ( - - ))} -
    + {ranks.length > 0 ? ( +
    + {ranks.map((tile, index) => ( + + ))} +
    + ) : ( + <> +
    + {stats.map((stat) => ( + + ))} +
    + {isOwner && !profile.hidden ? ( + + + Join the leaderboard to see where you rank. + + ) : null} + + )} {canShare ? ( ) : ( diff --git a/frontend/src/lib/profile-view.ts b/frontend/src/lib/profile-view.ts index ac5627472..49891f796 100644 --- a/frontend/src/lib/profile-view.ts +++ b/frontend/src/lib/profile-view.ts @@ -1,4 +1,4 @@ -import type { AchievementView } from "@/shared/api/public-profile"; +import type { AchievementView, ProfileRecords, ProfileStanding } from "@/shared/api/public-profile"; import type { CareerRequirement, CareerTier } from "@/shared/api/gamification"; import { CAREER_TIER_LABELS } from "@/shared/gamification/career"; import { LEAGUE_TIER_LABELS, LEAGUE_TIER_ORDER } from "@/shared/gamification/leagues"; @@ -88,3 +88,41 @@ export function achievementProgressCopy(a: AchievementView): string { } return `${a.value} / ${a.nextTarget}`; } + +export type StandingTile = { key: string; value: string; label: string; sub: string }; + +/** + * A rank as people say it: "Top 4%" on a board big enough for a percent to mean something, + * otherwise "#2 of 6". Never better than "Top 1%". + */ +export function rankPhrase(rank: number, total: number): string { + if (total >= 20) return `Top ${Math.max(1, Math.ceil((rank / total) * 100))}%`; + return `#${rank} of ${total}`; +} + +/** + * The profile header's tiles: how the learner stands against other learners, best first, at + * most four. Empty when there is no rank to show (hidden, not on the boards, nothing yet). + */ +export function standingTiles(standing: ProfileStanding | null, records: ProfileRecords | null): StandingTile[] { + const tiles: StandingTile[] = []; + if (standing?.allTime) { + const { rank, total } = standing.allTime; + tiles.push({ key: "all-time", value: rankPhrase(rank, total), label: "Of all learners", sub: `#${rank} of ${total} by XP` }); + } + if (standing?.league) { + const { tier, rank, groupSize } = standing.league; + tiles.push({ key: "league", value: `#${rank}`, label: `${LEAGUE_TIER_LABELS[tier]} league`, sub: `This week, of ${groupSize}` }); + } + const best = records?.bestLeagueFinish; + if (standing && best) { + tiles.push({ key: "best", value: `#${best.rank}`, label: "Best finish", sub: `${LEAGUE_TIER_LABELS[best.tier]}, ${shortDate(best.weekKey)}` }); + } + if (standing && standing.topThreeFinishes > 0) { + tiles.push({ key: "top3", value: `${standing.topThreeFinishes}×`, label: "Top 3 finishes", sub: "Course boards" }); + } + if (standing && !best && records?.highestLeagueTier) { + tiles.push({ key: "highest", value: LEAGUE_TIER_LABELS[records.highestLeagueTier], label: "Highest league", sub: "Reached so far" }); + } + return tiles.slice(0, 4); +} diff --git a/frontend/src/shared/api/public-profile.ts b/frontend/src/shared/api/public-profile.ts index 04326a244..b3132aae5 100644 --- a/frontend/src/shared/api/public-profile.ts +++ b/frontend/src/shared/api/public-profile.ts @@ -38,7 +38,21 @@ 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 } | 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 }; diff --git a/frontend/tests/unit/lib/profile-view.test.ts b/frontend/tests/unit/lib/profile-view.test.ts index 70839dba2..88b4b3c50 100644 --- a/frontend/tests/unit/lib/profile-view.test.ts +++ b/frontend/tests/unit/lib/profile-view.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import type { AchievementView } from "../../../src/shared/api/public-profile"; -import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy } from "../../../src/lib/profile-view"; +import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, rankPhrase, standingTiles } from "../../../src/lib/profile-view"; function achievement(id: string, progress: number, tier: number, nextTarget: number | null): AchievementView { return { @@ -105,3 +105,29 @@ describe("achievementProgressCopy", () => { ).toBe("Silver → Gold"); }); }); + +describe("profile header standing", () => { + const records = { + longestStreakDays: 11, bestWeeklyXp: null, mostXpInADay: null, + bestLeagueFinish: { rank: 1, tier: "BRONZE" as const, weekKey: "2026-11-23" }, + highestLeagueTier: "SILVER" as const, bestWeekChapters: null, mostStudyMinutesInADay: null, + longestSessionMinutes: 0, perfectQuizzes: 0, activeDays: 4, + }; + + it("says Top N% on a big board and #rank of total on a small one", () => { + expect(rankPhrase(3, 41)).toBe("Top 8%"); + expect(rankPhrase(1, 5000)).toBe("Top 1%"); + expect(rankPhrase(2, 6)).toBe("#2 of 6"); + }); + + it("puts the all-time rank first and keeps at most four tiles", () => { + const tiles = standingTiles({ allTime: { rank: 3, total: 41 }, league: { tier: "SILVER", rank: 2, groupSize: 27 }, topThreeFinishes: 3 }, records); + expect(tiles.map((t) => t.key)).toEqual(["all-time", "league", "best", "top3"]); + expect(tiles[0]!.value).toBe("Top 8%"); + expect(tiles[2]!.sub).toBe("Bronze, Nov 23"); + }); + + it("shows no rank for a learner who is not on the leaderboards", () => { + expect(standingTiles(null, records)).toEqual([]); + }); +}); diff --git a/server/src/services/profile/public-profile.ts b/server/src/services/profile/public-profile.ts index 177d6ed79..e09392e57 100644 --- a/server/src/services/profile/public-profile.ts +++ b/server/src/services/profile/public-profile.ts @@ -14,6 +14,8 @@ 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 @@ -133,6 +135,7 @@ const PROFILE_SELECT = { leagueTier: true, careerTier: true, gamificationHidden: true, + leaderboardOptIn: true, profilePublic: true, publicSlug: true, activeCosmetic: true, @@ -147,12 +150,33 @@ 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 } + : 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), @@ -162,6 +186,7 @@ async function buildProfileView(user: ProfileUser, slug: string): Promise
    diff --git a/frontend/src/components/profile/public-profile-card.tsx b/frontend/src/components/profile/public-profile-card.tsx index 21899bec0..4805a6cd5 100644 --- a/frontend/src/components/profile/public-profile-card.tsx +++ b/frontend/src/components/profile/public-profile-card.tsx @@ -32,7 +32,6 @@ import { CosmeticDot } from "@/components/learn/rewards/cosmetic-dot"; import { Dot, type DotMood } from "@/components/brand/dot"; import { cn } from "@/lib/utils"; import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, shortDate, standingTiles, type CareerNodeState, type StandingTile } from "@/lib/profile-view"; -import { ShareProfileButton } from "./share-profile-button"; import { RevealMore } from "./reveal-more"; import { AchievementClaimButton } from "./achievement-claim-button"; import { CareerPromotionCelebration } from "./career-promotion-celebration"; @@ -80,13 +79,19 @@ function HeroStat({ value, label }: { value: string; label: string }) { ); } -/** One cell of the header's standing strip: the rank, what it ranks, and its context. */ +/** + * One cell of the header's strip, read as a sentence: the number first and big ("Top 8%"), what + * it means right after ("of all learners"), then the detail. The lead cell is the proudest one. + */ function RankTile({ tile, lead }: { tile: StandingTile; lead: boolean }) { return ( -
    -
    {tile.label}
    -
    {tile.value}
    -
    {tile.sub}
    +
    +
    {tile.label}
    +
    + {tile.value} + {tile.label} +
    +
    {tile.sub}
    ); } @@ -578,8 +583,7 @@ export function PublicProfileCard({ aria-label="Profile header" className="rounded-2xl bg-[#0a0f2c] px-5 py-5 text-white dark:border dark:bg-card sm:px-6" > -
    -
    +
    @@ -597,17 +601,6 @@ export function PublicProfileCard({ ) : null}
    -
    - {canShare ? ( - - ) : ( - - Make profile public - - )}
    {ranks.length > 0 ? ( diff --git a/frontend/src/lib/profile-view.ts b/frontend/src/lib/profile-view.ts index 49891f796..2b896a97a 100644 --- a/frontend/src/lib/profile-view.ts +++ b/frontend/src/lib/profile-view.ts @@ -92,37 +92,54 @@ export function achievementProgressCopy(a: AchievementView): string { export type StandingTile = { key: string; value: string; label: string; sub: string }; /** - * A rank as people say it: "Top 4%" on a board big enough for a percent to mean something, - * otherwise "#2 of 6". Never better than "Top 1%". + * A rank as people like to hear it. "Top 8%" when the learner is in the top half of a board big + * enough for a percent to mean something. Otherwise the plain place ("#30"), never "Top 73%": + * a big percent reads as a failure, and the header is there to show what the learner has earned. */ export function rankPhrase(rank: number, total: number): string { - if (total >= 20) return `Top ${Math.max(1, Math.ceil((rank / total) * 100))}%`; - return `#${rank} of ${total}`; + const percent = Math.max(1, Math.ceil((rank / total) * 100)); + return total >= 20 && percent <= 50 ? `Top ${percent}%` : `#${rank}`; +} + +/** How close the next league is: a near goal pulls harder than a far one. */ +export function promotionLine(league: NonNullable): string { + if (!league.nextTier) return "Top league"; + if (league.promotionZone > 0 && league.rank <= league.promotionZone) return `In the promotion zone`; + if (league.promotionZone <= 0) return "Keep earning XP this week"; + const gap = league.rank - league.promotionZone; + return `${gap} ${gap === 1 ? "spot" : "spots"} from ${LEAGUE_TIER_LABELS[league.nextTier]}`; } /** - * The profile header's tiles: how the learner stands against other learners, best first, at - * most four. Empty when there is no rank to show (hidden, not on the boards, nothing yet). + * The profile header's strip: what the learner has earned against other learners, proudest + * first, at most four. Each reads as a sentence, number first ("Top 8%" "of all learners"). + * Empty when there is no rank to show (hidden, not on the boards, nothing yet). */ export function standingTiles(standing: ProfileStanding | null, records: ProfileRecords | null): StandingTile[] { const tiles: StandingTile[] = []; if (standing?.allTime) { const { rank, total } = standing.allTime; - tiles.push({ key: "all-time", value: rankPhrase(rank, total), label: "Of all learners", sub: `#${rank} of ${total} by XP` }); + const phrase = rankPhrase(rank, total); + tiles.push(phrase.startsWith("Top") + ? { key: "all-time", value: phrase, label: "of all learners", sub: `#${rank} of ${total} by XP` } + : { key: "all-time", value: phrase, label: `of ${total} learners`, sub: "By lifetime XP" }); } if (standing?.league) { - const { tier, rank, groupSize } = standing.league; - tiles.push({ key: "league", value: `#${rank}`, label: `${LEAGUE_TIER_LABELS[tier]} league`, sub: `This week, of ${groupSize}` }); + const { tier, rank } = standing.league; + tiles.push({ key: "league", value: `#${rank}`, label: `in ${LEAGUE_TIER_LABELS[tier]} league`, sub: promotionLine(standing.league) }); } const best = records?.bestLeagueFinish; if (standing && best) { - tiles.push({ key: "best", value: `#${best.rank}`, label: "Best finish", sub: `${LEAGUE_TIER_LABELS[best.tier]}, ${shortDate(best.weekKey)}` }); + tiles.push(best.rank === 1 + ? { key: "best", value: "1st", label: "league win", sub: `${LEAGUE_TIER_LABELS[best.tier]}, week of ${shortDate(best.weekKey)}` } + : { key: "best", value: `#${best.rank}`, label: "best league finish", sub: `${LEAGUE_TIER_LABELS[best.tier]}, week of ${shortDate(best.weekKey)}` }); } if (standing && standing.topThreeFinishes > 0) { - tiles.push({ key: "top3", value: `${standing.topThreeFinishes}×`, label: "Top 3 finishes", sub: "Course boards" }); + const n = standing.topThreeFinishes; + tiles.push({ key: "top3", value: String(n), label: n === 1 ? "podium finish" : "podium finishes", sub: "Top 3 on a course board" }); } if (standing && !best && records?.highestLeagueTier) { - tiles.push({ key: "highest", value: LEAGUE_TIER_LABELS[records.highestLeagueTier], label: "Highest league", sub: "Reached so far" }); + tiles.push({ key: "highest", value: LEAGUE_TIER_LABELS[records.highestLeagueTier], label: "highest league", sub: "Reached so far" }); } return tiles.slice(0, 4); } diff --git a/frontend/src/shared/api/public-profile.ts b/frontend/src/shared/api/public-profile.ts index b3132aae5..a5868208d 100644 --- a/frontend/src/shared/api/public-profile.ts +++ b/frontend/src/shared/api/public-profile.ts @@ -48,7 +48,15 @@ export type PublicProfileView = { 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 } | null; + 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. */ diff --git a/frontend/tests/unit/lib/profile-view.test.ts b/frontend/tests/unit/lib/profile-view.test.ts index 88b4b3c50..4b2b71bee 100644 --- a/frontend/tests/unit/lib/profile-view.test.ts +++ b/frontend/tests/unit/lib/profile-view.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import type { AchievementView } from "../../../src/shared/api/public-profile"; -import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, rankPhrase, standingTiles } from "../../../src/lib/profile-view"; +import { achievementProgressCopy, careerNodeState, careerRequirementLine, featuredAchievements, monthYear, nextStepCopy, promotionLine, rankPhrase, standingTiles } from "../../../src/lib/profile-view"; function achievement(id: string, progress: number, tier: number, nextTarget: number | null): AchievementView { return { @@ -114,17 +114,28 @@ describe("profile header standing", () => { longestSessionMinutes: 0, perfectQuizzes: 0, activeDays: 4, }; - it("says Top N% on a big board and #rank of total on a small one", () => { + it("says Top N% only in the top half of a big board", () => { expect(rankPhrase(3, 41)).toBe("Top 8%"); expect(rankPhrase(1, 5000)).toBe("Top 1%"); - expect(rankPhrase(2, 6)).toBe("#2 of 6"); + expect(rankPhrase(30, 41)).toBe("#30"); + expect(rankPhrase(2, 6)).toBe("#2"); }); - it("puts the all-time rank first and keeps at most four tiles", () => { - const tiles = standingTiles({ allTime: { rank: 3, total: 41 }, league: { tier: "SILVER", rank: 2, groupSize: 27 }, topThreeFinishes: 3 }, records); - expect(tiles.map((t) => t.key)).toEqual(["all-time", "league", "best", "top3"]); - expect(tiles[0]!.value).toBe("Top 8%"); - expect(tiles[2]!.sub).toBe("Bronze, Nov 23"); + it("tells how close the next league is", () => { + const league = { tier: "SILVER" as const, rank: 7, groupSize: 27, promotionZone: 5, nextTier: "GOLD" as const }; + expect(promotionLine(league)).toBe("2 spots from Gold"); + expect(promotionLine({ ...league, rank: 6 })).toBe("1 spot from Gold"); + expect(promotionLine({ ...league, rank: 2 })).toBe("In the promotion zone"); + expect(promotionLine({ ...league, nextTier: null })).toBe("Top league"); + }); + + it("reads each cell as a sentence, proudest first, at most four", () => { + const tiles = standingTiles( + { allTime: { rank: 3, total: 41 }, league: { tier: "SILVER", rank: 2, groupSize: 27, promotionZone: 5, nextTier: "GOLD" }, topThreeFinishes: 3 }, + records, + ); + expect(tiles.map((t) => `${t.value} ${t.label}`)).toEqual(["Top 8% of all learners", "#2 in Silver league", "1st league win", "3 podium finishes"]); + expect(tiles[2]!.sub).toBe("Bronze, week of Nov 23"); }); it("shows no rank for a learner who is not on the leaderboards", () => { diff --git a/server/src/services/profile/public-profile.ts b/server/src/services/profile/public-profile.ts index e09392e57..f41a0848c 100644 --- a/server/src/services/profile/public-profile.ts +++ b/server/src/services/profile/public-profile.ts @@ -168,7 +168,13 @@ export async function loadProfileStanding(user: Pick 0 ? { rank: allTime.you.rank, total: allTime.groupSize } : null; if (!league && !all && topThreeFinishes === 0) return null; diff --git a/server/src/shared/api/public-profile.ts b/server/src/shared/api/public-profile.ts index 1ec831fef..2b7d26853 100644 --- a/server/src/shared/api/public-profile.ts +++ b/server/src/shared/api/public-profile.ts @@ -47,7 +47,15 @@ export type PublicProfileView = { 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 } | null; + 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. */