diff --git a/src/collections/users/Evaluations.ts b/src/collections/users/Evaluations.ts index af0a96ea..b8d7cdce 100644 --- a/src/collections/users/Evaluations.ts +++ b/src/collections/users/Evaluations.ts @@ -12,10 +12,10 @@ import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels"; * and `getLatestSubordinateLevel`). * * Eligibility (rank-based, see `evaluateEligibility` in `src/lib/evaluations`): - * a strict rank gap between rater and ratee plus a yes-RSVP from at least one - * of them on the mission. An upward rating (junior rates senior) feeds the - * anonymous leadership aggregate; a downward rating (senior rates junior) is a - * command review. + * a strict rank gap between rater and ratee plus a yes-RSVP from both of them on + * the mission. A rating from the ratee's direct supervisor (the rater leads an + * assignment the ratee is a member of) is a command review. Every other rating + * feeds the anonymous leadership aggregate. * * Privacy model: raw documents are only readable/writable by users holding the * `evaluations:*` permissions (admin/developer via role docs). Normal users never diff --git a/src/components/frontend/profile/LeadershipEvaluationDialog.tsx b/src/components/frontend/profile/LeadershipEvaluationDialog.tsx index 7efd4fa9..1646cfdc 100644 --- a/src/components/frontend/profile/LeadershipEvaluationDialog.tsx +++ b/src/components/frontend/profile/LeadershipEvaluationDialog.tsx @@ -134,7 +134,7 @@ export function LeadershipEvaluationDialog({ {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 recorded as a command review and shown only to operators ranked above them."} + : "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/lib/evaluations/index.ts b/src/lib/evaluations/index.ts index 0a5fd820..53b964f8 100644 --- a/src/lib/evaluations/index.ts +++ b/src/lib/evaluations/index.ts @@ -59,9 +59,8 @@ export function isMissionEvaluable( /** * Documented participation proxy: this codebase has no actual participant list or * mission-leader field on missions. A "yes" RSVP in `mission-attendances` is the - * evidence we treat as "this user took part in the mission". Under the rank-based - * rules at least one side of the pair must have a yes-RSVP for the mission, so - * every rating is anchored to an op one of them actually attended. + * evidence we treat as "this user took part in the mission". Peer evaluations + * require it of both the rater and the ratee. */ export async function hasYesAttendance( payload: PayloadType, @@ -102,8 +101,8 @@ export interface EligibilityResult { * assignment membership plays no role. * - Rater strictly below ratee -> `leader-direct` (upward rating of a senior). * - Rater strictly above ratee -> `subordinate` (downward rating of a junior). - * - At least one of rater/ratee must have a yes-RSVP for the mission, so every - * rating is anchored to an op one of them attended. + * - Both the rater and the ratee must have a yes-RSVP for the mission, so an + * absent player can neither rate nor be rated for that op. */ export async function evaluateEligibility( payload: PayloadType, @@ -146,7 +145,7 @@ export async function evaluateEligibility( } const attended = - (await hasYesAttendance(payload, raterId, missionId)) || + (await hasYesAttendance(payload, raterId, missionId)) && (await hasYesAttendance(payload, rateeId, missionId)); if (!attended) { return { eligible: false, reason: "No attendance recorded for this mission." }; @@ -244,12 +243,12 @@ export interface LeaderMissionAggregate { } /** - * Anonymous aggregate of a ratee's upward evaluations (each from a rater ranked - * strictly below the ratee) for a ratee. The per-level breakdown and average are - * only exposed once at least ANONYMITY_THRESHOLD distinct raters have evaluated, - * where direction is derived from the current ranks rather than a stored kind. - * Below that threshold, `visible` is false and the numbers are null so no rater - * can be identified. No rater identity or comment ever appears in the output. + * Anonymous aggregate of a ratee's spectrum evaluations: every rating except a + * direct supervisor's command review (see partitionByDirection). The per-level + * breakdown and average are only exposed once at least ANONYMITY_THRESHOLD + * distinct raters have evaluated. Below that threshold, `visible` is false and + * the numbers are null so no rater can be identified. No rater identity or + * comment ever appears in the output. */ export async function getLeaderAggregate( payload: PayloadType, @@ -262,18 +261,18 @@ export async function getLeaderAggregate( overrideAccess: true, }); const docs = res.docs as unknown as EvaluationDoc[]; - const { upward } = await partitionByDirection(payload, rateeId, docs); - const totalRaters = new Set(upward.map((d) => d.rater)).size; + const { spectrum } = await partitionByDirection(payload, rateeId, docs); + const totalRaters = new Set(spectrum.map((d) => d.rater)).size; if (totalRaters < ANONYMITY_THRESHOLD) { return { rateeId, totalRaters, visible: false, levels: null, averageScore: null, missions: [] }; } const counts = new Map(); - for (const d of upward) { + for (const d of spectrum) { counts.set(d.level, (counts.get(d.level) ?? 0) + 1); } - const totalDocs = upward.length; + const totalDocs = spectrum.length; const levels = PERFORMANCE_LEVELS.map((l) => { const count = counts.get(l.id) ?? 0; return { @@ -286,15 +285,15 @@ export async function getLeaderAggregate( }; }).filter((l) => l.count > 0); - const averageScore = upward.length + const averageScore = spectrum.length ? Math.round( - (upward.reduce((sum, d) => sum + (getPerformanceLevel(d.level)?.score ?? 0), 0) / - upward.length) * + (spectrum.reduce((sum, d) => sum + (getPerformanceLevel(d.level)?.score ?? 0), 0) / + spectrum.length) * 100, ) / 100 : 0; - const missionIds = [...new Set(upward.map((doc) => doc.mission))]; + const missionIds = [...new Set(spectrum.map((doc) => doc.mission))]; const missionRows = await Promise.all( missionIds.map(async (missionId) => { const missionResult = await payload.findByID({ @@ -303,7 +302,7 @@ export async function getLeaderAggregate( depth: 0, overrideAccess: true, }); - const missionDocs = upward.filter((doc) => doc.mission === missionId); + const missionDocs = spectrum.filter((doc) => doc.mission === missionId); const missionRaters = new Set(missionDocs.map((doc) => doc.rater)).size; const missionScore = missionDocs.reduce( (sum, doc) => sum + (getPerformanceLevel(doc.level)?.score ?? 0), @@ -332,40 +331,71 @@ export async function getLeaderAggregate( } /** - * Split a ratee's evaluations into the two read models purely by current rank - * direction, since the stored `kind` was removed. `upward` ratings (rater - * strictly junior to the ratee) feed the anonymous leadership aggregate; - * `downward` ratings (rater strictly senior) are command reviews. Ratings where - * the two ranks are equal or unresolvable appear in neither bucket. + * Split a ratee's evaluations into the two read models. A rating from a direct + * supervisor (the rater leads an assignment the ratee is a member of, and ranks + * strictly above the ratee) is the command review. Every other rating with a + * resolvable rank that differs from the ratee's feeds the anonymous leadership + * aggregate, whether from a subordinate, another superior, or a superior's + * superior. Ratings with equal or unresolvable ranks appear in neither bucket. */ async function partitionByDirection( payload: PayloadType, rateeId: number, docs: EvaluationDoc[], -): Promise<{ upward: EvaluationDoc[]; downward: EvaluationDoc[] }> { +): Promise<{ spectrum: EvaluationDoc[]; command: EvaluationDoc[] }> { const raters = docs.map((d) => d.rater); const indexes = await getUserRankIndexes(payload, [rateeId, ...raters]); const rateeIndex = indexes.get(rateeId); - if (rateeIndex === undefined) return { upward: [], downward: [] }; - const upward: EvaluationDoc[] = []; - const downward: EvaluationDoc[] = []; + if (rateeIndex === undefined) return { spectrum: [], command: [] }; + const supervisors = await getDirectSupervisorIds(payload, rateeId, raters); + const spectrum: EvaluationDoc[] = []; + const command: EvaluationDoc[] = []; for (const doc of docs) { const raterIndex = indexes.get(doc.rater); - if (raterIndex === undefined) continue; - if (raterIndex < rateeIndex) { - upward.push(doc); - } else if (raterIndex > rateeIndex) { - downward.push(doc); + if (raterIndex === undefined || raterIndex === rateeIndex) continue; + if (raterIndex > rateeIndex && supervisors.has(doc.rater)) { + command.push(doc); + } else { + spectrum.push(doc); } } - return { upward, downward }; + return { spectrum, command }; } /** - * The most recent downward evaluation (a senior rating a junior) for a ratee, + * 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 - * comment are private and intentionally absent from this output. Direction is - * derived from the current ranks, so no `kind` is stored or read. + * comment are private and intentionally absent from this output. Direction and + * supervision are derived from current ranks and assignments; nothing is stored. */ export async function getLatestSubordinateLevel( payload: PayloadType, @@ -379,8 +409,8 @@ export async function getLatestSubordinateLevel( overrideAccess: true, }); const docs = res.docs as unknown as EvaluationDoc[]; - const { downward } = await partitionByDirection(payload, rateeId, docs); - const doc = downward[0]; + const { command } = await partitionByDirection(payload, rateeId, docs); + const doc = command[0]; if (!doc) return null; const level = getPerformanceLevel(doc.level); if (!level) return null; diff --git a/tests/int/evaluations.int.spec.ts b/tests/int/evaluations.int.spec.ts index 3abf0ef4..1044760b 100644 --- a/tests/int/evaluations.int.spec.ts +++ b/tests/int/evaluations.int.spec.ts @@ -35,6 +35,7 @@ describe("Leadership evaluations", () => { const userIds: number[] = []; const rankIds: number[] = []; + const assignmentIds: number[] = []; const attendanceIds: number[] = []; const evaluationIds: number[] = []; @@ -201,10 +202,22 @@ describe("Leadership evaluations", () => { const missionFuture = await makeMission("future-scheduled", "Scheduled", future); missionFutureId = missionFuture.id; - // Participation proxy: yes-RSVPs for B, C, E. F and D deliberately have none. + // Participation proxy: yes-RSVPs for A (leader), B, C, E. D and F deliberately have none. + await rsvp(leaderA, missionCompletedId); await rsvp(subordinateB, missionCompletedId); await rsvp(participantC, missionCompletedId); await rsvp(participantE, missionCompletedId); + + // Reporting line: leaderA leads Aviation; subordinateB is a member. leaderA is + // therefore B's direct supervisor. participantC ranks above B but does not lead + // any assignment B belongs to, so C is a non-direct superior. + const aviation = await payload.create({ + collection: "assignments", + data: { name: "Aviation", type: "squad", leader: leaderA.id, members: [subordinateB.id] }, + overrideAccess: true, + depth: 0, + }); + assignmentIds.push(aviation.id); }); afterAll(async () => { @@ -224,6 +237,9 @@ describe("Leadership evaluations", () => { } evaluationIds.length = 0; + for (const id of assignmentIds) { + await payload.delete({ collection: "assignments", id, overrideAccess: true }).catch(() => {}); + } for (const id of attendanceIds) { await payload .delete({ collection: "mission-attendances", id, overrideAccess: true }) @@ -296,16 +312,14 @@ describe("Leadership evaluations", () => { expect(isMissionEvaluable("Active", justStarted, 240)).toBe(false); }); - it("derives the evaluation direction from rank relation and shared attendance", async () => { + it("derives the evaluation direction from rank relation when both players attended", async () => { const cases = [ - // Junior rates a senior (rater attended) -> upward leader rating. + // Junior rates a senior (both attended) -> upward leader rating. { input: { raterId: subordinateB.id, rateeId: leaderA.id }, expectDirection: "upward" }, - // Mid rates the senior (rater attended) -> also upward, no assignment needed. + // Mid rates the senior (both attended) -> also upward, no assignment needed. { input: { raterId: participantC.id, rateeId: leaderA.id }, expectDirection: "upward" }, // Senior rates a junior -> downward subordinate rating. { input: { raterId: leaderA.id, rateeId: subordinateB.id }, expectDirection: "downward" }, - // F never RSVPed, but E did: one side attending anchors the mission. - { input: { raterId: noRsvpF.id, rateeId: participantE.id }, expectDirection: "upward" }, ]; for (const { input, expectDirection } of cases) { const result = await evaluateEligibility(payload, { ...input, missionId: missionCompletedId }); @@ -313,6 +327,24 @@ describe("Leadership evaluations", () => { expect(result.direction).toBe(expectDirection); } + // An attendee cannot rate an absent player, even with a strict rank gap. + const absentRatee = await evaluateEligibility(payload, { + raterId: participantE.id, + rateeId: noRsvpF.id, + missionId: missionCompletedId, + }); + expect(absentRatee.eligible).toBe(false); + expect(absentRatee.reason).toBe("No attendance recorded for this mission."); + + // An absent player cannot rate an attendee either. + const absentRater = await evaluateEligibility(payload, { + raterId: noRsvpF.id, + rateeId: participantE.id, + missionId: missionCompletedId, + }); + expect(absentRater.eligible).toBe(false); + expect(absentRater.reason).toBe("No attendance recorded for this mission."); + // Equal ranks can never rate each other, even with both on the roster. const peer = await evaluateEligibility(payload, { raterId: participantE.id, @@ -467,6 +499,25 @@ describe("Leadership evaluations", () => { expect(none).toBeNull(); }); + it("routes a non-direct superior's rating to the spectrum, not the command review", async () => { + // participantC ranks above subordinateB but does not lead B's assignment. + const c = await upsertEvaluation(payload, { + raterId: participantC.id, + rateeId: subordinateB.id, + missionId: missionCompletedId, + level: "under-review", + }); + evaluationIds.push(c.evaluation.id); + + // It is newer than leaderA's review, yet the command review is still leaderA's. + const latest = await getLatestSubordinateLevel(payload, subordinateB.id); + expect(latest?.level.id).toBe("excellent"); + + // It counts toward B's spectrum as a distinct rater. + const spectrum = await getLeaderAggregate(payload, subordinateB.id); + expect(spectrum.totalRaters).toBe(1); + }); + it("hides raw evaluation documents from users without the permission", async () => { // Local ops bypass access control unless overrideAccess: false — this flag // makes findOperation run the same requirePermission("evaluations:read")