diff --git a/src/app/(frontend)/profile/[username]/actions.ts b/src/app/(frontend)/profile/[username]/actions.ts index b4490005..4c19894d 100644 --- a/src/app/(frontend)/profile/[username]/actions.ts +++ b/src/app/(frontend)/profile/[username]/actions.ts @@ -7,6 +7,7 @@ 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, @@ -97,6 +98,17 @@ 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, diff --git a/src/app/(frontend)/profile/[username]/page.tsx b/src/app/(frontend)/profile/[username]/page.tsx index 9065c591..f49df9a3 100644 --- a/src/app/(frontend)/profile/[username]/page.tsx +++ b/src/app/(frontend)/profile/[username]/page.tsx @@ -10,6 +10,7 @@ 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"; @@ -165,6 +166,19 @@ 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 { + 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, @@ -346,9 +360,13 @@ export default async function ProfilePage({ params }: ProfilePageProps) { rankGapPromise, canEditIntelPromise, ]); - // 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 : []; + // 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) + : []; // Seniors may see the subordinate-rating line on their juniors' profiles. const canViewSubordinate = isProfileOwner || isLegacyPrivileged || isSuperuserViewer || rankGap === "downward"; diff --git a/src/components/frontend/profile/LeadershipEvaluationDialog.tsx b/src/components/frontend/profile/LeadershipEvaluationDialog.tsx index 1646cfdc..66c01fdc 100644 --- a/src/components/frontend/profile/LeadershipEvaluationDialog.tsx +++ b/src/components/frontend/profile/LeadershipEvaluationDialog.tsx @@ -38,7 +38,10 @@ import type { EvaluationMissionOption } from "./evaluation-types"; interface LeadershipEvaluationDialogProps { readonly username: string; readonly missions: readonly EvaluationMissionOption[]; - readonly direction: RankDirection; + /** 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; } function formatMissionDate(value: string): string { @@ -53,10 +56,15 @@ export function LeadershipEvaluationDialog({ username, missions, direction, + isCommandReview = false, }: LeadershipEvaluationDialogProps) { const router = useRouter(); const isUpward = direction === "upward"; - const triggerLabel = isUpward ? "Rate leadership" : "Rate subordinate"; + const triggerLabel = isCommandReview + ? "Command review" + : isUpward + ? "Rate leadership" + : "Rate subordinate"; const [open, setOpen] = useState(false); const [missionId, setMissionId] = useState(""); const [level, setLevel] = useState(""); @@ -132,9 +140,11 @@ export function LeadershipEvaluationDialog({ {triggerLabel} - {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."} + {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."} diff --git a/src/components/frontend/profile/LeadershipEvaluationSection.tsx b/src/components/frontend/profile/LeadershipEvaluationSection.tsx index 9aee8369..014ba92e 100644 --- a/src/components/frontend/profile/LeadershipEvaluationSection.tsx +++ b/src/components/frontend/profile/LeadershipEvaluationSection.tsx @@ -30,6 +30,7 @@ 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; } @@ -76,11 +77,12 @@ export function LeadershipEvaluationSection({ Leadership performance - {canSubmitEvaluation && ratingDirection && eligibleMissions.length > 0 && ( + {canSubmitEvaluation && eligibleMissions.length > 0 && ( )} diff --git a/src/lib/evaluations/index.ts b/src/lib/evaluations/index.ts index 53b964f8..cb30cc7d 100644 --- a/src/lib/evaluations/index.ts +++ b/src/lib/evaluations/index.ts @@ -7,6 +7,12 @@ 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>; @@ -85,6 +91,8 @@ 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; } @@ -137,7 +145,9 @@ export async function evaluateEligibility( } const direction = await rankDirection(payload, raterId, rateeId); - if (!direction) { + const isCommand = await isCommandLink(payload, missionId, raterId, rateeId); + + if (!direction && !isCommand) { return { eligible: false, reason: "Evaluations require a strict rank difference (rate those above or below you).", @@ -151,7 +161,10 @@ export async function evaluateEligibility( return { eligible: false, reason: "No attendance recorded for this mission." }; } - return { eligible: true, direction }; + if (isCommand) { + return { eligible: true, kind: "command", direction: direction ?? undefined }; + } + return { eligible: true, kind: "spectrum", direction: direction! }; } export interface UpsertEvaluationInput { @@ -347,50 +360,26 @@ 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(); 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; - if (raterIndex > rateeIndex && supervisors.has(doc.rater)) { - command.push(doc); - } else { - spectrum.push(doc); - } + 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> { - 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(); - 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 diff --git a/src/lib/evaluations/reminders.ts b/src/lib/evaluations/reminders.ts index 488cc631..ce833c48 100644 --- a/src/lib/evaluations/reminders.ts +++ b/src/lib/evaluations/reminders.ts @@ -6,18 +6,21 @@ 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). - * - 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. + * - 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. * * 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; @@ -111,7 +114,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 never rate each other + if (indexA === indexB) continue; // equal ranks: spectrum never; chain handled below const junior = indexA < indexB ? a : b; const senior = indexA < indexB ? b : a; ensure(junior).rateLeaders.set(senior, junior); @@ -119,6 +122,19 @@ 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({