diff --git a/docs/bot/design.md b/docs/bot/design.md index d371194e..e8e37a3d 100644 --- a/docs/bot/design.md +++ b/docs/bot/design.md @@ -126,7 +126,7 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun ### D. Evaluation reminders (post-mission) - **Trigger**: a mission becomes evaluable (status `Completed`, or `Scheduled`/`Active` whose scheduled window (`classification.startDateTime` + `classification.estimatedDuration`, default 240 min) has fully passed — same rule as `isMissionEvaluable` in `src/lib/evaluations`). Poll loop every `DISCORD_EVALUATION_POLL_MS` (default 60s) queries evaluable missions with no `evaluationRemindersSentAt` marker (one-shot, same pattern as `discordAttendanceSentAt`). -- **Recipients** (`computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`): participants = users with a "yes" RSVP. Each participant is reminded to rate their direct leader(s); each leader of an assignment containing a participant is reminded to rate that participant (subordinate kind needs no RSVP). Self-pairs skipped; a user who is both gets one merged DM. +- **Recipients** (`computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`): participants = users with a "yes" RSVP. Pairing follows rank, not assignments: every pair of participants with a strict rank gap is reminded both ways (the junior to rate the senior as `leader-direct`, the senior to rate the junior as `subordinate`). Same-rank participants and participants without a profile rank form no pairs; self-pairs skipped; a user with both lists gets one merged DM. - **DM**: embed with "Rate your leadership" / "Rate your subordinates" sections, each line linking to the ratee's profile page (`APP_URL + /profile/`) where the rating dialog lives. Best-effort: DM failures are logged and skipped, marker is set after the pass (cap 40 DMs/tick, 300ms between sends; overflow retries next tick before the marker is set). - **Deliberate exception**: these DMs ignore `preferences.discord.enabled` (defaults false, not yet exposed in the web UI — honoring it would DM nobody). Dedicated unit-admin flow, not notification-stream forwarding. - **Manual trigger**: `/remind-evaluations` (staff only, guild-only). Optional `mission` option (mission ID, name, or code name — ambiguous matches list candidates) sends reminders for that one mission even if the marker is already set (as long as it's evaluable); omitted, it runs the reconcile sweep over all pending missions immediately and reports `{processed, sent}`. Replies are ephemeral; the interaction is deferred because DM sending takes minutes at scale. diff --git a/src/app/(frontend)/profile/[username]/actions.ts b/src/app/(frontend)/profile/[username]/actions.ts index efe48648..c9039954 100644 --- a/src/app/(frontend)/profile/[username]/actions.ts +++ b/src/app/(frontend)/profile/[username]/actions.ts @@ -65,9 +65,9 @@ async function findUserByUsername( /** * Submit (or re-submit) a leadership evaluation for the given profile. The kind - * is derived server-side from the rater/ratee/mission relationship — it is never - * accepted from the client. Eligibility is the permission gate here; any logged-in - * user with a qualifying relationship may evaluate. + * 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. */ export async function submitEvaluation(input: { username: string; diff --git a/src/app/(frontend)/profile/[username]/page.tsx b/src/app/(frontend)/profile/[username]/page.tsx index 8c836204..e9530340 100644 --- a/src/app/(frontend)/profile/[username]/page.tsx +++ b/src/app/(frontend)/profile/[username]/page.tsx @@ -8,7 +8,8 @@ import { ClientDate } from "@/components/frontend/ClientDate"; import { resolveLevel } from "@/utils/xp/resolveLevel"; import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; import { isSuperuser, hasPermission } from "@/utils/access-control/hasPermission"; -import { isDirectLeaderOf, isMissionEvaluable } from "@/lib/evaluations"; +import { isMissionEvaluable } from "@/lib/evaluations"; +import { rankDirection, type RankDirection } from "@/lib/evaluations/ranks"; import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels"; import { getEvaluationSummary } from "./actions"; import { getContributionSummary } from "@/lib/contributions"; @@ -158,24 +159,43 @@ async function findUpgradedFromNames( return upgradedFromNames; } +/** + * Missions the viewer could anchor an evaluation on: evaluable missions where + * the viewer OR the profile subject has a yes-RSVP (rank-based rule: at least + * one side of the pair attended). Callers must additionally verify a strict + * rank gap exists before showing this list. + */ async function findEligibleEvaluationMissions( payload: Payload, viewerId: number, + subjectId: number, now: Date, ): Promise { - const attendanceRes = await payload.find({ - collection: "mission-attendances", - where: { - and: [{ user: { equals: viewerId } }, { response: { equals: "yes" } }], - }, - limit: 100, - depth: 0, - select: { mission: true }, - overrideAccess: true, - }); + const [viewerAttendanceRes, subjectAttendanceRes] = await Promise.all([ + payload.find({ + collection: "mission-attendances", + where: { + and: [{ user: { equals: viewerId } }, { response: { equals: "yes" } }], + }, + limit: 100, + depth: 0, + select: { mission: true }, + overrideAccess: true, + }), + payload.find({ + collection: "mission-attendances", + where: { + and: [{ user: { equals: subjectId } }, { response: { equals: "yes" } }], + }, + limit: 100, + depth: 0, + select: { mission: true }, + overrideAccess: true, + }), + ]); const missionIds = [ ...new Set( - attendanceRes.docs.map((attendance) => + [...viewerAttendanceRes.docs, ...subjectAttendanceRes.docs].map((attendance) => typeof attendance.mission === "number" ? attendance.mission : attendance.mission.id, ), ), @@ -301,33 +321,37 @@ export default async function ProfilePage({ params }: ProfilePageProps) { viewer?.roles?.some((role) => role === "admin" || role === "developer") === true; const evaluationSummaryPromise = viewer ? getEvaluationSummary(username) : Promise.resolve(null); const eligibleMissionsPromise: Promise = viewer - ? findEligibleEvaluationMissions(payload, viewer.id, new Date()) + ? findEligibleEvaluationMissions(payload, viewer.id, user.id, new Date()) : Promise.resolve([]); const privilegedViewerPromise: Promise = viewer ? isSuperuser(payload, viewer) : Promise.resolve(false); - const directLeaderPromise: Promise = + const rankGapPromise: Promise = viewer && !isProfileOwner - ? isDirectLeaderOf(payload, viewer.id, user.id) - : Promise.resolve(false); + ? rankDirection(payload, viewer.id, user.id) + : Promise.resolve(null); const canEditIntelPromise: Promise = viewer ? hasPermission(payload, viewer, "profiles:intel_excerpt:update") : Promise.resolve(false); const [ evaluationSummaryResult, - eligibleMissions, + eligibleMissionsRaw, isSuperuserViewer, - isDirectLeader, + rankGap, canEditIntel, ] = await Promise.all([ evaluationSummaryPromise, eligibleMissionsPromise, privilegedViewerPromise, - directLeaderPromise, + rankGapPromise, canEditIntelPromise, ]); + // Without a strict rank gap there is no direction to rate in, so the dialog + // gets no mission list at all. + const eligibleMissions = rankGap ? eligibleMissionsRaw : []; + // Seniors may see the subordinate-rating line on their juniors' profiles. const canViewSubordinate = - isProfileOwner || isLegacyPrivileged || isSuperuserViewer || isDirectLeader; + isProfileOwner || isLegacyPrivileged || isSuperuserViewer || rankGap === "downward"; const latestMissionRows = evaluationSummaryResult?.success && evaluationSummaryResult.data.leader.visible ? await findLatestLeaderMissionRows(payload, user.id) @@ -367,7 +391,7 @@ export default async function ProfilePage({ params }: ProfilePageProps) { evaluationSummaryResult && !evaluationSummaryResult.success ? evaluationSummaryResult.error : null; - const canSubmitEvaluation = viewer !== null && !isProfileOwner; + const canSubmitEvaluation = viewer !== null && !isProfileOwner && rankGap !== null; const rank = profile.rank as Rank; const promotionResult = viewer ? await resolvePromotionAuthority(payload, viewer) : null; const allowedTargetRanks = promotionResult diff --git a/src/app/api/mission-reminder/route.ts b/src/app/api/mission-reminder/route.ts index 533fdb48..4b722c5f 100644 --- a/src/app/api/mission-reminder/route.ts +++ b/src/app/api/mission-reminder/route.ts @@ -11,9 +11,9 @@ export const runtime = "nodejs"; * GET /api/mission-reminder * * Returns recently completed main operations (within 72h of completion) where the - * authenticated user RSVP'd "yes" and at least one of their assignment-based - * direct leaders also RSVP'd "yes". The client uses this to prompt mission - * feedback. Leader entries carry identity only — no rater/comment data. + * authenticated user RSVP'd "yes" and at least one strictly higher-ranked + * co-attendee also RSVP'd "yes". The client uses this to prompt mission + * feedback. Leader entries carry identity only, no rater/comment data. */ export async function GET(req: NextRequest) { const payload = await getPayload({ config: await config }); diff --git a/src/bot/AGENTS.md b/src/bot/AGENTS.md index f19da108..0abf055d 100644 --- a/src/bot/AGENTS.md +++ b/src/bot/AGENTS.md @@ -75,7 +75,7 @@ Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit ## Feature flow: evaluation reminders -Once a mission is evaluable (`Completed`, or `Scheduled`/`Active` past its start), sends a one-shot DM per linked user asking them to rate their leadership (leaders also get a "rate your subordinates" section). Recipient plan: `computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`; state marker `evaluationRemindersSentAt` on Missions (withheld if the 40-DM/tick cap is hit — retries next tick). DMs ignore `preferences.discord.enabled` (defaults false, not yet exposed in web UI). Staff can re-send manually via `/remind-evaluations`. +Once a mission is evaluable (`Completed`, or `Scheduled`/`Active` past its start), sends a one-shot DM per linked user asking them to rate their leadership (juniors get a "rate your seniors" list; seniors get a "rate your subordinates" section). Pairing is rank-based among the mission's yes-RSVP participants: every strict-rank-gap attendee pair is reminded in both directions; same-rank peers and rankless participants form no pairs. Recipient plan: `computeEvaluationReminderPlan` in `src/lib/evaluations/reminders.ts`; state marker `evaluationRemindersSentAt` on Missions (withheld if the 40-DM/tick cap is hit - retries next tick). DMs ignore `preferences.discord.enabled` (defaults false, not yet exposed in web UI). Staff can re-send manually via `/remind-evaluations`. ## Feature flow: imminent op reminder diff --git a/src/bot/services/evaluationReminders.ts b/src/bot/services/evaluationReminders.ts index a4ac3d55..4f8a3c7e 100644 --- a/src/bot/services/evaluationReminders.ts +++ b/src/bot/services/evaluationReminders.ts @@ -8,10 +8,10 @@ import { isMissionEvaluable } from "@/lib/evaluations"; /** * Evaluation reminder service: after a mission becomes evaluable (completed, or * its scheduled start has passed), every participant with a linked Discord - * account gets a one-shot DM asking them to rate their leadership — and every - * leader additionally gets a section asking them to rate the subordinates who - * participated. Each DM links to the relevant profile pages, where the rating - * dialog lives. + * account gets a one-shot DM listing the co-attendees they may rate under the + * rank-based rules: juniors are prompted to rate their higher-ranked attendees, + * seniors are prompted to rate their lower-ranked ones. Each DM links to the + * relevant profile pages, where the rating dialog lives. * * The DM deliberately ignores `preferences.discord.enabled` (the notification * bridge opt-in): that toggle defaults to false and is not yet exposed in the diff --git a/src/collections/users/Evaluations.ts b/src/collections/users/Evaluations.ts index d4aa4505..d62fe870 100644 --- a/src/collections/users/Evaluations.ts +++ b/src/collections/users/Evaluations.ts @@ -9,6 +9,13 @@ import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels"; * service layer (`upsertEvaluation` in `src/lib/evaluations`), not by a DB * constraint. * + * 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. + * * Privacy model: raw documents are only readable/writable by users holding the * `evaluations:*` permissions (admin/developer via role docs). Normal users never * receive raw rows over REST — the profile UI consumes pre-aggregated, rater-free @@ -56,15 +63,15 @@ export const Evaluations: CollectionConfig = { type: "select", options: [ { - label: "Leader (direct)", + label: "Leader (junior rates senior)", value: "leader-direct", }, { - label: "Leader (indirect)", + label: "Leader (legacy indirect)", value: "leader-indirect", }, { - label: "Subordinate", + label: "Subordinate (senior rates junior)", value: "subordinate", }, ], diff --git a/src/components/frontend/profile/LeadershipEvaluationDialog.tsx b/src/components/frontend/profile/LeadershipEvaluationDialog.tsx index b6488d59..0d79f7d7 100644 --- a/src/components/frontend/profile/LeadershipEvaluationDialog.tsx +++ b/src/components/frontend/profile/LeadershipEvaluationDialog.tsx @@ -127,8 +127,9 @@ export function LeadershipEvaluationDialog({ Rate leadership - Submit a new rating or update your existing rating for one completed mission. Your - rating is included anonymously in the leadership aggregate. + Submit a new rating or update your existing rating for one completed mission. Ratings + follow rank: only operators strictly above or below your own rank can be rated here. + Your rating is included anonymously. diff --git a/src/components/frontend/profile/LeadershipEvaluationSection.tsx b/src/components/frontend/profile/LeadershipEvaluationSection.tsx index 955d2a63..21c99a4a 100644 --- a/src/components/frontend/profile/LeadershipEvaluationSection.tsx +++ b/src/components/frontend/profile/LeadershipEvaluationSection.tsx @@ -78,7 +78,7 @@ export function LeadershipEvaluationSection({ )} - Anonymous feedback from operators who have served alongside this leader. + Anonymous ratings from unit members ranked above or below this operator. diff --git a/src/lib/evaluations/index.ts b/src/lib/evaluations/index.ts index 774ffefd..84e7fa6a 100644 --- a/src/lib/evaluations/index.ts +++ b/src/lib/evaluations/index.ts @@ -6,10 +6,18 @@ import { type PerformanceLevelId, } from "./levels"; import { missionEndTime } from "@/lib/intelligence/missionLifecycle"; +import { rankDirection } from "./ranks"; type PayloadType = Awaited>; -/** The three evaluation kinds, per the leadership-evaluations feature. */ +/** + * 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. + */ export type EvaluationKind = "leader-direct" | "leader-indirect" | "subordinate"; /** Shape of an evaluations doc as consumed by this service (depth 0). */ @@ -58,9 +66,9 @@ 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". Used for leader - * ratings (direct and indirect). Subordinate ratings do not require it — the - * command relationship itself is the basis. + * 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, @@ -83,45 +91,6 @@ export async function hasYesAttendance( 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; @@ -130,16 +99,18 @@ export interface EligibilityResult { /** * Determines whether `raterId` may evaluate `rateeId` for `missionId`, and under - * which kind. Rules (leadership-evaluations feature): + * which kind. Rules (leadership-evaluations feature, rank-based): * * - 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. + * - 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, @@ -173,25 +144,22 @@ export async function evaluateEligibility( 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 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 raterLeadsRatee = await isDirectLeaderOf(payload, raterId, rateeId); - if (raterLeadsRatee) { - return { eligible: true, kind: "subordinate" }; + const attended = + (await hasYesAttendance(payload, raterId, missionId)) || + (await hasYesAttendance(payload, rateeId, missionId)); + if (!attended) { + return { eligible: false, reason: "No attendance recorded for this mission." }; } - if (participated && (await isAnyLeader(payload, rateeId))) { - return { eligible: true, kind: "leader-indirect" }; - } - - return { eligible: false, reason: "No leadership relationship for this mission." }; + return { eligible: true, kind: direction === "upward" ? "leader-direct" : "subordinate" }; } export interface UpsertEvaluationInput { diff --git a/src/lib/evaluations/ranks.ts b/src/lib/evaluations/ranks.ts new file mode 100644 index 00000000..6491659a --- /dev/null +++ b/src/lib/evaluations/ranks.ts @@ -0,0 +1,74 @@ +import type { Payload } from "payload"; +import { loadRankLadder, rankIndex, resolveRankFromLadder } from "@/lib/promotions/authority"; + +/** + * Rank seniority helpers for the leadership-evaluations feature. + * + * Eligibility is rank-based: a strictly junior member may rate a senior + * (upward), a strictly senior member may rate a junior (downward). Equal + * ranks, users without a profile, and users whose profile has no rank (or a + * rank that is not on the ladder) never form an eligible pair. + */ + +type PayloadType = Payload; + +/** + * Direction of a rating relative to the rater: "upward" means the rater holds + * a strictly lower rank than the ratee; "downward" means strictly higher. + */ +export type RankDirection = "upward" | "downward"; + +/** + * Ladder index (0 = lowest rank) for each user that has a profile carrying a + * rank found on the ladder. Users without a profile, with a null rank, or with + * an off-ladder rank are simply absent from the map. Bulk helper shared by the + * reminder planners so they can load seniority for everyone in one pass. + */ +export async function getUserRankIndexes( + payload: PayloadType, + userIds: readonly number[], +): Promise> { + const uniqueIds = [...new Set(userIds)]; + if (uniqueIds.length === 0) return new Map(); + + const ladder = await loadRankLadder(payload); + if (ladder.length === 0) return new Map(); + + const res = await payload.find({ + collection: "profiles", + where: { user: { in: uniqueIds } }, + limit: 1000, + depth: 0, + select: { user: true, rank: true }, + overrideAccess: true, + }); + + const wanted = new Set(uniqueIds.map((id) => String(id))); + const indexes = new Map(); + for (const profile of res.docs) { + const userId = typeof profile.user === "number" ? profile.user : profile.user?.id; + if (userId == null || !wanted.has(String(userId))) continue; + const rank = resolveRankFromLadder(ladder, profile.rank as number | undefined | null); + if (!rank) continue; + indexes.set(userId, rankIndex(ladder, rank.id)); + } + return indexes; +} + +/** + * Rank relationship between rater and ratee, or null when no strict gap + * exists (equal ranks, or either side without a resolvable rank). + */ +export async function rankDirection( + payload: PayloadType, + raterId: number, + rateeId: number, +): Promise { + const indexes = await getUserRankIndexes(payload, [raterId, rateeId]); + const raterIndex = indexes.get(raterId); + const rateeIndex = indexes.get(rateeId); + if (raterIndex === undefined || rateeIndex === undefined) return null; + if (raterIndex < rateeIndex) return "upward"; + if (raterIndex > rateeIndex) return "downward"; + return null; +} diff --git a/src/lib/evaluations/reminders.ts b/src/lib/evaluations/reminders.ts index 33327141..488cc631 100644 --- a/src/lib/evaluations/reminders.ts +++ b/src/lib/evaluations/reminders.ts @@ -6,17 +6,19 @@ import type { Payload } from "payload"; * Rules (aligned with `evaluateEligibility` in ./index.ts): * - Participants = users with a "yes" RSVP for the mission (the documented * participation proxy — same as the profile-page rating dialog). - * - Every participant is reminded to rate their direct leader(s) — eligible as - * `leader-direct` (and, for any other leader, `leader-indirect`). - * - Every leader of an assignment containing a participant is reminded to rate - * that participant — eligible as `subordinate` (no RSVP required for leaders). - * - Self-pairs are skipped; a user who is both a participant and a leader gets a - * single merged DM. + * - Pairing follows rank, not assignments: every pair of participants with a + * strict rank gap is reminded in both directions. The junior is prompted to + * rate the senior (`leader-direct`); the senior is prompted to rate the + * junior (`subordinate`). + * - Same-rank participants and participants without a profile rank form no + * pairs; self-pairs are skipped; a user with both lists gets one merged DM. * * This module is payload-only (no Discord imports) so the recipient plan is * testable independently of the bot service. */ +import { getUserRankIndexes } from "./ranks"; + type PayloadType = Payload; export interface ReminderLink { @@ -42,18 +44,6 @@ export interface EvaluationReminderPlan { recipients: ReminderRecipient[]; } -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; -} - function extractId(value: unknown): number | null { if (typeof value === "number") return value; if (value && typeof value === "object" && typeof (value as { id?: unknown }).id === "number") { @@ -98,30 +88,13 @@ export async function computeEvaluationReminderPlan( return { missionId, recipients: [] }; } - // 2. Command graph from assignments: leader -> members, member -> leaders. - const assignments = await payload.find({ - collection: "assignments", - where: { leader: { not_equals: null } }, - limit: 1000, - depth: 0, - overrideAccess: true, - }); - const leadersOf = new Map>(); - const membersLedBy = new Map>(); - for (const a of assignments.docs) { - const leaderId = extractId(a.leader); - if (leaderId === null) continue; - for (const memberId of extractIds(a.members)) { - if (memberId === leaderId) continue; // a leader is not their own leader - if (!leadersOf.has(memberId)) leadersOf.set(memberId, new Set()); - leadersOf.get(memberId)!.add(leaderId); - if (!membersLedBy.has(leaderId)) membersLedBy.set(leaderId, new Set()); - membersLedBy.get(leaderId)!.add(memberId); - } - } + // 2. Rank ladder index per participant. Participants without a profile rank + // are left out: eligibility needs a strict rank gap on both sides. + const rankIndexes = await getUserRankIndexes(payload, participantIds); + const ranked = participantIds.filter((id) => rankIndexes.has(id)); - // 3. Merge both roles per user: participant -> rate leaders; leader of a - // participant -> rate that participant. + // 3. Pair every strict-rank-gap combination among the ranked participants: + // the junior rates the senior upward, the senior rates the junior downward. const plan = new Map; rateSubordinates: Map }>(); const ensure = (userId: number) => { let entry = plan.get(userId); @@ -132,11 +105,17 @@ export async function computeEvaluationReminderPlan( return entry; }; - for (const participantId of participantIds) { - ensure(participantId); // even with no direct leader they may still be rated by theirs - for (const leaderId of leadersOf.get(participantId) ?? []) { - ensure(participantId).rateLeaders.set(leaderId, participantId); - ensure(leaderId).rateSubordinates.set(participantId, leaderId); + for (let i = 0; i < ranked.length; i += 1) { + for (let j = i + 1; j < ranked.length; j += 1) { + const a = ranked[i]; + const b = ranked[j]; + const indexA = rankIndexes.get(a)!; + const indexB = rankIndexes.get(b)!; + if (indexA === indexB) continue; // equal ranks never rate each other + const junior = indexA < indexB ? a : b; + const senior = indexA < indexB ? b : a; + ensure(junior).rateLeaders.set(senior, junior); + ensure(senior).rateSubordinates.set(junior, senior); } } diff --git a/src/lib/intelligence/missionReminder.ts b/src/lib/intelligence/missionReminder.ts index e6f34b27..9a6f4601 100644 --- a/src/lib/intelligence/missionReminder.ts +++ b/src/lib/intelligence/missionReminder.ts @@ -1,4 +1,5 @@ import type { Payload } from "payload"; +import { getUserRankIndexes } from "@/lib/evaluations/ranks"; /** * Mission feedback reminder window: a completed main operation only prompts for @@ -13,7 +14,7 @@ export interface ReminderLeader { displayName: string; } -/** One eligible mission with the direct leaders who RSVP'd "yes". */ +/** One eligible mission with the strictly higher-ranked attendees who RSVP'd "yes". */ export interface MissionReminder { missionId: number; missionName: string; @@ -28,35 +29,16 @@ function refId(value: number | { id: number } | null | undefined): number | null return null; } -/** - * The user's direct leaders, using the same assignment model as - * `isDirectLeaderOf` in `@/lib/evaluations`: a leader is anyone who leads an - * assignment whose members include this user. - */ -async function findDirectLeaderIds(payload: Payload, userId: number): Promise { - const res = await payload.find({ - collection: "assignments", - where: { members: { contains: userId } }, - limit: 100, - depth: 0, - overrideAccess: true, - }); - const ids = new Set(); - for (const assignment of res.docs) { - const leaderId = refId(assignment.leader); - if (leaderId !== null) ids.add(leaderId); - } - return [...ids]; -} - /** * Recently completed main operations that need feedback from `user`: the mission * is a main operation, transitioned to Completed within the last 72 hours - * (`ownershipAndStatus.completedAt`), `user` RSVP'd "yes", and at least one of - * the user's assignment-based direct leaders also RSVP'd "yes". + * (`ownershipAndStatus.completedAt`), `user` RSVP'd "yes", and at least one + * strictly higher-ranked co-attendee also RSVP'd "yes" (rank-based feedback + * model: you rate those above you; same-rank peers are never listed). * * Fail-closed: missions with a missing or unparseable completion timestamp are - * never eligible, and `updatedAt` is never used as a completion proxy. + * never eligible, and `updatedAt` is never used as a completion proxy. A user + * without a profile rank gets no reminders because they cannot rate anyone. */ export async function getMissionReminders( payload: Payload, @@ -125,9 +107,14 @@ export async function getMissionReminders( yesUsers.add(userId); } - const leaderIds = await findDirectLeaderIds(payload, user.id); - if (leaderIds.length === 0) return []; - const leaderSet = new Set(leaderIds); + // Rank model: the people the user is prompted to rate are the co-attendees + // holding a strictly higher rank. No profile rank means nothing rateable. + const attendeeIds = [ + ...new Set([...yesByMission.values()].flatMap((yesUsers) => [...yesUsers])), + ]; + const rankIndexes = await getUserRankIndexes(payload, attendeeIds); + const userRankIndex = rankIndexes.get(user.id); + if (userRankIndex === undefined) return []; const eligible: Array<{ mission: (typeof missionsRes.docs)[number]; @@ -137,8 +124,12 @@ export async function getMissionReminders( for (const { mission, completedAt } of candidates) { const yesUsers = yesByMission.get(mission.id) ?? new Set(); if (!yesUsers.has(user.id)) continue; // the user must have RSVP'd "yes" - const leaders = [...yesUsers].filter((id) => leaderSet.has(id)); - if (leaders.length === 0) continue; // at least one direct leader must have RSVP'd "yes" + const leaders = [...yesUsers].filter((id) => { + if (id === user.id) return false; + const index = rankIndexes.get(id); + return index !== undefined && index > userRankIndex; + }); + if (leaders.length === 0) continue; // at least one higher-ranked co-attendee required eligible.push({ mission, completedAt, leaderIds: leaders }); } diff --git a/tests/int/evaluations.int.spec.ts b/tests/int/evaluations.int.spec.ts index e62c2989..350f9e62 100644 --- a/tests/int/evaluations.int.spec.ts +++ b/tests/int/evaluations.int.spec.ts @@ -27,11 +27,14 @@ describe("Leadership evaluations", () => { let participantE: User; let noRsvpF: User; let outsiderD: User; - let assignmentId: number; + let juniorRankId: number; + let midRankId: number; + let seniorRankId: number; let missionCompletedId: number; let missionFutureId: number; const userIds: number[] = []; + const rankIds: number[] = []; const attendanceIds: number[] = []; const evaluationIds: number[] = []; @@ -53,6 +56,41 @@ describe("Leadership evaluations", () => { return user; }; + // Self-contained ladder slice: creation order ascends in seniority, matching + // the pattern in promotions.int.spec.ts. + const makeRank = async (name: string): Promise => { + const rank = await payload.create({ + collection: "ranks", + data: { + name: `${RUN} ${name}`, + abbreviation: `${RUN}-${name.toLowerCase()}`, + description: `${RUN} test rank`, + }, + overrideAccess: true, + depth: 0, + }); + rankIds.push(rank.id); + return rank.id; + }; + + const setProfileRank = async (userId: number, rankId: number): Promise => { + const profiles = (await payload.find({ + collection: "profiles", + where: { user: { equals: userId } }, + limit: 1, + depth: 0, + overrideAccess: true, + })) as unknown as { docs: Array<{ id: number }> }; + expect(profiles.docs.length).toBe(1); // hook-provisioned profile + await payload.update({ + collection: "profiles", + id: profiles.docs[0].id, + data: { rank: rankId }, + overrideAccess: true, + depth: 0, + }); + }; + const makeMission = async ( label: string, status: Mission["ownershipAndStatus"]["status"], @@ -123,6 +161,10 @@ describe("Leadership evaluations", () => { })) as unknown as Campaign; campaignId = campaign.id; + juniorRankId = await makeRank("Jr"); + midRankId = await makeRank("Mid"); + seniorRankId = await makeRank("Sr"); + leaderA = await makeUser("leader-a"); subordinateB = await makeUser("subordinate-b"); participantC = await makeUser("participant-c"); @@ -130,18 +172,24 @@ describe("Leadership evaluations", () => { noRsvpF = await makeUser("no-rsvp-f"); outsiderD = await makeUser("outsider-d"); - const assignment = await payload.create({ - collection: "assignments", - data: { - name: `${RUN} Squad`, - type: "squad", - leader: leaderA.id, - members: [subordinateB.id, noRsvpF.id], - }, - overrideAccess: true, + // Rank ladder: leaderA (Sr) > C/E (Mid) > B/F (Jr). The Users hook gives + // every new profile a default bottom rank, and profiles require one, so D's + // profile is deleted outright to exercise the no-rank path. + await setProfileRank(leaderA.id, seniorRankId); + await setProfileRank(subordinateB.id, juniorRankId); + await setProfileRank(participantC.id, midRankId); + await setProfileRank(participantE.id, midRankId); + await setProfileRank(noRsvpF.id, juniorRankId); + const dProfiles = await payload.find({ + collection: "profiles", + where: { user: { equals: outsiderD.id } }, + limit: 5, depth: 0, + overrideAccess: true, }); - assignmentId = assignment.id; + for (const doc of dProfiles.docs) { + await payload.delete({ collection: "profiles", id: doc.id, overrideAccess: true }); + } const past = new Date(); past.setDate(past.getDate() - 7); @@ -181,9 +229,9 @@ describe("Leadership evaluations", () => { .delete({ collection: "mission-attendances", id, overrideAccess: true }) .catch(() => {}); } - await payload.delete({ collection: "assignments", id: assignmentId, overrideAccess: true }).catch( - () => {}, - ); + for (const id of rankIds) { + await payload.delete({ collection: "ranks", id, overrideAccess: true }).catch(() => {}); + } for (const id of [missionCompletedId, missionFutureId]) { await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {}); } @@ -248,11 +296,16 @@ describe("Leadership evaluations", () => { expect(isMissionEvaluable("Active", justStarted, 240)).toBe(false); }); - it("derives the evaluation kind from the rater/ratee/mission relationship", async () => { + it("derives the evaluation kind 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: participantC.id, rateeId: leaderA.id }, expectKind: "leader-indirect" }, + // Mid rates the senior (rater attended) -> also upward, no assignment needed. + { input: { raterId: participantC.id, rateeId: leaderA.id }, expectKind: "leader-direct" }, + // Senior rates a junior -> downward subordinate rating. { input: { raterId: leaderA.id, rateeId: subordinateB.id }, expectKind: "subordinate" }, + // F never RSVPed, but E did: one side attending anchors the mission. + { input: { raterId: noRsvpF.id, rateeId: participantE.id }, expectKind: "leader-direct" }, ]; for (const { input, expectKind } of cases) { const result = await evaluateEligibility(payload, { ...input, missionId: missionCompletedId }); @@ -260,22 +313,32 @@ describe("Leadership evaluations", () => { expect(result.kind).toBe(expectKind); } - // In A's assignment but never RSVPed yes — the participation proxy fails. - const noRsvp = await evaluateEligibility(payload, { - raterId: noRsvpF.id, - rateeId: leaderA.id, + // Equal ranks can never rate each other, even with both on the roster. + const peer = await evaluateEligibility(payload, { + raterId: participantE.id, + rateeId: participantC.id, missionId: missionCompletedId, }); - expect(noRsvp.eligible).toBe(false); - expect(noRsvp.reason).toBe("No attendance recorded for this mission."); + expect(peer.eligible).toBe(false); + expect(peer.reason).toContain("strict rank"); - // No leadership relationship at all. - const outsider = await evaluateEligibility(payload, { + // Rankless raters are ineligible regardless of attendance. + const rankless = await evaluateEligibility(payload, { raterId: outsiderD.id, rateeId: leaderA.id, missionId: missionCompletedId, }); - expect(outsider.eligible).toBe(false); + expect(rankless.eligible).toBe(false); + expect(rankless.reason).toContain("strict rank"); + + // Strict rank gap but neither side attended this mission. + const noAttendance = await evaluateEligibility(payload, { + raterId: noRsvpF.id, + rateeId: leaderA.id, + missionId: missionCompletedId, + }); + expect(noAttendance.eligible).toBe(false); + expect(noAttendance.reason).toBe("No attendance recorded for this mission."); // Self-rating is always rejected. const selfRating = await evaluateEligibility(payload, { diff --git a/tests/int/mission-reminder.int.spec.ts b/tests/int/mission-reminder.int.spec.ts index 22256d87..648a8d80 100644 --- a/tests/int/mission-reminder.int.spec.ts +++ b/tests/int/mission-reminder.int.spec.ts @@ -8,7 +8,7 @@ import { randomUUID } from "node:crypto"; import { NextRequest } from "next/server"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import type { Assignment, Campaign, Map as MissionMap, Mission, User } from "@/payload-types"; +import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types"; import { GET } from "@/app/api/mission-reminder/route"; import { getMissionReminders } from "@/lib/intelligence/missionReminder"; @@ -73,7 +73,7 @@ describe("Mission feedback reminder", () => { const userIds: number[] = []; const missionIds: number[] = []; const attendanceIds: number[] = []; - const assignmentIds: number[] = []; + const rankIds: number[] = []; let memberId: number; let leaderAId: number; @@ -92,7 +92,7 @@ describe("Mission feedback reminder", () => { let staleMainId: number; // main, 73h ago (past the window) let noStampId: number; // main, completion stamp cleared -> fail closed let userNoId: number; // member RSVP'd "no" - let leaderNoId: number; // only a non-leader (stranger) RSVP'd yes + let leaderNoId: number; // only a same-rank peer (stranger) RSVP'd yes // Boundary fixtures relative to fixedNow. let boundaryExactId: number; // exactly fixedNow - 72h -> included at fixedNow @@ -148,21 +148,50 @@ describe("Mission feedback reminder", () => { strangerId = stranger.id; lonerId = loner.id; - // The member belongs to two squads, so their direct leaders are both - // leaders (same model as isDirectLeaderOf in @/lib/evaluations). - const makeAssignment = async (label: string, leaderId: number): Promise => { - const assignment = (await payload.create({ - collection: "assignments", - data: { name: `${RUN} ${label}`, type: "squad", leader: leaderId, members: [memberId] }, + // Rank-based pairing (same model as @/lib/evaluations/ranks): leaderA and + // leaderB strictly outrank member/stranger/loner, who share one junior rank. + // Creation order ascends in seniority, matching the promotions specs. + const makeRank = async (label: string): Promise => { + const rank = await payload.create({ + collection: "ranks", + data: { + name: `${RUN} ${label}`, + abbreviation: `${RUN}-${label.toLowerCase()}`, + description: `${RUN} test rank`, + }, overrideAccess: true, depth: 0, - })) as unknown as Assignment; - assignmentIds.push(assignment.id); - return assignment; + }); + rankIds.push(rank.id); + return rank.id; }; - await makeAssignment("Squad A", leaderAId); - await makeAssignment("Squad B", leaderBId); + const setProfileRank = async (userId: number, rankId: number): Promise => { + const profiles = (await payload.find({ + collection: "profiles", + where: { user: { equals: userId } }, + limit: 1, + depth: 0, + overrideAccess: true, + })) as unknown as { docs: Array<{ id: number }> }; + expect(profiles.docs.length).toBe(1); // hook-provisioned profile + await payload.update({ + collection: "profiles", + id: profiles.docs[0].id, + data: { rank: rankId }, + overrideAccess: true, + depth: 0, + }); + }; + + const jrRankId = await makeRank("Jr"); + const sr1RankId = await makeRank("Sr1"); + const sr2RankId = await makeRank("Sr2"); + await setProfileRank(memberId, jrRankId); + await setProfileRank(strangerId, jrRankId); // same rank as the member + await setProfileRank(lonerId, jrRankId); + await setProfileRank(leaderAId, sr1RankId); + await setProfileRank(leaderBId, sr2RankId); const makeMission = async ( label: string, @@ -272,7 +301,7 @@ describe("Mission feedback reminder", () => { await makeMission("leader-no", "main", new Date(fixedNow.getTime() - DAY).toISOString()) ).id; await addAttendance(leaderNoId, memberId, "yes"); - await addAttendance(leaderNoId, strangerId, "yes"); // a non-leader "yes" must not count + await addAttendance(leaderNoId, strangerId, "yes"); // a same-rank peer "yes" must not count // Boundary fixtures relative to fixedNow. boundaryExactId = ( @@ -308,8 +337,8 @@ describe("Mission feedback reminder", () => { for (const id of missionIds) { await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {}); } - for (const id of assignmentIds) { - await payload.delete({ collection: "assignments", id, overrideAccess: true }).catch(() => {}); + for (const id of rankIds) { + await payload.delete({ collection: "ranks", id, overrideAccess: true }).catch(() => {}); } // User deletion trips FK constraints unless the hook-provisioned personal // bank account and profile are removed first. @@ -355,7 +384,7 @@ describe("Mission feedback reminder", () => { expect(res.status).toBe(401); }); - it("returns only eligible missions with the yes-RSVP direct leaders", async () => { + it("returns only eligible missions with the yes-RSVP higher-ranked attendees", async () => { const res = await GET(request(memberToken)); expect(res.status).toBe(200); const body = (await res.json()) as { reminders: Array> }; @@ -387,13 +416,13 @@ describe("Mission feedback reminder", () => { expect(leaders[0].username).toBe(`${RUN}-leader-a`); expect(leaders[0].displayName).toBe("LEADER A"); - // Both direct leaders who RSVP'd yes are reported. + // Both higher-ranked yes-RSVPers are reported. const multi = byMissionId.get(multiLeaderId)!; const multiLeaderIds = (multi.leaders as Array<{ id: number }>).map((leader) => leader.id); expect([...multiLeaderIds].sort()).toEqual([leaderAId, leaderBId].sort()); }); - it("returns nothing for a user without direct leaders", async () => { + it("returns nothing for a user without higher-ranked co-attendees", async () => { const res = await GET(request(lonerToken)); expect(res.status).toBe(200); const body = (await res.json()) as { reminders: unknown[] };