1
0
Fork 0
polaris-task-force/src/lib/minigames/periods/lifecycle.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

442 lines
14 KiB
TypeScript

import type { Payload, Where } from "payload";
import { CORE_MINIGAME_KEYS, type MinigameAchievementType } from "@/lib/minigames/registry";
import { loadMinigameRegistry, periodScoringGameKeys } from "@/lib/minigames/loadRegistry";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { derivePeriodForInstant, periodStartForIndex } from "./derive";
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[];
}
interface EntryDoc {
user: number | { id: number };
game: string;
score: number | null;
durationMs: number | null;
accuracy: number | null;
createdAt: string;
}
const userIdOf = (user: EntryDoc["user"]): number =>
typeof user === "object" ? user.id : user;
const toLedgerEntry = (doc: EntryDoc): LedgerEntry => ({
userId: userIdOf(doc.user),
game: doc.game,
score: typeof doc.score === "number" ? doc.score : 0,
durationMs: typeof doc.durationMs === "number" ? doc.durationMs : 0,
accuracy: typeof doc.accuracy === "number" ? doc.accuracy : null,
createdAtMs: new Date(doc.createdAt).getTime() || 0,
});
/** Fetch every ledger entry matching `where`, following pagination. */
const fetchEntries = async (payload: PayloadType, where: Where) => {
const entries: LedgerEntry[] = [];
let page = 1;
for (;;) {
const res = await payload.find({
collection: "minigame-entries",
where,
sort: "createdAt",
limit: 500,
page,
depth: 0,
overrideAccess: true,
});
for (const doc of res.docs) entries.push(toLedgerEntry(doc as unknown as EntryDoc));
if (!res.hasNextPage || page >= 500) break;
page += 1;
}
return entries;
};
const pointsForPeriod = (
entries: LedgerEntry[],
games: string[],
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 fetchEntries(payload, { period: { equals: previousPeriod.id } });
return pointsForPeriod(entries, games, rules);
};
/** 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 fetchEntries(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) {
await writeAchievement(payload, {
window: "period",
windowStart: period.startDate,
windowEnd: period.endDate,
type: award.type,
user: award.userId,
value: award.value,
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 fetchEntries(payload, {
and: [
{ occurredAt: { greater_than_equal: windowStart } },
{ occurredAt: { less_than: windowEnd } },
],
});
const champion = computeWindowChampion({
entries,
games: periodGames,
topN: rules.placementLadderTopN,
});
if (!champion) continue;
const wrote = await writeAchievement(payload, {
window: plan.unit,
windowStart,
windowEnd,
type: plan.type,
user: champion.userId,
value: champion.points,
detail: `${champion.points} placement point${champion.points === 1 ? "" : "s"} across ${champion.boards} board${champion.boards === 1 ? "" : "s"}`,
});
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 },
});
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);
}