1
0
Fork 0
polaris-task-force/src/lib/evaluations/reminders.ts
Z8MB1E 977f841056 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
2026-10-25 02:53:49 -04:00

154 lines
5.3 KiB
TypeScript

import type { Payload } from "payload";
/**
* Recipient computation for the post-mission evaluation reminder DMs (Discord bot).
*
* 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).
* - 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 {
userId: number;
username: string;
displayName: string;
/** App-relative link to the ratee's profile page where the rating dialog lives. */
profilePath: string;
}
export interface ReminderRecipient {
userId: number;
discordId: string | null;
/** Leaders this participant should rate (may be empty). */
rateLeaders: ReminderLink[];
/** Subordinates this leader should rate (may be empty). */
rateSubordinates: ReminderLink[];
}
export interface EvaluationReminderPlan {
missionId: number;
/** Only users with at least one actionable rating are included. */
recipients: ReminderRecipient[];
}
function extractId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value && typeof value === "object" && typeof (value as { id?: unknown }).id === "number") {
return (value as { id: number }).id;
}
return null;
}
function toLink(user: { id: number; username?: string | null; displayName?: string | null }): ReminderLink {
const username = user.username ?? `user-${user.id}`;
return {
userId: user.id,
username,
displayName: user.displayName || username,
profilePath: `/profile/${username}`,
};
}
/**
* Computes who should be reminded to submit evaluations for a mission.
* `missionId` must already be evaluable (see `isMissionEvaluable`) — this
* function does not re-check eligibility.
*/
export async function computeEvaluationReminderPlan(
payload: PayloadType,
missionId: number,
): Promise<EvaluationReminderPlan> {
// 1. Participants: yes-RSVP users for this mission.
const attendance = await payload.find({
collection: "mission-attendances",
where: {
and: [{ mission: { equals: missionId } }, { response: { equals: "yes" } }],
},
limit: 1000,
depth: 0,
overrideAccess: true,
});
const participantIds = [
...new Set(attendance.docs.map((doc) => extractId(doc.user)).filter((id): id is number => id !== null)),
];
if (participantIds.length === 0) {
return { missionId, recipients: [] };
}
// 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. 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<number, { rateLeaders: Map<number, number>; rateSubordinates: Map<number, number> }>();
const ensure = (userId: number) => {
let entry = plan.get(userId);
if (!entry) {
entry = { rateLeaders: new Map(), rateSubordinates: new Map() };
plan.set(userId, entry);
}
return entry;
};
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);
}
}
// 4. Resolve user docs (discordId / username / displayName) for everyone in the plan.
const userIds = [...plan.keys()];
const users = await payload.find({
collection: "users",
where: { id: { in: userIds } },
limit: 1000,
depth: 0,
overrideAccess: true,
});
const userById = new Map(users.docs.map((u) => [u.id, u]));
const recipients: ReminderRecipient[] = [];
for (const [userId, entry] of plan) {
const rateLeaders = [...entry.rateLeaders.keys()]
.map((id) => userById.get(id))
.filter((u): u is NonNullable<typeof u> => Boolean(u))
.map(toLink);
const rateSubordinates = [...entry.rateSubordinates.keys()]
.map((id) => userById.get(id))
.filter((u): u is NonNullable<typeof u> => Boolean(u))
.map(toLink);
if (rateLeaders.length === 0 && rateSubordinates.length === 0) continue;
const user = userById.get(userId);
recipients.push({
userId,
discordId: user?.discordId ?? null,
rateLeaders,
rateSubordinates,
});
}
return { missionId, recipients };
}