diff --git a/src/app/(frontend)/minigames/eod/page.tsx b/src/app/(frontend)/minigames/eod/page.tsx index 9d7221ee..8beecaa9 100644 --- a/src/app/(frontend)/minigames/eod/page.tsx +++ b/src/app/(frontend)/minigames/eod/page.tsx @@ -5,6 +5,7 @@ import { headers as nextHeaders } from "next/headers"; import { redirect } from "next/navigation"; import { Bomb } from "lucide-react"; import { EodArena } from "@/components/frontend/minigames/eod/EodArena"; +import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard"; export const metadata: Metadata = { title: "Minefield Clearance (Polaris Task Force)", @@ -60,6 +61,11 @@ export default async function EodPage() { + +
+

Anchored period standings

+ +
); } diff --git a/src/app/(frontend)/minigames/flappy/page.tsx b/src/app/(frontend)/minigames/flappy/page.tsx index a163aacf..9712e6b8 100644 --- a/src/app/(frontend)/minigames/flappy/page.tsx +++ b/src/app/(frontend)/minigames/flappy/page.tsx @@ -5,6 +5,7 @@ import { headers as nextHeaders } from "next/headers"; import { redirect } from "next/navigation"; import { Bird } from "lucide-react"; import { FlappyArena } from "@/components/frontend/minigames/flappy/FlappyArena"; +import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard"; export const metadata: Metadata = { title: "Flight Simulator: Polaris Task Force", @@ -58,6 +59,11 @@ export default async function FlappyPage() { + +
+

Anchored period standings

+ +
); } diff --git a/src/app/(frontend)/minigames/leaderboards/page.tsx b/src/app/(frontend)/minigames/leaderboards/page.tsx new file mode 100644 index 00000000..68ef314b --- /dev/null +++ b/src/app/(frontend)/minigames/leaderboards/page.tsx @@ -0,0 +1,37 @@ +import { Metadata } from "next"; +import config from "@payload-config"; +import { getPayload } from "payload"; +import { headers as nextHeaders } from "next/headers"; +import { redirect } from "next/navigation"; + +import { MinigameLeaderboards } from "@/components/frontend/minigames/MinigameLeaderboards"; +import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry"; + +export const metadata: Metadata = { + title: "Minigame Leaderboards: Polaris Task Force", + description: "Period standings, all-time bests and achievements for the Polaris minigames.", +}; + +export default async function MinigameLeaderboardsPage({ + searchParams, +}: { + searchParams: Promise<{ game?: string }>; +}) { + const { game } = await searchParams; + const headers = await nextHeaders(); + const payloadConfig = await config; + const payload = await getPayload({ config }); + const { user } = await payload.auth({ headers, canSetHeaders: false }); + + if (!user) { + redirect(`/login?returnTo=${encodeURIComponent("/minigames/leaderboards")}`); + } + + const games = await loadMinigameRegistry(payload); + + return ( +
+ +
+ ); +} diff --git a/src/app/(frontend)/minigames/opord/page.tsx b/src/app/(frontend)/minigames/opord/page.tsx index 8a7e39bd..ade1e90f 100644 --- a/src/app/(frontend)/minigames/opord/page.tsx +++ b/src/app/(frontend)/minigames/opord/page.tsx @@ -5,6 +5,7 @@ import { headers as nextHeaders } from "next/headers"; import { redirect } from "next/navigation"; import { ScrollText } from "lucide-react"; import { OpordArena } from "@/components/frontend/minigames/opord/OpordArena"; +import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard"; export const metadata: Metadata = { title: "OPORD Recall (Polaris Task Force)", @@ -61,6 +62,11 @@ export default async function OpordPage() { + +
+

Anchored period standings

+ +
); } diff --git a/src/app/(frontend)/minigames/qualification/page.tsx b/src/app/(frontend)/minigames/qualification/page.tsx index bc847323..71df6799 100644 --- a/src/app/(frontend)/minigames/qualification/page.tsx +++ b/src/app/(frontend)/minigames/qualification/page.tsx @@ -7,6 +7,7 @@ import { Crosshair } from "lucide-react"; import type { AimTrainerStats } from "@/app/(frontend)/minigames/qualification/actions"; import { AimTrainerArena } from "@/components/frontend/minigames/qualification/AimTrainerArena"; +import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard"; export const metadata: Metadata = { title: "Qualification Course: Polaris Task Force", @@ -65,6 +66,11 @@ export default async function QualificationPage() { + +
+

Anchored period standings

+ +
); } diff --git a/src/app/(frontend)/minigames/radio/page.tsx b/src/app/(frontend)/minigames/radio/page.tsx index a3304d37..df42265e 100644 --- a/src/app/(frontend)/minigames/radio/page.tsx +++ b/src/app/(frontend)/minigames/radio/page.tsx @@ -5,6 +5,7 @@ import { headers as nextHeaders } from "next/headers"; import { redirect } from "next/navigation"; import { Radio } from "lucide-react"; import { RadioArena } from "@/components/frontend/minigames/radio/RadioArena"; +import { PeriodStandingsCard } from "@/components/frontend/minigames/PeriodStandingsCard"; export const metadata: Metadata = { title: "Radio Traffic (Polaris Task Force)", @@ -69,6 +70,11 @@ export default async function RadioPage() { + +
+

Anchored period standings

+ +
); } diff --git a/src/app/api/minigames/leaderboards/route.ts b/src/app/api/minigames/leaderboards/route.ts new file mode 100644 index 00000000..4c8114a2 --- /dev/null +++ b/src/app/api/minigames/leaderboards/route.ts @@ -0,0 +1,44 @@ +import { NextRequest, NextResponse } from "next/server"; +import config from "@payload-config"; +import { getPayload } from "payload"; + +import { buildLeaderboardPayload } from "@/lib/minigames/periods/standings"; + +export const dynamic = "force-dynamic"; +export const runtime = "nodejs"; + +/** + * Leaderboard read model for the minigames UI. + * + * Query: `?period=current||all-time` (default `current`) and + * `?achievements=0` to skip the honor roll. Period boards come from the ledger; + * `all-time` reads the untouched profile aggregates. + */ +export async function GET(req: NextRequest) { + const payload = await getPayload({ config: await config }); + const { user } = await payload.auth({ headers: req.headers, canSetHeaders: false }); + if (!user) { + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); + } + + const params = req.nextUrl.searchParams; + const periodParam = params.get("period") ?? "current"; + const scope = periodParam === "all-time" ? "all-time" : "period"; + let periodId: number | null = null; + if (scope === "period" && periodParam !== "current") { + const parsed = Number.parseInt(periodParam, 10); + if (Number.isFinite(parsed)) periodId = parsed; + } + + try { + const data = await buildLeaderboardPayload(payload, { + scope, + periodId, + includeAchievements: params.get("achievements") !== "0", + }); + return NextResponse.json(data); + } catch (error) { + payload.logger.error(`[Minigames] Leaderboard payload failed: ${error}`); + return NextResponse.json({ error: "Could not load leaderboards." }, { status: 500 }); + } +} diff --git a/src/collections/minigames/Achievements.ts b/src/collections/minigames/Achievements.ts index 48a3e2b6..1233d51c 100644 --- a/src/collections/minigames/Achievements.ts +++ b/src/collections/minigames/Achievements.ts @@ -1,24 +1,13 @@ import { CollectionConfig } from "payload"; -import { MINIGAME_ACHIEVEMENT_TYPES, MINIGAME_ACHIEVEMENT_WINDOWS } from "@/lib/minigames/registry"; +import { + MINIGAME_ACHIEVEMENT_TYPE_LABELS, + MINIGAME_ACHIEVEMENT_TYPES, + MINIGAME_ACHIEVEMENT_WINDOW_LABELS, + MINIGAME_ACHIEVEMENT_WINDOWS, +} from "@/lib/minigames/registry"; const readOnly = { admin: { readOnly: true } } as const; -const TYPE_LABELS: Record = { - "period-champion": "Period Champion", - "player-of-month": "Player of the Month", - "player-of-year": "Player of the Year", - diligence: "Diligence (Most Attempts)", - dedication: "Dedication (Most Time)", - precision: "Precision (Accuracy)", - "most-improved": "Most Improved", -}; - -const WINDOW_LABELS: Record = { - period: "Period", - month: "Month", - year: "Year", -}; - /** * Evidence store for close-time achievements. This is NOT the Awards system: * awards are unit decorations, achievements are minigame honors. @@ -51,7 +40,7 @@ export const Achievements: CollectionConfig = { required: true, index: true, options: MINIGAME_ACHIEVEMENT_WINDOWS.map((value) => ({ - label: WINDOW_LABELS[value] ?? value, + label: MINIGAME_ACHIEVEMENT_WINDOW_LABELS[value] ?? value, value, })), ...readOnly, @@ -64,7 +53,7 @@ export const Achievements: CollectionConfig = { required: true, index: true, options: MINIGAME_ACHIEVEMENT_TYPES.map((value) => ({ - label: TYPE_LABELS[value] ?? value, + label: MINIGAME_ACHIEVEMENT_TYPE_LABELS[value] ?? value, value, })), ...readOnly, diff --git a/src/components/frontend/blocks/NavMinigames.tsx b/src/components/frontend/blocks/NavMinigames.tsx index 181014e3..135da526 100644 --- a/src/components/frontend/blocks/NavMinigames.tsx +++ b/src/components/frontend/blocks/NavMinigames.tsx @@ -1,6 +1,6 @@ "use client"; -import { ChevronRight, Gamepad2 } from "lucide-react"; +import { ChevronRight, Gamepad2, Trophy } from "lucide-react"; import Link from "next/link"; import { minigameIcon } from "@/components/frontend/minigames/minigameIcon"; @@ -80,6 +80,15 @@ export function NavMinigames({ games }: { games: RegistryGame[] }) { ); })} + + + + + + Leaderboards + + + diff --git a/src/components/frontend/minigames/AchievementsHonorRoll.tsx b/src/components/frontend/minigames/AchievementsHonorRoll.tsx new file mode 100644 index 00000000..e2a8f1e2 --- /dev/null +++ b/src/components/frontend/minigames/AchievementsHonorRoll.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { Award } from "lucide-react"; +import type { AchievementPayload } from "@/lib/minigames/leaderboardTypes"; + +const formatWindowStart = (iso: string): string => { + const date = new Date(iso); + if (Number.isNaN(date.getTime())) return ""; + return date.toLocaleDateString("en-US", { + month: "short", + day: "numeric", + year: "numeric", + timeZone: "UTC", + }); +}; + +export function AchievementsHonorRoll({ achievements }: { achievements: AchievementPayload[] }) { + if (achievements.length === 0) { + return ( +

+ No achievements yet. The first period close will crown its champions. +

+ ); + } + + return ( +
+ {achievements.map((achievement) => ( +
+ +
+

+ {achievement.typeLabel} + to + {achievement.userName} +

+

+ {achievement.detail ?? `${achievement.value}`} · {achievement.windowLabel} starting{" "} + {formatWindowStart(achievement.windowStart)} +

+
+
+ ))} +
+ ); +} diff --git a/src/components/frontend/minigames/MinigameLeaderboards.tsx b/src/components/frontend/minigames/MinigameLeaderboards.tsx new file mode 100644 index 00000000..846d2e4c --- /dev/null +++ b/src/components/frontend/minigames/MinigameLeaderboards.tsx @@ -0,0 +1,138 @@ +"use client"; + +import { useState } from "react"; +import { Trophy } from "lucide-react"; + +import { AchievementsHonorRoll } from "@/components/frontend/minigames/AchievementsHonorRoll"; +import { minigameIcon } from "@/components/frontend/minigames/minigameIcon"; +import { StandingsTable } from "@/components/frontend/minigames/StandingsTable"; +import { useLeaderboards } from "@/components/frontend/minigames/useLeaderboards"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { cn } from "@/lib/utils"; +import type { RegistryGame } from "@/lib/minigames/registry"; + +export interface MinigameLeaderboardsProps { + games: RegistryGame[]; + currentUserId?: number | string; + initialGame?: string; +} + +/** + * Unified minigames leaderboards: a period selector (current, every past + * period, All-Time), per-game tabs, and the achievements honor roll. Period + * boards come from the ledger; All-Time reads the profile aggregates. + */ +export function MinigameLeaderboards({ games, currentUserId, initialGame }: MinigameLeaderboardsProps) { + const [periodRef, setPeriodRef] = useState("current"); + const [gameKey, setGameKey] = useState(initialGame ?? games[0]?.key ?? "flappy"); + const { data, failed, loading } = useLeaderboards(periodRef); + + const boards = data?.boards ?? []; + const activeBoard = boards.find((board) => board.key === gameKey) ?? boards[0] ?? null; + const isAllTime = data?.mode === "all-time"; + + const periodOptions = [ + { value: "current", label: data?.period ? `Current period · ${data.period.label}` : "Current period" }, + ...(data?.periods ?? []) + .filter((period) => period.id != null && period.id !== data?.period?.id) + .map((period) => ({ + value: String(period.id), + label: `${period.label}${period.status === "open" ? " (open)" : ""}`, + })), + { value: "all-time", label: "All-Time (profile bests)" }, + ]; + + return ( +
+
+
+ +

Minigame Leaderboards

+
+

+ Placement points run across the five Core games each period. Periods reset, history stays. +

+
+ +
+ + {data?.period && ( + + {data.period.startDate.slice(0, 10)} to {data.period.endDate.slice(0, 10)} (UTC) + + )} +
+ +
+ {failed ? ( +

Could not load the leaderboards.

+ ) : loading && !data ? ( +
+
+
+
+ ) : boards.length === 0 ? ( +

No games to show yet.

+ ) : ( + + + {boards.map((board) => { + const Icon = minigameIcon(board.icon); + return ( + + + {board.label} + + ); + })} + + {boards.map((board) => ( + +
+ + {isAllTime ? "All-Time best per operator" : "Best run this period, with placement points"} + + {board.scoreLabel} · top 10 +
+ +
+ ))} +
+ )} +
+ +
+
+ +

Achievements

+ Latest first +
+ +
+
+ ); +} diff --git a/src/components/frontend/minigames/PeriodStandingsCard.tsx b/src/components/frontend/minigames/PeriodStandingsCard.tsx new file mode 100644 index 00000000..d3a94d08 --- /dev/null +++ b/src/components/frontend/minigames/PeriodStandingsCard.tsx @@ -0,0 +1,115 @@ +"use client"; + +import { useState } from "react"; +import Link from "next/link"; +import { Trophy } from "lucide-react"; + +import { minigameIcon } from "@/components/frontend/minigames/minigameIcon"; +import { StandingsTable } from "@/components/frontend/minigames/StandingsTable"; +import { useLeaderboards } from "@/components/frontend/minigames/useLeaderboards"; +import { cn } from "@/lib/utils"; +import type { PresenceParticipant } from "@/hooks/useRealtimePresence"; + +export interface PeriodStandingsCardProps { + gameKey: string; + /** Registry icon name; falls back to the board payload's icon. */ + icon?: string; + refreshKey?: number; + currentUserId?: number | string; + /** Optional presence line shown on the current-period view. */ + presence?: { participants: PresenceParticipant[]; noun?: string }; + className?: string; +} + +/** + * Period-scoped standings for a single game, embedded on the game page. Defaults + * to the current period and offers an All-Time toggle; the full multi-board view + * lives at /minigames/leaderboards. + */ +export function PeriodStandingsCard({ + gameKey, + icon, + refreshKey = 0, + currentUserId, + presence, + className, +}: PeriodStandingsCardProps) { + const [view, setView] = useState<"period" | "all-time">("period"); + const { data, failed, loading } = useLeaderboards(view === "all-time" ? "all-time" : "current", refreshKey); + + const board = data?.boards.find((entry) => entry.key === gameKey) ?? null; + const Icon = minigameIcon(icon ?? board?.icon); + const isAllTime = view === "all-time"; + + return ( +
+
+ + +

{board?.label ?? "Standings"}

+ + {isAllTime ? "All-Time" : (data?.period?.label ?? "No active period")} + +
+ +
+ + + + All boards + +
+ + {presence && !isAllTime && ( +
+ {presence.participants.length}{" "} + {presence.participants.length === 1 ? `${presence.noun ?? "operator"} is` : `${presence.noun ?? "operators"} are`} active now + {presence.participants.length > 0 && ( + + ({presence.participants.map((participant) => participant.name).join(", ")}) + + )} +
+ )} + + {failed ? ( +

Could not load the standings.

+ ) : loading && !data ? ( +
+
+
+
+
+ ) : ( + + )} +
+ ); +} diff --git a/src/components/frontend/minigames/StandingsTable.tsx b/src/components/frontend/minigames/StandingsTable.tsx new file mode 100644 index 00000000..f5d63c02 --- /dev/null +++ b/src/components/frontend/minigames/StandingsTable.tsx @@ -0,0 +1,78 @@ +"use client"; + +import { cn } from "@/lib/utils"; +import type { StandingsRow } from "@/lib/minigames/leaderboardTypes"; + +function rankClass(index: number) { + if (index === 0) return "font-bold text-amber-400"; + if (index === 1) return "font-semibold text-slate-300"; + if (index === 2) return "font-semibold text-amber-700"; + return "text-muted-foreground"; +} + +export interface StandingsTableProps { + rows: StandingsRow[]; + /** Column header for the score column (e.g. "Passes", "Score"). */ + scoreLabel: string; + currentUserId?: number | string; + /** Show the placement-points column (period boards only). */ + showPoints?: boolean; + emptyLabel?: string; + className?: string; +} + +/** + * Shared standings table for both the period boards and the all-time view. + * Rows are already ranked; this only renders them. + */ +export function StandingsTable({ + rows, + scoreLabel, + currentUserId, + showPoints = false, + emptyLabel = "No runs on the board yet.", + className, +}: StandingsTableProps) { + if (rows.length === 0) { + return ( +

{emptyLabel}

+ ); + } + + return ( + + + + + + + + {showPoints && } + + + + {rows.map((row) => { + const isCurrent = row.userId != null && String(row.userId) === String(currentUserId); + return ( + + + + + + {showPoints && ( + + )} + + ); + })} + +
#Operator{scoreLabel}RunsPoints
+ {row.rank} + + + {row.name} + {isCurrent && (you)} + + {row.bestScore}{row.attempts}{row.points}
+ ); +} diff --git a/src/components/frontend/minigames/useLeaderboards.ts b/src/components/frontend/minigames/useLeaderboards.ts new file mode 100644 index 00000000..19496ffd --- /dev/null +++ b/src/components/frontend/minigames/useLeaderboards.ts @@ -0,0 +1,46 @@ +"use client"; + +import { useEffect, useState } from "react"; +import type { LeaderboardPayload } from "@/lib/minigames/leaderboardTypes"; + +/** + * Fetch the leaderboard read model for a period scope. + * + * `periodRef` is "current", "all-time", or a period id as a string. Re-fetches + * when the scope or `refreshKey` changes (a finished run bumps `refreshKey`). + */ +export function useLeaderboards(periodRef: string, refreshKey = 0) { + const [data, setData] = useState(null); + const [failed, setFailed] = useState(false); + const [loading, setLoading] = useState(true); + + useEffect(() => { + let cancelled = false; + setLoading(true); + setFailed(false); + + fetch(`/api/minigames/leaderboards?period=${encodeURIComponent(periodRef)}`) + .then((res) => { + if (!res.ok) throw new Error("leaderboard fetch failed"); + return res.json() as Promise; + }) + .then((json) => { + if (!cancelled) { + setData(json); + setLoading(false); + } + }) + .catch(() => { + if (!cancelled) { + setFailed(true); + setLoading(false); + } + }); + + return () => { + cancelled = true; + }; + }, [periodRef, refreshKey]); + + return { data, failed, loading }; +} diff --git a/src/lib/minigames/leaderboardTypes.ts b/src/lib/minigames/leaderboardTypes.ts new file mode 100644 index 00000000..982d28b7 --- /dev/null +++ b/src/lib/minigames/leaderboardTypes.ts @@ -0,0 +1,55 @@ +/** + * Shared leaderboard read-model types. + * + * Pure (type-only imports) so both the server read models and the client + * components can reference the same shapes without pulling Payload into the + * client bundle. + */ + +export interface PeriodSummary { + id: number | null; + label: string; + status: "open" | "closed"; + startDate: string; + endDate: string; +} + +export interface StandingsRow { + userId: number | null; + name: string; + rank: number; + points: number; + bestScore: number; + attempts: number; + durationMs: number; +} + +export interface BoardPayload { + key: string; + label: string; + scoreLabel: string; + icon: string; + category: string; + rows: StandingsRow[]; +} + +export interface AchievementPayload { + id: number; + type: string; + typeLabel: string; + window: string; + windowLabel: string; + userId: number | null; + userName: string; + value: number; + detail: string | null; + windowStart: string; +} + +export interface LeaderboardPayload { + mode: "period" | "all-time"; + period: PeriodSummary | null; + periods: PeriodSummary[]; + boards: BoardPayload[]; + achievements: AchievementPayload[]; +} diff --git a/src/lib/minigames/periods/ledger.ts b/src/lib/minigames/periods/ledger.ts new file mode 100644 index 00000000..ff202dce --- /dev/null +++ b/src/lib/minigames/periods/ledger.ts @@ -0,0 +1,48 @@ +import type { Payload, Where } from "payload"; +import type { LedgerEntry } from "./boards"; + +/** + * Read helpers for the `minigame-entries` ledger. Shared by the close pipeline + * and the leaderboard endpoint so both interpret rows identically. + */ + +interface EntryDoc { + user: number | { id: number }; + game: string; + score: number | null; + durationMs: number | null; + accuracy: number | null; + createdAt: string; +} + +const userIdOf = (user: EntryDoc["user"]): number => (typeof user === "object" ? user.id : user); + +export const toLedgerEntry = (doc: EntryDoc): LedgerEntry => ({ + userId: userIdOf(doc.user), + game: doc.game, + score: typeof doc.score === "number" ? doc.score : 0, + durationMs: typeof doc.durationMs === "number" ? doc.durationMs : 0, + accuracy: typeof doc.accuracy === "number" ? doc.accuracy : null, + createdAtMs: new Date(doc.createdAt).getTime() || 0, +}); + +/** Fetch every ledger entry matching `where`, following pagination. */ +export async function fetchLedgerEntries(payload: Payload, where: Where): Promise { + const entries: LedgerEntry[] = []; + let page = 1; + for (;;) { + const res = await payload.find({ + collection: "minigame-entries", + where, + sort: "createdAt", + limit: 500, + page, + depth: 0, + overrideAccess: true, + }); + for (const doc of res.docs) entries.push(toLedgerEntry(doc as unknown as EntryDoc)); + if (!res.hasNextPage || page >= 500) break; + page += 1; + } + return entries; +} diff --git a/src/lib/minigames/periods/lifecycle.ts b/src/lib/minigames/periods/lifecycle.ts index a8f1b530..9ab9086b 100644 --- a/src/lib/minigames/periods/lifecycle.ts +++ b/src/lib/minigames/periods/lifecycle.ts @@ -1,9 +1,10 @@ -import type { Payload, Where } from "payload"; +import type { Payload } from "payload"; import { CORE_MINIGAME_KEYS, type MinigameAchievementType } from "@/lib/minigames/registry"; import { loadMinigameRegistry, periodScoringGameKeys } from "@/lib/minigames/loadRegistry"; import { emitGameEvent } from "@/utils/event-log/emit"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { derivePeriodForInstant, periodStartForIndex } from "./derive"; +import { fetchLedgerEntries } from "./ledger"; import { completedMonthWindows, completedYearWindows } from "./calendar"; import { buildGameBoard, @@ -65,48 +66,6 @@ export interface PeriodTickSummary { calendar: CalendarCloseSummary[]; } -interface EntryDoc { - user: number | { id: number }; - game: string; - score: number | null; - durationMs: number | null; - accuracy: number | null; - createdAt: string; -} - -const userIdOf = (user: EntryDoc["user"]): number => - typeof user === "object" ? user.id : user; - -const toLedgerEntry = (doc: EntryDoc): LedgerEntry => ({ - userId: userIdOf(doc.user), - game: doc.game, - score: typeof doc.score === "number" ? doc.score : 0, - durationMs: typeof doc.durationMs === "number" ? doc.durationMs : 0, - accuracy: typeof doc.accuracy === "number" ? doc.accuracy : null, - createdAtMs: new Date(doc.createdAt).getTime() || 0, -}); - -/** Fetch every ledger entry matching `where`, following pagination. */ -const fetchEntries = async (payload: PayloadType, where: Where) => { - const entries: LedgerEntry[] = []; - let page = 1; - for (;;) { - const res = await payload.find({ - collection: "minigame-entries", - where, - sort: "createdAt", - limit: 500, - page, - depth: 0, - overrideAccess: true, - }); - for (const doc of res.docs) entries.push(toLedgerEntry(doc as unknown as EntryDoc)); - if (!res.hasNextPage || page >= 500) break; - page += 1; - } - return entries; -}; - const pointsForPeriod = ( entries: LedgerEntry[], games: string[], @@ -155,7 +114,7 @@ const previousPointsFor = async ( const previousPeriod = previous.docs[0]; // A previous period with no entries still counts as "0 points for everyone". if (!previousPeriod) return new Map(); - const entries = await fetchEntries(payload, { period: { equals: previousPeriod.id } }); + const entries = await fetchLedgerEntries(payload, { period: { equals: previousPeriod.id } }); return pointsForPeriod(entries, games, rules); }; @@ -224,7 +183,7 @@ export async function closePeriodById( const rules = await resolveMinigameRules(payload); const periodGames = games ?? (await resolvePeriodGames(payload)); - const entries = await fetchEntries(payload, { period: { equals: periodId } }); + const entries = await fetchLedgerEntries(payload, { period: { equals: periodId } }); const previousPointsByUser = await previousPointsFor( payload, rules, @@ -317,7 +276,7 @@ export async function closeCalendarWindows( // A calendar window is scored over every run that HAPPENED inside it, // by the run's own server timestamp (a month holds two or three 14-day // periods, and month boundaries split those periods). - const entries = await fetchEntries(payload, { + const entries = await fetchLedgerEntries(payload, { and: [ { occurredAt: { greater_than_equal: windowStart } }, { occurredAt: { less_than: windowEnd } }, diff --git a/src/lib/minigames/periods/standings.ts b/src/lib/minigames/periods/standings.ts new file mode 100644 index 00000000..4998251b --- /dev/null +++ b/src/lib/minigames/periods/standings.ts @@ -0,0 +1,283 @@ +import type { Payload } from "payload"; +import { buildGameBoard } from "./boards"; +import { derivePeriodForInstant } from "./derive"; +import { fetchLedgerEntries } from "./ledger"; +import { resolveMinigameRules } from "./rules"; +import type { + AchievementPayload, + BoardPayload, + LeaderboardPayload, + PeriodSummary, + StandingsRow, +} from "../leaderboardTypes"; + +export type { + AchievementPayload, + BoardPayload, + LeaderboardPayload, + PeriodSummary, + StandingsRow, +} from "../leaderboardTypes"; +import { loadMinigameRegistry, periodScoringGameKeys } from "../loadRegistry"; +import { + MINIGAME_ACHIEVEMENT_TYPE_LABELS, + MINIGAME_ACHIEVEMENT_WINDOW_LABELS, + MINIGAME_PROFILE_GAME_KEYS, + type BuiltinMinigame, + type MinigameAchievementType, + type MinigameAchievementWindow, +} from "../registry"; + +/** + * Read models for the leaderboards UI. + * + * Period boards come from the `minigame-entries` ledger (rank + placement + * points, same ladder as the close pipeline). The All-Time view reads the + * untouched `profiles.progression.minigames.*` aggregates. Both are shaped into + * one row type so a single client component can render either. + */ + +type PayloadType = Payload; +const TOP_ROWS = 10; + +const nameOfUser = (user: unknown): string | null => { + if (!user || typeof user !== "object") return null; + const record = user as { + displayName?: string | null; + payloadDisplayName?: string | null; + username?: string | null; + }; + return record.displayName || record.payloadDisplayName || record.username || null; +}; + +/** Load display names for a set of user ids, in one query. */ +async function namesById(payload: PayloadType, ids: number[]): Promise> { + const unique = [...new Set(ids)].filter((id) => Number.isFinite(id) && id > 0); + const names = new Map(); + if (unique.length === 0) return names; + const res = await payload.find({ + collection: "users", + where: { id: { in: unique } }, + limit: unique.length, + depth: 0, + overrideAccess: true, + }); + for (const user of res.docs) { + names.set(user.id, nameOfUser(user) ?? `Operator #${user.id}`); + } + return names; +} + +/** Recent periods, newest first, for the period selector. */ +export async function listPeriods(payload: PayloadType): Promise { + const res = await payload.find({ + collection: "minigame-periods", + sort: "-startDate", + limit: 80, + depth: 0, + overrideAccess: true, + }); + return res.docs.map((doc) => ({ + id: doc.id, + label: doc.label, + status: doc.status === "closed" ? "closed" : "open", + startDate: doc.startDate, + endDate: doc.endDate, + })); +} + +/** + * The period covering `now`. Returns a virtual period (id null, no rows) when + * the derived period has no ledger row yet, so the UI can show an empty board + * instead of nothing. + */ +export async function currentPeriod(payload: PayloadType): Promise { + const rules = await resolveMinigameRules(payload); + if (!rules.anchorDate) return null; + const derived = derivePeriodForInstant(rules.anchorDate, rules.periodLengthDays, new Date()); + if (!derived) return null; + + const startIso = derived.startDate.toISOString(); + const res = await payload.find({ + collection: "minigame-periods", + where: { startDate: { equals: startIso } }, + limit: 1, + depth: 0, + overrideAccess: true, + }); + const row = res.docs[0]; + return { + id: row?.id ?? null, + label: row?.label ?? derived.label, + status: row?.status === "closed" ? "closed" : "open", + startDate: startIso, + endDate: derived.endDate.toISOString(), + }; +} + +/** Period boards from the ledger for the given games. */ +async function buildPeriodBoards( + payload: PayloadType, + periodId: number | null, + games: BuiltinMinigame[], + topN: number, +): Promise { + const entries = periodId == null ? [] : await fetchLedgerEntries(payload, { period: { equals: periodId } }); + const boards = games.map((game) => ({ + game, + rows: buildGameBoard( + entries.filter((entry) => entry.game === game.key), + topN, + ), + })); + + const names = await namesById( + payload, + boards.flatMap((board) => board.rows.map((row) => row.userId)), + ); + + return boards.map(({ game, rows }) => ({ + key: game.key, + label: game.label, + scoreLabel: game.scoreLabel, + icon: game.icon, + category: game.category, + rows: rows.slice(0, TOP_ROWS).map((row) => ({ + userId: row.userId, + name: names.get(row.userId) ?? `Operator #${row.userId}`, + rank: row.rank, + points: row.points, + bestScore: row.bestScore, + attempts: row.attempts, + durationMs: row.durationMs, + })), + })); +} + +type ProfileMinigameGroup = { bestScore?: number | null; gamesPlayed?: number | null } | null; + +/** All-Time boards from the untouched profile aggregates. */ +async function buildAllTimeBoards( + payload: PayloadType, + games: BuiltinMinigame[], +): Promise { + return Promise.all( + games.map(async (game) => { + const groupKey = MINIGAME_PROFILE_GAME_KEYS[game.key]; + if (!groupKey) { + return { key: game.key, label: game.label, scoreLabel: game.scoreLabel, icon: game.icon, category: game.category, rows: [] }; + } + const path = `progression.minigames.${groupKey}.bestScore`; + const res = await payload.find({ + collection: "profiles", + where: { [path]: { greater_than: 0 } }, + sort: `-${path}`, + limit: TOP_ROWS, + depth: 1, + overrideAccess: true, + }); + const rows: StandingsRow[] = res.docs.map((doc, index) => { + const minigames = (doc.progression?.minigames ?? {}) as Record; + const stats = minigames[groupKey] ?? {}; + const user = typeof doc.user === "object" && doc.user !== null ? doc.user : null; + return { + userId: user?.id ?? null, + name: nameOfUser(user) ?? `Profile #${doc.id}`, + rank: index + 1, + points: 0, + bestScore: stats.bestScore ?? 0, + attempts: stats.gamesPlayed ?? 0, + durationMs: 0, + }; + }); + return { + key: game.key, + label: game.label, + scoreLabel: game.scoreLabel, + icon: game.icon, + category: game.category, + rows, + }; + }), + ); +} + +/** Recent achievements, newest windows first, for the honor roll. */ +export async function recentAchievements( + payload: PayloadType, + limit = 60, +): Promise { + const res = await payload.find({ + collection: "achievements", + sort: "-windowStart", + limit, + depth: 1, + overrideAccess: true, + }); + return res.docs.map((doc) => { + const type = doc.type as MinigameAchievementType; + const window = doc.window as MinigameAchievementWindow; + const user = typeof doc.user === "object" && doc.user !== null ? doc.user : null; + return { + id: doc.id, + type, + typeLabel: MINIGAME_ACHIEVEMENT_TYPE_LABELS[type] ?? type, + window, + windowLabel: MINIGAME_ACHIEVEMENT_WINDOW_LABELS[window] ?? window, + userId: user?.id ?? (typeof doc.user === "number" ? doc.user : null), + userName: nameOfUser(user) ?? "Unknown", + value: doc.value, + detail: doc.detail ?? null, + windowStart: doc.windowStart, + }; + }); +} + +export interface LeaderboardQuery { + /** "period" (default), "all-time", or a specific period id. */ + scope?: "period" | "all-time"; + periodId?: number | null; + includeAchievements?: boolean; + achievementLimit?: number; +} + +/** Compose the full leaderboard payload the UI consumes. */ +export async function buildLeaderboardPayload( + payload: PayloadType, + query: LeaderboardQuery = {}, +): Promise { + const rules = await resolveMinigameRules(payload); + const registry = await loadMinigameRegistry(payload); + const allTime = query.scope === "all-time"; + + const boards = allTime + ? await buildAllTimeBoards(payload, registry) + : await buildPeriodBoards( + payload, + query.periodId ?? null, + registry.filter((game) => game.category === "core"), + rules.placementLadderTopN, + ); + + const periods = await listPeriods(payload); + let period: PeriodSummary | null = null; + if (!allTime) { + period = + query.periodId != null + ? (periods.find((entry) => entry.id === query.periodId) ?? (await currentPeriod(payload))) + : await currentPeriod(payload); + } + + return { + mode: allTime ? "all-time" : "period", + period, + periods, + boards, + achievements: query.includeAchievements + ? await recentAchievements(payload, query.achievementLimit ?? 60) + : [], + }; +} + +/** Exported for tests and callers that need the period-scoring key set. */ +export { periodScoringGameKeys }; diff --git a/src/lib/minigames/registry.ts b/src/lib/minigames/registry.ts index 031b82be..1085d01f 100644 --- a/src/lib/minigames/registry.ts +++ b/src/lib/minigames/registry.ts @@ -154,6 +154,37 @@ export type MinigameAchievementType = (typeof MINIGAME_ACHIEVEMENT_TYPES)[number export const MINIGAME_ACHIEVEMENT_WINDOWS = ["period", "month", "year"] as const; export type MinigameAchievementWindow = (typeof MINIGAME_ACHIEVEMENT_WINDOWS)[number]; +export const MINIGAME_ACHIEVEMENT_TYPE_LABELS: Record = { + "period-champion": "Period Champion", + "player-of-month": "Player of the Month", + "player-of-year": "Player of the Year", + diligence: "Diligence (Most Attempts)", + dedication: "Dedication (Most Time)", + precision: "Precision (Accuracy)", + "most-improved": "Most Improved", +}; + +export const MINIGAME_ACHIEVEMENT_WINDOW_LABELS: Record = { + period: "Period", + month: "Month", + year: "Year", +}; + +/** + * Registry key -> the `profiles.progression.minigames` group name, used by the + * All-Time tab and any all-time fallback. The ledger is the source of truth for + * period boards; these profile aggregates are the untouched all-time stats. + */ +export const MINIGAME_PROFILE_GAME_KEYS: Record = { + flappy: "flappyBird", + eod: "eodMinesweeper", + radio: "radioTraffic", + qualification: "aimTrainer", + opord: "opordRecall", + poker: "poker", + blackjack: "blackjack", +}; + /** Defaults for the `minigame-rules` global, seeded on first migration. */ export const MINIGAME_RULE_DEFAULTS = { enabled: true, diff --git a/tests/int/minigame-standings.int.spec.ts b/tests/int/minigame-standings.int.spec.ts new file mode 100644 index 00000000..0df709d4 --- /dev/null +++ b/tests/int/minigame-standings.int.spec.ts @@ -0,0 +1,162 @@ +import { getPayload, Payload } from "payload"; +import config from "@/payload.config"; + +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import type { User } from "@/payload-types"; +import { recordMinigameEntry } from "@/lib/minigames/periods/record"; +import { closeDuePeriods } from "@/lib/minigames/periods/lifecycle"; +import { + buildLeaderboardPayload, + recentAchievements, +} from "@/lib/minigames/periods/standings"; + +const ANCHOR = "2026-09-07T00:00:00.000Z"; +const RUN = `mgs-${Date.now().toString(36)}`; + +let payload: Payload; +let userA: number; +let userB: number; +let originalRules: Record | null = null; + +describe("Minigame leaderboard read model", () => { + beforeAll(async () => { + const payloadConfig = await config; + payload = await getPayload({ config: payloadConfig }); + await clearMinigameData(); + + originalRules = (await payload.findGlobal({ + slug: "minigame-rules", + depth: 0, + overrideAccess: true, + })) as unknown as Record | null; + + await payload.updateGlobal({ + slug: "minigame-rules", + data: { + enabled: true, + anchorDate: ANCHOR, + periodLengthDays: 14, + placementLadderTopN: 10, + precisionMinAttempts: 1, + }, + overrideAccess: true, + }); + + const createUser = async (suffix: string, displayName: string) => + ( + (await payload.create({ + collection: "users", + data: { + username: `${RUN}-${suffix}`, + discordUsername: `${RUN}-${suffix}`, + displayName, + steamId: `7656119${Math.floor(Math.random() * 1e9)}`, + password: "Test123", + roles: ["user"], + }, + overrideAccess: true, + depth: 0, + })) as unknown as User + ).id; + + userA = await createUser("a", "Alpha Operator"); + userB = await createUser("b", "Bravo Operator"); + }); + + afterAll(async () => { + await clearMinigameData(); + if (!originalRules) return; + await payload + .updateGlobal({ + slug: "minigame-rules", + data: { + enabled: Boolean(originalRules.enabled), + anchorDate: originalRules.anchorDate as string, + periodLengthDays: (originalRules.periodLengthDays as number) ?? 14, + placementLadderTopN: (originalRules.placementLadderTopN as number) ?? 10, + precisionMinAttempts: (originalRules.precisionMinAttempts as number) ?? 5, + }, + overrideAccess: true, + }) + .catch(() => undefined); + }); + + it("builds period boards from the ledger with names and placement points", async () => { + const when = new Date("2026-09-08T12:00:00.000Z"); + await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 9, durationMs: 1_000, now: when }); + await recordMinigameEntry({ payload, userId: userB, game: "flappy", score: 4, durationMs: 1_000, now: when }); + + const periodRow = await payload.find({ + collection: "minigame-periods", + limit: 1, + depth: 0, + overrideAccess: true, + }); + const periodId = periodRow.docs[0]?.id ?? null; + + const payloadData = await buildLeaderboardPayload(payload, { + scope: "period", + periodId, + includeAchievements: true, + }); + + expect(payloadData.mode).toBe("period"); + expect(payloadData.period?.label).toBe("Sep 7 to Sep 20, 2026"); + expect(payloadData.boards).toHaveLength(5); + + const flappy = payloadData.boards.find((board) => board.key === "flappy"); + expect(flappy?.rows.map((row) => row.name)).toEqual(["Alpha Operator", "Bravo Operator"]); + expect(flappy?.rows[0].points).toBe(10); + expect(flappy?.rows[1].points).toBe(9); + expect(flappy?.rows[0].rank).toBe(1); + }); + + it("reads All-Time boards from the untouched profile aggregates", async () => { + const rankRes = await payload.find({ + collection: "ranks", + limit: 1, + depth: 0, + overrideAccess: true, + }); + const rankId = rankRes.docs[0]?.id; + expect(rankId).toBeTruthy(); + + await payload.create({ + collection: "profiles", + data: { + user: userA, + rank: rankId, + dossier: { enlistmentDate: new Date().toISOString() }, + progression: { minigames: { flappyBird: { bestScore: 42, gamesPlayed: 7 } } }, + }, + overrideAccess: true, + depth: 0, + }); + + const payloadData = await buildLeaderboardPayload(payload, { scope: "all-time" }); + expect(payloadData.mode).toBe("all-time"); + const flappy = payloadData.boards.find((board) => board.key === "flappy"); + expect(flappy?.rows[0]?.name).toBe("Alpha Operator"); + expect(flappy?.rows[0]?.bestScore).toBe(42); + expect(flappy?.rows[0]?.attempts).toBe(7); + }); + + it("surfaces achievements after a close", async () => { + await closeDuePeriods(payload, new Date("2026-09-21T00:00:00.000Z")); + const achievements = await recentAchievements(payload, 20); + const types = achievements.map((achievement) => achievement.type); + expect(types).toContain("period-champion"); + expect(achievements.every((achievement) => achievement.userName.length > 0)).toBe(true); + }); + + async function clearMinigameData() { + for (const collection of [ + "achievements", + "minigame-entries", + "minigame-periods", + "minigames", + ] as const) { + await payload.delete({ collection, where: { id: { greater_than: 0 } }, overrideAccess: true }); + } + } +});