1
0
Fork 0
polaris-task-force/src/lib/minigames/periods/lifecycle.ts
Z8MB1E ccdeebbd35 feat(minigames): close anchored periods and grant period awards
Phase 2 of the minigame periods feature:

- Pure board + award math (lib/minigames/periods/boards.ts): best-performer
  boards from the ledger, a fixed top-N placement ladder summed across the
  five Core boards, and the five period awards (Period Champion, Diligence,
  Dedication, Precision, Most Improved) with the locked tie-break (raw
  period score, then earliest submission).
- Close pipeline (lib/minigames/periods/lifecycle.ts): computes boards for a
  period, writes its achievement rows, and marks it closed. Idempotent: the
  status is re-checked before committing and the achievements unique key
  makes a duplicate close insert nothing, so the tick and the admin override
  cannot double-grant.
- Shared rules resolver (lib/minigames/periods/rules.ts), now used by both
  the entry recorder and the close pipeline.
- New period-tick bin (registered in payload.config.ts) closes every due
  period and materializes the current one, mirroring the mission tick.
- Admin close/reopen route (POST /api/minigame-periods/close), gated on the
  minigame-periods:close permission. Reopen removes the period's awards so a
  future close can re-grant them.
- Integration tests for the pure math and the full close/reopen cycle, plus a
  clean-slate guard so the two minigame specs stay order-independent.
2026-10-11 17:06:52 -04:00

326 lines
9.9 KiB
TypeScript

import type { Payload, Where } from "payload";
import { CORE_MINIGAME_KEYS, type MinigameAchievementType } from "@/lib/minigames/registry";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { derivePeriodForInstant, periodStartForIndex } from "./derive";
import { buildGameBoard, computePeriodAwards, 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;
const PERIOD_GAMES: string[] = [...CORE_MINIGAME_KEYS];
export interface ClosedPeriodSummary {
periodId: number;
label: string;
achievements: number;
}
export interface PeriodTickSummary {
/** Id of the period covering `now`, materialized if it was missing. */
createdPeriodId: number | null;
closed: ClosedPeriodSummary[];
}
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[],
rules: ResolvedMinigameRules,
): Map<number, number> =>
totalPointsByUser(
PERIOD_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,
): 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, 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(),
): 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 entries = await fetchEntries(payload, { period: { equals: periodId } });
const previousPointsByUser = await previousPointsFor(
payload,
rules,
new Date(period.startDate).getTime(),
);
const awards = computePeriodAwards({
entries,
games: PERIOD_GAMES,
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 };
}
/**
* The tick sweep: close every open period whose window has ended, 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: [] };
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 closed: ClosedPeriodSummary[] = [];
for (const period of due.docs) {
const summary = await closePeriodById(payload, period.id, now);
if (summary) closed.push(summary);
}
const createdPeriodId = await ensurePeriodForInstant(payload, rules, now);
return { createdPeriodId, closed };
}
/**
* 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);
}