- Optional `estimatedReleaseDate` (date and time) on the minigames registry,
with a named migration and regenerated types.
- Sidebar: an `upcoming` game renders greyed out and non-interactive, with a
tooltip carrying the estimate and a live countdown. It is a hoverable row
rather than a disabled menu item, because a disabled Radix item sets
`pointer-events: none` and would swallow the tooltip.
- Page gate: each minigame page checks its registry status and renders
`MinigameComingSoon` instead of the arena while the game is upcoming, so a
typed URL cannot reach unfinished gameplay. The date is display only: the
game goes live when an admin flips `status` to active.
- Leaderboards exclude upcoming games, so they get neither a tab nor a board.
- Pure `countdown.ts` formatter plus a client ticker that computes the
remaining time only after mount, avoiding an SSR hydration mismatch.
Note: `registry.ts`, `payload-types.ts` and `migrations/index.ts` also carry
the Call for Fire registry row and its generated types. That feature was
committed as 6d6a5fb and announced a separate commit for those files; they are
included here because they are entangled with these edits in the same files.
Tests: pure countdown unit tests, registry/gate/leaderboard integration tests,
and an e2e that seeds an upcoming row, hovers the disabled sidebar entry to
assert the tooltip, and checks the coming-soon gate.
286 lines
8.8 KiB
TypeScript
286 lines
8.8 KiB
TypeScript
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<Map<number, string>> {
|
|
const unique = [...new Set(ids)].filter((id) => Number.isFinite(id) && id > 0);
|
|
const names = new Map<number, string>();
|
|
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<PeriodSummary[]> {
|
|
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<PeriodSummary | null> {
|
|
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<BoardPayload[]> {
|
|
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<BoardPayload[]> {
|
|
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<string, ProfileMinigameGroup>;
|
|
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<AchievementPayload[]> {
|
|
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<LeaderboardPayload> {
|
|
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 };
|