diff --git a/src/app/(frontend)/intelligence/missions/[id]/page.tsx b/src/app/(frontend)/intelligence/missions/[id]/page.tsx index 61596d0b..dc0bc2ef 100644 --- a/src/app/(frontend)/intelligence/missions/[id]/page.tsx +++ b/src/app/(frontend)/intelligence/missions/[id]/page.tsx @@ -28,6 +28,11 @@ import { MissionRoleSignups } from "@/components/frontend/intelligence/MissionRo import { MissionLogistics } from "@/components/frontend/intelligence/MissionLogistics"; import { MissionComms } from "@/components/frontend/intelligence/MissionComms"; import { MissionAttendance } from "@/components/frontend/intelligence/MissionAttendance"; +import { MissionRating } from "@/components/frontend/intelligence/MissionRating"; +import { + getMissionRatingAggregate, + getMissionRatingState, +} from "@/lib/missionRatings"; import { SideOpControls } from "@/components/frontend/intelligence/SideOpControls"; import type { SideOpDialogOption } from "@/components/frontend/intelligence/CreateSideOpDialog"; import { isAdminOrDeveloper } from "@/lib/promotions/authority"; @@ -261,6 +266,10 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro })), }; + const ratingCustomFactors = (mission.missionRating?.customFactors ?? []).map((f) => f.label); + const ratingState = await getMissionRatingState(payload, mission, currentUser?.id ?? null); + const ratingAggregate = await getMissionRatingAggregate(payload, mission.id); + const attendanceCard = ( {/* ── Main Content (2/3) ──────────────────────────── */}
+ + Mission Details diff --git a/src/bot/events/interactionCreate.ts b/src/bot/events/interactionCreate.ts index 0b097bf4..f2da9f35 100644 --- a/src/bot/events/interactionCreate.ts +++ b/src/bot/events/interactionCreate.ts @@ -7,6 +7,7 @@ import { fetchAttendanceDocs, renderAttendanceEmbed, } from "@/bot/services/missionEmbeds"; +import { botConfig } from "@/bot/config"; import { attendanceClosedMessage, type AttendanceResponse, @@ -32,6 +33,26 @@ export const handleButtonInteraction = async ( payload: Payload, ): Promise => { const parts = interaction.customId.split(":"); + + // Post-op survey rating prompt: link back to the mission page to rate. + if (parts.length === 3 && parts[0] === "ptf-rate") { + const missionId = Number(parts[1]); + if (!Number.isInteger(missionId)) return; + try { + const url = `${botConfig.appUrl}/intelligence/missions/${missionId}`; + await interaction.reply({ + content: `Rate this op here: ${url}`, + flags: MessageFlags.Ephemeral, + }); + } catch (error) { + payload.logger.error( + `[Bot] Rating interaction failed for mission #${missionId}: ${errorMessage(error)}`, + ); + } + return; + } + + // Attendance roll-call buttons. if (parts.length !== 3 || parts[0] !== "ptf-att") { return; } diff --git a/src/bot/services/missionEmbeds.ts b/src/bot/services/missionEmbeds.ts index 69a6fa40..b69ffcf2 100644 --- a/src/bot/services/missionEmbeds.ts +++ b/src/bot/services/missionEmbeds.ts @@ -12,6 +12,11 @@ import path from "path"; import type { Payload } from "payload"; import type { Mission, MissionAttendance, ModList, User } from "@/payload-types"; import { getMissionAttendance, type MissionAttendanceSummary } from "@/lib/attendance"; +import { + getMissionRatingAggregate, + type MissionRatingAggregate, +} from "@/lib/missionRatings"; +import { MISSION_RATING_CORE_FACTORS } from "@/lib/missionRatings/factors"; import { ATTENDANCE_CHANGED_CHANNEL } from "@/lib/attendance/realtime"; import { botConfig } from "@/bot/config"; @@ -255,6 +260,102 @@ export const buildAttendanceRow = (missionId: number): ActionRowBuilder + JSON.stringify({ missionId: mission.id, v: RATING_EMBED_SCHEMA_VERSION }); + +export const renderRatingEmbed = ( + mission: Mission, + aggregate: MissionRatingAggregate, +): EmbedBuilder => { + const missionUrl = `${botConfig.appUrl}/intelligence/missions/${mission.id}`; + const overall = aggregate.overallAverage; + const fields = MISSION_RATING_CORE_FACTORS.map((factor) => { + const factorAggregate = aggregate.factors?.find((entry) => entry.factor === factor); + const value = factorAggregate + ? `${factorAggregate.average.toFixed(2)} / 5 · ${factorAggregate.count} rating${factorAggregate.count === 1 ? "" : "s"}` + : "No ratings yet"; + return { name: factor, value, inline: true }; + }); + return new EmbedBuilder() + .setTitle(`The op is complete: rate ${missionTitle(mission)}`) + .setURL(missionUrl) + .setDescription( + [ + "How did we do? Rate each factor below, then head to the mission page to add a comment.", + "", + `**Overall:** ${overall !== null ? overall.toFixed(2) : "—"} / 5 (${ + aggregate.raterCount + } rating${aggregate.raterCount === 1 ? "" : "s"})`, + ].join("\n"), + ) + .setColor(RATING_EMBED_COLOR) + .addFields( + ...fields, + { name: "Rate it", value: missionUrl, inline: false }, + ); +}; + +export const buildRatingRow = (missionId: number): ActionRowBuilder => + new ActionRowBuilder().addComponents( + new ButtonBuilder() + .setCustomId(`ptf-rate:${missionId}:rate`) + .setStyle(ButtonStyle.Primary) + .setLabel("⭐ Rate this op"), + ); + +export const getRatingEligibleMissions = async (payload: Payload): Promise => { + const res = await payload.find({ + collection: "missions", + overrideAccess: true, + depth: 1, + sort: "-classification.startDateTime", + limit: MAX_ELIGIBLE_MISSIONS, + where: { + and: [ + { "ownershipAndStatus.visibility": { equals: "unit" } }, + { "ownershipAndStatus.status": { equals: "Completed" } }, + { discordRatingSentAt: { exists: false } }, + ], + }, + }); + return res.docs as unknown as Mission[]; +}; + +export const postRatingEmbed = async ( + client: Client, + payload: Payload, + opsChannelId: string, + mission: Mission, +): Promise => { + const aggregate = await getMissionRatingAggregate(payload, mission.id); + const channel = await getOpsChannel(client, opsChannelId); + await channel.send({ + embeds: [renderRatingEmbed(mission, aggregate)], + components: [buildRatingRow(mission.id)], + }); + await payload.update({ + collection: "missions", + id: mission.id, + data: { discordRatingSentAt: new Date().toISOString() }, + overrideAccess: true, + }); + payload.logger.info( + `[Bot] Posted rating prompt for mission #${mission.id} (${mission.name}).`, + ); +}; + export const getOpsChannel = async ( client: Client, opsChannelId: string, @@ -719,6 +820,18 @@ export const reconcile = async (client: Client, payload: Payload): Promise ); } } + + // Post-op survey prompt: post once per completed, unit-visible mission. + const ratingEligible = await getRatingEligibleMissions(payload); + for (const mission of ratingEligible) { + try { + await postRatingEmbed(client, payload, opsChannelId, mission); + } catch (error) { + payload.logger.error( + `[Bot] Rating-embed reconcile failed for mission #${mission.id}: ${errorMessage(error)}`, + ); + } + } } catch (error) { payload.logger.error(`[Bot] Attendance embed reconcile failed: ${errorMessage(error)}`); } finally { diff --git a/src/components/frontend/intelligence/MissionRating.tsx b/src/components/frontend/intelligence/MissionRating.tsx new file mode 100644 index 00000000..8a6e9d29 --- /dev/null +++ b/src/components/frontend/intelligence/MissionRating.tsx @@ -0,0 +1,367 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { MessageSquareIcon, StarIcon } from "lucide-react"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { Textarea } from "@/components/ui/textarea"; +import { Badge } from "@/components/ui/badge"; +import { Separator } from "@/components/ui/separator"; +import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item"; +import { + MISSION_RATING_CORE_FACTORS, + RATING_ANONYMITY_THRESHOLD, +} from "@/lib/missionRatings/factors"; +import type { MissionRatingAggregate, MissionRatingState } from "@/lib/missionRatings"; +import { submitMissionRating } from "@/app/(frontend)/intelligence/missions/actions"; + +interface MissionRatingProps { + readonly missionId: number; + readonly state: MissionRatingState; + readonly aggregate: MissionRatingAggregate; + readonly customFactors: readonly string[]; + readonly reviewError?: string | null; +} + +function ratingStars(factors: readonly string[]): string[] { + return [...MISSION_RATING_CORE_FACTORS, ...factors]; +} + +function StarRating({ + value, + onChange, + readOnly = false, + size = "md", +}: { + value: number | null; + onChange?: (value: number) => void; + readOnly?: boolean; + size?: "sm" | "md" | "lg"; +}) { + const [hover, setHover] = useState(null); + const dims = { sm: "size-4", md: "size-6", lg: "size-10" } as const; + const current = hover ?? value; + + return ( +
!readOnly && setHover(null)} + > + {[1, 2, 3, 4, 5].map((star) => { + const on = current ?? 0; + const filled = star <= on; + return ( + + ); + })} +
+ ); +} + +function formatStars(value: number): string { + return value.toFixed(value % 1 === 0 ? 1 : 2); +} + +function RatingForm({ + missionId, + factors, + initialValue, + onSubmitError, + onSuccess, +}: { + missionId: number; + factors: readonly string[]; + initialValue: Record | null; + onSubmitError: string | null; + onSuccess: () => void; +}) { + const router = useRouter(); + const [values, setValues] = useState>(initialValue ?? {}); + const [comment, setComment] = useState(initialValue ? "" : ""); + const [pending, setPending] = useState(false); + const [error, setError] = useState(onSubmitError); + + const allRated = factors.every((factor) => values[factor] !== undefined); + + async function handleSubmit(event: React.FormEvent) { + event.preventDefault(); + if (!allRated) { + setError("Rate every factor before submitting."); + return; + } + setPending(true); + setError(null); + const res = await submitMissionRating({ missionId, values, comment }); + setPending(false); + if (!res.success) { + setError(res.error ?? "Failed to submit your rating."); + return; + } + onSuccess(); + router.refresh(); + } + + function setValue(factor: string, value: number) { + setValues((prev) => ({ ...prev, [factor]: value })); + setError(null); + } + + return ( +
+

+ Rate each factor from one to five stars. Your rating is final. +

+ {factors.map((factor) => ( +
+ {factor} + setValue(factor, v)} /> +
+ ))} +
+ +