1
0
Fork 0

feat(missions): add command chain editor and MissionCommandLinks collection

Introduce a per-mission command chain: a new MissionCommandLinks collection, a
lib/command-chain resolver, and an admin/mission-page editor for supervisor ->
subordinate links. Evaluations and mission reminders later consume this chain to
resolve equal-rank command relationships.
This commit is contained in:
Jason Fraley 2026-11-02 09:59:55 -05:00
parent 8951b32157
commit ef3f26d4f9
12 changed files with 47454 additions and 10 deletions

View file

@ -25,6 +25,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 { MissionLogistics } from "@/components/frontend/intelligence/MissionLogistics";
import { MissionComms } from "@/components/frontend/intelligence/MissionComms";
import { MissionAttendance } from "@/components/frontend/intelligence/MissionAttendance";
@ -174,6 +176,9 @@ 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 createdById =
typeof mission.createdBy === "object" ? mission.createdBy?.id : mission.createdBy;
@ -558,6 +563,17 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
maxPlayers={mission.missionRoles?.maxPlayers ?? 32}
/>
{commandChainEditor && (
<MissionCommandChainEditor
missionId={mission.id}
mode={commandChainEditor.mode}
links={commandChainEditor.links}
participants={commandChainEditor.participants}
editable={commandChainEditor.editable}
lockReason={commandChainEditor.lockReason}
/>
)}
<MissionRoleSignups
missionId={mission.id}
currentUserId={currentUser ? (currentUser.id as number) : null}

View file

@ -27,6 +27,12 @@ import {
zonedWeekday,
} from "@/lib/intelligence/fridayTime";
import { describeArmaPresetFailure, parseArmaPreset } from "@/lib/modlistPreset";
import {
canEditMissionChain,
getChainLockReason,
resetMissionChain,
saveMissionChain,
} from "@/lib/command-chain";
import type { Mission, User } from "@/payload-types";
export interface ActionResult<T = undefined> {
@ -1027,6 +1033,63 @@ export async function withdrawMissionRoleSignup(input: {
}
}
async function loadChainEditableMission(
payload: Awaited<ReturnType<typeof getPayload>>,
user: Awaited<ReturnType<typeof authenticate>>["user"],
missionId: number,
) {
const mission = await payload
.findByID({ collection: "missions", id: missionId, depth: 0, user, overrideAccess: false })
.catch(() => null);
if (!mission) return { error: "You do not have access to this mission." as const };
const allowed = await canEditMissionChain(payload, user, mission as never);
if (!allowed) return { error: "Only authors, Zeus or superusers can edit the chain." as const };
const lock = await getChainLockReason(payload, mission as never);
if (lock) return { error: lock };
return { mission };
}
export async function saveMissionCommandChain(input: {
missionId: number;
links: Array<{ supervisorId: number; subordinateId: number }>;
}): Promise<ActionResult<{ saved: number }>> {
try {
const { payload, user } = await authenticate();
const checked = await loadChainEditableMission(payload, user, input.missionId);
if ("error" in checked) return { success: false, error: checked.error };
const result = await saveMissionChain(payload, {
missionId: input.missionId,
updatedById: user.id as number,
links: input.links,
});
if (result.errors.length > 0) return { success: false, error: result.errors.join(" ") };
return { success: true, data: { saved: result.saved } };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return message === "Unauthorized"
? { success: false, error: "You must be logged in." }
: { success: false, error: message };
}
}
export async function resetMissionCommandChain(input: {
missionId: number;
}): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const checked = await loadChainEditableMission(payload, user, input.missionId);
if ("error" in checked) return { success: false, error: checked.error };
await resetMissionChain(payload, input.missionId);
return { success: true };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return message === "Unauthorized"
? { success: false, error: "You must be logged in." }
: { success: false, error: message };
}
}
export async function removeMissionRoleSignup(input: {
missionId: number;
signupId: number;

View file

@ -0,0 +1,75 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
/**
* Per-mission chain-of-command overrides (who was in charge of whom for one op).
*
* One row per (mission, supervisor, subordinate). Rows are mission-scoped and
* never touch permanent assignments or ranks. A mission with no rows uses the
* legacy assignment-and-rank rule, unless a chain is frozen or edited.
*
* Uniqueness and editor checks are enforced in `src/lib/command-chain`, not by a
* DB constraint, matching `Evaluations` and `MissionRatings`. Writes are meant to
* go through that service; the REST/admin permissions below are for staff who
* already hold evaluations rights.
*/
export const MissionCommandLinks: CollectionConfig = {
slug: "mission-command-links",
admin: {
group: "Intelligence",
defaultColumns: ["mission", "supervisor", "subordinate", "source"],
description:
"Mission-scoped chain of command. Edited on the mission page by authors, Zeus and superusers.",
},
access: {
read: requirePermission("evaluations:read"),
create: requirePermission("evaluations:create"),
update: requirePermission("evaluations:update"),
delete: requirePermission("evaluations:delete"),
},
fields: [
{
name: "mission",
type: "relationship",
relationTo: "missions",
required: true,
index: true,
},
{
name: "supervisor",
type: "relationship",
relationTo: "users",
required: true,
admin: {
description: "The rater side: who was in charge for this op.",
},
},
{
name: "subordinate",
type: "relationship",
relationTo: "users",
required: true,
admin: {
description: "The ratee side: who the supervisor commanded for this op.",
},
},
{
name: "source",
type: "select",
required: true,
defaultValue: "override",
options: [
{ label: "Default (derived)", value: "default" },
{ label: "Override (edited)", value: "override" },
],
},
{
name: "updatedBy",
type: "relationship",
relationTo: "users",
admin: {
readOnly: true,
},
},
],
};

View file

@ -0,0 +1,198 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
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 { 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 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 (
<Card>
<CardHeader>
<CardTitle className="flex flex-wrap items-center justify-between gap-2 text-base">
<span>Command chain</span>
<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>
<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>
</Card>
);
}

View file

@ -0,0 +1,520 @@
import type { Payload } from "payload";
import { getUserRankIndexes } from "@/lib/evaluations/ranks";
import { isSuperuser } from "@/utils/access-control/hasPermission";
type PayloadType = Payload;
/** A supervisor-over-subordinate pair for one mission. */
export interface CommandLink {
supervisorId: number;
subordinateId: number;
source: "default" | "override";
}
/**
* - `stored`: rows exist (frozen on first rating, or edited). Rows win.
* - `default`: no rows and no ratings yet. Live defaults apply.
* - `legacy`: no rows but ratings exist. Mission was rated before this feature;
* command reviews stay on the original assignment-and-strict-rank rule so
* historical classifications do not move.
*/
export type ChainMode = "stored" | "default" | "legacy";
export interface ChainResolution {
mode: ChainMode;
links: CommandLink[];
}
interface MissionLike {
id: number;
ownershipAndStatus?: {
status?: string | null;
authors?: Array<number | { id: number }> | null;
zeus?: Array<number | { id: number }> | null;
} | null;
}
const relId = (value: number | { id: number } | null | undefined): number | null => {
if (typeof value === "number") return value;
if (value && typeof value.id === "number") return value.id;
return null;
};
/**
* Yes-RSVP participants for a mission, plus their resolved ladder index. Only
* ranked participants can take part in a chain (rank is needed for fallback and
* for the inverted-link guard).
*/
async function loadParticipants(
payload: PayloadType,
missionId: number,
): Promise<{ ids: number[]; rankIndexes: Map<number, number> }> {
const res = await payload.find({
collection: "mission-attendances",
where: {
and: [{ mission: { equals: missionId } }, { response: { equals: "yes" } }],
},
limit: 1000,
depth: 0,
overrideAccess: true,
});
const ids = [
...new Set(
res.docs
.map((doc) => relId(doc.user as unknown as number | { id: number } | null))
.filter((id): id is number => id !== null),
),
];
const rankIndexes = await getUserRankIndexes(payload, ids);
return { ids, rankIndexes };
}
/**
* Supervisors of each present member, taken from assignment leaders. Mirrors the
* rule the legacy command-review check used (a leader of an assignment the member belongs
* to), restricted to leaders who are themselves present, so an absent leader is
* never a default supervisor.
*/
async function loadAssignmentSupervisors(
payload: PayloadType,
memberIds: number[],
presentIds: Set<number>,
): Promise<Map<number, Set<number>>> {
const out = new Map<number, Set<number>>();
if (memberIds.length === 0) return out;
const res = await payload.find({
collection: "assignments",
where: { leader: { exists: true } },
limit: 1000,
depth: 0,
overrideAccess: true,
});
for (const assignment of res.docs as unknown as Array<{
leader?: number | { id: number } | null;
members?: Array<number | { id: number }> | null;
}>) {
const leaderId = relId(assignment.leader);
if (leaderId === null || !presentIds.has(leaderId)) continue;
for (const member of assignment.members ?? []) {
const memberId = relId(member);
if (memberId === null || memberId === leaderId || !presentIds.has(memberId)) continue;
const set = out.get(memberId) ?? new Set<number>();
set.add(leaderId);
out.set(memberId, set);
}
}
return out;
}
/**
* Live default chain, computed from RSVPs, assignments and ranks. Writes nothing.
*
* - A present member's supervisors are the present leaders of their assignments.
* - A member with no present leader falls back to rank: the nearest higher rank
* among present participants, all ties at that rank included.
* - Ranks never produce an inverted link: a fallback supervisor must rank above.
* - Members without a resolvable rank and no present leader get no supervisor.
*/
export async function computeDefaultChain(
payload: PayloadType,
missionId: number,
): Promise<CommandLink[]> {
const { ids, rankIndexes } = await loadParticipants(payload, missionId);
const presentIds = new Set(ids);
const assignmentSupervisors = await loadAssignmentSupervisors(payload, ids, presentIds);
const links: CommandLink[] = [];
const seen = new Set<string>();
const push = (supervisorId: number, subordinateId: number) => {
const key = `${supervisorId}:${subordinateId}`;
if (seen.has(key)) return;
seen.add(key);
links.push({ supervisorId, subordinateId, source: "default" });
};
for (const memberId of ids) {
const memberIndex = rankIndexes.get(memberId);
const leaders = [...(assignmentSupervisors.get(memberId) ?? [])].filter((leaderId) => {
const leaderIndex = rankIndexes.get(leaderId);
return memberIndex === undefined || leaderIndex === undefined || leaderIndex >= memberIndex;
});
if (leaders.length > 0) {
for (const leaderId of leaders) push(leaderId, memberId);
continue;
}
if (memberIndex === undefined) continue;
// Nearest higher rank among ranked, present participants.
let nearest: number | null = null;
for (const otherId of ids) {
const otherIndex = rankIndexes.get(otherId);
if (otherIndex === undefined || otherIndex <= memberIndex) continue;
if (nearest === null || otherIndex < nearest) nearest = otherIndex;
}
if (nearest === null) continue;
for (const otherId of ids) {
if (rankIndexes.get(otherId) === nearest) push(otherId, memberId);
}
}
return links;
}
/**
* Resolve the chain that governs a mission. Read-only; never writes.
* In `legacy` mode `links` is empty and callers must use the legacy rule
* (see `legacyCommandPair`).
*/
export async function resolveMissionChain(
payload: PayloadType,
missionId: number,
): Promise<ChainResolution> {
const stored = await loadStoredLinks(payload, missionId);
if (stored.length > 0) return { mode: "stored", links: stored };
const rated = await payload.find({
collection: "evaluations",
where: { mission: { equals: missionId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (rated.docs.length > 0) return { mode: "legacy", links: [] };
return { mode: "default", links: await computeDefaultChain(payload, missionId) };
}
/**
* Original command-review rule for missions rated before the chain existed:
* the rater leads an assignment the ratee belongs to and ranks strictly above.
*/
export async function legacyCommandPair(
payload: PayloadType,
raterId: number,
rateeId: number,
): Promise<boolean> {
if (raterId === rateeId) return false;
const indexes = await getUserRankIndexes(payload, [raterId, rateeId]);
const raterIndex = indexes.get(raterId);
const rateeIndex = indexes.get(rateeId);
if (raterIndex === undefined || rateeIndex === undefined) return false;
if (raterIndex <= rateeIndex) return false;
const res = await payload.find({
collection: "assignments",
where: {
and: [{ members: { contains: rateeId } }, { leader: { equals: raterId } }],
},
limit: 1,
depth: 0,
overrideAccess: true,
});
return res.docs.length > 0;
}
export async function loadStoredLinks(
payload: PayloadType,
missionId: number,
): Promise<CommandLink[]> {
const res = await payload.find({
collection: "mission-command-links",
where: { mission: { equals: missionId } },
limit: 1000,
depth: 0,
overrideAccess: true,
});
return res.docs.map((doc) => ({
supervisorId: relId(doc.supervisor as unknown as number | { id: number }) ?? 0,
subordinateId: relId(doc.subordinate as unknown as number | { id: number }) ?? 0,
source: doc.source === "default" ? "default" : "override",
}));
}
/**
* True when `raterId` is a supervisor of `rateeId` for this mission under the
* governing rule: the chain (stored or default), or the legacy rule for
* missions rated before the chain existed.
*/
export async function isCommandLink(
payload: PayloadType,
missionId: number,
raterId: number,
rateeId: number,
): Promise<boolean> {
return isCommandPair(payload, await resolveMissionChain(payload, missionId), raterId, rateeId);
}
/** Same as `isCommandLink`, for a chain the caller already resolved. */
export async function isCommandPair(
payload: PayloadType,
resolved: ChainResolution,
raterId: number,
rateeId: number,
): Promise<boolean> {
if (resolved.mode === "legacy") return legacyCommandPair(payload, raterId, rateeId);
return resolved.links.some((l) => l.supervisorId === raterId && l.subordinateId === rateeId);
}
/**
* Whether `user` may view and edit a mission's chain: superuser tier, or a
* listed author or Zeus. Authors and Zeus are checked from the mission doc.
*/
export async function canEditMissionChain(
payload: PayloadType,
user: { id: number; roleDocs?: unknown } | null | undefined,
mission: MissionLike,
): Promise<boolean> {
if (!user) return false;
const userId = Number(user.id);
const authors = mission.ownershipAndStatus?.authors ?? [];
const zeus = mission.ownershipAndStatus?.zeus ?? [];
const listed = [...authors, ...zeus].some((entry) => relId(entry) === userId);
if (listed) return true;
return isSuperuser(payload, user as Parameters<typeof isSuperuser>[1]);
}
/**
* The chain is locked once any evaluation exists for the mission, or the
* mission is Cancelled. Locked chains cannot be edited or reset.
*/
export async function getChainLockReason(
payload: PayloadType,
mission: MissionLike,
): Promise<string | null> {
if (mission.ownershipAndStatus?.status === "Cancelled") {
return "This mission is cancelled.";
}
const evals = await payload.find({
collection: "evaluations",
where: { mission: { equals: mission.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (evals.docs.length > 0) {
return "Ratings have already been submitted for this mission, so the chain is locked.";
}
return null;
}
/**
* Structural validation for a proposed chain. Returns human-readable errors;
* an empty array means the chain may be saved.
*
* - Both sides must be yes-RSVP participants of the mission.
* - No self-links.
* - No duplicate pairs.
* - No inverted rank: a supervisor must rank strictly above the subordinate
* (equal ranks are allowed for command links, per the chain-overrides-rank rule).
* - Members of equal or unresolvable rank may still be linked when the
* supervisor is present; only a strictly junior supervisor is rejected.
* - No cycles (A over B and B over A, or longer loops).
*/
export async function validateChain(
payload: PayloadType,
missionId: number,
links: ReadonlyArray<{ supervisorId: number; subordinateId: number }>,
): Promise<string[]> {
const errors: string[] = [];
const { ids, rankIndexes } = await loadParticipants(payload, missionId);
const present = new Set(ids);
const seen = new Set<string>();
for (const link of links) {
const { supervisorId: s, subordinateId: u } = link;
if (s === u) {
errors.push("A user cannot be their own supervisor.");
continue;
}
if (!present.has(s) || !present.has(u)) {
errors.push("Every linked user must have a yes RSVP for this mission.");
continue;
}
const key = `${s}:${u}`;
if (seen.has(key)) {
errors.push("Duplicate supervisor-subordinate pair.");
continue;
}
seen.add(key);
const si = rankIndexes.get(s);
const ui = rankIndexes.get(u);
if (si !== undefined && ui !== undefined && si < ui) {
errors.push("A supervisor cannot rank below the subordinate they command.");
}
}
if (hasCycle(links)) {
errors.push("The chain contains a cycle (users cannot be each other's supervisors).");
}
return errors;
}
function hasCycle(links: ReadonlyArray<{ supervisorId: number; subordinateId: number }>): boolean {
const graph = new Map<number, number[]>();
for (const { supervisorId, subordinateId } of links) {
const list = graph.get(supervisorId) ?? [];
list.push(subordinateId);
graph.set(supervisorId, list);
}
const state = new Map<number, 0 | 1 | 2>(); // 0 unseen, 1 in stack, 2 done
const visit = (node: number): boolean => {
const s = state.get(node) ?? 0;
if (s === 1) return true;
if (s === 2) return false;
state.set(node, 1);
for (const next of graph.get(node) ?? []) {
if (visit(next)) return true;
}
state.set(node, 2);
return false;
};
for (const node of graph.keys()) {
if (visit(node)) return true;
}
return false;
}
/**
* Freeze the default chain into rows, if none exist yet. Called on the first
* rating submission, so later assignment or rank changes cannot reclassify the
* ratings that already exist. Safe to call repeatedly.
*/
export async function freezeDefaults(payload: PayloadType, missionId: number): Promise<void> {
const existing = await payload.find({
collection: "mission-command-links",
where: { mission: { equals: missionId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existing.docs.length > 0) return;
const defaults = await computeDefaultChain(payload, missionId);
for (const link of defaults) {
await payload.create({
collection: "mission-command-links",
data: {
mission: missionId,
supervisor: link.supervisorId,
subordinate: link.subordinateId,
source: "default",
},
depth: 0,
overrideAccess: true,
});
}
}
/**
* Replace the mission's chain with `links`. Caller must have checked
* `canEditMissionChain` and `getChainLockReason`. Validates first; on success,
* deletes existing rows and writes the new ones as overrides.
*/
export async function saveMissionChain(
payload: PayloadType,
input: {
missionId: number;
updatedById: number;
links: ReadonlyArray<{ supervisorId: number; subordinateId: number }>;
},
): Promise<{ errors: string[]; saved: number }> {
if (input.links.length === 0) {
return {
errors: ["Add at least one command link, or reset the chain to defaults."],
saved: 0,
};
}
const errors = await validateChain(payload, input.missionId, input.links);
if (errors.length > 0) return { errors, saved: 0 };
await clearStoredLinks(payload, input.missionId);
for (const link of input.links) {
await payload.create({
collection: "mission-command-links",
data: {
mission: input.missionId,
supervisor: link.supervisorId,
subordinate: link.subordinateId,
source: "override",
updatedBy: input.updatedById,
},
depth: 0,
overrideAccess: true,
});
}
return { errors: [], saved: input.links.length };
}
export interface ChainParticipant {
id: number;
name: string;
}
export interface ChainEditorState {
mode: ChainMode;
links: CommandLink[];
participants: ChainParticipant[];
editable: boolean;
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).
*/
export async function getChainEditorState(
payload: PayloadType,
user: { id: number; roleDocs?: unknown } | null | undefined,
mission: MissionLike,
): Promise<ChainEditorState | null> {
if (!(await canEditMissionChain(payload, user, mission))) return null;
const resolved = await resolveMissionChain(payload, mission.id);
const { ids } = await loadParticipants(payload, mission.id);
const users =
ids.length === 0
? { docs: [] as Array<{ id: number; displayName?: string | null; username?: string | null }> }
: await payload.find({
collection: "users",
where: { id: { in: ids } },
limit: ids.length,
depth: 0,
overrideAccess: true,
});
const participants = users.docs
.map((doc) => ({ id: doc.id, name: doc.displayName || doc.username || `user-${doc.id}` }))
.sort((a, b) => a.name.localeCompare(b.name));
const lockReason = await getChainLockReason(payload, mission);
return {
mode: resolved.mode,
links: resolved.links,
participants,
editable: lockReason === null,
lockReason,
};
}
/**
* Delete stored rows so the mission returns to live defaults. Caller must have
* checked permission and lock state.
*/
export async function resetMissionChain(payload: PayloadType, missionId: number): Promise<void> {
await clearStoredLinks(payload, missionId);
}
async function clearStoredLinks(payload: PayloadType, missionId: number): Promise<void> {
const rows = await payload.find({
collection: "mission-command-links",
where: { mission: { equals: missionId } },
limit: 1000,
depth: 0,
overrideAccess: true,
});
for (const row of rows.docs) {
await payload.delete({
collection: "mission-command-links",
id: row.id,
overrideAccess: true,
});
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,49 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_mission_command_links_source" AS ENUM('default', 'override');
CREATE TABLE "mission_command_links" (
"id" serial PRIMARY KEY NOT NULL,
"mission_id" integer NOT NULL,
"supervisor_id" integer NOT NULL,
"subordinate_id" integer NOT NULL,
"source" "enum_mission_command_links_source" DEFAULT 'override' NOT NULL,
"updated_by_id" integer,
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
);
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "mission_command_links_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "mission_command_links_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "mission_command_links_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "mission_command_links_delete" boolean DEFAULT false;
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "mission_command_links_id" integer;
ALTER TABLE "mission_command_links" ADD CONSTRAINT "mission_command_links_mission_id_missions_id_fk" FOREIGN KEY ("mission_id") REFERENCES "public"."missions"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "mission_command_links" ADD CONSTRAINT "mission_command_links_supervisor_id_users_id_fk" FOREIGN KEY ("supervisor_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "mission_command_links" ADD CONSTRAINT "mission_command_links_subordinate_id_users_id_fk" FOREIGN KEY ("subordinate_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "mission_command_links" ADD CONSTRAINT "mission_command_links_updated_by_id_users_id_fk" FOREIGN KEY ("updated_by_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
CREATE INDEX "mission_command_links_mission_idx" ON "mission_command_links" USING btree ("mission_id");
CREATE INDEX "mission_command_links_supervisor_idx" ON "mission_command_links" USING btree ("supervisor_id");
CREATE INDEX "mission_command_links_subordinate_idx" ON "mission_command_links" USING btree ("subordinate_id");
CREATE INDEX "mission_command_links_updated_by_idx" ON "mission_command_links" USING btree ("updated_by_id");
CREATE INDEX "mission_command_links_updated_at_idx" ON "mission_command_links" USING btree ("updated_at");
CREATE INDEX "mission_command_links_created_at_idx" ON "mission_command_links" USING btree ("created_at");
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_mission_command_links_fk" FOREIGN KEY ("mission_command_links_id") REFERENCES "public"."mission_command_links"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "payload_locked_documents_rels_mission_command_links_id_idx" ON "payload_locked_documents_rels" USING btree ("mission_command_links_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "mission_command_links" DISABLE ROW LEVEL SECURITY;
DROP TABLE "mission_command_links" CASCADE;
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_mission_command_links_fk";
DROP INDEX "payload_locked_documents_rels_mission_command_links_id_idx";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "mission_command_links_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "mission_command_links_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "mission_command_links_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "mission_command_links_delete";
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "mission_command_links_id";
DROP TYPE "public"."enum_mission_command_links_source";`)
}

View file

@ -155,6 +155,7 @@ import * as migration_20261031_064618_drop_evaluation_kind from './20261031_0646
import * as migration_20261031_084725_add_mission_ratings from './20261031_084725_add_mission_ratings';
import * as migration_20261031_085035_add_mission_rating_sent_at_marker from './20261031_085035_add_mission_rating_sent_at_marker';
import * as migration_20261031_090000_add_missions_discord_modlist_buffer_sent_at from './20261031_090000_add_missions_discord_modlist_buffer_sent_at';
import * as migration_20261101_210013_add_mission_command_links from './20261101_210013_add_mission_command_links';
export const migrations = [
{
@ -935,11 +936,16 @@ export const migrations = [
{
up: migration_20261031_085035_add_mission_rating_sent_at_marker.up,
down: migration_20261031_085035_add_mission_rating_sent_at_marker.down,
name: '20261031_085035_add_mission_rating_sent_at_marker'
name: '20261031_085035_add_mission_rating_sent_at_marker',
},
{
up: migration_20261031_090000_add_missions_discord_modlist_buffer_sent_at.up,
down: migration_20261031_090000_add_missions_discord_modlist_buffer_sent_at.down,
name: '20261031_090000_add_missions_discord_modlist_buffer_sent_at'
name: '20261031_090000_add_missions_discord_modlist_buffer_sent_at',
},
{
up: migration_20261101_210013_add_mission_command_links.up,
down: migration_20261101_210013_add_mission_command_links.down,
name: '20261101_210013_add_mission_command_links'
},
];

View file

@ -195,6 +195,11 @@ export const enum_game_event_logs_required_permissions = pgEnum(
"mission-map-markers:update",
"mission-map-markers:delete",
"admin:mission-map-markers:manage",
"mission-ratings:create",
"mission-ratings:read",
"mission-ratings:update",
"mission-ratings:delete",
"admin:mission-ratings:manage",
"campaigns:create",
"campaigns:read",
"campaigns:update",
@ -755,6 +760,11 @@ export const enum_roles_permissions = pgEnum("enum_roles_permissions", [
"mission-map-markers:update",
"mission-map-markers:delete",
"admin:mission-map-markers:manage",
"mission-ratings:create",
"mission-ratings:read",
"mission-ratings:update",
"mission-ratings:delete",
"admin:mission-ratings:manage",
"campaigns:create",
"campaigns:read",
"campaigns:update",
@ -1113,6 +1123,7 @@ export const enum_contribution_entries_type = pgEnum("enum_contribution_entries_
"wiki-page-edit",
"mission-map-marker",
"survey-completion",
"mission-rating-completion",
"journal-publish",
"manual",
]);
@ -1124,13 +1135,8 @@ export const enum_contribution_entries_status = pgEnum("enum_contribution_entrie
]);
export const enum_contribution_entries_source_collection = pgEnum(
"enum_contribution_entries_source_collection",
["wiki-pages", "mission-map-markers", "form-submissions", "journals", "manual"],
["wiki-pages", "mission-map-markers", "form-submissions", "journals", "missions", "manual"],
);
export const enum_evaluations_kind = pgEnum("enum_evaluations_kind", [
"leader-direct",
"leader-indirect",
"subordinate",
]);
export const enum_evaluations_level = pgEnum("enum_evaluations_level", [
"exceptional",
"excellent",
@ -1219,6 +1225,17 @@ export const enum_mission_map_markers_shape = pgEnum("enum_mission_map_markers_s
"ellipse",
"polyline",
]);
export const enum_mission_ratings_ratings_value = pgEnum("enum_mission_ratings_ratings_value", [
"1",
"2",
"3",
"4",
"5",
]);
export const enum_mission_command_links_source = pgEnum("enum_mission_command_links_source", [
"default",
"override",
]);
export const enum_campaigns_status = pgEnum("enum_campaigns_status", [
"concept",
"inProgress",
@ -4007,7 +4024,6 @@ export const evaluations = pgTable(
.references(() => missions.id, {
onDelete: "set null",
}),
kind: enum_evaluations_kind("kind").notNull(),
level: enum_evaluations_level("level").notNull(),
comment: varchar("comment"),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
@ -4184,6 +4200,25 @@ export const leadership_transfers = pgTable(
],
);
export const missions_mission_rating_custom_factors = pgTable(
"missions_mission_rating_custom_factors",
{
_order: integer("_order").notNull(),
_parentID: integer("_parent_id").notNull(),
id: varchar("id").primaryKey(),
label: varchar("label").notNull(),
},
(columns) => [
index("missions_mission_rating_custom_factors_order_idx").on(columns._order),
index("missions_mission_rating_custom_factors_parent_id_idx").on(columns._parentID),
foreignKey({
columns: [columns["_parentID"]],
foreignColumns: [missions.id],
name: "missions_mission_rating_custom_factors_parent_id_fk",
}).onDelete("cascade"),
],
);
export const missions_mission_roles_provided_roles = pgTable(
"missions_mission_roles_provided_roles",
{
@ -4400,6 +4435,16 @@ export const missions = pgTable(
precision: 3,
}),
discordModlistHash: varchar("discord_modlist_hash"),
discordModlistBufferSentAt: timestamp("discord_modlist_buffer_sent_at", {
mode: "string",
withTimezone: true,
precision: 3,
}),
discordRatingSentAt: timestamp("discord_rating_sent_at", {
mode: "string",
withTimezone: true,
precision: 3,
}),
discordCancelledAt: timestamp("discord_cancelled_at", {
mode: "string",
withTimezone: true,
@ -4664,6 +4709,96 @@ export const mission_map_markers = pgTable(
],
);
export const mission_ratings_ratings = pgTable(
"mission_ratings_ratings",
{
_order: integer("_order").notNull(),
_parentID: integer("_parent_id").notNull(),
id: varchar("id").primaryKey(),
factor: varchar("factor").notNull(),
value: enum_mission_ratings_ratings_value("value").notNull(),
},
(columns) => [
index("mission_ratings_ratings_order_idx").on(columns._order),
index("mission_ratings_ratings_parent_id_idx").on(columns._parentID),
foreignKey({
columns: [columns["_parentID"]],
foreignColumns: [mission_ratings.id],
name: "mission_ratings_ratings_parent_id_fk",
}).onDelete("cascade"),
],
);
export const mission_ratings = pgTable(
"mission_ratings",
{
id: serial("id").primaryKey(),
mission: integer("mission_id")
.notNull()
.references(() => missions.id, {
onDelete: "set null",
}),
user: integer("user_id")
.notNull()
.references(() => users.id, {
onDelete: "set null",
}),
comment: varchar("comment"),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
},
(columns) => [
index("mission_ratings_mission_idx").on(columns.mission),
index("mission_ratings_user_idx").on(columns.user),
index("mission_ratings_updated_at_idx").on(columns.updatedAt),
index("mission_ratings_created_at_idx").on(columns.createdAt),
],
);
export const mission_command_links = pgTable(
"mission_command_links",
{
id: serial("id").primaryKey(),
mission: integer("mission_id")
.notNull()
.references(() => missions.id, {
onDelete: "set null",
}),
supervisor: integer("supervisor_id")
.notNull()
.references(() => users.id, {
onDelete: "set null",
}),
subordinate: integer("subordinate_id")
.notNull()
.references(() => users.id, {
onDelete: "set null",
}),
source: enum_mission_command_links_source("source").notNull().default("override"),
updatedBy: integer("updated_by_id").references(() => users.id, {
onDelete: "set null",
}),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
},
(columns) => [
index("mission_command_links_mission_idx").on(columns.mission),
index("mission_command_links_supervisor_idx").on(columns.supervisor),
index("mission_command_links_subordinate_idx").on(columns.subordinate),
index("mission_command_links_updated_by_idx").on(columns.updatedBy),
index("mission_command_links_updated_at_idx").on(columns.updatedAt),
index("mission_command_links_created_at_idx").on(columns.createdAt),
],
);
export const campaigns = pgTable(
"campaigns",
{
@ -9137,6 +9272,14 @@ export const payload_mcp_api_keys = pgTable(
missionMapMarkers_create: boolean("mission_map_markers_create").default(false),
missionMapMarkers_update: boolean("mission_map_markers_update").default(false),
missionMapMarkers_delete: boolean("mission_map_markers_delete").default(false),
missionRatings_find: boolean("mission_ratings_find").default(false),
missionRatings_create: boolean("mission_ratings_create").default(false),
missionRatings_update: boolean("mission_ratings_update").default(false),
missionRatings_delete: boolean("mission_ratings_delete").default(false),
missionCommandLinks_find: boolean("mission_command_links_find").default(false),
missionCommandLinks_create: boolean("mission_command_links_create").default(false),
missionCommandLinks_update: boolean("mission_command_links_update").default(false),
missionCommandLinks_delete: boolean("mission_command_links_delete").default(false),
campaigns_find: boolean("campaigns_find").default(false),
campaigns_create: boolean("campaigns_create").default(false),
campaigns_update: boolean("campaigns_update").default(false),
@ -9469,6 +9612,8 @@ export const payload_locked_documents_rels = pgTable(
"mission-attendancesID": integer("mission_attendances_id"),
"mission-role-signupsID": integer("mission_role_signups_id"),
"mission-map-markersID": integer("mission_map_markers_id"),
"mission-ratingsID": integer("mission_ratings_id"),
"mission-command-linksID": integer("mission_command_links_id"),
campaignsID: integer("campaigns_id"),
factionsID: integer("factions_id"),
technologiesID: integer("technologies_id"),
@ -9600,6 +9745,10 @@ export const payload_locked_documents_rels = pgTable(
index("payload_locked_documents_rels_mission_map_markers_id_idx").on(
columns["mission-map-markersID"],
),
index("payload_locked_documents_rels_mission_ratings_id_idx").on(columns["mission-ratingsID"]),
index("payload_locked_documents_rels_mission_command_links_id_idx").on(
columns["mission-command-linksID"],
),
index("payload_locked_documents_rels_campaigns_id_idx").on(columns.campaignsID),
index("payload_locked_documents_rels_factions_id_idx").on(columns.factionsID),
index("payload_locked_documents_rels_technologies_id_idx").on(columns.technologiesID),
@ -9887,6 +10036,16 @@ export const payload_locked_documents_rels = pgTable(
foreignColumns: [mission_map_markers.id],
name: "payload_locked_documents_rels_mission_map_markers_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["mission-ratingsID"]],
foreignColumns: [mission_ratings.id],
name: "payload_locked_documents_rels_mission_ratings_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["mission-command-linksID"]],
foreignColumns: [mission_command_links.id],
name: "payload_locked_documents_rels_mission_command_links_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["campaignsID"]],
foreignColumns: [campaigns.id],
@ -11464,6 +11623,16 @@ export const relations_leadership_transfers = relations(leadership_transfers, ({
relationName: "reviewedBy",
}),
}));
export const relations_missions_mission_rating_custom_factors = relations(
missions_mission_rating_custom_factors,
({ one }) => ({
_parentID: one(missions, {
fields: [missions_mission_rating_custom_factors._parentID],
references: [missions.id],
relationName: "missionRating_customFactors",
}),
}),
);
export const relations_missions_mission_roles_provided_roles = relations(
missions_mission_roles_provided_roles,
({ one }) => ({
@ -11599,6 +11768,9 @@ export const relations_missions = relations(missions, ({ one, many }) => ({
references: [campaigns.id],
relationName: "classification_campaign",
}),
missionRating_customFactors: many(missions_mission_rating_custom_factors, {
relationName: "missionRating_customFactors",
}),
missionRoles_providedRoles: many(missions_mission_roles_provided_roles, {
relationName: "missionRoles_providedRoles",
}),
@ -11676,6 +11848,50 @@ export const relations_mission_map_markers = relations(mission_map_markers, ({ o
relationName: "createdBy",
}),
}));
export const relations_mission_ratings_ratings = relations(mission_ratings_ratings, ({ one }) => ({
_parentID: one(mission_ratings, {
fields: [mission_ratings_ratings._parentID],
references: [mission_ratings.id],
relationName: "ratings",
}),
}));
export const relations_mission_ratings = relations(mission_ratings, ({ one, many }) => ({
mission: one(missions, {
fields: [mission_ratings.mission],
references: [missions.id],
relationName: "mission",
}),
user: one(users, {
fields: [mission_ratings.user],
references: [users.id],
relationName: "user",
}),
ratings: many(mission_ratings_ratings, {
relationName: "ratings",
}),
}));
export const relations_mission_command_links = relations(mission_command_links, ({ one }) => ({
mission: one(missions, {
fields: [mission_command_links.mission],
references: [missions.id],
relationName: "mission",
}),
supervisor: one(users, {
fields: [mission_command_links.supervisor],
references: [users.id],
relationName: "supervisor",
}),
subordinate: one(users, {
fields: [mission_command_links.subordinate],
references: [users.id],
relationName: "subordinate",
}),
updatedBy: one(users, {
fields: [mission_command_links.updatedBy],
references: [users.id],
relationName: "updatedBy",
}),
}));
export const relations_campaigns = relations(campaigns, ({ one }) => ({
coverImage: one(media, {
fields: [campaigns.coverImage],
@ -13767,6 +13983,16 @@ export const relations_payload_locked_documents_rels = relations(
references: [mission_map_markers.id],
relationName: "mission-map-markers",
}),
"mission-ratingsID": one(mission_ratings, {
fields: [payload_locked_documents_rels["mission-ratingsID"]],
references: [mission_ratings.id],
relationName: "mission-ratings",
}),
"mission-command-linksID": one(mission_command_links, {
fields: [payload_locked_documents_rels["mission-command-linksID"]],
references: [mission_command_links.id],
relationName: "mission-command-links",
}),
campaignsID: one(campaigns, {
fields: [payload_locked_documents_rels.campaignsID],
references: [campaigns.id],
@ -14251,7 +14477,6 @@ type DatabaseSchema = {
enum_contribution_entries_type: typeof enum_contribution_entries_type;
enum_contribution_entries_status: typeof enum_contribution_entries_status;
enum_contribution_entries_source_collection: typeof enum_contribution_entries_source_collection;
enum_evaluations_kind: typeof enum_evaluations_kind;
enum_evaluations_level: typeof enum_evaluations_level;
enum_ribbon_submissions_grantor_types: typeof enum_ribbon_submissions_grantor_types;
enum_ribbon_submissions_status: typeof enum_ribbon_submissions_status;
@ -14270,6 +14495,8 @@ type DatabaseSchema = {
enum_missions_civilian_presence: typeof enum_missions_civilian_presence;
enum_mission_attendances_response: typeof enum_mission_attendances_response;
enum_mission_map_markers_shape: typeof enum_mission_map_markers_shape;
enum_mission_ratings_ratings_value: typeof enum_mission_ratings_ratings_value;
enum_mission_command_links_source: typeof enum_mission_command_links_source;
enum_campaigns_status: typeof enum_campaigns_status;
enum_campaigns_campaign_mode: typeof enum_campaigns_campaign_mode;
enum_factions_type: typeof enum_factions_type;
@ -14430,6 +14657,7 @@ type DatabaseSchema = {
ribbon_submissions: typeof ribbon_submissions;
promotion_nominations: typeof promotion_nominations;
leadership_transfers: typeof leadership_transfers;
missions_mission_rating_custom_factors: typeof missions_mission_rating_custom_factors;
missions_mission_roles_provided_roles: typeof missions_mission_roles_provided_roles;
missions_briefing: typeof missions_briefing;
missions_mission_objectives: typeof missions_mission_objectives;
@ -14444,6 +14672,9 @@ type DatabaseSchema = {
mission_attendances: typeof mission_attendances;
mission_role_signups: typeof mission_role_signups;
mission_map_markers: typeof mission_map_markers;
mission_ratings_ratings: typeof mission_ratings_ratings;
mission_ratings: typeof mission_ratings;
mission_command_links: typeof mission_command_links;
campaigns: typeof campaigns;
factions_relationships: typeof factions_relationships;
factions: typeof factions;
@ -14667,6 +14898,7 @@ type DatabaseSchema = {
relations_ribbon_submissions: typeof relations_ribbon_submissions;
relations_promotion_nominations: typeof relations_promotion_nominations;
relations_leadership_transfers: typeof relations_leadership_transfers;
relations_missions_mission_rating_custom_factors: typeof relations_missions_mission_rating_custom_factors;
relations_missions_mission_roles_provided_roles: typeof relations_missions_mission_roles_provided_roles;
relations_missions_briefing: typeof relations_missions_briefing;
relations_missions_mission_objectives: typeof relations_missions_mission_objectives;
@ -14681,6 +14913,9 @@ type DatabaseSchema = {
relations_mission_attendances: typeof relations_mission_attendances;
relations_mission_role_signups: typeof relations_mission_role_signups;
relations_mission_map_markers: typeof relations_mission_map_markers;
relations_mission_ratings_ratings: typeof relations_mission_ratings_ratings;
relations_mission_ratings: typeof relations_mission_ratings;
relations_mission_command_links: typeof relations_mission_command_links;
relations_campaigns: typeof relations_campaigns;
relations_factions_relationships: typeof relations_factions_relationships;
relations_factions_rels: typeof relations_factions_rels;

View file

@ -104,6 +104,7 @@ export interface Config {
'mission-role-signups': MissionRoleSignup;
'mission-map-markers': MissionMapMarker;
'mission-ratings': MissionRating;
'mission-command-links': MissionCommandLink;
campaigns: Campaign;
factions: Faction;
technologies: Technology;
@ -219,6 +220,7 @@ export interface Config {
'mission-role-signups': MissionRoleSignupsSelect<false> | MissionRoleSignupsSelect<true>;
'mission-map-markers': MissionMapMarkersSelect<false> | MissionMapMarkersSelect<true>;
'mission-ratings': MissionRatingsSelect<false> | MissionRatingsSelect<true>;
'mission-command-links': MissionCommandLinksSelect<false> | MissionCommandLinksSelect<true>;
campaigns: CampaignsSelect<false> | CampaignsSelect<true>;
factions: FactionsSelect<false> | FactionsSelect<true>;
technologies: TechnologiesSelect<false> | TechnologiesSelect<true>;
@ -5013,6 +5015,28 @@ export interface MissionRating {
updatedAt: string;
createdAt: string;
}
/**
* Mission-scoped chain of command. Edited on the mission page by authors, Zeus and superusers.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "mission-command-links".
*/
export interface MissionCommandLink {
id: number;
mission: number | Mission;
/**
* The rater side: who was in charge for this op.
*/
supervisor: number | User;
/**
* The ratee side: who the supervisor commanded for this op.
*/
subordinate: number | User;
source: 'default' | 'override';
updatedBy?: (number | null) | User;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "tech-researches".
@ -8023,6 +8047,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
missionCommandLinks?: {
/**
* Allow clients to find mission-command-links.
*/
find?: boolean | null;
/**
* Allow clients to create mission-command-links.
*/
create?: boolean | null;
/**
* Allow clients to update mission-command-links.
*/
update?: boolean | null;
/**
* Allow clients to delete mission-command-links.
*/
delete?: boolean | null;
};
campaigns?: {
/**
* Allow clients to find campaigns.
@ -9296,6 +9338,10 @@ export interface PayloadLockedDocument {
relationTo: 'mission-ratings';
value: number | MissionRating;
} | null)
| ({
relationTo: 'mission-command-links';
value: number | MissionCommandLink;
} | null)
| ({
relationTo: 'campaigns';
value: number | Campaign;
@ -10788,6 +10834,19 @@ export interface MissionRatingsSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "mission-command-links_select".
*/
export interface MissionCommandLinksSelect<T extends boolean = true> {
mission?: T;
supervisor?: T;
subordinate?: T;
source?: T;
updatedBy?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "campaigns_select".
@ -12930,6 +12989,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
missionCommandLinks?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
campaigns?:
| T
| {

View file

@ -20,6 +20,7 @@ import { MissionAttendances } from "@/collections/intelligence/MissionAttendance
import { MissionRoleSignups } from "@/collections/intelligence/MissionRoleSignups";
import { MissionMapMarkers } from "@/collections/intelligence/MissionMapMarkers";
import { MissionRatings } from "@/collections/intelligence/MissionRatings";
import { MissionCommandLinks } from "@/collections/intelligence/MissionCommandLinks";
import { Maps } from "@/collections/world/Maps";
import { MapRoads } from "@/collections/world/MapRoads";
import { MapZones } from "@/collections/world/MapZones";
@ -349,6 +350,7 @@ const collections = [
MissionRoleSignups,
MissionMapMarkers,
MissionRatings,
MissionCommandLinks,
Campaigns,
Factions,
Technologies,
@ -742,6 +744,7 @@ export default buildConfig({
[MissionAttendances.slug]: true,
[MissionRoleSignups.slug]: true,
[MissionRatings.slug]: true,
[MissionCommandLinks.slug]: true,
[Campaigns.slug]: true,
[Factions.slug]: true,
[Technologies.slug]: true,

View file

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