1
0
Fork 0

Compare commits

...

8 commits

Author SHA1 Message Date
948109e362 v0.14.0 - add mission ratings system, post-op survey, Discord prompt, rating XP 2026-10-31 10:28:31 -04:00
1f46275926 chore(mission-ratings): sanitize em-dash placeholders in overview + discord embed 2026-10-31 10:28:28 -04:00
b207adc4dc docs: add v0.14.0 changelog entry (mission ratings) 2026-10-31 10:28:11 -04:00
8faa45a954 test(mission-ratings): eligibility, aggregate math, threshold, XP
Covers window classification, yes-RSVP/prior-rating gating, idempotent write,
factor validation, per-factor/distribution/overall-average aggregation,
anonymity threshold, custom-factor aggregation, numeric myValues, XP grant +
per-user idempotency, and permission gating (deny without / allow with read).
2026-10-31 10:25:37 -04:00
afe47ccd87 feat(mission-ratings): add collection, mission field, and discord rating marker
- add_mission_ratings: mission-ratings collection + enum values + missions
  missionRating.customFactors field
- add_mission_rating_sent_at_marker: Missions.discordRatingSentAt one-shot flag
- register both in migrations/index.ts
2026-10-31 10:25:33 -04:00
ee622ff6dd 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
2026-10-31 10:25:28 -04:00
f41a5bd5e4 feat(mission-ratings): service, contribution rule, server action
- service: isRatingAvailable, submitMissionRating, getMissionRatingState,
  getMissionRatingAggregate (per-factor/distribution/overall-average math,
  anonymity threshold, custom-factor support)
- contributions: mission-rating-completion rule (50 instant XP)
- server action submitMissionRating with permission + contribution XP award
2026-10-31 10:25:24 -04:00
1db0aabb7c feat(mission-ratings): add permissions, collection, mission field, config, generated types
- permissions: mission-ratings group + ALL_PERMISSION_VALUES, granted in seedRoles
- collection: src/collections/intelligence/MissionRatings.ts (field-gated, Intelligence group)
- Missions: missionRating.customFactors group (array of {label})
- payload.config: register MissionRatings + requireAdminPageAccess
- regenerate payload-types
2026-10-31 10:24:04 -04:00
23 changed files with 93177 additions and 3 deletions

View file

@ -1,5 +1,18 @@
# Changelog
# v0.14.0
Post-op mission ratings: operators rate each factor after a mission, anonymous aggregates surface on the mission page, the bot prompts for ratings in Discord, and completing the survey grants contribution XP.
### Features
- **Mission ratings.** Once a mission is marked Completed, operators can rate it within the rating window on the core factors (Briefing, Pacing, Map, Host, Balance) plus any authored custom factors, on a 1-5 scale. Each operator can rate a mission once.
- **Aggregate overview.** The overall average and per-factor breakdown stay hidden until at least three operators have rated; then the mission page shows the overall rating, each factor's average and vote distribution, and operator comments.
- **Discord prompt.** When a mission is completed, the bot posts a rating prompt in the ops channel with a button linking back to the mission page.
- **Rating XP.** Submitting a mission rating grants contribution XP (50 points, `mission-rating-completion`), counted once per operator per mission.
---
# v0.13.3
The rating system is now generic: evaluations no longer store a "kind", so a rating's direction is derived from the rater and ratee's ranks whenever it is read. The two views a profile shows are unchanged: the anonymous leadership aggregate and the latest command review.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.13.3",
"version": "0.14.0",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

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

@ -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<string, number>;
comment?: string | null;
}): Promise<ActionResult<{ ratings: Array<{ factor: string; value: number }> }>> {
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 };
}
}

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,98 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { RATING_VALUE_MAX, RATING_VALUE_MIN } from "@/lib/missionRatings/factors";
/**
* Mission ratings (a.k.a. post-op surveys).
*
* One row per (rater, mission) - the uniqueness is enforced by the service layer
* (`submitMissionRating` in `src/lib/missionRatings`), not by a DB constraint,
* exactly like `src/collections/users/Evaluations.ts`.
*
* Structure:
* - `ratings` is a flexible array of { factor, value } pairs. `factor` is the
* aggregation key. Core factors (Briefing, Pacing, Map, Host, Balance) are a
* fixed constant; mission authors add custom factor labels that are stored on
* the mission (`missionRating.customFactors`). Both are rated on a 1-5 scale.
* - `comment` is optional free text, shown anonymized in the public overview.
*
* Privacy model: raw documents are only readable/writable by users holding the
* `mission-ratings:*` permissions (admin via role docs). Normal users never
* receive raw rows over REST - the mission page consumes pre-aggregated,
* rater-free output produced by the service with explicit RBAC gating. `user`
* and `comment` are private fields and must never be surfaced to normal users
* by any read path.
*/
export const MissionRatings: CollectionConfig = {
slug: "mission-ratings",
admin: {
group: "Intelligence",
defaultColumns: ["mission", "user", "createdAt"],
},
access: {
read: requirePermission("mission-ratings:read"),
create: requirePermission("mission-ratings:create"),
update: requirePermission("mission-ratings:update"),
delete: requirePermission("mission-ratings:delete"),
},
fields: [
{
name: "mission",
type: "relationship",
relationTo: "missions",
required: true,
index: true,
admin: {
description: "The mission this rating is for.",
},
},
{
name: "user",
type: "relationship",
relationTo: "users",
required: true,
admin: {
description: "Who submitted this rating. Private, only visible to staff.",
},
},
{
name: "ratings",
type: "array",
labels: {
singular: "Rating",
plural: "Ratings",
},
admin: {
description:
"One entry per factor rated (core + any custom). factor is the label, value is 1-5 stars.",
},
fields: [
{
name: "factor",
type: "text",
required: true,
admin: {
description: "The factor label (core factor or authored custom factor).",
},
},
{
name: "value",
type: "select",
required: true,
options: [1, 2, 3, 4, 5].map((n) => ({ label: `${n} stars`, value: String(n) })),
admin: {
description: `Rating on a 1-${RATING_VALUE_MAX} star scale.`,
},
},
],
},
{
name: "comment",
type: "textarea",
admin: {
description:
"Optional free-text note. Shown anonymized in the public overview; raw attribution is staff-only.",
},
},
],
};

View file

@ -339,6 +339,15 @@ export const Missions: CollectionConfig = {
hidden: true,
},
},
{
name: "discordRatingSentAt",
type: "date",
admin: {
description:
"When the post-op survey prompt was first posted to Discord (managed by the bot, one-shot).",
hidden: true,
},
},
{
name: "discordCancelledAt",
type: "date",
@ -575,6 +584,36 @@ export const Missions: CollectionConfig = {
},
],
},
{
name: "missionRating",
type: "group",
label: "Post-Op Survey",
admin: {
description:
"Custom rating factors for the post-op survey. The core factors (Briefing, Pacing, Map, Host, Balance) are fixed; add extra labels below. Both core and authored factors are rated 1-5 stars.",
},
fields: [
{
name: "customFactors",
type: "array",
labels: {
singular: "Custom Factor",
plural: "Custom Factors",
},
admin: {
description:
"Extra factor labels (e.g. 'Gameplay', 'Server Lag') shown on the survey. Web-authoring only; Discord shows core factors. A factor appears in the aggregate only once it has a rating.",
},
fields: [
{
name: "label",
type: "text",
required: true,
},
],
},
],
},
{
name: "missionRoles",
type: "group",

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>
);
}

View file

@ -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<ContributionType, ContributionRule> = {
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",

View file

@ -0,0 +1,62 @@
/**
* Pure mission-rating definitions for the post-op survey.
*
* This module has no Payload imports - it is safe to use from server actions,
* integration tests, and frontend components. The factor labels drive the UI
* star selectors and the aggregation key; the value range drives validation.
*/
/**
* The immutable core factor set. These labels are the same on every mission and
* are the only factors shown in Discord. Mission authors may add custom labels
* (stored on the mission as `missionRating.customFactors`); both core and custom
* factors aggregate by their shared `factor` label.
*/
export const MISSION_RATING_CORE_FACTORS = [
"Briefing",
"Pacing",
"Map",
"Host",
"Balance",
] as const;
export type MissionRatingCoreFactor = (typeof MISSION_RATING_CORE_FACTORS)[number];
/**
* The 1-5 star scale every factor is rated on. `RATING_VALUE_MIN`/`RATING_VALUE_MAX`
* are the inclusive bounds; `RATING_VALUE_OPTIONS` is the ordered list for select
* widgets and distribution bars.
*/
export const RATING_VALUE_MIN = 1;
export const RATING_VALUE_MAX = 5;
export const RATING_VALUE_OPTIONS = [1, 2, 3, 4, 5] as const;
/**
* How long the rating window stays open after a mission is marked Completed,
* in days. Anchored on the mission's `completedAt` timestamp.
*/
export const RATING_WINDOW_DAYS = 14;
/**
* Minimum number of distinct raters before the factor breakdown and comments are
* surfaced publicly. Below this threshold only the overall average and rater
* count show, so a small group of raters cannot be identified from the
* distribution.
*/
export const RATING_ANONYMITY_THRESHOLD = 3;
/** Distinct core factor labels, in display order. */
export const MISSION_RATING_CORE_FACTORS_DISPLAY: readonly string[] = [
...MISSION_RATING_CORE_FACTORS,
];
/** True when `value` is an integer within the rating scale. */
export function isRatingValue(value: unknown): boolean {
return typeof value === "number" && RATING_VALUE_MIN <= value && value <= RATING_VALUE_MAX;
}
/** Resolve a human label for a factor. Core factors use their label verbatim;
* unknown/custom factors fall back to the raw label. */
export function getFactorLabel(factor: string): string {
return factor;
}

View file

@ -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<ReturnType<typeof import("payload").getPayload>>;
/** 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<boolean> {
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<boolean> {
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<boolean> {
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<string, number>;
/** 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<MissionRatingEntry[]> {
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<string>([...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<MissionRatingState> {
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<MissionRatingAggregate> {
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<string, MissionRatingEntry[]>();
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<string>(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 };

View file

@ -0,0 +1,17 @@
/**
* Tunable contribution configuration for the mission-rating survey.
*
* The contribution type and XP amount live here (not inline in the server action)
* so they are a single source of truth and easy to rebalance. The type string
* ("mission-rating-completion") must also be registered in
* `src/lib/contributions/rules.ts` so `isContributionType` accepts it.
*/
/** The contribution type recorded when a user submits a mission rating. */
export const CONTRIBUTION_TYPE_MISSION_RATING = "mission-rating-completion" as const;
/**
* Flat XP awarded for submitting a mission rating. Small and intentional: the
* survey is a post-op courtesy, not a primary XP earner.
*/
export const MISSION_RATING_XP = 50;

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "missions" ADD COLUMN "discord_rating_sent_at" timestamp(3) with time zone;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "missions" DROP COLUMN "discord_rating_sent_at";`)
}

View file

@ -152,6 +152,8 @@ import * as migration_20261026_073228_add_vehicle_category_static_and_drone from
import * as migration_20261026_195910_add_vehicle_disallowed_cargo_field from './20261026_195910_add_vehicle_disallowed_cargo_field';
import * as migration_20261026_205453_add_operation_effects_pending_action_and_decisions from './20261026_205453_add_operation_effects_pending_action_and_decisions';
import * as migration_20261031_064618_drop_evaluation_kind from './20261031_064618_drop_evaluation_kind';
import * as migration_20261031_084725_add_mission_ratings from './20261031_084725_add_mission_ratings';
import * as migration_20261031_085035_add_mission_rating_sent_at_marker from './20261031_085035_add_mission_rating_sent_at_marker';
export const migrations = [
{
@ -922,6 +924,16 @@ export const migrations = [
{
up: migration_20261031_064618_drop_evaluation_kind.up,
down: migration_20261031_064618_drop_evaluation_kind.down,
name: '20261031_064618_drop_evaluation_kind'
name: '20261031_064618_drop_evaluation_kind',
},
{
up: migration_20261031_084725_add_mission_ratings.up,
down: migration_20261031_084725_add_mission_ratings.down,
name: '20261031_084725_add_mission_ratings',
},
{
up: migration_20261031_085035_add_mission_rating_sent_at_marker.up,
down: migration_20261031_085035_add_mission_rating_sent_at_marker.down,
name: '20261031_085035_add_mission_rating_sent_at_marker'
},
];

View file

@ -103,6 +103,7 @@ export interface Config {
'mission-attendances': MissionAttendance;
'mission-role-signups': MissionRoleSignup;
'mission-map-markers': MissionMapMarker;
'mission-ratings': MissionRating;
campaigns: Campaign;
factions: Faction;
technologies: Technology;
@ -217,6 +218,7 @@ export interface Config {
'mission-attendances': MissionAttendancesSelect<false> | MissionAttendancesSelect<true>;
'mission-role-signups': MissionRoleSignupsSelect<false> | MissionRoleSignupsSelect<true>;
'mission-map-markers': MissionMapMarkersSelect<false> | MissionMapMarkersSelect<true>;
'mission-ratings': MissionRatingsSelect<false> | MissionRatingsSelect<true>;
campaigns: CampaignsSelect<false> | CampaignsSelect<true>;
factions: FactionsSelect<false> | FactionsSelect<true>;
technologies: TechnologiesSelect<false> | TechnologiesSelect<true>;
@ -725,6 +727,11 @@ export interface Role {
| 'mission-map-markers:update'
| 'mission-map-markers:delete'
| 'admin:mission-map-markers:manage'
| 'mission-ratings:create'
| 'mission-ratings:read'
| 'mission-ratings:update'
| 'mission-ratings:delete'
| 'admin:mission-ratings:manage'
| 'campaigns:create'
| 'campaigns:read'
| 'campaigns:update'
@ -3252,6 +3259,11 @@ export interface GameEventLog {
| 'mission-map-markers:update'
| 'mission-map-markers:delete'
| 'admin:mission-map-markers:manage'
| 'mission-ratings:create'
| 'mission-ratings:read'
| 'mission-ratings:update'
| 'mission-ratings:delete'
| 'admin:mission-ratings:manage'
| 'campaigns:create'
| 'campaigns:read'
| 'campaigns:update'
@ -4315,11 +4327,12 @@ export interface ContributionEntry {
| 'wiki-page-edit'
| 'mission-map-marker'
| 'survey-completion'
| 'mission-rating-completion'
| 'journal-publish'
| 'manual';
status: 'queued' | 'granted' | 'revoked' | 'expired';
points: number;
sourceCollection: 'wiki-pages' | 'mission-map-markers' | 'form-submissions' | 'journals' | 'manual';
sourceCollection: 'wiki-pages' | 'mission-map-markers' | 'form-submissions' | 'journals' | 'missions' | 'manual';
/**
* Id of the source document (polymorphic).
*/
@ -4374,6 +4387,10 @@ export interface Mission {
* Fingerprint of the attached modlist last announced to Discord (managed by the bot).
*/
discordModlistHash?: string | null;
/**
* When the post-op survey prompt was first posted to Discord (managed by the bot, one-shot).
*/
discordRatingSentAt?: string | null;
/**
* When the roll-call was marked cancelled in Discord (managed by the bot; cleared when a cancelled op is rescheduled).
*/
@ -4438,6 +4455,20 @@ export interface Mission {
*/
completedAt?: string | null;
};
/**
* Custom rating factors for the post-op survey. The core factors (Briefing, Pacing, Map, Host, Balance) are fixed; add extra labels below. Both core and authored factors are rated 1-5 stars.
*/
missionRating?: {
/**
* Extra factor labels (e.g. 'Gameplay', 'Server Lag') shown on the survey. Web-authoring only; Discord shows core factors. A factor appears in the aggregate only once it has a rating.
*/
customFactors?:
| {
label: string;
id?: string | null;
}[]
| null;
};
missionRoles: {
maxPlayers: number;
providedRoles?:
@ -4941,6 +4972,43 @@ export interface MissionMapMarker {
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "mission-ratings".
*/
export interface MissionRating {
id: number;
/**
* The mission this rating is for.
*/
mission: number | Mission;
/**
* Who submitted this rating. Private, only visible to staff.
*/
user: number | User;
/**
* One entry per factor rated (core + any custom). factor is the label, value is 1-5 stars.
*/
ratings?:
| {
/**
* The factor label (core factor or authored custom factor).
*/
factor: string;
/**
* Rating on a 1-5 star scale.
*/
value: '1' | '2' | '3' | '4' | '5';
id?: string | null;
}[]
| null;
/**
* Optional free-text note. Shown anonymized in the public overview; raw attribution is staff-only.
*/
comment?: string | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "tech-researches".
@ -7933,6 +8001,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
missionRatings?: {
/**
* Allow clients to find mission-ratings.
*/
find?: boolean | null;
/**
* Allow clients to create mission-ratings.
*/
create?: boolean | null;
/**
* Allow clients to update mission-ratings.
*/
update?: boolean | null;
/**
* Allow clients to delete mission-ratings.
*/
delete?: boolean | null;
};
campaigns?: {
/**
* Allow clients to find campaigns.
@ -9202,6 +9288,10 @@ export interface PayloadLockedDocument {
relationTo: 'mission-map-markers';
value: number | MissionMapMarker;
} | null)
| ({
relationTo: 'mission-ratings';
value: number | MissionRating;
} | null)
| ({
relationTo: 'campaigns';
value: number | Campaign;
@ -10489,6 +10579,7 @@ export interface MissionsSelect<T extends boolean = true> {
discordAttendanceHash?: T;
discordAttendanceSentAt?: T;
discordModlistHash?: T;
discordRatingSentAt?: T;
discordCancelledAt?: T;
evaluationRemindersSentAt?: T;
readyReminderWebSentAt?: T;
@ -10518,6 +10609,16 @@ export interface MissionsSelect<T extends boolean = true> {
visibility?: T;
completedAt?: T;
};
missionRating?:
| T
| {
customFactors?:
| T
| {
label?: T;
id?: T;
};
};
missionRoles?:
| T
| {
@ -10664,6 +10765,24 @@ export interface MissionMapMarkersSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "mission-ratings_select".
*/
export interface MissionRatingsSelect<T extends boolean = true> {
mission?: T;
user?: T;
ratings?:
| T
| {
factor?: T;
value?: T;
id?: T;
};
comment?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "campaigns_select".
@ -12798,6 +12917,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
missionRatings?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
campaigns?:
| T
| {

View file

@ -19,6 +19,7 @@ import { Missions } from "@/collections/intelligence/Missions";
import { MissionAttendances } from "@/collections/intelligence/MissionAttendances";
import { MissionRoleSignups } from "@/collections/intelligence/MissionRoleSignups";
import { MissionMapMarkers } from "@/collections/intelligence/MissionMapMarkers";
import { MissionRatings } from "@/collections/intelligence/MissionRatings";
import { Maps } from "@/collections/world/Maps";
import { MapRoads } from "@/collections/world/MapRoads";
import { MapZones } from "@/collections/world/MapZones";
@ -347,6 +348,7 @@ const collections = [
MissionAttendances,
MissionRoleSignups,
MissionMapMarkers,
MissionRatings,
Campaigns,
Factions,
Technologies,
@ -738,6 +740,8 @@ export default buildConfig({
// Intel
[Missions.slug]: true,
[MissionAttendances.slug]: true,
[MissionRoleSignups.slug]: true,
[MissionRatings.slug]: true,
[Campaigns.slug]: true,
[Factions.slug]: true,
[Technologies.slug]: true,

View file

@ -230,6 +230,16 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "admin:mission-map-markers:manage", label: "Manage Admin Page" },
],
},
{
group: "Mission Ratings",
permissions: [
{ value: "mission-ratings:create", label: "Create" },
{ value: "mission-ratings:read", label: "Read (staff: raw per-user ratings)" },
{ value: "mission-ratings:update", label: "Update" },
{ value: "mission-ratings:delete", label: "Delete" },
{ value: "admin:mission-ratings:manage", label: "Manage Admin Page" },
],
},
{
group: "Campaigns",
permissions: [
@ -981,6 +991,11 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"mission-map-markers:update",
"mission-map-markers:delete",
"admin:mission-map-markers:manage",
"mission-ratings:create",
"mission-ratings:read",
"mission-ratings:update",
"mission-ratings:delete",
"admin:mission-ratings:manage",
"campaigns:create",
"campaigns:read",
"campaigns:update",

View file

@ -57,6 +57,10 @@ const ADMIN_PERMISSIONS: Permission[] = [
"mission-attendances:read",
"mission-attendances:update",
"mission-attendances:delete",
"mission-ratings:create",
"mission-ratings:read",
"mission-ratings:update",
"mission-ratings:delete",
"missions:read",
"market-negotiations:read",
"market-negotiations:update",

View file

@ -0,0 +1,640 @@
import { getTestPayload } from "../helpers/get-test-payload";
import type { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Campaign, Map as MissionMap, Mission, Role, User } from "@/payload-types";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
import {
isRatingAvailable,
isRatingWindowOpen,
getMissionRatingAggregate,
getMissionRatingState,
submitMissionRating,
} from "@/lib/missionRatings";
import {
MISSION_RATING_CORE_FACTORS,
RATING_ANONYMITY_THRESHOLD,
RATING_VALUE_OPTIONS,
} from "@/lib/missionRatings/factors";
import { CONTRIBUTION_TYPE_MISSION_RATING, MISSION_RATING_XP } from "@/lib/missionRatings/xp";
import { recordContribution } from "@/lib/contributions";
type TestPayload = Awaited<ReturnType<typeof getTestPayload>>;
describe("Mission ratings (post-op survey)", () => {
let payload: TestPayload;
const RUN = `mrat-${Date.now().toString(36)}`;
let mapId: number;
let campaignId: number;
const missionIds: number[] = [];
const userIds: number[] = [];
// Raters shared across scenarios.
let rater1: User;
let rater2: User;
let rater3: User;
let noRsvp: User;
let outsider: User;
// Missions, each created in `beforeAll`.
let aggMissionId: number; // Completed, unit: aggregate math + per-factor + state
let belowMissionId: number; // Completed, unit: below-then-at threshold + comments
let closedMissionId: number; // Scheduled future: window closed
let eligMissionId: number; // Completed, unit: eligibility gate
let customMissionId: number; // Completed, unit, custom factor "Comms"
let xpMissionId: number; // Completed, unit: XP grant + idempotency
const past = new Date();
past.setHours(past.getHours() - 1); // within the 14-day window
const future = new Date();
future.setDate(future.getDate() + 20);
const makeUser = async (label: string): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const rsvp = async (userId: number, missionId: number): Promise<void> => {
await payload.create({
collection: "mission-attendances",
data: { mission: missionId, user: userId, response: "yes" },
overrideAccess: true,
depth: 0,
});
};
const makeCompletedMission = async (
label: string,
opts?: { customFactors?: { label: string }[] },
): Promise<Mission> => {
const mission = (await payload.create({
collection: "missions",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Mission rating test mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
campaign: campaignId,
startDateTime: past.toISOString(),
estimatedDuration: 60,
},
ownershipAndStatus: {
status: "Completed",
completedAt: past.toISOString(),
visibility: "unit",
authors: [rater1.id],
},
...(opts?.customFactors ? { missionRating: { customFactors: opts.customFactors } } : {}),
missionRoles: { maxPlayers: 16 },
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
briefing: [],
},
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id as number);
return mission;
};
const makeFutureMission = async (label: string): Promise<Mission> => {
const mission = (await payload.create({
collection: "missions",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Future mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
campaign: campaignId,
startDateTime: future.toISOString(),
estimatedDuration: 60,
},
ownershipAndStatus: {
status: "Scheduled",
visibility: "unit",
authors: [rater1.id],
},
missionRoles: { maxPlayers: 16 },
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
briefing: [],
},
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id as number);
return mission;
};
const bucketFor = async (userId: number): Promise<number> => {
const res = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
select: { progression: { contributions: { xpEarned: true } } },
});
return res.docs[0]?.progression?.contributions?.xpEarned ?? 0;
};
beforeAll(async () => {
payload = await getTestPayload();
const map = (await payload.create({
collection: "maps",
data: { name: `${RUN} Map`, worldSizeWidth: 8192, worldSizeHeight: 8192, basemapMode: "image" },
overrideAccess: true,
depth: 0,
})) as unknown as MissionMap;
mapId = map.id;
const campaign = (await payload.create({
collection: "campaigns",
data: { name: `${RUN} Campaign`, summary: "Rating test campaign", status: "concept", campaignMode: "custom" },
overrideAccess: true,
depth: 0,
})) as unknown as Campaign;
campaignId = campaign.id;
rater1 = await makeUser("rater1");
rater2 = await makeUser("rater2");
rater3 = await makeUser("rater3");
noRsvp = await makeUser("no-rsvp");
outsider = await makeUser("outsider");
aggMissionId = (await makeCompletedMission("agg")).id as number;
belowMissionId = (await makeCompletedMission("below")).id as number;
closedMissionId = (await makeFutureMission("closed")).id as number;
eligMissionId = (await makeCompletedMission("elig")).id as number;
customMissionId = (await makeCompletedMission("custom", { customFactors: [{ label: "Comms" }] })).id as number;
xpMissionId = (await makeCompletedMission("xp")).id as number;
});
afterAll(async () => {
await payload
.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {})
.catch(() => {});
// Drop everything created for this run.
await payload
.delete({
collection: "mission-ratings",
where: { mission: { in: missionIds } },
overrideAccess: true,
})
.catch(() => {});
await payload
.delete({
collection: "mission-attendances",
where: { mission: { in: missionIds } },
overrideAccess: true,
})
.catch(() => {});
for (const id of missionIds) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "campaigns", id: campaignId, overrideAccess: true }).catch(() => {});
await payload
.delete({ collection: "contribution-entries", where: { user: { in: userIds } }, overrideAccess: true })
.catch(() => {});
for (const userId of userIds) {
const profiles = await payload
.find({ collection: "profiles", where: { user: { equals: userId } }, depth: 0, overrideAccess: true })
.catch(() => ({ docs: [] }));
for (const doc of profiles.docs) {
await payload.delete({ collection: "profiles", id: doc.id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "users", id: userId, overrideAccess: true }).catch(() => {});
}
});
// ---------------------------------------------------------------------------
// Window classification (pure)
// ---------------------------------------------------------------------------
it("classifies the rating window (pure)", () => {
const now = new Date();
const inWindow = new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString();
expect(isRatingWindowOpen("Completed", inWindow, now)).toBe(true);
// Exactly 14 days after completion: the window's end equals `now`, which
// is inclusive.
const boundary = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString();
expect(isRatingWindowOpen("Completed", boundary, now)).toBe(true);
// One second past the 14-day mark: closed.
const justPast = new Date(now.getTime() - (14 * 24 * 60 * 60 * 1000 + 1000)).toISOString();
expect(isRatingWindowOpen("Completed", justPast, now)).toBe(false);
// Not completed, or no completion timestamp.
expect(isRatingWindowOpen("Scheduled", inWindow, now)).toBe(false);
expect(isRatingWindowOpen("Completed", null, now)).toBe(false);
expect(isRatingWindowOpen("Completed", "not-a-date", now)).toBe(false);
});
// ---------------------------------------------------------------------------
// Eligibility
// ---------------------------------------------------------------------------
it("gates availability on window, yes-RSVP, and prior rating", async () => {
// rater1: window open + yes-RSVP + not rated -> eligible.
await rsvp(rater1.id, eligMissionId);
expect(
await isRatingAvailable(payload, { id: eligMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString() } }, rater1.id),
).toBe(true);
// noRsvp: no attendance -> ineligible.
expect(
await isRatingAvailable(payload, { id: eligMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString() } }, noRsvp.id),
).toBe(false);
// Window closed for a different mission -> ineligible.
expect(
await isRatingAvailable(payload, { id: closedMissionId, ownershipAndStatus: { status: "Scheduled", completedAt: null } }, rater1.id),
).toBe(false);
});
it("rejects a second rating from the same user (idempotent write)", async () => {
await rsvp(rater1.id, aggMissionId);
await submitMissionRating(payload, {
missionId: aggMissionId,
userId: rater1.id,
values: { Briefing: 5, Pacing: 4, Map: 3, Host: 2, Balance: 5 },
});
await expect(
submitMissionRating(payload, {
missionId: aggMissionId,
userId: rater1.id,
values: { Briefing: 3, Pacing: 3, Map: 3, Host: 4, Balance: 4 },
}),
).rejects.toThrow(/already submitted/i);
// A different user can still rate the same mission.
await rsvp(rater2.id, aggMissionId);
const second = await submitMissionRating(payload, {
missionId: aggMissionId,
userId: rater2.id,
values: { Briefing: 4, Pacing: 4, Map: 3, Host: 3, Balance: 3 },
});
expect(second).toHaveLength(5);
});
it("validates factor values before writing (unknown / out-of-range / closed)", async () => {
await rsvp(rater3.id, aggMissionId);
await expect(
submitMissionRating(payload, {
missionId: aggMissionId,
userId: rater3.id,
values: { Briefing: 5, NotAFactor: 4 },
}),
).rejects.toThrow(/unknown factor/i);
await expect(
submitMissionRating(payload, {
missionId: aggMissionId,
userId: rater3.id,
values: { Briefing: 6 },
}),
).rejects.toThrow(/between 1 and 5/i);
await expect(
submitMissionRating(payload, {
missionId: aggMissionId,
userId: rater3.id,
values: { Briefing: 0 },
}),
).rejects.toThrow(/between 1 and 5/i);
// A closed-window mission rejects the write outright.
await rsvp(rater3.id, closedMissionId);
await expect(
submitMissionRating(payload, {
missionId: closedMissionId,
userId: rater3.id,
values: { Briefing: 5 },
}),
).rejects.toThrow(/window.*closed/i);
});
// ---------------------------------------------------------------------------
// Aggregate math + per-factor breakdown (at threshold)
// ---------------------------------------------------------------------------
it("aggregates the overall average and per-factor breakdown once visible", async () => {
// rater1 and rater2 have already rated (idempotent-write test). rater3 rates now.
await rsvp(rater3.id, aggMissionId);
await submitMissionRating(payload, {
missionId: aggMissionId,
userId: rater3.id,
values: { Briefing: 3, Pacing: 3, Map: 3, Host: 4, Balance: 4 },
});
const agg = await getMissionRatingAggregate(payload, aggMissionId);
// 3 distinct raters, each rating 5 core factors -> 15 values.
expect(agg.raterCount).toBe(3);
expect(agg.visible).toBe(true);
expect(agg.factors).not.toBeNull();
// Overall: (19 + 17 + 17) / 15 = 53 / 15 = 3.5333...
expect(agg.overallAverage).toBeCloseTo(3.53, 0.01);
const byFactor = new Map((agg.factors as Array<{ factor: string; average: number; count: number; distribution: { value: number; count: number }[] }>).map((f) => [f.factor, f]));
// Canonical core order.
expect((agg.factors as Array<{ factor: string }>).map((f) => f.factor)).toEqual([...MISSION_RATING_CORE_FACTORS]);
// Briefing = (5 + 4 + 3) / 3 = 4.0.
expect(byFactor.get("Briefing")?.average).toBeCloseTo(4.0, 6);
expect(byFactor.get("Briefing")?.count).toBe(3);
expect(byFactor.get("Briefing")?.distribution).toEqual([
{ value: 1, count: 0 },
{ value: 2, count: 0 },
{ value: 3, count: 1 },
{ value: 4, count: 1 },
{ value: 5, count: 1 },
]);
// Map is unanimous at 3.
expect(byFactor.get("Map")?.average).toBeCloseTo(3.0, 6);
// Every distribution sums to the factor count and only uses valid options.
for (const factor of agg.factors as Array<{ factor: string; count: number; distribution: { value: number; count: number }[]}>) {
const total = factor.distribution.reduce((sum, d) => sum + d.count, 0);
expect(total).toBe(factor.count);
for (const d of factor.distribution) {
expect(RATING_VALUE_OPTIONS).toContain(d.value);
}
}
});
// ---------------------------------------------------------------------------
// Anonymity threshold
// ---------------------------------------------------------------------------
it("withholds the breakdown below the anonymity threshold and reveals it at threshold", async () => {
const state = (r: User) => ({ id: belowMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString() } });
await rsvp(rater1.id, belowMissionId);
await submitMissionRating(payload, {
missionId: belowMissionId,
userId: rater1.id,
values: { Briefing: 5, Pacing: 5 },
comment: "Great op",
});
await rsvp(rater2.id, belowMissionId);
await submitMissionRating(payload, {
missionId: belowMissionId,
userId: rater2.id,
values: { Briefing: 3, Pacing: 1 },
comment: "Could be better",
});
// 2 distinct raters < RATING_ANONYMITY_THRESHOLD.
expect(RATING_ANONYMITY_THRESHOLD).toBe(3);
const hidden = await getMissionRatingAggregate(payload, belowMissionId);
expect(hidden.raterCount).toBe(2);
expect(hidden.visible).toBe(false);
expect(hidden.factors).toBeNull();
expect(hidden.comments).toBeNull();
// The overall average and rater count are always available.
expect(hidden.overallAverage).toBeCloseTo(3.5, 0.01);
// Add a third rater -> now visible.
await rsvp(rater3.id, belowMissionId);
await submitMissionRating(payload, {
missionId: belowMissionId,
userId: rater3.id,
values: { Briefing: 4, Pacing: 4 },
});
const revealed = await getMissionRatingAggregate(payload, belowMissionId);
expect(revealed.raterCount).toBe(3);
expect(revealed.visible).toBe(true);
expect(revealed.factors).not.toBeNull();
expect(revealed.comments).not.toBeNull();
expect(revealed.comments?.some((c) => c.text === "Great op")).toBe(true);
expect(revealed.overallAverage).toBeCloseTo(22 / 6, 0.01);
});
// ---------------------------------------------------------------------------
// Custom factors
// ---------------------------------------------------------------------------
it("aggregates authored custom factors alongside core factors", async () => {
// Three raters so the breakdown is visible (threshold = 3). Each rates the
// authored custom factor "Comms" plus one core factor.
await rsvp(rater1.id, customMissionId);
await submitMissionRating(payload, {
missionId: customMissionId,
userId: rater1.id,
values: { Comms: 5, Briefing: 5 },
});
await rsvp(rater2.id, customMissionId);
await submitMissionRating(payload, {
missionId: customMissionId,
userId: rater2.id,
values: { Comms: 4, Briefing: 3 },
});
await rsvp(rater3.id, customMissionId);
await submitMissionRating(payload, {
missionId: customMissionId,
userId: rater3.id,
values: { Comms: 3, Briefing: 4 },
});
const agg = await getMissionRatingAggregate(payload, customMissionId);
expect(agg.visible).toBe(true);
const factor = (agg.factors ?? []).find((f) => f.factor === "Comms");
// (5 + 4 + 3) / 3 = 4.0
expect(factor?.average).toBeCloseTo(4.0, 6);
expect(factor?.count).toBe(3);
expect(factor?.distribution).toEqual([
{ value: 1, count: 0 },
{ value: 2, count: 0 },
{ value: 3, count: 1 },
{ value: 4, count: 1 },
{ value: 5, count: 1 },
]);
// Custom factors sort after core factors.
const labels = (agg.factors ?? []).map((f) => f.factor);
expect(labels.indexOf("Briefing")).toBeLessThan(labels.indexOf("Comms"));
});
// ---------------------------------------------------------------------------
// Read state (myValues coercion)
// ---------------------------------------------------------------------------
it("returns the current user's own ratings with numeric values", async () => {
// rater2 already rated aggMission.
const state = await getMissionRatingState(payload, { id: aggMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString() } }, rater2.id);
expect(state.windowOpen).toBe(true);
expect(state.canRate).toBe(false); // already rated
expect(state.myValues).not.toBeNull();
for (const entry of state.myValues ?? []) {
expect(typeof entry.value).toBe("number");
expect(Number.isInteger(entry.value)).toBe(true);
}
});
// ---------------------------------------------------------------------------
// Contribution XP
// ---------------------------------------------------------------------------
it("grants the rating XP and bumps the profile bucket", async () => {
await rsvp(rater1.id, xpMissionId);
await submitMissionRating(payload, {
missionId: xpMissionId,
userId: rater1.id,
values: { Briefing: 5 },
});
const before = await bucketFor(rater1.id);
const result = await recordContribution(payload, {
userId: rater1.id,
type: CONTRIBUTION_TYPE_MISSION_RATING,
sourceCollection: "missions",
sourceId: xpMissionId,
summary: `Rated mission "xp"`,
pointsOverride: MISSION_RATING_XP,
dedupeSuffix: `user:${rater1.id}`,
actorId: rater1.id,
});
expect(result.status).toBe("granted");
expect(result.points).toBe(MISSION_RATING_XP);
expect(MISSION_RATING_XP).toBe(50);
expect(await bucketFor(rater1.id)).toBe(before + MISSION_RATING_XP);
});
it("is idempotent: the same rating contribution cannot be counted twice", async () => {
await rsvp(rater2.id, xpMissionId);
await submitMissionRating(payload, {
missionId: xpMissionId,
userId: rater2.id,
values: { Briefing: 4 },
});
const input = {
userId: rater2.id,
type: CONTRIBUTION_TYPE_MISSION_RATING,
sourceCollection: "missions" as const,
sourceId: xpMissionId,
summary: "Duplicate guard",
pointsOverride: MISSION_RATING_XP,
dedupeSuffix: `user:${rater2.id}`,
};
const first = await recordContribution(payload, input);
const second = await recordContribution(payload, input);
expect(second.entryId).toBe(first.entryId);
const count = await payload.count({
collection: "contribution-entries",
where: { idempotencyKey: { equals: `mission-rating-completion:missions:${xpMissionId}:user:${rater2.id}` } },
overrideAccess: true,
});
expect(count.totalDocs).toBe(1);
});
it("grants XP to each distinct rater of the same mission (per-user, not per-mission)", async () => {
// xpMission already carries rater1 and rater2 ratings; rater3 is a third,
// distinct rater on the same mission. Without per-user idempotency the
// shared sourceId would collide and rater3 would earn nothing.
await rsvp(rater3.id, xpMissionId);
await submitMissionRating(payload, {
missionId: xpMissionId,
userId: rater3.id,
values: { Briefing: 5 },
});
const before = await bucketFor(rater3.id);
await recordContribution(payload, {
userId: rater3.id,
type: CONTRIBUTION_TYPE_MISSION_RATING,
sourceCollection: "missions",
sourceId: xpMissionId,
summary: "Cross-user grant",
pointsOverride: MISSION_RATING_XP,
dedupeSuffix: `user:${rater3.id}`,
});
expect(await bucketFor(rater3.id)).toBe(before + MISSION_RATING_XP);
});
// ---------------------------------------------------------------------------
it("hides raw mission-ratings from users without the permission", async () => {
await expect(
payload.find({
collection: "mission-ratings",
limit: 50,
depth: 0,
user: outsider,
overrideAccess: false,
}),
).rejects.toThrow(/not allowed/);
});
it("exposes raw mission-ratings to users holding mission-ratings:read", async () => {
const role = (await payload.create({
collection: "roles",
data: { name: `${RUN} Rating Reader`, slug: `${RUN}-rating-reader`, permissions: ["mission-ratings:read"] },
overrideAccess: true,
depth: 0,
})) as unknown as Role;
const reader = (await payload.create({
collection: "users",
data: {
username: `${RUN}-rating-reader`,
discordUsername: `${RUN}-rating-reader`,
displayName: "RATING READER",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(reader.id);
await payload.update({
collection: "users",
id: reader.id,
data: { roleDocs: [role.id] },
overrideAccess: true,
depth: 0,
});
invalidatePermissionCache();
try {
const result = await payload.find({
collection: "mission-ratings",
limit: 50,
depth: 0,
user: reader,
overrideAccess: false,
});
expect(result.docs.length).toBeGreaterThan(0);
const doc = result.docs[0] as unknown as Record<string, unknown>;
// Staff-only fields are present on the raw doc.
expect(typeof doc.user).toBe("number");
expect(Array.isArray(doc.ratings)).toBe(true);
} finally {
await payload.delete({ collection: "roles", id: role.id, overrideAccess: true }).catch(() => {});
}
});
});