1
0
Fork 0

feat(intelligence): add attendance-gated feature unlocks to mission pages

Missions gain an attendanceUnlocks tier list (admin tab plus side-op dialog),
rendered as a timeline under the attendance card: reached tiers light up in
their accent, unreached tiers stay muted with an X TO GO tag.

- shared derivation, validation and side-op parser in lib/intelligence
- thresholds sorted on save, duplicates rejected, above-max allowed
- one compact field in the Discord roll-call; attendance hash now includes
  tiers, embed schema version 4
- int tests and an e2e render check at two attendance levels
This commit is contained in:
Jason Fraley 2026-11-21 02:30:48 -05:00
parent 429d2028d0
commit 4022e5b5f1
15 changed files with 47842 additions and 17 deletions

View file

@ -41,6 +41,7 @@ import { getChainEditorState } from "@/lib/command-chain";
import { MissionLogistics } from "@/components/frontend/intelligence/MissionLogistics";
import { MissionComms } from "@/components/frontend/intelligence/MissionComms";
import { MissionAttendance } from "@/components/frontend/intelligence/MissionAttendance";
import { MissionAttendanceUnlocks } from "@/components/frontend/intelligence/MissionAttendanceUnlocks";
import { MissionRating } from "@/components/frontend/intelligence/MissionRating";
import {
getMissionRatingAggregate,
@ -296,6 +297,17 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
/>
);
// Feature unlocks travel with the attendance card: once stacked above the
// main column, once in the right sidebar. Both wrappers must stay in sync.
const unlocksCard = (
<MissionAttendanceUnlocks
missionId={mission.id}
tiers={mission.attendanceUnlocks}
yesCount={attendance.counts.yes}
terminal={["Completed", "Cancelled"].includes(mission.ownershipAndStatus.status)}
/>
);
// Planning map: visible to everyone who can see the mission once enabled.
// Curators (missions:update or the creator) manage the map and delegate
// per-mission access; delegates may place/edit only their own markers. The
@ -515,8 +527,11 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
initialObjectives={planObjectives}
/>
)}
{/* Attendance sits right under the hero on stacked (below-xl) layouts */}
<div className="xl:hidden">{attendanceCard}</div>
{/* Attendance and its unlock timeline sit right under the hero on stacked (below-xl) layouts */}
<div className="xl:hidden flex flex-col gap-4">
{attendanceCard}
{unlocksCard}
</div>
<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">
@ -717,6 +732,12 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
successOrFailConditions: obj.successOrFailConditions ?? "",
redacted: obj.redacted ?? false,
})),
attendanceUnlocks: (mission.attendanceUnlocks ?? []).map((tier) => ({
threshold: tier.threshold,
title: tier.title,
description: tier.description ?? null,
accentColor: tier.accentColor ?? null,
})),
civilianPresence: mission.civilianPresence ?? "None",
radioPlan: mission.commsAndDocs?.radioPlan ?? null,
insertion: mission.logisticsAndSupport?.insertion ?? [],
@ -742,7 +763,10 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
/>
)}
<div className="hidden xl:block">{attendanceCard}</div>
<div className="hidden xl:flex xl:flex-col gap-4">
{attendanceCard}
{unlocksCard}
</div>
{/* Campaign Card */}
{campaign && (

View file

@ -27,6 +27,10 @@ import {
zonedWeekday,
} from "@/lib/intelligence/fridayTime";
import { describeArmaPresetFailure, parseArmaPreset } from "@/lib/modlistPreset";
import {
parseAttendanceUnlocks,
type AttendanceUnlockTierInput,
} from "@/lib/intelligence/attendanceUnlocks";
import {
canEditMissionChain,
getChainLockReason,
@ -301,6 +305,7 @@ export interface FridaySideOpInput {
doesRespawn?: boolean | null;
assetCallsign?: string | null;
}[] | null;
attendanceUnlocks?: AttendanceUnlockTierInput[] | null;
}
type SideOpNarrativeData = {
@ -540,6 +545,9 @@ export async function createFridaySideOp(
const narrative = narrativeData(input);
if (!narrative.success) return narrative;
const unlocks = parseAttendanceUnlocks(input.attendanceUnlocks);
if (!unlocks.success) return unlocks;
const mission = await payload.create({
collection: "missions",
overrideAccess: true,
@ -579,6 +587,9 @@ export async function createFridaySideOp(
: {}),
},
...narrative.data,
...(input.attendanceUnlocks !== undefined
? { attendanceUnlocks: unlocks.data }
: {}),
},
});
@ -625,6 +636,7 @@ export interface UpdateFridaySideOpInput {
insertion?: InfilExfilMethod[] | null;
extraction?: InfilExfilMethod[] | null;
assetsAvailable?: FridaySideOpInput["assetsAvailable"];
attendanceUnlocks?: AttendanceUnlockTierInput[] | null;
}
export async function updateFridaySideOp(
@ -712,6 +724,7 @@ export async function updateFridaySideOp(
classification?: SideOpClassificationUpdate;
missionRoles?: { maxPlayers?: number };
gameDetails?: { gameSetup?: { requiredMods?: number | null } };
attendanceUnlocks?: AttendanceUnlockTierInput[];
} = {};
if (input.name !== undefined) data.name = input.name.trim();
if (input.codeName !== undefined) data.codeName = input.codeName.trim() || null;
@ -751,6 +764,12 @@ export async function updateFridaySideOp(
if (!narrative.success) return narrative;
Object.assign(data, narrative.data);
const unlocks = parseAttendanceUnlocks(input.attendanceUnlocks);
if (!unlocks.success) return unlocks;
if (input.attendanceUnlocks !== undefined) {
data.attendanceUnlocks = unlocks.data;
}
const updated = await payload.update({
collection: "missions",
id: input.missionId,

View file

@ -90,7 +90,10 @@ export const handleButtonInteraction = async (
const summary = await getMissionAttendance(payload, missionId);
const hash = attendanceHash(
await fetchAttendanceDocs(payload, missionId),
mission.classification.startDateTime,
{
startDateTime: mission.classification.startDateTime,
unlocks: mission.attendanceUnlocks ?? null,
},
);
await interaction.message.edit({

View file

@ -18,6 +18,7 @@ import {
} from "@/lib/missionRatings";
import { MISSION_RATING_CORE_FACTORS } from "@/lib/missionRatings/factors";
import { ATTENDANCE_CHANGED_CHANNEL } from "@/lib/attendance/realtime";
import { sortAttendanceUnlocks } from "@/lib/intelligence/attendanceUnlocks";
import { botConfig } from "@/bot/config";
const EMBED_COLOR = 0x3b82f6;
@ -73,7 +74,7 @@ const operationTypeLabel = (type: Mission["operationType"]): string => {
* already-live roll-calls when the embed layout changes (v2 added the
* mission-page link); bump it again for future layout-only changes.
*/
const EMBED_SCHEMA_VERSION = 3;
const EMBED_SCHEMA_VERSION = 4;
const SUMMARY_MAX_CHARS = 300;
@ -85,14 +86,41 @@ const renderSummaryForEmbed = (summary: string | null | undefined): string => {
: text;
};
export const attendanceHash = (docs: MissionAttendance[], startDateTime?: string): string => {
export interface AttendanceHashContext {
startDateTime?: string | null;
/**
* Attendance unlock tiers. Required so every call site passes the current
* tiers: an omitted argument would leave live embeds silently stale.
*/
unlocks:
| {
threshold: number;
title: string;
}[]
| null
| undefined;
}
export const attendanceHash = (
docs: MissionAttendance[],
context: AttendanceHashContext,
): string => {
const rows = docs
.map((doc) => {
const userId = typeof doc.user === "object" ? doc.user.id : doc.user;
return [userId, doc.response] as const;
})
.sort((a, b) => a[0] - b[0] || a[1].localeCompare(b[1]));
return JSON.stringify({ rows, startDateTime: startDateTime ?? null, v: EMBED_SCHEMA_VERSION });
const unlocks = sortAttendanceUnlocks(context.unlocks ?? []).map((tier) => [
tier.threshold,
tier.title,
]);
return JSON.stringify({
rows,
startDateTime: context.startDateTime ?? null,
unlocks,
v: EMBED_SCHEMA_VERSION,
});
};
export const fetchAttendanceDocs = async (
@ -188,6 +216,9 @@ export const renderAttendanceEmbed = (
const missionUrl = `${botConfig.appUrl}/intelligence/missions/${mission.id}`;
const names = (users: User[]): string => users.map(memberName).join("\n").slice(0, 1024) || "-";
const summaryText = renderSummaryForEmbed(mission.summary);
// Thresholds and titles only: live unlock status would churn the embed on
// every RSVP, and the hash would have to track the counts too.
const unlockTiers = sortAttendanceUnlocks(mission.attendanceUnlocks ?? []);
return new EmbedBuilder()
.setTitle(missionTitle(mission))
.setURL(missionUrl)
@ -208,6 +239,17 @@ export const renderAttendanceEmbed = (
inline: true,
},
{ name: `❌ No (${summary.counts.no})`, value: names(summary.no), inline: true },
...(unlockTiers.length > 0
? [
{
name: "🔓 Attendance unlocks",
value: unlockTiers
.map((tier) => `${tier.threshold}+: ${tier.title}`)
.join(" · ")
.slice(0, 1024),
},
]
: []),
{ name: "Open the op", value: missionUrl },
);
};
@ -385,10 +427,10 @@ export const postEmbed = async (
mission: Mission,
): Promise<void> => {
const summary = await getMissionAttendance(payload, mission.id);
const hash = attendanceHash(
await fetchAttendanceDocs(payload, mission.id),
mission.classification.startDateTime,
);
const hash = attendanceHash(await fetchAttendanceDocs(payload, mission.id), {
startDateTime: mission.classification.startDateTime,
unlocks: mission.attendanceUnlocks ?? null,
});
const channel = await getOpsChannel(client, opsChannelId);
const message = await channel.send({
embeds: [renderAttendanceEmbed(mission, summary)],
@ -670,10 +712,10 @@ const manageMission = async (
return;
}
const hash = attendanceHash(
await fetchAttendanceDocs(payload, mission.id),
mission.classification.startDateTime,
);
const hash = attendanceHash(await fetchAttendanceDocs(payload, mission.id), {
startDateTime: mission.classification.startDateTime,
unlocks: mission.attendanceUnlocks ?? null,
});
if (hash === mission.discordAttendanceHash) {
return;
}
@ -750,7 +792,10 @@ export const forceRollCall = async (
const summary = await getMissionAttendance(payload, mission.id);
const hash = attendanceHash(
await fetchAttendanceDocs(payload, mission.id),
mission.classification.startDateTime,
{
startDateTime: mission.classification.startDateTime,
unlocks: mission.attendanceUnlocks ?? null,
},
);
await message.edit({
embeds: [renderAttendanceEmbed(mission, summary)],

View file

@ -7,6 +7,11 @@ import {
} from "@/utils/access-control/hasPermission";
import { expireQueuedEntriesForMission, grantQueuedEntriesForMission } from "@/lib/contributions";
import { nextSaturdayStart } from "@/lib/intelligence/fridayTime";
import {
ATTENDANCE_UNLOCK_ACCENTS,
MAX_ATTENDANCE_UNLOCK_TIERS,
validateAttendanceUnlocks,
} from "@/lib/intelligence/attendanceUnlocks";
type AssignmentRef = { id: number } | number;
@ -153,6 +158,16 @@ export const Missions: CollectionConfig = {
},
};
},
// Keep attendance unlock tiers ordered by threshold on every write, so
// admin edits, side-op edits and seeded data all render the same way.
async ({ data }) => {
const tiers = data?.attendanceUnlocks;
if (!Array.isArray(tiers)) return data;
return {
...data,
attendanceUnlocks: [...tiers].sort((a, b) => (a?.threshold ?? 0) - (b?.threshold ?? 0)),
};
},
// Prune role sign-ups whose roleIndex points past the current role list
// (the mission's roles were edited after people signed up). Update-only:
// a mission cannot have sign-ups before it exists.
@ -809,6 +824,62 @@ export const Missions: CollectionConfig = {
},
],
},
{
label: "Attendance Unlocks",
description:
"Features that become available as confirmed attendance grows, shown as a timeline on the mission page.",
fields: [
{
name: "attendanceUnlocks",
type: "array",
label: "Feature Unlocks by Attendance",
labels: { singular: "Unlock Tier", plural: "Unlock Tiers" },
maxRows: MAX_ATTENDANCE_UNLOCK_TIERS,
admin: {
initCollapsed: true,
description:
"Features that become available as confirmed attendance grows. Shown on the mission page as a timeline. Tiers are sorted by threshold when saved.",
},
fields: [
{
name: "threshold",
type: "number",
required: true,
min: 1,
admin: {
description: "Confirmed players needed. Must be unique across tiers.",
},
},
{
name: "title",
type: "text",
required: true,
maxLength: 60,
},
{
name: "description",
type: "textarea",
maxLength: 400,
admin: {
description: "What the tier unlocks. Line breaks are preserved.",
},
},
{
name: "accentColor",
type: "select",
options: ATTENDANCE_UNLOCK_ACCENTS.map((accent) => ({
label: accent.label,
value: accent.value,
})),
admin: {
description: "Optional. Leave empty to light up in plain white.",
},
},
],
validate: (value) => validateAttendanceUnlocks(value) ?? true,
},
],
},
{
label: "Intelligence",
description:

View file

@ -0,0 +1,191 @@
"use client";
import { Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
ATTENDANCE_UNLOCK_ACCENTS,
MAX_ATTENDANCE_UNLOCK_TIERS,
type AttendanceUnlockAccent,
type AttendanceUnlockTierInput,
} from "@/lib/intelligence/attendanceUnlocks";
import { cn } from "@/lib/utils";
/** Client draft keeps the threshold as text so the field can be cleared. */
export interface AttendanceUnlockDraft {
threshold: string;
title: string;
description: string;
accentColor: string | null;
}
export function attendanceUnlockDraftsFromTiers(
tiers:
| {
threshold: number;
title: string;
description?: string | null;
accentColor?: string | null;
}[]
| null
| undefined,
): AttendanceUnlockDraft[] {
return (tiers ?? []).map((tier) => ({
threshold: String(tier.threshold),
title: tier.title,
description: tier.description ?? "",
accentColor: tier.accentColor ?? null,
}));
}
export function attendanceUnlockInputsFromDrafts(
drafts: AttendanceUnlockDraft[],
): AttendanceUnlockTierInput[] {
return drafts
.filter((draft) => draft.title.trim() !== "" && Number(draft.threshold) >= 1)
.map((draft) => ({
threshold: Number(draft.threshold),
title: draft.title.trim(),
description: draft.description.trim() || null,
accentColor: draft.accentColor as AttendanceUnlockAccent | null,
}));
}
interface AttendanceUnlockTiersFieldProps {
value: AttendanceUnlockDraft[];
onChange: (next: AttendanceUnlockDraft[]) => void;
maxPlayers: number;
}
export function AttendanceUnlockTiersField({
value,
onChange,
maxPlayers,
}: AttendanceUnlockTiersFieldProps) {
const update = (index: number, patch: Partial<AttendanceUnlockDraft>) => {
onChange(value.map((row, rowIndex) => (rowIndex === index ? { ...row, ...patch } : row)));
};
return (
<div className="grid gap-3">
<p className="text-xs text-muted-foreground">
Features that become available as confirmed attendance grows. Only "yes" RSVPs count.
Shown on the mission page as a timeline, sorted by threshold.
</p>
{value.map((row, index) => {
const threshold = Number(row.threshold);
const aboveMax = Number.isFinite(threshold) && threshold > maxPlayers;
return (
<div key={index} className="grid gap-2 rounded-md border p-2.5">
<div className="flex items-start gap-2">
<div className="grid w-24 gap-1">
<Label htmlFor={`unlock-threshold-${index}`} className="text-xs">
At players
</Label>
<Input
id={`unlock-threshold-${index}`}
type="number"
min={1}
step={1}
value={row.threshold}
onChange={(event) => update(index, { threshold: event.target.value })}
placeholder="6"
/>
</div>
<div className="grid min-w-0 flex-1 gap-1">
<Label htmlFor={`unlock-title-${index}`} className="text-xs">
Unlock title
</Label>
<Input
id={`unlock-title-${index}`}
value={row.title}
maxLength={60}
onChange={(event) => update(index, { title: event.target.value })}
placeholder="Armor support"
/>
</div>
<Button
type="button"
variant="ghost"
size="icon"
aria-label="Remove unlock tier"
onClick={() => onChange(value.filter((_, rowIndex) => rowIndex !== index))}
>
<Trash2 className="size-4" />
</Button>
</div>
<Textarea
value={row.description}
maxLength={400}
rows={2}
onChange={(event) => update(index, { description: event.target.value })}
placeholder="What this tier unlocks (optional)"
aria-label={`Unlock tier ${index + 1} description`}
/>
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs text-muted-foreground">Accent</span>
<button
type="button"
aria-label="No accent"
aria-pressed={row.accentColor === null}
className={cn(
"size-5 rounded-full border border-border bg-background",
row.accentColor === null &&
"ring-2 ring-ring ring-offset-2 ring-offset-background",
)}
onClick={() => update(index, { accentColor: null })}
/>
{ATTENDANCE_UNLOCK_ACCENTS.map((accent) => (
<button
key={accent.value}
type="button"
aria-label={`${accent.label} accent`}
aria-pressed={row.accentColor === accent.value}
className={cn(
"size-5 rounded-full border border-border",
row.accentColor === accent.value &&
"ring-2 ring-ring ring-offset-2 ring-offset-background",
)}
style={{ backgroundColor: accent.value }}
onClick={() => update(index, { accentColor: accent.value })}
/>
))}
</div>
{aboveMax ? (
<p className="text-xs text-amber-400">
Above max players ({maxPlayers}): this tier can never be reached.
</p>
) : null}
</div>
);
})}
{value.length < MAX_ATTENDANCE_UNLOCK_TIERS ? (
<Button
type="button"
variant="outline"
size="sm"
className="w-fit"
onClick={() =>
onChange([
...value,
{ threshold: String(value.length + 1), title: "", description: "", accentColor: null },
])
}
>
<Plus className="size-4" /> Add unlock tier
</Button>
) : (
<p className="text-xs text-muted-foreground">
{MAX_ATTENDANCE_UNLOCK_TIERS} tiers is the maximum.
</p>
)}
</div>
);
}

View file

@ -35,6 +35,12 @@ import {
SideOpNarrativeFields,
type SideOpNarrative,
} from "@/components/frontend/intelligence/SideOpNarrativeFields";
import {
AttendanceUnlockTiersField,
attendanceUnlockDraftsFromTiers,
attendanceUnlockInputsFromDrafts,
type AttendanceUnlockDraft,
} from "@/components/frontend/intelligence/AttendanceUnlockTiersField";
import type { LexicalJson } from "./LexicalRichTextEditor";
const MISSION_TYPES = ["Zeus", "PvE", "PvP", "PvPvE", "Training", "Special"] as const;
@ -104,6 +110,12 @@ export interface SideOpDialogInitial {
doesRespawn: boolean;
assetCallsign: string;
}[];
attendanceUnlocks?: {
threshold: number;
title: string;
description?: string | null;
accentColor?: string | null;
}[];
}
interface CreateSideOpDialogProps {
@ -154,6 +166,8 @@ export function CreateSideOpDialog({
const [newCampaignName, setNewCampaignName] = useState("");
const [narrative, setNarrative] = useState<SideOpNarrative>(defaultNarrative);
const [narrativeOpen, setNarrativeOpen] = useState(false);
const [unlockTiers, setUnlockTiers] = useState<AttendanceUnlockDraft[]>([]);
const [unlocksOpen, setUnlocksOpen] = useState(false);
const [coverImage, setCoverImage] = useState<{ id: number; url: string } | null>(null);
const [coverImageUploading, setCoverImageUploading] = useState(false);
const [error, setError] = useState<string | null>(null);
@ -163,6 +177,7 @@ export function CreateSideOpDialog({
if (open) {
setError(null);
setNarrativeOpen(false);
setUnlocksOpen(false);
if (initial) {
setName(initial.name);
setCodeName(initial.codeName ?? "");
@ -190,9 +205,11 @@ export function CreateSideOpDialog({
extraction: initial.extraction ?? [],
assetsAvailable: initial.assetsAvailable ?? [],
});
setUnlockTiers(attendanceUnlockDraftsFromTiers(initial.attendanceUnlocks));
} else {
setCoverImage(null);
setNarrative(defaultNarrative());
setUnlockTiers([]);
}
}
}, [open, initial]);
@ -227,6 +244,15 @@ export function CreateSideOpDialog({
};
}
function attendanceUnlockInput() {
// Same guard as the narrative block: an untouched section sends nothing, so
// saving details cannot wipe tiers authored in the admin panel.
if (!unlocksOpen) {
return {};
}
return { attendanceUnlocks: attendanceUnlockInputsFromDrafts(unlockTiers) };
}
function mapInput() {
return mapChoice === "custom" && customMapName.trim() !== ""
? { customMapName }
@ -332,6 +358,7 @@ export function CreateSideOpDialog({
: { campaignId: Number(campaignChoice) }
: {}),
...narrativeInput(),
...attendanceUnlockInput(),
});
if (!result.success) {
setError(result.error ?? "Failed to update the side operation.");
@ -359,6 +386,7 @@ export function CreateSideOpDialog({
newCampaignName: campaignChoice === "new" ? newCampaignName || null : null,
noCampaign: campaignChoice === "none",
...narrativeInput(),
...attendanceUnlockInput(),
});
if (!result.success) {
setError(result.error ?? "Failed to schedule the side operation.");
@ -566,6 +594,24 @@ export function CreateSideOpDialog({
</p>
</div>
<Collapsible open={unlocksOpen} onOpenChange={setUnlocksOpen}>
<CollapsibleTrigger asChild>
<Button type="button" variant="outline" className="w-full justify-between">
Attendance unlocks (optional)
<span className="text-xs text-muted-foreground">
{unlocksOpen ? "Hide" : "Show"}
</span>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="pt-3">
<AttendanceUnlockTiersField
value={unlockTiers}
onChange={setUnlockTiers}
maxPlayers={Number(maxPlayers) || 32}
/>
</CollapsibleContent>
</Collapsible>
<Collapsible open={narrativeOpen} onOpenChange={setNarrativeOpen}>
<CollapsibleTrigger asChild>
<Button type="button" variant="outline" className="w-full justify-between">

View file

@ -0,0 +1,162 @@
import { UnlockIcon } from "lucide-react";
import type { Mission } from "@/payload-types";
import { TacticalFrame, refCodeFrom } from "@/components/frontend/dashboard/tactical";
import {
deriveAttendanceUnlockRows,
type AttendanceUnlockRow,
} from "@/lib/intelligence/attendanceUnlocks";
import { cn } from "@/lib/utils";
interface MissionAttendanceUnlocksProps {
missionId: number;
tiers: Mission["attendanceUnlocks"];
/** Confirmed ("yes") RSVPs only. Tentative never unlocks a tier. */
yesCount: number;
/** Completed or Cancelled: keep lit/dim state, drop the "X TO GO" tags. */
terminal?: boolean;
}
export function MissionAttendanceUnlocks({
missionId,
tiers,
yesCount,
terminal = false,
}: MissionAttendanceUnlocksProps) {
const timeline = deriveAttendanceUnlockRows(tiers, yesCount, { terminal });
if (timeline.total === 0) return null;
return (
<TacticalFrame
classification="OPERATION // ATTENDANCE UNLOCKS"
icon={UnlockIcon}
refCode={`REF ${refCodeFrom(missionId)}`}
grow={false}
>
<div className="relative flex flex-col gap-3 p-4" data-testid="attendance-unlocks">
<span
aria-hidden="true"
className="absolute top-6 bottom-6 left-[21px] w-px bg-border"
/>
{timeline.baseline ? <BaselineRow row={timeline.baseline} /> : null}
{timeline.rows.map((row) => (
<TierRow key={row.threshold} row={row} />
))}
</div>
</TacticalFrame>
);
}
function TimelineNode({ unlocked, accent }: { unlocked: boolean; accent: string | null }) {
if (!unlocked) {
return (
<span className="block size-[11px] rotate-45 border border-muted-foreground/50 bg-background" />
);
}
const color = accent ?? "#ffffff";
return (
<span
className="block size-[11px] rotate-45"
style={{ backgroundColor: color, boxShadow: `0 0 8px ${color}` }}
/>
);
}
function BaselineRow({ row }: { row: AttendanceUnlockRow }) {
return (
<div className="relative z-10 flex gap-3">
<span className="mt-1 flex w-[11px] shrink-0 justify-center">
<TimelineNode unlocked={false} accent={null} />
</span>
<div className="min-w-0 flex-1">
<p className="font-mono text-[9px] uppercase tracking-widest text-muted-foreground/70">
{row.rangeLabel} Players
</p>
<p className="mt-1 text-sm font-medium text-muted-foreground">{row.title}</p>
<p className="mt-0.5 text-xs leading-relaxed text-muted-foreground/70">
{row.description}
</p>
</div>
</div>
);
}
function TierRow({ row }: { row: AttendanceUnlockRow }) {
const accent = row.accentColor;
const color = accent ?? "#ffffff";
const tag = row.unlocked
? "Unlocked"
: row.toGo != null
? `${row.toGo} to go`
: null;
return (
<div
className="relative z-10 flex gap-3"
data-testid={`attendance-unlock-tier-${row.threshold}`}
data-unlocked={row.unlocked ? "true" : "false"}
>
<span className="mt-1 flex w-[11px] shrink-0 justify-center">
<TimelineNode unlocked={row.unlocked} accent={accent} />
</span>
<div
className={cn(
"min-w-0 flex-1 rounded-sm px-3 py-2",
!row.unlocked && "border border-border/60",
)}
style={
row.unlocked
? {
border: `1px solid color-mix(in srgb, ${color} 35%, transparent)`,
borderLeft: `2px solid ${color}`,
backgroundColor: `color-mix(in srgb, ${color} 8%, transparent)`,
}
: undefined
}
>
<div className="flex flex-wrap items-center justify-between gap-x-2 gap-y-1">
<p
className={cn(
"font-mono text-[9px] uppercase tracking-widest",
row.unlocked ? undefined : "text-muted-foreground/70",
)}
style={row.unlocked ? { color } : undefined}
>
{row.rangeLabel} Players
</p>
{tag ? (
<span
className={cn(
"rounded-sm border px-1.5 py-0.5 font-mono text-[9px] font-semibold uppercase tracking-wider",
row.unlocked
? undefined
: "border-border/60 text-muted-foreground",
)}
style={row.unlocked ? { borderColor: color, color } : undefined}
>
{tag}
</span>
) : null}
</div>
<p
className={cn(
"mt-1 text-sm font-medium",
row.unlocked ? undefined : "text-muted-foreground",
)}
style={row.unlocked ? { color } : undefined}
>
{row.title}
</p>
{row.description ? (
<p
className={cn(
"mt-0.5 text-xs leading-relaxed whitespace-pre-line",
row.unlocked ? "text-foreground/80" : "text-muted-foreground/70",
)}
>
{row.description}
</p>
) : null}
</div>
</div>
);
}

View file

@ -0,0 +1,273 @@
/**
* Attendance-gated feature unlocks.
*
* Pure module (no Payload import) shared by the mission page, the side-op
* editor, the collection validation and the Discord embed. A tier is a
* threshold of confirmed ("yes") players plus the feature it unlocks. Tentative
* RSVPs never count toward a threshold.
*/
export type AttendanceUnlockAccent =
| "#f59e0b"
| "#22d3ee"
| "#34d399"
| "#a78bfa"
| "#f87171"
| "#38bdf8";
export interface AttendanceUnlockAccentOption {
label: string;
value: AttendanceUnlockAccent;
}
/** Fixed accent palette. Stored as hex so inline styles stay type-safe. */
export const ATTENDANCE_UNLOCK_ACCENTS: readonly AttendanceUnlockAccentOption[] = [
{ label: "Amber", value: "#f59e0b" },
{ label: "Cyan", value: "#22d3ee" },
{ label: "Emerald", value: "#34d399" },
{ label: "Violet", value: "#a78bfa" },
{ label: "Red", value: "#f87171" },
{ label: "Sky", value: "#38bdf8" },
];
export const ATTENDANCE_UNLOCK_ACCENT_VALUES: readonly string[] = ATTENDANCE_UNLOCK_ACCENTS.map(
(accent) => accent.value,
);
export const MAX_ATTENDANCE_UNLOCK_TIERS = 10;
export const ATTENDANCE_UNLOCK_TITLE_MAX = 60;
export const ATTENDANCE_UNLOCK_DESCRIPTION_MAX = 400;
/** Shape used for writing tiers (collection rows and side-op input). */
export interface AttendanceUnlockTierInput {
threshold: number;
title: string;
description?: string | null;
accentColor?: AttendanceUnlockAccent | null;
}
export interface AttendanceUnlockRow {
/** Plain hyphen range: "0-5", "6-7", "8+". */
rangeLabel: string;
/** Null for the baseline row. */
threshold: number | null;
title: string;
description: string | null;
accentColor: string | null;
unlocked: boolean;
/** Players still needed, or null when terminal or for the baseline row. */
toGo: number | null;
}
export interface AttendanceUnlockTimeline {
/** Tier rows only, ascending. */
rows: AttendanceUnlockRow[];
/** Present only when the lowest threshold is greater than 2. */
baseline: AttendanceUnlockRow | null;
unlockedCount: number;
total: number;
}
interface DeriveOptions {
/** Completed or Cancelled: keep lit/dim state, drop the "X TO GO" tags. */
terminal: boolean;
}
const isAccentValue = (value: string): boolean =>
ATTENDANCE_UNLOCK_ACCENT_VALUES.includes(value);
/**
* Sort a copy of the tiers ascending. Never trust stored order: admin edits,
* side-op writes, and older data can all disagree.
*/
export function sortAttendanceUnlocks<T extends { threshold: number }>(tiers: readonly T[]): T[] {
return [...tiers].sort((a, b) => a.threshold - b.threshold);
}
export function deriveAttendanceUnlockRows(
tiers: readonly AttendanceUnlockTierInput[] | null | undefined,
yesCount: number,
{ terminal }: DeriveOptions,
): AttendanceUnlockTimeline {
const sorted = sortAttendanceUnlocks(
(tiers ?? []).filter((tier) => Number.isFinite(tier.threshold)),
);
if (sorted.length === 0) {
return { rows: [], baseline: null, unlockedCount: 0, total: 0 };
}
const confirmed = Math.max(0, Math.floor(yesCount));
const rows: AttendanceUnlockRow[] = sorted.map((tier, index) => {
const next = sorted[index + 1];
const unlocked = confirmed >= tier.threshold;
return {
rangeLabel: next ? `${tier.threshold}-${next.threshold - 1}` : `${tier.threshold}+`,
threshold: tier.threshold,
title: tier.title,
description: tier.description ?? null,
accentColor: tier.accentColor ?? null,
unlocked,
toGo: !unlocked && !terminal ? tier.threshold - confirmed : null,
};
});
// A baseline of 0-0 or 0-1 reads as noise; only show it when the first tier
// sits far enough above zero to be meaningful.
const firstThreshold = sorted[0].threshold;
const baseline: AttendanceUnlockRow | null =
firstThreshold > 2
? {
rangeLabel: `0-${firstThreshold - 1}`,
threshold: null,
title: "Standard mission parameters",
description: "No special unlocks at this attendance level.",
accentColor: null,
unlocked: false,
toGo: null,
}
: null;
return {
rows,
baseline,
unlockedCount: rows.filter((row) => row.unlocked).length,
total: rows.length,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/**
* Shared validation for every write path: the Payload collection and the
* side-op parser. Returns a human-readable message, or null when valid.
*/
export function validateAttendanceUnlocks(value: unknown): string | null {
if (value === null || value === undefined) return null;
if (!Array.isArray(value)) return "Attendance unlocks must be a list.";
if (value.length > MAX_ATTENDANCE_UNLOCK_TIERS) {
return `Attendance unlocks are limited to ${MAX_ATTENDANCE_UNLOCK_TIERS} tiers.`;
}
const seen = new Set<number>();
for (let index = 0; index < value.length; index += 1) {
const row = value[index];
const label = `Unlock tier ${index + 1}`;
if (!isRecord(row)) return `${label} is invalid.`;
const threshold = row.threshold;
if (typeof threshold !== "number" || !Number.isInteger(threshold) || threshold < 1) {
return `${label} needs a positive whole-number threshold.`;
}
if (seen.has(threshold)) {
return `Duplicate threshold ${threshold}: each unlock tier needs a unique threshold.`;
}
seen.add(threshold);
const title = typeof row.title === "string" ? row.title.trim() : "";
if (title.length === 0) return `${label} needs a title.`;
if (title.length > ATTENDANCE_UNLOCK_TITLE_MAX) {
return `${label} title is too long (${ATTENDANCE_UNLOCK_TITLE_MAX} characters max).`;
}
const description = row.description;
if (
description !== null &&
description !== undefined &&
(typeof description !== "string" ||
description.length > ATTENDANCE_UNLOCK_DESCRIPTION_MAX)
) {
return `${label} description is too long (${ATTENDANCE_UNLOCK_DESCRIPTION_MAX} characters max).`;
}
const accent = row.accentColor;
if (
accent !== null &&
accent !== undefined &&
accent !== "" &&
(typeof accent !== "string" || !isAccentValue(accent))
) {
return `${label} accent is not in the palette.`;
}
}
return null;
}
export type ParseAttendanceUnlocksResult =
| { success: true; data: AttendanceUnlockTierInput[] }
| { success: false; error: string };
/**
* Single gate for side-op writes (both actions use overrideAccess). Admin
* writes are covered by the collection field's own validate, which calls the
* same shared validation above.
*/
export function parseAttendanceUnlocks(value: unknown): ParseAttendanceUnlocksResult {
if (value === null || value === undefined) return { success: true, data: [] };
if (!Array.isArray(value)) {
return { success: false, error: "Attendance unlocks must be a list." };
}
const rows: AttendanceUnlockTierInput[] = [];
for (const raw of value) {
if (!isRecord(raw)) {
return { success: false, error: "Invalid attendance unlock tier." };
}
const threshold = raw.threshold;
if (typeof threshold !== "number" || !Number.isInteger(threshold) || threshold < 1) {
return { success: false, error: "Each unlock tier needs a positive whole-number threshold." };
}
const title = typeof raw.title === "string" ? raw.title.trim() : "";
if (title.length === 0) {
return { success: false, error: "Each unlock tier needs a title." };
}
if (title.length > ATTENDANCE_UNLOCK_TITLE_MAX) {
return {
success: false,
error: `Unlock tier titles are limited to ${ATTENDANCE_UNLOCK_TITLE_MAX} characters.`,
};
}
if (
raw.description !== null &&
raw.description !== undefined &&
typeof raw.description !== "string"
) {
return { success: false, error: "Unlock tier descriptions must be text." };
}
const description =
typeof raw.description === "string" && raw.description.trim() !== ""
? raw.description.trim()
: null;
if (description && description.length > ATTENDANCE_UNLOCK_DESCRIPTION_MAX) {
return {
success: false,
error: `Unlock tier descriptions are limited to ${ATTENDANCE_UNLOCK_DESCRIPTION_MAX} characters.`,
};
}
const accentColor =
raw.accentColor === null || raw.accentColor === undefined || raw.accentColor === ""
? null
: raw.accentColor;
if (accentColor !== null && typeof accentColor !== "string") {
return { success: false, error: "Unlock tier accent is not in the palette." };
}
if (typeof accentColor === "string" && !isAccentValue(accentColor)) {
return { success: false, error: "Unlock tier accent is not in the palette." };
}
rows.push({
threshold,
title,
description,
accentColor: accentColor as AttendanceUnlockAccent | null,
});
}
const error = validateAttendanceUnlocks(rows);
if (error) return { success: false, error };
return { success: true, data: sortAttendanceUnlocks(rows) };
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_missions_attendance_unlocks_accent_color" AS ENUM('#f59e0b', '#22d3ee', '#34d399', '#a78bfa', '#f87171', '#38bdf8');
CREATE TABLE "missions_attendance_unlocks" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"threshold" numeric NOT NULL,
"title" varchar NOT NULL,
"description" varchar,
"accent_color" "enum_missions_attendance_unlocks_accent_color"
);
ALTER TABLE "missions_attendance_unlocks" ADD CONSTRAINT "missions_attendance_unlocks_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."missions"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "missions_attendance_unlocks_order_idx" ON "missions_attendance_unlocks" USING btree ("_order");
CREATE INDEX "missions_attendance_unlocks_parent_id_idx" ON "missions_attendance_unlocks" USING btree ("_parent_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP TABLE "missions_attendance_unlocks" CASCADE;
DROP TYPE "public"."enum_missions_attendance_unlocks_accent_color";`)
}

View file

@ -162,6 +162,7 @@ import * as migration_20261118_143000_add_wiki_pages_draft_and_created_by from '
import * as migration_20261118_184813_add_faction_relation_entries from './20261118_184813_add_faction_relation_entries';
import * as migration_20261118_184851_drop_factions_relationships_array from './20261118_184851_drop_factions_relationships_array';
import * as migration_20261120_234950_add_locker_unlimited from './20261120_234950_add_locker_unlimited';
import * as migration_20261121_015435_add_mission_attendance_unlocks from './20261121_015435_add_mission_attendance_unlocks';
export const migrations = [
{
@ -982,6 +983,11 @@ export const migrations = [
{
up: migration_20261120_234950_add_locker_unlimited.up,
down: migration_20261120_234950_add_locker_unlimited.down,
name: '20261120_234950_add_locker_unlimited'
name: '20261120_234950_add_locker_unlimited',
},
{
up: migration_20261121_015435_add_mission_attendance_unlocks.up,
down: migration_20261121_015435_add_mission_attendance_unlocks.down,
name: '20261121_015435_add_mission_attendance_unlocks'
},
];

View file

@ -4597,6 +4597,27 @@ export interface Mission {
id?: string | null;
}[]
| null;
/**
* Features that become available as confirmed attendance grows. Shown on the mission page as a timeline. Tiers are sorted by threshold when saved.
*/
attendanceUnlocks?:
| {
/**
* Confirmed players needed. Must be unique across tiers.
*/
threshold: number;
title: string;
/**
* What the tier unlocks. Line breaks are preserved.
*/
description?: string | null;
/**
* Optional. Leave empty to light up in plain white.
*/
accentColor?: ('#f59e0b' | '#22d3ee' | '#34d399' | '#a78bfa' | '#f87171' | '#38bdf8') | null;
id?: string | null;
}[]
| null;
/**
* Likelihood that the unit will encounter each enemy force type during the mission. Rendered as a color-coded table on the mission page.
*/
@ -10864,6 +10885,15 @@ export interface MissionsSelect<T extends boolean = true> {
threatLevel?: T;
id?: T;
};
attendanceUnlocks?:
| T
| {
threshold?: T;
title?: T;
description?: T;
accentColor?: T;
id?: T;
};
threatAssessment?:
| T
| {

View file

@ -0,0 +1,141 @@
import { expect, test, type Page } from "@playwright/test";
/**
* Attendance unlock timeline: a mission with two tiers renders the reached tier
* in its accent and the unreached one muted with a TO GO tag. Lowering the
* confirmed count re-dims both on the next load.
*
* Seeding note: attendance rows are created through REST for the signed-in dev
* account. The timeline counts rows responding "yes" (that is what
* getMissionAttendance summarises), so repeated rows are a valid fixture and
* avoid provisioning a squad of users per run.
*/
test.describe("Mission attendance unlocks", () => {
let mapId: number | null = null;
let missionId: number | null = null;
let meId: number | null = null;
const attendanceIds: number[] = [];
async function login(page: Page) {
const res = await page.request.post("/api/users/login", {
data: { username: "dev", password: "Test123" },
});
expect(res.ok(), `login failed: ${res.status()}`).toBe(true);
}
test.afterAll(async ({ browser }) => {
const page = await browser.newPage();
await login(page);
for (const id of attendanceIds) {
await page.request.delete(`/api/mission-attendances/${id}`);
}
if (missionId) await page.request.delete(`/api/missions/${missionId}`);
if (mapId) await page.request.delete(`/api/maps/${mapId}`);
await page.close();
});
test("lights reached tiers and dims the rest, then re-dims after attendance drops", async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 1000 });
await login(page);
// Tours would overlay the page; opt this browser out before any page runs.
await page.addInitScript(() => window.localStorage.setItem("ptf:tours:opted-out", "1"));
const mapRes = await page.request.post("/api/maps", {
data: {
name: "E2E Attendance Unlocks Map",
worldSizeWidth: 8192,
worldSizeHeight: 8192,
basemapMode: "image",
isActive: true,
},
});
expect(mapRes.ok(), await mapRes.text()).toBe(true);
mapId = (await mapRes.json()).doc.id;
const meRes = await page.request.get("/api/users/me");
meId = (await meRes.json()).user.id as number;
const missionRes = await page.request.post("/api/missions", {
data: {
name: "E2E Attendance Unlocks",
codeName: "E2E-UNLOCK",
summary: "Attendance unlock timeline e2e mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
startDateTime: new Date(Date.now() + 3 * 86_400_000).toISOString(),
estimatedDuration: 90,
},
ownershipAndStatus: { authors: [meId], status: "Scheduled", visibility: "unit" },
missionRoles: { maxPlayers: 12, providedRoles: [] },
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
briefing: [],
attendanceUnlocks: [
{
threshold: 6,
title: "Armor Support",
description: "Gain access to an M1A1 for the operation.",
accentColor: "#f59e0b",
},
{
threshold: 8,
title: "Air Support",
description: "Call in a rotary gunship.",
accentColor: "#22d3ee",
},
],
},
});
expect(missionRes.ok(), await missionRes.text()).toBe(true);
missionId = (await missionRes.json()).doc.id;
const addYes = async (count: number) => {
for (let index = 0; index < count; index += 1) {
const res = await page.request.post("/api/mission-attendances", {
data: { mission: missionId, user: meId, response: "yes" },
});
expect(res.ok(), await res.text()).toBe(true);
attendanceIds.push((await res.json()).doc.id);
}
};
await addYes(6);
await page.goto(`/intelligence/missions/${missionId}`);
const card = page.locator('[data-testid="attendance-unlocks"]:visible').first();
await expect(card).toBeVisible();
const unlocked = card.getByTestId("attendance-unlock-tier-6");
const locked = card.getByTestId("attendance-unlock-tier-8");
await expect(unlocked).toHaveAttribute("data-unlocked", "true");
await expect(unlocked).toContainText("Armor Support");
await expect(unlocked).toContainText("Unlocked");
// The accent is applied inline, so the computed colour is exact.
await expect(unlocked.locator("p").first()).toHaveCSS("color", "rgb(245, 158, 11)");
await expect(locked).toHaveAttribute("data-unlocked", "false");
await expect(locked).toContainText("Air Support");
await expect(locked).toContainText("2 to go");
await expect(locked.locator("p").first()).not.toHaveCSS("color", "rgb(245, 158, 11)");
// Drop below the first threshold: both tiers dim.
const removed = attendanceIds.pop();
expect(removed).toBeTruthy();
const deleteRes = await page.request.delete(`/api/mission-attendances/${removed}`);
expect(deleteRes.ok(), await deleteRes.text()).toBe(true);
await page.reload();
const reloaded = page.locator('[data-testid="attendance-unlocks"]:visible').first();
await expect(reloaded).toBeVisible();
await expect(reloaded.getByTestId("attendance-unlock-tier-6")).toHaveAttribute(
"data-unlocked",
"false",
);
await expect(reloaded.getByTestId("attendance-unlock-tier-6")).toContainText("1 to go");
await expect(reloaded.getByTestId("attendance-unlock-tier-8")).toContainText("3 to go");
await expect(reloaded.getByTestId("attendance-unlock-tier-6")).not.toContainText("Unlocked");
});
});

View file

@ -0,0 +1,367 @@
import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Map as MissionMap, Mission, MissionAttendance } from "@/payload-types";
import {
attendanceHash,
renderAttendanceEmbed,
} from "@/bot/services/missionEmbeds";
import type { MissionAttendanceSummary } from "@/lib/attendance";
import {
MAX_ATTENDANCE_UNLOCK_TIERS,
deriveAttendanceUnlockRows,
parseAttendanceUnlocks,
} from "@/lib/intelligence/attendanceUnlocks";
let payload: Payload;
const RUN = `unlocks-${Date.now().toString(36)}`;
const START = "2026-12-04T19:00:00.000Z";
const tiers = [
{ threshold: 6, title: "Armor", description: "Gain access to an M1A1.", accentColor: "#f59e0b" as const },
{ threshold: 8, title: "Air Support", description: "Call in a rotary gunship.", accentColor: "#22d3ee" as const },
];
describe("Attendance unlock derivation", () => {
it("builds plain hyphen ranges and ends the last row with +", () => {
const timeline = deriveAttendanceUnlockRows(tiers, 0, { terminal: false });
expect(timeline.rows.map((row) => row.rangeLabel)).toEqual(["6-7", "8+"]);
expect(timeline.total).toBe(2);
});
it("adds a baseline row only when the first threshold is above 2", () => {
const atSix = deriveAttendanceUnlockRows(tiers, 0, { terminal: false });
expect(atSix.baseline).toMatchObject({
rangeLabel: "0-5",
title: "Standard mission parameters",
description: "No special unlocks at this attendance level.",
});
const firstTierAtOne = deriveAttendanceUnlockRows([{ threshold: 1, title: "One" }], 0, {
terminal: false,
});
expect(firstTierAtOne.baseline).toBeNull();
const firstTierAtTwo = deriveAttendanceUnlockRows([{ threshold: 2, title: "Two" }], 0, {
terminal: false,
});
expect(firstTierAtTwo.baseline).toBeNull();
const firstTierAtThree = deriveAttendanceUnlockRows([{ threshold: 3, title: "Three" }], 0, {
terminal: false,
});
expect(firstTierAtThree.baseline?.rangeLabel).toBe("0-2");
});
it("counts unlocked tiers from yes attendance only", () => {
const counts: Record<number, number> = { 5: 0, 6: 1, 7: 1, 8: 2 };
for (const [yesCount, expected] of Object.entries(counts)) {
const timeline = deriveAttendanceUnlockRows(tiers, Number(yesCount), { terminal: false });
expect(timeline.unlockedCount).toBe(expected);
}
});
it("exposes X TO GO on locked tiers and suppresses it on terminal missions", () => {
const live = deriveAttendanceUnlockRows(tiers, 5, { terminal: false });
expect(live.rows[0].unlocked).toBe(false);
expect(live.rows[0].toGo).toBe(1);
expect(live.rows[1].toGo).toBe(3);
const terminal = deriveAttendanceUnlockRows(tiers, 6, { terminal: true });
expect(terminal.rows[0].unlocked).toBe(true);
expect(terminal.rows[0].toGo).toBeNull();
expect(terminal.rows[1].unlocked).toBe(false);
expect(terminal.rows[1].toGo).toBeNull();
expect(terminal.unlockedCount).toBe(1);
});
it("never trusts stored order and handles an empty tier list", () => {
const outOfOrder = deriveAttendanceUnlockRows(
[
{ threshold: 8, title: "Air Support" },
{ threshold: 6, title: "Armor" },
],
6,
{ terminal: false },
);
expect(outOfOrder.rows.map((row) => row.threshold)).toEqual([6, 8]);
expect(deriveAttendanceUnlockRows(null, 6, { terminal: false })).toEqual({
rows: [],
baseline: null,
unlockedCount: 0,
total: 0,
});
expect(deriveAttendanceUnlockRows([], 0, { terminal: false }).total).toBe(0);
});
});
describe("parseAttendanceUnlocks", () => {
it("accepts valid tiers, sorts them and permits a threshold above max players", () => {
const parsed = parseAttendanceUnlocks([
{ threshold: 200, title: " Impossible", description: " Never reached ", accentColor: "#f59e0b" },
{ threshold: 6, title: "Armor", description: "", accentColor: null },
]);
expect(parsed.success).toBe(true);
if (!parsed.success) return;
expect(parsed.data.map((row) => row.threshold)).toEqual([6, 200]);
expect(parsed.data[0]).toMatchObject({
threshold: 6,
title: "Armor",
description: null,
accentColor: null,
});
expect(parsed.data[1]).toMatchObject({ threshold: 200, title: "Impossible", description: "Never reached" });
});
it("treats undefined as an empty list", () => {
expect(parseAttendanceUnlocks(undefined)).toEqual({ success: true, data: [] });
expect(parseAttendanceUnlocks(null)).toEqual({ success: true, data: [] });
});
it("rejects duplicate thresholds", () => {
const parsed = parseAttendanceUnlocks([
{ threshold: 6, title: "Armor" },
{ threshold: 6, title: "Air Support" },
]);
expect(parsed.success).toBe(false);
if (!parsed.success) expect(parsed.error).toMatch(/Duplicate threshold 6/);
});
it("rejects non-integer and non-positive thresholds", () => {
for (const threshold of [6.5, 0, -1, "6", Number.NaN]) {
const parsed = parseAttendanceUnlocks([{ threshold, title: "Armor" }]);
expect(parsed.success).toBe(false);
}
});
it("rejects empty and over-long titles, over-long descriptions and unknown accents", () => {
expect(parseAttendanceUnlocks([{ threshold: 6, title: " " }]).success).toBe(false);
expect(parseAttendanceUnlocks([{ threshold: 6, title: "x".repeat(61) }]).success).toBe(false);
expect(
parseAttendanceUnlocks([{ threshold: 6, title: "Armor", description: "x".repeat(401) }])
.success,
).toBe(false);
expect(
parseAttendanceUnlocks([{ threshold: 6, title: "Armor", accentColor: "#000000" }]).success,
).toBe(false);
});
it("rejects more than the tier cap", () => {
const tooMany = Array.from({ length: MAX_ATTENDANCE_UNLOCK_TIERS + 1 }, (_, index) => ({
threshold: index + 1,
title: `Tier ${index + 1}`,
}));
expect(parseAttendanceUnlocks(tooMany).success).toBe(false);
});
});
describe("Attendance unlocks collection behaviour", () => {
let mapId: number;
let authorId: number;
const missionIds: number[] = [];
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;
// Authors are required. Create a throwaway owner and remove it, with the
// profile and bank account that user hooks provision.
const author = (await payload.create({
collection: "users",
data: {
username: `${RUN}-author`,
discordUsername: `${RUN}-author`,
displayName: "UNLOCKS AUTHOR",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
authorId = author.id;
});
afterAll(async () => {
for (const id of missionIds) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
const accounts = await payload
.find({
collection: "bank-accounts",
where: { ownerUser: { equals: authorId } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const account of accounts?.docs ?? []) {
await payload
.delete({ collection: "bank-accounts", id: account.id, overrideAccess: true })
.catch(() => {});
}
const profiles = await payload
.find({
collection: "profiles",
where: { user: { equals: authorId } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const profile of profiles?.docs ?? []) {
await payload
.delete({ collection: "profiles", id: profile.id, overrideAccess: true })
.catch(() => {});
}
await payload.delete({ collection: "users", id: authorId, overrideAccess: true }).catch(() => {});
});
const missionData = (label: string, attendanceUnlocks: unknown) =>
({
name: `${RUN} ${label}`,
summary: "Attendance unlock collection test mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
startDateTime: START,
estimatedDuration: 120,
},
ownershipAndStatus: {
authors: [authorId],
status: "Scheduled",
visibility: "unit",
},
missionRoles: { maxPlayers: 12 },
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
briefing: [],
attendanceUnlocks,
}) as never;
it("stores out-of-order tiers sorted by threshold", async () => {
const mission = (await payload.create({
collection: "missions",
data: missionData("sorted", [
{ threshold: 8, title: "Air Support", accentColor: "#22d3ee" },
{ threshold: 6, title: "Armor", accentColor: "#f59e0b" },
]),
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id);
expect((mission.attendanceUnlocks ?? []).map((tier) => tier.threshold)).toEqual([6, 8]);
const reread = (await payload.findByID({
collection: "missions",
id: mission.id,
depth: 0,
overrideAccess: true,
})) as unknown as Mission;
expect((reread.attendanceUnlocks ?? []).map((tier) => tier.title)).toEqual([
"Armor",
"Air Support",
]);
});
it("fails a write with a duplicate threshold", async () => {
let thrown: unknown;
try {
const mission = await payload.create({
collection: "missions",
data: missionData("duplicate", [
{ threshold: 6, title: "Armor" },
{ threshold: 6, title: "Air Support" },
]),
overrideAccess: true,
depth: 0,
});
missionIds.push((mission as unknown as Mission).id);
} catch (error) {
thrown = error;
}
expect(thrown).toBeTruthy();
// Payload reports the invalid field path; the exact message is covered by
// the shared validator tests above.
expect(String(thrown)).toMatch(/Attendance Unlocks > Feature Unlocks by Attendance/);
expect(String(thrown)).not.toMatch(/Authors/);
});
});
describe("Attendance embed and hash", () => {
const summary: MissionAttendanceSummary = {
yes: [],
no: [],
tentative: [],
counts: { yes: 6, no: 0, tentative: 1 },
};
const embedMission = (attendanceUnlocks: Mission["attendanceUnlocks"]) =>
({
id: 4242,
name: "Operation Test",
codeName: "OP:TST",
summary: "Test summary",
operationType: "main",
classification: {
map: 1,
missionType: "PvE",
startDateTime: START,
estimatedDuration: 120,
},
ownershipAndStatus: { authors: [], status: "Scheduled", visibility: "unit" },
missionRoles: { maxPlayers: 32 },
briefing: [],
attendanceUnlocks,
}) as unknown as Mission;
const fieldsOf = (mission: Mission) =>
renderAttendanceEmbed(mission, summary).toJSON().fields ?? [];
it("adds one compact attendance unlocks field only when tiers exist", () => {
const withTiers = fieldsOf(embedMission(tiers));
const unlockField = withTiers.find((field) => field.name === "🔓 Attendance unlocks");
expect(unlockField?.value).toBe("6+: Armor · 8+: Air Support");
const withoutTiers = fieldsOf(embedMission(null));
expect(withoutTiers.some((field) => field.name === "🔓 Attendance unlocks")).toBe(false);
});
const docs = [
{ user: 1, response: "yes" },
{ user: 2, response: "tentative" },
] as unknown as MissionAttendance[];
it("hashes the tiers so title and threshold changes re-render the embed", () => {
const base = attendanceHash(docs, { startDateTime: START, unlocks: tiers });
expect(attendanceHash(docs, { startDateTime: START, unlocks: [...tiers] })).toBe(base);
const renamed = attendanceHash(docs, {
startDateTime: START,
unlocks: [{ ...tiers[0], title: "Armor (renamed)" }, tiers[1]],
});
expect(renamed).not.toBe(base);
const retuned = attendanceHash(docs, {
startDateTime: START,
unlocks: [{ ...tiers[0], threshold: 5 }, tiers[1]],
});
expect(retuned).not.toBe(base);
});
});