1
0
Fork 0

feat(evaluations): gate leadership ratings by rank instead of squad assignments

Eligibility now requires a strict rank gap plus a yes-RSVP from at least
one side of the pair on an evaluable mission. Junior rates senior writes
leader-direct (feeds the anonymous aggregate); senior rates junior writes
subordinate; leader-indirect stays readable for legacy rows only.

- New src/lib/evaluations/ranks.ts ladder helpers shared by all call sites
- Profile page: eligible missions union viewer+subject attendance, dialog
  hidden without a rank gap, subordinate line visible to higher ranks
- Bot and in-app reminder planners pair co-attendees by rank, not squads
- isDirectLeaderOf/isAnyLeader removed; no schema change or migration
This commit is contained in:
Jason Fraley 2026-10-25 02:53:49 -04:00
parent 633853589f
commit 977f841056
15 changed files with 361 additions and 225 deletions

View file

@ -126,7 +126,7 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
### D. Evaluation reminders (post-mission) ### 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`). - **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/<username>`) 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). - **DM**: embed with "Rate your leadership" / "Rate your subordinates" sections, each line linking to the ratee's profile page (`APP_URL + /profile/<username>`) 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. - **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. - **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.

View file

@ -65,9 +65,9 @@ async function findUserByUsername(
/** /**
* Submit (or re-submit) a leadership evaluation for the given profile. The kind * 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 * is derived server-side from the rater/ratee rank relationship and attendance;
* accepted from the client. Eligibility is the permission gate here; any logged-in * it is never accepted from the client. Eligibility is the permission gate here;
* user with a qualifying relationship may evaluate. * any logged-in user with a strict rank difference may evaluate.
*/ */
export async function submitEvaluation(input: { export async function submitEvaluation(input: {
username: string; username: string;

View file

@ -8,7 +8,8 @@ import { ClientDate } from "@/components/frontend/ClientDate";
import { resolveLevel } from "@/utils/xp/resolveLevel"; import { resolveLevel } from "@/utils/xp/resolveLevel";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { isSuperuser, hasPermission } from "@/utils/access-control/hasPermission"; 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 { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels";
import { getEvaluationSummary } from "./actions"; import { getEvaluationSummary } from "./actions";
import { getContributionSummary } from "@/lib/contributions"; import { getContributionSummary } from "@/lib/contributions";
@ -158,24 +159,43 @@ async function findUpgradedFromNames(
return upgradedFromNames; 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( async function findEligibleEvaluationMissions(
payload: Payload, payload: Payload,
viewerId: number, viewerId: number,
subjectId: number,
now: Date, now: Date,
): Promise<readonly EvaluationMissionOption[]> { ): Promise<readonly EvaluationMissionOption[]> {
const attendanceRes = await payload.find({ const [viewerAttendanceRes, subjectAttendanceRes] = await Promise.all([
collection: "mission-attendances", payload.find({
where: { collection: "mission-attendances",
and: [{ user: { equals: viewerId } }, { response: { equals: "yes" } }], where: {
}, and: [{ user: { equals: viewerId } }, { response: { equals: "yes" } }],
limit: 100, },
depth: 0, limit: 100,
select: { mission: true }, depth: 0,
overrideAccess: true, 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 = [ const missionIds = [
...new Set( ...new Set(
attendanceRes.docs.map((attendance) => [...viewerAttendanceRes.docs, ...subjectAttendanceRes.docs].map((attendance) =>
typeof attendance.mission === "number" ? attendance.mission : attendance.mission.id, 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; viewer?.roles?.some((role) => role === "admin" || role === "developer") === true;
const evaluationSummaryPromise = viewer ? getEvaluationSummary(username) : Promise.resolve(null); const evaluationSummaryPromise = viewer ? getEvaluationSummary(username) : Promise.resolve(null);
const eligibleMissionsPromise: Promise<readonly EvaluationMissionOption[]> = viewer const eligibleMissionsPromise: Promise<readonly EvaluationMissionOption[]> = viewer
? findEligibleEvaluationMissions(payload, viewer.id, new Date()) ? findEligibleEvaluationMissions(payload, viewer.id, user.id, new Date())
: Promise.resolve([]); : Promise.resolve([]);
const privilegedViewerPromise: Promise<boolean> = viewer const privilegedViewerPromise: Promise<boolean> = viewer
? isSuperuser(payload, viewer) ? isSuperuser(payload, viewer)
: Promise.resolve(false); : Promise.resolve(false);
const directLeaderPromise: Promise<boolean> = const rankGapPromise: Promise<RankDirection | null> =
viewer && !isProfileOwner viewer && !isProfileOwner
? isDirectLeaderOf(payload, viewer.id, user.id) ? rankDirection(payload, viewer.id, user.id)
: Promise.resolve(false); : Promise.resolve(null);
const canEditIntelPromise: Promise<boolean> = viewer const canEditIntelPromise: Promise<boolean> = viewer
? hasPermission(payload, viewer, "profiles:intel_excerpt:update") ? hasPermission(payload, viewer, "profiles:intel_excerpt:update")
: Promise.resolve(false); : Promise.resolve(false);
const [ const [
evaluationSummaryResult, evaluationSummaryResult,
eligibleMissions, eligibleMissionsRaw,
isSuperuserViewer, isSuperuserViewer,
isDirectLeader, rankGap,
canEditIntel, canEditIntel,
] = await Promise.all([ ] = await Promise.all([
evaluationSummaryPromise, evaluationSummaryPromise,
eligibleMissionsPromise, eligibleMissionsPromise,
privilegedViewerPromise, privilegedViewerPromise,
directLeaderPromise, rankGapPromise,
canEditIntelPromise, 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 = const canViewSubordinate =
isProfileOwner || isLegacyPrivileged || isSuperuserViewer || isDirectLeader; isProfileOwner || isLegacyPrivileged || isSuperuserViewer || rankGap === "downward";
const latestMissionRows = const latestMissionRows =
evaluationSummaryResult?.success && evaluationSummaryResult.data.leader.visible evaluationSummaryResult?.success && evaluationSummaryResult.data.leader.visible
? await findLatestLeaderMissionRows(payload, user.id) ? await findLatestLeaderMissionRows(payload, user.id)
@ -367,7 +391,7 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
evaluationSummaryResult && !evaluationSummaryResult.success evaluationSummaryResult && !evaluationSummaryResult.success
? evaluationSummaryResult.error ? evaluationSummaryResult.error
: null; : null;
const canSubmitEvaluation = viewer !== null && !isProfileOwner; const canSubmitEvaluation = viewer !== null && !isProfileOwner && rankGap !== null;
const rank = profile.rank as Rank; const rank = profile.rank as Rank;
const promotionResult = viewer ? await resolvePromotionAuthority(payload, viewer) : null; const promotionResult = viewer ? await resolvePromotionAuthority(payload, viewer) : null;
const allowedTargetRanks = promotionResult const allowedTargetRanks = promotionResult

View file

@ -11,9 +11,9 @@ export const runtime = "nodejs";
* GET /api/mission-reminder * GET /api/mission-reminder
* *
* Returns recently completed main operations (within 72h of completion) where the * Returns recently completed main operations (within 72h of completion) where the
* authenticated user RSVP'd "yes" and at least one of their assignment-based * authenticated user RSVP'd "yes" and at least one strictly higher-ranked
* direct leaders also RSVP'd "yes". The client uses this to prompt mission * co-attendee also RSVP'd "yes". The client uses this to prompt mission
* feedback. Leader entries carry identity only — no rater/comment data. * feedback. Leader entries carry identity only, no rater/comment data.
*/ */
export async function GET(req: NextRequest) { export async function GET(req: NextRequest) {
const payload = await getPayload({ config: await config }); const payload = await getPayload({ config: await config });

View file

@ -75,7 +75,7 @@ Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit
## Feature flow: evaluation reminders ## 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 ## Feature flow: imminent op reminder

View file

@ -8,10 +8,10 @@ import { isMissionEvaluable } from "@/lib/evaluations";
/** /**
* Evaluation reminder service: after a mission becomes evaluable (completed, or * Evaluation reminder service: after a mission becomes evaluable (completed, or
* its scheduled start has passed), every participant with a linked Discord * 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 * account gets a one-shot DM listing the co-attendees they may rate under the
* leader additionally gets a section asking them to rate the subordinates who * rank-based rules: juniors are prompted to rate their higher-ranked attendees,
* participated. Each DM links to the relevant profile pages, where the rating * seniors are prompted to rate their lower-ranked ones. Each DM links to the
* dialog lives. * relevant profile pages, where the rating dialog lives.
* *
* The DM deliberately ignores `preferences.discord.enabled` (the notification * The DM deliberately ignores `preferences.discord.enabled` (the notification
* bridge opt-in): that toggle defaults to false and is not yet exposed in the * bridge opt-in): that toggle defaults to false and is not yet exposed in the

View file

@ -9,6 +9,13 @@ import { PERFORMANCE_LEVELS } from "@/lib/evaluations/levels";
* service layer (`upsertEvaluation` in `src/lib/evaluations`), not by a DB * service layer (`upsertEvaluation` in `src/lib/evaluations`), not by a DB
* constraint. * 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 * 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
* receive raw rows over REST — the profile UI consumes pre-aggregated, rater-free * receive raw rows over REST — the profile UI consumes pre-aggregated, rater-free
@ -56,15 +63,15 @@ export const Evaluations: CollectionConfig = {
type: "select", type: "select",
options: [ options: [
{ {
label: "Leader (direct)", label: "Leader (junior rates senior)",
value: "leader-direct", value: "leader-direct",
}, },
{ {
label: "Leader (indirect)", label: "Leader (legacy indirect)",
value: "leader-indirect", value: "leader-indirect",
}, },
{ {
label: "Subordinate", label: "Subordinate (senior rates junior)",
value: "subordinate", value: "subordinate",
}, },
], ],

View file

@ -127,8 +127,9 @@ export function LeadershipEvaluationDialog({
<DialogHeader> <DialogHeader>
<DialogTitle>Rate leadership</DialogTitle> <DialogTitle>Rate leadership</DialogTitle>
<DialogDescription> <DialogDescription>
Submit a new rating or update your existing rating for one completed mission. Your Submit a new rating or update your existing rating for one completed mission. Ratings
rating is included anonymously in the leadership aggregate. follow rank: only operators strictly above or below your own rank can be rated here.
Your rating is included anonymously.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>

View file

@ -78,7 +78,7 @@ export function LeadershipEvaluationSection({
)} )}
</CardTitle> </CardTitle>
<CardDescription> <CardDescription>
Anonymous feedback from operators who have served alongside this leader. Anonymous ratings from unit members ranked above or below this operator.
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>

View file

@ -6,10 +6,18 @@ import {
type PerformanceLevelId, type PerformanceLevelId,
} from "./levels"; } from "./levels";
import { missionEndTime } from "@/lib/intelligence/missionLifecycle"; import { missionEndTime } from "@/lib/intelligence/missionLifecycle";
import { rankDirection } from "./ranks";
type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>; type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
/** 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"; export type EvaluationKind = "leader-direct" | "leader-indirect" | "subordinate";
/** Shape of an evaluations doc as consumed by this service (depth 0). */ /** 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 * 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". Used for leader * evidence we treat as "this user took part in the mission". Under the rank-based
* ratings (direct and indirect). Subordinate ratings do not require it — the * rules at least one side of the pair must have a yes-RSVP for the mission, so
* command relationship itself is the basis. * every rating is anchored to an op one of them actually attended.
*/ */
export async function hasYesAttendance( export async function hasYesAttendance(
payload: PayloadType, payload: PayloadType,
@ -83,45 +91,6 @@ export async function hasYesAttendance(
return res.docs.length > 0; 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<boolean> {
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<boolean> {
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 { export interface EligibilityResult {
eligible: boolean; eligible: boolean;
kind?: EvaluationKind; kind?: EvaluationKind;
@ -130,16 +99,18 @@ export interface EligibilityResult {
/** /**
* Determines whether `raterId` may evaluate `rateeId` for `missionId`, and under * 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. * - You cannot evaluate yourself.
* - The mission must be completed/past (see {@link isMissionEvaluable}). * - The mission must be completed/past (see {@link isMissionEvaluable}).
* - `leader-direct`: the ratee directly leads the rater's assignment AND the rater * - Strict rank gap: the rater must hold a strictly lower or strictly higher
* participated in the mission (yes-RSVP proxy). * rank than the ratee (per the ranks ladder). Equal ranks, or either side
* - `subordinate`: the rater directly leads the ratee's assignment. No RSVP * without a resolvable profile rank, are never eligible. Squad/division or
* required — the command relationship itself is the basis. * assignment membership plays no role.
* - `leader-indirect`: the rater participated in the mission and the ratee leads at * - Rater strictly below ratee -> `leader-direct` (upward rating of a senior).
* least one assignment, but did not directly lead the rater. * - 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( export async function evaluateEligibility(
payload: PayloadType, payload: PayloadType,
@ -173,25 +144,22 @@ export async function evaluateEligibility(
return { eligible: false, reason: "This mission is not completed or past yet." }; return { eligible: false, reason: "This mission is not completed or past yet." };
} }
const participated = await hasYesAttendance(payload, raterId, missionId); const direction = await rankDirection(payload, raterId, rateeId);
const rateeLeadsRater = await isDirectLeaderOf(payload, rateeId, raterId); if (!direction) {
if (rateeLeadsRater) { return {
if (!participated) { eligible: false,
return { eligible: false, reason: "No attendance recorded for this mission." }; reason: "Evaluations require a strict rank difference (rate those above or below you).",
} };
return { eligible: true, kind: "leader-direct" };
} }
const raterLeadsRatee = await isDirectLeaderOf(payload, raterId, rateeId); const attended =
if (raterLeadsRatee) { (await hasYesAttendance(payload, raterId, missionId)) ||
return { eligible: true, kind: "subordinate" }; (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: direction === "upward" ? "leader-direct" : "subordinate" };
return { eligible: true, kind: "leader-indirect" };
}
return { eligible: false, reason: "No leadership relationship for this mission." };
} }
export interface UpsertEvaluationInput { export interface UpsertEvaluationInput {

View file

@ -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<Map<number, number>> {
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<number, number>();
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<RankDirection | null> {
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;
}

View file

@ -6,17 +6,19 @@ import type { Payload } from "payload";
* Rules (aligned with `evaluateEligibility` in ./index.ts): * Rules (aligned with `evaluateEligibility` in ./index.ts):
* - Participants = users with a "yes" RSVP for the mission (the documented * - Participants = users with a "yes" RSVP for the mission (the documented
* participation proxy — same as the profile-page rating dialog). * participation proxy — same as the profile-page rating dialog).
* - Every participant is reminded to rate their direct leader(s) — eligible as * - Pairing follows rank, not assignments: every pair of participants with a
* `leader-direct` (and, for any other leader, `leader-indirect`). * strict rank gap is reminded in both directions. The junior is prompted to
* - Every leader of an assignment containing a participant is reminded to rate * rate the senior (`leader-direct`); the senior is prompted to rate the
* that participant — eligible as `subordinate` (no RSVP required for leaders). * junior (`subordinate`).
* - Self-pairs are skipped; a user who is both a participant and a leader gets a * - Same-rank participants and participants without a profile rank form no
* single merged DM. * 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 * This module is payload-only (no Discord imports) so the recipient plan is
* testable independently of the bot service. * testable independently of the bot service.
*/ */
import { getUserRankIndexes } from "./ranks";
type PayloadType = Payload; type PayloadType = Payload;
export interface ReminderLink { export interface ReminderLink {
@ -42,18 +44,6 @@ export interface EvaluationReminderPlan {
recipients: ReminderRecipient[]; 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 { function extractId(value: unknown): number | null {
if (typeof value === "number") return value; if (typeof value === "number") return value;
if (value && typeof value === "object" && typeof (value as { id?: unknown }).id === "number") { if (value && typeof value === "object" && typeof (value as { id?: unknown }).id === "number") {
@ -98,30 +88,13 @@ export async function computeEvaluationReminderPlan(
return { missionId, recipients: [] }; return { missionId, recipients: [] };
} }
// 2. Command graph from assignments: leader -> members, member -> leaders. // 2. Rank ladder index per participant. Participants without a profile rank
const assignments = await payload.find({ // are left out: eligibility needs a strict rank gap on both sides.
collection: "assignments", const rankIndexes = await getUserRankIndexes(payload, participantIds);
where: { leader: { not_equals: null } }, const ranked = participantIds.filter((id) => rankIndexes.has(id));
limit: 1000,
depth: 0,
overrideAccess: true,
});
const leadersOf = new Map<number, Set<number>>();
const membersLedBy = new Map<number, Set<number>>();
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);
}
}
// 3. Merge both roles per user: participant -> rate leaders; leader of a // 3. Pair every strict-rank-gap combination among the ranked participants:
// participant -> rate that participant. // the junior rates the senior upward, the senior rates the junior downward.
const plan = new Map<number, { rateLeaders: Map<number, number>; rateSubordinates: Map<number, number> }>(); const plan = new Map<number, { rateLeaders: Map<number, number>; rateSubordinates: Map<number, number> }>();
const ensure = (userId: number) => { const ensure = (userId: number) => {
let entry = plan.get(userId); let entry = plan.get(userId);
@ -132,11 +105,17 @@ export async function computeEvaluationReminderPlan(
return entry; return entry;
}; };
for (const participantId of participantIds) { for (let i = 0; i < ranked.length; i += 1) {
ensure(participantId); // even with no direct leader they may still be rated by theirs for (let j = i + 1; j < ranked.length; j += 1) {
for (const leaderId of leadersOf.get(participantId) ?? []) { const a = ranked[i];
ensure(participantId).rateLeaders.set(leaderId, participantId); const b = ranked[j];
ensure(leaderId).rateSubordinates.set(participantId, leaderId); 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);
} }
} }

View file

@ -1,4 +1,5 @@
import type { Payload } from "payload"; import type { Payload } from "payload";
import { getUserRankIndexes } from "@/lib/evaluations/ranks";
/** /**
* Mission feedback reminder window: a completed main operation only prompts for * Mission feedback reminder window: a completed main operation only prompts for
@ -13,7 +14,7 @@ export interface ReminderLeader {
displayName: string; 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 { export interface MissionReminder {
missionId: number; missionId: number;
missionName: string; missionName: string;
@ -28,35 +29,16 @@ function refId(value: number | { id: number } | null | undefined): number | null
return 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<number[]> {
const res = await payload.find({
collection: "assignments",
where: { members: { contains: userId } },
limit: 100,
depth: 0,
overrideAccess: true,
});
const ids = new Set<number>();
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 * Recently completed main operations that need feedback from `user`: the mission
* is a main operation, transitioned to Completed within the last 72 hours * is a main operation, transitioned to Completed within the last 72 hours
* (`ownershipAndStatus.completedAt`), `user` RSVP'd "yes", and at least one of * (`ownershipAndStatus.completedAt`), `user` RSVP'd "yes", and at least one
* the user's assignment-based direct leaders also RSVP'd "yes". * 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 * 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( export async function getMissionReminders(
payload: Payload, payload: Payload,
@ -125,9 +107,14 @@ export async function getMissionReminders(
yesUsers.add(userId); yesUsers.add(userId);
} }
const leaderIds = await findDirectLeaderIds(payload, user.id); // Rank model: the people the user is prompted to rate are the co-attendees
if (leaderIds.length === 0) return []; // holding a strictly higher rank. No profile rank means nothing rateable.
const leaderSet = new Set(leaderIds); 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<{ const eligible: Array<{
mission: (typeof missionsRes.docs)[number]; mission: (typeof missionsRes.docs)[number];
@ -137,8 +124,12 @@ export async function getMissionReminders(
for (const { mission, completedAt } of candidates) { for (const { mission, completedAt } of candidates) {
const yesUsers = yesByMission.get(mission.id) ?? new Set<number>(); const yesUsers = yesByMission.get(mission.id) ?? new Set<number>();
if (!yesUsers.has(user.id)) continue; // the user must have RSVP'd "yes" if (!yesUsers.has(user.id)) continue; // the user must have RSVP'd "yes"
const leaders = [...yesUsers].filter((id) => leaderSet.has(id)); const leaders = [...yesUsers].filter((id) => {
if (leaders.length === 0) continue; // at least one direct leader must have RSVP'd "yes" 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 }); eligible.push({ mission, completedAt, leaderIds: leaders });
} }

View file

@ -27,11 +27,14 @@ describe("Leadership evaluations", () => {
let participantE: User; let participantE: User;
let noRsvpF: User; let noRsvpF: User;
let outsiderD: User; let outsiderD: User;
let assignmentId: number; let juniorRankId: number;
let midRankId: number;
let seniorRankId: number;
let missionCompletedId: number; let missionCompletedId: number;
let missionFutureId: number; let missionFutureId: number;
const userIds: number[] = []; const userIds: number[] = [];
const rankIds: number[] = [];
const attendanceIds: number[] = []; const attendanceIds: number[] = [];
const evaluationIds: number[] = []; const evaluationIds: number[] = [];
@ -53,6 +56,41 @@ describe("Leadership evaluations", () => {
return user; 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<number> => {
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<void> => {
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 ( const makeMission = async (
label: string, label: string,
status: Mission["ownershipAndStatus"]["status"], status: Mission["ownershipAndStatus"]["status"],
@ -123,6 +161,10 @@ describe("Leadership evaluations", () => {
})) as unknown as Campaign; })) as unknown as Campaign;
campaignId = campaign.id; campaignId = campaign.id;
juniorRankId = await makeRank("Jr");
midRankId = await makeRank("Mid");
seniorRankId = await makeRank("Sr");
leaderA = await makeUser("leader-a"); leaderA = await makeUser("leader-a");
subordinateB = await makeUser("subordinate-b"); subordinateB = await makeUser("subordinate-b");
participantC = await makeUser("participant-c"); participantC = await makeUser("participant-c");
@ -130,18 +172,24 @@ describe("Leadership evaluations", () => {
noRsvpF = await makeUser("no-rsvp-f"); noRsvpF = await makeUser("no-rsvp-f");
outsiderD = await makeUser("outsider-d"); outsiderD = await makeUser("outsider-d");
const assignment = await payload.create({ // Rank ladder: leaderA (Sr) > C/E (Mid) > B/F (Jr). The Users hook gives
collection: "assignments", // every new profile a default bottom rank, and profiles require one, so D's
data: { // profile is deleted outright to exercise the no-rank path.
name: `${RUN} Squad`, await setProfileRank(leaderA.id, seniorRankId);
type: "squad", await setProfileRank(subordinateB.id, juniorRankId);
leader: leaderA.id, await setProfileRank(participantC.id, midRankId);
members: [subordinateB.id, noRsvpF.id], await setProfileRank(participantE.id, midRankId);
}, await setProfileRank(noRsvpF.id, juniorRankId);
overrideAccess: true, const dProfiles = await payload.find({
collection: "profiles",
where: { user: { equals: outsiderD.id } },
limit: 5,
depth: 0, 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(); const past = new Date();
past.setDate(past.getDate() - 7); past.setDate(past.getDate() - 7);
@ -181,9 +229,9 @@ describe("Leadership evaluations", () => {
.delete({ collection: "mission-attendances", id, overrideAccess: true }) .delete({ collection: "mission-attendances", id, overrideAccess: true })
.catch(() => {}); .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]) { for (const id of [missionCompletedId, missionFutureId]) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {}); await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
} }
@ -248,11 +296,16 @@ describe("Leadership evaluations", () => {
expect(isMissionEvaluable("Active", justStarted, 240)).toBe(false); 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 = [ 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 }, 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" }, { 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) { for (const { input, expectKind } of cases) {
const result = await evaluateEligibility(payload, { ...input, missionId: missionCompletedId }); const result = await evaluateEligibility(payload, { ...input, missionId: missionCompletedId });
@ -260,22 +313,32 @@ describe("Leadership evaluations", () => {
expect(result.kind).toBe(expectKind); expect(result.kind).toBe(expectKind);
} }
// In A's assignment but never RSVPed yes — the participation proxy fails. // Equal ranks can never rate each other, even with both on the roster.
const noRsvp = await evaluateEligibility(payload, { const peer = await evaluateEligibility(payload, {
raterId: noRsvpF.id, raterId: participantE.id,
rateeId: leaderA.id, rateeId: participantC.id,
missionId: missionCompletedId, missionId: missionCompletedId,
}); });
expect(noRsvp.eligible).toBe(false); expect(peer.eligible).toBe(false);
expect(noRsvp.reason).toBe("No attendance recorded for this mission."); expect(peer.reason).toContain("strict rank");
// No leadership relationship at all. // Rankless raters are ineligible regardless of attendance.
const outsider = await evaluateEligibility(payload, { const rankless = await evaluateEligibility(payload, {
raterId: outsiderD.id, raterId: outsiderD.id,
rateeId: leaderA.id, rateeId: leaderA.id,
missionId: missionCompletedId, 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. // Self-rating is always rejected.
const selfRating = await evaluateEligibility(payload, { const selfRating = await evaluateEligibility(payload, {

View file

@ -8,7 +8,7 @@ import { randomUUID } from "node:crypto";
import { NextRequest } from "next/server"; import { NextRequest } from "next/server";
import { afterAll, beforeAll, describe, expect, it } from "vitest"; 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 { GET } from "@/app/api/mission-reminder/route";
import { getMissionReminders } from "@/lib/intelligence/missionReminder"; import { getMissionReminders } from "@/lib/intelligence/missionReminder";
@ -73,7 +73,7 @@ describe("Mission feedback reminder", () => {
const userIds: number[] = []; const userIds: number[] = [];
const missionIds: number[] = []; const missionIds: number[] = [];
const attendanceIds: number[] = []; const attendanceIds: number[] = [];
const assignmentIds: number[] = []; const rankIds: number[] = [];
let memberId: number; let memberId: number;
let leaderAId: number; let leaderAId: number;
@ -92,7 +92,7 @@ describe("Mission feedback reminder", () => {
let staleMainId: number; // main, 73h ago (past the window) let staleMainId: number; // main, 73h ago (past the window)
let noStampId: number; // main, completion stamp cleared -> fail closed let noStampId: number; // main, completion stamp cleared -> fail closed
let userNoId: number; // member RSVP'd "no" 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. // Boundary fixtures relative to fixedNow.
let boundaryExactId: number; // exactly fixedNow - 72h -> included at fixedNow let boundaryExactId: number; // exactly fixedNow - 72h -> included at fixedNow
@ -148,21 +148,50 @@ describe("Mission feedback reminder", () => {
strangerId = stranger.id; strangerId = stranger.id;
lonerId = loner.id; lonerId = loner.id;
// The member belongs to two squads, so their direct leaders are both // Rank-based pairing (same model as @/lib/evaluations/ranks): leaderA and
// leaders (same model as isDirectLeaderOf in @/lib/evaluations). // leaderB strictly outrank member/stranger/loner, who share one junior rank.
const makeAssignment = async (label: string, leaderId: number): Promise<Assignment> => { // Creation order ascends in seniority, matching the promotions specs.
const assignment = (await payload.create({ const makeRank = async (label: string): Promise<number> => {
collection: "assignments", const rank = await payload.create({
data: { name: `${RUN} ${label}`, type: "squad", leader: leaderId, members: [memberId] }, collection: "ranks",
data: {
name: `${RUN} ${label}`,
abbreviation: `${RUN}-${label.toLowerCase()}`,
description: `${RUN} test rank`,
},
overrideAccess: true, overrideAccess: true,
depth: 0, depth: 0,
})) as unknown as Assignment; });
assignmentIds.push(assignment.id); rankIds.push(rank.id);
return assignment; return rank.id;
}; };
await makeAssignment("Squad A", leaderAId); const setProfileRank = async (userId: number, rankId: number): Promise<void> => {
await makeAssignment("Squad B", leaderBId); 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 ( const makeMission = async (
label: string, label: string,
@ -272,7 +301,7 @@ describe("Mission feedback reminder", () => {
await makeMission("leader-no", "main", new Date(fixedNow.getTime() - DAY).toISOString()) await makeMission("leader-no", "main", new Date(fixedNow.getTime() - DAY).toISOString())
).id; ).id;
await addAttendance(leaderNoId, memberId, "yes"); 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. // Boundary fixtures relative to fixedNow.
boundaryExactId = ( boundaryExactId = (
@ -308,8 +337,8 @@ describe("Mission feedback reminder", () => {
for (const id of missionIds) { for (const id of missionIds) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {}); await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
} }
for (const id of assignmentIds) { for (const id of rankIds) {
await payload.delete({ collection: "assignments", id, overrideAccess: true }).catch(() => {}); await payload.delete({ collection: "ranks", id, overrideAccess: true }).catch(() => {});
} }
// User deletion trips FK constraints unless the hook-provisioned personal // User deletion trips FK constraints unless the hook-provisioned personal
// bank account and profile are removed first. // bank account and profile are removed first.
@ -355,7 +384,7 @@ describe("Mission feedback reminder", () => {
expect(res.status).toBe(401); 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)); const res = await GET(request(memberToken));
expect(res.status).toBe(200); expect(res.status).toBe(200);
const body = (await res.json()) as { reminders: Array<Record<string, unknown>> }; const body = (await res.json()) as { reminders: Array<Record<string, unknown>> };
@ -387,13 +416,13 @@ describe("Mission feedback reminder", () => {
expect(leaders[0].username).toBe(`${RUN}-leader-a`); expect(leaders[0].username).toBe(`${RUN}-leader-a`);
expect(leaders[0].displayName).toBe("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 multi = byMissionId.get(multiLeaderId)!;
const multiLeaderIds = (multi.leaders as Array<{ id: number }>).map((leader) => leader.id); const multiLeaderIds = (multi.leaders as Array<{ id: number }>).map((leader) => leader.id);
expect([...multiLeaderIds].sort()).toEqual([leaderAId, leaderBId].sort()); 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)); const res = await GET(request(lonerToken));
expect(res.status).toBe(200); expect(res.status).toBe(200);
const body = (await res.json()) as { reminders: unknown[] }; const body = (await res.json()) as { reminders: unknown[] };