1
0
Fork 0

feat(mission-ratings): UI, page wiring, discord embed + button handler

- MissionRating.tsx star form + overview renderer, wired into missions/[id]
- Discord rating embed + ptf-rate action row, posted on mission Completed
- interactionCreate ptf-rate handler replies ephemeral with mission URL
This commit is contained in:
Jason Fraley 2026-10-31 10:25:28 -04:00
parent f41a5bd5e4
commit ee622ff6dd
4 changed files with 517 additions and 0 deletions

View file

@ -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 = (
<MissionAttendance
missionId={mission.id}
@ -495,6 +504,13 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* ── Main Content (2/3) ──────────────────────────── */}
<div className="xl:col-span-2 flex flex-col gap-6">
<MissionRating
missionId={mission.id}
state={ratingState}
aggregate={ratingAggregate}
customFactors={ratingCustomFactors}
/>
<Item variant="outline">
<ItemHeader>
<ItemTitle>Mission Details</ItemTitle>

View file

@ -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<void> => {
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;
}

View file

@ -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<ButtonBu
.setLabel("❌ No"),
);
// Post-op survey embeds. Core factors only; custom (web-authored) factors are
// shown on the web mission page, never in Discord. The rating prompt is posted
// once, when a mission is marked Completed, and the marker keeps reconcile from
// reposting.
const RATING_EMBED_COLOR = 0xf59e0b;
/**
* Fingerprint of the completed-mission rating state so reconcile can skip
* embeds that haven't changed (anti-loop). Bump on layout-only changes.
*/
const RATING_EMBED_SCHEMA_VERSION = 1;
export const ratingHash = (mission: Mission): string =>
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<ButtonBuilder> =>
new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder()
.setCustomId(`ptf-rate:${missionId}:rate`)
.setStyle(ButtonStyle.Primary)
.setLabel("⭐ Rate this op"),
);
export const getRatingEligibleMissions = async (payload: Payload): Promise<Mission[]> => {
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<void> => {
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<void>
);
}
}
// 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 {

View file

@ -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<number | null>(null);
const dims = { sm: "size-4", md: "size-6", lg: "size-10" } as const;
const current = hover ?? value;
return (
<div
className="flex items-center gap-1"
role="radiogroup"
aria-label="Star rating"
onMouseLeave={() => !readOnly && setHover(null)}
>
{[1, 2, 3, 4, 5].map((star) => {
const on = current ?? 0;
const filled = star <= on;
return (
<button
key={star}
type="button"
role="radio"
aria-checked={value === star}
aria-label={`${star} star${star > 1 ? "s" : ""}`}
disabled={readOnly || onChange === undefined}
onMouseEnter={() => !readOnly && setHover(star)}
onClick={() => onChange?.(star)}
className={cn(
"rounded p-0.5 transition-colors",
!readOnly && onChange !== undefined && "cursor-pointer hover:bg-muted/60",
readOnly && "cursor-default",
)}
>
<StarIcon
className={cn(
dims[size],
filled ? "fill-amber-400 text-amber-400" : "text-muted-foreground/70",
)}
/>
</button>
);
})}
</div>
);
}
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<string, number> | null;
onSubmitError: string | null;
onSuccess: () => void;
}) {
const router = useRouter();
const [values, setValues] = useState<Record<string, number>>(initialValue ?? {});
const [comment, setComment] = useState<string>(initialValue ? "" : "");
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(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 (
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">
Rate each factor from one to five stars. Your rating is final.
</p>
{factors.map((factor) => (
<div key={factor} className="flex items-center gap-3">
<span className="w-24 shrink-0 text-sm font-medium">{factor}</span>
<StarRating value={values[factor] ?? null} onChange={(v) => setValue(factor, v)} />
</div>
))}
<div className="flex flex-col gap-1.5">
<label className="text-sm font-medium" htmlFor={`rating-comment-${missionId}`}>
Comment (optional)
</label>
<Textarea
id={`rating-comment-${missionId}`}
value={comment}
onChange={(event) => setComment(event.target.value)}
placeholder="Share feedback shown anonymously in the overview."
rows={3}
/>
</div>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
<div className="flex items-center gap-3">
<Button type="submit" disabled={pending || !allRated}>
{pending ? "Submitting…" : "Submit rating"}
</Button>
{!allRated && (
<span className="text-xs text-muted-foreground">Rate every factor to submit.</span>
)}
</div>
</form>
);
}
function YouRatedState({
state,
factors,
}: {
state: MissionRatingState;
factors: readonly string[];
}) {
const myValues = state.myValues;
if (!myValues) return null;
const byFactor = new Map(myValues.map((entry) => [entry.factor, entry.value]));
return (
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2 text-sm font-medium text-green-400">
<StarIcon className="size-4 fill-green-400" />
<span>You have already rated this mission. Your rating is final.</span>
</div>
{factors.map((factor) => {
const value = byFactor.get(factor);
if (value === undefined) return null;
return (
<div key={factor} className="flex items-center gap-3">
<span className="w-24 shrink-0 text-sm font-medium">{factor}</span>
<StarRating value={value} readOnly size="md" />
</div>
);
})}
</div>
);
}
function DistributionBar({ distribution, count }: { count: number; distribution: readonly { value: number; count: number }[] }) {
const total = distribution.reduce((sum, point) => sum + point.count, 0);
return (
<div className="flex flex-col gap-1">
<div className="flex h-2 overflow-hidden rounded-full bg-muted">
{distribution.map((point) => {
const width = total === 0 ? 0 : (point.count / total) * 100;
if (point.count === 0) return null;
return (
<div
key={point.value}
title={`${point.count} vote${point.count > 1 ? "s" : ""} at ${point.value} star${point.value > 1 ? "s" : ""}`}
className="h-full bg-amber-400/80"
style={{ width: `${width}%` }}
/>
);
})}
</div>
<div className="flex justify-between font-mono text-[10px] text-muted-foreground">
<span>1</span><span>2</span><span>3</span><span>4</span><span>5</span>
</div>
</div>
);
}
function Overview({ aggregate, factors }: { aggregate: MissionRatingAggregate; factors: readonly string[] }) {
const overall = aggregate.overallAverage;
return (
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-3 rounded-md border border-border bg-muted/30 p-4">
<div className="flex items-end justify-between gap-3">
<div className="flex flex-col gap-1">
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Overall rating
</span>
<span className="font-mono text-4xl font-semibold tracking-tight">
{overall !== null ? formatStars(overall) : "—"}
</span>
</div>
<span className="text-xs text-muted-foreground">
{aggregate.raterCount} rating{aggregate.raterCount === 1 ? "" : "s"}
</span>
</div>
</div>
{aggregate.visible ? (
<div className="flex flex-col gap-4">
{aggregate.factors?.map((factor) => (
<div key={factor.factor} className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<span className="text-sm font-medium">{factor.factor}</span>
<span className="font-mono text-xs text-muted-foreground">
{factor.average !== null ? formatStars(factor.average) : "—"} · {factor.count}
</span>
</div>
<DistributionBar distribution={factor.distribution} count={factor.count} />
</div>
))}
{aggregate.comments && aggregate.comments.length > 0 && (
<>
<Separator />
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 text-sm font-semibold">
<MessageSquareIcon className="size-4 text-muted-foreground" />
<span>Comments</span>
</div>
<div className="flex flex-col gap-2">
{aggregate.comments.map((comment, index) => (
<blockquote
key={index}
className="rounded-md border-border bg-muted/30 p-3 text-sm text-muted-foreground"
>
{comment.text}
</blockquote>
))}
</div>
</div>
</>
)}
</div>
) : (
<div className="flex flex-col gap-2 rounded-md border border-border bg-muted/30 p-4">
<span className="text-sm font-semibold">Confidential baseline</span>
<p className="text-sm text-muted-foreground">
Factor breakdowns and comments stay private until at least {RATING_ANONYMITY_THRESHOLD}{' '}
distinct operators have responded.
</p>
</div>
)}
</div>
);
}
export function MissionRating({
missionId,
state,
aggregate,
customFactors,
reviewError,
}: MissionRatingProps) {
const factors = ratingStars(customFactors);
const ratingLocked = state.myValues !== null;
const showForm = state.canRate && !ratingLocked;
const windowClosed = state.windowClosed;
const notEligible = !state.isEligible;
return (
<section className="flex flex-col gap-3" aria-labelledby="mission-rating-heading">
<div className="flex items-center gap-2">
<StarIcon className="size-4 text-muted-foreground" />
<h2
id="mission-rating-heading"
className="text-sm font-semibold uppercase tracking-wider text-muted-foreground"
>
Mission Rating
</h2>
</div>
<Item variant="outline">
<ItemHeader>
<ItemTitle>Rate this mission</ItemTitle>
</ItemHeader>
<ItemContent className="flex flex-col gap-4">
{showForm && (
<RatingForm
missionId={missionId}
factors={factors}
initialValue={null}
onSubmitError={reviewError ?? null}
onSuccess={() => {}}
/>
)}
{ratingLocked && <YouRatedState state={state} factors={factors} />}
{!showForm && !ratingLocked && windowClosed && (
<p className="text-sm text-muted-foreground">
The rating window for this mission is closed.
</p>
)}
{!showForm && !ratingLocked && !windowClosed && notEligible && (
<p className="text-sm text-muted-foreground">
You need a Yes RSVP for this mission to rate it.
</p>
)}
</ItemContent>
</Item>
<Item variant="outline">
<ItemHeader>
<ItemTitle>Overview</ItemTitle>
</ItemHeader>
<ItemContent>
<Overview aggregate={aggregate} factors={factors} />
</ItemContent>
</Item>
{aggregate.raterCount === 0 && !showForm && (
<Badge variant="outline" className="self-start font-normal">
Be the first to rate.
</Badge>
)}
</section>
);
}