import { getPerformanceLevel, isPerformanceLevelId, PERFORMANCE_LEVELS, type PerformanceLevel, type PerformanceLevelId, } from "./levels"; import { missionEndTime } from "@/lib/intelligence/missionLifecycle"; type PayloadType = Awaited>; /** The three evaluation kinds, per the leadership-evaluations feature. */ 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; 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". Used for leader * ratings (direct and indirect). Subordinate ratings do not require it — the * command relationship itself is the basis. */ 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; } function extractIds(value: unknown): number[] { if (!Array.isArray(value)) return []; const ids: number[] = []; for (const v of value) { if (typeof v === "number") ids.push(v); else if (v && typeof v === "object" && typeof (v as { id?: unknown }).id === "number") { ids.push((v as { id: number }).id); } } return ids; } /** True when `leaderId` leads an assignment whose members include `subordinateId`. */ export async function isDirectLeaderOf( payload: PayloadType, leaderId: number, subordinateId: number, ): Promise { const assignments = await payload.find({ collection: "assignments", where: { leader: { equals: leaderId } }, depth: 0, overrideAccess: true, }); return assignments.docs.some((a) => extractIds(a.members).includes(subordinateId)); } /** True when `userId` leads at least one assignment. */ export async function isAnyLeader(payload: PayloadType, userId: number): Promise { const res = await payload.find({ collection: "assignments", where: { leader: { equals: userId } }, limit: 1, depth: 0, overrideAccess: true, }); return res.docs.length > 0; } export interface EligibilityResult { eligible: boolean; kind?: EvaluationKind; reason?: string; } /** * Determines whether `raterId` may evaluate `rateeId` for `missionId`, and under * which kind. Rules (leadership-evaluations feature): * * - You cannot evaluate yourself. * - The mission must be completed/past (see {@link isMissionEvaluable}). * - `leader-direct`: the ratee directly leads the rater's assignment AND the rater * participated in the mission (yes-RSVP proxy). * - `subordinate`: the rater directly leads the ratee's assignment. No RSVP * required — the command relationship itself is the basis. * - `leader-indirect`: the rater participated in the mission and the ratee leads at * least one assignment, but did not directly lead the rater. */ 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 participated = await hasYesAttendance(payload, raterId, missionId); const rateeLeadsRater = await isDirectLeaderOf(payload, rateeId, raterId); if (rateeLeadsRater) { if (!participated) { return { eligible: false, reason: "No attendance recorded for this mission." }; } return { eligible: true, kind: "leader-direct" }; } const raterLeadsRatee = await isDirectLeaderOf(payload, raterId, rateeId); if (raterLeadsRatee) { return { eligible: true, kind: "subordinate" }; } if (participated && (await isAnyLeader(payload, rateeId))) { return { eligible: true, kind: "leader-indirect" }; } return { eligible: false, reason: "No leadership relationship for this mission." }; } 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. */ 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 } }, { kind: { equals: input.kind } }, ], }, 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, kind: input.kind, 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 all leader-kind 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 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. */ export async function getLeaderAggregate( payload: PayloadType, rateeId: number, ): Promise { const res = await payload.find({ collection: "evaluations", where: { and: [{ ratee: { equals: rateeId } }, { kind: { in: ["leader-direct", "leader-indirect"] } }], }, depth: 0, overrideAccess: true, }); const docs = res.docs as unknown as EvaluationDoc[]; const totalRaters = new Set(docs.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 docs) { counts.set(d.level, (counts.get(d.level) ?? 0) + 1); } const totalDocs = docs.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 = totalDocs ? Math.round( (docs.reduce((sum, d) => sum + (getPerformanceLevel(d.level)?.score ?? 0), 0) / totalDocs) * 100, ) / 100 : 0; const missionIds = [...new Set(docs.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 = docs.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) }; } /** * 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. */ export async function getLatestSubordinateLevel( payload: PayloadType, rateeId: number, ): Promise<{ level: PerformanceLevel; missionId: number; at: string } | null> { const res = await payload.find({ collection: "evaluations", where: { and: [{ ratee: { equals: rateeId } }, { kind: { equals: "subordinate" } }], }, sort: "-updatedAt", limit: 1, depth: 0, overrideAccess: true, }); const doc = res.docs[0] as unknown as EvaluationDoc | undefined; if (!doc) return null; const level = getPerformanceLevel(doc.level); if (!level) return null; return { level, missionId: doc.mission, at: doc.updatedAt }; }