import { MISSION_RATING_CORE_FACTORS, RATING_ANONYMITY_THRESHOLD, RATING_VALUE_MAX, RATING_VALUE_MIN, RATING_VALUE_OPTIONS, RATING_WINDOW_DAYS, isRatingValue, } from "./factors"; type PayloadType = Awaited>; /** A single factor rating (stored on the `ratings` array of a mission-ratings doc). */ export interface MissionRatingEntry { factor: string; value: number; } /** A mission as consumed by this service (depth 0). */ interface MissionRatingMission { id: number; ownershipAndStatus?: { status?: string | null; completedAt?: string | null; authors?: Array | null; } | null; } /** * Whether `userId` is one of the mission's authors. Authors ran or planned the * op, so they may not rate it. Authors are a relationship array: entries are * either bare ids or populated docs, depending on depth. */ export function isMissionAuthor( mission: MissionRatingMission, userId: number, ): boolean { const authors = mission.ownershipAndStatus?.authors ?? []; return authors.some((a) => (typeof a === "number" ? a : a.id) === userId); } /** * Whether the rating window is open for a mission at `now`. The window opens * when the mission is marked Completed and stays open for RATING_WINDOW_DAYS from * `completedAt`. A mission manually re-set to Completed re-opens its window. */ export function isRatingWindowOpen( status: string | null | undefined, completedAt: string | null | undefined, now: Date = new Date(), ): boolean { if (status !== "Completed") return false; if (!completedAt) return false; const start = new Date(completedAt).getTime(); if (Number.isNaN(start)) return false; const end = start + RATING_WINDOW_DAYS * 24 * 60 * 60 * 1000; const nowMs = now.getTime(); return nowMs >= start && nowMs <= end; } async function hasYesAttendance( payload: PayloadType, userId: number, missionId: number, ): Promise { const res = await payload.find({ collection: "mission-attendances", where: { and: [ { user: { equals: userId } }, { mission: { equals: missionId } }, { response: { equals: "yes" } }, ], }, limit: 1, depth: 0, overrideAccess: true, }); return res.docs.length > 0; } async function hasRated( payload: PayloadType, missionId: number, userId: number, ): Promise { const res = await payload.find({ collection: "mission-ratings", where: { and: [{ mission: { equals: missionId } }, { user: { equals: userId } }], }, limit: 1, depth: 0, overrideAccess: true, }); return res.docs.length > 0; } /** * Whether `userId` may currently rate `mission`: it must be Completed and within * the window, the user must have a yes-RSVP, and the user must not have already * submitted a (final) rating. */ export async function isRatingAvailable( payload: PayloadType, mission: MissionRatingMission, userId: number, now: Date = new Date(), ): Promise { if (!isRatingWindowOpen(mission.ownershipAndStatus?.status, mission.ownershipAndStatus?.completedAt, now)) { return false; } if (isMissionAuthor(mission, userId)) return false; if (!(await hasYesAttendance(payload, userId, mission.id))) return false; if (await hasRated(payload, mission.id, userId)) return false; return true; } export interface SubmitMissionRatingInput { missionId: number; userId: number; /** Factor label -> 1-5 value. */ values: Record; /** Optional free-text comment. */ comment?: string | null; } /** * Validate and create one row per (rater, mission). Rejects (throws) when a * factor value is out of range, a factor is unknown (not a core factor and not * an authored custom factor), the window is closed, or the user already rated. * The uniqueness is enforced here in the service layer, not by a DB constraint. */ export async function submitMissionRating( payload: PayloadType, input: SubmitMissionRatingInput, ): Promise { const { missionId, userId, values, comment = null } = input; if (typeof values !== "object" || values === null || Object.keys(values).length === 0) { throw new Error("At least one factor rating is required."); } // Resolve the mission so custom factors are known. This must succeed and be // inside the window before we accept anything. const mission = (await payload .findByID({ collection: "missions", id: missionId, depth: 0, overrideAccess: true, }) .catch(() => null)) as unknown as | { id: number; ownershipAndStatus?: { status?: string | null; completedAt?: string | null; authors?: Array | null; }; missionRating?: { customFactors?: Array<{ label: string }> | null }; } | null; if (!mission) throw new Error("Mission not found."); if (isMissionAuthor(mission, userId)) { throw new Error("Mission authors cannot rate their own mission."); } if (!isRatingWindowOpen(mission.ownershipAndStatus?.status, mission.ownershipAndStatus?.completedAt)) { throw new Error("The rating window for this mission is closed."); } const customFactors = (mission.missionRating?.customFactors ?? []).map((f) => f.label); const knownFactors = new Set([...MISSION_RATING_CORE_FACTORS, ...customFactors]); const ratings: MissionRatingEntry[] = []; for (const [factor, value] of Object.entries(values)) { if (!isRatingValue(value)) { throw new Error(`Invalid rating for "${factor}": must be an integer between ${RATING_VALUE_MIN} and ${RATING_VALUE_MAX}.`); } if (!knownFactors.has(factor)) { throw new Error(`Unknown factor: "${factor}".`); } ratings.push({ factor, value }); } const already = await hasRated(payload, missionId, userId); if (already) { throw new Error("You have already submitted a rating for this mission."); } await payload.create({ collection: "mission-ratings", overrideAccess: true, depth: 0, data: { mission: missionId, user: userId, ratings: ratings.map((r) => ({ factor: r.factor, value: String(r.value) as "1" | "2" | "3" | "4" | "5", })), comment: comment?.trim() || null, }, }); return ratings; } export interface MissionRatingState { /** Window is open (Completed + within window). */ windowOpen: boolean; /** Window is not open. */ windowClosed: boolean; /** The current user has a yes-RSVP for the mission. */ isEligible: boolean; /** The current user is an author of the mission (authors never rate it). */ isAuthor: boolean; /** Window open AND eligible AND the user has not already rated. */ canRate: boolean; /** The user's existing ratings, or null when they have not rated yet. */ myValues: MissionRatingEntry[] | null; } /** * The rating state for `currentUser` on `mission`, computed during server render. * `myValues` is the user's already-submitted ratings (final), used to render the * read-only "you've rated" state. */ export async function getMissionRatingState( payload: PayloadType, mission: MissionRatingMission & { missionRating?: { customFactors?: Array<{ label: string }> | null }; }, userId: number | null, now: Date = new Date(), ): Promise { const windowOpen = isRatingWindowOpen( mission.ownershipAndStatus?.status, mission.ownershipAndStatus?.completedAt, now, ); const isAuthor = userId !== null && isMissionAuthor(mission, userId); const isEligible = userId !== null && !isAuthor && (await hasYesAttendance(payload, userId, mission.id)); let myValues: MissionRatingEntry[] | null = null; if (userId !== null) { const existing = await payload.find({ collection: "mission-ratings", where: { and: [{ mission: { equals: mission.id } }, { user: { equals: userId } }], }, limit: 1, depth: 0, overrideAccess: true, }); if (existing.docs.length > 0) { const doc = existing.docs[0] as unknown as { ratings?: MissionRatingEntry[] | null }; myValues = doc.ratings ? doc.ratings.map(normalizeEntry) : null; } } const canRate = windowOpen && isEligible && myValues === null && userId !== null; return { windowOpen, windowClosed: !windowOpen, isEligible, isAuthor, canRate, myValues, }; } export interface MissionRatingFactorAggregate { factor: string; average: number; /** Number of factor ratings feeding this average. */ count: number; /** 1-5 distribution counts. */ distribution: { value: number; count: number }[]; } export interface MissionRatingComment { /** Anonymized free-text comment (no user identity). */ text: string; } export interface MissionRatingAggregate { missionId: number; /** Distinct raters who submitted. */ raterCount: number; /** true when distinct raters >= ANONYMITY_THRESHOLD (breakdown + comments visible). */ visible: boolean; /** Per-factor averages/distributions, or null below the anonymity threshold. */ factors: MissionRatingFactorAggregate[] | null; /** Mean of every submitted factor value (1-5), or null when there are no ratings. */ overallAverage: number | null; /** Anonymized comments, or null below the anonymity threshold. */ comments: MissionRatingComment[] | null; } /** * Coerce a stored rating entry to the numeric shape the service uses. * * `value` is a Payload `select`, so a row read back from the DB carries it as a * string ("1".."5"). All the math below (overall average, per-factor average, * distribution counts) assumes a number: with a string, `sum + e.value` * concatenates ("1"+"2"="12") and `e.value === value` never matches. Normalize * at the read boundary so the pure math stays correct. */ function normalizeEntry(entry: MissionRatingEntry): MissionRatingEntry { return { factor: entry.factor, value: Number(entry.value) }; } /** Round a percentage to the same precision the leadership aggregate uses. */ function roundPercent(numerator: number, denominator: number): number { if (denominator === 0) return 0; return Math.round((numerator / denominator) * 10000) / 100; } /** * Public, rater-free aggregate of a mission's ratings. The per-factor breakdown * and comments are withheld until at least ANONYMITY_THRESHOLD distinct raters * have submitted, so a small group cannot be identified from the distribution. * The overall average (mean of every submitted factor value) and rater count are * always returned. Resolution and joins are kept at depth 0. */ export async function getMissionRatingAggregate( payload: PayloadType, missionId: number, ): Promise { const res = await payload.find({ collection: "mission-ratings", where: { mission: { equals: missionId } }, depth: 0, limit: 1000, sort: "createdAt", overrideAccess: true, }); const docs = res.docs as unknown as Array<{ user: number | { id: number }; ratings?: MissionRatingEntry[] | null; comment?: string | null; }>; const raterCount = new Set(docs.map((d) => typeof d.user === "object" ? d.user.id : d.user)).size; const visible = raterCount >= RATING_ANONYMITY_THRESHOLD; // Flatten every submitted (factor, value) pair. const allValues: MissionRatingEntry[] = []; for (const doc of docs) { for (const entry of doc.ratings ?? []) { allValues.push(normalizeEntry(entry)); } } const overallAverage = allValues.length > 0 ? Math.round((allValues.reduce((sum, e) => sum + e.value, 0) / allValues.length) * 100) / 100 : null; const factors: MissionRatingFactorAggregate[] | null = visible ? buildFactorAggregates(allValues) : null; const comments: MissionRatingComment[] | null = visible ? docs .map((d) => d.comment?.trim()) .filter((t): t is string => typeof t === "string" && t.length > 0) .map((text) => ({ text })) : null; return { missionId, raterCount, visible, factors, overallAverage, comments, }; } /** Build per-factor averages + 1-5 distributions from a flat list of entries. */ function buildFactorAggregates(values: MissionRatingEntry[]): MissionRatingFactorAggregate[] { const byFactor = new Map(); for (const entry of values) { const list = byFactor.get(entry.factor) ?? []; list.push(entry); byFactor.set(entry.factor, list); } const factors: MissionRatingFactorAggregate[] = []; for (const [factor, entries] of byFactor) { const distribution = RATING_VALUE_OPTIONS.map((value) => ({ value, count: entries.filter((e) => e.value === value).length, })); const count = entries.length; const average = Math.round((entries.reduce((sum, e) => sum + e.value, 0) / count) * 100) / 100; factors.push({ factor, average, count, distribution }); } // Order core factors first (in canonical order), then authored custom factors. const coreSet = new Set(MISSION_RATING_CORE_FACTORS); const ordered = [...factors].sort((a, b) => { const aCore = coreSet.has(a.factor); const bCore = coreSet.has(b.factor); if (aCore !== bCore) return aCore ? -1 : 1; const aIndex = MISSION_RATING_CORE_FACTORS.indexOf(a.factor as never); const bIndex = MISSION_RATING_CORE_FACTORS.indexOf(b.factor as never); if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex; return a.factor.localeCompare(b.factor); }); return ordered; } export { RATING_ANONYMITY_THRESHOLD, roundPercent };