1
0
Fork 0

Compare commits

..

No commits in common. "bf50dd99a90c000643db71b71c08ff910f13dd2d" and "0c00726759a1fa0b885a9fb352746d514deb2226" have entirely different histories.

72 changed files with 42 additions and 86464 deletions

View file

@ -1,21 +1,5 @@
# Changelog
# v0.8.8
The minigames get anchored periods, close-time achievements, a public leaderboards hub and a game registry.
### Features
- **Minigame periods and achievements.** The five Core minigames (Flight Simulator, Minefield Clearance, Radio Traffic, Qualification Course, OPORD Recall) now play in anchored 14-day periods. Every completed run is recorded, each period crowns a Period Champion plus Diligence, Dedication, Precision and Most Improved, and completed calendar months and years crown a Player of the Month and a Player of the Year. Winners get an in-app notification and a Discord announcement.
- **Minigame leaderboards hub.** A new Minigames leaderboards page collects the current period standings, every past period, an All-Time tab that reads the existing profile bests, and a public achievements honor roll. Each game page also shows its current period standings.
- **Minigame registry.** Games are now registered data: admins can add, reorder or retire a game without a code change, and a retired game leaves the sidebar while its history stays.
- **Admin period control.** A close/reopen control on the Minigames periods admin page lets staff close a period early or reopen a closed one.
---
# v0.8.7
### Fixes

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.8.8",
"version": "0.8.7",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -36,8 +36,6 @@ 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,
@ -93,10 +91,8 @@ 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,
@ -191,7 +187,6 @@ 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

@ -6,7 +6,6 @@ import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { broadcastToUser } from "@/lib/realtime/bus";
import { chipsForXp } from "@/lib/minigames/chips";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
interface ActionResult<T = undefined> {
success: boolean;
@ -231,18 +230,6 @@ export async function submitEodResult(input: {
});
}
if (input.won) {
await recordMinigameEntry({
payload,
userId: Number(user.id),
game: "eod",
score,
durationMs: input.seconds * 1000,
mode: difficulty,
meta: { flags: input.flags, seconds: input.seconds },
});
}
return {
success: true,
data: {

View file

@ -5,7 +5,6 @@ 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)",
@ -61,11 +60,6 @@ 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>
);
}

View file

@ -6,7 +6,6 @@ import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { broadcastToUser } from "@/lib/realtime/bus";
import { chipsForXp } from "@/lib/minigames/chips";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
interface ActionResult<T = undefined> {
success: boolean;
@ -24,8 +23,6 @@ export interface FlappyStats {
const PASSES_PER_XP = 15;
const MAX_PASSES_PER_GAME = 5000;
// A maximal run (5000 passes) is a few hours at most; reject absurd durations.
const MAX_FLAPPY_DURATION_MS = 6 * 60 * 60 * 1000;
async function authenticate() {
const payloadConfig = await config;
@ -46,7 +43,6 @@ async function authenticate() {
export async function submitFlappyScore(input: {
passes: number;
durationMs: number;
}): Promise<ActionResult<FlappyStats>> {
try {
const { payload, user } = await authenticate();
@ -58,14 +54,6 @@ export async function submitFlappyScore(input: {
if (passes > MAX_PASSES_PER_GAME) {
return { success: false, error: "Score too large." };
}
if (
typeof input.durationMs !== "number" ||
!Number.isFinite(input.durationMs) ||
input.durationMs <= 0 ||
input.durationMs > MAX_FLAPPY_DURATION_MS
) {
return { success: false, error: "Invalid run duration." };
}
const profileRes = await payload.find({
collection: "profiles",
@ -133,14 +121,6 @@ export async function submitFlappyScore(input: {
targetId: user.id as number,
data: { passes, xpEarned: runXp, bestScore, totalPasses, flappyXp },
});
await recordMinigameEntry({
payload,
userId: Number(user.id),
game: "flappy",
score: passes,
durationMs: input.durationMs,
meta: { xpEarned: runXp },
});
}
return {

View file

@ -5,7 +5,6 @@ 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",
@ -59,11 +58,6 @@ 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>
);
}

View file

@ -1,37 +0,0 @@
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>
);
}

View file

@ -17,7 +17,6 @@ import {
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { broadcastToUser } from "@/lib/realtime/bus";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
interface ActionResult<T = undefined> {
success: boolean;
@ -215,17 +214,6 @@ export async function submitOpordRecallResult(
});
}
await recordMinigameEntry({
payload,
userId: Number(user.id),
game: "opord",
score,
accuracy,
durationMs: Math.round(timeMs),
mode: input.difficulty,
meta: { correct, total: tier.questionCount },
});
return {
success: true,
data: {

View file

@ -5,7 +5,6 @@ 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)",
@ -62,11 +61,6 @@ 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>
);
}

View file

@ -6,13 +6,11 @@ import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { broadcastToUser } from "@/lib/realtime/bus";
import { chipsForXp } from "@/lib/minigames/chips";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
import {
isAimTrainerDifficulty,
calculateAimTrainerAccuracy,
calculateAimTrainerScore,
calculateAimTrainerXp,
COURSE_DURATION_MS,
MAX_SHOTS_FIRED,
MAX_HITS,
MAX_DESPAWNED_TARGETS,
@ -47,13 +45,8 @@ export interface AimTrainerResultInput {
civilianHits: number;
shotsFired: number;
despawnedUnhitTargets: number;
/** Wall-clock run duration reported by the client; the course is 30s long. */
durationMs?: number;
}
// Allow for a backgrounded tab throttling rAF past the nominal course length.
const AIM_DURATION_GRACE_MS = 60_000;
async function authenticate() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
@ -113,22 +106,6 @@ export async function submitAimTrainerResult(
return { success: false, error: "Too many despawned targets." };
}
const reportedDuration = input.durationMs;
if (
reportedDuration != null &&
(!Number.isFinite(reportedDuration) ||
reportedDuration < 0 ||
reportedDuration > COURSE_DURATION_MS + AIM_DURATION_GRACE_MS)
) {
return { success: false, error: "Invalid result." };
}
const runDurationMs = Math.min(
typeof reportedDuration === "number" && reportedDuration > 0
? Math.round(reportedDuration)
: COURSE_DURATION_MS,
COURSE_DURATION_MS,
);
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
@ -254,17 +231,6 @@ export async function submitAimTrainerResult(
});
}
await recordMinigameEntry({
payload,
userId: Number(user.id),
game: "qualification",
score,
accuracy,
durationMs: runDurationMs,
mode: input.difficulty,
meta: { civilianHits },
});
return {
success: true,
data: {
@ -281,7 +247,8 @@ export async function submitAimTrainerResult(
score,
accuracy,
},
}; } catch (error) {
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };

View file

@ -7,7 +7,6 @@ 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",
@ -66,11 +65,6 @@ 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>
);
}

View file

@ -6,7 +6,6 @@ import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { broadcastToUser } from "@/lib/realtime/bus";
import { chipsForXp } from "@/lib/minigames/chips";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
interface ActionResult<T = undefined> {
success: boolean;
@ -39,9 +38,6 @@ const SPRINT_MESSAGE_COUNT = 10;
const MAX_WATCH_MESSAGES = 30;
const MAX_SCORE_PER_GAME = 5000;
const MAX_SPRINT_TIME_MS = 600_000;
// Watch rounds run against a 60s clock; allow generous grace for throttled tabs.
const MAX_WATCH_TIME_MS = 120_000;
const WATCH_DURATION_FALLBACK_MS = 60_000;
type RadioMode = "sprint" | "watch";
@ -116,19 +112,6 @@ export async function submitRadioResult(input: {
) {
return { success: false, error: "Invalid result." };
}
if (
input.mode === "watch" &&
sprintTime != null &&
(typeof sprintTime !== "number" || !Number.isFinite(sprintTime) || sprintTime < 0 || sprintTime > MAX_WATCH_TIME_MS)
) {
return { success: false, error: "Invalid result." };
}
const runDurationMs =
input.mode === "sprint"
? Math.round(sprintTime as number)
: typeof sprintTime === "number" && Number.isFinite(sprintTime) && sprintTime > 0
? Math.round(sprintTime)
: WATCH_DURATION_FALLBACK_MS;
const profileRes = await payload.find({
collection: "profiles",
@ -270,22 +253,6 @@ export async function submitRadioResult(input: {
});
}
if (input.correctMessages >= 1) {
await recordMinigameEntry({
payload,
userId: Number(user.id),
game: "radio",
score,
accuracy: input.accuracy,
durationMs: runDurationMs,
mode: input.mode,
meta: {
messageCount: input.messageCount,
correctMessages: input.correctMessages,
},
});
}
return {
success: true,
data: {

View file

@ -5,7 +5,6 @@ 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)",
@ -70,11 +69,6 @@ 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>
);
}

View file

@ -35,7 +35,6 @@ import { default as default_0edde40a6ccd30c893b1227360f69360 } from '@/component
import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/components/static/WarningMessage'
import { AudioPreviewField as AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2 } from '@/components/admin/voiceover/AudioPreviewField'
import { default as default_7fa52484aec46e988e9cfb5e86c0c759 } from '@/components/admin/narrative-flow/NarrativeFlowEditor'
import { default as default_b7f86fb8e028bca592f57e6d387a0380 } from '@/components/admin/minigames/PeriodCloseControl'
import { SelectField as SelectField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { PromptEditorField as PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { default as default_b16af798585cda7cfed92f7b1dd0c707 } from '@/components/admin/shims/ShimContentField'
@ -88,7 +87,6 @@ export const importMap = {
"@/components/static/WarningMessage#default": default_2d468cc5cf0b647ffca3201592c20825,
"@/components/admin/voiceover/AudioPreviewField#AudioPreviewField": AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2,
"@/components/admin/narrative-flow/NarrativeFlowEditor#default": default_7fa52484aec46e988e9cfb5e86c0c759,
"@/components/admin/minigames/PeriodCloseControl#default": default_b7f86fb8e028bca592f57e6d387a0380,
"@ai-stack/payloadcms/client#SelectField": SelectField_4490b89d4413c1ffaecdacfe72efaf73,
"@ai-stack/payloadcms/client#PromptEditorField": PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73,
"@/components/admin/shims/ShimContentField#default": default_b16af798585cda7cfed92f7b1dd0c707,

View file

@ -1,73 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import config from "@payload-config";
import { getPayload } from "payload";
import {
closeLatestOpenPeriod,
closePeriodById,
reopenPeriodById,
} from "@/lib/minigames/periods/lifecycle";
import { hasPermission } from "@/utils/access-control/hasPermission";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* Admin close/reopen control for minigame scoring periods.
*
* Body: `{ action: "close" | "reopen", periodId?: number }`.
* - `close` with a `periodId` closes that period; without one it closes the
* most recent open period (the early-close override).
* - `reopen` requires a `periodId` and reverses the close (removing that
* period's awards so a future close can re-grant them).
*
* Gated on the `minigame-periods:close` permission. The period tick owns the
* scheduled sweep; this route is the manual override, and both share the same
* idempotent close pipeline.
*/
export async function POST(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 });
}
if (!(await hasPermission(payload, user, "minigame-periods:close"))) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
let body: { action?: string; periodId?: number };
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
try {
if (body.action === "reopen") {
if (typeof body.periodId !== "number") {
return NextResponse.json({ error: "periodId is required to reopen." }, { status: 400 });
}
const reOpened = await reopenPeriodById(payload, body.periodId);
if (!reOpened) {
return NextResponse.json({ error: "Period not found." }, { status: 404 });
}
return NextResponse.json({ ok: true, reOpened });
}
if (body.action === "close") {
const closed =
typeof body.periodId === "number"
? await closePeriodById(payload, body.periodId)
: await closeLatestOpenPeriod(payload);
if (!closed) {
return NextResponse.json({ ok: false, error: "No open period to close." }, { status: 409 });
}
return NextResponse.json({ ok: true, closed: [closed] });
}
return NextResponse.json({ error: "Unknown action." }, { status: 400 });
} catch (error) {
payload.logger.error(`[MinigamePeriods] Close/reopen failed: ${error}`);
return NextResponse.json({ error: "Period operation failed." }, { status: 500 });
}
}

View file

@ -1,44 +0,0 @@
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 });
}
}

View file

@ -15,7 +15,6 @@ export interface BotConfig {
readyReminderPollMs: number;
imminentReminderPollMs: number;
sideOpsNoticePollMs: number;
achievementPollMs: number;
}
const required = (name: string): string => {
@ -63,5 +62,4 @@ export const botConfig: BotConfig = {
readyReminderPollMs: pollMs("DISCORD_READY_REMINDER_POLL_MS", 60_000),
imminentReminderPollMs: pollMs("DISCORD_IMMINENT_POLL_MS", 60_000),
sideOpsNoticePollMs: pollMs("DISCORD_SIDE_OPS_POLL_MS", 1_800_000),
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
};

View file

@ -1,116 +0,0 @@
import { formatPeriodLabel } from "@/lib/minigames/periods/derive";
import { formatMonthLabel, formatYearLabel } from "@/lib/minigames/periods/calendar";
import { MINIGAME_ACHIEVEMENT_TYPE_LABELS } from "@/lib/minigames/registry";
/**
* Pure helpers that turn achievement rows into Discord announcement content.
* No Discord or Payload dependencies, so grouping and rendering are testable in
* isolation. The service layer converts the rendered shape into an EmbedBuilder.
*/
export interface AchievementAnnouncementRow {
id: number;
type: string;
window: string;
windowStart: string;
windowEnd: string;
user:
| number
| {
id: number;
displayName?: string | null;
payloadDisplayName?: string | null;
username?: string | null;
}
| null;
value: number;
detail?: string | null;
}
export interface AchievementAnnouncementGroup {
window: string;
windowStart: string;
windowEnd: string;
label: string;
achievements: AchievementAnnouncementRow[];
}
export interface RenderedAchievementAnnouncement {
title: string;
description: string;
color: number;
fields: { name: string; value: string }[];
}
/** Display order for awards inside one announcement. */
const AWARD_ORDER = [
"period-champion",
"player-of-year",
"player-of-month",
"most-improved",
"diligence",
"dedication",
"precision",
];
const GOLD = 0xf59e0b;
const nameOf = (user: AchievementAnnouncementRow["user"]): string => {
if (!user || typeof user !== "object") return "Unknown";
return user.displayName || user.payloadDisplayName || user.username || `Operator #${user.id}`;
};
/** Human label for a window, e.g. "Oct 12 to Oct 25, 2026", "October 2026", "2026". */
export function achievementWindowLabel(window: string, windowStart: string, windowEnd: string): string {
const start = new Date(windowStart);
if (window === "month") return formatMonthLabel(start);
if (window === "year") return formatYearLabel(start);
return formatPeriodLabel(start.getTime(), new Date(windowEnd).getTime());
}
/** Group achievement rows by window (one Discord message per window). */
export function groupAchievementsForAnnouncement(
rows: AchievementAnnouncementRow[],
): AchievementAnnouncementGroup[] {
const byKey = new Map<string, AchievementAnnouncementGroup>();
for (const row of rows) {
const key = `${row.window}|${row.windowStart}`;
const group =
byKey.get(key) ??
({
window: row.window,
windowStart: row.windowStart,
windowEnd: row.windowEnd,
label: achievementWindowLabel(row.window, row.windowStart, row.windowEnd),
achievements: [],
} satisfies AchievementAnnouncementGroup);
group.achievements.push(row);
byKey.set(key, group);
}
const groups = [...byKey.values()];
for (const group of groups) {
group.achievements.sort(
(a, b) => AWARD_ORDER.indexOf(a.type) - AWARD_ORDER.indexOf(b.type) || a.id - b.id,
);
}
return groups.sort((a, b) => new Date(a.windowStart).getTime() - new Date(b.windowStart).getTime());
}
/** Render one window group into embed-ready content (one message per close). */
export function renderAchievementAnnouncement(
group: AchievementAnnouncementGroup,
): RenderedAchievementAnnouncement {
return {
title: `Minigame results: ${group.label}`,
description:
group.window === "period"
? "Anchored period closed. Placement points across the five Core boards."
: `Calendar ${group.window} closed.`,
color: GOLD,
fields: group.achievements.map((achievement) => ({
name: MINIGAME_ACHIEVEMENT_TYPE_LABELS[achievement.type as keyof typeof MINIGAME_ACHIEVEMENT_TYPE_LABELS] ?? achievement.type,
value: `${nameOf(achievement.user)} · ${achievement.detail ?? `${achievement.value}`}`,
})),
};
}

View file

@ -1,111 +0,0 @@
import { type Client, EmbedBuilder } from "discord.js";
import type { Payload } from "payload";
import { botConfig } from "@/bot/config";
import {
groupAchievementsForAnnouncement,
renderAchievementAnnouncement,
type AchievementAnnouncementRow,
} from "@/bot/lib/achievementRender";
/**
* Achievement announcements: poll unannounced achievements, post ONE embed per
* window to the announce channel, then stamp `announcedAt` + `discordMessageId`.
*
* One message per window keeps a close readable: a period close produces a single
* embed listing the five awards. Windows that fail to post stay unannounced and
* are retried on the next tick.
*
* The Next app never talks to Discord; this service owns the bot side.
*/
const MAX_GROUPS_PER_TICK = 3;
const BATCH_LIMIT = 100;
/** Minimal text-channel shape we rely on (mirrors fridayOpsNotice). */
type AnnounceChannel = {
send(payload: { embeds: EmbedBuilder[] }): Promise<{ id: string }>;
};
let running = false;
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
const poll = async (client: Client, payload: Payload): Promise<void> => {
if (running) return;
running = true;
try {
const channelId = botConfig.announceChannelId;
if (!channelId) return;
const res = await payload.find({
collection: "achievements",
where: { announcedAt: { exists: false } },
sort: "windowStart",
limit: BATCH_LIMIT,
depth: 1,
overrideAccess: true,
});
if (res.docs.length === 0) return;
const groups = groupAchievementsForAnnouncement(
res.docs as unknown as AchievementAnnouncementRow[],
);
const channel = await client.channels.fetch(channelId);
if (!channel || !("send" in channel)) {
throw new Error(`[Bot] Announce channel ${channelId} is not a text channel.`);
}
const textChannel = channel as unknown as AnnounceChannel;
let posted = 0;
for (const group of groups.slice(0, MAX_GROUPS_PER_TICK)) {
try {
const rendered = renderAchievementAnnouncement(group);
const message = await textChannel.send({
embeds: [
new EmbedBuilder()
.setTitle(rendered.title)
.setDescription(rendered.description)
.setColor(rendered.color)
.addFields(rendered.fields),
],
});
const announcedAt = new Date().toISOString();
for (const achievement of group.achievements) {
await payload.update({
collection: "achievements",
id: achievement.id,
data: { announcedAt, discordMessageId: message.id },
overrideAccess: true,
depth: 0,
});
}
posted += 1;
} catch (error) {
// Leave the rows unannounced so the next tick retries this window.
payload.logger.error(
`[Bot] Achievement announcement for "${group.label}" failed: ${errorMessage(error)}`,
);
}
}
if (posted > 0) {
payload.logger.info(`[Bot] Achievement announcements posted: ${posted}`);
}
} catch (error) {
payload.logger.error(`[Bot] Achievement announcement poll failed: ${errorMessage(error)}`);
} finally {
running = false;
}
};
export const start = (client: Client, payload: Payload): void => {
payload.logger.info("[Bot] Achievement announcement service started");
void poll(client, payload);
setInterval(() => {
void poll(client, payload);
}, botConfig.achievementPollMs);
};

View file

@ -7,7 +7,6 @@ import { start as startEvaluationReminders } from "./evaluationReminders";
import { start as startReadyReminders } from "./readyReminders";
import { start as startImminentReminders } from "./imminentReminders";
import { start as startFridayOpsNotice } from "./fridayOpsNotice";
import { start as startAchievementAnnouncements } from "./achievementAnnouncements";
export type ServiceStarter = (client: Client, payload: Payload) => Promise<void> | void;
@ -19,5 +18,4 @@ export const services: ServiceStarter[] = [
startReadyReminders,
startImminentReminders,
startFridayOpsNotice,
startAchievementAnnouncements,
];

View file

@ -1,75 +0,0 @@
import { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import {
MINIGAME_ANCHOR_DATE,
PERIOD_LENGTH_DAYS_DEFAULT,
PLACEMENT_LADDER_TOP_N_DEFAULT,
PRECISION_MIN_ATTEMPTS_DEFAULT,
} from "@/lib/minigames/registry";
/**
* Global tuning for minigame periods and achievements.
*
* `anchorDate` is treated as immutable: changing it re-slices and re-labels
* every period, so it should only change through an explicit, confirmed admin
* action. Periods before the anchor do not exist.
*/
export const MinigameRules: GlobalConfig = {
slug: "minigame-rules",
label: "Minigame Rules",
access: {
read: requirePermission("minigame-rules:read"),
update: requirePermission("minigame-rules:update"),
},
fields: [
{
name: "enabled",
type: "checkbox",
defaultValue: true,
admin: {
description:
"Master gate for anchored scoring periods and achievements. When off, the period tick does nothing and period boards fall back to All-Time.",
},
},
{
name: "periodLengthDays",
type: "number",
required: true,
min: 1,
defaultValue: PERIOD_LENGTH_DAYS_DEFAULT,
admin: { description: "Length of each scoring period in days." },
},
{
name: "anchorDate",
type: "date",
required: true,
defaultValue: MINIGAME_ANCHOR_DATE,
admin: {
description:
"Start of Period 1 (UTC). Immutable once set: changing it re-slices every period, so confirm before editing.",
},
},
{
name: "placementLadderTopN",
type: "number",
required: true,
min: 1,
defaultValue: PLACEMENT_LADDER_TOP_N_DEFAULT,
admin: {
description:
"How many placements earn points on each board (1st = N points down to Nth = 1). Points sum across the five Core boards.",
},
},
{
name: "precisionMinAttempts",
type: "number",
required: true,
min: 1,
defaultValue: PRECISION_MIN_ATTEMPTS_DEFAULT,
admin: {
description:
"Minimum qualifying attempts (Aim Trainer + Radio + OPORD) for the Precision achievement.",
},
},
],
};

View file

@ -1,74 +0,0 @@
import { CollectionConfig } from "payload";
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;
/**
* Evidence store for close-time achievements. This is NOT the Awards system:
* awards are unit decorations, achievements are minigame honors.
*
* Written only by the close pipeline (`src/lib/minigames/periods/`, running
* with `overrideAccess`). Publicly readable for the honor roll. The unique
* `type:windowStart:user` key makes concurrent closes (the tick and the admin
* override) idempotent: a second close inserts nothing.
*/
export const Achievements: CollectionConfig = {
slug: "achievements",
labels: { singular: "Achievement", plural: "Achievements" },
admin: {
group: "Minigames",
useAsTitle: "detail",
defaultColumns: ["type", "window", "user", "value", "rank", "windowStart", "announcedAt"],
description:
"Minigame achievements granted at period/month/year close. Read-only here; written by the close pipeline.",
},
access: {
read: () => true,
create: () => false,
update: () => false,
delete: () => false,
},
fields: [
{
name: "window",
type: "select",
required: true,
index: true,
options: MINIGAME_ACHIEVEMENT_WINDOWS.map((value) => ({
label: MINIGAME_ACHIEVEMENT_WINDOW_LABELS[value] ?? value,
value,
})),
...readOnly,
},
{ name: "windowStart", type: "date", required: true, index: true, ...readOnly },
{ name: "windowEnd", type: "date", required: true, ...readOnly },
{
name: "type",
type: "select",
required: true,
index: true,
options: MINIGAME_ACHIEVEMENT_TYPES.map((value) => ({
label: MINIGAME_ACHIEVEMENT_TYPE_LABELS[value] ?? value,
value,
})),
...readOnly,
},
{ name: "user", type: "relationship", relationTo: "users", required: true, index: true, ...readOnly },
{ name: "value", type: "number", required: true, ...readOnly },
{
name: "detail",
type: "text",
...readOnly,
admin: { readOnly: true, description: "Short human-readable context, e.g. '42 points across 5 boards'." },
},
{ name: "rank", type: "number", ...readOnly },
{ name: "announcedAt", type: "date", index: true, ...readOnly },
{ name: "discordMessageId", type: "text", ...readOnly },
],
indexes: [{ fields: ["type", "windowStart", "user"], unique: true }],
};

View file

@ -1,86 +0,0 @@
import { CollectionConfig } from "payload";
const readOnly = { admin: { readOnly: true } } as const;
/**
* Append-only ledger of completed minigame runs for the Core 5 games.
*
* One row per completed, scored run: the same runs that emit `minigame:*`
* events. Rows are the source of truth for anchored period boards and
* achievements; the all-time profile aggregates on
* `profiles.progression.minigames.*` stay untouched and continue to update.
*
* Writes are service-only (`src/lib/minigames/periods/` runs with
* `overrideAccess`) so the collection denies create/update/delete outright and
* the admin panel is a read-only review surface. Never let a client author a
* row: the validating submit actions are the only write path.
*/
export const MinigameEntries: CollectionConfig = {
slug: "minigame-entries",
labels: { singular: "Minigame Entry", plural: "Minigame Entries" },
admin: {
group: "Minigames",
useAsTitle: "game",
defaultColumns: ["user", "game", "mode", "score", "accuracy", "durationMs", "period", "occurredAt"],
description:
"Append-only ledger of completed minigame runs. Read-only here; writes flow through the minigame submit actions.",
},
access: {
read: () => true,
create: () => false,
update: () => false,
delete: () => false,
},
fields: [
{ name: "user", type: "relationship", relationTo: "users", required: true, index: true, ...readOnly },
{
name: "game",
type: "text",
required: true,
index: true,
...readOnly,
admin: { readOnly: true, description: "Registry key (minigames.key)." },
},
{
name: "mode",
type: "text",
...readOnly,
admin: { readOnly: true, description: "Mode or difficulty label when applicable (e.g. sprint, elite)." },
},
{ name: "score", type: "number", required: true, index: true, ...readOnly },
{
name: "occurredAt",
type: "date",
index: true,
...readOnly,
admin: {
readOnly: true,
description:
"When the run happened (server clock at submit). Calendar month/year windows score by this, not the row's createdAt.",
},
},
{
name: "accuracy",
type: "number",
min: 0,
max: 1,
...readOnly,
admin: { readOnly: true, description: "Fractional accuracy for games that score it." },
},
{
name: "durationMs",
type: "number",
required: true,
min: 0,
...readOnly,
admin: { readOnly: true, description: "Server-validated run duration in milliseconds." },
},
{ name: "period", type: "relationship", relationTo: "minigame-periods", index: true, ...readOnly },
{
name: "meta",
type: "json",
...readOnly,
admin: { readOnly: true, description: "Small extras (e.g. EOD win flags) that do not warrant a column." },
},
],
};

View file

@ -1,68 +0,0 @@
import { CollectionConfig } from "payload";
const readOnly = { admin: { readOnly: true } } as const;
/**
* Anchored 14-day scoring periods for the Core 5 minigames.
*
* Period 1 starts at the `minigame-rules.anchorDate` and each subsequent period
* is `periodLengthDays` long. Boards reset each period; the ledger history is
* never removed. Exactly one period is expected to be `open` at a time (the
* close pipeline is idempotent and re-checks status before writing).
*
* Writes are service-only (`src/lib/minigames/periods/` runs with
* `overrideAccess`), so the collection denies create/update/delete; the admin
* panel is a read-only review surface plus the close/reopen control.
*/
export const MinigamePeriods: CollectionConfig = {
slug: "minigame-periods",
labels: { singular: "Minigame Period", plural: "Minigame Periods" },
admin: {
group: "Minigames",
useAsTitle: "label",
defaultColumns: ["label", "startDate", "endDate", "status", "closedAt"],
description:
"Anchored scoring periods. Read-only here; the period tick and the close/reopen control manage them.",
components: {
beforeListTable: ["@/components/admin/minigames/PeriodCloseControl"],
},
},
access: {
read: () => true,
create: () => false,
update: () => false,
delete: () => false,
},
fields: [
{
name: "startDate",
type: "date",
required: true,
unique: true,
index: true,
...readOnly,
admin: { readOnly: true, description: "Inclusive UTC start. Unique; drives period identity." },
},
{ name: "endDate", type: "date", required: true, ...readOnly },
{ name: "label", type: "text", required: true, ...readOnly },
{
name: "status",
type: "select",
required: true,
defaultValue: "open",
index: true,
options: [
{ label: "Open", value: "open" },
{ label: "Closed", value: "closed" },
],
},
{ name: "closedAt", type: "date", ...readOnly },
{
name: "previousPeriod",
type: "relationship",
relationTo: "minigame-periods",
...readOnly,
admin: { readOnly: true, description: "Previous period in the chain, for most-improved deltas." },
},
],
};

View file

@ -1,85 +0,0 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
/**
* Registry of minigames.
*
* Drives the Core / Cardtable sidebar grouping and the period-scoring scope.
* Games are never deleted: setting `status: "retired"` removes a game from the
* nav and from future period scoring while its ledger history stays intact.
* Publicly readable so the frontend can render the nav and boards; writes are
* admin-gated.
*/
export const Minigames: CollectionConfig = {
slug: "minigames",
labels: { singular: "Minigame", plural: "Minigames" },
admin: {
group: "Minigames",
useAsTitle: "label",
defaultColumns: ["key", "label", "category", "status", "order", "countsForPeriods"],
description:
"Registry of minigames. Retired games keep their history but leave the nav and future period scoring.",
},
access: {
read: () => true,
create: requirePermission("minigames:create"),
update: requirePermission("minigames:update"),
delete: requirePermission("minigames:delete"),
},
fields: [
{
name: "key",
type: "text",
required: true,
unique: true,
index: true,
admin: {
description:
"Stable machine key (e.g. flappy, eod). Ledger rows reference it; avoid changing it after launch.",
},
},
{ name: "label", type: "text", required: true },
{ name: "description", type: "textarea" },
{
name: "route",
type: "text",
required: true,
admin: { description: "Frontend path, e.g. /minigames/flappy." },
},
{
name: "icon",
type: "text",
defaultValue: "Gamepad2",
admin: { description: "lucide-react icon name, mapped in the client." },
},
{
name: "category",
type: "select",
required: true,
defaultValue: "core",
options: [
{ label: "Core", value: "core" },
{ label: "Cardtable", value: "cardtable" },
],
},
{
name: "status",
type: "select",
required: true,
defaultValue: "active",
options: [
{ label: "Active", value: "active" },
{ label: "Upcoming", value: "upcoming" },
{ label: "Retired", value: "retired" },
],
},
{ name: "order", type: "number", required: true, defaultValue: 0 },
{
name: "countsForPeriods",
type: "checkbox",
defaultValue: false,
admin: { description: "When on, ledger entries for this game feed anchored period boards." },
},
{ name: "scoreLabel", type: "text", defaultValue: "Score" },
],
};

View file

@ -1,173 +0,0 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@payloadcms/ui";
/**
* Admin close/reopen control for minigame scoring periods.
*
* Rendered above the minigame-periods list. It reads periods through the REST
* API (admin session cookie) and drives POST /api/minigame-periods/close, which
* is gated on the `minigame-periods:close` permission; a 403 is surfaced inline.
* The scheduled sweep lives in the period-tick bin, so this is the manual
* override for closing early or reopening a closed period.
*/
interface PeriodRow {
id: number;
label: string;
status: string;
startDate: string;
endDate: string;
}
const dateOnly = (iso: string): string => (iso ? iso.slice(0, 10) : "");
export default function PeriodCloseControl() {
const router = useRouter();
const [rows, setRows] = useState<PeriodRow[] | null>(null);
const [busy, setBusy] = useState<number | null>(null);
const [message, setMessage] = useState<string | null>(null);
const load = useCallback(async () => {
try {
const res = await fetch("/api/minigame-periods?limit=20&sort=-startDate&depth=0", {
credentials: "include",
});
if (!res.ok) throw new Error("load failed");
const json = (await res.json()) as { docs?: PeriodRow[] };
setRows(
(json.docs ?? []).map((doc) => ({
id: doc.id,
label: doc.label,
status: doc.status,
startDate: doc.startDate,
endDate: doc.endDate,
})),
);
} catch {
setRows([]);
}
}, []);
useEffect(() => {
void load();
}, [load]);
const act = async (action: "close" | "reopen", periodId: number) => {
setBusy(periodId);
setMessage(null);
try {
const res = await fetch("/api/minigame-periods/close", {
method: "POST",
headers: { "content-type": "application/json" },
credentials: "include",
body: JSON.stringify({ action, periodId }),
});
const json = (await res.json().catch(() => ({}))) as {
ok?: boolean;
error?: string;
closed?: { label?: string }[];
};
if (!res.ok || json.ok === false) {
setMessage(
res.status === 403
? "You do not have permission to close or reopen periods."
: (json.error ?? `Request failed (${res.status}).`),
);
return;
}
setMessage(
action === "close"
? `Closed "${json.closed?.[0]?.label ?? "period"}".`
: "Period reopened.",
);
await load();
router.refresh();
} catch {
setMessage("Request failed.");
} finally {
setBusy(null);
}
};
if (rows === null) return null;
return (
<div
style={{
border: "1px solid var(--theme-elevation-150)",
borderRadius: 8,
padding: "12px 16px",
marginBottom: 16,
}}
>
<div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
<strong>Period control</strong>
<span style={{ opacity: 0.7, fontSize: 13 }}>
Close the open period early, or reopen a closed one. The period tick usually does this on
schedule.
</span>
</div>
{message && (
<p style={{ marginTop: 8, fontSize: 13 }} role="status">
{message}
</p>
)}
<div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
{rows.length === 0 && (
<span style={{ opacity: 0.7, fontSize: 13 }}>
No periods yet. The first one appears when a Core run is recorded or the period tick runs.
</span>
)}
{rows.slice(0, 6).map((row) => (
<div
key={row.id}
style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}
>
<span style={{ minWidth: 220 }}>{row.label}</span>
<span style={{ opacity: 0.7, fontSize: 12 }}>
{dateOnly(row.startDate)} to {dateOnly(row.endDate)} UTC
</span>
<span
style={{
fontSize: 11,
textTransform: "uppercase",
letterSpacing: 0.5,
opacity: 0.8,
}}
>
{row.status}
</span>
<span style={{ marginLeft: "auto" }}>
{row.status === "open" ? (
<Button
type="button"
buttonStyle="secondary"
size="small"
disabled={busy !== null}
onClick={() => void act("close", row.id)}
>
{busy === row.id ? "Closing..." : "Close now"}
</Button>
) : (
<Button
type="button"
buttonStyle="subtle"
size="small"
disabled={busy !== null}
onClick={() => void act("reopen", row.id)}
>
{busy === row.id ? "Reopening..." : "Reopen"}
</Button>
)}
</span>
</div>
))}
</div>
</div>
);
}

View file

@ -34,7 +34,6 @@ 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: [
@ -78,7 +77,6 @@ export function AppSidebar({
showCallsign = false,
canImpersonate = false,
preferences,
minigameNav = [],
...props
}: {
user: {
@ -95,7 +93,6 @@ 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,
@ -196,7 +193,7 @@ export function AppSidebar({
</SidebarMenuButton>
</SidebarMenuItem>
)}
<div className="pb-1"><NavMinigames games={minigameNav} /></div>
<div className="pb-1"><NavMinigames /></div>
</SidebarMenu>
</SidebarContent>
<SidebarFooter>

View file

@ -1,10 +1,8 @@
"use client";
import { ChevronRight, Gamepad2, Trophy } from "lucide-react";
import { Bird, Bomb, ChevronRight, Club, Crosshair, FileTextIcon, Gamepad2, Radio, Spade } 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,
@ -20,17 +18,21 @@ import {
useSidebar,
} from "@/components/ui/sidebar";
/**
* 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 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 visible = games.filter((game) => game.status !== "retired");
const coreGames = visible.filter((game) => game.category === "core");
const cardtableGames = visible.filter((game) => game.category === "cardtable");
const cardtableGames = [
{ title: "Poker", url: "/minigames/poker", icon: Spade },
{ title: "Blackjack", url: "/minigames/blackjack", icon: Club },
];
export function NavMinigames() {
const { isMobile } = useSidebar();
return (
<SidebarMenuItem>
@ -50,17 +52,14 @@ export function NavMinigames({ games }: { games: RegistryGame[] }) {
>
<DropdownMenuGroup>
<DropdownMenuLabel>Core</DropdownMenuLabel>
{coreGames.map((game) => {
const Icon = minigameIcon(game.icon);
return (
<DropdownMenuItem key={game.key} asChild>
<Link href={game.route}>
<Icon />
{game.label}
</Link>
</DropdownMenuItem>
);
})}
{coreGames.map((game) => (
<DropdownMenuItem key={game.url} asChild>
<Link href={game.url}>
<game.icon />
{game.title}
</Link>
</DropdownMenuItem>
))}
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
@ -68,26 +67,14 @@ export function NavMinigames({ games }: { games: RegistryGame[] }) {
<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) => {
const Icon = minigameIcon(game.icon);
return (
<DropdownMenuItem key={game.key} asChild>
<Link href={game.route}>
<Icon />
{game.label}
</Link>
</DropdownMenuItem>
);
})}
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem asChild>
<Link href="/minigames/leaderboards">
<Trophy />
Leaderboards
</Link>
</DropdownMenuItem>
{cardtableGames.map((game) => (
<DropdownMenuItem key={game.url} asChild>
<Link href={game.url}>
<game.icon />
{game.title}
</Link>
</DropdownMenuItem>
))}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>

View file

@ -1,46 +0,0 @@
"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>
);
}

View file

@ -1,138 +0,0 @@
"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>
);
}

View file

@ -1,115 +0,0 @@
"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>
);
}

View file

@ -1,78 +0,0 @@
"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>
);
}

View file

@ -427,7 +427,6 @@ export function FlappyBird({
flockTimer: 480,
});
const submittingRef = useRef(false);
const runStartedAtRef = useRef(0);
const statsRef = useRef<FlappyStats>(serverStats);
const [phase, setPhase] = useState<Phase>("ready");
@ -466,7 +465,7 @@ export function FlappyBird({
}, [setPhaseSafe]);
const handleGameOver = useCallback(
async (finalScore: number, durationMs: number) => {
async (finalScore: number) => {
if (submittingRef.current) return;
if (expiredRef.current) {
setLastRun({
@ -487,7 +486,7 @@ export function FlappyBird({
}
submittingRef.current = true;
setSubmitting(true);
const res = await submitFlappyScore({ passes: finalScore, durationMs });
const res = await submitFlappyScore({ passes: finalScore });
submittingRef.current = false;
setSubmitting(false);
if (res.success && res.data) {
@ -532,7 +531,6 @@ export function FlappyBird({
const g = gameRef.current;
g.birdY = START_Y;
g.birdVy = FLAP_VY;
runStartedAtRef.current = performance.now();
setPhaseSafe("playing");
playFlap();
} else if (p === "playing") {
@ -562,10 +560,7 @@ export function FlappyBird({
const g = gameRef.current;
setPhaseSafe("over");
playHit();
const startedAt = runStartedAtRef.current;
const durationMs =
startedAt > 0 ? Math.max(1, Math.round(performance.now() - startedAt)) : 1;
handleGameOverRef.current(g.score, durationMs);
handleGameOverRef.current(g.score);
};
const step = (now: number) => {

View file

@ -1,34 +0,0 @@
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

@ -482,7 +482,6 @@ export function AimTrainerGame({
civilianHits: game.civilianHits,
shotsFired: game.shotsFired,
despawnedUnhitTargets: game.despawnedUnhitTargets,
durationMs: Math.max(1, Math.round(performance.now() - game.startedAt)),
});
};

View file

@ -391,7 +391,7 @@ export function RadioTraffic({
});
return;
}
const elapsedMs = performance.now() - roundStartedAtRef.current;
const elapsedMs = resultMode === "sprint" ? performance.now() - roundStartedAtRef.current : undefined;
void recordResult(finalResults, resultMode, elapsedMs, incorrectMessages);
},
[recordResult, setPhaseSafe],

View file

@ -1,46 +0,0 @@
"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 };
}

View file

@ -9,43 +9,3 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved
- **Radio Traffic**: `/minigames/radio`, sprint + watch modes, procedural message generation (`src/components/frontend/minigames/radio/messageGenerator.ts`). Action `submitRadioResult` emits `minigame:radio-traffic`; stats under `progression.minigames.radioTraffic` (incl. `bestSprintTimeMs`).
- **Flight Simulator**: `/minigames/flappy` (canvas game + leaderboard). **Minefield Clearance (EOD)**: `/minigames/eod`. **OPORD Recall**: `/minigames/opord` (`src/lib/minigames/opord-recall.ts`).
- Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong.
## Periods, achievements & the game registry
Anchored 14-day scoring periods, close-time achievements, and a registry that lets
games be phased in and out without losing history. Full behavior is documented in the
code; the invariants are:
- **Scope**: only the Core five (flappy, eod, radio, qualification, opord) score periods.
Poker and Blackjack keep their all-time profile boards and are out of periods.
- **Anchor**: `minigame-rules.anchorDate` (default `2026-10-12T00:00:00Z`) starts Period 1
and is treated as immutable; changing it re-slices and re-labels every period. All math
is UTC.
- **Ledger**: `minigame-entries` is an append-only row per completed scored run, written
ONLY by the five submit actions through `recordMinigameEntry` (`src/lib/minigames/periods/record.ts`),
which swallows failures so a ledger hiccup never breaks a submission. Each row carries
`occurredAt` (the run's own instant) plus its `period`.
- **Boards & awards**: `src/lib/minigames/periods/boards.ts` is pure. Best score ranks each
board, the top-N placement ladder (default 10) sums across the Core boards, and ties break
on raw period score then earliest submission. Period awards: period-champion, diligence,
dedication, precision (min `precisionMinAttempts`), most-improved (skipped in Period 1).
- **Close pipeline**: `src/lib/minigames/periods/lifecycle.ts` closes a period, writes its
`achievements` rows and marks it closed. Idempotent: the status is re-checked before
committing and the `achievements` unique key (`type:windowStart:user`) makes a duplicate
close insert nothing. `closeCalendarWindows` additionally crowns Player of the Month and
Player of the Year for completed calendar windows (scored by run `occurredAt`; the first
window of each kind is partial).
- **Tick & override**: the `period-tick` bin (`src/scripts/periodTick.ts`, external cron) runs
the sweep; the admin close/reopen control
(`src/components/admin/minigames/PeriodCloseControl.tsx` → `POST /api/minigame-periods/close`,
permission `minigame-periods:close`) is the manual override.
- **Registry**: `minigames` drives the sidebar grouping and period scoring. Retired games leave
the nav and stop accruing next-period points while their ledger history stays. Period scoring
uses core games with `countsForPeriods`; `loadMinigameRegistry` falls back to
`BUILTIN_MINIGAMES` if the collection is empty.
- **Surfaces**: `/minigames/leaderboards` (period selector + game tabs + achievements honor roll,
fed by `GET /api/minigames/leaderboards?period=current|<id>|all-time`) and a `PeriodStandingsCard`
on each Core game page. All-Time reads the untouched `profiles.progression.minigames.*` bests.
- **Notifications**: winners are notified in-app on close (`minigame:achievement`, muteable);
the Discord bot service `src/bot/services/achievementAnnouncements.ts` posts ONE embed per
window to `DISCORD_ANNOUNCE_CHANNEL_ID` and stamps `announcedAt` + `discordMessageId`.

View file

@ -1,55 +0,0 @@
/**
* 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[];
}

View file

@ -1,60 +0,0 @@
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,329 +0,0 @@
/**
* Pure period board + award math.
*
* A period board is built from the `minigame-entries` ledger: every player's
* best score on a game ranks them, the top `topN` placements earn fixed ladder
* points (1st = topN down to Nth = 1), and points sum across the five Core
* boards for the Period Champion.
*
* Tie-break, per the locked rules: raw period score (the player's total raw
* score on the board, and the sum of their best scores for the champion),
* then earliest submission. `userId` is the final deterministic guard.
*
* No Payload import: safe to unit-test and to reuse on the client.
*/
export interface LedgerEntry {
userId: number;
game: string;
score: number;
durationMs: number;
accuracy: number | null;
createdAtMs: number;
}
export interface BoardRow {
userId: number;
bestScore: number;
/** Sum of every score the player posted on this board. */
rawScore: number;
attempts: number;
durationMs: number;
accuracySum: number;
accuracyCount: number;
/** Earliest submission among the runs that reached `bestScore`. */
bestAtMs: number;
/** Earliest submission on this board, period-wide. */
firstAtMs: number;
}
export interface RankedRow extends BoardRow {
rank: number;
points: number;
}
/** Rank one game's ledger entries into a board with placement points. */
export function buildGameBoard(entries: LedgerEntry[], topN: number): RankedRow[] {
const byUser = new Map<number, BoardRow>();
for (const entry of entries) {
const row =
byUser.get(entry.userId) ??
({
userId: entry.userId,
bestScore: Number.NEGATIVE_INFINITY,
rawScore: 0,
attempts: 0,
durationMs: 0,
accuracySum: 0,
accuracyCount: 0,
bestAtMs: Number.POSITIVE_INFINITY,
firstAtMs: Number.POSITIVE_INFINITY,
} satisfies BoardRow);
row.attempts += 1;
row.rawScore += entry.score;
row.durationMs += entry.durationMs;
if (typeof entry.accuracy === "number" && Number.isFinite(entry.accuracy)) {
row.accuracySum += entry.accuracy;
row.accuracyCount += 1;
}
if (entry.score > row.bestScore) {
row.bestScore = entry.score;
row.bestAtMs = entry.createdAtMs;
} else if (entry.score === row.bestScore && entry.createdAtMs < row.bestAtMs) {
row.bestAtMs = entry.createdAtMs;
}
if (entry.createdAtMs < row.firstAtMs) row.firstAtMs = entry.createdAtMs;
byUser.set(entry.userId, row);
}
const rows = [...byUser.values()].sort(
(a, b) =>
b.bestScore - a.bestScore ||
b.rawScore - a.rawScore ||
a.bestAtMs - b.bestAtMs ||
a.userId - b.userId,
);
return rows.map((row, index) => ({
...row,
rank: index + 1,
points: index < topN ? topN - index : 0,
}));
}
export interface PlayerTotal {
userId: number;
points: number;
/** Sum of the player's best score on every board they appear on. */
rawScore: number;
attempts: number;
durationMs: number;
accuracySum: number;
accuracyCount: number;
firstAtMs: number;
}
/** Sum placement points and raw stats for every player across all boards. */
export function aggregatePlayers(boards: RankedRow[][]): PlayerTotal[] {
const byUser = new Map<number, PlayerTotal>();
for (const board of boards) {
for (const row of board) {
const total =
byUser.get(row.userId) ??
({
userId: row.userId,
points: 0,
rawScore: 0,
attempts: 0,
durationMs: 0,
accuracySum: 0,
accuracyCount: 0,
firstAtMs: Number.POSITIVE_INFINITY,
} satisfies PlayerTotal);
total.points += row.points;
total.rawScore += row.bestScore;
total.attempts += row.attempts;
total.durationMs += row.durationMs;
total.accuracySum += row.accuracySum;
total.accuracyCount += row.accuracyCount;
total.firstAtMs = Math.min(total.firstAtMs, row.firstAtMs);
byUser.set(row.userId, total);
}
}
return [...byUser.values()];
}
/** Total placement points per player across a set of boards. */
export function totalPointsByUser(boards: RankedRow[][]): Map<number, number> {
const points = new Map<number, number>();
for (const board of boards) {
for (const row of board) {
points.set(row.userId, (points.get(row.userId) ?? 0) + row.points);
}
}
return points;
}
export const PERIOD_AWARD_TYPES = [
"period-champion",
"diligence",
"dedication",
"precision",
"most-improved",
] as const;
export type PeriodAwardType = (typeof PERIOD_AWARD_TYPES)[number];
export interface ComputedAward {
type: PeriodAwardType;
userId: number;
value: number;
detail: string;
}
export interface PeriodAwardInput {
entries: LedgerEntry[];
/** Registry keys that count for periods (the Core five). */
games: string[];
topN: number;
precisionMinAttempts: number;
/** Null when there is no previous period (Period 1); skips Most Improved. */
previousPointsByUser: Map<number, number> | null;
}
const plural = (count: number, singular: string, pluralForm = `${singular}s`): string =>
`${count} ${count === 1 ? singular : pluralForm}`;
/** Human-readable duration for award details, e.g. "1h 12m", "45m", "30s". */
export function formatDuration(ms: number): string {
const totalSeconds = Math.max(0, Math.round(ms / 1000));
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) return `${hours}h ${minutes}m`;
if (minutes > 0) return `${minutes}m ${seconds}s`;
return `${seconds}s`;
}
/** The five period awards, ranked with the locked tie-break rules. */
export function computePeriodAwards(input: PeriodAwardInput): ComputedAward[] {
const { entries, games, topN, precisionMinAttempts, previousPointsByUser } = input;
const boards = games.map((game) =>
buildGameBoard(
entries.filter((entry) => entry.game === game),
topN,
),
);
const players = aggregatePlayers(boards);
if (players.length === 0) return [];
const awards: ComputedAward[] = [];
// Period Champion: most summed placement points.
const byPoints = [...players].sort(
(a, b) =>
b.points - a.points ||
b.rawScore - a.rawScore ||
a.firstAtMs - b.firstAtMs ||
a.userId - b.userId,
);
const champion = byPoints[0];
const championBoards = boards.filter((board) =>
board.some((row) => row.userId === champion.userId),
).length;
awards.push({
type: "period-champion",
userId: champion.userId,
value: champion.points,
detail: `${plural(champion.points, "point")} across ${plural(championBoards, "board")}`,
});
// Diligence: most attempts.
const diligence = [...players].sort(
(a, b) => b.attempts - a.attempts || b.points - a.points || a.userId - b.userId,
)[0];
awards.push({
type: "diligence",
userId: diligence.userId,
value: diligence.attempts,
detail: plural(diligence.attempts, "attempt"),
});
// Dedication: most total time.
const dedication = [...players].sort(
(a, b) => b.durationMs - a.durationMs || b.points - a.points || a.userId - b.userId,
)[0];
awards.push({
type: "dedication",
userId: dedication.userId,
value: dedication.durationMs,
detail: `${formatDuration(dedication.durationMs)} played`,
});
// Precision: best average accuracy, minimum qualifying attempts.
const precisionCandidates = players.filter(
(player) => player.accuracyCount >= precisionMinAttempts,
);
if (precisionCandidates.length > 0) {
const precision = precisionCandidates.sort((a, b) => {
const avgA = a.accuracySum / a.accuracyCount;
const avgB = b.accuracySum / b.accuracyCount;
return avgB - avgA || b.accuracyCount - a.accuracyCount || a.userId - b.userId;
})[0];
const average = precision.accuracySum / precision.accuracyCount;
awards.push({
type: "precision",
userId: precision.userId,
value: Math.round(average * 10_000) / 10_000,
detail: `${Math.round(average * 100)}% average accuracy over ${plural(precision.accuracyCount, "scoring run")}`,
});
}
// Most Improved: placement-point gain vs the previous period. Not awarded in
// Period 1 (no previous period).
if (previousPointsByUser) {
const improved = players
.map((player) => ({
player,
gain: player.points - (previousPointsByUser.get(player.userId) ?? 0),
}))
.filter((candidate) => candidate.gain > 0)
.sort(
(a, b) =>
b.gain - a.gain ||
b.player.points - a.player.points ||
a.player.userId - b.player.userId,
)[0];
if (improved) {
awards.push({
type: "most-improved",
userId: improved.player.userId,
value: improved.gain,
detail: `+${plural(improved.gain, "point")} vs the previous period`,
});
}
}
return awards;
}
export interface WindowChampion {
userId: number;
points: number;
/** How many boards the champion placed on. */
boards: number;
}
/**
* The champion of an arbitrary window (a calendar month or year), scored with
* the same top-N placement ladder summed across the Core boards as the period
* champion. Returns null when the window has no entries.
*/
export function computeWindowChampion(input: {
entries: LedgerEntry[];
games: string[];
topN: number;
}): WindowChampion | null {
const boards = input.games.map((game) =>
buildGameBoard(
input.entries.filter((entry) => entry.game === game),
input.topN,
),
);
const players = aggregatePlayers(boards);
if (players.length === 0) return null;
const winner = [...players].sort(
(a, b) =>
b.points - a.points ||
b.rawScore - a.rawScore ||
a.firstAtMs - b.firstAtMs ||
a.userId - b.userId,
)[0];
const boardsWith = boards.filter((board) =>
board.some((row) => row.userId === winner.userId),
).length;
return { userId: winner.userId, points: winner.points, boards: boardsWith };
}

View file

@ -1,99 +0,0 @@
/**
* Pure UTC calendar windows for the month/year achievements.
*
* Player of the Month and Player of the Year are calendar windows, not period
* windows: a month holds two or three 14-day periods. Everything is UTC, and
* the first window of each kind is partial because it begins at the anchor
* (see the feature's locked assumptions).
*
* A window is only "complete" once its exclusive end has passed, so the tick
* never crowns a month that is still running.
*
* No Payload import: safe to unit-test.
*/
const MONTH_NAMES = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
] as const;
export interface CalendarWindow {
/** Inclusive UTC start (max of the natural boundary and the anchor). */
windowStart: Date;
/** Exclusive UTC end (the next natural boundary). */
windowEnd: Date;
/** Human label, e.g. "October 2026" or "2026". */
label: string;
}
export const startOfUtcMonth = (instant: Date): Date =>
new Date(Date.UTC(instant.getUTCFullYear(), instant.getUTCMonth(), 1));
export const startOfNextUtcMonth = (instant: Date): Date =>
new Date(Date.UTC(instant.getUTCFullYear(), instant.getUTCMonth() + 1, 1));
export const startOfUtcYear = (instant: Date): Date =>
new Date(Date.UTC(instant.getUTCFullYear(), 0, 1));
export const startOfNextUtcYear = (instant: Date): Date =>
new Date(Date.UTC(instant.getUTCFullYear() + 1, 0, 1));
const laterOf = (a: Date, b: Date): Date => (a.getTime() >= b.getTime() ? a : b);
export const formatMonthLabel = (instant: Date): string =>
`${MONTH_NAMES[instant.getUTCMonth()]} ${instant.getUTCFullYear()}`;
export const formatYearLabel = (instant: Date): string => `${instant.getUTCFullYear()}`;
const MAX_WINDOWS = 1000;
/**
* Every completed calendar month from the anchor through `now`, oldest first.
* The first window starts at the anchor when the anchor falls mid-month.
*/
export function completedMonthWindows(anchor: Date, now: Date): CalendarWindow[] {
const out: CalendarWindow[] = [];
if (!Number.isFinite(anchor.getTime()) || !Number.isFinite(now.getTime())) return out;
if (now.getTime() < anchor.getTime()) return out;
let cursor = startOfUtcMonth(anchor);
for (let guard = 0; guard < MAX_WINDOWS; guard += 1) {
const naturalEnd = startOfNextUtcMonth(cursor);
if (naturalEnd.getTime() > now.getTime()) break;
const windowStart = laterOf(cursor, anchor);
if (windowStart.getTime() < naturalEnd.getTime()) {
out.push({ windowStart, windowEnd: naturalEnd, label: formatMonthLabel(windowStart) });
}
cursor = naturalEnd;
}
return out;
}
/** Every completed calendar year from the anchor through `now`, oldest first. */
export function completedYearWindows(anchor: Date, now: Date): CalendarWindow[] {
const out: CalendarWindow[] = [];
if (!Number.isFinite(anchor.getTime()) || !Number.isFinite(now.getTime())) return out;
if (now.getTime() < anchor.getTime()) return out;
let cursor = startOfUtcYear(anchor);
for (let guard = 0; guard < MAX_WINDOWS; guard += 1) {
const naturalEnd = startOfNextUtcYear(cursor);
if (naturalEnd.getTime() > now.getTime()) break;
const windowStart = laterOf(cursor, anchor);
if (windowStart.getTime() < naturalEnd.getTime()) {
out.push({ windowStart, windowEnd: naturalEnd, label: formatYearLabel(windowStart) });
}
cursor = naturalEnd;
}
return out;
}

View file

@ -1,84 +0,0 @@
/**
* Pure anchored-period math for minigame scoring periods.
*
* No Payload import: safe for the client and for unit tests. Periods are fixed
* `periodLengthDays`-long blocks anchored at the `minigame-rules.anchorDate`.
* Period `index` 0 starts exactly at the anchor. Instants before the anchor
* have no period (`null`).
*/
const DAY_MS = 86_400_000;
const MONTHS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
] as const;
export interface DerivedPeriod {
/** Zero-based period number; 0 is the first period at the anchor. */
index: number;
/** Inclusive UTC start instant. */
startDate: Date;
/** Exclusive UTC end instant (the instant the next period begins). */
endDate: Date;
/** Human label, e.g. "Oct 12 to Oct 25, 2026". */
label: string;
}
const utcDate = (ms: number): { month: number; day: number; year: number } => {
const d = new Date(ms);
return { month: d.getUTCMonth(), day: d.getUTCDate(), year: d.getUTCFullYear() };
};
/** Label a period by its inclusive start and inclusive last day. */
export function formatPeriodLabel(startMs: number, endMs: number): string {
const start = utcDate(startMs);
// `endMs` is exclusive, so the last covered instant is endMs - 1ms.
const end = utcDate(endMs - 1);
const sameYear = start.year === end.year;
const startText = sameYear
? `${MONTHS[start.month]} ${start.day}`
: `${MONTHS[start.month]} ${start.day}, ${start.year}`;
return `${startText} to ${MONTHS[end.month]} ${end.day}, ${end.year}`;
}
/**
* Derive the anchored period containing `instant`.
* Returns `null` for instants before the anchor or when inputs are unusable.
*/
export function derivePeriodForInstant(
anchor: Date,
periodLengthDays: number,
instant: Date,
): DerivedPeriod | null {
const anchorMs = anchor.getTime();
const instantMs = instant.getTime();
const lengthMs = periodLengthDays * DAY_MS;
if (!Number.isFinite(anchorMs) || !Number.isFinite(instantMs) || !(lengthMs > 0)) return null;
if (instantMs < anchorMs) return null;
const index = Math.floor((instantMs - anchorMs) / lengthMs);
const startMs = anchorMs + index * lengthMs;
const endMs = startMs + lengthMs;
return {
index,
startDate: new Date(startMs),
endDate: new Date(endMs),
label: formatPeriodLabel(startMs, endMs),
};
}
/** Exclusive end instant of the period with the given 0-based index. */
export function periodStartForIndex(anchor: Date, periodLengthDays: number, index: number): Date {
return new Date(anchor.getTime() + index * periodLengthDays * DAY_MS);
}

View file

@ -1,48 +0,0 @@
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;
}

View file

@ -1,440 +0,0 @@
import type { Payload } from "payload";
import {
CORE_MINIGAME_KEYS,
MINIGAME_ACHIEVEMENT_TYPE_LABELS,
type MinigameAchievementType,
} from "@/lib/minigames/registry";
import { loadMinigameRegistry, periodScoringGameKeys } from "@/lib/minigames/loadRegistry";
import { notifyUser } from "@/lib/notifications";
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,
computePeriodAwards,
computeWindowChampion,
totalPointsByUser,
type LedgerEntry,
} from "./boards";
import { ensurePeriodForInstant } from "./record";
import { resolveMinigameRules, type ResolvedMinigameRules } from "./rules";
/**
* Period lifecycle: the close pipeline.
*
* The `period-tick` bin closes every anchored period whose window has ended,
* and the admin close/reopen control can close (early) or reopen one by hand.
* Both paths are idempotent: the close pipeline re-checks the period status
* before writing and the `achievements` unique `type:windowStart:user` key
* means a duplicate close inserts nothing (so the tick and a concurrent admin
* action cannot double-grant).
*
* Empty periods (no ledger entries) never get a row, so there is nothing to
* close for them; `ensureOpenPeriodForNow` still materializes the current
* period so boards render with an empty slate.
*/
type PayloadType = Payload;
/**
* 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;
label: string;
achievements: number;
}
export interface CalendarCloseSummary {
unit: "month" | "year";
label: string;
windowStart: string;
windowEnd: string;
/** 0 when the window had no entries and nobody was crowned. */
achievements: number;
}
export interface PeriodTickSummary {
/** Id of the period covering `now`, materialized if it was missing. */
createdPeriodId: number | null;
closed: ClosedPeriodSummary[];
/** Month/year windows crowned this run (usually empty). */
calendar: CalendarCloseSummary[];
}
const pointsForPeriod = (
entries: LedgerEntry[],
games: string[],
rules: ResolvedMinigameRules,
): Map<number, number> =>
totalPointsByUser(
games.map((game) =>
buildGameBoard(
entries.filter((entry) => entry.game === game),
rules.placementLadderTopN,
),
),
);
/**
* Placement points per player for the period immediately before the one that
* starts at `periodStartMs`. Returns null when there is no previous period
* (Period 1), which skips Most Improved.
*/
const previousPointsFor = async (
payload: PayloadType,
rules: ResolvedMinigameRules,
periodStartMs: number,
games: string[],
): Promise<Map<number, number> | null> => {
if (!rules.anchorDate) return null;
const derived = derivePeriodForInstant(
rules.anchorDate,
rules.periodLengthDays,
new Date(periodStartMs),
);
if (!derived || derived.index === 0) return null;
const previousStartIso = periodStartForIndex(
rules.anchorDate,
rules.periodLengthDays,
derived.index - 1,
).toISOString();
const previous = await payload.find({
collection: "minigame-periods",
where: { startDate: { equals: previousStartIso } },
limit: 1,
depth: 0,
overrideAccess: true,
});
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 fetchLedgerEntries(payload, { period: { equals: previousPeriod.id } });
return pointsForPeriod(entries, games, rules);
};
/**
* Notify a winner in-app. Fire-and-forget (notifyUser swallows errors) but
* awaited so the ordering after the achievement write is deterministic. Muteable
* through the `minigame:achievement` notification preference.
*/
const notifyAchievement = async (
payload: PayloadType,
input: { userId: number; type: MinigameAchievementType; windowLabel: string; detail: string },
): Promise<void> => {
const label = MINIGAME_ACHIEVEMENT_TYPE_LABELS[input.type] ?? input.type;
await notifyUser(payload, {
userId: input.userId,
type: "minigame:achievement",
title: `${label} earned for ${input.windowLabel}`,
message: `${input.detail}. See the honor roll on the minigame leaderboards.`,
link: "/minigames/leaderboards",
});
};
/** Insert one achievement unless its `type:windowStart:user` key already exists. */
const writeAchievement = async (
payload: PayloadType,
data: {
window: "period" | "month" | "year";
windowStart: string;
windowEnd: string;
type: MinigameAchievementType;
user: number;
value: number;
detail: string;
rank?: number;
},
): Promise<boolean> => {
try {
const existing = await payload.find({
collection: "achievements",
where: {
and: [
{ type: { equals: data.type } },
{ windowStart: { equals: data.windowStart } },
{ user: { equals: data.user } },
],
},
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existing.docs.length > 0) return false;
await payload.create({
collection: "achievements",
data: { ...data, rank: data.rank ?? 1 },
overrideAccess: true,
depth: 0,
});
return true;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
try {
payload.logger.error(`[Minigames] Failed to write achievement: ${message}`);
} catch {
// ignore logging failures
}
return false;
}
};
/**
* Close a single period: compute its boards and awards, write the achievement
* rows, then mark it closed. Returns null when the period is missing or is not
* open (already closed, possibly by a concurrent closer).
*/
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 })
.catch(() => null);
if (!period || period.status !== "open") return null;
const rules = await resolveMinigameRules(payload);
const periodGames = games ?? (await resolvePeriodGames(payload));
const entries = await fetchLedgerEntries(payload, { period: { equals: periodId } });
const previousPointsByUser = await previousPointsFor(
payload,
rules,
new Date(period.startDate).getTime(),
periodGames,
);
const awards = computePeriodAwards({
entries,
games: periodGames,
topN: rules.placementLadderTopN,
precisionMinAttempts: rules.precisionMinAttempts,
previousPointsByUser,
});
for (const award of awards) {
const wrote = await writeAchievement(payload, {
window: "period",
windowStart: period.startDate,
windowEnd: period.endDate,
type: award.type,
user: award.userId,
value: award.value,
detail: award.detail,
});
if (wrote) {
await notifyAchievement(payload, {
userId: award.userId,
type: award.type,
windowLabel: period.label,
detail: award.detail,
});
}
}
// Re-check before committing: a concurrent closer may have won the race.
const fresh = await payload
.findByID({ collection: "minigame-periods", id: periodId, depth: 0, overrideAccess: true })
.catch(() => null);
if (!fresh || fresh.status !== "open") return null;
await payload.update({
collection: "minigame-periods",
id: periodId,
data: { status: "closed", closedAt: now.toISOString() },
overrideAccess: true,
depth: 0,
});
await emitGameEvent(payload, {
type: EventTypes.MinigamePeriodClosed,
message: `Minigame period "${period.label}" closed with ${awards.length} achievement(s).`,
data: { periodId, label: period.label, achievements: awards.length },
});
return { periodId, label: period.label, achievements: awards.length };
}
/**
* Crown the champion of every completed calendar month and year. Idempotent:
* a window whose achievement already exists is skipped, so re-running the tick
* never double-grants. Windows with no entries are simply left unchampioned.
*/
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;
windows: ReturnType<typeof completedMonthWindows>;
}> = [
{ unit: "month", type: "player-of-month", windows: completedMonthWindows(rules.anchorDate, now) },
{ unit: "year", type: "player-of-year", windows: completedYearWindows(rules.anchorDate, now) },
];
const summaries: CalendarCloseSummary[] = [];
for (const plan of plans) {
for (const window of plan.windows) {
const windowStart = window.windowStart.toISOString();
const windowEnd = window.windowEnd.toISOString();
const existing = await payload.find({
collection: "achievements",
where: { and: [{ type: { equals: plan.type } }, { windowStart: { equals: windowStart } }] },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existing.docs.length > 0) continue;
// 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 fetchLedgerEntries(payload, {
and: [
{ occurredAt: { greater_than_equal: windowStart } },
{ occurredAt: { less_than: windowEnd } },
],
});
const champion = computeWindowChampion({
entries,
games: periodGames,
topN: rules.placementLadderTopN,
});
if (!champion) continue;
const detail = `${champion.points} placement point${champion.points === 1 ? "" : "s"} across ${champion.boards} board${champion.boards === 1 ? "" : "s"}`;
const wrote = await writeAchievement(payload, {
window: plan.unit,
windowStart,
windowEnd,
type: plan.type,
user: champion.userId,
value: champion.points,
detail,
});
if (wrote) {
await emitGameEvent(payload, {
type: EventTypes.MinigamePeriodClosed,
message: `Minigame ${plan.unit} "${window.label}" closed with 1 achievement.`,
data: { unit: plan.unit, label: window.label, windowStart },
});
await notifyAchievement(payload, {
userId: champion.userId,
type: plan.type,
windowLabel: window.label,
detail,
});
summaries.push({ unit: plan.unit, label: window.label, windowStart, windowEnd, achievements: 1 });
}
}
}
return summaries;
}
/**
* The tick sweep: close every open period whose window has ended, crown any
* completed month/year window, then materialize the period covering `now`.
* Idempotent and safe to re-run.
*/
export async function closeDuePeriods(
payload: PayloadType,
now: Date = new Date(),
): Promise<PeriodTickSummary> {
const rules = await resolveMinigameRules(payload);
if (!rules.enabled || !rules.anchorDate) {
return { createdPeriodId: null, closed: [], calendar: [] };
}
const due = await payload.find({
collection: "minigame-periods",
where: {
and: [{ status: { equals: "open" } }, { endDate: { less_than_equal: now.toISOString() } }],
},
sort: "startDate",
limit: 200,
depth: 0,
overrideAccess: true,
});
const games = await resolvePeriodGames(payload);
const closed: ClosedPeriodSummary[] = [];
for (const period of due.docs) {
const summary = await closePeriodById(payload, period.id, now, games);
if (summary) closed.push(summary);
}
const calendar = await closeCalendarWindows(payload, rules, now, games);
const createdPeriodId = await ensurePeriodForInstant(payload, rules, now);
return { createdPeriodId, closed, calendar };
}
/**
* Reopen a period: delete its awarded achievements so a future close can
* re-grant them, then flip it back to open. Service-only (the admin override).
*/
export async function reopenPeriodById(
payload: PayloadType,
periodId: number,
): Promise<ClosedPeriodSummary | null> {
const period = await payload
.findByID({ collection: "minigame-periods", id: periodId, depth: 0, overrideAccess: true })
.catch(() => null);
if (!period) return null;
await payload.delete({
collection: "achievements",
where: {
and: [{ window: { equals: "period" } }, { windowStart: { equals: period.startDate } }],
},
overrideAccess: true,
});
await payload.update({
collection: "minigame-periods",
id: periodId,
data: { status: "open", closedAt: null },
overrideAccess: true,
depth: 0,
});
return { periodId, label: period.label, achievements: 0 };
}
/** Close the most recent open period (the admin early-close override). */
export async function closeLatestOpenPeriod(
payload: PayloadType,
now: Date = new Date(),
): Promise<ClosedPeriodSummary | null> {
const latest = await payload.find({
collection: "minigame-periods",
where: { status: { equals: "open" } },
sort: "-startDate",
limit: 1,
depth: 0,
overrideAccess: true,
});
const target = latest.docs[0];
if (!target) return null;
return closePeriodById(payload, target.id, now);
}

View file

@ -1,122 +0,0 @@
import type { Payload } from "payload";
import { derivePeriodForInstant, periodStartForIndex } from "./derive";
import { resolveMinigameRules, type ResolvedMinigameRules } from "./rules";
/**
* Single write path for the `minigame-entries` append-only ledger.
*
* Called by the five Core minigame submit actions AFTER their profile update,
* so a completed, scored run is always recorded (and never allowed to break
* the game submission: every failure is swallowed and logged).
*
* The period is resolved lazily: the first entry in an anchored period creates
* that period (idempotently; a unique `startDate` guards concurrent writers),
* so the ledger has a period reference even before the period tick has ever
* run. Phase 2's close pipeline then closes it at its end boundary.
*/
export interface RecordMinigameEntryInput {
payload: Payload;
userId: number;
/** Registry key (minigames.key), e.g. "flappy". */
game: string;
score: number;
durationMs: number;
accuracy?: number | null;
mode?: string | null;
meta?: Record<string, unknown> | null;
/** Injectable clock, for tests. */
now?: Date;
}
const findPeriodIdByStart = async (payload: Payload, startIso: string): Promise<number | null> => {
const res = await payload.find({
collection: "minigame-periods",
where: { startDate: { equals: startIso } },
limit: 1,
depth: 0,
overrideAccess: true,
});
return res.docs[0]?.id ?? null;
};
/** Find or lazily create the anchored period containing `instant`. */
export const ensurePeriodForInstant = async (
payload: Payload,
rules: ResolvedMinigameRules,
instant: Date,
): Promise<number | null> => {
if (!rules.enabled || !rules.anchorDate) return null;
const derived = derivePeriodForInstant(rules.anchorDate, rules.periodLengthDays, instant);
if (!derived) return null;
const startIso = derived.startDate.toISOString();
const existingId = await findPeriodIdByStart(payload, startIso);
if (existingId != null) return existingId;
let previousPeriodId: number | null = null;
if (derived.index > 0) {
const prevStart = periodStartForIndex(
rules.anchorDate,
rules.periodLengthDays,
derived.index - 1,
).toISOString();
previousPeriodId = await findPeriodIdByStart(payload, prevStart);
}
try {
const created = await payload.create({
collection: "minigame-periods",
data: {
startDate: startIso,
endDate: derived.endDate.toISOString(),
label: derived.label,
status: "open",
previousPeriod: previousPeriodId,
},
overrideAccess: true,
depth: 0,
});
return created.id;
} catch {
// Lost a race to another writer; the unique startDate means ours is there.
return findPeriodIdByStart(payload, startIso);
}
};
export async function recordMinigameEntry(input: RecordMinigameEntryInput): Promise<void> {
const { payload } = input;
try {
const instant = input.now ?? new Date();
const rules = await resolveMinigameRules(payload);
const periodId = await ensurePeriodForInstant(payload, rules, instant);
const durationMs =
Number.isFinite(input.durationMs) && input.durationMs >= 0 ? Math.round(input.durationMs) : 0;
await payload.create({
collection: "minigame-entries",
data: {
user: input.userId,
game: input.game,
mode: input.mode ?? null,
score: input.score,
accuracy: input.accuracy ?? null,
durationMs,
occurredAt: instant.toISOString(),
period: periodId,
meta: input.meta ?? null,
},
overrideAccess: true,
depth: 0,
});
} catch (error) {
// Never fail the player's submission because the ledger hiccuped.
const message = error instanceof Error ? error.message : String(error);
try {
payload.logger.error(`[Minigames] Failed to record ${input.game} entry: ${message}`);
} catch {
// ignore logging failures
}
}
}

View file

@ -1,60 +0,0 @@
import type { Payload } from "payload";
import {
PERIOD_LENGTH_DAYS_DEFAULT,
PLACEMENT_LADDER_TOP_N_DEFAULT,
PRECISION_MIN_ATTEMPTS_DEFAULT,
} from "@/lib/minigames/registry";
/**
* Resolved `minigame-rules` tuning, with defaults applied. Read by the entry
* recorder, the close pipeline and the leaderboard endpoint so they all agree
* on the anchor, period length and ladder.
*/
export interface ResolvedMinigameRules {
enabled: boolean;
/** Null when unset/unparseable; period math is impossible without it. */
anchorDate: Date | null;
periodLengthDays: number;
placementLadderTopN: number;
precisionMinAttempts: number;
}
const positiveIntOr = (value: unknown, fallback: number): number =>
typeof value === "number" && Number.isFinite(value) && value > 0
? Math.floor(value)
: fallback;
/**
* Read the `minigame-rules` global and normalize it. Never throws: a failed
* read degrades to "disabled", so callers treat the feature as off rather than
* crashing.
*/
export async function resolveMinigameRules(payload: Payload): Promise<ResolvedMinigameRules> {
try {
const rules = await payload.findGlobal({
slug: "minigame-rules",
depth: 0,
overrideAccess: true,
});
const anchorRaw = rules?.anchorDate;
const anchor = anchorRaw ? new Date(anchorRaw) : null;
return {
enabled: rules?.enabled !== false,
anchorDate: anchor && Number.isFinite(anchor.getTime()) ? anchor : null,
periodLengthDays: positiveIntOr(rules?.periodLengthDays, PERIOD_LENGTH_DAYS_DEFAULT),
placementLadderTopN: positiveIntOr(rules?.placementLadderTopN, PLACEMENT_LADDER_TOP_N_DEFAULT),
precisionMinAttempts: positiveIntOr(
rules?.precisionMinAttempts,
PRECISION_MIN_ATTEMPTS_DEFAULT,
),
};
} catch {
return {
enabled: false,
anchorDate: null,
periodLengthDays: PERIOD_LENGTH_DAYS_DEFAULT,
placementLadderTopN: PLACEMENT_LADDER_TOP_N_DEFAULT,
precisionMinAttempts: PRECISION_MIN_ATTEMPTS_DEFAULT,
};
}
}

View file

@ -1,283 +0,0 @@
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 };

View file

@ -1,205 +0,0 @@
/**
* Canonical registry data for the minigames feature.
*
* Pure and client-safe (no Payload import): the `minigames` collection seeds
* its rows from `BUILTIN_MINIGAMES`, the `minigame-rules` global seeds its
* defaults from `MINIGAME_RULE_DEFAULTS`, and the sidebar can read the same
* list without a Payload round trip.
*
* `icon` is a lucide-react icon name (a string), mapped to a component in the
* client. Keeping it as data means the registry can be edited in the admin
* panel without shipping new code.
*/
export type MinigameCategory = "core" | "cardtable";
export type MinigameStatus = "active" | "retired" | "upcoming";
/** The five period-scoring games. Poker and Blackjack stay out of periods. */
export const CORE_MINIGAME_KEYS = [
"flappy",
"eod",
"radio",
"qualification",
"opord",
] as const;
export const CARDTABLE_MINIGAME_KEYS = ["poker", "blackjack"] as const;
export type CoreMinigameKey = (typeof CORE_MINIGAME_KEYS)[number];
export type MinigameKey = CoreMinigameKey | (typeof CARDTABLE_MINIGAME_KEYS)[number];
export interface BuiltinMinigame {
key: string;
label: string;
description: string;
route: string;
/** lucide-react icon name, resolved in the client. */
icon: string;
category: MinigameCategory;
status: MinigameStatus;
/** Sort order within the sidebar / leaderboards. */
order: number;
/** Whether this game's ledger entries feed anchored period boards. */
countsForPeriods: boolean;
/** Label for the score column, e.g. "Passes", "Time". */
scoreLabel: string;
}
/** The seven built-in games, seeded into the `minigames` registry collection. */
export const BUILTIN_MINIGAMES: BuiltinMinigame[] = [
{
key: "flappy",
label: "Flight Simulator",
description: "Guide an aircraft through an obstacle course for as many passes as you can manage.",
route: "/minigames/flappy",
icon: "Bird",
category: "core",
status: "active",
order: 1,
countsForPeriods: true,
scoreLabel: "Passes",
},
{
key: "eod",
label: "Minefield Clearance",
description: "Clear a minefield without detonating a charge, against the clock.",
route: "/minigames/eod",
icon: "Bomb",
category: "core",
status: "active",
order: 2,
countsForPeriods: true,
scoreLabel: "Score",
},
{
key: "radio",
label: "Radio Traffic",
description: "Transcribe and repeat radio traffic accurately, sprint or watch mode.",
route: "/minigames/radio",
icon: "Radio",
category: "core",
status: "active",
order: 3,
countsForPeriods: true,
scoreLabel: "Score",
},
{
key: "qualification",
label: "Qualification Course",
description: "Range drill: engage targets quickly and accurately while sparing civilians.",
route: "/minigames/qualification",
icon: "Crosshair",
category: "core",
status: "active",
order: 4,
countsForPeriods: true,
scoreLabel: "Score",
},
{
key: "opord",
label: "OPORD Recall",
description: "Study a briefing, then recall its details under time pressure.",
route: "/minigames/opord",
icon: "FileTextIcon",
category: "core",
status: "active",
order: 5,
countsForPeriods: true,
scoreLabel: "Score",
},
{
key: "poker",
label: "Poker",
description: "Cardtable game. Play chips earned from Core minigames. Keeps its own all-time board.",
route: "/minigames/poker",
icon: "Spade",
category: "cardtable",
status: "active",
order: 6,
countsForPeriods: false,
scoreLabel: "Chips",
},
{
key: "blackjack",
label: "Blackjack",
description: "Cardtable game. Play chips earned from Core minigames. Keeps its own all-time board.",
route: "/minigames/blackjack",
icon: "Club",
category: "cardtable",
status: "active",
order: 7,
countsForPeriods: false,
scoreLabel: "Chips",
},
];
/** 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;
export const MINIGAME_ACHIEVEMENT_TYPES = [
"period-champion",
"player-of-month",
"player-of-year",
"diligence",
"dedication",
"precision",
"most-improved",
] as const;
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,
periodLengthDays: PERIOD_LENGTH_DAYS_DEFAULT,
anchorDate: MINIGAME_ANCHOR_DATE,
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

@ -24,7 +24,6 @@ export const MUTEABLE_NOTIFICATION_TYPES = [
{ label: "Role slot promotions", value: "mission:role-promoted" },
{ label: "Contribution XP granted", value: "contribution:xp-granted" },
{ label: "Contribution XP revoked", value: "contribution:xp-revoked" },
{ label: "Minigame achievements", value: "minigame:achievement" },
] as const;
export type MuteableNotificationType = (typeof MUTEABLE_NOTIFICATION_TYPES)[number]["value"];
export const MUTEABLE_NOTIFICATION_VALUES = MUTEABLE_NOTIFICATION_TYPES.map((t) => t.value);

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -1,14 +0,0 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "minigame_entries" ADD COLUMN "occurred_at" timestamp(3) with time zone;
CREATE INDEX "minigame_entries_occurred_at_idx" ON "minigame_entries" USING btree ("occurred_at");
UPDATE "minigame_entries" SET "occurred_at" = "created_at" WHERE "occurred_at" IS NULL;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP INDEX "minigame_entries_occurred_at_idx";
ALTER TABLE "minigame_entries" DROP COLUMN "occurred_at";`)
}

View file

@ -120,8 +120,6 @@ import * as migration_20261009_160740_add_campaign_on_hold_status from './202610
import * as migration_20261009_185259_add_wiki_featured_curation from './20261009_185259_add_wiki_featured_curation';
import * as migration_20261009_201920_add_contribution_entries from './20261009_201920_add_contribution_entries';
import * as migration_20261010_050644_add_mission_threat_assessment from './20261010_050644_add_mission_threat_assessment';
import * as migration_20261011_195306_add_minigame_periods from './20261011_195306_add_minigame_periods';
import * as migration_20261011_201531_add_minigame_entry_occurred_at from './20261011_201531_add_minigame_entry_occurred_at';
export const migrations = [
{
@ -732,16 +730,6 @@ export const migrations = [
{
up: migration_20261010_050644_add_mission_threat_assessment.up,
down: migration_20261010_050644_add_mission_threat_assessment.down,
name: '20261010_050644_add_mission_threat_assessment',
},
{
up: migration_20261011_195306_add_minigame_periods.up,
down: migration_20261011_195306_add_minigame_periods.down,
name: '20261011_195306_add_minigame_periods',
},
{
up: migration_20261011_201531_add_minigame_entry_occurred_at.up,
down: migration_20261011_201531_add_minigame_entry_occurred_at.down,
name: '20261011_201531_add_minigame_entry_occurred_at'
name: '20261010_050644_add_mission_threat_assessment'
},
];

File diff suppressed because it is too large Load diff

View file

@ -151,10 +151,6 @@ export interface Config {
'custom-minefield-scores': CustomMinefieldScore;
'custom-radio-tests': CustomRadioTest;
'custom-radio-test-scores': CustomRadioTestScore;
minigames: Minigame;
'minigame-entries': MinigameEntry;
'minigame-periods': MinigamePeriod;
achievements: Achievement;
forms: Form;
'form-submissions': FormSubmission;
'plugin-ai-instructions': PluginAiInstruction;
@ -256,10 +252,6 @@ export interface Config {
'custom-minefield-scores': CustomMinefieldScoresSelect<false> | CustomMinefieldScoresSelect<true>;
'custom-radio-tests': CustomRadioTestsSelect<false> | CustomRadioTestsSelect<true>;
'custom-radio-test-scores': CustomRadioTestScoresSelect<false> | CustomRadioTestScoresSelect<true>;
minigames: MinigamesSelect<false> | MinigamesSelect<true>;
'minigame-entries': MinigameEntriesSelect<false> | MinigameEntriesSelect<true>;
'minigame-periods': MinigamePeriodsSelect<false> | MinigamePeriodsSelect<true>;
achievements: AchievementsSelect<false> | AchievementsSelect<true>;
forms: FormsSelect<false> | FormsSelect<true>;
'form-submissions': FormSubmissionsSelect<false> | FormSubmissionsSelect<true>;
'plugin-ai-instructions': PluginAiInstructionsSelect<false> | PluginAiInstructionsSelect<true>;
@ -276,12 +268,10 @@ export interface Config {
globals: {
'game-rules': GameRule;
shims: Shim;
'minigame-rules': MinigameRule;
};
globalsSelect: {
'game-rules': GameRulesSelect<false> | GameRulesSelect<true>;
shims: ShimsSelect<false> | ShimsSelect<true>;
'minigame-rules': MinigameRulesSelect<false> | MinigameRulesSelect<true>;
};
locale: null;
widgets: {
@ -492,7 +482,6 @@ export interface User {
| 'mission:role-promoted'
| 'contribution:xp-granted'
| 'contribution:xp-revoked'
| 'minigame:achievement'
)[]
| null;
};
@ -532,7 +521,6 @@ export interface User {
| 'mission:role-promoted'
| 'contribution:xp-granted'
| 'contribution:xp-revoked'
| 'minigame:achievement'
)[]
| null;
};
@ -931,8 +919,6 @@ export interface Role {
| 'game-rules:update'
| 'shims:read'
| 'shims:update'
| 'minigame-rules:read'
| 'minigame-rules:update'
| 'logistics:manage'
| 'intelligence:manage'
| 'profiles:intel_excerpt:update'
@ -946,27 +932,6 @@ export interface Role {
| 'custom-radio-tests:update'
| 'custom-radio-tests:delete'
| 'custom-radio-test-scores:delete'
| 'minigames:create'
| 'minigames:read'
| 'minigames:update'
| 'minigames:delete'
| 'admin:minigames:manage'
| 'minigame-entries:create'
| 'minigame-entries:read'
| 'minigame-entries:update'
| 'minigame-entries:delete'
| 'admin:minigame-entries:manage'
| 'minigame-periods:create'
| 'minigame-periods:read'
| 'minigame-periods:update'
| 'minigame-periods:delete'
| 'minigame-periods:close'
| 'admin:minigame-periods:manage'
| 'achievements:create'
| 'achievements:read'
| 'achievements:update'
| 'achievements:delete'
| 'admin:achievements:manage'
)[]
| null;
/**
@ -3040,8 +3005,6 @@ export interface GameEventLog {
| 'game-rules:update'
| 'shims:read'
| 'shims:update'
| 'minigame-rules:read'
| 'minigame-rules:update'
| 'logistics:manage'
| 'intelligence:manage'
| 'profiles:intel_excerpt:update'
@ -3055,27 +3018,6 @@ export interface GameEventLog {
| 'custom-radio-tests:update'
| 'custom-radio-tests:delete'
| 'custom-radio-test-scores:delete'
| 'minigames:create'
| 'minigames:read'
| 'minigames:update'
| 'minigames:delete'
| 'admin:minigames:manage'
| 'minigame-entries:create'
| 'minigame-entries:read'
| 'minigame-entries:update'
| 'minigame-entries:delete'
| 'admin:minigame-entries:manage'
| 'minigame-periods:create'
| 'minigame-periods:read'
| 'minigame-periods:update'
| 'minigame-periods:delete'
| 'minigame-periods:close'
| 'admin:minigame-periods:manage'
| 'achievements:create'
| 'achievements:read'
| 'achievements:update'
| 'achievements:delete'
| 'admin:achievements:manage'
)[]
| null;
timestamp: string;
@ -5971,139 +5913,6 @@ export interface CustomRadioTestScore {
updatedAt: string;
createdAt: string;
}
/**
* Registry of minigames. Retired games keep their history but leave the nav and future period scoring.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "minigames".
*/
export interface Minigame {
id: number;
/**
* Stable machine key (e.g. flappy, eod). Ledger rows reference it; avoid changing it after launch.
*/
key: string;
label: string;
description?: string | null;
/**
* Frontend path, e.g. /minigames/flappy.
*/
route: string;
/**
* lucide-react icon name, mapped in the client.
*/
icon?: string | null;
category: 'core' | 'cardtable';
status: 'active' | 'upcoming' | 'retired';
order: number;
/**
* When on, ledger entries for this game feed anchored period boards.
*/
countsForPeriods?: boolean | null;
scoreLabel?: string | null;
updatedAt: string;
createdAt: string;
}
/**
* Append-only ledger of completed minigame runs. Read-only here; writes flow through the minigame submit actions.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "minigame-entries".
*/
export interface MinigameEntry {
id: number;
user: number | User;
/**
* Registry key (minigames.key).
*/
game: string;
/**
* Mode or difficulty label when applicable (e.g. sprint, elite).
*/
mode?: string | null;
score: number;
/**
* When the run happened (server clock at submit). Calendar month/year windows score by this, not the row's createdAt.
*/
occurredAt?: string | null;
/**
* Fractional accuracy for games that score it.
*/
accuracy?: number | null;
/**
* Server-validated run duration in milliseconds.
*/
durationMs: number;
period?: (number | null) | MinigamePeriod;
/**
* Small extras (e.g. EOD win flags) that do not warrant a column.
*/
meta?:
| {
[k: string]: unknown;
}
| unknown[]
| string
| number
| boolean
| null;
updatedAt: string;
createdAt: string;
}
/**
* Anchored scoring periods. Read-only here; the period tick and the close/reopen control manage them.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "minigame-periods".
*/
export interface MinigamePeriod {
id: number;
/**
* Inclusive UTC start. Unique; drives period identity.
*/
startDate: string;
endDate: string;
label: string;
status: 'open' | 'closed';
closedAt?: string | null;
/**
* Previous period in the chain, for most-improved deltas.
*/
previousPeriod?: (number | null) | MinigamePeriod;
updatedAt: string;
createdAt: string;
}
/**
* Minigame achievements granted at period/month/year close. Read-only here; written by the close pipeline.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "achievements".
*/
export interface Achievement {
id: number;
window: 'period' | 'month' | 'year';
windowStart: string;
windowEnd: string;
type:
| 'period-champion'
| 'player-of-month'
| 'player-of-year'
| 'diligence'
| 'dedication'
| 'precision'
| 'most-improved';
user: number | User;
value: number;
/**
* Short human-readable context, e.g. '42 points across 5 boards'.
*/
detail?: string | null;
rank?: number | null;
announcedAt?: string | null;
discordMessageId?: string | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "forms".
@ -7886,78 +7695,6 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
minigames?: {
/**
* Allow clients to find minigames.
*/
find?: boolean | null;
/**
* Allow clients to create minigames.
*/
create?: boolean | null;
/**
* Allow clients to update minigames.
*/
update?: boolean | null;
/**
* Allow clients to delete minigames.
*/
delete?: boolean | null;
};
minigameEntries?: {
/**
* Allow clients to find minigame-entries.
*/
find?: boolean | null;
/**
* Allow clients to create minigame-entries.
*/
create?: boolean | null;
/**
* Allow clients to update minigame-entries.
*/
update?: boolean | null;
/**
* Allow clients to delete minigame-entries.
*/
delete?: boolean | null;
};
minigamePeriods?: {
/**
* Allow clients to find minigame-periods.
*/
find?: boolean | null;
/**
* Allow clients to create minigame-periods.
*/
create?: boolean | null;
/**
* Allow clients to update minigame-periods.
*/
update?: boolean | null;
/**
* Allow clients to delete minigame-periods.
*/
delete?: boolean | null;
};
achievements?: {
/**
* Allow clients to find achievements.
*/
find?: boolean | null;
/**
* Allow clients to create achievements.
*/
create?: boolean | null;
/**
* Allow clients to update achievements.
*/
update?: boolean | null;
/**
* Allow clients to delete achievements.
*/
delete?: boolean | null;
};
updatedAt: string;
createdAt: string;
enableAPIKey?: boolean | null;
@ -8321,22 +8058,6 @@ export interface PayloadLockedDocument {
relationTo: 'custom-radio-test-scores';
value: number | CustomRadioTestScore;
} | null)
| ({
relationTo: 'minigames';
value: number | Minigame;
} | null)
| ({
relationTo: 'minigame-entries';
value: number | MinigameEntry;
} | null)
| ({
relationTo: 'minigame-periods';
value: number | MinigamePeriod;
} | null)
| ({
relationTo: 'achievements';
value: number | Achievement;
} | null)
| ({
relationTo: 'forms';
value: number | Form;
@ -10713,73 +10434,6 @@ export interface CustomRadioTestScoresSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "minigames_select".
*/
export interface MinigamesSelect<T extends boolean = true> {
key?: T;
label?: T;
description?: T;
route?: T;
icon?: T;
category?: T;
status?: T;
order?: T;
countsForPeriods?: T;
scoreLabel?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "minigame-entries_select".
*/
export interface MinigameEntriesSelect<T extends boolean = true> {
user?: T;
game?: T;
mode?: T;
score?: T;
occurredAt?: T;
accuracy?: T;
durationMs?: T;
period?: T;
meta?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "minigame-periods_select".
*/
export interface MinigamePeriodsSelect<T extends boolean = true> {
startDate?: T;
endDate?: T;
label?: T;
status?: T;
closedAt?: T;
previousPeriod?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "achievements_select".
*/
export interface AchievementsSelect<T extends boolean = true> {
window?: T;
windowStart?: T;
windowEnd?: T;
type?: T;
user?: T;
value?: T;
detail?: T;
rank?: T;
announcedAt?: T;
discordMessageId?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "forms_select".
@ -11668,38 +11322,6 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
minigames?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
minigameEntries?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
minigamePeriods?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
achievements?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
updatedAt?: T;
createdAt?: T;
enableAPIKey?: T;
@ -11919,35 +11541,6 @@ export interface Shim {
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "minigame-rules".
*/
export interface MinigameRule {
id: number;
/**
* Master gate for anchored scoring periods and achievements. When off, the period tick does nothing and period boards fall back to All-Time.
*/
enabled?: boolean | null;
/**
* Length of each scoring period in days.
*/
periodLengthDays: number;
/**
* Start of Period 1 (UTC). Immutable once set: changing it re-slices every period, so confirm before editing.
*/
anchorDate: string;
/**
* How many placements earn points on each board (1st = N points down to Nth = 1). Points sum across the five Core boards.
*/
placementLadderTopN: number;
/**
* Minimum qualifying attempts (Aim Trainer + Radio + OPORD) for the Precision achievement.
*/
precisionMinAttempts: number;
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "game-rules_select".
@ -12019,20 +11612,6 @@ export interface ShimsSelect<T extends boolean = true> {
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "minigame-rules_select".
*/
export interface MinigameRulesSelect<T extends boolean = true> {
enabled?: T;
periodLengthDays?: T;
anchorDate?: T;
placementLadderTopN?: T;
precisionMinAttempts?: T;
updatedAt?: T;
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "collections_widget".

View file

@ -90,11 +90,6 @@ import { CustomMinefields } from "@/collections/minigames/CustomMinefields";
import { CustomMinefieldScores } from "@/collections/minigames/CustomMinefieldScores";
import { CustomRadioTests } from "@/collections/minigames/CustomRadioTests";
import { CustomRadioTestScores } from "@/collections/minigames/CustomRadioTestScores";
import { Minigames } from "@/collections/minigames/Minigames";
import { MinigameEntries } from "@/collections/minigames/MinigameEntries";
import { MinigamePeriods } from "@/collections/minigames/MinigamePeriods";
import { Achievements } from "@/collections/minigames/Achievements";
import { MinigameRules } from "@/collections/game/MinigameRules";
import { RibbonSubmissions } from "@/collections/users/RibbonSubmissions";
import { PromotionNominations } from "@/collections/users/PromotionNominations";
import { LeadershipTransfers } from "@/collections/users/LeadershipTransfers";
@ -382,10 +377,6 @@ const collections = [
CustomMinefieldScores,
CustomRadioTests,
CustomRadioTestScores,
Minigames,
MinigameEntries,
MinigamePeriods,
Achievements,
];
// Scoped admin pages: a user needs BOTH `<slug>:read` AND `admin:<slug>:manage`
@ -461,7 +452,7 @@ export default buildConfig({
},
},
},
globals: [GameRules, Shims, MinigameRules],
globals: [GameRules, Shims],
collections: scopedCollections,
editor: lexicalEditor({
features: ({ defaultFeatures }) => {
@ -508,10 +499,6 @@ export default buildConfig({
scriptPath: path.resolve(dirname, "scripts/economyTick.ts"),
key: "economy-tick",
},
{
scriptPath: path.resolve(dirname, "scripts/periodTick.ts"),
key: "period-tick",
},
{
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
key: "generate-mission",

View file

@ -734,13 +734,6 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "shims:update", label: "Update" },
],
},
{
group: "Minigame Rules (Global)",
permissions: [
{ value: "minigame-rules:read", label: "Read" },
{ value: "minigame-rules:update", label: "Update" },
],
},
// ---- Special / Feature-area ----------------------------------------------
{
@ -778,27 +771,6 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "custom-radio-tests:update", label: "Edit Any Custom Radio Test" },
{ value: "custom-radio-tests:delete", label: "Delete Custom Radio Tests" },
{ value: "custom-radio-test-scores:delete", label: "Delete Custom Radio Test Scores" },
{ value: "minigames:create", label: ["Registry", "Create"] },
{ value: "minigames:read", label: ["Registry", "Read"] },
{ value: "minigames:update", label: ["Registry", "Update"] },
{ value: "minigames:delete", label: ["Registry", "Delete"] },
{ value: "admin:minigames:manage", label: ["Registry", "Manage Admin Page"] },
{ value: "minigame-entries:create", label: ["Entries", "Create"] },
{ value: "minigame-entries:read", label: ["Entries", "Read"] },
{ value: "minigame-entries:update", label: ["Entries", "Update"] },
{ value: "minigame-entries:delete", label: ["Entries", "Delete"] },
{ value: "admin:minigame-entries:manage", label: ["Entries", "Manage Admin Page"] },
{ value: "minigame-periods:create", label: ["Periods", "Create"] },
{ value: "minigame-periods:read", label: ["Periods", "Read"] },
{ value: "minigame-periods:update", label: ["Periods", "Update"] },
{ value: "minigame-periods:delete", label: ["Periods", "Delete"] },
{ value: "minigame-periods:close", label: ["Periods", "Close or Reopen"] },
{ value: "admin:minigame-periods:manage", label: ["Periods", "Manage Admin Page"] },
{ value: "achievements:create", label: ["Achievements", "Create"] },
{ value: "achievements:read", label: ["Achievements", "Read"] },
{ value: "achievements:update", label: ["Achievements", "Update"] },
{ value: "achievements:delete", label: ["Achievements", "Delete"] },
{ value: "admin:achievements:manage", label: ["Achievements", "Manage Admin Page"] },
],
},
];
@ -1130,8 +1102,6 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"game-rules:update",
"shims:read",
"shims:update",
"minigame-rules:read",
"minigame-rules:update",
"announcements:create",
"announcements:read",
"announcements:update",
@ -1164,27 +1134,6 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"custom-radio-tests:update",
"custom-radio-tests:delete",
"custom-radio-test-scores:delete",
"minigames:create",
"minigames:read",
"minigames:update",
"minigames:delete",
"admin:minigames:manage",
"minigame-entries:create",
"minigame-entries:read",
"minigame-entries:update",
"minigame-entries:delete",
"admin:minigame-entries:manage",
"minigame-periods:create",
"minigame-periods:read",
"minigame-periods:update",
"minigame-periods:delete",
"minigame-periods:close",
"admin:minigame-periods:manage",
"achievements:create",
"achievements:read",
"achievements:update",
"achievements:delete",
"admin:achievements:manage",
];
/**

View file

@ -1,51 +0,0 @@
import type { SanitizedConfig } from "payload";
import { getPayload } from "payload";
import { closeDuePeriods } from "@/lib/minigames/periods/lifecycle";
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
export const script = async (config: SanitizedConfig) => {
const payload = await getPayload({ config });
const log = createBinLogger("period-tick", payload.logger);
try {
log.info("[Period Tick] Starting period tick...");
const nowIso = new Date().toISOString();
const summary = await closeDuePeriods(payload);
for (const closed of summary.closed) {
log.info(
`[Period Tick] Closed "${closed.label}" (id ${closed.periodId}) with ${closed.achievements} achievement(s).`,
);
}
for (const window of summary.calendar) {
log.info(`[Period Tick] Crowned the ${window.unit} "${window.label}" champion.`);
}
const notifyUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
const notifySecret = process.env.GAME_TICK_NOTIFY_SECRET;
if (notifySecret) {
await fetch(`${notifyUrl}/api/game-tick/notify`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-game-tick-secret": notifySecret,
},
body: JSON.stringify({ processedAt: nowIso, source: "period-tick" }),
}).catch((error: unknown) => {
log.error(`[Period Tick] Failed to notify app clients: ${errorMessage(error)}`);
});
} else {
log.warn("[Period Tick] GAME_TICK_NOTIFY_SECRET not set; skipping client notification");
}
log.info(`[Period Tick] Complete. Closed ${summary.closed.length} period(s).`);
process.exit(0);
} catch (error) {
log.error(
`[Period Tick] Fatal: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
);
process.exit(1);
}
};

View file

@ -2,7 +2,6 @@ import { seedRanks } from "@/tools/seed/seedRanks";
import { seedUsers } from "@/tools/seed/seedUsers";
import { seedFactions } from "@/tools/seed/seedFactions";
import { seedExperience } from "@/tools/seed/seedExperience";
import { seedMinigames } from "@/tools/seed/seedMinigames";
// Users
await seedUsers();
@ -11,6 +10,3 @@ await seedExperience();
// Intelligence
await seedFactions();
// Minigames
await seedMinigames();

View file

@ -1,77 +0,0 @@
import { getPayload } from "payload";
import config from "@payload-config";
import { BUILTIN_MINIGAMES, MINIGAME_RULE_DEFAULTS } from "@/lib/minigames/registry";
/**
* Idempotent seed for the minigame registry and rules global.
*
* Production gets the same defaults from the `add_minigame_periods` migration;
* this script exists for local resets and test/dev databases. Safe to re-run:
* existing registry rows are left untouched and only unset global fields are
* filled.
*/
export const seedMinigames = async (): Promise<void> => {
const payload = await getPayload({ config });
payload.logger.info("Seeding minigame registry...");
for (const game of BUILTIN_MINIGAMES) {
const existing = await payload.find({
collection: "minigames",
where: { key: { equals: game.key } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existing.docs.length > 0) {
payload.logger.info(` Minigame "${game.key}" already exists, skipping.`);
continue;
}
const created = await payload.create({
collection: "minigames",
data: game,
overrideAccess: true,
});
payload.logger.info(` Created minigame "${game.key}" (id=${created.id}).`);
}
payload.logger.info("Seeding minigame-rules defaults...");
const existingRules = (await payload.findGlobal({
slug: "minigame-rules",
depth: 0,
overrideAccess: true,
})) as unknown as Record<string, unknown> | null;
const current = existingRules ?? {};
const data: Record<string, unknown> = {};
if (current.enabled == null) data.enabled = MINIGAME_RULE_DEFAULTS.enabled;
if (current.periodLengthDays == null) data.periodLengthDays = MINIGAME_RULE_DEFAULTS.periodLengthDays;
if (!current.anchorDate) data.anchorDate = MINIGAME_RULE_DEFAULTS.anchorDate;
if (current.placementLadderTopN == null) {
data.placementLadderTopN = MINIGAME_RULE_DEFAULTS.placementLadderTopN;
}
if (current.precisionMinAttempts == null) {
data.precisionMinAttempts = MINIGAME_RULE_DEFAULTS.precisionMinAttempts;
}
if (Object.keys(data).length > 0) {
await payload.updateGlobal({
slug: "minigame-rules",
data,
overrideAccess: true,
});
payload.logger.info(` Seeded minigame-rules defaults: ${Object.keys(data).join(", ")}.`);
} else {
payload.logger.info(" minigame-rules already seeded.");
}
};
if (import.meta.main) {
await seedMinigames();
// CLI script: the Payload pool keeps the event loop alive after completion;
// exit explicitly (same convention as the game-tick bins).
process.exit(0);
}

View file

@ -89,7 +89,6 @@ export const EventTypes = {
MinigameCustomRadioEdit: "minigame:custom-radio-edit",
MinigameCustomRadioDelete: "minigame:custom-radio-delete",
MinigameCustomRadioPlay: "minigame:custom-radio-play",
MinigamePeriodClosed: "minigame:period-closed",
// Voiceover
VoiceoverSubmit: "voiceover:submit",

View file

@ -1,48 +0,0 @@
import { expect, test } from "@playwright/test";
/**
* Smoke coverage for the unified minigames leaderboards: the period view, the
* All-Time switch (which also reveals the cardtable games) and the inline period
* standings card on a game page.
*/
test.describe("Minigame leaderboards", () => {
test.beforeEach(async ({ page }) => {
await page.goto("/login");
await page.getByLabel("Username").fill("dev");
await page.getByLabel("Password").fill("Test123");
await page.getByRole("button", { name: "Log in" }).click();
await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 30_000 });
});
test("shows the period boards, game tabs and achievements", async ({ page }) => {
await page.goto("/minigames/leaderboards");
await expect(
page.getByRole("heading", { level: 1, name: "Minigame Leaderboards" }),
).toBeVisible();
await expect(page.getByRole("tab", { name: "Flight Simulator" })).toBeVisible();
await expect(page.getByRole("tab", { name: "OPORD Recall" })).toBeVisible();
// Cardtable games are not period-scored, so they only appear All-Time.
await expect(page.getByRole("tab", { name: "Poker" })).toHaveCount(0);
await expect(page.getByText("Achievements", { exact: true })).toBeVisible();
});
test("switching to All-Time surfaces every registered game", async ({ page }) => {
await page.goto("/minigames/leaderboards");
await page.getByRole("combobox").click();
await page.getByRole("option", { name: /All-Time/ }).click();
await expect(page.getByRole("tab", { name: "Poker" })).toBeVisible({ timeout: 15_000 });
await expect(page.getByRole("tab", { name: "Blackjack" })).toBeVisible();
});
test("a game page shows its anchored period standings card", async ({ page }) => {
await page.goto("/minigames/flappy");
await expect(
page.getByRole("heading", { level: 2, name: "Anchored period standings" }),
).toBeVisible();
await expect(page.getByRole("link", { name: "All boards" })).toBeVisible();
});
});

View file

@ -1,80 +0,0 @@
import { describe, expect, it } from "vitest";
import {
achievementWindowLabel,
groupAchievementsForAnnouncement,
renderAchievementAnnouncement,
type AchievementAnnouncementRow,
} from "@/bot/lib/achievementRender";
const row = (over: Partial<AchievementAnnouncementRow>): AchievementAnnouncementRow => ({
id: 1,
type: "period-champion",
window: "period",
windowStart: "2026-10-12T00:00:00.000Z",
windowEnd: "2026-10-26T00:00:00.000Z",
user: { id: 7, displayName: "Alpha" },
value: 42,
detail: "42 placement points across 5 boards",
...over,
});
describe("Achievement announcement rendering", () => {
it("labels period, month and year windows", () => {
expect(
achievementWindowLabel("period", "2026-10-12T00:00:00.000Z", "2026-10-26T00:00:00.000Z"),
).toBe("Oct 12 to Oct 25, 2026");
expect(
achievementWindowLabel("month", "2026-10-01T00:00:00.000Z", "2026-11-01T00:00:00.000Z"),
).toBe("October 2026");
expect(
achievementWindowLabel("year", "2026-01-01T00:00:00.000Z", "2027-01-01T00:00:00.000Z"),
).toBe("2026");
});
it("groups by window and orders awards canonically", () => {
const groups = groupAchievementsForAnnouncement([
row({ id: 3, type: "precision", user: { id: 9, username: "charlie" } }),
row({ id: 1, type: "period-champion" }),
row({ id: 2, type: "diligence", user: { id: 8, displayName: "Bravo" } }),
row({
id: 4,
type: "player-of-month",
window: "month",
windowStart: "2026-10-01T00:00:00.000Z",
windowEnd: "2026-11-01T00:00:00.000Z",
}),
]);
expect(groups).toHaveLength(2);
expect(groups.map((group) => group.label)).toEqual(["October 2026", "Oct 12 to Oct 25, 2026"]);
expect(groups[0].achievements.map((a) => a.type)).toEqual(["player-of-month"]);
expect(groups[1].achievements.map((a) => a.type)).toEqual([
"period-champion",
"diligence",
"precision",
]);
});
it("renders one embed shape per group with the winner and detail", () => {
const [group] = groupAchievementsForAnnouncement([
row({ id: 1, type: "period-champion" }),
row({ id: 2, type: "dedication", detail: "1h 12m played", user: { id: 8, displayName: "Bravo" } }),
]);
const rendered = renderAchievementAnnouncement(group);
expect(rendered.title).toBe("Minigame results: Oct 12 to Oct 25, 2026");
expect(rendered.fields).toEqual([
{ name: "Period Champion", value: "Alpha · 42 placement points across 5 boards" },
{ name: "Dedication (Most Time)", value: "Bravo · 1h 12m played" },
]);
});
it("falls back for an unknown award type and an unpopulated user", () => {
const [group] = groupAchievementsForAnnouncement([
row({ type: "mystery-award", user: 5, detail: null }),
]);
const rendered = renderAchievementAnnouncement(group);
expect(rendered.fields[0].name).toBe("mystery-award");
expect(rendered.fields[0].value).toBe("Unknown · 42");
});
});

View file

@ -1,120 +0,0 @@
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";
const ANCHOR = "2026-08-03T00:00:00.000Z";
const RUN = `mgnotif-${Date.now().toString(36)}`;
let payload: Payload;
let userA: number;
let originalRules: Record<string, unknown> | null = null;
const notificationsFor = async (userId: number) => {
const res = await payload.find({
collection: "user-notifications",
where: { and: [{ user: { equals: userId } }, { type: { equals: "minigame:achievement" } }] },
limit: 50,
depth: 0,
overrideAccess: true,
});
return res.docs;
};
describe("Minigame achievement notifications", () => {
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: "Notified Operator",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User
).id;
await recordMinigameEntry({
payload,
userId: userA,
game: "flappy",
score: 7,
durationMs: 1_000,
now: new Date("2026-08-04T12:00:00.000Z"),
});
});
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("notifies winners in-app on close, and does not repeat on a re-run", async () => {
const summary = await closeDuePeriods(payload, new Date("2026-08-18T00:00:00.000Z"));
expect(summary.closed).toHaveLength(1);
const afterFirst = await notificationsFor(userA);
expect(afterFirst.length).toBeGreaterThan(0);
expect(afterFirst[0].title).toContain("earned for");
expect(afterFirst[0].link).toBe("/minigames/leaderboards");
// Idempotent close: nothing new is granted, so nothing new is sent.
await closeDuePeriods(payload, new Date("2026-08-18T00:00:00.000Z"));
const afterSecond = await notificationsFor(userA);
expect(afterSecond.length).toBe(afterFirst.length);
});
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 });
}
}
});

View file

@ -1,176 +0,0 @@
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 {
completedMonthWindows,
completedYearWindows,
} from "@/lib/minigames/periods/calendar";
const ANCHOR = "2026-01-15T00:00:00.000Z";
const RUN = `mgc-${Date.now().toString(36)}`;
let payload: Payload;
let userA: number;
let userB: number;
let originalRules: Record<string, unknown> | null = null;
const at = (iso: string) => new Date(iso);
describe("Minigame month/year achievements", () => {
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: 5,
},
overrideAccess: true,
});
const createUser = async (suffix: string) =>
(
(await payload.create({
collection: "users",
data: {
username: `${RUN}-${suffix}`,
discordUsername: `${RUN}-${suffix}`,
displayName: `MG ${suffix.toUpperCase()}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User
).id;
userA = await createUser("a");
userB = await createUser("b");
// January window (anchor-relative, Jan 15 to Feb 1): A leads.
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 10, durationMs: 1_000, now: at("2026-01-20T12:00:00Z") });
await recordMinigameEntry({ payload, userId: userA, game: "eod", score: 5, durationMs: 1_000, now: at("2026-01-22T12:00:00Z") });
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score: 3, durationMs: 1_000, now: at("2026-01-25T12:00:00Z") });
// February window (Feb 1 to Mar 1): B leads.
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 2, durationMs: 1_000, now: at("2026-02-03T12:00:00Z") });
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score: 20, durationMs: 1_000, now: at("2026-02-05T12:00:00Z") });
});
afterAll(async () => {
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("enumerates completed UTC calendar windows, partial first window included", () => {
const anchor = at(ANCHOR);
const months = completedMonthWindows(anchor, at("2026-03-05T00:00:00Z"));
expect(months.map((window) => window.label)).toEqual(["January 2026", "February 2026"]);
expect(months[0].windowStart.toISOString()).toBe("2026-01-15T00:00:00.000Z");
expect(months[1].windowStart.toISOString()).toBe("2026-02-01T00:00:00.000Z");
expect(completedMonthWindows(anchor, at("2026-01-20T00:00:00Z"))).toHaveLength(0);
expect(completedYearWindows(anchor, at("2026-12-31T00:00:00Z"))).toHaveLength(0);
const years = completedYearWindows(anchor, at("2027-01-02T00:00:00Z"));
expect(years.map((window) => window.label)).toEqual(["2026"]);
expect(years[0].windowStart.toISOString()).toBe("2026-01-15T00:00:00.000Z");
expect(years[0].windowEnd.toISOString()).toBe("2027-01-01T00:00:00.000Z");
});
it("crowns each completed month and is idempotent", async () => {
const first = await closeDuePeriods(payload, at("2026-03-05T00:00:00Z"));
const months = first.calendar.filter((entry) => entry.unit === "month");
expect(months.map((entry) => entry.label).sort()).toEqual(["February 2026", "January 2026"]);
const january = await monthChampion("2026-01-15T00:00:00.000Z");
const february = await monthChampion("2026-02-01T00:00:00.000Z");
expect(january?.user).toBe(userA);
expect(february?.user).toBe(userB);
const before = await achievementCount();
const second = await closeDuePeriods(payload, at("2026-03-05T00:00:00Z"));
expect(second.calendar).toHaveLength(0);
expect(second.closed).toHaveLength(0);
expect(await achievementCount()).toBe(before);
});
it("crowns the year once it closes", async () => {
const summary = await closeDuePeriods(payload, at("2027-01-02T00:00:00Z"));
const years = summary.calendar.filter((entry) => entry.unit === "year");
expect(years.map((entry) => entry.label)).toEqual(["2026"]);
const year = await yearChampion("2026-01-15T00:00:00.000Z");
expect(year?.user).toBe(userA);
expect(year?.window).toBe("year");
});
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 });
}
}
async function monthChampion(windowStart: string) {
return firstAchievement("player-of-month", windowStart);
}
async function yearChampion(windowStart: string) {
return firstAchievement("player-of-year", windowStart);
}
async function firstAchievement(type: string, windowStart: string) {
const res = await payload.find({
collection: "achievements",
where: { and: [{ type: { equals: type } }, { windowStart: { equals: windowStart } }] },
limit: 1,
depth: 0,
overrideAccess: true,
});
return res.docs[0];
}
async function achievementCount() {
const res = await payload.find({
collection: "achievements",
limit: 0,
depth: 0,
overrideAccess: true,
});
return res.totalDocs;
}
});

View file

@ -1,190 +0,0 @@
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 { derivePeriodForInstant } from "@/lib/minigames/periods/derive";
const ANCHOR = "2026-10-12T00:00:00.000Z";
const RUN = `mg-${Date.now().toString(36)}`;
let payload: Payload;
let userId: number;
let originalRules: Record<string, unknown> | null = null;
const entryPeriodId = (entry: { period?: unknown }): number | null => {
const period = entry.period;
if (period == null) return null;
return typeof period === "object" ? (period as { id: number }).id : (period as number);
};
/** 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",
"minigames",
] as const) {
await payload.delete({
collection,
where: { id: { greater_than: 0 } },
overrideAccess: true,
});
}
}
describe("Minigame entry recording + anchored periods", () => {
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
// The period spec shares these tables and the same anchor; start clean so
// the two files are order-independent.
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 },
overrideAccess: true,
});
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-player`,
discordUsername: `${RUN}-player`,
displayName: "MG PLAYER",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userId = user.id;
});
afterAll(async () => {
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,
},
overrideAccess: true,
})
.catch(() => undefined);
});
it("derives anchored period indexes, labels and pre-anchor nulls", () => {
const anchor = new Date(ANCHOR);
const period0 = derivePeriodForInstant(anchor, 14, new Date(ANCHOR));
expect(period0?.index).toBe(0);
expect(period0?.label).toBe("Oct 12 to Oct 25, 2026");
const period1 = derivePeriodForInstant(anchor, 14, new Date("2026-10-26T00:00:00.000Z"));
expect(period1?.index).toBe(1);
expect(period1?.label).toBe("Oct 26 to Nov 8, 2026");
expect(
derivePeriodForInstant(anchor, 14, new Date("2026-10-11T23:59:59.999Z")),
).toBeNull();
});
it("lazily creates the anchored period and links entries to it", async () => {
await recordMinigameEntry({
payload,
userId,
game: "flappy",
score: 7,
durationMs: 12_000,
now: new Date("2026-10-14T12:00:00.000Z"),
});
await recordMinigameEntry({
payload,
userId,
game: "eod",
score: 300,
durationMs: 45_000,
mode: "perimeter",
now: new Date("2026-10-15T08:00:00.000Z"),
});
const entries = await payload.find({
collection: "minigame-entries",
where: {
and: [
{ user: { equals: userId } },
{ game: { in: ["flappy", "eod"] } },
],
},
sort: "createdAt",
depth: 0,
overrideAccess: true,
});
expect(entries.docs.length).toBe(2);
const periodIds = new Set(entries.docs.map(entryPeriodId));
expect(periodIds.size).toBe(1);
const periodId = [...periodIds][0];
expect(periodId).toBeTruthy();
const period = await payload.findByID({
collection: "minigame-periods",
id: periodId as number,
depth: 0,
overrideAccess: true,
});
expect(period.label).toBe("Oct 12 to Oct 25, 2026");
expect(period.status).toBe("open");
});
it("records entries before the anchor with no period", async () => {
await recordMinigameEntry({
payload,
userId,
game: "opord",
score: 5,
durationMs: 30_000,
now: new Date("2026-10-01T00:00:00.000Z"),
});
const res = await payload.find({
collection: "minigame-entries",
where: {
and: [{ user: { equals: userId } }, { game: { equals: "opord" } }],
},
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(res.docs.length).toBe(1);
expect(entryPeriodId(res.docs[0])).toBeNull();
});
it("never throws when recording fails", async () => {
// A non-existent user id violates the FK; the recorder must swallow it.
await expect(
recordMinigameEntry({
payload,
userId: 999_999_999,
game: "flappy",
score: 1,
durationMs: 1_000,
now: new Date("2026-10-14T12:00:00.000Z"),
}),
).resolves.toBeUndefined();
});
});

View file

@ -1,265 +0,0 @@
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,
closePeriodById,
reopenPeriodById,
} from "@/lib/minigames/periods/lifecycle";
import { computePeriodAwards, type LedgerEntry } from "@/lib/minigames/periods/boards";
const ANCHOR = "2026-10-12T00:00:00.000Z";
const PERIOD_0_LABEL = "Oct 12 to Oct 25, 2026";
const RUN = `mgp-${Date.now().toString(36)}`;
const inPeriod0 = (day: number) => new Date(`2026-10-${String(day).padStart(2, "0")}T12:00:00.000Z`);
const AFTER_PERIOD_0 = new Date("2026-10-26T00:00:30.000Z");
let payload: Payload;
let userA: number;
let userB: number;
let originalRules: Record<string, unknown> | null = null;
const entry = (over: Partial<LedgerEntry>): LedgerEntry => ({
userId: 1,
game: "flappy",
score: 1,
durationMs: 1_000,
accuracy: null,
createdAtMs: 0,
...over,
});
describe("Minigame period close pipeline", () => {
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
// The entries spec shares these tables and the same anchor; start clean so
// the two files are order-independent.
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) =>
(
(await payload.create({
collection: "users",
data: {
username: `${RUN}-${suffix}`,
discordUsername: `${RUN}-${suffix}`,
displayName: `MG ${suffix.toUpperCase()}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User
).id;
userA = await createUser("a");
userB = await createUser("b");
});
afterAll(async () => {
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);
});
describe("pure award math", () => {
it("ranks boards, sums placement points and picks every period award", () => {
const entries: LedgerEntry[] = [
entry({ userId: 1, game: "flappy", score: 10, createdAtMs: 10 }),
entry({ userId: 2, game: "flappy", score: 3, createdAtMs: 20 }),
entry({ userId: 2, game: "flappy", score: 2, createdAtMs: 21 }),
entry({ userId: 2, game: "flappy", score: 1, createdAtMs: 22 }),
entry({ userId: 1, game: "radio", score: 5, accuracy: 0.9, createdAtMs: 30 }),
];
const awards = computePeriodAwards({
entries,
games: ["flappy", "radio"],
topN: 10,
precisionMinAttempts: 1,
previousPointsByUser: new Map([
[1, 50],
[2, 0],
]),
});
const byType = Object.fromEntries(awards.map((award) => [award.type, award]));
// Flappy: user1 rank1 (10 pts), user2 rank2 (9 pts). Radio: user1 rank1 (10 pts).
expect(byType["period-champion"].userId).toBe(1);
expect(byType["period-champion"].value).toBe(20);
expect(byType.diligence.userId).toBe(2); // 3 attempts vs 2
expect(byType.precision.userId).toBe(1);
expect(Number(byType.precision.value)).toBeCloseTo(0.9, 4);
// user2 gained points over the previous period (0 -> 9).
expect(byType["most-improved"].userId).toBe(2);
expect(byType["most-improved"].value).toBe(9);
});
it("skips most-improved when there is no previous period", () => {
const awards = computePeriodAwards({
entries: [entry({ userId: 1, game: "flappy", score: 1 })],
games: ["flappy"],
topN: 10,
precisionMinAttempts: 1,
previousPointsByUser: null,
});
expect(awards.some((award) => award.type === "most-improved")).toBe(false);
});
it("gives ladder points only down to topN", () => {
const entries: LedgerEntry[] = Array.from({ length: 12 }, (_, i) =>
entry({ userId: i + 1, game: "flappy", score: 100 - i }),
);
const awards = computePeriodAwards({
entries,
games: ["flappy"],
topN: 3,
precisionMinAttempts: 10,
previousPointsByUser: null,
});
// Only the top three earn points; user 4+ get zero, and the champion is
// the top scorer, not the deepest roster.
expect(awards.find((award) => award.type === "period-champion")?.value).toBe(3);
});
});
describe("close / reopen against the ledger", () => {
it("closes the due period and grants the four Period-1 awards", async () => {
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 10, durationMs: 1_000, now: inPeriod0(14) });
await recordMinigameEntry({ payload, userId: userA, game: "eod", score: 5, durationMs: 1_000, now: inPeriod0(14) });
await recordMinigameEntry({ payload, userId: userA, game: "radio", score: 5, durationMs: 1_000, accuracy: 0.9, now: inPeriod0(14) });
await recordMinigameEntry({ payload, userId: userA, game: "opord", score: 4, durationMs: 1_000, accuracy: 0.8, now: inPeriod0(15) });
await recordMinigameEntry({ payload, userId: userA, game: "qualification", score: 6, durationMs: 1_000, accuracy: 1, now: inPeriod0(15) });
for (const score of [3, 2, 2, 1, 1]) {
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score, durationMs: 10_000, now: inPeriod0(14) });
}
await recordMinigameEntry({ payload, userId: userB, game: "eod", score: 9, durationMs: 10_000, now: inPeriod0(14) });
// A later period exists but must stay untouched.
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 1, durationMs: 1_000, now: new Date("2026-10-27T12:00:00.000Z") });
const summary = await closeDuePeriods(payload, AFTER_PERIOD_0);
expect(summary.closed.length).toBe(1);
expect(summary.closed[0].label).toBe(PERIOD_0_LABEL);
expect(summary.closed[0].achievements).toBe(4);
expect(summary.createdPeriodId).toBeTruthy();
const period0 = await findPeriodByLabel(PERIOD_0_LABEL);
expect(period0.status).toBe("closed");
expect(period0.closedAt).toBeTruthy();
const awards = await periodAwards(period0.startDate);
const types = awards.map((row) => row.type).sort();
expect(types).toEqual(["dedication", "diligence", "period-champion", "precision"]);
expect(awards.find((row) => row.type === "period-champion")?.user).toBe(userA);
expect(awards.find((row) => row.type === "diligence")?.user).toBe(userB);
expect(awards.find((row) => row.type === "dedication")?.user).toBe(userB);
expect(awards.find((row) => row.type === "precision")?.user).toBe(userA);
});
it("is idempotent: a second sweep grants nothing new", async () => {
const period0 = await findPeriodByLabel(PERIOD_0_LABEL);
const before = (await periodAwards(period0.startDate)).length;
const summary = await closeDuePeriods(payload, AFTER_PERIOD_0);
expect(summary.closed.length).toBe(0);
expect((await periodAwards(period0.startDate)).length).toBe(before);
});
it("reopens a period, removing its awards, then re-grants on close", async () => {
const period0 = await findPeriodByLabel(PERIOD_0_LABEL);
const reopened = await reopenPeriodById(payload, period0.id);
expect(reopened?.periodId).toBe(period0.id);
expect((await periodAwards(period0.startDate)).length).toBe(0);
const afterReopen = await payload.findByID({
collection: "minigame-periods",
id: period0.id,
depth: 0,
overrideAccess: true,
});
expect(afterReopen.status).toBe("open");
expect(afterReopen.closedAt).toBeFalsy();
const reclosed = await closePeriodById(payload, period0.id, AFTER_PERIOD_0);
expect(reclosed?.achievements).toBe(4);
expect((await periodAwards(period0.startDate)).length).toBe(4);
});
});
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,
});
}
}
async function findPeriodByLabel(label: string) {
const res = await payload.find({
collection: "minigame-periods",
where: { label: { equals: label } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const doc = res.docs[0];
expect(doc).toBeTruthy();
return doc;
}
async function periodAwards(windowStart: string) {
const res = await payload.find({
collection: "achievements",
where: {
and: [{ window: { equals: "period" } }, { windowStart: { equals: windowStart } }],
},
limit: 50,
depth: 0,
overrideAccess: true,
});
return res.docs;
}
});

View file

@ -1,157 +0,0 @@
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 });
}
}
});

View file

@ -1,162 +0,0 @@
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 });
}
}
});