import { getPerformanceLevel, isPerformanceLevelId, PERFORMANCE_LEVELS, type PerformanceLevel, type PerformanceLevelId, } from "./levels"; import { missionEndTime } from "@/lib/intelligence/missionLifecycle"; import { getUserRankIndexes, rankDirection, type RankDirection } from "./ranks"; type PayloadType = Awaited>; /** * 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 interface EvaluationDoc { id: number; rater: number; ratee: number; mission: number; level: PerformanceLevelId; comment: string | null; createdAt: string; updatedAt: string; } /** * Minimum number of distinct raters before a leader aggregate is visible to anyone. * Below this threshold the per-level breakdown and average are withheld so a small * group of raters cannot be identified from the displayed distribution. */ export const ANONYMITY_THRESHOLD = 3; /** * Pure eligibility check for whether a mission is "completed/past" enough to be * evaluated. Draft statuses (Concept/Planning/Ready) and Cancelled are never * eligible. Scheduled/Active missions become eligible only once their scheduled * window (start + estimated duration, defaulting to 240 minutes when missing — * same rule as the mission-lifecycle auto-complete) has fully passed, so an op * that just started is not treated as evaluable while it is still running. */ export function isMissionEvaluable( status: string, startDateTimeISO?: string | null, estimatedDurationMinutes?: number | null, now: Date = new Date(), ): boolean { if (status === "Completed") return true; if (status === "Scheduled" || status === "Active") { const end = missionEndTime(startDateTimeISO ?? null, estimatedDurationMinutes ?? null); if (!end) return false; return end.getTime() <= now.getTime(); } return false; } /** * 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. */ export async function hasYesAttendance( payload: PayloadType, userId: number, missionId: number, ): Promise { const res = await payload.find({ collection: "mission-attendances", where: { and: [ { user: { equals: userId } }, { mission: { equals: missionId } }, { response: { equals: "yes" } }, ], }, limit: 1, depth: 0, overrideAccess: true, }); return res.docs.length > 0; } export interface EligibilityResult { eligible: boolean; direction?: RankDirection; reason?: string; } /** * Determines whether `raterId` may evaluate `rateeId` for `missionId`, and under * which kind. Rules (leadership-evaluations feature, rank-based): * * - You cannot evaluate yourself. * - The mission must be completed/past (see {@link isMissionEvaluable}). * - Strict rank gap: the rater must hold a strictly lower or strictly higher * rank than the ratee (per the ranks ladder). Equal ranks, or either side * without a resolvable profile rank, are never eligible. Squad/division or * 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. */ export async function evaluateEligibility( payload: PayloadType, input: { raterId: number; rateeId: number; missionId: number }, ): Promise { const { raterId, rateeId, missionId } = input; if (raterId === rateeId) { return { eligible: false, reason: "You cannot evaluate yourself." }; } const missions = await payload.find({ collection: "missions", where: { id: { equals: missionId } }, limit: 1, depth: 0, overrideAccess: true, }); const mission = missions.docs[0] as | { ownershipAndStatus?: { status?: string }; classification?: { startDateTime?: string | null; estimatedDuration?: number | null }; } | undefined; if (!mission) return { eligible: false, reason: "Mission not found." }; const status = mission.ownershipAndStatus?.status ?? ""; const startDateTime = mission.classification?.startDateTime; const estimatedDuration = mission.classification?.estimatedDuration ?? null; if (!isMissionEvaluable(status, startDateTime, estimatedDuration)) { return { eligible: false, reason: "This mission is not completed or past yet." }; } const direction = await rankDirection(payload, raterId, rateeId); if (!direction) { return { eligible: false, reason: "Evaluations require a strict rank difference (rate those above or below you).", }; } const attended = (await hasYesAttendance(payload, raterId, missionId)) || (await hasYesAttendance(payload, rateeId, missionId)); if (!attended) { return { eligible: false, reason: "No attendance recorded for this mission." }; } return { eligible: true, direction }; } export interface UpsertEvaluationInput { raterId: number; rateeId: number; missionId: number; level: PerformanceLevelId; comment?: string; } /** * 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, input: UpsertEvaluationInput, ): Promise<{ evaluation: EvaluationDoc; created: boolean }> { if (!isPerformanceLevelId(input.level)) { throw new Error(`Unknown performance level: ${String(input.level)}`); } const existing = await payload.find({ collection: "evaluations", where: { and: [ { rater: { equals: input.raterId } }, { ratee: { equals: input.rateeId } }, { mission: { equals: input.missionId } }, ], }, limit: 1, depth: 0, overrideAccess: true, }); if (existing.docs.length > 0) { const updated = await payload.update({ collection: "evaluations", id: existing.docs[0].id, data: { level: input.level, comment: input.comment ?? null }, depth: 0, overrideAccess: true, }); return { evaluation: updated as unknown as EvaluationDoc, created: false }; } const created = await payload.create({ collection: "evaluations", data: { rater: input.raterId, ratee: input.rateeId, mission: input.missionId, level: input.level, comment: input.comment ?? null, }, depth: 0, overrideAccess: true, }); return { evaluation: created as unknown as EvaluationDoc, created: true }; } export interface LeaderEvaluationAggregate { rateeId: number; /** Distinct raters across this ratee's upward (junior-rating-senior) evaluations. */ totalRaters: number; /** False while raters are below ANONYMITY_THRESHOLD — breakdown withheld. */ visible: boolean; levels: { id: string; label: string; score: number; color: string; count: number; percentage: number; }[] | null; averageScore: number | null; missions: LeaderMissionAggregate[]; } export interface LeaderMissionAggregate { missionId: number; missionName: string; missionCodeName: string | null; startDateTime: string | null; totalRaters: number; percentage: number | null; } /** * 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, rateeId: number, ): Promise { const res = await payload.find({ collection: "evaluations", where: { ratee: { equals: rateeId } }, depth: 0, 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; if (totalRaters < ANONYMITY_THRESHOLD) { return { rateeId, totalRaters, visible: false, levels: null, averageScore: null, missions: [] }; } const counts = new Map(); for (const d of upward) { counts.set(d.level, (counts.get(d.level) ?? 0) + 1); } const totalDocs = upward.length; const levels = PERFORMANCE_LEVELS.map((l) => { const count = counts.get(l.id) ?? 0; return { id: l.id, label: l.label, score: l.score, color: l.color, count, percentage: totalDocs ? Math.round((count / totalDocs) * 10000) / 100 : 0, }; }).filter((l) => l.count > 0); const averageScore = upward.length ? Math.round( (upward.reduce((sum, d) => sum + (getPerformanceLevel(d.level)?.score ?? 0), 0) / upward.length) * 100, ) / 100 : 0; const missionIds = [...new Set(upward.map((doc) => doc.mission))]; const missionRows = await Promise.all( missionIds.map(async (missionId) => { const missionResult = await payload.findByID({ collection: "missions", id: missionId, depth: 0, overrideAccess: true, }); 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), 0, ); return { missionId, missionName: missionResult.name, missionCodeName: missionResult.codeName ?? null, startDateTime: missionResult.classification?.startDateTime ?? null, totalRaters: missionRaters, percentage: missionRaters >= ANONYMITY_THRESHOLD && missionDocs.length > 0 ? Math.round((missionScore / missionDocs.length) * 100) / 100 : null, } satisfies LeaderMissionAggregate; }), ); missionRows.sort((a, b) => { const dateA = a.startDateTime ? new Date(a.startDateTime).getTime() : 0; const dateB = b.startDateTime ? new Date(b.startDateTime).getTime() : 0; return dateB - dateA; }); return { rateeId, totalRaters, visible: true, levels, averageScore, missions: missionRows.slice(0, 5) }; } /** * 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, rateeId: number, ): Promise<{ level: PerformanceLevel; missionId: number; at: string } | null> { const res = await payload.find({ collection: "evaluations", where: { ratee: { equals: rateeId } }, sort: "-updatedAt", depth: 0, overrideAccess: true, }); 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; return { level, missionId: doc.mission, at: doc.updatedAt }; }