feat(intelligence): render mission chain of command as an editable org chart
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
This commit is contained in:
parent
48ce0fa6a0
commit
bff6a7a908
11 changed files with 1400 additions and 266 deletions
|
|
@ -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
|
|||
/>
|
||||
</TacticalFrame>
|
||||
|
||||
{commandChainEditor && (
|
||||
<TacticalFrame
|
||||
classification="OPERATION // COMMAND"
|
||||
icon={GitBranchIcon}
|
||||
refCode={`REF ${refCodeFrom(mission.id)}`}
|
||||
grow={false}
|
||||
>
|
||||
<MissionCommandChainEditor
|
||||
missionId={mission.id}
|
||||
mode={commandChainEditor.mode}
|
||||
links={commandChainEditor.links}
|
||||
participants={commandChainEditor.participants}
|
||||
editable={commandChainEditor.editable}
|
||||
lockReason={commandChainEditor.lockReason}
|
||||
/>
|
||||
</TacticalFrame>
|
||||
)}
|
||||
<TacticalFrame
|
||||
classification="OPERATION // COMMAND"
|
||||
icon={GitBranchIcon}
|
||||
refCode={`REF ${refCodeFrom(mission.id)}`}
|
||||
grow={false}
|
||||
>
|
||||
<MissionCommandChainSection
|
||||
missionId={mission.id}
|
||||
mode={commandChain.mode}
|
||||
links={commandChain.links}
|
||||
participants={commandChain.participants}
|
||||
editable={commandChain.editable}
|
||||
lockReason={commandChain.lockReason}
|
||||
/>
|
||||
</TacticalFrame>
|
||||
|
||||
<TacticalFrame
|
||||
classification="OPERATION // SIGN-UPS"
|
||||
|
|
|
|||
|
|
@ -4143,3 +4143,25 @@
|
|||
.frontend-tech-tree .react-flow__attribution a {
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
||||
/* Mission chain org chart (React Flow): dark chrome, same treatment as the
|
||||
frontend tech tree canvas above. */
|
||||
.mission-chain-canvas .react-flow__controls button {
|
||||
background: rgba(0, 0, 0, 0.72);
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.15);
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
border-radius: 0;
|
||||
}
|
||||
.mission-chain-canvas .react-flow__controls button:hover {
|
||||
background: rgba(0, 0, 0, 0.92);
|
||||
color: #ffffff;
|
||||
}
|
||||
.mission-chain-canvas .react-flow__controls button svg {
|
||||
fill: currentColor;
|
||||
}
|
||||
.mission-chain-canvas .react-flow__attribution {
|
||||
background: transparent;
|
||||
}
|
||||
.mission-chain-canvas .react-flow__attribution a {
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,334 @@
|
|||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import {
|
||||
Background,
|
||||
BackgroundVariant,
|
||||
BaseEdge,
|
||||
Controls,
|
||||
EdgeLabelRenderer,
|
||||
Handle,
|
||||
MarkerType,
|
||||
Position,
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
getSmoothStepPath,
|
||||
useReactFlow,
|
||||
type Edge,
|
||||
type EdgeProps,
|
||||
type EdgeTypes,
|
||||
type Node,
|
||||
type NodeProps,
|
||||
type NodeTypes,
|
||||
type OnConnect,
|
||||
} from "@xyflow/react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
|
||||
import { CHAIN_NODE_H, CHAIN_NODE_W, computeChainLayout } from "./chainLayout";
|
||||
import type { ChainDraft } from "./chainDraftRules";
|
||||
|
||||
/**
|
||||
* Org-chart view of a mission chain of command on a React Flow canvas.
|
||||
* Tactical dossier styling (squared cards, mono rank strip, faint grid),
|
||||
* auto-layout only: nodes are fixed by data, drag positions are not stored.
|
||||
* Editing = drawing connections between cards and removing them; every change
|
||||
* lands in the section-owned draft, shared with the List tab.
|
||||
*/
|
||||
|
||||
export interface ChartParticipant {
|
||||
id: number;
|
||||
name: string;
|
||||
rankIndex: number | null;
|
||||
rankLabel: string | null;
|
||||
}
|
||||
|
||||
interface PersonNodeData extends Record<string, unknown> {
|
||||
name: string;
|
||||
rankLabel: string | null;
|
||||
/** True for the unlinked band: dashed border, dimmer chrome. */
|
||||
unlinked: boolean;
|
||||
connectable: boolean;
|
||||
}
|
||||
|
||||
interface LabelNodeData extends Record<string, unknown> {
|
||||
label: string;
|
||||
}
|
||||
|
||||
type PersonNodeModel = Node<PersonNodeData, "chainPerson">;
|
||||
type LabelNodeModel = Node<LabelNodeData, "chainBandLabel">;
|
||||
|
||||
interface ChainEdgeData extends Record<string, unknown> {
|
||||
invalid: boolean;
|
||||
removeable: boolean;
|
||||
onRemove?: () => void;
|
||||
}
|
||||
|
||||
function ChainPersonNodeCard({ data, selected }: NodeProps<PersonNodeModel>) {
|
||||
return (
|
||||
<div
|
||||
data-testid={`chain-node-${data.name}`}
|
||||
className={[
|
||||
"flex h-full w-full flex-col justify-center rounded-none border px-3 py-1.5 backdrop-blur-sm transition-colors",
|
||||
data.unlinked
|
||||
? "border-dashed border-white/15 bg-black/40"
|
||||
: "border-white/25 bg-zinc-900/90",
|
||||
selected ? "border-white/60" : "hover:border-white/45",
|
||||
].join(" ")}
|
||||
>
|
||||
<span
|
||||
className={`truncate text-sm leading-snug font-semibold ${
|
||||
data.unlinked ? "text-white/60" : "text-white"
|
||||
}`}
|
||||
>
|
||||
{data.name}
|
||||
</span>
|
||||
<span className="font-mono text-[8px] uppercase tracking-widest text-white/45">
|
||||
{data.rankLabel ?? "UNRANKED"}
|
||||
</span>
|
||||
{data.connectable && (
|
||||
<>
|
||||
<Handle
|
||||
type="target"
|
||||
id="t"
|
||||
position={Position.Top}
|
||||
className="!bg-white/45 hover:!bg-[#22d3ee]"
|
||||
style={{ width: 10, height: 10, border: "1px solid rgba(0,0,0,0.6)" }}
|
||||
/>
|
||||
<Handle
|
||||
type="source"
|
||||
id="s"
|
||||
position={Position.Bottom}
|
||||
className="!bg-white/45 hover:!bg-[#22d3ee]"
|
||||
style={{ width: 10, height: 10, border: "1px solid rgba(0,0,0,0.6)" }}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ChainBandLabelNode({ data }: NodeProps<LabelNodeModel>) {
|
||||
return (
|
||||
<div className="whitespace-nowrap font-mono text-[9px] uppercase tracking-widest text-white/40">
|
||||
{data.label}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<>
|
||||
<BaseEdge
|
||||
id={id}
|
||||
path={path}
|
||||
markerEnd={markerEnd}
|
||||
style={{
|
||||
stroke,
|
||||
strokeWidth: edgeData?.invalid ? 2 : 1.5,
|
||||
strokeDasharray: edgeData?.invalid ? "4 3" : undefined,
|
||||
}}
|
||||
/>
|
||||
<EdgeLabelRenderer>
|
||||
{selected && edgeData?.removeable && (
|
||||
<div
|
||||
className="nodrag nopan"
|
||||
style={{
|
||||
position: "absolute",
|
||||
transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
|
||||
pointerEvents: "all",
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Remove command link"
|
||||
title="Remove this command link"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
edgeData.onRemove?.();
|
||||
}}
|
||||
onPointerDown={(e) => e.stopPropagation()}
|
||||
className="flex h-4 w-4 items-center justify-center rounded-full border border-red-400/70 bg-black/85 font-mono text-[10px] leading-none text-red-300 hover:bg-red-500/25"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</EdgeLabelRenderer>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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<string>;
|
||||
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<number>();
|
||||
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<Node[]>(() => {
|
||||
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<Edge[]>(
|
||||
() =>
|
||||
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 (
|
||||
<div
|
||||
// Dark controls/attribution chrome lives in app/(frontend)/styles.css
|
||||
// under .mission-chain-canvas (mirrors the frontend tech tree canvas).
|
||||
className="mission-chain-canvas relative h-[420px] w-full overflow-hidden rounded-none border border-white/15 md:h-[560px]"
|
||||
style={{ backgroundColor: "#05070a" }}
|
||||
data-testid="chain-chart-canvas"
|
||||
>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
edgeTypes={edgeTypes}
|
||||
fitView
|
||||
fitViewOptions={{ padding: 0.15, maxZoom: 1 }}
|
||||
minZoom={0.2}
|
||||
proOptions={{ hideAttribution: false }}
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={editable}
|
||||
nodesFocusable={false}
|
||||
onConnect={onConnect}
|
||||
>
|
||||
<Background
|
||||
variant={BackgroundVariant.Lines}
|
||||
gap={28}
|
||||
size={1}
|
||||
color="rgba(255,255,255,0.055)"
|
||||
/>
|
||||
<Controls showInteractive={false} />
|
||||
</ReactFlow>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MissionCommandChainChart(props: MissionCommandChainChartProps) {
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<ChartInner {...props} />
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<Record<number, number[]>>(() =>
|
||||
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 (
|
||||
<Collapsible open={contentOpen} onOpenChange={setContentOpen}>
|
||||
<Card>
|
||||
<CardHeader className="flex flex-col gap-2">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Badge variant="outline">
|
||||
{mode === "stored" ? "Override" : mode === "legacy" ? "Legacy" : "Defaults"}
|
||||
</Badge>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Who was in command of whom for this operation only. Permanent assignments are not
|
||||
changed. Supervisors may rate their subordinate as a command review.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CollapsibleTrigger asChild>
|
||||
<div
|
||||
className="relative mx-2 mt-1 mb-5 flex cursor-pointer items-center outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
aria-label={contentOpen ? "Collapse command chain" : "Expand command chain"}
|
||||
>
|
||||
<span className="block h-px flex-1 border-t border-border" />
|
||||
<ChevronDown
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"h-4 w-4 text-muted-foreground transition-transform hover:text-foreground",
|
||||
contentOpen && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
<span className="block h-px flex-1 border-t border-border" />
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent className="overflow-hidden">
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
{mode === "legacy" && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
This mission was rated before the chain existed, so its command reviews follow the
|
||||
original assignment rule and cannot be changed here.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{!editable && lockReason && (
|
||||
<Alert>
|
||||
<AlertDescription>{lockReason}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{mode !== "legacy" && (
|
||||
<div className="flex flex-col gap-3">
|
||||
{participants.map((sub) => {
|
||||
const supervisors = draft[sub.id] ?? [];
|
||||
const options = participants.filter(
|
||||
(p) => p.id !== sub.id && !supervisors.includes(p.id),
|
||||
);
|
||||
return (
|
||||
<div key={sub.id} className="flex flex-col gap-1.5">
|
||||
<Label>{sub.name}</Label>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{supervisors.length === 0 && (
|
||||
<span className="text-sm text-muted-foreground">No supervisor</span>
|
||||
)}
|
||||
{supervisors.map((supId) => (
|
||||
<Badge key={supId} variant="secondary" className="gap-1">
|
||||
{nameOf(supId)}
|
||||
{editable && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Remove ${nameOf(supId)} as supervisor`}
|
||||
onClick={() => removeSupervisor(sub.id, supId)}
|
||||
className="ml-1 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
))}
|
||||
{editable && options.length > 0 && (
|
||||
<Select onValueChange={(value) => addSupervisor(sub.id, Number(value))}>
|
||||
<SelectTrigger aria-label={`Add supervisor for ${sub.name}`}>
|
||||
<SelectValue placeholder="Add supervisor" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{options.map((opt) => (
|
||||
<SelectItem key={opt.id} value={String(opt.id)}>
|
||||
{opt.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editable && mode !== "legacy" && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button onClick={save} disabled={pending}>
|
||||
Save chain
|
||||
</Button>
|
||||
<Button variant="outline" onClick={reset} disabled={pending}>
|
||||
Reset to defaults
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</CollapsibleContent>
|
||||
</Card>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
103
src/components/frontend/intelligence/MissionCommandChainList.tsx
Normal file
103
src/components/frontend/intelligence/MissionCommandChainList.tsx
Normal file
|
|
@ -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 (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nobody has RSVP'd yes to this mission yet, so there is no chain to configure.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
{participants.map((sub) => {
|
||||
const supervisors = draft[sub.id] ?? [];
|
||||
const options = participants.filter((p) => p.id !== sub.id && !supervisors.includes(p.id));
|
||||
return (
|
||||
<div key={sub.id} className="flex flex-col gap-1.5">
|
||||
<Label>
|
||||
{sub.name}
|
||||
{sub.rankLabel && (
|
||||
<span className="ml-2 font-mono text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||
{sub.rankLabel}
|
||||
</span>
|
||||
)}
|
||||
</Label>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{supervisors.length === 0 && (
|
||||
<span className="text-sm text-muted-foreground">No supervisor</span>
|
||||
)}
|
||||
{supervisors.map((supId) => (
|
||||
<Badge key={supId} variant="secondary" className="ml-1 gap-1">
|
||||
{nameOf(supId)}
|
||||
{editable && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Remove ${nameOf(supId)} as supervisor`}
|
||||
onClick={() => onRemoveSupervisor(sub.id, supId)}
|
||||
className="ml-1 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</Badge>
|
||||
))}
|
||||
{editable && options.length > 0 && (
|
||||
<Select onValueChange={(value) => onAddSupervisor(sub.id, Number(value))}>
|
||||
<SelectTrigger
|
||||
className="w-[180px]"
|
||||
aria-label={`Add supervisor for ${sub.name}`}
|
||||
>
|
||||
<SelectValue placeholder="Add supervisor" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{options.map((opt) => (
|
||||
<SelectItem key={opt.id} value={String(opt.id)}>
|
||||
{opt.name}
|
||||
{opt.rankLabel ? ` (${opt.rankLabel})` : ""}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -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<ChainMode, string> = {
|
||||
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<ChainDraft>(() => 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 (
|
||||
<div className="flex flex-col gap-3 p-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<p className="max-w-xl text-xs leading-relaxed text-muted-foreground">
|
||||
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.
|
||||
</p>
|
||||
<Badge variant="outline" className="shrink-0 font-mono text-[10px] uppercase">
|
||||
{MODE_LABELS[mode]}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{mode === "legacy" && (
|
||||
<Alert>
|
||||
<AlertDescription>
|
||||
This mission was rated before the chain existed, so its command reviews follow the
|
||||
original assignment rule and cannot be edited here.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
{editable === false && lockReason && mode !== "legacy" && (
|
||||
<Alert>
|
||||
<AlertDescription>{lockReason}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{mode === "legacy" ? (
|
||||
<MissionCommandChainList
|
||||
participants={participants}
|
||||
draft={draft}
|
||||
editable={false}
|
||||
onAddSupervisor={() => {}}
|
||||
onRemoveSupervisor={() => {}}
|
||||
/>
|
||||
) : nothingToDraw ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No one has RSVP'd yes yet, so there is no chain to draw.
|
||||
</p>
|
||||
) : (
|
||||
<Tabs value={tab} onValueChange={(v) => setTab(v === "list" ? "list" : "chart")}>
|
||||
<TabsList variant="line">
|
||||
<TabsTrigger value="chart">Org chart</TabsTrigger>
|
||||
<TabsTrigger value="list">List</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="chart" className="flex flex-col gap-2 pt-2">
|
||||
<MissionCommandChainChart
|
||||
participants={participants.map((p) => ({
|
||||
id: p.id,
|
||||
name: p.name,
|
||||
rankIndex: p.rankIndex,
|
||||
rankLabel: p.rankLabel,
|
||||
}))}
|
||||
draft={draft}
|
||||
invalidKeys={invalidKeys}
|
||||
editable={editable}
|
||||
onAddLink={handleChartAdd}
|
||||
onRemoveLink={remove}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="list" className="pt-2">
|
||||
<MissionCommandChainList
|
||||
participants={participants}
|
||||
draft={draft}
|
||||
editable={editable}
|
||||
onAddSupervisor={(subordinateId, supervisorId) => tryAdd(supervisorId, subordinateId)}
|
||||
onRemoveSupervisor={(subordinateId, supervisorId) => remove(supervisorId, subordinateId)}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
{editable && mode !== "legacy" && !nothingToDraw && (
|
||||
<div className="flex flex-wrap items-center gap-2 border-t border-border/60 pt-3">
|
||||
<Button onClick={save} disabled={pending}>
|
||||
Save chain
|
||||
</Button>
|
||||
<Button variant="outline" onClick={reset} disabled={pending}>
|
||||
Reset to defaults
|
||||
</Button>
|
||||
<span className="ml-auto text-[10px] uppercase tracking-wider text-muted-foreground">
|
||||
Changes apply to this mission only
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
142
src/components/frontend/intelligence/chainDraftRules.ts
Normal file
142
src/components/frontend/intelligence/chainDraftRules.ts
Normal file
|
|
@ -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<ConnectRejection, string> = {
|
||||
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<number, number[]>;
|
||||
|
||||
/**
|
||||
* 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<number>();
|
||||
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<string> {
|
||||
const invalid = new Set<string>();
|
||||
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<number>();
|
||||
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;
|
||||
}
|
||||
187
src/components/frontend/intelligence/chainLayout.ts
Normal file
187
src/components/frontend/intelligence/chainLayout.ts
Normal file
|
|
@ -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<number, { x: number; y: number }>;
|
||||
/** 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<number, number[]>,
|
||||
): Map<number, number> {
|
||||
const GREY = 1;
|
||||
const BLACK = 2;
|
||||
const state = new Map<number, number>();
|
||||
const layer = new Map<number, number>();
|
||||
|
||||
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<number, number[]>();
|
||||
const parents = new Map<number, number[]>();
|
||||
const seenPair = new Set<string>();
|
||||
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<number>();
|
||||
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<number, { x: number; y: number }>();
|
||||
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<number, number>,
|
||||
parents: Map<number, number[]>,
|
||||
children: Map<number, number[]>,
|
||||
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<number, number>();
|
||||
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;
|
||||
}
|
||||
|
|
@ -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<number, number> }> {
|
||||
): Promise<number[]> {
|
||||
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<number, number> }> {
|
||||
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<ChainEditorState | null> {
|
||||
if (!(await canEditMissionChain(payload, user, mission))) return null;
|
||||
): Promise<ChainViewerState> {
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<Map<number, number>> {
|
||||
): Promise<Map<number, UserRankInfo>> {
|
||||
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<number, number>();
|
||||
const infos = new Map<number, UserRankInfo>();
|
||||
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<Map<number, number>> {
|
||||
const infos = await getUserRankInfos(payload, userIds);
|
||||
return new Map([...infos].map(([id, info]) => [id, info.index]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
305
tests/int/mission-command-chain-chart.int.spec.ts
Normal file
305
tests/int/mission-command-chain-chart.int.spec.ts
Normal file
|
|
@ -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<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 });
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue