1
0
Fork 0

fix(evaluations): require attendance from both players and route direct-supervisor reviews

- peer eligibility now requires a yes-RSVP from both rater and ratee, so
  absent players can neither rate nor be rated for that op
- a rating from the ratee's direct supervisor (rater leads an assignment the
  ratee is a member of and ranks above them) is the command review; every
  other rating feeds the anonymous leadership spectrum
- dialog copy and collection docs updated to match; tests cover both rules
This commit is contained in:
Jason Fraley 2026-11-01 15:51:45 -05:00
parent 21cced3ad9
commit e64c477250
4 changed files with 133 additions and 52 deletions

View file

@ -12,10 +12,10 @@ import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels";
* and `getLatestSubordinateLevel`). * and `getLatestSubordinateLevel`).
* *
* Eligibility (rank-based, see `evaluateEligibility` in `src/lib/evaluations`): * 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 * a strict rank gap between rater and ratee plus a yes-RSVP from both of them on
* of them on the mission. An upward rating (junior rates senior) feeds the * the mission. A rating from the ratee's direct supervisor (the rater leads an
* anonymous leadership aggregate; a downward rating (senior rates junior) is a * assignment the ratee is a member of) is a command review. Every other rating
* command review. * feeds the anonymous leadership aggregate.
* *
* Privacy model: raw documents are only readable/writable by users holding the * Privacy model: raw documents are only readable/writable by users holding the
* `evaluations:*` permissions (admin/developer via role docs). Normal users never * `evaluations:*` permissions (admin/developer via role docs). Normal users never

View file

@ -134,7 +134,7 @@ export function LeadershipEvaluationDialog({
<DialogDescription> <DialogDescription>
{isUpward {isUpward
? "Rate this senior operator for one completed mission you both attended. Your rating is included anonymously in the leadership aggregate." ? "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."}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>

View file

@ -59,9 +59,8 @@ export function isMissionEvaluable(
/** /**
* Documented participation proxy: this codebase has no actual participant list or * Documented participation proxy: this codebase has no actual participant list or
* mission-leader field on missions. A "yes" RSVP in `mission-attendances` is the * 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 * evidence we treat as "this user took part in the mission". Peer evaluations
* rules at least one side of the pair must have a yes-RSVP for the mission, so * require it of both the rater and the ratee.
* every rating is anchored to an op one of them actually attended.
*/ */
export async function hasYesAttendance( export async function hasYesAttendance(
payload: PayloadType, payload: PayloadType,
@ -102,8 +101,8 @@ export interface EligibilityResult {
* assignment membership plays no role. * assignment membership plays no role.
* - Rater strictly below ratee -> `leader-direct` (upward rating of a senior). * - Rater strictly below ratee -> `leader-direct` (upward rating of a senior).
* - Rater strictly above ratee -> `subordinate` (downward rating of a junior). * - 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 * - Both the rater and the ratee must have a yes-RSVP for the mission, so an
* rating is anchored to an op one of them attended. * absent player can neither rate nor be rated for that op.
*/ */
export async function evaluateEligibility( export async function evaluateEligibility(
payload: PayloadType, payload: PayloadType,
@ -146,7 +145,7 @@ export async function evaluateEligibility(
} }
const attended = const attended =
(await hasYesAttendance(payload, raterId, missionId)) || (await hasYesAttendance(payload, raterId, missionId)) &&
(await hasYesAttendance(payload, rateeId, missionId)); (await hasYesAttendance(payload, rateeId, missionId));
if (!attended) { if (!attended) {
return { eligible: false, reason: "No attendance recorded for this mission." }; 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 * Anonymous aggregate of a ratee's spectrum evaluations: every rating except a
* strictly below the ratee) for a ratee. The per-level breakdown and average are * direct supervisor's command review (see partitionByDirection). The per-level
* only exposed once at least ANONYMITY_THRESHOLD distinct raters have evaluated, * breakdown and average are only exposed once at least ANONYMITY_THRESHOLD
* where direction is derived from the current ranks rather than a stored kind. * distinct raters have evaluated. Below that threshold, `visible` is false and
* Below that threshold, `visible` is false and the numbers are null so no rater * the numbers are null so no rater can be identified. No rater identity or
* can be identified. No rater identity or comment ever appears in the output. * comment ever appears in the output.
*/ */
export async function getLeaderAggregate( export async function getLeaderAggregate(
payload: PayloadType, payload: PayloadType,
@ -262,18 +261,18 @@ export async function getLeaderAggregate(
overrideAccess: true, overrideAccess: true,
}); });
const docs = res.docs as unknown as EvaluationDoc[]; const docs = res.docs as unknown as EvaluationDoc[];
const { upward } = await partitionByDirection(payload, rateeId, docs); const { spectrum } = await partitionByDirection(payload, rateeId, docs);
const totalRaters = new Set(upward.map((d) => d.rater)).size; const totalRaters = new Set(spectrum.map((d) => d.rater)).size;
if (totalRaters < ANONYMITY_THRESHOLD) { if (totalRaters < ANONYMITY_THRESHOLD) {
return { rateeId, totalRaters, visible: false, levels: null, averageScore: null, missions: [] }; return { rateeId, totalRaters, visible: false, levels: null, averageScore: null, missions: [] };
} }
const counts = new Map<string, number>(); const counts = new Map<string, number>();
for (const d of upward) { for (const d of spectrum) {
counts.set(d.level, (counts.get(d.level) ?? 0) + 1); 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 levels = PERFORMANCE_LEVELS.map((l) => {
const count = counts.get(l.id) ?? 0; const count = counts.get(l.id) ?? 0;
return { return {
@ -286,15 +285,15 @@ export async function getLeaderAggregate(
}; };
}).filter((l) => l.count > 0); }).filter((l) => l.count > 0);
const averageScore = upward.length const averageScore = spectrum.length
? Math.round( ? Math.round(
(upward.reduce((sum, d) => sum + (getPerformanceLevel(d.level)?.score ?? 0), 0) / (spectrum.reduce((sum, d) => sum + (getPerformanceLevel(d.level)?.score ?? 0), 0) /
upward.length) * spectrum.length) *
100, 100,
) / 100 ) / 100
: 0; : 0;
const missionIds = [...new Set(upward.map((doc) => doc.mission))]; const missionIds = [...new Set(spectrum.map((doc) => doc.mission))];
const missionRows = await Promise.all( const missionRows = await Promise.all(
missionIds.map(async (missionId) => { missionIds.map(async (missionId) => {
const missionResult = await payload.findByID({ const missionResult = await payload.findByID({
@ -303,7 +302,7 @@ export async function getLeaderAggregate(
depth: 0, depth: 0,
overrideAccess: true, 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 missionRaters = new Set(missionDocs.map((doc) => doc.rater)).size;
const missionScore = missionDocs.reduce( const missionScore = missionDocs.reduce(
(sum, doc) => sum + (getPerformanceLevel(doc.level)?.score ?? 0), (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 * Split a ratee's evaluations into the two read models. A rating from a direct
* direction, since the stored `kind` was removed. `upward` ratings (rater * supervisor (the rater leads an assignment the ratee is a member of, and ranks
* strictly junior to the ratee) feed the anonymous leadership aggregate; * strictly above the ratee) is the command review. Every other rating with a
* `downward` ratings (rater strictly senior) are command reviews. Ratings where * resolvable rank that differs from the ratee's feeds the anonymous leadership
* the two ranks are equal or unresolvable appear in neither bucket. * 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( async function partitionByDirection(
payload: PayloadType, payload: PayloadType,
rateeId: number, rateeId: number,
docs: EvaluationDoc[], docs: EvaluationDoc[],
): Promise<{ upward: EvaluationDoc[]; downward: EvaluationDoc[] }> { ): Promise<{ spectrum: EvaluationDoc[]; command: EvaluationDoc[] }> {
const raters = docs.map((d) => d.rater); const raters = docs.map((d) => d.rater);
const indexes = await getUserRankIndexes(payload, [rateeId, ...raters]); const indexes = await getUserRankIndexes(payload, [rateeId, ...raters]);
const rateeIndex = indexes.get(rateeId); const rateeIndex = indexes.get(rateeId);
if (rateeIndex === undefined) return { upward: [], downward: [] }; if (rateeIndex === undefined) return { spectrum: [], command: [] };
const upward: EvaluationDoc[] = []; const supervisors = await getDirectSupervisorIds(payload, rateeId, raters);
const downward: EvaluationDoc[] = []; const spectrum: EvaluationDoc[] = [];
const command: EvaluationDoc[] = [];
for (const doc of docs) { for (const doc of docs) {
const raterIndex = indexes.get(doc.rater); const raterIndex = indexes.get(doc.rater);
if (raterIndex === undefined) continue; if (raterIndex === undefined || raterIndex === rateeIndex) continue;
if (raterIndex < rateeIndex) { if (raterIndex > rateeIndex && supervisors.has(doc.rater)) {
upward.push(doc); command.push(doc);
} else if (raterIndex > rateeIndex) { } else {
downward.push(doc); 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<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 * reduced to the level definition plus mission and timestamp. Rater identity and
* comment are private and intentionally absent from this output. Direction is * comment are private and intentionally absent from this output. Direction and
* derived from the current ranks, so no `kind` is stored or read. * supervision are derived from current ranks and assignments; nothing is stored.
*/ */
export async function getLatestSubordinateLevel( export async function getLatestSubordinateLevel(
payload: PayloadType, payload: PayloadType,
@ -379,8 +409,8 @@ export async function getLatestSubordinateLevel(
overrideAccess: true, overrideAccess: true,
}); });
const docs = res.docs as unknown as EvaluationDoc[]; const docs = res.docs as unknown as EvaluationDoc[];
const { downward } = await partitionByDirection(payload, rateeId, docs); const { command } = await partitionByDirection(payload, rateeId, docs);
const doc = downward[0]; const doc = command[0];
if (!doc) return null; if (!doc) return null;
const level = getPerformanceLevel(doc.level); const level = getPerformanceLevel(doc.level);
if (!level) return null; if (!level) return null;

View file

@ -35,6 +35,7 @@ describe("Leadership evaluations", () => {
const userIds: number[] = []; const userIds: number[] = [];
const rankIds: number[] = []; const rankIds: number[] = [];
const assignmentIds: number[] = [];
const attendanceIds: number[] = []; const attendanceIds: number[] = [];
const evaluationIds: number[] = []; const evaluationIds: number[] = [];
@ -201,10 +202,22 @@ describe("Leadership evaluations", () => {
const missionFuture = await makeMission("future-scheduled", "Scheduled", future); const missionFuture = await makeMission("future-scheduled", "Scheduled", future);
missionFutureId = missionFuture.id; 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(subordinateB, missionCompletedId);
await rsvp(participantC, missionCompletedId); await rsvp(participantC, missionCompletedId);
await rsvp(participantE, 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 () => { afterAll(async () => {
@ -224,6 +237,9 @@ describe("Leadership evaluations", () => {
} }
evaluationIds.length = 0; evaluationIds.length = 0;
for (const id of assignmentIds) {
await payload.delete({ collection: "assignments", id, overrideAccess: true }).catch(() => {});
}
for (const id of attendanceIds) { for (const id of attendanceIds) {
await payload await payload
.delete({ collection: "mission-attendances", id, overrideAccess: true }) .delete({ collection: "mission-attendances", id, overrideAccess: true })
@ -296,16 +312,14 @@ describe("Leadership evaluations", () => {
expect(isMissionEvaluable("Active", justStarted, 240)).toBe(false); 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 = [ 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" }, { 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" }, { input: { raterId: participantC.id, rateeId: leaderA.id }, expectDirection: "upward" },
// Senior rates a junior -> downward subordinate rating. // Senior rates a junior -> downward subordinate rating.
{ input: { raterId: leaderA.id, rateeId: subordinateB.id }, expectDirection: "downward" }, { 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) { for (const { input, expectDirection } of cases) {
const result = await evaluateEligibility(payload, { ...input, missionId: missionCompletedId }); const result = await evaluateEligibility(payload, { ...input, missionId: missionCompletedId });
@ -313,6 +327,24 @@ describe("Leadership evaluations", () => {
expect(result.direction).toBe(expectDirection); 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. // Equal ranks can never rate each other, even with both on the roster.
const peer = await evaluateEligibility(payload, { const peer = await evaluateEligibility(payload, {
raterId: participantE.id, raterId: participantE.id,
@ -467,6 +499,25 @@ describe("Leadership evaluations", () => {
expect(none).toBeNull(); 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 () => { it("hides raw evaluation documents from users without the permission", async () => {
// Local ops bypass access control unless overrideAccess: false — this flag // Local ops bypass access control unless overrideAccess: false — this flag
// makes findOperation run the same requirePermission("evaluations:read") // makes findOperation run the same requirePermission("evaluations:read")