Phase 3 of the minigame periods feature: - Record each ledger row's own instant (`occurredAt`, server clock at submit) so calendar windows score runs that actually happened in them. Backfilled from createdAt for existing rows. - Pure UTC calendar windows (lib/minigames/periods/calendar.ts): completed month and year windows, with the first window of each kind partial because it begins at the anchor, and nothing crowned until the window has ended. - Close pipeline extended: after the period sweep it crowns Player of the Month and Player of the Year for every completed window, scored with the same placement ladder as the period champion. Idempotent like the period close (achievement unique key plus an existence check). - period-tick logs the crowned windows; integration tests cover window enumeration, both crowns and idempotency.
122 lines
3.9 KiB
TypeScript
122 lines
3.9 KiB
TypeScript
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
|
|
}
|
|
}
|
|
}
|