feat(minigames): crown player of the month and year
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.
This commit is contained in:
parent
ccdeebbd35
commit
5cf245b855
11 changed files with 40379 additions and 7 deletions
|
|
@ -21,7 +21,7 @@ export const MinigameEntries: CollectionConfig = {
|
|||
admin: {
|
||||
group: "Minigames",
|
||||
useAsTitle: "game",
|
||||
defaultColumns: ["user", "game", "mode", "score", "accuracy", "durationMs", "period", "createdAt"],
|
||||
defaultColumns: ["user", "game", "mode", "score", "accuracy", "durationMs", "period", "occurredAt"],
|
||||
description:
|
||||
"Append-only ledger of completed minigame runs. Read-only here; writes flow through the minigame submit actions.",
|
||||
},
|
||||
|
|
@ -48,6 +48,17 @@ export const MinigameEntries: CollectionConfig = {
|
|||
admin: { readOnly: true, description: "Mode or difficulty label when applicable (e.g. sprint, elite)." },
|
||||
},
|
||||
{ name: "score", type: "number", required: true, index: true, ...readOnly },
|
||||
{
|
||||
name: "occurredAt",
|
||||
type: "date",
|
||||
index: true,
|
||||
...readOnly,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
"When the run happened (server clock at submit). Calendar month/year windows score by this, not the row's createdAt.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "accuracy",
|
||||
type: "number",
|
||||
|
|
|
|||
|
|
@ -288,3 +288,42 @@ export function computePeriodAwards(input: PeriodAwardInput): ComputedAward[] {
|
|||
|
||||
return awards;
|
||||
}
|
||||
|
||||
export interface WindowChampion {
|
||||
userId: number;
|
||||
points: number;
|
||||
/** How many boards the champion placed on. */
|
||||
boards: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The champion of an arbitrary window (a calendar month or year), scored with
|
||||
* the same top-N placement ladder summed across the Core boards as the period
|
||||
* champion. Returns null when the window has no entries.
|
||||
*/
|
||||
export function computeWindowChampion(input: {
|
||||
entries: LedgerEntry[];
|
||||
games: string[];
|
||||
topN: number;
|
||||
}): WindowChampion | null {
|
||||
const boards = input.games.map((game) =>
|
||||
buildGameBoard(
|
||||
input.entries.filter((entry) => entry.game === game),
|
||||
input.topN,
|
||||
),
|
||||
);
|
||||
const players = aggregatePlayers(boards);
|
||||
if (players.length === 0) return null;
|
||||
|
||||
const winner = [...players].sort(
|
||||
(a, b) =>
|
||||
b.points - a.points ||
|
||||
b.rawScore - a.rawScore ||
|
||||
a.firstAtMs - b.firstAtMs ||
|
||||
a.userId - b.userId,
|
||||
)[0];
|
||||
const boardsWith = boards.filter((board) =>
|
||||
board.some((row) => row.userId === winner.userId),
|
||||
).length;
|
||||
return { userId: winner.userId, points: winner.points, boards: boardsWith };
|
||||
}
|
||||
|
|
|
|||
99
src/lib/minigames/periods/calendar.ts
Normal file
99
src/lib/minigames/periods/calendar.ts
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
/**
|
||||
* Pure UTC calendar windows for the month/year achievements.
|
||||
*
|
||||
* Player of the Month and Player of the Year are calendar windows, not period
|
||||
* windows: a month holds two or three 14-day periods. Everything is UTC, and
|
||||
* the first window of each kind is partial because it begins at the anchor
|
||||
* (see the feature's locked assumptions).
|
||||
*
|
||||
* A window is only "complete" once its exclusive end has passed, so the tick
|
||||
* never crowns a month that is still running.
|
||||
*
|
||||
* No Payload import: safe to unit-test.
|
||||
*/
|
||||
|
||||
const MONTH_NAMES = [
|
||||
"January",
|
||||
"February",
|
||||
"March",
|
||||
"April",
|
||||
"May",
|
||||
"June",
|
||||
"July",
|
||||
"August",
|
||||
"September",
|
||||
"October",
|
||||
"November",
|
||||
"December",
|
||||
] as const;
|
||||
|
||||
export interface CalendarWindow {
|
||||
/** Inclusive UTC start (max of the natural boundary and the anchor). */
|
||||
windowStart: Date;
|
||||
/** Exclusive UTC end (the next natural boundary). */
|
||||
windowEnd: Date;
|
||||
/** Human label, e.g. "October 2026" or "2026". */
|
||||
label: string;
|
||||
}
|
||||
|
||||
export const startOfUtcMonth = (instant: Date): Date =>
|
||||
new Date(Date.UTC(instant.getUTCFullYear(), instant.getUTCMonth(), 1));
|
||||
|
||||
export const startOfNextUtcMonth = (instant: Date): Date =>
|
||||
new Date(Date.UTC(instant.getUTCFullYear(), instant.getUTCMonth() + 1, 1));
|
||||
|
||||
export const startOfUtcYear = (instant: Date): Date =>
|
||||
new Date(Date.UTC(instant.getUTCFullYear(), 0, 1));
|
||||
|
||||
export const startOfNextUtcYear = (instant: Date): Date =>
|
||||
new Date(Date.UTC(instant.getUTCFullYear() + 1, 0, 1));
|
||||
|
||||
const laterOf = (a: Date, b: Date): Date => (a.getTime() >= b.getTime() ? a : b);
|
||||
|
||||
export const formatMonthLabel = (instant: Date): string =>
|
||||
`${MONTH_NAMES[instant.getUTCMonth()]} ${instant.getUTCFullYear()}`;
|
||||
|
||||
export const formatYearLabel = (instant: Date): string => `${instant.getUTCFullYear()}`;
|
||||
|
||||
const MAX_WINDOWS = 1000;
|
||||
|
||||
/**
|
||||
* Every completed calendar month from the anchor through `now`, oldest first.
|
||||
* The first window starts at the anchor when the anchor falls mid-month.
|
||||
*/
|
||||
export function completedMonthWindows(anchor: Date, now: Date): CalendarWindow[] {
|
||||
const out: CalendarWindow[] = [];
|
||||
if (!Number.isFinite(anchor.getTime()) || !Number.isFinite(now.getTime())) return out;
|
||||
if (now.getTime() < anchor.getTime()) return out;
|
||||
|
||||
let cursor = startOfUtcMonth(anchor);
|
||||
for (let guard = 0; guard < MAX_WINDOWS; guard += 1) {
|
||||
const naturalEnd = startOfNextUtcMonth(cursor);
|
||||
if (naturalEnd.getTime() > now.getTime()) break;
|
||||
const windowStart = laterOf(cursor, anchor);
|
||||
if (windowStart.getTime() < naturalEnd.getTime()) {
|
||||
out.push({ windowStart, windowEnd: naturalEnd, label: formatMonthLabel(windowStart) });
|
||||
}
|
||||
cursor = naturalEnd;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Every completed calendar year from the anchor through `now`, oldest first. */
|
||||
export function completedYearWindows(anchor: Date, now: Date): CalendarWindow[] {
|
||||
const out: CalendarWindow[] = [];
|
||||
if (!Number.isFinite(anchor.getTime()) || !Number.isFinite(now.getTime())) return out;
|
||||
if (now.getTime() < anchor.getTime()) return out;
|
||||
|
||||
let cursor = startOfUtcYear(anchor);
|
||||
for (let guard = 0; guard < MAX_WINDOWS; guard += 1) {
|
||||
const naturalEnd = startOfNextUtcYear(cursor);
|
||||
if (naturalEnd.getTime() > now.getTime()) break;
|
||||
const windowStart = laterOf(cursor, anchor);
|
||||
if (windowStart.getTime() < naturalEnd.getTime()) {
|
||||
out.push({ windowStart, windowEnd: naturalEnd, label: formatYearLabel(windowStart) });
|
||||
}
|
||||
cursor = naturalEnd;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -3,7 +3,14 @@ import { CORE_MINIGAME_KEYS, type MinigameAchievementType } from "@/lib/minigame
|
|||
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 { completedMonthWindows, completedYearWindows } from "./calendar";
|
||||
import {
|
||||
buildGameBoard,
|
||||
computePeriodAwards,
|
||||
computeWindowChampion,
|
||||
totalPointsByUser,
|
||||
type LedgerEntry,
|
||||
} from "./boards";
|
||||
import { ensurePeriodForInstant } from "./record";
|
||||
import { resolveMinigameRules, type ResolvedMinigameRules } from "./rules";
|
||||
|
||||
|
|
@ -32,10 +39,21 @@ export interface ClosedPeriodSummary {
|
|||
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 {
|
||||
|
|
@ -244,15 +262,92 @@ export async function closePeriodById(
|
|||
}
|
||||
|
||||
/**
|
||||
* The tick sweep: close every open period whose window has ended, then
|
||||
* materialize the period covering `now`. Idempotent and safe to re-run.
|
||||
* 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(),
|
||||
): Promise<CalendarCloseSummary[]> {
|
||||
if (!rules.enabled || !rules.anchorDate) return [];
|
||||
|
||||
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: PERIOD_GAMES,
|
||||
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: [] };
|
||||
if (!rules.enabled || !rules.anchorDate) {
|
||||
return { createdPeriodId: null, closed: [], calendar: [] };
|
||||
}
|
||||
|
||||
const due = await payload.find({
|
||||
collection: "minigame-periods",
|
||||
|
|
@ -271,8 +366,10 @@ export async function closeDuePeriods(
|
|||
if (summary) closed.push(summary);
|
||||
}
|
||||
|
||||
const calendar = await closeCalendarWindows(payload, rules, now);
|
||||
|
||||
const createdPeriodId = await ensurePeriodForInstant(payload, rules, now);
|
||||
return { createdPeriodId, closed };
|
||||
return { createdPeriodId, closed, calendar };
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -103,6 +103,7 @@ export async function recordMinigameEntry(input: RecordMinigameEntryInput): Prom
|
|||
score: input.score,
|
||||
accuracy: input.accuracy ?? null,
|
||||
durationMs,
|
||||
occurredAt: instant.toISOString(),
|
||||
period: periodId,
|
||||
meta: input.meta ?? null,
|
||||
},
|
||||
|
|
|
|||
39925
src/migrations/20261011_201531_add_minigame_entry_occurred_at.json
Normal file
39925
src/migrations/20261011_201531_add_minigame_entry_occurred_at.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,14 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "minigame_entries" ADD COLUMN "occurred_at" timestamp(3) with time zone;
|
||||
CREATE INDEX "minigame_entries_occurred_at_idx" ON "minigame_entries" USING btree ("occurred_at");
|
||||
UPDATE "minigame_entries" SET "occurred_at" = "created_at" WHERE "occurred_at" IS NULL;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
DROP INDEX "minigame_entries_occurred_at_idx";
|
||||
ALTER TABLE "minigame_entries" DROP COLUMN "occurred_at";`)
|
||||
}
|
||||
|
|
@ -121,6 +121,7 @@ import * as migration_20261009_185259_add_wiki_featured_curation from './2026100
|
|||
import * as migration_20261009_201920_add_contribution_entries from './20261009_201920_add_contribution_entries';
|
||||
import * as migration_20261010_050644_add_mission_threat_assessment from './20261010_050644_add_mission_threat_assessment';
|
||||
import * as migration_20261011_195306_add_minigame_periods from './20261011_195306_add_minigame_periods';
|
||||
import * as migration_20261011_201531_add_minigame_entry_occurred_at from './20261011_201531_add_minigame_entry_occurred_at';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -736,6 +737,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261011_195306_add_minigame_periods.up,
|
||||
down: migration_20261011_195306_add_minigame_periods.down,
|
||||
name: '20261011_195306_add_minigame_periods'
|
||||
name: '20261011_195306_add_minigame_periods',
|
||||
},
|
||||
{
|
||||
up: migration_20261011_201531_add_minigame_entry_occurred_at.up,
|
||||
down: migration_20261011_201531_add_minigame_entry_occurred_at.down,
|
||||
name: '20261011_201531_add_minigame_entry_occurred_at'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -6020,6 +6020,10 @@ export interface MinigameEntry {
|
|||
*/
|
||||
mode?: string | null;
|
||||
score: number;
|
||||
/**
|
||||
* When the run happened (server clock at submit). Calendar month/year windows score by this, not the row's createdAt.
|
||||
*/
|
||||
occurredAt?: string | null;
|
||||
/**
|
||||
* Fractional accuracy for games that score it.
|
||||
*/
|
||||
|
|
@ -10734,6 +10738,7 @@ export interface MinigameEntriesSelect<T extends boolean = true> {
|
|||
game?: T;
|
||||
mode?: T;
|
||||
score?: T;
|
||||
occurredAt?: T;
|
||||
accuracy?: T;
|
||||
durationMs?: T;
|
||||
period?: T;
|
||||
|
|
|
|||
|
|
@ -19,6 +19,10 @@ export const script = async (config: SanitizedConfig) => {
|
|||
);
|
||||
}
|
||||
|
||||
for (const window of summary.calendar) {
|
||||
log.info(`[Period Tick] Crowned the ${window.unit} "${window.label}" champion.`);
|
||||
}
|
||||
|
||||
const notifyUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
|
||||
const notifySecret = process.env.GAME_TICK_NOTIFY_SECRET;
|
||||
if (notifySecret) {
|
||||
|
|
|
|||
171
tests/int/minigame-calendar.int.spec.ts
Normal file
171
tests/int/minigame-calendar.int.spec.ts
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
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 } from "@/lib/minigames/periods/lifecycle";
|
||||
import {
|
||||
completedMonthWindows,
|
||||
completedYearWindows,
|
||||
} from "@/lib/minigames/periods/calendar";
|
||||
|
||||
const ANCHOR = "2026-01-15T00:00:00.000Z";
|
||||
const RUN = `mgc-${Date.now().toString(36)}`;
|
||||
|
||||
let payload: Payload;
|
||||
let userA: number;
|
||||
let userB: number;
|
||||
let originalRules: Record<string, unknown> | null = null;
|
||||
|
||||
const at = (iso: string) => new Date(iso);
|
||||
|
||||
describe("Minigame month/year achievements", () => {
|
||||
beforeAll(async () => {
|
||||
const payloadConfig = await config;
|
||||
payload = await getPayload({ config: payloadConfig });
|
||||
|
||||
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: 5,
|
||||
},
|
||||
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");
|
||||
|
||||
// January window (anchor-relative, Jan 15 to Feb 1): A leads.
|
||||
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 10, durationMs: 1_000, now: at("2026-01-20T12:00:00Z") });
|
||||
await recordMinigameEntry({ payload, userId: userA, game: "eod", score: 5, durationMs: 1_000, now: at("2026-01-22T12:00:00Z") });
|
||||
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score: 3, durationMs: 1_000, now: at("2026-01-25T12:00:00Z") });
|
||||
// February window (Feb 1 to Mar 1): B leads.
|
||||
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 2, durationMs: 1_000, now: at("2026-02-03T12:00:00Z") });
|
||||
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score: 20, durationMs: 1_000, now: at("2026-02-05T12:00:00Z") });
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it("enumerates completed UTC calendar windows, partial first window included", () => {
|
||||
const anchor = at(ANCHOR);
|
||||
|
||||
const months = completedMonthWindows(anchor, at("2026-03-05T00:00:00Z"));
|
||||
expect(months.map((window) => window.label)).toEqual(["January 2026", "February 2026"]);
|
||||
expect(months[0].windowStart.toISOString()).toBe("2026-01-15T00:00:00.000Z");
|
||||
expect(months[1].windowStart.toISOString()).toBe("2026-02-01T00:00:00.000Z");
|
||||
|
||||
expect(completedMonthWindows(anchor, at("2026-01-20T00:00:00Z"))).toHaveLength(0);
|
||||
expect(completedYearWindows(anchor, at("2026-12-31T00:00:00Z"))).toHaveLength(0);
|
||||
const years = completedYearWindows(anchor, at("2027-01-02T00:00:00Z"));
|
||||
expect(years.map((window) => window.label)).toEqual(["2026"]);
|
||||
expect(years[0].windowStart.toISOString()).toBe("2026-01-15T00:00:00.000Z");
|
||||
expect(years[0].windowEnd.toISOString()).toBe("2027-01-01T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("crowns each completed month and is idempotent", async () => {
|
||||
const first = await closeDuePeriods(payload, at("2026-03-05T00:00:00Z"));
|
||||
const months = first.calendar.filter((entry) => entry.unit === "month");
|
||||
expect(months.map((entry) => entry.label).sort()).toEqual(["February 2026", "January 2026"]);
|
||||
|
||||
const january = await monthChampion("2026-01-15T00:00:00.000Z");
|
||||
const february = await monthChampion("2026-02-01T00:00:00.000Z");
|
||||
expect(january?.user).toBe(userA);
|
||||
expect(february?.user).toBe(userB);
|
||||
|
||||
const before = await achievementCount();
|
||||
const second = await closeDuePeriods(payload, at("2026-03-05T00:00:00Z"));
|
||||
expect(second.calendar).toHaveLength(0);
|
||||
expect(second.closed).toHaveLength(0);
|
||||
expect(await achievementCount()).toBe(before);
|
||||
});
|
||||
|
||||
it("crowns the year once it closes", async () => {
|
||||
const summary = await closeDuePeriods(payload, at("2027-01-02T00:00:00Z"));
|
||||
const years = summary.calendar.filter((entry) => entry.unit === "year");
|
||||
expect(years.map((entry) => entry.label)).toEqual(["2026"]);
|
||||
|
||||
const year = await yearChampion("2026-01-15T00:00:00.000Z");
|
||||
expect(year?.user).toBe(userA);
|
||||
expect(year?.window).toBe("year");
|
||||
});
|
||||
|
||||
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 monthChampion(windowStart: string) {
|
||||
return firstAchievement("player-of-month", windowStart);
|
||||
}
|
||||
|
||||
async function yearChampion(windowStart: string) {
|
||||
return firstAchievement("player-of-year", windowStart);
|
||||
}
|
||||
|
||||
async function firstAchievement(type: string, windowStart: string) {
|
||||
const res = await payload.find({
|
||||
collection: "achievements",
|
||||
where: { and: [{ type: { equals: type } }, { windowStart: { equals: windowStart } }] },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return res.docs[0];
|
||||
}
|
||||
|
||||
async function achievementCount() {
|
||||
const res = await payload.find({
|
||||
collection: "achievements",
|
||||
limit: 0,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return res.totalDocs;
|
||||
}
|
||||
});
|
||||
Loading…
Reference in a new issue