diff --git a/src/app/(frontend)/intelligence/missions/actions.ts b/src/app/(frontend)/intelligence/missions/actions.ts index 47773747..25e8d566 100644 --- a/src/app/(frontend)/intelligence/missions/actions.ts +++ b/src/app/(frontend)/intelligence/missions/actions.ts @@ -14,6 +14,9 @@ import { import { hasPermission } from "@/utils/access-control/hasPermission"; import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; import { emitGameEvent } from "@/utils/event-log/emit"; +import { submitMissionRating as submitMissionRatingService } from "@/lib/missionRatings"; +import { recordContribution } from "@/lib/contributions"; +import { CONTRIBUTION_TYPE_MISSION_RATING, MISSION_RATING_XP } from "@/lib/missionRatings/xp"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { nextDayKey, @@ -1051,3 +1054,72 @@ export async function removeMissionRoleSignup(input: { : { success: false, error: message }; } } + +// --------------------------------------------------------------------------- +// Mission ratings (post-op survey) +// --------------------------------------------------------------------------- + +export async function submitMissionRating(input: { + missionId: number; + values: Record; + comment?: string | null; +}): Promise }>> { + try { + const { payload, user } = await authenticate(); + const userId = user.id as number; + + // Verify the caller can actually see this mission before accepting a rating. + const mission = await payload + .findByID({ + collection: "missions", + id: input.missionId, + depth: 0, + user, + overrideAccess: false, + }) + .catch(() => null); + if (!mission) { + return { success: false, error: "You do not have access to this mission." }; + } + + const ratings = await submitMissionRatingService(payload, { + missionId: input.missionId, + userId, + values: input.values, + comment: input.comment ?? null, + }); + + // Award contribution XP for completing the survey. + try { + await recordContribution(payload, { + userId, + type: CONTRIBUTION_TYPE_MISSION_RATING, + pointsOverride: MISSION_RATING_XP, + sourceCollection: "missions", + sourceId: input.missionId, + // Idempotency must be per (user, mission): the sourceId is the mission, + // which is shared across raters, so the discriminator carries the rater. + dedupeSuffix: `user:${userId}`, + summary: `Rated mission "${mission.name || `Mission #${input.missionId}`}"`, + actorId: userId, + missionId: input.missionId, + }); + } catch (xpError) { + payload.logger.warn( + `Mission rating submitted, but contribution XP recording failed: ${ + xpError instanceof Error ? xpError.message : "unknown error" + }`, + ); + } + + return { success: true, data: { ratings } }; + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + if (message === "You have already submitted a rating for this mission.") { + return { success: false, error: message }; + } + return message === "Unauthorized" + ? { success: false, error: "You must be logged in." } + : { success: false, error: message }; + } +} diff --git a/src/lib/contributions/rules.ts b/src/lib/contributions/rules.ts index 70688f4b..96399547 100644 --- a/src/lib/contributions/rules.ts +++ b/src/lib/contributions/rules.ts @@ -15,6 +15,7 @@ export const CONTRIBUTION_TYPES = [ "wiki-page-edit", "mission-map-marker", "survey-completion", + "mission-rating-completion", "journal-publish", "manual", ] as const; @@ -31,6 +32,7 @@ export const CONTRIBUTION_SOURCE_COLLECTIONS = [ "mission-map-markers", "form-submissions", "journals", + "missions", "manual", ] as const; @@ -95,6 +97,16 @@ export const CONTRIBUTION_RULES: Record = { maxPerMission: null, minEditDeltaChars: null, }, + "mission-rating-completion": { + type: "mission-rating-completion", + label: "Mission rating submitted", + points: 50, + mode: "instant", + description: "Submitted the post-op mission rating survey.", + dailyCap: 50, + maxPerMission: null, + minEditDeltaChars: null, + }, "journal-publish": { type: "journal-publish", label: "Journal entry published", diff --git a/src/lib/missionRatings/index.ts b/src/lib/missionRatings/index.ts new file mode 100644 index 00000000..a02abc0a --- /dev/null +++ b/src/lib/missionRatings/index.ts @@ -0,0 +1,387 @@ +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; + } | null; +} + +/** + * 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 (!(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 + | { ownershipAndStatus?: { status?: string | null; completedAt?: string | null }; missionRating?: { customFactors?: Array<{ label: string }> | null } } + | null; + + if (!mission) throw new Error("Mission not found."); + 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; + /** 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 isEligible = userId !== null && (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, + 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 };