diff --git a/src/app/api/minigame-periods/close/route.ts b/src/app/api/minigame-periods/close/route.ts new file mode 100644 index 00000000..10113bb8 --- /dev/null +++ b/src/app/api/minigame-periods/close/route.ts @@ -0,0 +1,73 @@ +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 }); + } +} diff --git a/src/lib/minigames/periods/boards.ts b/src/lib/minigames/periods/boards.ts new file mode 100644 index 00000000..b178f796 --- /dev/null +++ b/src/lib/minigames/periods/boards.ts @@ -0,0 +1,290 @@ +/** + * 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(); + 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(); + 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 { + const points = new Map(); + 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 | 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; +} diff --git a/src/lib/minigames/periods/lifecycle.ts b/src/lib/minigames/periods/lifecycle.ts new file mode 100644 index 00000000..d3be57de --- /dev/null +++ b/src/lib/minigames/periods/lifecycle.ts @@ -0,0 +1,326 @@ +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 => + 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 | 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 => { + 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 { + 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 { + 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 { + 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 { + 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); +} diff --git a/src/lib/minigames/periods/record.ts b/src/lib/minigames/periods/record.ts index 9c8ac8f2..f5b02203 100644 --- a/src/lib/minigames/periods/record.ts +++ b/src/lib/minigames/periods/record.ts @@ -1,5 +1,6 @@ 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. @@ -14,8 +15,6 @@ import { derivePeriodForInstant, periodStartForIndex } from "./derive"; * run. Phase 2's close pipeline then closes it at its end boundary. */ -const DEFAULT_PERIOD_LENGTH_DAYS = 14; - export interface RecordMinigameEntryInput { payload: Payload; userId: number; @@ -30,35 +29,6 @@ export interface RecordMinigameEntryInput { now?: Date; } -interface ResolvedRules { - enabled: boolean; - anchorDate: Date | null; - periodLengthDays: number; -} - -const resolveRules = async (payload: Payload): Promise => { - try { - const rules = await payload.findGlobal({ - slug: "minigame-rules", - depth: 0, - overrideAccess: true, - }); - const anchorRaw = rules?.anchorDate; - const anchorDate = anchorRaw ? new Date(anchorRaw) : null; - const periodLengthDays = - typeof rules?.periodLengthDays === "number" && rules.periodLengthDays > 0 - ? rules.periodLengthDays - : DEFAULT_PERIOD_LENGTH_DAYS; - return { - enabled: rules?.enabled !== false, - anchorDate: anchorDate && Number.isFinite(anchorDate.getTime()) ? anchorDate : null, - periodLengthDays, - }; - } catch { - return { enabled: false, anchorDate: null, periodLengthDays: DEFAULT_PERIOD_LENGTH_DAYS }; - } -}; - const findPeriodIdByStart = async (payload: Payload, startIso: string): Promise => { const res = await payload.find({ collection: "minigame-periods", @@ -73,7 +43,7 @@ const findPeriodIdByStart = async (payload: Payload, startIso: string): Promise< /** Find or lazily create the anchored period containing `instant`. */ export const ensurePeriodForInstant = async ( payload: Payload, - rules: ResolvedRules, + rules: ResolvedMinigameRules, instant: Date, ): Promise => { if (!rules.enabled || !rules.anchorDate) return null; @@ -118,7 +88,7 @@ export async function recordMinigameEntry(input: RecordMinigameEntryInput): Prom const { payload } = input; try { const instant = input.now ?? new Date(); - const rules = await resolveRules(payload); + const rules = await resolveMinigameRules(payload); const periodId = await ensurePeriodForInstant(payload, rules, instant); const durationMs = diff --git a/src/lib/minigames/periods/rules.ts b/src/lib/minigames/periods/rules.ts new file mode 100644 index 00000000..b6faa716 --- /dev/null +++ b/src/lib/minigames/periods/rules.ts @@ -0,0 +1,60 @@ +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 { + 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, + }; + } +} diff --git a/src/payload.config.ts b/src/payload.config.ts index b1ac3f4b..6b23026c 100644 --- a/src/payload.config.ts +++ b/src/payload.config.ts @@ -508,6 +508,10 @@ 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", diff --git a/src/scripts/periodTick.ts b/src/scripts/periodTick.ts new file mode 100644 index 00000000..0d30c77f --- /dev/null +++ b/src/scripts/periodTick.ts @@ -0,0 +1,47 @@ +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).`, + ); + } + + 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); + } +}; diff --git a/src/utils/event-log/eventTypes.ts b/src/utils/event-log/eventTypes.ts index 7d547d0b..370b4337 100644 --- a/src/utils/event-log/eventTypes.ts +++ b/src/utils/event-log/eventTypes.ts @@ -89,6 +89,7 @@ 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", diff --git a/tests/int/minigame-entries.int.spec.ts b/tests/int/minigame-entries.int.spec.ts index 2c6471c1..091a240d 100644 --- a/tests/int/minigame-entries.int.spec.ts +++ b/tests/int/minigame-entries.int.spec.ts @@ -19,11 +19,26 @@ const entryPeriodId = (entry: { period?: unknown }): number | 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 { + for (const collection of ["achievements", "minigame-entries", "minigame-periods"] 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, diff --git a/tests/int/minigame-periods.int.spec.ts b/tests/int/minigame-periods.int.spec.ts new file mode 100644 index 00000000..af9d00f5 --- /dev/null +++ b/tests/int/minigame-periods.int.spec.ts @@ -0,0 +1,260 @@ +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 | null = null; + +const entry = (over: Partial): 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 | 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"] 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; + } +});