Replace the per-person supervisor list as the primary chain-of-command surface on the mission page with a layered DAG rendered on React Flow. Both views share one draft; connections stay editable until the first evaluation or cancellation locks them. - getChainViewerState: always returns state (viewer-aware), replacing getChainEditorState's null-for-viewers contract so plain viewers see the chain read-only - auto-layout wraps wide layers instead of shrinking past readability - tactical dossier styling for nodes and canvas chrome
305 lines
11 KiB
TypeScript
305 lines
11 KiB
TypeScript
/**
|
|
* Org-chart feature coverage: the pure chain layout and client draft rules,
|
|
* plus getChainViewerState end-to-end (permissions, modes, rank labels).
|
|
* Mirrors the fixtures of mission-command-chain.int.spec.ts.
|
|
*/
|
|
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 { getChainViewerState, saveMissionChain } from "@/lib/command-chain";
|
|
import {
|
|
CHAIN_NODE_H,
|
|
computeChainLayout,
|
|
} from "@/components/frontend/intelligence/chainLayout";
|
|
import {
|
|
autoOrientPair,
|
|
checkConnect,
|
|
wouldCreateCycle,
|
|
type ChainDraft,
|
|
} from "@/components/frontend/intelligence/chainDraftRules";
|
|
import { setMissionAttendance } from "@/lib/attendance";
|
|
|
|
describe("chain org-chart layout (pure)", () => {
|
|
// ids: 1 capt, 2 lt (under capt), 3 sgt (under capt), 4 pvt (under lt), 5 rct (unlinked)
|
|
const links = [
|
|
{ supervisorId: 1, subordinateId: 2 },
|
|
{ supervisorId: 1, subordinateId: 3 },
|
|
{ supervisorId: 2, subordinateId: 4 },
|
|
];
|
|
|
|
it("layers supervisors above subordinates with linked nodes only where edges reach", () => {
|
|
const layout = computeChainLayout({ participantIds: [1, 2, 3, 4, 5], links });
|
|
const y = (id: number) => layout.positions.get(id)?.y ?? Infinity;
|
|
expect(layout.positions.size).toBe(5);
|
|
expect(y(1)).toBeLessThan(y(2));
|
|
expect(y(2)).toBeLessThan(y(4));
|
|
expect(y(3)).toBeGreaterThan(y(1));
|
|
});
|
|
|
|
it("places unlinked participants in the band below all layers", () => {
|
|
const layout = computeChainLayout({ participantIds: [1, 2, 3, 4, 5], links });
|
|
const y = (id: number) => layout.positions.get(id)?.y ?? -Infinity;
|
|
const linkedMaxY = Math.max(...[1, 2, 3, 4].map(y));
|
|
expect(layout.bandTop).not.toBeNull();
|
|
expect(y(5)).toBeGreaterThanOrEqual(linkedMaxY + CHAIN_NODE_H);
|
|
});
|
|
|
|
it("is deterministic across calls with equal inputs", () => {
|
|
const a = computeChainLayout({ participantIds: [5, 1, 3, 2, 4], links });
|
|
const b = computeChainLayout({ participantIds: [5, 1, 3, 2, 4], links });
|
|
for (const id of [1, 2, 3, 4, 5]) {
|
|
expect(a.positions.get(id)).toEqual(b.positions.get(id));
|
|
}
|
|
});
|
|
|
|
it("terminates and returns positions even when input contains a cycle", () => {
|
|
const cyclic = [
|
|
{ supervisorId: 1, subordinateId: 2 },
|
|
{ supervisorId: 2, subordinateId: 3 },
|
|
{ supervisorId: 3, subordinateId: 1 }, // back edge: must not hang the DFS
|
|
];
|
|
const layout = computeChainLayout({ participantIds: [1, 2, 3], links: cyclic });
|
|
expect(layout.positions.size).toBe(3);
|
|
});
|
|
|
|
it("ignores edges touching unknown or self endpoints", () => {
|
|
const messy = [
|
|
{ supervisorId: 1, subordinateId: 99 },
|
|
{ supervisorId: 2, subordinateId: 2 },
|
|
{ supervisorId: 2, subordinateId: 1 },
|
|
];
|
|
const layout = computeChainLayout({ participantIds: [1, 2], links: messy });
|
|
expect(layout.positions.get(2)!.y).toBeLessThan(layout.positions.get(1)!.y);
|
|
expect(layout.bandTop).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("chain draft rules (pure client mirror)", () => {
|
|
const participants = [
|
|
{ id: 10, rankIndex: 5 }, // captain
|
|
{ id: 11, rankIndex: 3 }, // lieutenant
|
|
{ id: 12, rankIndex: null }, // unranked recruit
|
|
];
|
|
const emptyDraft: ChainDraft = {};
|
|
|
|
it("rejects self-links, rank inversions, duplicates and cycles like the server", () => {
|
|
expect(checkConnect(emptyDraft, participants, 10, 10)).toBe("self");
|
|
expect(checkConnect(emptyDraft, participants, 11, 10)).toBe("rank-inverted");
|
|
expect(checkConnect({ 12: [10] }, participants, 10, 12)).toBe("duplicate");
|
|
// Chain 10 -> 11 -> 12 (draft keyed by subordinate).
|
|
const loopable: ChainDraft = { 11: [10], 12: [11] };
|
|
// A shortcut down is legal...
|
|
expect(wouldCreateCycle(loopable, 10, 12)).toBe(false);
|
|
// ...closing the loop back up is not.
|
|
expect(wouldCreateCycle(loopable, 12, 10)).toBe(true);
|
|
expect(checkConnect(loopable, participants, 12, 10)).toBe("cycle");
|
|
});
|
|
|
|
it("lets unranked and equal-rank edges through (server allows them)", () => {
|
|
expect(checkConnect(emptyDraft, participants, 10, 12)).toBe(null);
|
|
expect(checkConnect(emptyDraft, participants, 12, 10)).toBe(null);
|
|
const peers = [
|
|
{ id: 20, rankIndex: 3 },
|
|
{ id: 21, rankIndex: 3 },
|
|
];
|
|
expect(checkConnect({}, peers, 20, 21)).toBe(null);
|
|
});
|
|
|
|
it("auto-orients drags so the higher rank becomes the supervisor", () => {
|
|
// Drag up from pvt(11) to capt(10): captain must end up the supervisor.
|
|
expect(autoOrientPair(participants, 11, 10)).toEqual({ supervisorId: 10, subordinateId: 11 });
|
|
// Drag down: direction stands.
|
|
expect(autoOrientPair(participants, 10, 11)).toEqual({ supervisorId: 10, subordinateId: 11 });
|
|
// Unranked target: the drag direction stands (server-side rules decide).
|
|
expect(autoOrientPair(participants, 10, 12)).toEqual({ supervisorId: 10, subordinateId: 12 });
|
|
});
|
|
});
|
|
|
|
let payload: Payload;
|
|
|
|
const RUN = `coc-chart-${Date.now().toString(36)}`;
|
|
|
|
describe("getChainViewerState (integration)", () => {
|
|
let mapId: number;
|
|
const rankIds: number[] = [];
|
|
const userIds: number[] = [];
|
|
const missionIds: number[] = [];
|
|
|
|
let senior: Rank;
|
|
let junior: Rank;
|
|
let author: User;
|
|
let leader: User;
|
|
let member: 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,
|
|
});
|
|
await payload.update({
|
|
collection: "profiles",
|
|
id: (profiles.docs[0] as { id: number }).id,
|
|
data: { rank: rankId },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
};
|
|
|
|
const makeMission = async (label: string): Promise<Mission> => {
|
|
const mission = (await payload.create({
|
|
collection: "missions",
|
|
data: {
|
|
name: `${RUN} ${label}`,
|
|
codeName: `${RUN}-${label}`,
|
|
summary: "Org chart 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: "Planning",
|
|
visibility: "unit",
|
|
},
|
|
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;
|
|
};
|
|
|
|
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;
|
|
|
|
// Ladder order follows creation order (_order), so create junior first.
|
|
junior = (await payload.create({
|
|
collection: "ranks",
|
|
data: { name: `${RUN} Junior`, abbreviation: `${RUN}-Jr`, description: "test" },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Rank;
|
|
rankIds.push(junior.id);
|
|
senior = (await payload.create({
|
|
collection: "ranks",
|
|
data: { name: `${RUN} Senior`, abbreviation: `${RUN}-Sr`, description: "test" },
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as Rank;
|
|
rankIds.push(senior.id);
|
|
|
|
author = await makeUser("author");
|
|
leader = await makeUser("leader");
|
|
member = await makeUser("member");
|
|
|
|
await setRank(leader.id, senior.id);
|
|
await setRank(member.id, junior.id);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
for (const id of missionIds) {
|
|
const docs = await payload.find({
|
|
collection: "mission-command-links",
|
|
where: { mission: { equals: id } },
|
|
limit: 500,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
for (const doc of docs.docs) {
|
|
await payload.delete({ collection: "mission-command-links", id: doc.id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
const rsvps = await payload.find({
|
|
collection: "mission-attendances",
|
|
where: { mission: { equals: id } },
|
|
limit: 500,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
for (const doc of rsvps.docs) {
|
|
await payload.delete({ collection: "mission-attendances", id: doc.id, overrideAccess: true }).catch(() => {});
|
|
}
|
|
await payload.delete({ collection: "missions", 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("shows the live default chain read-only to plain viewers, with rank labels", async () => {
|
|
const mission = await makeMission("Viewer");
|
|
await setMissionAttendance(payload, { missionId: mission.id, userId: leader.id, response: "yes" });
|
|
await setMissionAttendance(payload, { missionId: mission.id, userId: member.id, response: "yes" });
|
|
|
|
// A would-be editor is required by makeMission authorship; the plain viewer
|
|
// here is the leader (attending, not an author).
|
|
const state = await getChainViewerState(payload, leader as never, mission as never);
|
|
expect(state.editable).toBe(false);
|
|
expect(state.mode).toBe("default");
|
|
expect(state.participants.map((p) => p.name)).toContain(leader.displayName);
|
|
const leaderRow = state.participants.find((p) => p.id === leader.id)!;
|
|
expect(leaderRow.rankLabel).toBe(senior.abbreviation);
|
|
expect(typeof leaderRow.rankIndex).toBe("number");
|
|
});
|
|
|
|
it("grants authors an editable chain and reflects saved overrides", async () => {
|
|
const mission = await makeMission("Editable");
|
|
await setMissionAttendance(payload, { missionId: mission.id, userId: leader.id, response: "yes" });
|
|
await setMissionAttendance(payload, { missionId: mission.id, userId: member.id, response: "yes" });
|
|
|
|
const before = await getChainViewerState(payload, author as never, mission as never);
|
|
expect(before.editable).toBe(true);
|
|
expect(before.lockReason).toBeNull();
|
|
|
|
const saved = await saveMissionChain(payload, {
|
|
missionId: mission.id,
|
|
updatedById: author.id,
|
|
links: [{ supervisorId: leader.id, subordinateId: member.id }],
|
|
});
|
|
expect(saved.errors).toEqual([]);
|
|
|
|
const after = await getChainViewerState(payload, author as never, mission as never);
|
|
expect(after.mode).toBe("stored");
|
|
expect(after.links).toHaveLength(1);
|
|
expect(after.links[0]).toMatchObject({ supervisorId: leader.id, subordinateId: member.id });
|
|
});
|
|
});
|