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
226 lines
7.7 KiB
TypeScript
226 lines
7.7 KiB
TypeScript
"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>
|
|
);
|
|
}
|