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"; // Upcoming games are not shown on the leaderboards (they have no board and // their sidebar entry is disabled), so they get neither a tab nor rows. const playable = registry.filter((game) => game.status !== "upcoming"); const boards = allTime ? await buildAllTimeBoards(payload, playable) : await buildPeriodBoards( payload, query.periodId ?? null, playable.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 };