1
0
Fork 0

feat(minigames): drive the nav and period scoring from the registry

Phase 4 of the minigame periods feature:

- Server registry loader (lib/minigames/loadRegistry.ts) reads the
  minigames collection and falls back to the built-in seven when it is empty
  or unreadable, so the nav and boards never render blank.
- The sidebar minigames dropdown now renders from the registry (Core and
  Cardtable groups, retired games hidden, registry order), with lucide icons
  resolved from the icon-name string through a client icon map and a
  safe fallback.
- Period scoring is registry-driven: the close pipeline uses core games with
  countsForPeriods instead of a hardcoded list. A retired game simply stops
  accruing entries and drops out of the next period while its history stays.
- Integration tests for the fallback, ordering, retirement filtering and the
  non-scoring-game exclusion; the older minigame specs now wipe the registry
  too so files stay order-independent.
This commit is contained in:
Jason Fraley 2026-10-11 16:27:49 -04:00
parent 5cf245b855
commit deb88ded56
11 changed files with 349 additions and 43 deletions

View file

@ -36,6 +36,8 @@ import type { AnnouncementEntry } from "@/lib/announcements/evaluate";
import { TourHost } from "@/components/frontend/tours/TourHost";
import { DevDashboardGate } from "@/components/frontend/dev/DevDashboardGate";
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry";
import type { RegistryGame } from "@/lib/minigames/registry";
// Skip static prerendering of this layout (and all pages under (frontend)/).
// The layout calls `getPayload()` at render time to resolve the current user,
@ -91,8 +93,10 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
let isAdmin = false;
let statisticsEnabled = true;
let helpdeskEnabled = true;
let minigameNav: RegistryGame[] = [];
if (user) {
minigameNav = await loadMinigameRegistry(payload);
const [
intelligenceQual,
logisticsQual,
@ -187,6 +191,7 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
showCallsign={user.preferences?.display?.showCallsign ?? false}
canImpersonate={await isSuperuser(payload, user)}
preferences={user.preferences}
minigameNav={minigameNav}
className="border-r"
/>
<SidebarInset

View file

@ -34,6 +34,7 @@ import { Progress } from "@/components/ui/progress";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { updatePreferences } from "@/app/(frontend)/account/actions";
import { sidebarData } from "@/components/frontend/blocks/sidebarData";
import type { RegistryGame } from "@/lib/minigames/registry";
const data = {
navMain: [
@ -77,6 +78,7 @@ export function AppSidebar({
showCallsign = false,
canImpersonate = false,
preferences,
minigameNav = [],
...props
}: {
user: {
@ -93,6 +95,7 @@ export function AppSidebar({
showCallsign?: boolean;
canImpersonate?: boolean;
preferences?: NonNullable<User["preferences"]>;
minigameNav?: RegistryGame[];
} & React.ComponentProps<typeof Sidebar>) {
const [isMiniMode, setIsMiniMode] = React.useState<boolean>(
preferences?.display?.xpDisplayMini ?? false,
@ -193,7 +196,7 @@ export function AppSidebar({
</SidebarMenuButton>
</SidebarMenuItem>
)}
<div className="pb-1"><NavMinigames /></div>
<div className="pb-1"><NavMinigames games={minigameNav} /></div>
</SidebarMenu>
</SidebarContent>
<SidebarFooter>

View file

@ -1,8 +1,10 @@
"use client";
import { Bird, Bomb, ChevronRight, Club, Crosshair, FileTextIcon, Gamepad2, Radio, Spade } from "lucide-react";
import { ChevronRight, Gamepad2 } from "lucide-react";
import Link from "next/link";
import { minigameIcon } from "@/components/frontend/minigames/minigameIcon";
import type { RegistryGame } from "@/lib/minigames/registry";
import {
DropdownMenu,
DropdownMenuContent,
@ -18,22 +20,18 @@ import {
useSidebar,
} from "@/components/ui/sidebar";
const coreGames = [
{ title: "Flight Simulator", url: "/minigames/flappy", icon: Bird },
{ title: "Minefield Clearance", url: "/minigames/eod", icon: Bomb },
{ title: "Radio Traffic", url: "/minigames/radio", icon: Radio },
{ title: "Qualification Course", url: "/minigames/qualification", icon: Crosshair },
{ title: "OPORD Recall", url: "/minigames/opord", icon: FileTextIcon },
];
const cardtableGames = [
{ title: "Poker", url: "/minigames/poker", icon: Spade },
{ title: "Blackjack", url: "/minigames/blackjack", icon: Club },
];
export function NavMinigames() {
/**
* Minigames sidebar dropdown. The groups and entries come from the minigames
* registry (resolved on the server and passed in), so retiring a game or
* reordering the list is an admin-data change, not a code change.
*/
export function NavMinigames({ games }: { games: RegistryGame[] }) {
const { isMobile } = useSidebar();
const visible = games.filter((game) => game.status !== "retired");
const coreGames = visible.filter((game) => game.category === "core");
const cardtableGames = visible.filter((game) => game.category === "cardtable");
return (
<SidebarMenuItem>
<DropdownMenu>
@ -52,14 +50,17 @@ export function NavMinigames() {
>
<DropdownMenuGroup>
<DropdownMenuLabel>Core</DropdownMenuLabel>
{coreGames.map((game) => (
<DropdownMenuItem key={game.url} asChild>
<Link href={game.url}>
<game.icon />
{game.title}
</Link>
</DropdownMenuItem>
))}
{coreGames.map((game) => {
const Icon = minigameIcon(game.icon);
return (
<DropdownMenuItem key={game.key} asChild>
<Link href={game.route}>
<Icon />
{game.label}
</Link>
</DropdownMenuItem>
);
})}
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
@ -67,14 +68,17 @@ export function NavMinigames() {
<span>Cardtable</span>
<span className="text-xs font-normal text-muted-foreground">Earn chips to spend by playing Core minigames!</span>
</DropdownMenuLabel>
{cardtableGames.map((game) => (
<DropdownMenuItem key={game.url} asChild>
<Link href={game.url}>
<game.icon />
{game.title}
</Link>
</DropdownMenuItem>
))}
{cardtableGames.map((game) => {
const Icon = minigameIcon(game.icon);
return (
<DropdownMenuItem key={game.key} asChild>
<Link href={game.route}>
<Icon />
{game.label}
</Link>
</DropdownMenuItem>
);
})}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>

View file

@ -0,0 +1,34 @@
import {
Bird,
Bomb,
Club,
Crosshair,
FileTextIcon,
Gamepad2,
Radio,
Spade,
type LucideIcon,
} from "lucide-react";
import { MINIGAME_ICON_FALLBACK } from "@/lib/minigames/registry";
/**
* Maps a registry row's `icon` name (a string the admin can edit) to a lucide
* component. Unknown or missing names fall back to a generic gamepad so a bad
* value never crashes a render.
*/
const ICONS: Record<string, LucideIcon> = {
Bird,
Bomb,
Radio,
Crosshair,
FileTextIcon,
Spade,
Club,
Gamepad2,
};
export function minigameIcon(name: string | null | undefined): LucideIcon {
if (!name) return ICONS[MINIGAME_ICON_FALLBACK] ?? Gamepad2;
return ICONS[name] ?? ICONS[MINIGAME_ICON_FALLBACK] ?? Gamepad2;
}

View file

@ -0,0 +1,60 @@
import type { Payload } from "payload";
import {
BUILTIN_MINIGAMES,
type BuiltinMinigame,
type MinigameCategory,
type MinigameStatus,
} from "./registry";
/**
* Server-side registry loader.
*
* The `minigames` collection is the source of truth (admins can add, retire or
* reorder games), but this falls back to `BUILTIN_MINIGAMES` when the table is
* empty or the read fails, so the nav and boards never render blank (a fresh
* test database, for instance, has the schema without the seeded rows).
*
* Not client-safe: imports the Payload type. Client components take the
* resolved list as a prop and use `RegistryGame` from the pure `registry.ts`.
*/
export async function loadMinigameRegistry(payload: Payload): Promise<BuiltinMinigame[]> {
try {
const res = await payload.find({
collection: "minigames",
limit: 200,
depth: 0,
sort: "order",
overrideAccess: true,
});
const rows = res.docs.map(
(doc): BuiltinMinigame => ({
key: doc.key,
label: doc.label,
description: doc.description ?? "",
route: doc.route,
icon: doc.icon || "Gamepad2",
category: (doc.category ?? "core") as MinigameCategory,
status: (doc.status ?? "active") as MinigameStatus,
order: typeof doc.order === "number" ? doc.order : 0,
countsForPeriods: Boolean(doc.countsForPeriods),
scoreLabel: doc.scoreLabel || "Score",
}),
);
if (rows.length > 0) return rows;
} catch {
// Fall through to the built-in list below.
}
return [...BUILTIN_MINIGAMES];
}
/** Games visible in the nav: everything not retired, in registry order. */
export function visibleRegistryGames(games: BuiltinMinigame[]): BuiltinMinigame[] {
return games.filter((game) => game.status !== "retired");
}
/** Registry keys whose ledger entries feed anchored period boards. */
export function periodScoringGameKeys(games: BuiltinMinigame[]): string[] {
return games
.filter((game) => game.category === "core" && game.countsForPeriods)
.map((game) => game.key);
}

View file

@ -1,5 +1,6 @@
import type { Payload, Where } 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";
@ -31,7 +32,15 @@ import { resolveMinigameRules, type ResolvedMinigameRules } from "./rules";
type PayloadType = Payload;
const PERIOD_GAMES: string[] = [...CORE_MINIGAME_KEYS];
/**
* Games whose entries feed period boards, from the registry (core games with
* `countsForPeriods`). Falls back to the built-in Core five when the registry
* is empty or unreadable so scoring never silently stops.
*/
const resolvePeriodGames = async (payload: PayloadType): Promise<string[]> => {
const keys = periodScoringGameKeys(await loadMinigameRegistry(payload));
return keys.length > 0 ? keys : [...CORE_MINIGAME_KEYS];
};
export interface ClosedPeriodSummary {
periodId: number;
@ -100,10 +109,11 @@ const fetchEntries = async (payload: PayloadType, where: Where) => {
const pointsForPeriod = (
entries: LedgerEntry[],
games: string[],
rules: ResolvedMinigameRules,
): Map<number, number> =>
totalPointsByUser(
PERIOD_GAMES.map((game) =>
games.map((game) =>
buildGameBoard(
entries.filter((entry) => entry.game === game),
rules.placementLadderTopN,
@ -120,6 +130,7 @@ const previousPointsFor = async (
payload: PayloadType,
rules: ResolvedMinigameRules,
periodStartMs: number,
games: string[],
): Promise<Map<number, number> | null> => {
if (!rules.anchorDate) return null;
const derived = derivePeriodForInstant(
@ -145,7 +156,7 @@ const previousPointsFor = async (
// 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 } });
return pointsForPeriod(entries, rules);
return pointsForPeriod(entries, games, rules);
};
/** Insert one achievement unless its `type:windowStart:user` key already exists. */
@ -204,6 +215,7 @@ export async function closePeriodById(
payload: PayloadType,
periodId: number,
now: Date = new Date(),
games?: string[],
): Promise<ClosedPeriodSummary | null> {
const period = await payload
.findByID({ collection: "minigame-periods", id: periodId, depth: 0, overrideAccess: true })
@ -211,16 +223,18 @@ export async function closePeriodById(
if (!period || period.status !== "open") return null;
const rules = await resolveMinigameRules(payload);
const periodGames = games ?? (await resolvePeriodGames(payload));
const entries = await fetchEntries(payload, { period: { equals: periodId } });
const previousPointsByUser = await previousPointsFor(
payload,
rules,
new Date(period.startDate).getTime(),
periodGames,
);
const awards = computePeriodAwards({
entries,
games: PERIOD_GAMES,
games: periodGames,
topN: rules.placementLadderTopN,
precisionMinAttempts: rules.precisionMinAttempts,
previousPointsByUser,
@ -270,9 +284,12 @@ export async function closeCalendarWindows(
payload: PayloadType,
rules: ResolvedMinigameRules,
now: Date = new Date(),
games?: string[],
): Promise<CalendarCloseSummary[]> {
if (!rules.enabled || !rules.anchorDate) return [];
const periodGames = games ?? (await resolvePeriodGames(payload));
const plans: Array<{
unit: "month" | "year";
type: MinigameAchievementType;
@ -308,7 +325,7 @@ export async function closeCalendarWindows(
});
const champion = computeWindowChampion({
entries,
games: PERIOD_GAMES,
games: periodGames,
topN: rules.placementLadderTopN,
});
if (!champion) continue;
@ -360,13 +377,15 @@ export async function closeDuePeriods(
overrideAccess: true,
});
const games = await resolvePeriodGames(payload);
const closed: ClosedPeriodSummary[] = [];
for (const period of due.docs) {
const summary = await closePeriodById(payload, period.id, now);
const summary = await closePeriodById(payload, period.id, now, games);
if (summary) closed.push(summary);
}
const calendar = await closeCalendarWindows(payload, rules, now);
const calendar = await closeCalendarWindows(payload, rules, now, games);
const createdPeriodId = await ensurePeriodForInstant(payload, rules, now);
return { createdPeriodId, closed, calendar };

View file

@ -135,7 +135,6 @@ export const BUILTIN_MINIGAMES: BuiltinMinigame[] = [
/** Anchor for Period 1: the Monday 00:00 UTC the feature goes live. */
export const MINIGAME_ANCHOR_DATE = "2026-10-12T00:00:00.000Z";
export const PERIOD_LENGTH_DAYS_DEFAULT = 14;
export const PLACEMENT_LADDER_TOP_N_DEFAULT = 10;
export const PRECISION_MIN_ATTEMPTS_DEFAULT = 5;
@ -163,3 +162,13 @@ export const MINIGAME_RULE_DEFAULTS = {
placementLadderTopN: PLACEMENT_LADDER_TOP_N_DEFAULT,
precisionMinAttempts: PRECISION_MIN_ATTEMPTS_DEFAULT,
} as const;
/**
* A registry row as the client sees it. Same shape as a built-in so the nav and
* leaderboards render identically whether the data came from the DB or from the
* built-in fallback (`src/lib/minigames/loadRegistry.ts`).
*/
export type RegistryGame = BuiltinMinigame;
/** Icon name used when a registry row's `icon` is missing or unknown. */
export const MINIGAME_ICON_FALLBACK = "Gamepad2";

View file

@ -135,7 +135,12 @@ describe("Minigame month/year achievements", () => {
});
async function clearMinigameData() {
for (const collection of ["achievements", "minigame-entries", "minigame-periods"] as const) {
for (const collection of [
"achievements",
"minigame-entries",
"minigame-periods",
"minigames",
] as const) {
await payload.delete({ collection, where: { id: { greater_than: 0 } }, overrideAccess: true });
}
}

View file

@ -21,7 +21,12 @@ const entryPeriodId = (entry: { period?: unknown }): number | null => {
/** Wipe the minigame feature tables so this file never sees another file's rows. */
async function clearMinigameData(): Promise<void> {
for (const collection of ["achievements", "minigame-entries", "minigame-periods"] as const) {
for (const collection of [
"achievements",
"minigame-entries",
"minigame-periods",
"minigames",
] as const) {
await payload.delete({
collection,
where: { id: { greater_than: 0 } },

View file

@ -223,7 +223,12 @@ describe("Minigame period close pipeline", () => {
});
async function clearMinigameData() {
for (const collection of ["achievements", "minigame-entries", "minigame-periods"] as const) {
for (const collection of [
"achievements",
"minigame-entries",
"minigame-periods",
"minigames",
] as const) {
await payload.delete({
collection,
where: { id: { greater_than: 0 } },

View file

@ -0,0 +1,157 @@
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 { BUILTIN_MINIGAMES } from "@/lib/minigames/registry";
import {
loadMinigameRegistry,
periodScoringGameKeys,
visibleRegistryGames,
} from "@/lib/minigames/loadRegistry";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
import { closeDuePeriods } from "@/lib/minigames/periods/lifecycle";
const ANCHOR = "2026-06-01T00:00:00.000Z";
const RUN = `mgr-${Date.now().toString(36)}`;
let payload: Payload;
let userA: number;
let originalRules: Record<string, unknown> | null = null;
describe("Minigame registry", () => {
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<string, unknown> | null;
await payload.updateGlobal({
slug: "minigame-rules",
data: {
enabled: true,
anchorDate: ANCHOR,
periodLengthDays: 14,
placementLadderTopN: 10,
precisionMinAttempts: 1,
},
overrideAccess: true,
});
userA = (
(await payload.create({
collection: "users",
data: {
username: `${RUN}-a`,
discordUsername: `${RUN}-a`,
displayName: "MG A",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User
).id;
});
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("falls back to the built-in seven when the registry is empty", async () => {
const games = await loadMinigameRegistry(payload);
expect(games).toHaveLength(BUILTIN_MINIGAMES.length);
expect(games.map((game) => game.key)).toEqual(BUILTIN_MINIGAMES.map((game) => game.key));
});
it("orders by registry order and hides retired games from the nav", async () => {
await createGame({ key: "zeta", label: "Zeta", category: "core", status: "retired", order: 1 });
await createGame({ key: "alpha", label: "Alpha", category: "cardtable", status: "active", order: 2 });
const games = await loadMinigameRegistry(payload);
expect(games.map((game) => game.key)).toEqual(["zeta", "alpha"]);
expect(visibleRegistryGames(games).map((game) => game.key)).toEqual(["alpha"]);
// Neither counts for periods (both default countsForPeriods false).
expect(periodScoringGameKeys(games)).toEqual([]);
});
it("excludes a non-scoring game from period boards", async () => {
await clearMinigameData();
await createGame({ key: "flappy", label: "Flight Simulator", category: "core", status: "active", order: 1, countsForPeriods: true });
await createGame({ key: "eod", label: "Minefield Clearance", category: "core", status: "active", order: 2, countsForPeriods: false });
expect(periodScoringGameKeys(await loadMinigameRegistry(payload))).toEqual(["flappy"]);
const when = new Date("2026-06-05T12:00:00.000Z");
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 10, durationMs: 1_000, now: when });
await recordMinigameEntry({ payload, userId: userA, game: "eod", score: 5, durationMs: 1_000, now: when });
const summary = await closeDuePeriods(payload, new Date("2026-06-16T00:00:00.000Z"));
expect(summary.closed).toHaveLength(1);
const achievements = await payload.find({
collection: "achievements",
where: { type: { equals: "period-champion" } },
limit: 1,
depth: 0,
overrideAccess: true,
});
// Only the flappy board scored, so the champion has its 10 ladder points;
// had the non-scoring EOD board counted, this would be 20.
expect(achievements.docs[0]?.value).toBe(10);
});
async function createGame(data: {
key: string;
label: string;
category: "core" | "cardtable";
status: "active" | "retired" | "upcoming";
order: number;
countsForPeriods?: boolean;
}) {
await payload.create({
collection: "minigames",
data: {
...data,
route: `/minigames/${data.key}`,
icon: "Gamepad2",
scoreLabel: "Score",
description: "",
},
overrideAccess: true,
depth: 0,
});
}
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 });
}
}
});