1
0
Fork 0

Compare commits

..

No commits in common. "8fff9c3f924a2a53bd41afba35cf0dfa46cd24f1" and "70b773ee5b0121b71076b4940e8a333da7a98f56" have entirely different histories.

37 changed files with 347 additions and 48097 deletions

View file

@ -1,25 +1,5 @@
# Changelog
# v0.15.0
Mission detail is restyled as bordered dossier cards with classification strips, a new command-chain editor lets staff assign command hierarchy and drive command reviews, and faction chips become links with cover-image backgrounds.
### Features
- **Dossier styling.** The mission detail sections and the right sidebar (Campaign, Roster, Server) are now bordered frames with squared corners, a faint grid texture, corner brackets that brighten on hover, and a classification strip. Section titles, faction types, and empty states were consolidated across the page.
- **Command chain editor.** Staff can assign who was in command of whom on a mission. The chain drives command reviews: whoever was the ratee's direct supervisor, and whoever leads an assignment they were on, produces a review.
- **Faction cards.** Faction chips on the mission detail page are now links, each with a cover-image background.
### Fixes
- **Dashboard.** Centered empty mission text and neutralized the heading when no missions exist.
### Changes
- **Sidebar.** Moved the Contributions link into the Contribute sub-navlist above Minigames and added intro text to the Contribute dropdown.
---
# v0.14.2
Peer evaluations now need both players at the op, and a senior's review of their own direct subordinate is shown as a command review, while everyone else's ratings feed the leadership spectrum.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.15.0",
"version": "0.14.2",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -9,26 +9,15 @@ import {
CalendarDaysIcon,
ChevronRightIcon,
ClockIcon,
ClipboardListIcon,
CrosshairIcon,
FileTextIcon,
FlagIcon,
GitBranchIcon,
MapPinIcon,
RadarIcon,
RadioIcon,
ServerIcon,
ShieldIcon,
StarIcon,
TruckIcon,
UserIcon,
UserPlusIcon,
UsersIcon,
} from "lucide-react";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { ClientDate } from "@/components/frontend/ClientDate";
import { MissionBriefingSection } from "@/components/frontend/intelligence/MissionBriefingSection";
import { ReadoutFooter, TacticalFrame, refCodeFrom } from "@/components/frontend/dashboard/tactical";
import { MissionObjectives } from "@/components/frontend/intelligence/MissionObjectives";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { redactText } from "@/lib/redaction";
@ -36,8 +25,6 @@ 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";
@ -187,9 +174,6 @@ 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;
@ -520,166 +504,73 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* ── Main Content (2/3) ──────────────────────────── */}
<div className="xl:col-span-2 flex flex-col gap-6">
<TacticalFrame
classification="OPERATION // RATING"
icon={StarIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionRating
missionId={mission.id}
state={ratingState}
aggregate={ratingAggregate}
customFactors={ratingCustomFactors}
/>
</TacticalFrame>
<MissionRating
missionId={mission.id}
state={ratingState}
aggregate={ratingAggregate}
customFactors={ratingCustomFactors}
/>
<TacticalFrame
classification="OPERATION // DETAILS"
icon={ClipboardListIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<Item variant="outline">
<ItemContent>
<div className="grid grid-cols-2 md:grid-cols-3 gap-3 text-sm">
<div>
<span className="text-muted-foreground">Type</span>
<p className="font-medium">{mission.classification.missionType}</p>
</div>
<div>
<span className="text-muted-foreground">Operation Type</span>
<p className="font-medium capitalize">{mission.operationType}</p>
</div>
<div>
<span className="text-muted-foreground">Max Players</span>
<p className="font-medium">{mission.missionRoles?.maxPlayers ?? "-"}</p>
</div>
<Item variant="outline">
<ItemHeader>
<ItemTitle>Mission Details</ItemTitle>
</ItemHeader>
<ItemContent>
<div className="grid grid-cols-2 md:grid-cols-3 gap-3 text-sm">
<div>
<span className="text-muted-foreground">Type</span>
<p className="font-medium">{mission.classification.missionType}</p>
</div>
</ItemContent>
</Item>
<ReadoutFooter
cells={[
{ label: "Type", value: mission.classification.missionType },
{ label: "Op Type", value: mission.operationType },
{ label: "Max Players", value: String(mission.missionRoles?.maxPlayers ?? "-") },
]}
/>
</TacticalFrame>
<div>
<span className="text-muted-foreground">Operation Type</span>
<p className="font-medium capitalize">{mission.operationType}</p>
</div>
<div>
<span className="text-muted-foreground">Max Players</span>
<p className="font-medium">{mission.missionRoles?.maxPlayers ?? "-"}</p>
</div>
</div>
</ItemContent>
</Item>
<TacticalFrame
classification="OPERATION // THREAT"
icon={RadarIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionThreatAssessment
likelihoods={mission.threatAssessment?.likelihoods ?? null}
missionId={mission.id}
/>
</TacticalFrame>
<MissionThreatAssessment
likelihoods={mission.threatAssessment?.likelihoods ?? null}
missionId={mission.id}
/>
<TacticalFrame
classification="OPERATION // BRIEFING"
icon={FileTextIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionBriefingSection
briefing={mission.briefing ?? null}
missionName={mission.name}
/>
</TacticalFrame>
<MissionBriefingSection
briefing={mission.briefing ?? null}
missionName={mission.name}
/>
<TacticalFrame
classification="OPERATION // OBJECTIVES"
icon={CrosshairIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionObjectives
objectives={objectives}
missionId={mission.id}
isEditable={canManage}
canReveal={canReveal}
/>
<ReadoutFooter cells={[{ label: "Obj", value: String(objectives.length) }]} />
</TacticalFrame>
<MissionObjectives
objectives={objectives}
missionId={mission.id}
isEditable={canManage}
canReveal={canReveal}
/>
<TacticalFrame
classification="OPERATION // FACTIONS"
icon={ShieldIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionFactions factionsInvolved={mission.factionsInvolved ?? null} />
</TacticalFrame>
<MissionFactions factionsInvolved={mission.factionsInvolved ?? null} />
<TacticalFrame
classification="OPERATION // ROLES"
icon={UsersIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionRoles
roles={mission.missionRoles?.providedRoles ?? null}
notes={mission.missionRoles?.notes ?? null}
maxPlayers={mission.missionRoles?.maxPlayers ?? 32}
/>
</TacticalFrame>
<MissionRoles
roles={mission.missionRoles?.providedRoles ?? null}
notes={mission.missionRoles?.notes ?? null}
maxPlayers={mission.missionRoles?.maxPlayers ?? 32}
/>
{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>
)}
<MissionRoleSignups
missionId={mission.id}
currentUserId={currentUser ? (currentUser.id as number) : null}
closed={!signupGate.open}
closedReason={signupGate.reason ?? null}
roles={signupRoles}
mySignup={signupState.mySignup}
canManage={canManage}
/>
<TacticalFrame
classification="OPERATION // SIGN-UPS"
icon={UserPlusIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionRoleSignups
missionId={mission.id}
currentUserId={currentUser ? (currentUser.id as number) : null}
closed={!signupGate.open}
closedReason={signupGate.reason ?? null}
roles={signupRoles}
mySignup={signupState.mySignup}
canManage={canManage}
/>
</TacticalFrame>
<MissionLogistics logisticsAndSupport={mission.logisticsAndSupport ?? null} />
<TacticalFrame
classification="OPERATION // LOGISTICS"
icon={TruckIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionLogistics logisticsAndSupport={mission.logisticsAndSupport ?? null} />
</TacticalFrame>
<TacticalFrame
classification="OPERATION // COMMS"
icon={RadioIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionComms commsAndDocs={mission.commsAndDocs ?? null} />
</TacticalFrame>
<MissionComms commsAndDocs={mission.commsAndDocs ?? null} />
</div>
{/* ── Right Sidebar (1/3) ─────────────────────────── */}
@ -746,94 +637,110 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
{/* Campaign Card */}
{campaign && (
<TacticalFrame
classification="OPERATION // CAMPAIGN"
refCode={`REF ${refCodeFrom(campaign.id)}`}
grow={false}
>
<Link
href={`/intelligence/campaigns/${campaign.id}`}
className="block min-w-0 flex-1 flex-col gap-2 p-4 transition-colors group hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
>
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<FlagIcon className="size-4 shrink-0 text-white/60" />
<span className="truncate text-sm font-medium text-white">
{campaign.name}
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<FlagIcon className="size-4 text-muted-foreground" />
<ItemTitle>Campaign</ItemTitle>
</div>
<Link
href={`/intelligence/campaigns/${campaign.id}`}
className="py-1 text-xs text-muted-foreground hover:text-primary transition-colors"
>
View
</Link>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-2">
<div>
<h3 className="text-sm font-semibold">{campaign.name}</h3>
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded mt-1 inline-block ${campaign.status === "inProgress" ? "bg-blue-500/20 text-blue-400" : campaign.status === "onHold" ? "bg-amber-500/20 text-amber-400" : "bg-muted text-muted-foreground"}`}
>
{campaign.status === "inProgress"
? "In Progress"
: campaign.status === "onHold"
? "On Hold"
: campaign.status}
</span>
</div>
<span className="inline-flex shrink-0 items-center gap-2">
<span className={`self-start inline-block text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${campaign.status === "concept" ? "bg-emerald-500/20 text-emerald-400" : campaign.status === "inProgress" ? "bg-blue-500/20 text-blue-400" : campaign.status === "onHold" ? "bg-amber-500/20 text-amber-400" : "bg-emerald-500/20 text-emerald-400"}`}>
{campaign.status === "concept" ? "Planning" : campaign.status === "inProgress" ? "Active Deployment" : campaign.status === "onHold" ? "On Hold" : "Concluded"}
</span>
<ChevronRightIcon className="size-3 text-white/50 opacity-0 group-hover:opacity-100 transition-opacity" />
</span>
<p className="text-xs text-muted-foreground line-clamp-3">{campaign.summary}</p>
</div>
<p className="text-xs text-white/60 line-clamp-3">{campaign.summary}</p>
</Link>
</TacticalFrame>
</ItemContent>
</Item>
)}
{/* Sibling Missions */}
{siblingMissions.length > 0 && (
<TacticalFrame
classification="OPERATION // ROSTER"
refCode={`REF ${refCodeFrom(campaign?.id ?? mission.id)}`}
grow={false}
>
<div className="flex min-w-0 flex-1 flex-col gap-0.5 p-3">
{siblingMissions.map((m) => {
return (
<Link
key={m.id}
href={`/intelligence/missions/${m.id}`}
className="flex items-center gap-3 rounded-md px-2 py-1.5 text-white/80 transition-colors group hover:bg-muted/50 hover:text-white"
>
<div className="flex min-w-0 flex-1 flex-col">
{m.codeName && (
<span className="font-mono text-[10px] text-white/50">
{m.codeName}
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<CrosshairIcon className="size-4 text-muted-foreground" />
<ItemTitle>Other Missions in Campaign</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-1.5">
{siblingMissions.map((m) => {
const mDate = new Date(m.classification.startDateTime);
return (
<Link
key={m.id}
href={`/intelligence/missions/${m.id}`}
className="flex items-center gap-3 p-1.5 rounded-md hover:bg-muted/50 transition-colors group"
>
<div className="flex flex-col min-w-0 flex-1">
{m.codeName && (
<span className="font-mono text-[10px] text-muted-foreground">
{m.codeName}
</span>
)}
<span className="text-sm truncate group-hover:text-primary transition-colors">
{m.name}
</span>
)}
<span className="truncate text-sm font-medium group-hover:text-white">
{m.name}
</span>
</div>
<div className="flex items-center gap-2 shrink-0">
<span className={`self-start inline-block text-[10px] font-semibold uppercase tracking-wider px-1 py-0.5 rounded ${statusColors[m.ownershipAndStatus.status] ?? "bg-muted text-muted-foreground"}`}>
{m.ownershipAndStatus.status}
</span>
<ChevronRightIcon className="size-3 text-white/50 opacity-0 group-hover:opacity-100 transition-opacity" />
</div>
</Link>
);
})}
</div>
</TacticalFrame>
</div>
<div className="flex items-center gap-2 shrink-0">
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1 py-0.5 rounded ${statusColors[m.ownershipAndStatus.status] ?? "bg-muted text-muted-foreground"}`}
>
{m.ownershipAndStatus.status}
</span>
<ChevronRightIcon className="size-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
</div>
</Link>
);
})}
</div>
</ItemContent>
</Item>
)}
{/* Server Details */}
{mission.gameDetails?.serverDetails?.serverIp && (
<TacticalFrame
classification="OPERATION // SERVER"
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<div className="flex min-w-0 flex-1 flex-col gap-3 p-4 text-sm">
<div className="flex items-center justify-between gap-2">
<span className="text-white/60">Address</span>
<span className="font-mono text-white">
{mission.gameDetails.serverDetails.serverIp}
</span>
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ServerIcon className="size-4 text-muted-foreground" />
<ItemTitle>Server</ItemTitle>
</div>
<div className="flex items-center justify-between gap-2">
<span className="text-white/60">Port</span>
<span className="font-mono text-white">
{mission.gameDetails.serverDetails.serverPort}
</span>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-1.5 text-sm">
<div className="flex justify-between">
<span className="text-muted-foreground">Address</span>
<span className="font-mono">
{mission.gameDetails.serverDetails.serverIp}
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Port</span>
<span className="font-mono">
{mission.gameDetails.serverDetails.serverPort}
</span>
</div>
</div>
</div>
</TacticalFrame>
</ItemContent>
</Item>
)}
</div>
</div>

View file

@ -27,12 +27,6 @@ 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> {
@ -1033,63 +1027,6 @@ 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

@ -333,13 +333,7 @@ export default async function HomePage() {
"mission-briefing",
<MissionBriefing
mission={mission}
heading={
upcomingRes.docs[0]
? "Next Mission"
: briefingMission
? "Last Mission"
: "Missions"
}
heading={upcomingRes.docs[0] ? "Next Mission" : "Last Mission"}
/>,
);
widgetNodes.set("recent-events", <RecentEvents events={events} currentUserId={userId} />);

View file

@ -7,7 +7,6 @@ import type { User } from "@/payload-types";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { isPerformanceLevelId } from "@/lib/evaluations/levels";
import { freezeDefaults } from "@/lib/command-chain";
import {
evaluateEligibility,
getLatestSubordinateLevel,
@ -98,17 +97,6 @@ export async function submitEvaluation(input: {
return { success: false, error: eligibility.reason ?? "Not eligible to evaluate." };
}
const anyRating = await payload.find({
collection: "evaluations",
where: { mission: { equals: input.missionId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (anyRating.docs.length === 0) {
await freezeDefaults(payload, input.missionId);
}
const { evaluation, created } = await upsertEvaluation(payload, {
raterId: user.id as number,
rateeId: ratee.id,

View file

@ -10,7 +10,6 @@ import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { isSuperuser, hasPermission } from "@/utils/access-control/hasPermission";
import { isMissionEvaluable } from "@/lib/evaluations";
import { rankDirection, type RankDirection } from "@/lib/evaluations/ranks";
import { isCommandLink } from "@/lib/command-chain";
import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels";
import { getEvaluationSummary } from "./actions";
import { getContributionSummary } from "@/lib/contributions";
@ -166,19 +165,6 @@ async function findUpgradedFromNames(
* one side of the pair attended). Callers must additionally verify a strict
* rank gap exists before showing this list.
*/
async function filterCommandMissions(
payload: Payload,
missions: readonly EvaluationMissionOption[],
viewerId: number,
subjectId: number,
): Promise<readonly EvaluationMissionOption[]> {
const kept: EvaluationMissionOption[] = [];
for (const mission of missions) {
if (await isCommandLink(payload, mission.id, viewerId, subjectId)) kept.push(mission);
}
return kept;
}
async function findEligibleEvaluationMissions(
payload: Payload,
viewerId: number,
@ -360,13 +346,9 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
rankGapPromise,
canEditIntelPromise,
]);
// Without a strict rank gap the dialog only lists missions where the viewer is
// a chain command link for this subject (equal-rank command reviews).
const eligibleMissions = rankGap
? eligibleMissionsRaw
: viewer && !isProfileOwner
? await filterCommandMissions(payload, eligibleMissionsRaw, viewer.id, user.id)
: [];
// Without a strict rank gap there is no direction to rate in, so the dialog
// gets no mission list at all.
const eligibleMissions = rankGap ? eligibleMissionsRaw : [];
// Seniors may see the subordinate-rating line on their juniors' profiles.
const canViewSubordinate =
isProfileOwner || isLegacyPrivileged || isSuperuserViewer || rankGap === "downward";

View file

@ -11,8 +11,8 @@ export const runtime = "nodejs";
* GET /api/mission-reminder
*
* Returns recently completed main operations (within 72h of completion) where the
* authenticated user RSVP'd "yes" and at least one rateable co-attendee also
* RSVP'd "yes" (a strictly higher-ranked one, or a chain supervisor). The client uses this to prompt mission
* authenticated user RSVP'd "yes" and at least one strictly higher-ranked
* co-attendee also RSVP'd "yes". The client uses this to prompt mission
* feedback. Leader entries carry identity only, no rater/comment data.
*/
export async function GET(req: NextRequest) {

View file

@ -1,75 +0,0 @@
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

@ -1,13 +1,12 @@
"use client";
import { ChevronRight, Mic, Trophy } from "lucide-react";
import { ChevronRight, Mic } from "lucide-react";
import Link from "next/link";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
@ -21,8 +20,6 @@ import {
* (NavUser): a "Contribute" header with a single Voiceover entry. Kept as its
* own dropdown so it stays visually consistent with the adjacent Minigames
* entry and can grow to more contribution channels without a code change.
* Now holds both contribution channels: Voiceover (record takes) and
* Contributions (leaderboard + moderation).
*/
export function NavContribute() {
const { isMobile } = useSidebar();
@ -43,22 +40,12 @@ export function NavContribute() {
align="end"
sideOffset={4}
>
<div className="px-2 pb-3 pt-1.5 text-xs text-muted-foreground leading-snug">
Contribute to the web app to earn XP and contribution rewards!
</div>
<DropdownMenuItem asChild>
<Link href="/voiceover">
<Mic />
Voiceover
</Link>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link href="/contributions">
<Trophy />
Contributions
</Link>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>

View file

@ -25,6 +25,7 @@ import {
Search,
Store,
Swords,
Trophy,
Truck,
UserCog,
Users,
@ -198,6 +199,11 @@ export const sidebarData = {
url: "/awards",
icon: Award,
},
{
title: "Contributions",
url: "/contributions",
icon: Trophy,
},
{
title: "Locker",
url: "/locker",

View file

@ -17,15 +17,11 @@ export function MissionBriefing({ mission, heading = "Next Mission" }: MissionBr
>
{/* No separate header row: the frame strip names the section and the
mission card carries its own "View details" affordance. */}
<div className="flex min-h-0 flex-1 flex-col p-4">
<div className="p-4">
{mission ? (
<MissionCard mission={mission} showFullDetails />
) : (
<div className="flex min-w-0 flex-1 items-center justify-center">
<p className="text-center text-sm text-muted-foreground italic">
No missions currently scheduled.
</p>
</div>
<p className="text-sm text-muted-foreground italic">No missions currently scheduled.</p>
)}
</div>
</TacticalFrame>

View file

@ -1,5 +1,4 @@
import type { ReactNode } from "react";
import type { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
/**
@ -21,39 +20,30 @@ export function refCodeFrom(seed: string | number): string {
}
interface TacticalFrameProps {
/** Left classification-strip label, e.g. "Personnel // Service Record". Omit for label-less frames, where the internal content title owns the heading. */
classification?: string;
/** Left classification-strip label, e.g. "Personnel // Service Record". */
classification: string;
/** Right strip label, e.g. "REF 042". Omit to hide. */
refCode?: string;
/** Optional lead icon rendered before the classification label in the strip. */
icon?: LucideIcon;
children: ReactNode;
/** Optional permanent readout bar pinned to the bottom edge. */
footer?: ReactNode;
/** Corner brackets, default on. Turn off for bar-shaped surfaces. */
brackets?: boolean;
/** Fill the parent's cross axis (flex-1). Default true; pass false for a
* content-height frame (e.g. stacked, non-stretching sections). */
grow?: boolean;
className?: string;
}
export function TacticalFrame({
classification,
refCode,
icon,
children,
footer,
brackets = true,
grow = true,
className,
}: TacticalFrameProps) {
const Icon = icon;
return (
<div
className={cn(
"group relative flex min-w-0 flex-col overflow-hidden rounded-none border border-border/70 bg-card transition-colors duration-300 hover:border-foreground/30",
grow && "flex-1",
className,
)}
>
@ -72,9 +62,8 @@ export function TacticalFrame({
aria-hidden="true"
className="relative z-20 flex items-center justify-between gap-2 border-b border-white/15 bg-black/50 px-4 py-1.5 backdrop-blur-sm"
>
<span className="flex items-center gap-1.5 font-mono text-[9px] uppercase tracking-widest text-white/60">
{Icon ? <Icon className="size-3 shrink-0" /> : null}
{classification ? <span className="truncate">{classification}</span> : null}
<span className="truncate font-mono text-[9px] uppercase tracking-widest text-white/60">
{classification}
</span>
{refCode ? (
<span className="shrink-0 font-mono text-[9px] uppercase tracking-widest text-white/60">

View file

@ -35,8 +35,14 @@ export function MissionBriefingSection({ briefing, missionName }: MissionBriefin
}
return (
<div className="flex min-w-0 flex-col gap-3 px-4 py-4">
<div className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<FileTextIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Briefing
</h2>
</div>
<BriefingSqfExport entries={briefing} missionName={missionName} />
</div>
{briefing.map((entry, index) => (

View file

@ -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>
);
}

View file

@ -51,7 +51,13 @@ export function MissionComms({ commsAndDocs }: MissionCommsProps) {
const hasFrequencies = frequencies && frequencies.length > 0;
return (
<div className="flex min-w-0 flex-col gap-3 px-4 py-4">
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<RadioIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Communications
</h2>
</div>
<Item variant="outline">
<ItemContent className="flex flex-col gap-4">
{radioPlan && (

View file

@ -1,5 +1,5 @@
import { ShieldIcon } from "lucide-react";
import type { Faction, Media } from "@/payload-types";
import type { Faction } from "@/payload-types";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
interface FactionEntry {
@ -18,22 +18,6 @@ const threatLevelColors: Record<string, string> = {
hostile: "bg-red-500/20 text-red-400",
};
const FACTION_TYPE_LABELS: Record<string, string> = {
playerFaction: "Player Faction",
majorFaction: "Major Faction",
minorFaction: "Minor Faction",
corporation: "Corporation",
special: "Special",
};
const FACTION_TYPE_COLORS: Record<string, string> = {
playerFaction: "bg-amber-500/20 text-amber-300",
majorFaction: "bg-indigo-500/20 text-indigo-300",
minorFaction: "bg-muted/50 text-muted-foreground",
corporation: "bg-cyan-500/20 text-cyan-300",
special: "bg-violet-500/20 text-violet-300",
};
export function MissionFactions({ factionsInvolved }: MissionFactionsProps) {
if (!factionsInvolved || factionsInvolved.length === 0) {
return (
@ -52,48 +36,32 @@ export function MissionFactions({ factionsInvolved }: MissionFactionsProps) {
}
return (
<div className="flex min-w-0 flex-col gap-3 px-4 py-4">
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<ShieldIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Factions Involved
</h2>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
{factionsInvolved.map((entry, index) => {
const faction = typeof entry.faction === "object" ? entry.faction : null;
const coverImage =
faction && typeof faction.coverImage === "object" && faction.coverImage !== null
? (faction.coverImage as Media)
: null;
const coverUrl = coverImage?.url ?? null;
const factionId = typeof entry.faction === "object" ? entry.faction.id : entry.faction;
return (
<Item key={index} variant="outline" asChild>
<a
href={`/intelligence/factions/${factionId}`}
className="relative overflow-hidden hover:bg-accent/50"
>
{coverUrl && (
<img
src={coverUrl}
alt=""
className="absolute inset-0 z-0 h-full w-full object-cover object-center opacity-15 transition-opacity [a]:hover:opacity-30"
/>
)}
<ItemHeader>
<ItemTitle>{faction?.name ?? `Faction #${entry.faction}`}</ItemTitle>
<span
className={`w-fit self-start text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${threatLevelColors[entry.threatLevel] ?? "bg-muted text-muted-foreground"}`}
>
{entry.threatLevel}
</span>
</ItemHeader>
{faction && (
<ItemContent>
<span
className={`w-fit self-start text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${FACTION_TYPE_COLORS[faction.type] ?? "bg-muted/50 text-muted-foreground"}`}
>
{FACTION_TYPE_LABELS[faction.type] ?? faction.type}
</span>
</ItemContent>
)}
</a>
<Item key={index} variant="outline">
<ItemHeader>
<ItemTitle>{faction?.name ?? `Faction #${entry.faction}`}</ItemTitle>
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded ${threatLevelColors[entry.threatLevel] ?? "bg-muted text-muted-foreground"}`}
>
{entry.threatLevel}
</span>
</ItemHeader>
{faction && (
<ItemContent>
<span className="text-xs text-muted-foreground">{faction.type}</span>
</ItemContent>
)}
</Item>
);
})}

View file

@ -41,7 +41,13 @@ export function MissionLogistics({ logisticsAndSupport }: MissionLogisticsProps)
const hasAssets = assetsAvailable && assetsAvailable.length > 0;
return (
<div className="flex min-w-0 flex-col gap-3 px-4 py-4">
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<TruckIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Logistics &amp; Support
</h2>
</div>
<Item variant="outline">
<ItemContent className="flex flex-col gap-4">
{hasInsertion && (

View file

@ -91,7 +91,13 @@ export function MissionObjectives({
}
return (
<div className="flex min-w-0 flex-col gap-3 px-4 py-4">
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<CrosshairIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Objectives
</h2>
</div>
<div className="border border-border rounded-lg overflow-x-auto">
<table className="w-full text-sm">
<thead>

View file

@ -309,10 +309,18 @@ export function MissionRating({
const notEligible = !state.isEligible;
return (
<section
className="flex min-w-0 flex-col gap-3 px-4 py-4"
>
<Item variant="outline" className="py-4">
<section className="flex flex-col gap-3" aria-labelledby="mission-rating-heading">
<div className="flex items-center gap-2">
<StarIcon className="size-4 text-muted-foreground" />
<h2
id="mission-rating-heading"
className="text-sm font-semibold uppercase tracking-wider text-muted-foreground"
>
Mission Rating
</h2>
</div>
<Item variant="outline">
<ItemHeader>
<ItemTitle>Rate this mission</ItemTitle>
</ItemHeader>
@ -345,7 +353,7 @@ export function MissionRating({
</ItemContent>
</Item>
<Item variant="outline" className="py-4">
<Item variant="outline">
<ItemHeader>
<ItemTitle>Overview</ItemTitle>
</ItemHeader>

View file

@ -2,7 +2,7 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import { UserCheckIcon, UserPlusIcon, UsersIcon, XIcon } from "lucide-react";
import { ClipboardListIcon, UserCheckIcon, UserPlusIcon, UsersIcon, XIcon } from "lucide-react";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
@ -83,6 +83,10 @@ export function MissionRoleSignups({
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ClipboardListIcon className="size-4 text-muted-foreground" />
<ItemTitle>Role Sign-Ups</ItemTitle>
</div>
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
First come, first served
</span>

View file

@ -48,8 +48,12 @@ export function MissionRoles({ roles, notes, maxPlayers }: MissionRolesProps) {
}
return (
<div className="flex min-w-0 flex-col gap-3 px-4 py-4">
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<UsersIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Roles
</h2>
<span className="ml-auto text-xs font-mono text-muted-foreground">
Max Players: <span className="text-foreground font-semibold">{maxPlayers}</span>
</span>

View file

@ -234,30 +234,51 @@ export function MissionThreatAssessment({
missionId,
}: MissionThreatAssessmentProps) {
if (!likelihoods || likelihoods.length === 0) {
return (
<section
aria-label="Threat Assessment"
className="relative overflow-hidden rounded-none bg-card"
>
{/* Placeholder body when no analyst estimate has been entered. */}
<div className="relative z-10 flex min-h-[10rem] flex-col items-center justify-center gap-2 px-6 py-10 text-center">
<BinocularsIcon aria-hidden="true" className="size-6 text-white/20" />
<p className="text-sm font-mono uppercase tracking-widest text-white/40">
Threat assessment unavailable
</p>
<p className="text-xs font-mono uppercase tracking-wider text-white/25">
insufficient intel
</p>
</div>
</section>
);
return null;
}
const refCode = missionId != null ? String(missionId).padStart(3, "0") : null;
return (
<section
aria-label="Threat Assessment"
className="relative overflow-hidden rounded-none bg-card"
className="relative overflow-hidden rounded-none border border-border/70 bg-card"
>
{/* Faint grid texture: constant opacity, never brightens. */}
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[1] opacity-[0.04]"
style={{
backgroundImage:
"linear-gradient(to right, white 1px, transparent 1px), linear-gradient(to bottom, white 1px, transparent 1px)",
backgroundSize: "28px 28px",
}}
/>
{/* Corner brackets. */}
<div aria-hidden="true" className="pointer-events-none absolute inset-2 z-30">
<span className="absolute left-0 top-0 size-3 border-l border-t border-white/25" />
<span className="absolute right-0 top-0 size-3 border-r border-t border-white/25" />
<span className="absolute bottom-0 left-0 size-3 border-b border-l border-white/25" />
<span className="absolute bottom-0 right-0 size-3 border-b border-r border-white/25" />
</div>
{/* Classification strip. */}
<div
aria-hidden="true"
className="relative z-20 flex items-center justify-between border-b border-white/15 bg-black/50 px-5 py-1.5 backdrop-blur-sm"
>
<span className="flex items-center gap-1.5 font-mono text-[9px] uppercase tracking-widest text-white/60">
<RadarIcon className="size-3" />
Threat Assessment // Intel
</span>
{refCode && (
<span className="font-mono text-[9px] uppercase tracking-widest text-white/60">
REF {refCode}
</span>
)}
</div>
{/* Likelihood rows. */}
<table className="relative z-10 w-full border-collapse text-sm">
<caption className="sr-only">

View file

@ -38,10 +38,7 @@ import type { EvaluationMissionOption } from "./evaluation-types";
interface LeadershipEvaluationDialogProps {
readonly username: string;
readonly missions: readonly EvaluationMissionOption[];
/** Undefined for an equal-rank command review (chain link, no rank gap). */
readonly direction: RankDirection | undefined;
/** True when the viewer is this mission's chain supervisor for the subject. */
readonly isCommandReview?: boolean;
readonly direction: RankDirection;
}
function formatMissionDate(value: string): string {
@ -56,15 +53,10 @@ export function LeadershipEvaluationDialog({
username,
missions,
direction,
isCommandReview = false,
}: LeadershipEvaluationDialogProps) {
const router = useRouter();
const isUpward = direction === "upward";
const triggerLabel = isCommandReview
? "Command review"
: isUpward
? "Rate leadership"
: "Rate subordinate";
const triggerLabel = isUpward ? "Rate leadership" : "Rate subordinate";
const [open, setOpen] = useState(false);
const [missionId, setMissionId] = useState("");
const [level, setLevel] = useState<PerformanceLevelId | "">("");
@ -140,11 +132,9 @@ export function LeadershipEvaluationDialog({
<DialogHeader>
<DialogTitle>{triggerLabel}</DialogTitle>
<DialogDescription>
{isCommandReview
? "You were in command of this operator for this mission. Your rating is recorded as a command review."
: isUpward
? "Rate this senior operator for one completed mission you both attended. Your rating is included anonymously in the leadership aggregate."
: "Rate this junior operator for one completed mission you both attended. Your rating is included anonymously in the leadership aggregate. If you are their direct supervisor, it is recorded as a command review instead."}
{isUpward
? "Rate this senior operator for one completed mission you both attended. Your rating is included anonymously in the leadership aggregate."
: "Rate this junior operator for one completed mission you both attended. Your rating is included anonymously in the leadership aggregate. If you are their direct supervisor, it is recorded as a command review instead."}
</DialogDescription>
</DialogHeader>

View file

@ -30,7 +30,6 @@ interface LeadershipEvaluationSectionProps {
readonly latestMissionRows: readonly LatestMissionRow[];
readonly canSubmitEvaluation: boolean;
readonly canViewSubordinate: boolean;
/** Null when there is no strict rank gap; then `eligibleMissions` lists command links only. */
readonly ratingDirection: RankDirection | null;
}
@ -77,12 +76,11 @@ export function LeadershipEvaluationSection({
<CardHeader>
<CardTitle className="flex flex-wrap items-center justify-between gap-3 text-base">
<span>Leadership performance</span>
{canSubmitEvaluation && eligibleMissions.length > 0 && (
{canSubmitEvaluation && ratingDirection && eligibleMissions.length > 0 && (
<LeadershipEvaluationDialog
username={username}
missions={eligibleMissions}
direction={ratingDirection ?? undefined}
isCommandReview={!ratingDirection}
direction={ratingDirection}
/>
)}
</CardTitle>

View file

@ -1,520 +0,0 @@
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,
});
}
}

View file

@ -7,12 +7,6 @@ import {
} from "./levels";
import { missionEndTime } from "@/lib/intelligence/missionLifecycle";
import { getUserRankIndexes, rankDirection, type RankDirection } from "./ranks";
import {
type ChainResolution,
isCommandLink,
isCommandPair,
resolveMissionChain,
} from "@/lib/command-chain";
type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
@ -91,8 +85,6 @@ export async function hasYesAttendance(
export interface EligibilityResult {
eligible: boolean;
/** `command` = chain command link (may be equal rank); `spectrum` = strict rank gap. */
kind?: "command" | "spectrum";
direction?: RankDirection;
reason?: string;
}
@ -145,9 +137,7 @@ export async function evaluateEligibility(
}
const direction = await rankDirection(payload, raterId, rateeId);
const isCommand = await isCommandLink(payload, missionId, raterId, rateeId);
if (!direction && !isCommand) {
if (!direction) {
return {
eligible: false,
reason: "Evaluations require a strict rank difference (rate those above or below you).",
@ -161,10 +151,7 @@ export async function evaluateEligibility(
return { eligible: false, reason: "No attendance recorded for this mission." };
}
if (isCommand) {
return { eligible: true, kind: "command", direction: direction ?? undefined };
}
return { eligible: true, kind: "spectrum", direction: direction! };
return { eligible: true, direction };
}
export interface UpsertEvaluationInput {
@ -360,26 +347,50 @@ async function partitionByDirection(
const indexes = await getUserRankIndexes(payload, [rateeId, ...raters]);
const rateeIndex = indexes.get(rateeId);
if (rateeIndex === undefined) return { spectrum: [], command: [] };
const supervisors = await getDirectSupervisorIds(payload, rateeId, raters);
const spectrum: EvaluationDoc[] = [];
const command: EvaluationDoc[] = [];
const chainByMission = new Map<number, ChainResolution>();
for (const doc of docs) {
let resolved = chainByMission.get(doc.mission);
if (!resolved) {
resolved = await resolveMissionChain(payload, doc.mission);
chainByMission.set(doc.mission, resolved);
}
if (await isCommandPair(payload, resolved, doc.rater, rateeId)) {
command.push(doc);
continue;
}
const raterIndex = indexes.get(doc.rater);
if (raterIndex === undefined || raterIndex === rateeIndex) continue;
spectrum.push(doc);
if (raterIndex > rateeIndex && supervisors.has(doc.rater)) {
command.push(doc);
} else {
spectrum.push(doc);
}
}
return { spectrum, command };
}
/**
* Of the given raters, the ones who lead an assignment the ratee is a member of.
* Assignment leaders are direct supervisors of that assignment's members.
*/
async function getDirectSupervisorIds(
payload: PayloadType,
rateeId: number,
raterIds: number[],
): Promise<Set<number>> {
const candidates = [...new Set(raterIds)].filter((id) => id !== rateeId);
if (candidates.length === 0) return new Set();
const res = await payload.find({
collection: "assignments",
where: {
and: [{ members: { contains: rateeId } }, { leader: { in: candidates } }],
},
limit: 500,
depth: 0,
overrideAccess: true,
});
const leaders = new Set<number>();
for (const doc of res.docs as unknown as Array<{ leader?: number | { id: number } | null }>) {
const leader = doc.leader;
const id = typeof leader === "number" ? leader : leader?.id;
if (typeof id === "number") leaders.add(id);
}
return leaders;
}
/**
* The most recent command review (a direct supervisor's rating) for a ratee,
* reduced to the level definition plus mission and timestamp. Rater identity and

View file

@ -6,21 +6,18 @@ import type { Payload } from "payload";
* Rules (aligned with `evaluateEligibility` in ./index.ts):
* - Participants = users with a "yes" RSVP for the mission (the documented
* participation proxy — same as the profile-page rating dialog).
* - Command links come from the mission's chain (`src/lib/command-chain`). Each
* chain link is reminded in its own direction, including equal-rank links.
* - Strict-rank pairs keep their reminders in both directions for the spectrum:
* the junior is prompted to rate the senior, the senior the junior. A pair
* already covered by a chain link is not reminded twice.
* - Same-rank pairs that are not chain links form no reminders; participants
* without a profile rank are left out; self-pairs are skipped; a user with
* both lists gets one merged DM.
* - Pairing follows rank, not assignments: every pair of participants with a
* strict rank gap is reminded in both directions. The junior is prompted to
* rate the senior (`leader-direct`); the senior is prompted to rate the
* junior (`subordinate`).
* - Same-rank participants and participants without a profile rank form no
* pairs; self-pairs are skipped; a user with both lists gets one merged DM.
*
* This module is payload-only (no Discord imports) so the recipient plan is
* testable independently of the bot service.
*/
import { getUserRankIndexes } from "./ranks";
import { resolveMissionChain } from "@/lib/command-chain";
type PayloadType = Payload;
@ -114,7 +111,7 @@ export async function computeEvaluationReminderPlan(
const b = ranked[j];
const indexA = rankIndexes.get(a)!;
const indexB = rankIndexes.get(b)!;
if (indexA === indexB) continue; // equal ranks: spectrum never; chain handled below
if (indexA === indexB) continue; // equal ranks never rate each other
const junior = indexA < indexB ? a : b;
const senior = indexA < indexB ? b : a;
ensure(junior).rateLeaders.set(senior, junior);
@ -122,19 +119,6 @@ export async function computeEvaluationReminderPlan(
}
}
// Chain command links add equal-rank pairs and re-set strict ones (idempotent).
// Legacy missions (rated before the chain existed) get no extra links: their
// command reviews always had a strict gap, so the strict pairs above cover them.
const resolved = await resolveMissionChain(payload, missionId);
if (resolved.mode !== "legacy") {
for (const link of resolved.links) {
if (!participantIds.includes(link.supervisorId)) continue;
if (!participantIds.includes(link.subordinateId)) continue;
ensure(link.subordinateId).rateLeaders.set(link.supervisorId, link.subordinateId);
ensure(link.supervisorId).rateSubordinates.set(link.subordinateId, link.supervisorId);
}
}
// 4. Resolve user docs (discordId / username / displayName) for everyone in the plan.
const userIds = [...plan.keys()];
const users = await payload.find({

View file

@ -1,6 +1,5 @@
import type { Payload } from "payload";
import { getUserRankIndexes } from "@/lib/evaluations/ranks";
import { resolveMissionChain } from "@/lib/command-chain";
/**
* Mission feedback reminder window: a completed main operation only prompts for
@ -115,9 +114,8 @@ export async function getMissionReminders(
];
const rankIndexes = await getUserRankIndexes(payload, attendeeIds);
const userRankIndex = rankIndexes.get(user.id);
if (userRankIndex === undefined) return [];
// Chain command links (per mission) add supervisors at any rank, including
// equal rank. Strict-rank leaders still apply for the spectrum.
const eligible: Array<{
mission: (typeof missionsRes.docs)[number];
completedAt: string;
@ -126,23 +124,12 @@ export async function getMissionReminders(
for (const { mission, completedAt } of candidates) {
const yesUsers = yesByMission.get(mission.id) ?? new Set<number>();
if (!yesUsers.has(user.id)) continue; // the user must have RSVP'd "yes"
const strictLeaders =
userRankIndex === undefined
? []
: [...yesUsers].filter((id) => {
if (id === user.id) return false;
const index = rankIndexes.get(id);
return index !== undefined && index > userRankIndex;
});
const resolved = await resolveMissionChain(payload, mission.id);
const chainLeaders =
resolved.mode === "legacy"
? []
: resolved.links
.filter((l) => l.subordinateId === user.id && yesUsers.has(l.supervisorId))
.map((l) => l.supervisorId);
const leaders = [...new Set([...strictLeaders, ...chainLeaders])];
if (leaders.length === 0) continue; // at least one rateable co-attendee required
const leaders = [...yesUsers].filter((id) => {
if (id === user.id) return false;
const index = rankIndexes.get(id);
return index !== undefined && index > userRankIndex;
});
if (leaders.length === 0) continue; // at least one higher-ranked co-attendee required
eligible.push({ mission, completedAt, leaderIds: leaders });
}

File diff suppressed because it is too large Load diff

View file

@ -1,49 +0,0 @@
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,7 +155,6 @@ 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 = [
{
@ -936,16 +935,11 @@ 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',
},
{
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'
name: '20261031_090000_add_missions_discord_modlist_buffer_sent_at'
},
];

View file

@ -195,11 +195,6 @@ 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",
@ -760,11 +755,6 @@ 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",
@ -1123,7 +1113,6 @@ export const enum_contribution_entries_type = pgEnum("enum_contribution_entries_
"wiki-page-edit",
"mission-map-marker",
"survey-completion",
"mission-rating-completion",
"journal-publish",
"manual",
]);
@ -1135,8 +1124,13 @@ 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", "missions", "manual"],
["wiki-pages", "mission-map-markers", "form-submissions", "journals", "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",
@ -1225,17 +1219,6 @@ 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",
@ -4024,6 +4007,7 @@ 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 })
@ -4200,25 +4184,6 @@ 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",
{
@ -4435,16 +4400,6 @@ 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,
@ -4709,96 +4664,6 @@ 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",
{
@ -9272,14 +9137,6 @@ 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),
@ -9612,8 +9469,6 @@ 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"),
@ -9745,10 +9600,6 @@ 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),
@ -10036,16 +9887,6 @@ 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],
@ -11623,16 +11464,6 @@ 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 }) => ({
@ -11768,9 +11599,6 @@ 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",
}),
@ -11848,50 +11676,6 @@ 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],
@ -13983,16 +13767,6 @@ 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],
@ -14477,6 +14251,7 @@ 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;
@ -14495,8 +14270,6 @@ 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;
@ -14657,7 +14430,6 @@ 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;
@ -14672,9 +14444,6 @@ 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;
@ -14898,7 +14667,6 @@ 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;
@ -14913,9 +14681,6 @@ 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,7 +104,6 @@ export interface Config {
'mission-role-signups': MissionRoleSignup;
'mission-map-markers': MissionMapMarker;
'mission-ratings': MissionRating;
'mission-command-links': MissionCommandLink;
campaigns: Campaign;
factions: Faction;
technologies: Technology;
@ -220,7 +219,6 @@ 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>;
@ -5015,28 +5013,6 @@ 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".
@ -8047,24 +8023,6 @@ 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.
@ -9338,10 +9296,6 @@ export interface PayloadLockedDocument {
relationTo: 'mission-ratings';
value: number | MissionRating;
} | null)
| ({
relationTo: 'mission-command-links';
value: number | MissionCommandLink;
} | null)
| ({
relationTo: 'campaigns';
value: number | Campaign;
@ -10834,19 +10788,6 @@ 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".
@ -12989,14 +12930,6 @@ 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,7 +20,6 @@ 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";
@ -350,7 +349,6 @@ const collections = [
MissionRoleSignups,
MissionMapMarkers,
MissionRatings,
MissionCommandLinks,
Campaigns,
Factions,
Technologies,
@ -657,10 +655,6 @@ export default buildConfig({
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
key: "generate-mission",
},
{
scriptPath: path.resolve(dirname, "scripts/seedMissionAttendance.ts"),
key: "seed-attendance",
},
{
scriptPath: path.resolve(dirname, "scripts/analyticsRollup.ts"),
key: "analytics-rollup",
@ -748,7 +742,6 @@ 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

@ -1,121 +0,0 @@
import type { SanitizedConfig } from "payload";
import { getPayload } from "payload";
import {
getMissionAttendance,
setMissionAttendance,
type AttendanceResponse,
} from "@/lib/attendance";
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
/**
* Test helper: seeds random attendance for a mission. Picks a random subset of
* users and assigns each a response weighted 75% yes / 15% no / 10% tentative.
*
* Existing attendance for the mission is cleared first so every run produces a
* fresh, predictable sample rather than accumulating stale rows.
*
* Usage:
* bun run payload seed-attendance <missionId> [count]
* <missionId> required — the mission to seed
* [count] optional — how many random users to sample (default 25)
*/
const YES_WEIGHT = 0.75;
const NO_WEIGHT = 0.15;
const DEFAULT_SAMPLE_SIZE = 25;
function drawResponse(): AttendanceResponse {
const roll = Math.random();
if (roll < YES_WEIGHT) return "yes";
if (roll < YES_WEIGHT + NO_WEIGHT) return "no";
return "tentative";
}
function shuffle<T>(items: T[]): T[] {
const result = [...items];
for (let i = result.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
export const script = async (config: SanitizedConfig) => {
const payload = await getPayload({ config });
const log = createBinLogger("seed-attendance", payload.logger);
try {
// Payload's bin runner calls `script(config)` and leaves the CLI args in
// process.argv as [node, bin.js, <bin-key>, ...positionals], so the first
// positional is the bin key and the mission id is the second token.
const tokens = process.argv.slice(2).filter((arg) => !arg.startsWith("-"));
const rawMissionId = tokens[1];
const rawCount = tokens[2];
const missionId = Number(rawMissionId);
if (!rawMissionId || Number.isNaN(missionId)) {
log.error(
"[Seed Attendance] Usage: bun run payload seed-attendance <missionId> [count]",
);
process.exit(1);
}
const mission = await payload
.findByID({ collection: "missions", id: missionId, depth: 0, overrideAccess: true })
.catch(() => null);
if (!mission) {
log.error(`[Seed Attendance] Mission #${missionId} not found.`);
process.exit(1);
}
// Existing attendance for this mission is wiped so re-runs stay idempotent
// in size (fresh random set, never stacking on prior runs).
const cleared = (await payload.delete({
collection: "mission-attendances",
where: { mission: { equals: missionId } },
overrideAccess: true,
})) as unknown as { totalDocs: number; docs: { id: number }[] };
const clearedCount = cleared.totalDocs ?? (cleared.docs?.length ?? 0);
const users = (await payload.find({
collection: "users",
limit: 1000,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: { id: number }[] };
const candidates = shuffle(users.docs);
const sampleSize = Math.min(
rawCount ? Number(rawCount) : DEFAULT_SAMPLE_SIZE,
candidates.length,
);
if (candidates.length === 0) {
log.info("[Seed Attendance] No users found; nothing to seed.");
process.exit(0);
}
let yes = 0;
let no = 0;
let tentative = 0;
for (let i = 0; i < sampleSize; i += 1) {
const userId = candidates[i].id;
const response = drawResponse();
await setMissionAttendance(payload, { missionId, userId, response });
if (response === "yes") yes += 1;
else if (response === "no") no += 1;
else tentative += 1;
}
const summary = await getMissionAttendance(payload, missionId);
log.info(
`[Seed Attendance] Seeded ${sampleSize} attendance record(s) for Mission #${missionId} ` +
`(cleared ${clearedCount} prior). Yes: ${summary.counts.yes}, No: ${summary.counts.no}, ` +
`Tentative: ${summary.counts.tentative}.`,
);
process.exit(0);
} catch (error) {
log.error(
`[Seed Attendance] Fatal: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
);
process.exit(1);
}
};

View file

@ -1,400 +0,0 @@
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);
});
});