feat(minigames): add period leaderboards, all-time view and achievements
Phase 5 of the minigame periods feature: - Read model (lib/minigames/periods/standings.ts) that shapes period boards from the ledger (rank, placement points, names) and All-Time boards from the untouched profile aggregates into one row type. - GET /api/minigames/leaderboards: ?period=current|<id>|all-time, returning the period, the period list, the boards and the achievements honor roll. - New /minigames/leaderboards page: period selector (current, every past period, All-Time), per-game tabs, and the achievements honor roll. Core-only in period mode; every registered game in All-Time. - Shared client pieces: useLeaderboards hook, StandingsTable, PeriodStandingsCard (period by default, All-Time toggle) and AchievementsHonorRoll. - Each Core game page gains an "Anchored period standings" card so the period board is visible on the game itself; its existing all-time board and mode/difficulty selectors are untouched, and it links to the full page. (Plan said replace the inline board; keeping it preserves the per-mode selectors, so the period board is added instead. Easy to swap if you prefer.) - Ledger fetch helper extracted to lib/minigames/periods/ledger.ts. - Integration test for the period boards, the All-Time path and the honor roll.
This commit is contained in:
parent
deb88ded56
commit
316797d27d
20 changed files with 1136 additions and 66 deletions
|
|
@ -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() {
|
|||
</div>
|
||||
|
||||
<EodArena initialStats={stats} currentUserId={user.id as number} />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground">Anchored period standings</h2>
|
||||
<PeriodStandingsCard gameKey="eod" icon="Bomb" currentUserId={user.id as number} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
</div>
|
||||
|
||||
<FlappyArena initialStats={stats} currentUserId={user.id as number} />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground">Anchored period standings</h2>
|
||||
<PeriodStandingsCard gameKey="flappy" icon="Bird" currentUserId={user.id as number} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
37
src/app/(frontend)/minigames/leaderboards/page.tsx
Normal file
37
src/app/(frontend)/minigames/leaderboards/page.tsx
Normal file
|
|
@ -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 (
|
||||
<div className="flex flex-col gap-6 p-5">
|
||||
<MinigameLeaderboards games={games} currentUserId={user.id as number} initialGame={game} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -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() {
|
|||
</div>
|
||||
|
||||
<OpordArena initialStats={stats} currentUserId={user.id as number} />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground">Anchored period standings</h2>
|
||||
<PeriodStandingsCard gameKey="opord" icon="FileTextIcon" currentUserId={user.id as number} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
</div>
|
||||
|
||||
<AimTrainerArena initialStats={stats} currentUserId={user.id} />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground">Anchored period standings</h2>
|
||||
<PeriodStandingsCard gameKey="qualification" icon="Crosshair" currentUserId={user.id as number} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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() {
|
|||
</div>
|
||||
|
||||
<RadioArena initialStats={stats} currentUserId={user.id as number} />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground">Anchored period standings</h2>
|
||||
<PeriodStandingsCard gameKey="radio" icon="Radio" currentUserId={user.id as number} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
44
src/app/api/minigames/leaderboards/route.ts
Normal file
44
src/app/api/minigames/leaderboards/route.ts
Normal file
|
|
@ -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|<id>|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 });
|
||||
}
|
||||
}
|
||||
|
|
@ -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<string, string> = {
|
||||
"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<string, string> = {
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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[] }) {
|
|||
);
|
||||
})}
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/minigames/leaderboards">
|
||||
<Trophy />
|
||||
Leaderboards
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
|
|
|
|||
46
src/components/frontend/minigames/AchievementsHonorRoll.tsx
Normal file
46
src/components/frontend/minigames/AchievementsHonorRoll.tsx
Normal file
|
|
@ -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 (
|
||||
<p className="px-4 py-4 text-sm text-muted-foreground">
|
||||
No achievements yet. The first period close will crown its champions.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-border">
|
||||
{achievements.map((achievement) => (
|
||||
<div key={achievement.id} className="flex items-start gap-3 px-4 py-3">
|
||||
<Award className="mt-0.5 size-4 shrink-0 text-amber-400" />
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm">
|
||||
<span className="font-semibold">{achievement.typeLabel}</span>
|
||||
<span className="text-muted-foreground"> to </span>
|
||||
<span className="font-medium">{achievement.userName}</span>
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{achievement.detail ?? `${achievement.value}`} · {achievement.windowLabel} starting{" "}
|
||||
{formatWindowStart(achievement.windowStart)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
138
src/components/frontend/minigames/MinigameLeaderboards.tsx
Normal file
138
src/components/frontend/minigames/MinigameLeaderboards.tsx
Normal file
|
|
@ -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 (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Trophy className="size-5 text-amber-400" />
|
||||
<h1 className="text-lg font-semibold">Minigame Leaderboards</h1>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Placement points run across the five Core games each period. Periods reset, history stays.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Select value={periodRef} onValueChange={setPeriodRef}>
|
||||
<SelectTrigger className="w-full sm:w-72">
|
||||
<SelectValue placeholder="Select a period" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{periodOptions.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{data?.period && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{data.period.startDate.slice(0, 10)} to {data.period.endDate.slice(0, 10)} (UTC)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="w-full rounded-xl border border-border bg-card">
|
||||
{failed ? (
|
||||
<p className="px-4 py-6 text-sm text-muted-foreground">Could not load the leaderboards.</p>
|
||||
) : loading && !data ? (
|
||||
<div className="space-y-2 px-4 py-6">
|
||||
<div className="h-4 w-1/2 animate-pulse rounded bg-border" />
|
||||
<div className="h-4 w-3/4 animate-pulse rounded bg-border" />
|
||||
</div>
|
||||
) : boards.length === 0 ? (
|
||||
<p className="px-4 py-6 text-sm text-muted-foreground">No games to show yet.</p>
|
||||
) : (
|
||||
<Tabs value={activeBoard?.key ?? gameKey} onValueChange={setGameKey} className="gap-0">
|
||||
<TabsList className="flex w-full flex-wrap justify-start rounded-b-none bg-transparent p-2">
|
||||
{boards.map((board) => {
|
||||
const Icon = minigameIcon(board.icon);
|
||||
return (
|
||||
<TabsTrigger key={board.key} value={board.key} className="gap-1.5">
|
||||
<Icon className="size-3.5" />
|
||||
{board.label}
|
||||
</TabsTrigger>
|
||||
);
|
||||
})}
|
||||
</TabsList>
|
||||
{boards.map((board) => (
|
||||
<TabsContent key={board.key} value={board.key} className="mt-0">
|
||||
<div className={cn("flex items-center justify-between px-4 py-2 text-xs text-muted-foreground")}>
|
||||
<span>
|
||||
{isAllTime ? "All-Time best per operator" : "Best run this period, with placement points"}
|
||||
</span>
|
||||
<span>{board.scoreLabel} · top 10</span>
|
||||
</div>
|
||||
<StandingsTable
|
||||
rows={board.rows}
|
||||
scoreLabel={board.scoreLabel}
|
||||
currentUserId={currentUserId}
|
||||
showPoints={!isAllTime}
|
||||
emptyLabel={isAllTime ? "No all-time runs yet." : "No runs this period yet. Be the first!"}
|
||||
/>
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="w-full rounded-xl border border-border bg-card">
|
||||
<div className="flex items-center gap-2 border-b border-border px-4 py-3">
|
||||
<Trophy className="size-4 text-muted-foreground" />
|
||||
<h2 className="text-sm font-semibold">Achievements</h2>
|
||||
<span className="ml-auto text-xs text-muted-foreground">Latest first</span>
|
||||
</div>
|
||||
<AchievementsHonorRoll achievements={data?.achievements ?? []} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
115
src/components/frontend/minigames/PeriodStandingsCard.tsx
Normal file
115
src/components/frontend/minigames/PeriodStandingsCard.tsx
Normal file
|
|
@ -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 (
|
||||
<div className={cn("w-full max-w-[420px] rounded-xl border border-border bg-card", className)}>
|
||||
<div className="flex items-center gap-2 border-b border-border px-4 py-3">
|
||||
<Trophy className="size-4 text-amber-400" />
|
||||
<Icon className="size-4 text-muted-foreground" />
|
||||
<h2 className="truncate text-sm font-semibold">{board?.label ?? "Standings"}</h2>
|
||||
<span className="ml-auto shrink-0 text-xs text-muted-foreground">
|
||||
{isAllTime ? "All-Time" : (data?.period?.label ?? "No active period")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 border-b border-border px-2 py-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setView("period")}
|
||||
className={cn(
|
||||
"rounded-md px-2.5 py-1 text-xs font-medium",
|
||||
!isAllTime ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
This period
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setView("all-time")}
|
||||
className={cn(
|
||||
"rounded-md px-2.5 py-1 text-xs font-medium",
|
||||
isAllTime ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
All-Time
|
||||
</button>
|
||||
<Link
|
||||
href={`/minigames/leaderboards?game=${gameKey}`}
|
||||
className="ml-auto pr-1 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
All boards
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{presence && !isAllTime && (
|
||||
<div className="border-b border-border px-4 py-2 text-xs text-muted-foreground" aria-live="polite">
|
||||
<span className="font-medium text-emerald-400">{presence.participants.length}</span>{" "}
|
||||
{presence.participants.length === 1 ? `${presence.noun ?? "operator"} is` : `${presence.noun ?? "operators"} are`} active now
|
||||
{presence.participants.length > 0 && (
|
||||
<span className="ml-1 text-foreground">
|
||||
({presence.participants.map((participant) => participant.name).join(", ")})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{failed ? (
|
||||
<p className="px-4 py-4 text-sm text-muted-foreground">Could not load the standings.</p>
|
||||
) : loading && !data ? (
|
||||
<div className="space-y-2 px-4 py-4">
|
||||
<div className="h-4 w-full animate-pulse rounded bg-border" />
|
||||
<div className="h-4 w-3/4 animate-pulse rounded bg-border" />
|
||||
<div className="h-4 w-1/2 animate-pulse rounded bg-border" />
|
||||
</div>
|
||||
) : (
|
||||
<StandingsTable
|
||||
rows={board?.rows ?? []}
|
||||
scoreLabel={board?.scoreLabel ?? "Score"}
|
||||
currentUserId={currentUserId}
|
||||
showPoints={!isAllTime}
|
||||
emptyLabel={isAllTime ? "No all-time runs yet." : "No runs this period yet. Be the first!"}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
78
src/components/frontend/minigames/StandingsTable.tsx
Normal file
78
src/components/frontend/minigames/StandingsTable.tsx
Normal file
|
|
@ -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 (
|
||||
<p className={cn("px-4 py-4 text-sm text-muted-foreground", className)}>{emptyLabel}</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<table className={cn("w-full text-sm", className)}>
|
||||
<thead>
|
||||
<tr className="text-left text-xs uppercase tracking-wider text-muted-foreground">
|
||||
<th className="px-4 py-2 font-medium">#</th>
|
||||
<th className="px-2 py-2 font-medium">Operator</th>
|
||||
<th className="px-2 py-2 text-right font-medium">{scoreLabel}</th>
|
||||
<th className="px-2 py-2 text-right font-medium">Runs</th>
|
||||
{showPoints && <th className="px-4 py-2 text-right font-medium">Points</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border">
|
||||
{rows.map((row) => {
|
||||
const isCurrent = row.userId != null && String(row.userId) === String(currentUserId);
|
||||
return (
|
||||
<tr key={`${row.userId ?? "anon"}-${row.rank}`} className={cn(isCurrent && "bg-accent/40")}>
|
||||
<td className="px-4 py-2">
|
||||
<span className={rankClass(row.rank - 1)}>{row.rank}</span>
|
||||
</td>
|
||||
<td className="px-2 py-2 font-medium">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="max-w-[200px] truncate">{row.name}</span>
|
||||
{isCurrent && <span className="shrink-0 text-xs text-muted-foreground">(you)</span>}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-2 py-2 text-right font-semibold tabular-nums">{row.bestScore}</td>
|
||||
<td className="px-2 py-2 text-right tabular-nums text-muted-foreground">{row.attempts}</td>
|
||||
{showPoints && (
|
||||
<td className="px-4 py-2 text-right tabular-nums text-muted-foreground">{row.points}</td>
|
||||
)}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
46
src/components/frontend/minigames/useLeaderboards.ts
Normal file
46
src/components/frontend/minigames/useLeaderboards.ts
Normal file
|
|
@ -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<LeaderboardPayload | null>(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<LeaderboardPayload>;
|
||||
})
|
||||
.then((json) => {
|
||||
if (!cancelled) {
|
||||
setData(json);
|
||||
setLoading(false);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
setFailed(true);
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [periodRef, refreshKey]);
|
||||
|
||||
return { data, failed, loading };
|
||||
}
|
||||
55
src/lib/minigames/leaderboardTypes.ts
Normal file
55
src/lib/minigames/leaderboardTypes.ts
Normal file
|
|
@ -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[];
|
||||
}
|
||||
48
src/lib/minigames/periods/ledger.ts
Normal file
48
src/lib/minigames/periods/ledger.ts
Normal file
|
|
@ -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<LedgerEntry[]> {
|
||||
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;
|
||||
}
|
||||
|
|
@ -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 } },
|
||||
|
|
|
|||
283
src/lib/minigames/periods/standings.ts
Normal file
283
src/lib/minigames/periods/standings.ts
Normal file
|
|
@ -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<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";
|
||||
|
||||
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 };
|
||||
|
|
@ -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<MinigameAchievementType, string> = {
|
||||
"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<MinigameAchievementWindow, string> = {
|
||||
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<string, string> = {
|
||||
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,
|
||||
|
|
|
|||
162
tests/int/minigame-standings.int.spec.ts
Normal file
162
tests/int/minigame-standings.int.spec.ts
Normal file
|
|
@ -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<string, unknown> | 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<string, unknown> | 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 });
|
||||
}
|
||||
}
|
||||
});
|
||||
Loading…
Reference in a new issue