diff --git a/src/app/(frontend)/intelligence/missions/[id]/page.tsx b/src/app/(frontend)/intelligence/missions/[id]/page.tsx index 6ab6edb4..71ac69c8 100644 --- a/src/app/(frontend)/intelligence/missions/[id]/page.tsx +++ b/src/app/(frontend)/intelligence/missions/[id]/page.tsx @@ -36,8 +36,8 @@ import { MissionFactions } from "@/components/frontend/intelligence/MissionFacti import { MissionThreatAssessment } from "@/components/frontend/intelligence/MissionThreatAssessment"; import { MissionRoles } from "@/components/frontend/intelligence/MissionRoles"; import { MissionRoleSignups } from "@/components/frontend/intelligence/MissionRoleSignups"; -import { MissionCommandChainEditor } from "@/components/frontend/intelligence/MissionCommandChainEditor"; -import { getChainEditorState } from "@/lib/command-chain"; +import { MissionCommandChainSection } from "@/components/frontend/intelligence/MissionCommandChainSection"; +import { getChainViewerState } from "@/lib/command-chain"; import { MissionLogistics } from "@/components/frontend/intelligence/MissionLogistics"; import { MissionComms } from "@/components/frontend/intelligence/MissionComms"; import { MissionAttendance } from "@/components/frontend/intelligence/MissionAttendance"; @@ -188,9 +188,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro const canManage = currentUser ? await hasPermission(payload, currentUser, "missions:update") : false; - const commandChainEditor = currentUser - ? await getChainEditorState(payload, currentUser, mission as never) - : null; + const commandChain = await getChainViewerState(payload, currentUser as never, mission as never); const createdById = typeof mission.createdBy === "object" ? mission.createdBy?.id : mission.createdBy; @@ -643,23 +641,21 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro /> - {commandChainEditor && ( - - - - )} + + + { + name: string; + rankLabel: string | null; + /** True for the unlinked band: dashed border, dimmer chrome. */ + unlinked: boolean; + connectable: boolean; +} + +interface LabelNodeData extends Record { + label: string; +} + +type PersonNodeModel = Node; +type LabelNodeModel = Node; + +interface ChainEdgeData extends Record { + invalid: boolean; + removeable: boolean; + onRemove?: () => void; +} + +function ChainPersonNodeCard({ data, selected }: NodeProps) { + return ( +
+ + {data.name} + + + {data.rankLabel ?? "UNRANKED"} + + {data.connectable && ( + <> + + + + )} +
+ ); +} + +function ChainBandLabelNode({ data }: NodeProps) { + return ( +
+ {data.label} +
+ ); +} + +function ChainCommandEdge({ id, sourceX, sourceY, targetX, targetY, markerEnd, selected, data }: EdgeProps) { + const edgeData = data as ChainEdgeData | undefined; + const [path, labelX, labelY] = getSmoothStepPath({ + sourceX, + sourceY, + targetX, + targetY, + sourcePosition: Position.Bottom, + targetPosition: Position.Top, + borderRadius: 8, + }); + const stroke = edgeData?.invalid ? "#f87171" : "rgba(255,255,255,0.35)"; + return ( + <> + + + {selected && edgeData?.removeable && ( +
+ +
+ )} +
+ + ); +} + +const nodeTypes: NodeTypes = { + chainPerson: ChainPersonNodeCard, + chainBandLabel: ChainBandLabelNode, +}; + +const edgeTypes: EdgeTypes = { + command: ChainCommandEdge, +}; + +/** Rank-aware auto-orientation lives with the rules; edges are directed. */ +export interface MissionCommandChainChartProps { + participants: ChartParticipant[]; + draft: ChainDraft; + /** `"supervisor->subordinate"` keys of draft links that break a rule. */ + invalidKeys: Set; + editable: boolean; + onAddLink: (supervisorId: number, subordinateId: number) => void; + onRemoveLink: (supervisorId: number, subordinateId: number) => void; +} + +function ChartInner({ + participants, + draft, + invalidKeys, + editable, + onAddLink, + onRemoveLink, +}: MissionCommandChainChartProps) { + const rf = useReactFlow(); + const participantKey = participants.map((p) => p.id).join(","); + + const layout = React.useMemo(() => { + const links = Object.entries(draft).flatMap(([subordinateId, supervisorIds]) => + supervisorIds.map((supervisorId) => ({ supervisorId, subordinateId: Number(subordinateId) })), + ); + return computeChainLayout({ participantIds: participants.map((p) => p.id), links }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [participantKey, draft]); + + /** Participants with at least one command edge (either direction). */ + const linked = React.useMemo(() => { + const set = new Set(); + for (const [subordinateId, supervisorIds] of Object.entries(draft)) { + if (supervisorIds.length > 0) { + set.add(Number(subordinateId)); + for (const s of supervisorIds) set.add(s); + } + } + return set; + }, [draft]); + + const nodes = React.useMemo(() => { + const flowNodes: Node[] = participants.map((p) => ({ + id: String(p.id), + type: "chainPerson", + position: layout.positions.get(p.id) ?? { x: 0, y: 0 }, + width: CHAIN_NODE_W, + height: CHAIN_NODE_H, + draggable: false, + data: { + name: p.name, + rankLabel: p.rankLabel, + unlinked: !linked.has(p.id), + connectable: editable, + } satisfies PersonNodeData, + })); + if (layout.bandTop !== null) { + // Caption above the first band card; shares its x so the two line up. + const firstUnlinked = participants.find((p) => !linked.has(p.id)); + const x = firstUnlinked ? (layout.positions.get(firstUnlinked.id)?.x ?? 0) : 0; + flowNodes.push({ + id: "chain-band-label", + type: "chainBandLabel", + position: { x, y: layout.bandTop - 26 }, + draggable: false, + selectable: false, + focusable: false, + data: { label: "No command links" } satisfies LabelNodeData, + }); + } + return flowNodes; + }, [participants, layout, linked, editable]); + + const edges = React.useMemo( + () => + Object.entries(draft).flatMap(([subordinateIdText, supervisorIds]) => { + const subordinateId = Number(subordinateIdText); + return supervisorIds.map((supervisorId) => { + const invalid = invalidKeys.has(`${supervisorId}->${subordinateId}`); + return { + id: `${supervisorId}->${subordinateId}`, + source: String(supervisorId), + target: String(subordinateId), + sourceHandle: "s", + targetHandle: "t", + type: "command", + selectable: editable, + markerEnd: { type: MarkerType.ArrowClosed, width: 14, height: 14, color: invalid ? "#f87171" : "rgba(255,255,255,0.5)" }, + data: { + invalid, + removeable: editable, + onRemove: () => onRemoveLink(supervisorId, subordinateId), + } satisfies ChainEdgeData, + }; + }); + }), + [draft, invalidKeys, editable, onRemoveLink], + ); + + const onConnect: OnConnect = React.useCallback( + (connection) => { + if (!editable || connection.source == null || connection.target == null) return; + onAddLink(Number(connection.source), Number(connection.target)); + }, + [editable, onAddLink], + ); + + // Re-fit when the participant set changes (RSVP churn after router.refresh). + React.useEffect(() => { + rf.fitView({ padding: 0.15, maxZoom: 1 }); + }, [rf, participantKey]); + + return ( +
+ + + + +
+ ); +} + +export function MissionCommandChainChart(props: MissionCommandChainChartProps) { + return ( + + + + ); +} diff --git a/src/components/frontend/intelligence/MissionCommandChainEditor.tsx b/src/components/frontend/intelligence/MissionCommandChainEditor.tsx deleted file mode 100644 index f7e3e643..00000000 --- a/src/components/frontend/intelligence/MissionCommandChainEditor.tsx +++ /dev/null @@ -1,223 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { useRouter } from "next/navigation"; -import { toast } from "sonner"; -import { ChevronDown } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { Button } from "@/components/ui/button"; -import { Badge } from "@/components/ui/badge"; -import { Label } from "@/components/ui/label"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; -import { Alert, AlertDescription } from "@/components/ui/alert"; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; -import { - resetMissionCommandChain, - saveMissionCommandChain, -} from "@/app/(frontend)/intelligence/missions/actions"; - -interface ChainParticipantView { - id: number; - name: string; -} - -interface ChainLinkView { - supervisorId: number; - subordinateId: number; - source: "default" | "override"; -} - -interface MissionCommandChainEditorProps { - missionId: number; - mode: "stored" | "default" | "legacy"; - links: ChainLinkView[]; - participants: ChainParticipantView[]; - editable: boolean; - lockReason: string | null; -} - -/** - * Per-subordinate supervisor picker. Edits are held locally until Save; the - * server re-validates everything (participants, rank, cycles, duplicates). - */ -export function MissionCommandChainEditor({ - missionId, - mode, - links, - participants, - editable, - lockReason, -}: MissionCommandChainEditorProps) { - const router = useRouter(); - const [pending, setPending] = useState(false); - const [contentOpen, setContentOpen] = useState(true); - const initialSupervisors = (subordinateId: number) => - links.filter((l) => l.subordinateId === subordinateId).map((l) => l.supervisorId); - const [draft, setDraft] = useState>(() => - Object.fromEntries(participants.map((p) => [p.id, initialSupervisors(p.id)])), - ); - const nameOf = (id: number) => participants.find((p) => p.id === id)?.name ?? `#${id}`; - - const save = async () => { - setPending(true); - const pairs = Object.entries(draft).flatMap(([sub, sups]) => - sups.map((supervisorId) => ({ supervisorId, subordinateId: Number(sub) })), - ); - const result = await saveMissionCommandChain({ missionId, links: pairs }); - setPending(false); - if (!result.success) { - toast.error(result.error ?? "Could not save the chain."); - return; - } - toast.success("Command chain saved for this mission."); - router.refresh(); - }; - - const reset = async () => { - setPending(true); - const result = await resetMissionCommandChain({ missionId }); - setPending(false); - if (!result.success) { - toast.error(result.error ?? "Could not reset the chain."); - return; - } - toast.success("Chain reset to defaults."); - router.refresh(); - }; - - const addSupervisor = (subordinateId: number, supervisorId: number) => { - setDraft((prev) => { - const current = prev[subordinateId] ?? []; - if (current.includes(supervisorId)) return prev; - return { ...prev, [subordinateId]: [...current, supervisorId] }; - }); - }; - - const removeSupervisor = (subordinateId: number, supervisorId: number) => { - setDraft((prev) => ({ - ...prev, - [subordinateId]: (prev[subordinateId] ?? []).filter((id) => id !== supervisorId), - })); - }; - - return ( - - - - - - {mode === "stored" ? "Override" : mode === "legacy" ? "Legacy" : "Defaults"} - - - - Who was in command of whom for this operation only. Permanent assignments are not - changed. Supervisors may rate their subordinate as a command review. - - - - -
- - - -
-
- - - - {mode === "legacy" && ( - - - This mission was rated before the chain existed, so its command reviews follow the - original assignment rule and cannot be changed here. - - - )} - {!editable && lockReason && ( - - {lockReason} - - )} - - {mode !== "legacy" && ( -
- {participants.map((sub) => { - const supervisors = draft[sub.id] ?? []; - const options = participants.filter( - (p) => p.id !== sub.id && !supervisors.includes(p.id), - ); - return ( -
- -
- {supervisors.length === 0 && ( - No supervisor - )} - {supervisors.map((supId) => ( - - {nameOf(supId)} - {editable && ( - - )} - - ))} - {editable && options.length > 0 && ( - - )} -
-
- ); - })} -
- )} - - {editable && mode !== "legacy" && ( -
- - -
- )} -
-
-
-
- ); -} diff --git a/src/components/frontend/intelligence/MissionCommandChainList.tsx b/src/components/frontend/intelligence/MissionCommandChainList.tsx new file mode 100644 index 00000000..b61f3b2e --- /dev/null +++ b/src/components/frontend/intelligence/MissionCommandChainList.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { Label } from "@/components/ui/label"; +import { Badge } from "@/components/ui/badge"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import type { ChainParticipant } from "@/lib/command-chain"; +import type { ChainDraft } from "./chainDraftRules"; + +interface MissionCommandChainListProps { + participants: ChainParticipant[]; + draft: ChainDraft; + editable: boolean; + onAddSupervisor: (subordinateId: number, supervisorId: number) => void; + onRemoveSupervisor: (subordinateId: number, supervisorId: number) => void; +} + +/** + * The per-person supervisor editor, previously the whole chain surface and now + * the "List" tab. Rows read directly from the shared draft owned by + * `MissionCommandChainSection`; the chart tab edits the same draft. + */ +export function MissionCommandChainList({ + participants, + draft, + editable, + onAddSupervisor, + onRemoveSupervisor, +}: MissionCommandChainListProps) { + const nameOf = (id: number) => participants.find((p) => p.id === id)?.name ?? `#${id}`; + + if (participants.length === 0) { + return ( +

+ Nobody has RSVP'd yes to this mission yet, so there is no chain to configure. +

+ ); + } + + return ( +
+ {participants.map((sub) => { + const supervisors = draft[sub.id] ?? []; + const options = participants.filter((p) => p.id !== sub.id && !supervisors.includes(p.id)); + return ( +
+ +
+ {supervisors.length === 0 && ( + No supervisor + )} + {supervisors.map((supId) => ( + + {nameOf(supId)} + {editable && ( + + )} + + ))} + {editable && options.length > 0 && ( + + )} +
+
+ ); + })} +
+ ); +} diff --git a/src/components/frontend/intelligence/MissionCommandChainSection.tsx b/src/components/frontend/intelligence/MissionCommandChainSection.tsx new file mode 100644 index 00000000..cdda8196 --- /dev/null +++ b/src/components/frontend/intelligence/MissionCommandChainSection.tsx @@ -0,0 +1,226 @@ +"use client"; + +import * as React from "react"; +import { useRouter } from "next/navigation"; +import { toast } from "sonner"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { resetMissionCommandChain, saveMissionCommandChain } from "@/app/(frontend)/intelligence/missions/actions"; +import type { ChainMode, ChainParticipant } from "@/lib/command-chain"; +import { + CONNECT_REJECTION_MESSAGES, + autoOrientPair, + checkConnect, + invalidLinkKeys, + type ChainDraft, +} from "./chainDraftRules"; +import { MissionCommandChainChart } from "./MissionCommandChainChart"; +import { MissionCommandChainList } from "./MissionCommandChainList"; + +interface MissionCommandChainSectionProps { + missionId: number; + mode: ChainMode; + links: Array<{ supervisorId: number; subordinateId: number; source: "default" | "override" }>; + participants: ChainParticipant[]; + editable: boolean; + lockReason: string | null; +} + +const MODE_LABELS: Record = { + stored: "Override", + default: "Live defaults", + legacy: "Legacy rule", +}; + +function draftFromLinks( + links: MissionCommandChainSectionProps["links"], +): ChainDraft { + const draft: ChainDraft = {}; + for (const link of links) { + const row = draft[link.subordinateId] ?? []; + if (!row.includes(link.supervisorId)) draft[link.subordinateId] = [...row, link.supervisorId]; + } + return draft; +} + +/** + * Operation COMMAND section: the chain of command as an editable org chart + * (primary) plus the per-person supervisor list (fallback). Both tabs share + * one draft; edits stay local until Save, and the server re-validates + * everything (`saveMissionCommandChain`). + */ +export function MissionCommandChainSection({ + missionId, + mode, + links, + participants, + editable, + lockReason, +}: MissionCommandChainSectionProps) { + const router = useRouter(); + const [pending, setPending] = React.useState(false); + const [draft, setDraft] = React.useState(() => draftFromLinks(links)); + + // Refreeze the draft when a save/reset refreshes server state. + const signature = React.useMemo( + () => + links + .map((l) => `${l.supervisorId}>${l.subordinateId}`) + .sort() + .join(","), + [links], + ); + React.useEffect(() => { + setDraft(draftFromLinks(links)); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [signature]); + + const tryAdd = (supervisorId: number, subordinateId: number) => { + const error = checkConnect(draft, participants, supervisorId, subordinateId); + if (error) { + toast.error(CONNECT_REJECTION_MESSAGES[error]); + return; + } + setDraft((prev) => { + const row = prev[subordinateId] ?? []; + if (row.includes(supervisorId)) return prev; + return { ...prev, [subordinateId]: [...row, supervisorId] }; + }); + }; + + const remove = (supervisorId: number, subordinateId: number) => { + setDraft((prev) => ({ + ...prev, + [subordinateId]: (prev[subordinateId] ?? []).filter((s) => s !== supervisorId), + })); + }; + + /** Canvas connect: the drag direction is only a hint; rank decides. */ + const handleChartAdd = (dragFrom: number, dragTo: number) => { + const { supervisorId, subordinateId } = autoOrientPair(participants, dragFrom, dragTo); + tryAdd(supervisorId, subordinateId); + }; + + const invalidKeys = React.useMemo(() => invalidLinkKeys(draft, participants), [draft, participants]); + + const save = async () => { + setPending(true); + const payload = Object.entries(draft).flatMap(([subordinateId, supervisorIds]) => + supervisorIds.map((supervisorId) => ({ supervisorId, subordinateId: Number(subordinateId) })), + ); + const result = await saveMissionCommandChain({ missionId, links: payload }); + setPending(false); + if (!result.success) { + toast.error(result.error ?? "Could not save the chain."); + return; + } + toast.success("Chain of command saved."); + router.refresh(); + }; + + const reset = async () => { + setPending(true); + const result = await resetMissionCommandChain({ missionId }); + setPending(false); + if (!result.success) { + toast.error(result.error ?? "Could not reset the chain."); + return; + } + toast.success("Chain reset to live defaults."); + router.refresh(); + }; + + const nothingToDraw = participants.length === 0; + + const [tab, setTab] = React.useState<"chart" | "list">(mode === "legacy" ? "list" : "chart"); + + return ( +
+
+

+ Who commands whom for this operation. Supervisors may rate their + subordinates as a command review. Drag between cards to add a link; + the higher-ranked card becomes the supervisor. +

+ + {MODE_LABELS[mode]} + +
+ + {mode === "legacy" && ( + + + This mission was rated before the chain existed, so its command reviews follow the + original assignment rule and cannot be edited here. + + + )} + {editable === false && lockReason && mode !== "legacy" && ( + + {lockReason} + + )} + + {mode === "legacy" ? ( + {}} + onRemoveSupervisor={() => {}} + /> + ) : nothingToDraw ? ( +

+ No one has RSVP'd yes yet, so there is no chain to draw. +

+ ) : ( + setTab(v === "list" ? "list" : "chart")}> + + Org chart + List + + + ({ + id: p.id, + name: p.name, + rankIndex: p.rankIndex, + rankLabel: p.rankLabel, + }))} + draft={draft} + invalidKeys={invalidKeys} + editable={editable} + onAddLink={handleChartAdd} + onRemoveLink={remove} + /> + + + tryAdd(supervisorId, subordinateId)} + onRemoveSupervisor={(subordinateId, supervisorId) => remove(supervisorId, subordinateId)} + /> + + + )} + + {editable && mode !== "legacy" && !nothingToDraw && ( +
+ + + + Changes apply to this mission only + +
+ )} +
+ ); +} diff --git a/src/components/frontend/intelligence/chainDraftRules.ts b/src/components/frontend/intelligence/chainDraftRules.ts new file mode 100644 index 00000000..1c32e133 --- /dev/null +++ b/src/components/frontend/intelligence/chainDraftRules.ts @@ -0,0 +1,142 @@ +/** + * Client-side mirror of the command-chain save rules (`validateChain` in + * `src/lib/command-chain`). Used by the chart canvas to reject bad connections + * at drop time and to flag invalid links already present in a draft. These + * checks are a pre-filter for UX only; the server action remains the authority + * and re-validates everything on save. + */ + +export type ChainParticipantLite = { + id: number; + rankIndex: number | null; +}; + +export type ConnectRejection = "self" | "rank-inverted" | "duplicate" | "cycle"; + +export const CONNECT_REJECTION_MESSAGES: Record = { + self: "A user cannot be their own supervisor.", + "rank-inverted": "Supervisors cannot rank below the person they command.", + duplicate: "That command link already exists.", + cycle: "That link would create a circular chain of command.", +}; + +/** Draft shape shared with the list editor: subordinate id -> supervisor ids. */ +export type ChainDraft = Record; + +/** + * Whether adding `supervisorId -> subordinateId` closes a loop: the supervisor + * is themselves commanded (transitively) by the subordinate already, so the + * new edge would put someone above themselves. + */ +export function wouldCreateCycle( + draft: ChainDraft, + supervisorId: number, + subordinateId: number, +): boolean { + let frontier = draft[supervisorId] ?? []; + const visited = new Set(); + while (frontier.length > 0) { + const next: number[] = []; + for (const s of frontier) { + if (s === subordinateId) return true; + if (visited.has(s)) continue; + visited.add(s); + next.push(...(draft[s] ?? [])); + } + frontier = next; + } + return false; +} + +/** + * Validate one prospective connect. Returns null when the link may be added, + * otherwise the first matching rejection rule (same order as the server). + */ +export function checkConnect( + draft: ChainDraft, + participants: readonly ChainParticipantLite[], + supervisorId: number, + subordinateId: number, +): ConnectRejection | null { + if (supervisorId === subordinateId) return "self"; + const rankOf = new Map(participants.map((p) => [p.id, p.rankIndex])); + const supRank = rankOf.get(supervisorId); + const subRank = rankOf.get(subordinateId); + if (supRank != null && subRank != null && supRank < subRank) return "rank-inverted"; + if ((draft[subordinateId] ?? []).includes(supervisorId)) return "duplicate"; + if (wouldCreateCycle(draft, supervisorId, subordinateId)) return "cycle"; + return null; +} + +/** + * Auto-orient a canvas drag by rank: the higher-ranked endpoint becomes the + * supervisor. With equal ranks or an unranked side, the drag direction stands + * (both are legal per the save rules). + */ +export function autoOrientPair( + participants: readonly ChainParticipantLite[], + dragFrom: number, + dragTo: number, +): { supervisorId: number; subordinateId: number } { + const rankOf = new Map(participants.map((p) => [p.id, p.rankIndex])); + const fromRank = rankOf.get(dragFrom); + const toRank = rankOf.get(dragTo); + if (fromRank != null && toRank != null && fromRank < toRank) { + return { supervisorId: dragTo, subordinateId: dragFrom }; + } + return { supervisorId: dragFrom, subordinateId: dragTo }; +} + +/** + * Keys (`"supervisor->subordinate"`) of draft links that break a rule, so the + * canvas can paint them red until they are fixed or removed. Rank/self checks + * are per edge; edges sitting on (or inside) a command loop are marked when + * both endpoints participate in some cycle. Mission-sized graphs only, so the + * naive upward walks here are fine. + */ +export function invalidLinkKeys( + draft: ChainDraft, + participants: readonly ChainParticipantLite[], +): Set { + const invalid = new Set(); + const key = (s: number, u: number) => `${s}->${u}`; + const rankOf = new Map(participants.map((p) => [p.id, p.rankIndex])); + + for (const [subordinateId, supervisorIds] of Object.entries(draft)) { + const u = Number(subordinateId); + const subRank = rankOf.get(u); + for (const s of supervisorIds) { + const supRank = rankOf.get(s); + if (s === u || (supRank != null && subRank != null && supRank < subRank)) { + invalid.add(key(s, u)); + } + } + } + + const cycleNodes = new Set(); + const walkUp = (start: number) => { + const path: number[] = []; + const stack = [...(draft[start] ?? [])]; + while (stack.length > 0) { + const s = stack.pop()!; + if (s === start) { + cycleNodes.add(start); + for (const n of path) cycleNodes.add(n); + continue; + } + if (path.includes(s)) continue; + path.push(s); + stack.push(...(draft[s] ?? [])); + } + }; + for (const node of participants.map((p) => p.id)) walkUp(node); + if (cycleNodes.size > 0) { + for (const [subordinateId, supervisorIds] of Object.entries(draft)) { + const u = Number(subordinateId); + for (const s of supervisorIds) { + if (cycleNodes.has(s) && cycleNodes.has(u)) invalid.add(key(s, u)); + } + } + } + return invalid; +} diff --git a/src/components/frontend/intelligence/chainLayout.ts b/src/components/frontend/intelligence/chainLayout.ts new file mode 100644 index 00000000..5fdb1b6b --- /dev/null +++ b/src/components/frontend/intelligence/chainLayout.ts @@ -0,0 +1,187 @@ +/** + * Deterministic layered layout for the mission command chain (a DAG: one + * subordinate may have several supervisors). Used by the chart canvas; drag + * positions are deliberately not persisted, the chart re-flows from data. + * + * Pure function: same participants/links (same order) always produce the same + * coordinates. Cycles in stored links are impossible through the save path but + * are broken defensively so rendering never loops forever. + */ + +export const CHAIN_NODE_W = 176; +export const CHAIN_NODE_H = 54; +const GAP_X = 28; +const GAP_Y = 64; +/** Extra gap after a sub-row produced by wrapping one wide layer. */ +const WRAP_GAP = 28; +const BAND_GAP = 40; +/** Rows wider than this (in flow units) wrap into stacked sub-rows. */ +const MAX_ROW_WIDTH = 1680; + +export interface ChainLayoutInput { + /** Participant ids in display order (name-sorted upstream). */ + participantIds: number[]; + /** Directed supervisor -> subordinate pairs. Invalid pairs are ignored. */ + links: ReadonlyArray<{ supervisorId: number; subordinateId: number }>; +} + +export interface ChainLayout { + /** Flow-space position per participant id. */ + positions: Map; + /** Ids with no links at all, rendered in the bottom band. */ + bandIds: number[]; + /** Top edge of the unlinked band row, or null when every node is linked. */ + bandTop: number | null; + /** Bounding box of all placed nodes (relative to its own min corner). */ + width: number; + height: number; +} + +/** Longest-path layering over the supervisor DAG, back edges dropped. */ +function assignLayers( + participantIds: number[], + parents: Map, +): Map { + const GREY = 1; + const BLACK = 2; + const state = new Map(); + const layer = new Map(); + + const visit = (id: number): void => { + state.set(id, GREY); + let depth = 0; + for (const parent of parents.get(id) ?? []) { + if (state.get(parent) === GREY) continue; // back edge: ignore for layering + if (state.get(parent) === undefined) visit(parent); + depth = Math.max(depth, (layer.get(parent) ?? 0) + 1); + } + layer.set(id, depth); + state.set(id, BLACK); + }; + for (const id of participantIds) { + if (state.get(id) === undefined) visit(id); + } + return layer; +} + +export function computeChainLayout(input: ChainLayoutInput): ChainLayout { + const ids = new Set(input.participantIds); + const children = new Map(); + const parents = new Map(); + const seenPair = new Set(); + const validLinks: Array<{ supervisorId: number; subordinateId: number }> = []; + + for (const link of input.links) { + const { supervisorId: s, subordinateId: u } = link; + if (!ids.has(s) || !ids.has(u) || s === u) continue; + const key = `${s}->${u}`; + if (seenPair.has(key)) continue; + seenPair.add(key); + validLinks.push({ supervisorId: s, subordinateId: u }); + children.set(s, [...(children.get(s) ?? []), u]); + parents.set(u, [...(parents.get(u) ?? []), s]); + } + + const linked = new Set(); + for (const { supervisorId: s, subordinateId: u } of validLinks) { + linked.add(s); + linked.add(u); + } + const bandIds = input.participantIds.filter((id) => !linked.has(id)); + const graphIds = input.participantIds.filter((id) => linked.has(id)); + + const layersById = assignLayers(graphIds, parents); + const orderedRows = orderRows(layersById, parents, children, graphIds); + + const positions = new Map(); + let minX = Infinity; + let maxX = -Infinity; + // Flatten layers into physical rows, splitting any layer wider than the + // wrap threshold; sub-rows of one layer keep a tighter vertical rhythm. + const perRow = Math.max(1, Math.floor((MAX_ROW_WIDTH + GAP_X) / (CHAIN_NODE_W + GAP_X))); + const physicalRows: Array<{ ids: number[]; gapBelow: number }> = []; + orderedRows.forEach((row, layerIndex) => { + if (row.length === 0) return; + for (let start = 0; start < row.length; start += perRow) { + const moreInLayer = start + perRow < row.length; + physicalRows.push({ + ids: row.slice(start, start + perRow), + gapBelow: moreInLayer ? WRAP_GAP : GAP_Y, + }); + } + }); + let cursorY = 0; + physicalRows.forEach((row) => { + const rowWidth = row.ids.length * CHAIN_NODE_W + Math.max(0, row.ids.length - 1) * GAP_X; + row.ids.forEach((id, i) => { + const x = i * (CHAIN_NODE_W + GAP_X) - rowWidth / 2; + positions.set(id, { x, y: cursorY }); + minX = Math.min(minX, x); + maxX = Math.max(maxX, x + CHAIN_NODE_W); + }); + cursorY += CHAIN_NODE_H + row.gapBelow; + }); + + let bandTop: number | null = null; + if (bandIds.length > 0) { + const bandRowWidth = + bandIds.length * CHAIN_NODE_W + Math.max(0, bandIds.length - 1) * GAP_X; + const contentCenter = Number.isFinite(minX) && Number.isFinite(maxX) ? (minX + maxX) / 2 : 0; + const bandY = graphIds.length > 0 ? cursorY + BAND_GAP - GAP_Y : 0; + bandTop = bandY; + bandIds.forEach((id, i) => { + positions.set(id, { x: contentCenter - bandRowWidth / 2 + i * (CHAIN_NODE_W + GAP_X), y: bandY }); + }); + minX = Math.min(minX, contentCenter - bandRowWidth / 2); + maxX = Math.max(maxX, contentCenter - bandRowWidth / 2 + bandRowWidth); + } + + const height = bandTop !== null ? bandTop + CHAIN_NODE_H : Math.max(CHAIN_NODE_H, cursorY); + + return { + positions, + bandIds, + bandTop, + width: Number.isFinite(minX) && Number.isFinite(maxX) ? maxX - minX : CHAIN_NODE_W, + height, + }; +} + +/** Sorted rows per layer (layer order ascending, within-layer barycentric). */ +function orderRows( + layersById: Map, + parents: Map, + children: Map, + graphIds: number[], +): number[][] { + if (graphIds.length === 0) return []; + const maxLayer = Math.max(...graphIds.map((id) => layersById.get(id) ?? 0)); + const byLayer: number[][] = Array.from({ length: maxLayer + 1 }, () => []); + for (const id of graphIds) byLayer[layersById.get(id) ?? 0].push(id); + + const seq = new Map(); + const reindex = () => { + for (const row of byLayer) row.forEach((id, i) => seq.set(id, i)); + }; + reindex(); + + const barySort = (row: number[], neighborsOf: (id: number) => number[]) => { + const keyed = row.map((id, i) => { + const known = neighborsOf(id) + .map((n) => seq.get(n)) + .filter((v): v is number => v !== undefined); + const bary = known.length > 0 ? known.reduce((a, b) => a + b, 0) / known.length : i; + return { id, bary }; + }); + keyed.sort((a, b) => a.bary - b.bary || a.id - b.id); + row.splice(0, row.length, ...keyed.map((k) => k.id)); + }; + + for (let sweep = 0; sweep < 2; sweep += 1) { + for (let l = 1; l <= maxLayer; l += 1) barySort(byLayer[l], (id) => parents.get(id) ?? []); + reindex(); + } + for (let l = maxLayer - 1; l >= 0; l -= 1) barySort(byLayer[l], (id) => children.get(id) ?? []); + + return byLayer; +} diff --git a/src/lib/command-chain/index.ts b/src/lib/command-chain/index.ts index 5c9f2996..b9afb677 100644 --- a/src/lib/command-chain/index.ts +++ b/src/lib/command-chain/index.ts @@ -1,5 +1,5 @@ import type { Payload } from "payload"; -import { getUserRankIndexes } from "@/lib/evaluations/ranks"; +import { getUserRankIndexes, getUserRankInfos } from "@/lib/evaluations/ranks"; import { isSuperuser } from "@/utils/access-control/hasPermission"; type PayloadType = Payload; @@ -45,10 +45,11 @@ const relId = (value: number | { id: number } | null | undefined): number | null * ranked participants can take part in a chain (rank is needed for fallback and * for the inverted-link guard). */ -async function loadParticipants( +/** Yes-RSVP participants of one mission (ids only; names resolved by callers). */ +async function loadParticipantIds( payload: PayloadType, missionId: number, -): Promise<{ ids: number[]; rankIndexes: Map }> { +): Promise { const res = await payload.find({ collection: "mission-attendances", where: { @@ -58,13 +59,20 @@ async function loadParticipants( depth: 0, overrideAccess: true, }); - const ids = [ + return [ ...new Set( res.docs .map((doc) => relId(doc.user as unknown as number | { id: number } | null)) .filter((id): id is number => id !== null), ), ]; +} + +async function loadParticipants( + payload: PayloadType, + missionId: number, +): Promise<{ ids: number[]; rankIndexes: Map }> { + const ids = await loadParticipantIds(payload, missionId); const rankIndexes = await getUserRankIndexes(payload, ids); return { ids, rankIndexes }; } @@ -449,28 +457,35 @@ export async function saveMissionChain( export interface ChainParticipant { id: number; name: string; + /** Ladder position for auto-orienting new edges (0 = lowest); null when unranked. */ + rankIndex: number | null; + /** Short rank label for node display; null when no ladder rank resolves. */ + rankLabel: string | null; } -export interface ChainEditorState { +export interface ChainViewerState { mode: ChainMode; links: CommandLink[]; participants: ChainParticipant[]; + /** True when the requesting user may configure the chain and it is unlocked. */ editable: boolean; + /** Populated only for would-be editors; explains why editing is unavailable. */ lockReason: string | null; } /** - * Editor view for the mission page. Returns null unless `user` may edit the - * chain, so non-editors never receive the state (plan decision F). + * Chain display state for the mission page, for any viewer who can see the + * mission itself (read access is enforced by the caller's fetch). Renders + * read-only unless `editable`: author/Zeus/superuser AND not locked. The lock + * reason is computed only for would-be editors so members skip the lookup. */ -export async function getChainEditorState( +export async function getChainViewerState( payload: PayloadType, user: { id: number; roleDocs?: unknown } | null | undefined, mission: MissionLike, -): Promise { - if (!(await canEditMissionChain(payload, user, mission))) return null; +): Promise { const resolved = await resolveMissionChain(payload, mission.id); - const { ids } = await loadParticipants(payload, mission.id); + const ids = await loadParticipantIds(payload, mission.id); const users = ids.length === 0 ? { docs: [] as Array<{ id: number; displayName?: string | null; username?: string | null }> } @@ -481,15 +496,22 @@ export async function getChainEditorState( depth: 0, overrideAccess: true, }); - const participants = users.docs - .map((doc) => ({ id: doc.id, name: doc.displayName || doc.username || `user-${doc.id}` })) + const rankInfos = await getUserRankInfos(payload, ids); + const participants: ChainParticipant[] = users.docs + .map((doc) => ({ + id: doc.id, + name: doc.displayName || doc.username || `user-${doc.id}`, + rankIndex: rankInfos.get(doc.id)?.index ?? null, + rankLabel: rankInfos.get(doc.id)?.label ?? null, + })) .sort((a, b) => a.name.localeCompare(b.name)); - const lockReason = await getChainLockReason(payload, mission); + const allowed = user ? await canEditMissionChain(payload, user, mission) : false; + const lockReason = allowed ? await getChainLockReason(payload, mission) : null; return { mode: resolved.mode, links: resolved.links, participants, - editable: lockReason === null, + editable: allowed && lockReason === null, lockReason, }; } diff --git a/src/lib/evaluations/ranks.ts b/src/lib/evaluations/ranks.ts index 6491659a..8750e371 100644 --- a/src/lib/evaluations/ranks.ts +++ b/src/lib/evaluations/ranks.ts @@ -18,16 +18,24 @@ type PayloadType = Payload; */ export type RankDirection = "upward" | "downward"; +/** Ladder position plus a short display label for one ranked user. */ +export interface UserRankInfo { + /** Ladder index, 0 = lowest rank. */ + index: number; + /** Rank abbreviation when present, else its name. */ + label: string; +} + /** - * Ladder index (0 = lowest rank) for each user that has a profile carrying a + * Ladder index and display label for each user that has a profile carrying a * rank found on the ladder. Users without a profile, with a null rank, or with * an off-ladder rank are simply absent from the map. Bulk helper shared by the * reminder planners so they can load seniority for everyone in one pass. */ -export async function getUserRankIndexes( +export async function getUserRankInfos( payload: PayloadType, userIds: readonly number[], -): Promise> { +): Promise> { const uniqueIds = [...new Set(userIds)]; if (uniqueIds.length === 0) return new Map(); @@ -44,15 +52,27 @@ export async function getUserRankIndexes( }); const wanted = new Set(uniqueIds.map((id) => String(id))); - const indexes = new Map(); + const infos = new Map(); for (const profile of res.docs) { const userId = typeof profile.user === "number" ? profile.user : profile.user?.id; if (userId == null || !wanted.has(String(userId))) continue; const rank = resolveRankFromLadder(ladder, profile.rank as number | undefined | null); if (!rank) continue; - indexes.set(userId, rankIndex(ladder, rank.id)); + infos.set(userId, { + index: rankIndex(ladder, rank.id), + label: rank.abbreviation || rank.name || `#${rank.id}`, + }); } - return indexes; + return infos; +} + +/** Index-only projection of {@link getUserRankInfos}. */ +export async function getUserRankIndexes( + payload: PayloadType, + userIds: readonly number[], +): Promise> { + const infos = await getUserRankInfos(payload, userIds); + return new Map([...infos].map(([id, info]) => [id, info.index])); } /** diff --git a/tests/int/mission-command-chain-chart.int.spec.ts b/tests/int/mission-command-chain-chart.int.spec.ts new file mode 100644 index 00000000..661b7c42 --- /dev/null +++ b/tests/int/mission-command-chain-chart.int.spec.ts @@ -0,0 +1,305 @@ +/** + * 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 => { + 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 => { + 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 }); + }); +});