1
0
Fork 0

feat(bot): add /rollcall to force-send or refresh a mission roll-call

This commit is contained in:
Jason Fraley 2026-10-11 15:26:17 -04:00
parent bf36e1e2be
commit dda9f08f33
7 changed files with 486 additions and 2 deletions

View file

@ -114,6 +114,8 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
**Embed contents**: mission name + codeName (title links to the mission page), mission summary below the title (truncated to 300 characters with an ellipsis), `<t:epoch:F>` absolute + `<t:epoch:R>` relative start time, operationType, maxPlayers, and three sections — ✅ Yes (n), 🤔 Tentative (n), ❌ No (n) — with member display names, plus an "Open the op" field with the mission-page URL. `attendanceHash` carries an embed schema version so layout-only changes force one idempotent re-render of already-live roll-calls.
**Manual trigger**: `/rollcall` (staff only, guild-only). Optional `mission` option (ID, name, or code name, same resolution UX as `/remind-evaluations`; omitted = the soonest future Scheduled unit-visible mission). Bypasses the 3-day lead-time gate and the one-shot marker only: it re-renders the live roll-call message in place, or posts a fresh one when no live message exists (including after a manual deletion, which the automatic flow refuses to repost). Rejects non-Scheduled, non-unit-visible, and already-started ops with an ephemeral explanation. Logic: `forceRollCall` in `services/missionEmbeds.ts`, target helpers in `src/lib/intelligence/rollCall.ts`.
### C. Notifications bridge + announcements (feature 3)
- **Poll loop** (every `DISCORD_NOTIFICATION_POLL_MS`, default 20s): query `user-notifications` with `id > lastSeenId`, sorted ascending, limit 50. In-memory cursor; on startup, cursor = current max id (never DM pre-startup history).

View file

@ -25,6 +25,7 @@ bot/
announce.ts # /announce (guild-only, staff only; message omitted = compose modal with channel picker, handler in this file)
changelog.ts # /changelog (guild-only, staff only; posts a CHANGELOG.md entry to #releases, native markdown, splits long entries)
remindEvaluations.ts # /remind-evaluations (guild-only, staff only, manual evaluation-reminder trigger)
rollcall.ts # /rollcall (guild-only, staff only, force-send/refresh a roll-call)
events/
interactionCreate.ts # Routes ptf-att: RSVP button interactions
@ -50,7 +51,7 @@ bot/
## Command registration scope
- **Global** (DM-usable): `signup`, `link`, `ping`
- **Guild-only**: `announce`, `remind-evaluations` (guild-scoped commands never appear in DMs)
- **Guild-only**: `announce`, `remind-evaluations`, `rollcall` (guild-scoped commands never appear in DMs)
## Feature flow: signup/link
@ -62,7 +63,7 @@ bot/
## Feature flow: attendance
Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit" missions into ops channel. Stores `discordMessageId` + `discordAttendanceHash` on mission. Reconciles hash changes every poll tick (web ↔ Discord two-way sync, loop-safe). The embed title links to the mission page, a mission summary sits under the title (truncated to 300 characters with an ellipsis), and an "Open the op" field carries the URL; `attendanceHash` includes an embed schema version so layout-only changes re-render live roll-calls once (idempotent). Web UI: `MissionAttendance` component. Weekly main missions are cloned by `bun run payload generate-mission` (a payload bin, see `src/scripts/AGENTS.md`).
Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit" missions into ops channel. Stores `discordMessageId` + `discordAttendanceHash` on mission. Reconciles hash changes every poll tick (web ↔ Discord two-way sync, loop-safe). The embed title links to the mission page, a mission summary sits under the title (truncated to 300 characters with an ellipsis), and an "Open the op" field carries the URL; `attendanceHash` includes an embed schema version so layout-only changes re-render live roll-calls once (idempotent). Web UI: `MissionAttendance` component. Weekly main missions are cloned by `bun run payload generate-mission` (a payload bin, see `src/scripts/AGENTS.md`). Staff can force one outside the lead-time window with `/rollcall [mission]` (ID, name, or code name; omit to target the next upcoming Scheduled unit op): `forceRollCall` in `missionEmbeds.ts` re-renders the live message or posts a fresh one (even after a manual deletion), bypassing only the 3-day gate; target lookup/validation lives in `src/lib/intelligence/rollCall.ts`.
## Feature flow: notifications
@ -92,6 +93,7 @@ At 8 PM Eastern on Wednesday (`America/New_York`, evaluated via `isNoticeDue` in
| Changelog rendering/splitting | `bot/lib/changelogRender.ts` |
| Add button interaction | `bot/events/interactionCreate.ts` (RSVP) or `transferInteractions.ts` (transfers) |
| Modify embed lifecycle | `bot/services/missionEmbeds.ts` |
| Force a roll-call manually | `bot/commands/rollcall.ts` + `src/lib/intelligence/rollCall.ts` |
| Change DM bridging | `bot/services/notificationBridge.ts` |
| Evaluation reminder logic | `bot/services/evaluationReminders.ts` + `src/lib/evaluations/reminders.ts` |
| Imminent-op reminder logic | `bot/services/imminentReminders.ts` + `src/lib/intelligence/imminentReminders.ts` |

View file

@ -6,6 +6,7 @@ import { linkCommand } from "./link";
import { announceCommand } from "./announce";
import { changelogCommand } from "./changelog";
import { remindEvaluationsCommand } from "./remindEvaluations";
import { rollCallCommand } from "./rollcall";
export interface BotCommand {
builder: SlashCommandBuilder;

View file

@ -0,0 +1,85 @@
import { MessageFlags, SlashCommandBuilder, type Client } from "discord.js";
import type { Payload } from "payload";
import type { BotCommand } from "./index";
import { isStaff } from "@/bot/lib/roles";
import { forceRollCall } from "@/bot/services/missionEmbeds";
import {
getNextUpcomingScheduledMission,
missionLabel,
resolveMissionByRef,
validateRollCallTarget,
} from "@/lib/intelligence/rollCall";
import type { Mission } from "@/payload-types";
export const rollCallCommand: BotCommand = {
builder: new SlashCommandBuilder()
.setName("rollcall")
.setDescription("Force-send or refresh a mission roll-call in the ops channel (staff only)")
.addStringOption((option) =>
option
.setName("mission")
.setDescription(
"Mission ID, name, or code name. Omit to target the next upcoming scheduled op.",
),
) as SlashCommandBuilder,
execute: async (interaction, payload) => {
if (!interaction.inGuild() || !interaction.guild) {
await interaction.reply({
content: "This command only works in a server.",
flags: MessageFlags.Ephemeral,
});
return;
}
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!(await isStaff(member, payload))) {
await interaction.reply({
content: "You don't have permission to trigger roll-calls.",
flags: MessageFlags.Ephemeral,
});
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const client = interaction.client as Client;
const missionInput = interaction.options.getString("mission")?.trim();
try {
let mission: Mission | undefined;
if (missionInput) {
const resolved = await resolveMissionByRef(payload, missionInput);
if (resolved.error || !resolved.mission) {
await interaction.editReply(resolved.error ?? `No mission matches "${missionInput}".`);
return;
}
mission = resolved.mission;
} else {
mission = (await getNextUpcomingScheduledMission(payload)) ?? undefined;
if (!mission) {
await interaction.editReply(
"No upcoming Scheduled, unit-visible mission found. Name one with the `mission` option.",
);
return;
}
}
const rejection = validateRollCallTarget(mission);
if (rejection) {
await interaction.editReply(rejection);
return;
}
const result = await forceRollCall(client, payload, mission);
await interaction.editReply(
result === "updated"
? `Refreshed the live roll-call for **${missionLabel(mission)}** in the ops channel.`
: `Posted a fresh roll-call for **${missionLabel(mission)}** in the ops channel.`,
);
} catch (error) {
await interaction.editReply(
`Roll-call trigger failed: ${error instanceof Error ? error.message : "Unknown error"}`,
);
}
},
};

View file

@ -519,6 +519,63 @@ export const reconcileMission = async (
await manageMission(client, payload, opsChannelId, mission);
};
/**
* Manual override for staff (`/rollcall`): bypasses the lead-time gate and the
* one-shot send marker. Re-renders the live roll-call message when one exists,
* otherwise posts a fresh one (including after a manual deletion, which the
* automatic flow deliberately refuses to repost). Modlist sync rides along on
* the post path via postEmbed.
*/
export const forceRollCall = async (
client: Client,
payload: Payload,
mission: Mission,
): Promise<"posted" | "updated"> => {
const opsChannelId = botConfig.opsChannelId;
if (!opsChannelId) {
throw new Error("DISCORD_OPS_CHANNEL_ID is not set; cannot post roll-calls.");
}
if (mission.discordMessageId) {
const channel = await getOpsChannel(client, opsChannelId);
let message;
try {
message = await channel.messages.fetch(mission.discordMessageId);
} catch {
message = null; // Deleted, fall through and post a fresh roll-call.
}
if (message) {
const summary = await getMissionAttendance(payload, mission.id);
const hash = attendanceHash(
await fetchAttendanceDocs(payload, mission.id),
mission.classification.startDateTime,
);
await message.edit({
embeds: [renderAttendanceEmbed(mission, summary)],
components: [buildAttendanceRow(mission.id)],
});
await payload.update({
collection: "missions",
id: mission.id,
data: {
discordAttendanceHash: hash,
...(mission.discordAttendanceSentAt
? {}
: { discordAttendanceSentAt: new Date().toISOString() }),
},
overrideAccess: true,
});
payload.logger.info(
`[Bot] Force-refreshed roll-call for mission #${mission.id} (${mission.name}).`,
);
return "updated";
}
}
await postEmbed(client, payload, opsChannelId, mission);
return "posted";
};
/**
* A cancelled op gets its roll-call edited into the cancelled state (buttons
* removed) plus a standalone cancellation notice. The message id, attendance

View file

@ -0,0 +1,100 @@
import type { Payload } from "payload";
import type { Mission } from "@/payload-types";
/**
* Target-lookup helpers for the manual `/rollcall` bot command. Kept free of
* discord.js imports (unlike `bot/services/missionEmbeds`) so they run in
* integration tests against the test database.
*/
export const missionLabel = (mission: Mission): string =>
mission.codeName ? `${mission.name} (${mission.codeName})` : mission.name;
/**
* The default `/rollcall` target: the soonest-starting future mission that is
* Scheduled and unit-visible, regardless of whether its roll-call already went
* out (force-refreshing the next op is a valid use). Returns null when none.
*/
export const getNextUpcomingScheduledMission = async (
payload: Payload,
now = new Date(),
): Promise<Mission | null> => {
const res = await payload.find({
collection: "missions",
overrideAccess: true,
depth: 0,
limit: 1,
sort: "classification.startDateTime",
where: {
and: [
{ "ownershipAndStatus.visibility": { equals: "unit" } },
{ "ownershipAndStatus.status": { equals: "Scheduled" } },
{ "classification.startDateTime": { greater_than: now.toISOString() } },
],
},
});
return (res.docs[0] as unknown as Mission) ?? null;
};
export interface MissionResolution {
mission?: Mission;
error?: string;
}
/** Resolve a mission by ID, name, or code name (same UX as /remind-evaluations). */
export const resolveMissionByRef = async (
payload: Payload,
input: string,
): Promise<MissionResolution> => {
const trimmed = input.trim();
try {
const mission = await payload.findByID({
collection: "missions",
id: trimmed,
overrideAccess: true,
depth: 0,
});
return { mission: mission as unknown as Mission };
} catch {
// Not an ID, fall through to a name / code-name search.
}
const res = await payload.find({
collection: "missions",
overrideAccess: true,
depth: 0,
limit: 6,
where: {
or: [{ name: { like: trimmed } }, { codeName: { like: trimmed } }],
},
});
const docs = res.docs as unknown as Mission[];
if (docs.length === 0) {
return { error: `No mission matches "${trimmed}" (searched by ID, name, and code name).` };
}
if (docs.length > 1) {
const list = docs.map((m) => `• ${missionLabel(m)} (#${m.id})`).join("\n");
return { error: `Multiple missions match "${trimmed}". Be more specific:\n${list}` };
}
return { mission: docs[0] };
};
/**
* Whether a mission may receive a forced roll-call. Returns null when allowed,
* otherwise a staff-facing explanation. The force bypasses the lead-time gate
* only: drafts (Ready/Concept) stay quiet per the side-op workflow, leadership
* missions never touch the unit-wide ops channel, and a past op has nothing to
* roll call.
*/
export const validateRollCallTarget = (mission: Mission, now = new Date()): string | null => {
if (mission.ownershipAndStatus.status !== "Scheduled") {
return `**${missionLabel(mission)}** is not Scheduled (status: ${mission.ownershipAndStatus.status}). Roll-calls only post for scheduled ops; set the status to Scheduled first.`;
}
if (mission.ownershipAndStatus.visibility !== "unit") {
return `**${missionLabel(mission)}** is not unit-visible (visibility: ${mission.ownershipAndStatus.visibility}); roll-calls post to the unit-wide ops channel.`;
}
if (new Date(mission.classification.startDateTime).getTime() <= now.getTime()) {
return `**${missionLabel(mission)}** has already started; there is nothing left to roll call.`;
}
return null;
};

View file

@ -0,0 +1,237 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types";
import {
getNextUpcomingScheduledMission,
resolveMissionByRef,
validateRollCallTarget,
} from "@/lib/intelligence/rollCall";
let payload: Payload;
const RUN = `rc-${Date.now().toString(36)}`;
describe("Forced roll-call target helpers", () => {
let mapId: number;
let campaignId: number;
let authorId: number;
const missionIds: number[] = [];
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
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: "Roll-call force test campaign", status: "concept", campaignMode: "custom" },
overrideAccess: true,
depth: 0,
})) as unknown as Campaign;
campaignId = campaign.id;
const author = (await payload.create({
collection: "users",
data: {
username: `${RUN}-author`,
discordUsername: `${RUN}-author`,
displayName: "RC AUTHOR",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
authorId = author.id;
});
afterAll(async () => {
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: "maps", id: mapId, overrideAccess: true }).catch(() => {});
// User deletion trips FK constraints unless the hook-provisioned
// personal bank account and profile are removed first.
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 makeMission = async (
label: string,
overrides: {
name?: string;
status?: Mission["ownershipAndStatus"]["status"];
visibility?: Mission["ownershipAndStatus"]["visibility"];
start: Date;
},
): Promise<Mission> => {
const mission = (await payload.create({
collection: "missions",
data: {
name: overrides.name ?? `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Forced roll-call test mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
campaign: campaignId,
startDateTime: overrides.start.toISOString(),
estimatedDuration: 60,
},
ownershipAndStatus: {
authors: [authorId],
status: overrides.status ?? "Scheduled",
visibility: overrides.visibility ?? "unit",
},
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);
return mission;
};
describe("getNextUpcomingScheduledMission", () => {
it("picks the soonest future Scheduled unit op and skips past, draft, and leadership ops", async () => {
const now = new Date();
await makeMission("far", { start: new Date(now.getTime() + 4 * 86_400_000) });
const soon = await makeMission("soon", { start: new Date(now.getTime() + 2 * 86_400_000) });
const past = await makeMission("past", { start: new Date(now.getTime() - 3_600_000) });
const draft = await makeMission("draft", {
status: "Ready",
start: new Date(now.getTime() + 600_000),
});
const leadership = await makeMission("leadership", {
visibility: "leadership",
start: new Date(now.getTime() + 600_000),
});
const next = await getNextUpcomingScheduledMission(payload, now);
expect(next).not.toBeNull();
// Other suites may leave missions in the shared test DB, so assert
// ordering/exclusion rather than exact identity: the pick must never be
// one of the excluded rows and must start no later than our soonest.
expect([past.id, draft.id, leadership.id]).not.toContain(next!.id);
expect(new Date(next!.classification.startDateTime).getTime()).toBeLessThanOrEqual(
new Date(soon.classification.startDateTime).getTime(),
);
});
});
describe("resolveMissionByRef", () => {
it("resolves by ID, name, and code name", async () => {
const now = new Date();
const mission = await makeMission("solo", { start: new Date(now.getTime() + 86_400_000) });
const byId = await resolveMissionByRef(payload, String(mission.id));
expect(byId.mission?.id).toBe(mission.id);
const byCodeName = await resolveMissionByRef(payload, `${RUN}-solo`);
expect(byCodeName.mission?.id).toBe(mission.id);
const byName = await resolveMissionByRef(payload, `${RUN} solo`);
expect(byName.mission?.id).toBe(mission.id);
});
it("reports no-match and ambiguity instead of guessing", async () => {
const now = new Date();
const twinStart = new Date(now.getTime() + 86_400_000);
await makeMission("twin-a", { name: `${RUN} twins`, start: twinStart });
await makeMission("twin-b", { name: `${RUN} twins`, start: twinStart });
const missing = await resolveMissionByRef(payload, `${RUN} definitely-not-here`);
expect(missing.mission).toBeUndefined();
expect(missing.error).toContain("No mission matches");
const ambiguous = await resolveMissionByRef(payload, `${RUN} twins`);
expect(ambiguous.mission).toBeUndefined();
expect(ambiguous.error).toContain("Multiple missions match");
});
});
describe("validateRollCallTarget", () => {
const base = (overrides: {
status?: Mission["ownershipAndStatus"]["status"];
visibility?: Mission["ownershipAndStatus"]["visibility"];
start?: Date;
}): Mission =>
({
id: 1,
name: "Validation Probe",
ownershipAndStatus: {
status: overrides.status ?? "Scheduled",
visibility: overrides.visibility ?? "unit",
},
classification: {
startDateTime: (overrides.start ?? new Date(Date.now() + 86_400_000)).toISOString(),
},
}) as unknown as Mission;
it("accepts a future Scheduled unit op", () => {
expect(validateRollCallTarget(base({}))).toBeNull();
});
it("rejects drafts, leadership visibility, and started ops with explanations", () => {
expect(validateRollCallTarget(base({ status: "Ready" }))).toContain("not Scheduled");
expect(validateRollCallTarget(base({ visibility: "leadership" }))).toContain(
"not unit-visible",
);
expect(
validateRollCallTarget(base({ start: new Date(Date.now() - 60_000) })),
).toContain("already started");
});
});
});