1
0
Fork 0
polaris-task-force/tests/int/minigame-periods.int.spec.ts
Z8MB1E deb88ded56 feat(minigames): drive the nav and period scoring from the registry
Phase 4 of the minigame periods feature:

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

265 lines
9.8 KiB
TypeScript

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;
}
});