From 4022e5b5f12ae412a01e5dc93f8f230578b6d579 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Sat, 21 Nov 2026 02:30:48 -0500 Subject: [PATCH] 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 --- .../intelligence/missions/[id]/page.tsx | 30 +- .../intelligence/missions/actions.ts | 19 + src/bot/events/interactionCreate.ts | 5 +- src/bot/services/missionEmbeds.ts | 69 +- src/collections/intelligence/Missions.ts | 71 + .../AttendanceUnlockTiersField.tsx | 191 + .../intelligence/CreateSideOpDialog.tsx | 46 + .../intelligence/MissionAttendanceUnlocks.tsx | 162 + src/lib/intelligence/attendanceUnlocks.ts | 273 + ...015435_add_mission_attendance_unlocks.json | 46422 ++++++++++++++++ ...1_015435_add_mission_attendance_unlocks.ts | 25 + src/migrations/index.ts | 8 +- src/payload-types.ts | 30 + .../mission-attendance-unlocks.e2e.spec.ts | 141 + tests/int/attendance-unlocks.int.spec.ts | 367 + 15 files changed, 47842 insertions(+), 17 deletions(-) create mode 100644 src/components/frontend/intelligence/AttendanceUnlockTiersField.tsx create mode 100644 src/components/frontend/intelligence/MissionAttendanceUnlocks.tsx create mode 100644 src/lib/intelligence/attendanceUnlocks.ts create mode 100644 src/migrations/20261121_015435_add_mission_attendance_unlocks.json create mode 100644 src/migrations/20261121_015435_add_mission_attendance_unlocks.ts create mode 100644 tests/e2e/mission-attendance-unlocks.e2e.spec.ts create mode 100644 tests/int/attendance-unlocks.int.spec.ts diff --git a/src/app/(frontend)/intelligence/missions/[id]/page.tsx b/src/app/(frontend)/intelligence/missions/[id]/page.tsx index ccce4a43..6ab6edb4 100644 --- a/src/app/(frontend)/intelligence/missions/[id]/page.tsx +++ b/src/app/(frontend)/intelligence/missions/[id]/page.tsx @@ -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 = ( + + ); + // 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 */} -
{attendanceCard}
+ {/* Attendance and its unlock timeline sit right under the hero on stacked (below-xl) layouts */} +
+ {attendanceCard} + {unlocksCard} +
{/* ── Main Content (2/3) ──────────────────────────── */}
@@ -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 /> )} -
{attendanceCard}
+
+ {attendanceCard} + {unlocksCard} +
{/* Campaign Card */} {campaign && ( diff --git a/src/app/(frontend)/intelligence/missions/actions.ts b/src/app/(frontend)/intelligence/missions/actions.ts index cc71fea0..35de3216 100644 --- a/src/app/(frontend)/intelligence/missions/actions.ts +++ b/src/app/(frontend)/intelligence/missions/actions.ts @@ -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, diff --git a/src/bot/events/interactionCreate.ts b/src/bot/events/interactionCreate.ts index 537f5c76..a42b7d27 100644 --- a/src/bot/events/interactionCreate.ts +++ b/src/bot/events/interactionCreate.ts @@ -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({ diff --git a/src/bot/services/missionEmbeds.ts b/src/bot/services/missionEmbeds.ts index 2f754031..2b78abf7 100644 --- a/src/bot/services/missionEmbeds.ts +++ b/src/bot/services/missionEmbeds.ts @@ -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 => { 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)], diff --git a/src/collections/intelligence/Missions.ts b/src/collections/intelligence/Missions.ts index 5031660a..b80086ce 100644 --- a/src/collections/intelligence/Missions.ts +++ b/src/collections/intelligence/Missions.ts @@ -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: diff --git a/src/components/frontend/intelligence/AttendanceUnlockTiersField.tsx b/src/components/frontend/intelligence/AttendanceUnlockTiersField.tsx new file mode 100644 index 00000000..d4dadddd --- /dev/null +++ b/src/components/frontend/intelligence/AttendanceUnlockTiersField.tsx @@ -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) => { + onChange(value.map((row, rowIndex) => (rowIndex === index ? { ...row, ...patch } : row))); + }; + + return ( +
+

+ Features that become available as confirmed attendance grows. Only "yes" RSVPs count. + Shown on the mission page as a timeline, sorted by threshold. +

+ + {value.map((row, index) => { + const threshold = Number(row.threshold); + const aboveMax = Number.isFinite(threshold) && threshold > maxPlayers; + return ( +
+
+
+ + update(index, { threshold: event.target.value })} + placeholder="6" + /> +
+
+ + update(index, { title: event.target.value })} + placeholder="Armor support" + /> +
+ +
+ +