1
0
Fork 0

refactor(evaluations): drop stored kind, derive rating direction from ranks

This commit is contained in:
Jason Fraley 2026-10-31 03:26:51 -04:00
parent fee3377474
commit 66666547ad
9 changed files with 45237 additions and 99 deletions

View file

@ -64,10 +64,11 @@ async function findUserByUsername(
}
/**
* Submit (or re-submit) a leadership evaluation for the given profile. The kind
* is derived server-side from the rater/ratee rank relationship and attendance;
* it is never accepted from the client. Eligibility is the permission gate here;
* any logged-in user with a strict rank difference may evaluate.
* Submit (or re-submit) a performance review for the given profile. The rating
* is stored generically — no `kind` — and the upward/downward read models are
* derived at read time from the rater/ratee rank relationship. Eligibility is the
* permission gate here; any logged-in user with a strict rank difference may
* evaluate. The direction is derived server-side and never accepted from the client.
*/
export async function submitEvaluation(input: {
username: string;
@ -92,7 +93,7 @@ export async function submitEvaluation(input: {
rateeId: ratee.id,
missionId: input.missionId,
});
if (!eligibility.eligible || !eligibility.kind) {
if (!eligibility.eligible) {
return { success: false, error: eligibility.reason ?? "Not eligible to evaluate." };
}
@ -100,7 +101,6 @@ export async function submitEvaluation(input: {
raterId: user.id as number,
rateeId: ratee.id,
missionId: input.missionId,
kind: eligibility.kind,
level: input.level,
comment: input.comment,
});
@ -109,10 +109,10 @@ export async function submitEvaluation(input: {
// must not leak who rated whom.
await emitGameEvent(payload, {
type: EventTypes.EvaluationSubmit,
message: "A leadership evaluation was submitted.",
message: "A performance review was submitted.",
targetCollection: "evaluations",
targetId: evaluation.id,
data: { kind: eligibility.kind },
data: { direction: eligibility.direction },
});
return { success: true, data: { created } };

View file

@ -3,18 +3,19 @@ import { requirePermission } from "@/utils/access-control/hasPermission";
import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels";
/**
* Leadership evaluations.
* Performance reviews (a.k.a. leadership evaluations).
*
* One row per (rater, ratee, mission, kind) — the uniqueness is enforced by the
* One row per (rater, ratee, mission) — the uniqueness is enforced by the
* service layer (`upsertEvaluation` in `src/lib/evaluations`), not by a DB
* constraint.
* constraint. There is no stored "kind": the upward/downward split is derived
* at read time from the rater/ratee rank relationship (see `getLeaderAggregate`
* 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. Upward ratings (junior rates senior) are stored as
* `leader-direct`; downward ratings (senior rates junior) as `subordinate`.
* `leader-indirect` only exists on legacy rows written while eligibility was
* assignment-based.
* 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.
*
* Privacy model: raw documents are only readable/writable by users holding the
* `evaluations:*` permissions (admin/developer via role docs). Normal users never
@ -27,7 +28,7 @@ export const Evaluations: CollectionConfig = {
slug: "evaluations",
admin: {
group: "Users",
defaultColumns: ["ratee", "rater", "mission", "kind", "level"],
defaultColumns: ["ratee", "rater", "mission", "level"],
},
access: {
read: requirePermission("evaluations:read"),
@ -58,25 +59,6 @@ export const Evaluations: CollectionConfig = {
relationTo: "missions",
required: true,
},
{
name: "kind",
type: "select",
options: [
{
label: "Leader (junior rates senior)",
value: "leader-direct",
},
{
label: "Leader (legacy indirect)",
value: "leader-indirect",
},
{
label: "Subordinate (senior rates junior)",
value: "subordinate",
},
],
required: true,
},
{
name: "level",
type: "select",

View file

@ -6,27 +6,20 @@ import {
type PerformanceLevelId,
} from "./levels";
import { missionEndTime } from "@/lib/intelligence/missionLifecycle";
import { rankDirection } from "./ranks";
import { getUserRankIndexes, rankDirection, type RankDirection } from "./ranks";
type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
/**
* The evaluation kinds. Since the rank-based rework only two kinds are ever
* written: `leader-direct` for an upward rating (junior rates senior, feeds
* the leader aggregate) and `subordinate` for a downward rating (senior rates
* junior). `leader-indirect` is legacy: rows written while eligibility was
* assignment-based keep it so their aggregates stay intact, but nothing new
* produces it.
* Shape of an evaluations doc as consumed by this service (depth 0). There is no
* `kind` field: the upward/downward split is derived from ranks at read time, so
* the same stored row is bucketed differently as ranks change.
*/
export type EvaluationKind = "leader-direct" | "leader-indirect" | "subordinate";
/** Shape of an evaluations doc as consumed by this service (depth 0). */
export interface EvaluationDoc {
id: number;
rater: number;
ratee: number;
mission: number;
kind: EvaluationKind;
level: PerformanceLevelId;
comment: string | null;
createdAt: string;
@ -93,7 +86,7 @@ export async function hasYesAttendance(
export interface EligibilityResult {
eligible: boolean;
kind?: EvaluationKind;
direction?: RankDirection;
reason?: string;
}
@ -159,22 +152,21 @@ export async function evaluateEligibility(
return { eligible: false, reason: "No attendance recorded for this mission." };
}
return { eligible: true, kind: direction === "upward" ? "leader-direct" : "subordinate" };
return { eligible: true, direction };
}
export interface UpsertEvaluationInput {
raterId: number;
rateeId: number;
missionId: number;
kind: EvaluationKind;
level: PerformanceLevelId;
comment?: string;
}
/**
* One row per (rater, ratee, mission, kind). An existing evaluation for that tuple
* is updated in place; otherwise a new one is created. Enforced here in the service
* layer — there is deliberately no DB constraint to hand-maintain.
* One row per (rater, ratee, mission). An existing evaluation for that tuple
* is updated in place; otherwise a new one is created. Enforced here in the
* service layer — there is deliberately no DB constraint to hand-maintain.
*/
export async function upsertEvaluation(
payload: PayloadType,
@ -191,7 +183,6 @@ export async function upsertEvaluation(
{ rater: { equals: input.raterId } },
{ ratee: { equals: input.rateeId } },
{ mission: { equals: input.missionId } },
{ kind: { equals: input.kind } },
],
},
limit: 1,
@ -216,7 +207,6 @@ export async function upsertEvaluation(
rater: input.raterId,
ratee: input.rateeId,
mission: input.missionId,
kind: input.kind,
level: input.level,
comment: input.comment ?? null,
},
@ -228,7 +218,7 @@ export async function upsertEvaluation(
export interface LeaderEvaluationAggregate {
rateeId: number;
/** Distinct raters across all leader-kind evaluations. */
/** Distinct raters across this ratee's upward (junior-rating-senior) evaluations. */
totalRaters: number;
/** False while raters are below ANONYMITY_THRESHOLD — breakdown withheld. */
visible: boolean;
@ -254,11 +244,12 @@ export interface LeaderMissionAggregate {
}
/**
* Anonymous aggregate of leader-kind evaluations (direct + indirect) for a ratee.
* The per-level breakdown and average are only exposed once at least
* ANONYMITY_THRESHOLD distinct raters have evaluated — below that, `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 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.
*/
export async function getLeaderAggregate(
payload: PayloadType,
@ -266,24 +257,23 @@ export async function getLeaderAggregate(
): Promise<LeaderEvaluationAggregate> {
const res = await payload.find({
collection: "evaluations",
where: {
and: [{ ratee: { equals: rateeId } }, { kind: { in: ["leader-direct", "leader-indirect"] } }],
},
where: { ratee: { equals: rateeId } },
depth: 0,
overrideAccess: true,
});
const docs = res.docs as unknown as EvaluationDoc[];
const totalRaters = new Set(docs.map((d) => d.rater)).size;
const { upward } = await partitionByDirection(payload, rateeId, docs);
const totalRaters = new Set(upward.map((d) => d.rater)).size;
if (totalRaters < ANONYMITY_THRESHOLD) {
return { rateeId, totalRaters, visible: false, levels: null, averageScore: null, missions: [] };
}
const counts = new Map<string, number>();
for (const d of docs) {
for (const d of upward) {
counts.set(d.level, (counts.get(d.level) ?? 0) + 1);
}
const totalDocs = docs.length;
const totalDocs = upward.length;
const levels = PERFORMANCE_LEVELS.map((l) => {
const count = counts.get(l.id) ?? 0;
return {
@ -296,15 +286,15 @@ export async function getLeaderAggregate(
};
}).filter((l) => l.count > 0);
const averageScore = totalDocs
const averageScore = upward.length
? Math.round(
(docs.reduce((sum, d) => sum + (getPerformanceLevel(d.level)?.score ?? 0), 0) /
totalDocs) *
(upward.reduce((sum, d) => sum + (getPerformanceLevel(d.level)?.score ?? 0), 0) /
upward.length) *
100,
) / 100
: 0;
const missionIds = [...new Set(docs.map((doc) => doc.mission))];
const missionIds = [...new Set(upward.map((doc) => doc.mission))];
const missionRows = await Promise.all(
missionIds.map(async (missionId) => {
const missionResult = await payload.findByID({
@ -313,7 +303,7 @@ export async function getLeaderAggregate(
depth: 0,
overrideAccess: true,
});
const missionDocs = docs.filter((doc) => doc.mission === missionId);
const missionDocs = upward.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),
@ -342,9 +332,40 @@ export async function getLeaderAggregate(
}
/**
* The most recent subordinate-kind evaluation for a ratee, reduced to the level
* definition plus mission and timestamp. Rater identity and comment are private
* and intentionally absent from this output.
* 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.
*/
async function partitionByDirection(
payload: PayloadType,
rateeId: number,
docs: EvaluationDoc[],
): Promise<{ upward: EvaluationDoc[]; downward: 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[] = [];
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);
}
}
return { upward, downward };
}
/**
* The most recent downward evaluation (a senior rating a junior) 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.
*/
export async function getLatestSubordinateLevel(
payload: PayloadType,
@ -352,15 +373,14 @@ export async function getLatestSubordinateLevel(
): Promise<{ level: PerformanceLevel; missionId: number; at: string } | null> {
const res = await payload.find({
collection: "evaluations",
where: {
and: [{ ratee: { equals: rateeId } }, { kind: { equals: "subordinate" } }],
},
where: { ratee: { equals: rateeId } },
sort: "-updatedAt",
limit: 1,
depth: 0,
overrideAccess: true,
});
const doc = res.docs[0] as unknown as EvaluationDoc | undefined;
const docs = res.docs as unknown as EvaluationDoc[];
const { downward } = await partitionByDirection(payload, rateeId, docs);
const doc = downward[0];
if (!doc) return null;
const level = getPerformanceLevel(doc.level);
if (!level) return null;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,13 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "evaluations" DROP COLUMN "kind";
DROP TYPE "public"."enum_evaluations_kind";`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_evaluations_kind" AS ENUM('leader-direct', 'leader-indirect', 'subordinate');
ALTER TABLE "evaluations" ADD COLUMN "kind" "enum_evaluations_kind" NOT NULL;`)
}

View file

@ -151,6 +151,7 @@ import * as migration_20261022_170228_add_vehicle_mod_field from './20261022_170
import * as migration_20261026_073228_add_vehicle_category_static_and_drone from './20261026_073228_add_vehicle_category_static_and_drone';
import * as migration_20261026_195910_add_vehicle_disallowed_cargo_field from './20261026_195910_add_vehicle_disallowed_cargo_field';
import * as migration_20261026_205453_add_operation_effects_pending_action_and_decisions from './20261026_205453_add_operation_effects_pending_action_and_decisions';
import * as migration_20261031_064618_drop_evaluation_kind from './20261031_064618_drop_evaluation_kind';
export const migrations = [
{
@ -916,6 +917,11 @@ export const migrations = [
{
up: migration_20261026_205453_add_operation_effects_pending_action_and_decisions.up,
down: migration_20261026_205453_add_operation_effects_pending_action_and_decisions.down,
name: '20261026_205453_add_operation_effects_pending_action_and_decisions'
name: '20261026_205453_add_operation_effects_pending_action_and_decisions',
},
{
up: migration_20261031_064618_drop_evaluation_kind.up,
down: migration_20261031_064618_drop_evaluation_kind.down,
name: '20261031_064618_drop_evaluation_kind'
},
];

View file

@ -4710,7 +4710,6 @@ export interface Evaluation {
rater: number | User;
ratee: number | User;
mission: number | Mission;
kind: 'leader-direct' | 'leader-indirect' | 'subordinate';
level: 'exceptional' | 'excellent' | 'proficient' | 'adequate' | 'moderate' | 'under-review';
/**
* Private free-text note. Never shown to normal users; managers only.
@ -10415,7 +10414,6 @@ export interface EvaluationsSelect<T extends boolean = true> {
rater?: T;
ratee?: T;
mission?: T;
kind?: T;
level?: T;
comment?: T;
updatedAt?: T;

View file

@ -296,21 +296,21 @@ describe("Leadership evaluations", () => {
expect(isMissionEvaluable("Active", justStarted, 240)).toBe(false);
});
it("derives the evaluation kind from rank relation and shared attendance", async () => {
it("derives the evaluation direction from rank relation and shared attendance", async () => {
const cases = [
// Junior rates a senior (rater attended) -> upward leader rating.
{ input: { raterId: subordinateB.id, rateeId: leaderA.id }, expectKind: "leader-direct" },
{ input: { raterId: subordinateB.id, rateeId: leaderA.id }, expectDirection: "upward" },
// Mid rates the senior (rater attended) -> also upward, no assignment needed.
{ input: { raterId: participantC.id, rateeId: leaderA.id }, expectKind: "leader-direct" },
{ input: { raterId: participantC.id, rateeId: leaderA.id }, expectDirection: "upward" },
// Senior rates a junior -> downward subordinate rating.
{ input: { raterId: leaderA.id, rateeId: subordinateB.id }, expectKind: "subordinate" },
{ 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 }, expectKind: "leader-direct" },
{ input: { raterId: noRsvpF.id, rateeId: participantE.id }, expectDirection: "upward" },
];
for (const { input, expectKind } of cases) {
for (const { input, expectDirection } of cases) {
const result = await evaluateEligibility(payload, { ...input, missionId: missionCompletedId });
expect(result.eligible).toBe(true);
expect(result.kind).toBe(expectKind);
expect(result.direction).toBe(expectDirection);
}
// Equal ranks can never rate each other, even with both on the roster.
@ -357,12 +357,11 @@ describe("Leadership evaluations", () => {
expect(tooEarly.eligible).toBe(false);
});
it("keeps one row per rater/ratee/mission/kind", async () => {
it("keeps one row per rater/ratee/mission", async () => {
const first = await upsertEvaluation(payload, {
raterId: subordinateB.id,
rateeId: leaderA.id,
missionId: missionCompletedId,
kind: "leader-direct",
level: "excellent",
comment: "First pass",
});
@ -373,7 +372,6 @@ describe("Leadership evaluations", () => {
raterId: subordinateB.id,
rateeId: leaderA.id,
missionId: missionCompletedId,
kind: "leader-direct",
level: "proficient",
comment: "Revised",
});
@ -388,7 +386,6 @@ describe("Leadership evaluations", () => {
{ rater: { equals: subordinateB.id } },
{ ratee: { equals: leaderA.id } },
{ mission: { equals: missionCompletedId } },
{ kind: { equals: "leader-direct" } },
],
},
limit: 10,
@ -403,7 +400,6 @@ describe("Leadership evaluations", () => {
raterId: participantC.id,
rateeId: leaderA.id,
missionId: missionCompletedId,
kind: "leader-indirect",
level: "excellent",
});
evaluationIds.push(c.evaluation.id);
@ -421,7 +417,6 @@ describe("Leadership evaluations", () => {
raterId: participantE.id,
rateeId: leaderA.id,
missionId: missionCompletedId,
kind: "leader-indirect",
level: "exceptional",
});
evaluationIds.push(e.evaluation.id);
@ -448,7 +443,6 @@ describe("Leadership evaluations", () => {
raterId: leaderA.id,
rateeId: subordinateB.id,
missionId: missionCompletedId,
kind: "subordinate",
level: "adequate",
comment: "Manager note — must never leak",
});
@ -457,7 +451,6 @@ describe("Leadership evaluations", () => {
raterId: leaderA.id,
rateeId: subordinateB.id,
missionId: missionCompletedId,
kind: "subordinate",
level: "excellent",
});
evaluationIds.push(revised.evaluation.id);
@ -539,7 +532,7 @@ describe("Leadership evaluations", () => {
expect(typeof doc.rater).toBe("number");
expect(typeof doc.ratee).toBe("number");
expect(typeof doc.mission).toBe("number");
expect(["leader-direct", "leader-indirect", "subordinate"]).toContain(doc.kind);
expect(typeof doc.level).toBe("string");
} finally {
await payload.delete({ collection: "roles", id: role.id, overrideAccess: true }).catch(() => {});
}

View file

@ -84,7 +84,7 @@ async function makeMission(label: string, authorId: number): Promise<number> {
async function makeEvaluation(missionId: number, ratee: number): Promise<number> {
const doc = await payload.create({
collection: "evaluations",
data: { rater: raterId, ratee, mission: missionId, kind: "leader-direct", level: "proficient" },
data: { rater: raterId, ratee, mission: missionId, level: "proficient" },
overrideAccess: true,
depth: 0,
});