1
0
Fork 0
polaris-task-force/tests/int/mission-command-chain.int.spec.ts
Z8MB1E ef3f26d4f9 feat(missions): add command chain editor and MissionCommandLinks collection
Introduce a per-mission command chain: a new MissionCommandLinks collection, a
lib/command-chain resolver, and an admin/mission-page editor for supervisor ->
subordinate links. Evaluations and mission reminders later consume this chain to
resolve equal-rank command relationships.
2026-11-02 09:59:55 -05:00

400 lines
14 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, Rank, User } from "@/payload-types";
import {
canEditMissionChain,
computeDefaultChain,
freezeDefaults,
getChainLockReason,
resetMissionChain,
resolveMissionChain,
saveMissionChain,
validateChain,
} from "@/lib/command-chain";
import { evaluateEligibility, upsertEvaluation } from "@/lib/evaluations";
import { computeEvaluationReminderPlan } from "@/lib/evaluations/reminders";
import { setMissionAttendance } from "@/lib/attendance";
let payload: Payload;
const RUN = `mcc-${Date.now().toString(36)}`;
describe("Mission command chain overrides", () => {
let mapId: number;
const rankIds: number[] = [];
const userIds: number[] = [];
const missionIds: number[] = [];
const assignmentIds: number[] = [];
let junior: Rank;
let mid: Rank;
let senior: Rank;
let leader: User; // senior, leads the squad
let member: User; // junior in the leader's squad
let peer: User; // equal rank to member, not in the squad
let author: User;
let officer: User; // admin:missions:manage only
let outsider: User;
const makeUser = async (label: string, roles: User["roles"] = ["user"]): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles,
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const setRank = async (userId: number, rankId: number) => {
const profiles = (await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: Array<{ id: number }> };
await payload.update({
collection: "profiles",
id: profiles.docs[0].id,
data: { rank: rankId },
overrideAccess: true,
depth: 0,
});
};
const makeRank = async (name: string): Promise<Rank> => {
const rank = (await payload.create({
collection: "ranks",
data: { name: `${RUN} ${name}`, abbreviation: `${RUN}-${name.toLowerCase()}`, description: "test" },
overrideAccess: true,
depth: 0,
})) as unknown as Rank;
rankIds.push(rank.id);
return rank;
};
const makeMission = async (label: string, status: "Completed" | "Cancelled" = "Completed") => {
const mission = (await payload.create({
collection: "missions",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Command chain test mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
startDateTime: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(),
estimatedDuration: 60,
},
ownershipAndStatus: {
authors: [author.id],
status,
visibility: "unit",
completedAt: status === "Completed" ? new Date(Date.now() - 60_000).toISOString() : undefined,
},
briefing: [],
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
missionRoles: { maxPlayers: 32, providedRoles: [] },
},
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id);
return mission;
};
const rsvp = (missionId: number, userId: number) =>
setMissionAttendance(payload, { missionId, userId, response: "yes" });
beforeAll(async () => {
payload = await getTestPayload();
const map = (await payload.create({
collection: "maps",
data: { name: `${RUN} map`, worldSizeWidth: 8192, worldSizeHeight: 8192 } as never,
overrideAccess: true,
depth: 0,
})) as unknown as MissionMap;
mapId = map.id;
junior = await makeRank("Junior");
mid = await makeRank("Mid");
senior = await makeRank("Senior");
author = await makeUser("author");
officer = await makeUser("officer");
outsider = await makeUser("outsider");
leader = await makeUser("leader");
member = await makeUser("member");
peer = await makeUser("peer");
await setRank(author.id, mid.id);
await setRank(officer.id, mid.id);
await setRank(outsider.id, junior.id);
await setRank(leader.id, senior.id);
await setRank(member.id, junior.id);
await setRank(peer.id, junior.id);
const squad = (await payload.create({
collection: "assignments",
data: {
name: `${RUN} squad`,
type: "squad",
leader: leader.id,
members: [member.id],
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
assignmentIds.push(squad.id);
});
afterAll(async () => {
for (const id of missionIds) {
for (const collection of ["mission-command-links", "evaluations", "mission-attendances"] as const) {
const docs = await payload.find({
collection,
where: { mission: { equals: id } },
limit: 500,
depth: 0,
overrideAccess: true,
});
for (const doc of docs.docs) {
await payload.delete({ collection, id: doc.id, overrideAccess: true }).catch(() => {});
}
}
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
for (const id of assignmentIds) {
await payload.delete({ collection: "assignments", id, overrideAccess: true }).catch(() => {});
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
for (const id of rankIds) {
await payload.delete({ collection: "ranks", id, overrideAccess: true }).catch(() => {});
}
});
it("defaults to the squad leader, and ranks a member with no present leader to the nearest higher rank", async () => {
const mission = await makeMission("Defaults");
await rsvp(mission.id, leader.id);
await rsvp(mission.id, member.id);
const defaults = await computeDefaultChain(payload, mission.id);
expect(defaults).toEqual([
{ supervisorId: leader.id, subordinateId: member.id, source: "default" },
]);
// Leader absent: the member's default falls back to rank (no higher rank present,
// so nobody). The peer has equal rank and gets no supervisor.
const noLeader = await makeMission("NoLeader");
await rsvp(noLeader.id, member.id);
await rsvp(noLeader.id, peer.id);
expect(await computeDefaultChain(payload, noLeader.id)).toEqual([]);
});
it("uses the nearest higher rank as fallback when the leader is absent", async () => {
const mission = await makeMission("RankFallback");
await rsvp(mission.id, member.id); // junior, no present leader
await rsvp(mission.id, author.id); // mid, nearest higher rank present
await rsvp(mission.id, leader.id); // senior, also higher
// Leader is present, so the assignment rule wins; remove the leader to test fallback.
await payload.delete({
collection: "mission-attendances",
where: { and: [{ mission: { equals: mission.id } }, { user: { equals: leader.id } }] },
overrideAccess: true,
});
const chain = await computeDefaultChain(payload, mission.id);
expect(chain).toEqual([{ supervisorId: author.id, subordinateId: member.id, source: "default" }]);
});
it("rejects self-links, duplicates, inverted rank, and cycles", async () => {
const mission = await makeMission("Validation");
for (const u of [leader, member, peer]) await rsvp(mission.id, u.id);
expect(
await validateChain(payload, mission.id, [
{ supervisorId: member.id, subordinateId: member.id },
]),
).toContainEqual(expect.stringMatching(/own supervisor/));
expect(
await validateChain(payload, mission.id, [
{ supervisorId: leader.id, subordinateId: member.id },
{ supervisorId: leader.id, subordinateId: member.id },
]),
).toContainEqual(expect.stringMatching(/Duplicate/));
// Inverted: junior member set as supervisor of senior leader.
expect(
await validateChain(payload, mission.id, [
{ supervisorId: member.id, subordinateId: leader.id },
]),
).toContainEqual(expect.stringMatching(/cannot rank below/));
// Equal rank is allowed for command links (chain overrides rank).
expect(
await validateChain(payload, mission.id, [
{ supervisorId: peer.id, subordinateId: member.id },
]),
).toEqual([]);
// Cycle between equal-rank peers.
expect(
await validateChain(payload, mission.id, [
{ supervisorId: peer.id, subordinateId: member.id },
{ supervisorId: member.id, subordinateId: peer.id },
]),
).toContainEqual(expect.stringMatching(/cycle/));
});
it("refuses non-participants", async () => {
const mission = await makeMission("NonParticipant");
await rsvp(mission.id, leader.id);
const errors = await validateChain(payload, mission.id, [
{ supervisorId: leader.id, subordinateId: outsider.id },
]);
expect(errors).toContainEqual(expect.stringMatching(/yes RSVP/));
});
it("lets a chain equal-rank supervisor rate, while spectrum still needs a strict rank gap", async () => {
const mission = await makeMission("EqualRankEligibility");
for (const u of [member, peer]) await rsvp(mission.id, u.id);
expect((await evaluateEligibility(payload, { raterId: peer.id, rateeId: member.id, missionId: mission.id })).eligible).toBe(false);
const save = await saveMissionChain(payload, {
missionId: mission.id,
updatedById: author.id,
links: [{ supervisorId: peer.id, subordinateId: member.id }],
});
expect(save.errors).toEqual([]);
const eligible = await evaluateEligibility(payload, {
raterId: peer.id,
rateeId: member.id,
missionId: mission.id,
});
expect(eligible).toMatchObject({ eligible: true, kind: "command" });
});
it("freezes defaults on the first rating and locks edits afterwards", async () => {
const mission = await makeMission("Freeze");
await rsvp(mission.id, leader.id);
await rsvp(mission.id, member.id);
await freezeDefaults(payload, mission.id);
const resolved = await resolveMissionChain(payload, mission.id);
expect(resolved.mode).toBe("stored");
// A later assignment change must not reclassify the frozen chain.
await payload.update({
collection: "assignments",
id: assignmentIds[0],
data: { members: [] },
overrideAccess: true,
depth: 0,
});
const frozen = await resolveMissionChain(payload, mission.id);
expect(frozen.links).toEqual([
{ supervisorId: leader.id, subordinateId: member.id, source: "default" },
]);
await payload.update({
collection: "assignments",
id: assignmentIds[0],
data: { members: [member.id] },
overrideAccess: true,
depth: 0,
});
await upsertEvaluation(payload, {
raterId: leader.id,
rateeId: member.id,
missionId: mission.id,
level: "adequate",
});
expect(await getChainLockReason(payload, { id: mission.id, ownershipAndStatus: { status: "Completed" } })).toMatch(/locked/);
const blocked = await saveMissionChain(payload, {
missionId: mission.id,
updatedById: author.id,
links: [],
});
expect(blocked.errors.length).toBeGreaterThan(0);
});
it("keeps legacy missions (rated, no rows) on the original assignment rule", async () => {
const mission = await makeMission("Legacy");
await rsvp(mission.id, leader.id);
await rsvp(mission.id, member.id);
await upsertEvaluation(payload, {
raterId: leader.id,
rateeId: member.id,
missionId: mission.id,
level: "adequate",
});
const resolved = await resolveMissionChain(payload, mission.id);
expect(resolved.mode).toBe("legacy");
});
it("allows authors, Zeus and superusers to edit, and denies officers and ratees", async () => {
const mission = await makeMission("Permissions");
const missionDoc = {
id: mission.id,
ownershipAndStatus: { status: "Completed", authors: [author.id], zeus: [] },
};
expect(await canEditMissionChain(payload, author, missionDoc as never)).toBe(true);
expect(await canEditMissionChain(payload, officer, missionDoc as never)).toBe(false);
expect(await canEditMissionChain(payload, member, missionDoc as never)).toBe(false);
const withZeus = { ...missionDoc, ownershipAndStatus: { ...missionDoc.ownershipAndStatus, zeus: [outsider.id] } };
expect(await canEditMissionChain(payload, outsider, withZeus as never)).toBe(true);
});
it("reset returns a mission to live defaults", async () => {
const mission = await makeMission("Reset");
await rsvp(mission.id, leader.id);
await rsvp(mission.id, member.id);
await saveMissionChain(payload, {
missionId: mission.id,
updatedById: author.id,
links: [{ supervisorId: leader.id, subordinateId: member.id }],
});
expect((await resolveMissionChain(payload, mission.id)).mode).toBe("stored");
await resetMissionChain(payload, mission.id);
expect((await resolveMissionChain(payload, mission.id)).mode).toBe("default");
});
it("reminders include equal-rank chain links and keep strict-rank pairs", async () => {
const mission = await makeMission("Reminders");
for (const u of [leader, member, peer]) await rsvp(mission.id, u.id);
await saveMissionChain(payload, {
missionId: mission.id,
updatedById: author.id,
links: [{ supervisorId: peer.id, subordinateId: member.id }],
});
const plan = await computeEvaluationReminderPlan(payload, mission.id);
const memberEntry = plan.recipients.find((r) => r.userId === member.id);
expect(memberEntry?.rateLeaders.map((l) => l.userId)).toContain(peer.id);
// Strict pair leader (senior) vs member (junior) still reminded.
expect(memberEntry?.rateLeaders.map((l) => l.userId)).toContain(leader.id);
});
});