1
0
Fork 0
polaris-task-force/tests/int/attendance-unlocks.int.spec.ts
Z8MB1E 4022e5b5f1 feat(intelligence): add attendance-gated feature unlocks to mission pages
Missions gain an attendanceUnlocks tier list (admin tab plus side-op dialog),
rendered as a timeline under the attendance card: reached tiers light up in
their accent, unreached tiers stay muted with an X TO GO tag.

- shared derivation, validation and side-op parser in lib/intelligence
- thresholds sorted on save, duplicates rejected, above-max allowed
- one compact field in the Discord roll-call; attendance hash now includes
  tiers, embed schema version 4
- int tests and an e2e render check at two attendance levels
2026-11-21 02:30:48 -05:00

367 lines
12 KiB
TypeScript

import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Map as MissionMap, Mission, MissionAttendance } from "@/payload-types";
import {
attendanceHash,
renderAttendanceEmbed,
} from "@/bot/services/missionEmbeds";
import type { MissionAttendanceSummary } from "@/lib/attendance";
import {
MAX_ATTENDANCE_UNLOCK_TIERS,
deriveAttendanceUnlockRows,
parseAttendanceUnlocks,
} from "@/lib/intelligence/attendanceUnlocks";
let payload: Payload;
const RUN = `unlocks-${Date.now().toString(36)}`;
const START = "2026-12-04T19:00:00.000Z";
const tiers = [
{ threshold: 6, title: "Armor", description: "Gain access to an M1A1.", accentColor: "#f59e0b" as const },
{ threshold: 8, title: "Air Support", description: "Call in a rotary gunship.", accentColor: "#22d3ee" as const },
];
describe("Attendance unlock derivation", () => {
it("builds plain hyphen ranges and ends the last row with +", () => {
const timeline = deriveAttendanceUnlockRows(tiers, 0, { terminal: false });
expect(timeline.rows.map((row) => row.rangeLabel)).toEqual(["6-7", "8+"]);
expect(timeline.total).toBe(2);
});
it("adds a baseline row only when the first threshold is above 2", () => {
const atSix = deriveAttendanceUnlockRows(tiers, 0, { terminal: false });
expect(atSix.baseline).toMatchObject({
rangeLabel: "0-5",
title: "Standard mission parameters",
description: "No special unlocks at this attendance level.",
});
const firstTierAtOne = deriveAttendanceUnlockRows([{ threshold: 1, title: "One" }], 0, {
terminal: false,
});
expect(firstTierAtOne.baseline).toBeNull();
const firstTierAtTwo = deriveAttendanceUnlockRows([{ threshold: 2, title: "Two" }], 0, {
terminal: false,
});
expect(firstTierAtTwo.baseline).toBeNull();
const firstTierAtThree = deriveAttendanceUnlockRows([{ threshold: 3, title: "Three" }], 0, {
terminal: false,
});
expect(firstTierAtThree.baseline?.rangeLabel).toBe("0-2");
});
it("counts unlocked tiers from yes attendance only", () => {
const counts: Record<number, number> = { 5: 0, 6: 1, 7: 1, 8: 2 };
for (const [yesCount, expected] of Object.entries(counts)) {
const timeline = deriveAttendanceUnlockRows(tiers, Number(yesCount), { terminal: false });
expect(timeline.unlockedCount).toBe(expected);
}
});
it("exposes X TO GO on locked tiers and suppresses it on terminal missions", () => {
const live = deriveAttendanceUnlockRows(tiers, 5, { terminal: false });
expect(live.rows[0].unlocked).toBe(false);
expect(live.rows[0].toGo).toBe(1);
expect(live.rows[1].toGo).toBe(3);
const terminal = deriveAttendanceUnlockRows(tiers, 6, { terminal: true });
expect(terminal.rows[0].unlocked).toBe(true);
expect(terminal.rows[0].toGo).toBeNull();
expect(terminal.rows[1].unlocked).toBe(false);
expect(terminal.rows[1].toGo).toBeNull();
expect(terminal.unlockedCount).toBe(1);
});
it("never trusts stored order and handles an empty tier list", () => {
const outOfOrder = deriveAttendanceUnlockRows(
[
{ threshold: 8, title: "Air Support" },
{ threshold: 6, title: "Armor" },
],
6,
{ terminal: false },
);
expect(outOfOrder.rows.map((row) => row.threshold)).toEqual([6, 8]);
expect(deriveAttendanceUnlockRows(null, 6, { terminal: false })).toEqual({
rows: [],
baseline: null,
unlockedCount: 0,
total: 0,
});
expect(deriveAttendanceUnlockRows([], 0, { terminal: false }).total).toBe(0);
});
});
describe("parseAttendanceUnlocks", () => {
it("accepts valid tiers, sorts them and permits a threshold above max players", () => {
const parsed = parseAttendanceUnlocks([
{ threshold: 200, title: " Impossible", description: " Never reached ", accentColor: "#f59e0b" },
{ threshold: 6, title: "Armor", description: "", accentColor: null },
]);
expect(parsed.success).toBe(true);
if (!parsed.success) return;
expect(parsed.data.map((row) => row.threshold)).toEqual([6, 200]);
expect(parsed.data[0]).toMatchObject({
threshold: 6,
title: "Armor",
description: null,
accentColor: null,
});
expect(parsed.data[1]).toMatchObject({ threshold: 200, title: "Impossible", description: "Never reached" });
});
it("treats undefined as an empty list", () => {
expect(parseAttendanceUnlocks(undefined)).toEqual({ success: true, data: [] });
expect(parseAttendanceUnlocks(null)).toEqual({ success: true, data: [] });
});
it("rejects duplicate thresholds", () => {
const parsed = parseAttendanceUnlocks([
{ threshold: 6, title: "Armor" },
{ threshold: 6, title: "Air Support" },
]);
expect(parsed.success).toBe(false);
if (!parsed.success) expect(parsed.error).toMatch(/Duplicate threshold 6/);
});
it("rejects non-integer and non-positive thresholds", () => {
for (const threshold of [6.5, 0, -1, "6", Number.NaN]) {
const parsed = parseAttendanceUnlocks([{ threshold, title: "Armor" }]);
expect(parsed.success).toBe(false);
}
});
it("rejects empty and over-long titles, over-long descriptions and unknown accents", () => {
expect(parseAttendanceUnlocks([{ threshold: 6, title: " " }]).success).toBe(false);
expect(parseAttendanceUnlocks([{ threshold: 6, title: "x".repeat(61) }]).success).toBe(false);
expect(
parseAttendanceUnlocks([{ threshold: 6, title: "Armor", description: "x".repeat(401) }])
.success,
).toBe(false);
expect(
parseAttendanceUnlocks([{ threshold: 6, title: "Armor", accentColor: "#000000" }]).success,
).toBe(false);
});
it("rejects more than the tier cap", () => {
const tooMany = Array.from({ length: MAX_ATTENDANCE_UNLOCK_TIERS + 1 }, (_, index) => ({
threshold: index + 1,
title: `Tier ${index + 1}`,
}));
expect(parseAttendanceUnlocks(tooMany).success).toBe(false);
});
});
describe("Attendance unlocks collection behaviour", () => {
let mapId: number;
let authorId: number;
const missionIds: number[] = [];
beforeAll(async () => {
payload = await getTestPayload();
const map = (await payload.create({
collection: "maps",
data: {
name: `${RUN} Map`,
worldSizeWidth: 8192,
worldSizeHeight: 8192,
basemapMode: "image",
},
overrideAccess: true,
depth: 0,
})) as unknown as MissionMap;
mapId = map.id;
// Authors are required. Create a throwaway owner and remove it, with the
// profile and bank account that user hooks provision.
const author = (await payload.create({
collection: "users",
data: {
username: `${RUN}-author`,
discordUsername: `${RUN}-author`,
displayName: "UNLOCKS AUTHOR",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
authorId = author.id;
});
afterAll(async () => {
for (const id of missionIds) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
const accounts = await payload
.find({
collection: "bank-accounts",
where: { ownerUser: { equals: authorId } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const account of accounts?.docs ?? []) {
await payload
.delete({ collection: "bank-accounts", id: account.id, overrideAccess: true })
.catch(() => {});
}
const profiles = await payload
.find({
collection: "profiles",
where: { user: { equals: authorId } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const profile of profiles?.docs ?? []) {
await payload
.delete({ collection: "profiles", id: profile.id, overrideAccess: true })
.catch(() => {});
}
await payload.delete({ collection: "users", id: authorId, overrideAccess: true }).catch(() => {});
});
const missionData = (label: string, attendanceUnlocks: unknown) =>
({
name: `${RUN} ${label}`,
summary: "Attendance unlock collection test mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
startDateTime: START,
estimatedDuration: 120,
},
ownershipAndStatus: {
authors: [authorId],
status: "Scheduled",
visibility: "unit",
},
missionRoles: { maxPlayers: 12 },
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
briefing: [],
attendanceUnlocks,
}) as never;
it("stores out-of-order tiers sorted by threshold", async () => {
const mission = (await payload.create({
collection: "missions",
data: missionData("sorted", [
{ threshold: 8, title: "Air Support", accentColor: "#22d3ee" },
{ threshold: 6, title: "Armor", accentColor: "#f59e0b" },
]),
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id);
expect((mission.attendanceUnlocks ?? []).map((tier) => tier.threshold)).toEqual([6, 8]);
const reread = (await payload.findByID({
collection: "missions",
id: mission.id,
depth: 0,
overrideAccess: true,
})) as unknown as Mission;
expect((reread.attendanceUnlocks ?? []).map((tier) => tier.title)).toEqual([
"Armor",
"Air Support",
]);
});
it("fails a write with a duplicate threshold", async () => {
let thrown: unknown;
try {
const mission = await payload.create({
collection: "missions",
data: missionData("duplicate", [
{ threshold: 6, title: "Armor" },
{ threshold: 6, title: "Air Support" },
]),
overrideAccess: true,
depth: 0,
});
missionIds.push((mission as unknown as Mission).id);
} catch (error) {
thrown = error;
}
expect(thrown).toBeTruthy();
// Payload reports the invalid field path; the exact message is covered by
// the shared validator tests above.
expect(String(thrown)).toMatch(/Attendance Unlocks > Feature Unlocks by Attendance/);
expect(String(thrown)).not.toMatch(/Authors/);
});
});
describe("Attendance embed and hash", () => {
const summary: MissionAttendanceSummary = {
yes: [],
no: [],
tentative: [],
counts: { yes: 6, no: 0, tentative: 1 },
};
const embedMission = (attendanceUnlocks: Mission["attendanceUnlocks"]) =>
({
id: 4242,
name: "Operation Test",
codeName: "OP:TST",
summary: "Test summary",
operationType: "main",
classification: {
map: 1,
missionType: "PvE",
startDateTime: START,
estimatedDuration: 120,
},
ownershipAndStatus: { authors: [], status: "Scheduled", visibility: "unit" },
missionRoles: { maxPlayers: 32 },
briefing: [],
attendanceUnlocks,
}) as unknown as Mission;
const fieldsOf = (mission: Mission) =>
renderAttendanceEmbed(mission, summary).toJSON().fields ?? [];
it("adds one compact attendance unlocks field only when tiers exist", () => {
const withTiers = fieldsOf(embedMission(tiers));
const unlockField = withTiers.find((field) => field.name === "🔓 Attendance unlocks");
expect(unlockField?.value).toBe("6+: Armor · 8+: Air Support");
const withoutTiers = fieldsOf(embedMission(null));
expect(withoutTiers.some((field) => field.name === "🔓 Attendance unlocks")).toBe(false);
});
const docs = [
{ user: 1, response: "yes" },
{ user: 2, response: "tentative" },
] as unknown as MissionAttendance[];
it("hashes the tiers so title and threshold changes re-render the embed", () => {
const base = attendanceHash(docs, { startDateTime: START, unlocks: tiers });
expect(attendanceHash(docs, { startDateTime: START, unlocks: [...tiers] })).toBe(base);
const renamed = attendanceHash(docs, {
startDateTime: START,
unlocks: [{ ...tiers[0], title: "Armor (renamed)" }, tiers[1]],
});
expect(renamed).not.toBe(base);
const retuned = attendanceHash(docs, {
startDateTime: START,
unlocks: [{ ...tiers[0], threshold: 5 }, tiers[1]],
});
expect(retuned).not.toBe(base);
});
});