feat(bot): post modlist reminder 8 hours before scheduled operations
Adds reconcileModlistBuffer, which resends the modlist-updated message once per Scheduled mission with a modlist attached, when its start is within DISCORD_MODLIST_BUFFER_HOURS (default 8). Tracked by the new discordModlistBufferSentAt marker, so it is independent of the roll-call modlist sync. Also fixes type errors in modlist-file-access.int.spec.ts.
This commit is contained in:
parent
a6709e4cf3
commit
e9bc929213
8 changed files with 430 additions and 5 deletions
|
|
@ -20,6 +20,8 @@ export interface BotConfig {
|
|||
achievementPollMs: number;
|
||||
presencePollMs: number;
|
||||
npcEventPollMs: number;
|
||||
/** Hours before a scheduled operation the modlist buffer reminder fires. */
|
||||
modlistBufferHours: number;
|
||||
}
|
||||
|
||||
const required = (name: string): string => {
|
||||
|
|
@ -47,6 +49,19 @@ const pollMs = (name: string, fallback: number): number => {
|
|||
return value;
|
||||
};
|
||||
|
||||
/** Parse a positive-integer count of hours from an env var (milliseconds unused here). */
|
||||
const parseHours = (name: string, fallback: number): number => {
|
||||
const raw = process.env[name]?.trim();
|
||||
if (!raw) {
|
||||
return fallback;
|
||||
}
|
||||
const value = Number.parseInt(raw, 10);
|
||||
if (!Number.isInteger(value) || value <= 0) {
|
||||
throw new Error(`[Bot] Invalid ${name}: expected a positive integer, got "${raw}"`);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
export const botConfig: BotConfig = {
|
||||
token: required("DISCORD_TOKEN"),
|
||||
guildId: required("DISCORD_GUILD_ID"),
|
||||
|
|
@ -72,4 +87,5 @@ export const botConfig: BotConfig = {
|
|||
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
|
||||
presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000),
|
||||
npcEventPollMs: pollMs("DISCORD_NPC_EVENT_POLL_MS", 60_000),
|
||||
modlistBufferHours: parseHours("DISCORD_MODLIST_BUFFER_HOURS", 8),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -550,6 +550,87 @@ const syncModlistMessage = async (
|
|||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 8-hour modlist buffer: for each Scheduled mission with a modlist attached,
|
||||
* post the modlist message ONCE, 8 hours before the operation's scheduled
|
||||
* start. This runs independently of the roll-call-driven modlist sync
|
||||
* (`syncModlistMessage`), so a message always appears on both the modlist
|
||||
* update and this buffer.
|
||||
*
|
||||
* The `discordModlistBufferSentAt` marker makes it one-shot per mission. The
|
||||
* poll queries missions whose start is within the next `modlistBufferHours`
|
||||
* (so the buffer moment has arrived) and whose marker is unset, then sends the
|
||||
* current modlist and stamps the marker. `now` is injectable for tests.
|
||||
*
|
||||
* A mission created/scheduled less than `modlistBufferHours` before its start
|
||||
* (so the buffer moment is already in the past) still fires, as soon as the
|
||||
* poll sees it with a modlist attached.
|
||||
*/
|
||||
export const reconcileModlistBuffer = async (
|
||||
client: Client,
|
||||
payload: Payload,
|
||||
now: Date = new Date(),
|
||||
): Promise<number> => {
|
||||
const opsChannelId = botConfig.opsChannelId;
|
||||
if (!opsChannelId) return 0;
|
||||
|
||||
const bufferMs = botConfig.modlistBufferHours * 60 * 60 * 1000;
|
||||
const upperBound = new Date(now.getTime() + bufferMs).toISOString();
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "missions",
|
||||
where: {
|
||||
and: [
|
||||
{ "ownershipAndStatus.status": { equals: "Scheduled" } },
|
||||
{
|
||||
"classification.startDateTime": {
|
||||
greater_than: now.toISOString(),
|
||||
less_than_equal: upperBound,
|
||||
},
|
||||
},
|
||||
{ discordModlistBufferSentAt: { exists: false } },
|
||||
],
|
||||
},
|
||||
sort: "classification.startDateTime",
|
||||
limit: 100,
|
||||
depth: 1,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
let posted = 0;
|
||||
for (const mission of res.docs as unknown as Mission[]) {
|
||||
const start = new Date(mission.classification.startDateTime);
|
||||
|
||||
// The query upper bound already implies this, but keep it explicit so the
|
||||
// window stays exact under clock skew or a stale `now`.
|
||||
if (start.getTime() - bufferMs > now.getTime()) continue;
|
||||
if (start.getTime() <= now.getTime()) continue;
|
||||
|
||||
const modlist = await resolveModlist(payload, mission);
|
||||
if (!modlist) continue;
|
||||
|
||||
try {
|
||||
await postModlistMessage(client, payload, opsChannelId, mission, modlist, "updated");
|
||||
await payload.update({
|
||||
collection: "missions",
|
||||
id: mission.id,
|
||||
data: { discordModlistBufferSentAt: now.toISOString() },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
payload.logger.info(
|
||||
`[Bot] Posted 8h modlist buffer for mission #${mission.id} (${mission.name}).`,
|
||||
);
|
||||
posted += 1;
|
||||
} catch (error) {
|
||||
payload.logger.error(
|
||||
`[Bot] Modlist buffer post failed for mission #${mission.id}: ${errorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return posted;
|
||||
};
|
||||
|
||||
const manageMission = async (
|
||||
client: Client,
|
||||
payload: Payload,
|
||||
|
|
@ -832,6 +913,16 @@ export const reconcile = async (client: Client, payload: Payload): Promise<void>
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 8-hour modlist buffer: post the modlist message once per scheduled
|
||||
// mission, 8 hours before its start, independent of the roll-call sync.
|
||||
try {
|
||||
await reconcileModlistBuffer(client, payload);
|
||||
} catch (error) {
|
||||
payload.logger.error(
|
||||
`[Bot] Modlist buffer reconcile failed: ${errorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
payload.logger.error(`[Bot] Attendance embed reconcile failed: ${errorMessage(error)}`);
|
||||
} finally {
|
||||
|
|
|
|||
|
|
@ -339,6 +339,15 @@ export const Missions: CollectionConfig = {
|
|||
hidden: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "discordModlistBufferSentAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
description:
|
||||
"When the 8-hours-before-start modlist buffer was posted to Discord (managed by the bot, one-shot).",
|
||||
hidden: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "discordRatingSentAt",
|
||||
type: "date",
|
||||
|
|
|
|||
|
|
@ -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_modlist_buffer_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_modlist_buffer_sent_at";`)
|
||||
}
|
||||
|
|
@ -154,6 +154,7 @@ import * as migration_20261026_205453_add_operation_effects_pending_action_and_d
|
|||
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';
|
||||
import * as migration_20261031_090000_add_missions_discord_modlist_buffer_sent_at from './20261031_090000_add_missions_discord_modlist_buffer_sent_at';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -936,4 +937,9 @@ export const migrations = [
|
|||
down: migration_20261031_085035_add_mission_rating_sent_at_marker.down,
|
||||
name: '20261031_085035_add_mission_rating_sent_at_marker'
|
||||
},
|
||||
{
|
||||
up: migration_20261031_090000_add_missions_discord_modlist_buffer_sent_at.up,
|
||||
down: migration_20261031_090000_add_missions_discord_modlist_buffer_sent_at.down,
|
||||
name: '20261031_090000_add_missions_discord_modlist_buffer_sent_at'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -4387,6 +4387,10 @@ export interface Mission {
|
|||
* Fingerprint of the attached modlist last announced to Discord (managed by the bot).
|
||||
*/
|
||||
discordModlistHash?: string | null;
|
||||
/**
|
||||
* When the 8-hours-before-start modlist buffer was posted to Discord (managed by the bot, one-shot).
|
||||
*/
|
||||
discordModlistBufferSentAt?: string | null;
|
||||
/**
|
||||
* When the post-op survey prompt was first posted to Discord (managed by the bot, one-shot).
|
||||
*/
|
||||
|
|
@ -10579,6 +10583,7 @@ export interface MissionsSelect<T extends boolean = true> {
|
|||
discordAttendanceHash?: T;
|
||||
discordAttendanceSentAt?: T;
|
||||
discordModlistHash?: T;
|
||||
discordModlistBufferSentAt?: T;
|
||||
discordRatingSentAt?: T;
|
||||
discordCancelledAt?: T;
|
||||
evaluationRemindersSentAt?: T;
|
||||
|
|
|
|||
283
tests/int/modlist-buffer.int.spec.ts
Normal file
283
tests/int/modlist-buffer.int.spec.ts
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
import { getTestPayload } from "../helpers/get-test-payload";
|
||||
import { Payload } from "payload";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types";
|
||||
import { reconcileModlistBuffer } from "@/bot/services/missionEmbeds";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `modlist-buffer-${Date.now().toString(36)}`;
|
||||
|
||||
/**
|
||||
* 8-hour modlist buffer: for each Scheduled mission with a modlist attached,
|
||||
* the buffer posts the modlist message once, 8 hours before start, and stamps
|
||||
* `discordModlistBufferSentAt`. These tests exercise the query + stamp path
|
||||
* directly (the roll-call sync is separate), so the mock client only needs to
|
||||
* record the send and never touches the filesystem.
|
||||
*/
|
||||
describe("reconcileModlistBuffer (8h modlist reminder)", () => {
|
||||
let mapId: number;
|
||||
let campaignId: number;
|
||||
let authorId: number;
|
||||
let modlistId: 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;
|
||||
|
||||
const campaign = (await payload.create({
|
||||
collection: "campaigns",
|
||||
data: { name: `${RUN} Campaign`, summary: "modlist buffer 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: "AUTHOR",
|
||||
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
roles: ["user"],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as User;
|
||||
authorId = author.id;
|
||||
|
||||
// A real mod-lists doc so resolveModlist can resolve gameSetup.requiredMods.
|
||||
// The launcher export starts with an XML prologue, which Payload sniffs as
|
||||
// application/xml (one of the allowed mimeTypes for the collection).
|
||||
const modlistBuffer = Buffer.from(
|
||||
'<?xml version="1.0" encoding="utf-8"?><html><head><meta name="arma:PresetName" content="buffer" /></head><body>buffer preset</body></html>',
|
||||
);
|
||||
const modlist = (await payload.create({
|
||||
collection: "mod-lists",
|
||||
data: {
|
||||
modlistName: `${RUN} Preset`,
|
||||
author: authorId,
|
||||
},
|
||||
file: {
|
||||
data: modlistBuffer,
|
||||
mimetype: "application/xml",
|
||||
name: `${RUN}-preset.html`,
|
||||
size: modlistBuffer.byteLength,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as { id: number; filename: string; url: string | null; modlistName: string };
|
||||
modlistId = modlist.id;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of missionIds) {
|
||||
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
await payload
|
||||
.delete({ collection: "mod-lists", id: modlistId, overrideAccess: true })
|
||||
.catch(() => {});
|
||||
await payload
|
||||
.delete({ collection: "campaigns", id: campaignId, 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 makeMission = async (
|
||||
label: string,
|
||||
status: Mission["ownershipAndStatus"]["status"],
|
||||
start: Date,
|
||||
withModlist: boolean,
|
||||
): Promise<Mission> => {
|
||||
const mission = (await payload.create({
|
||||
collection: "missions",
|
||||
data: {
|
||||
name: `${RUN} ${label}`,
|
||||
codeName: `${RUN}-${label}`,
|
||||
summary: "modlist buffer test mission",
|
||||
operationType: "main",
|
||||
classification: {
|
||||
map: mapId,
|
||||
missionType: "PvE",
|
||||
campaign: campaignId,
|
||||
startDateTime: start.toISOString(),
|
||||
estimatedDuration: 240,
|
||||
},
|
||||
ownershipAndStatus: {
|
||||
authors: [authorId],
|
||||
status,
|
||||
visibility: "unit",
|
||||
},
|
||||
missionRoles: {
|
||||
maxPlayers: 16,
|
||||
},
|
||||
gameDetails: {
|
||||
serverDetails: {
|
||||
serverIp: "127.0.0.1",
|
||||
serverPort: 2302,
|
||||
},
|
||||
gameSetup: withModlist
|
||||
? {
|
||||
requiredMods: modlistId,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
briefing: [],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Mission;
|
||||
missionIds.push(mission.id);
|
||||
return mission;
|
||||
};
|
||||
|
||||
const fetchMission = (id: number): Promise<Mission> =>
|
||||
payload.findByID({
|
||||
collection: "missions",
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
}) as unknown as Promise<Mission>;
|
||||
|
||||
const mockClient = () => {
|
||||
const send = vi.fn().mockResolvedValue({ id: "msg-1" });
|
||||
return { client: { channels: { fetch: async () => ({ send }) } } as never, send };
|
||||
};
|
||||
|
||||
it("posts the modlist message once, 8 hours before start, and stamps the marker", async () => {
|
||||
const now = new Date("2026-08-24T12:00:00.000Z");
|
||||
const start = new Date(now);
|
||||
start.setHours(now.getHours() + 8); // exactly at the buffer moment
|
||||
|
||||
const mission = await makeMission("buffer-due", "Scheduled", start, true);
|
||||
const { client, send } = mockClient();
|
||||
|
||||
const posted = await reconcileModlistBuffer(client, payload, now);
|
||||
|
||||
expect(posted).toBe(1);
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
|
||||
const updated = await fetchMission(mission.id);
|
||||
expect(updated.discordModlistBufferSentAt).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does not post when the mission is outside the 8h window", async () => {
|
||||
const now = new Date("2026-08-24T12:00:00.000Z");
|
||||
const start = new Date(now);
|
||||
start.setHours(now.getHours() + 10); // 10h out — buffer not due yet
|
||||
|
||||
const mission = await makeMission("buffer-not-due", "Scheduled", start, true);
|
||||
const { client, send } = mockClient();
|
||||
|
||||
const posted = await reconcileModlistBuffer(client, payload, now);
|
||||
|
||||
expect(posted).toBe(0);
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
expect((await fetchMission(mission.id)).discordModlistBufferSentAt).toBeNull();
|
||||
});
|
||||
|
||||
it("does not post for a mission whose start has already passed", async () => {
|
||||
const now = new Date("2026-08-24T12:00:00.000Z");
|
||||
const start = new Date(now);
|
||||
start.setHours(now.getHours() - 1); // started an hour ago
|
||||
|
||||
const mission = await makeMission("buffer-past", "Scheduled", start, true);
|
||||
const { client, send } = mockClient();
|
||||
|
||||
const posted = await reconcileModlistBuffer(client, payload, now);
|
||||
|
||||
expect(posted).toBe(0);
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
expect((await fetchMission(mission.id)).discordModlistBufferSentAt).toBeNull();
|
||||
});
|
||||
|
||||
it("does not post for a Scheduled mission with no modlist attached", async () => {
|
||||
const now = new Date("2026-08-24T12:00:00.000Z");
|
||||
const start = new Date(now);
|
||||
start.setHours(now.getHours() + 6);
|
||||
|
||||
const mission = await makeMission("buffer-no-modlist", "Scheduled", start, false);
|
||||
const { client, send } = mockClient();
|
||||
|
||||
const posted = await reconcileModlistBuffer(client, payload, now);
|
||||
|
||||
expect(posted).toBe(0);
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
expect((await fetchMission(mission.id)).discordModlistBufferSentAt).toBeNull();
|
||||
});
|
||||
|
||||
it("does not post for a non-Scheduled mission", async () => {
|
||||
const now = new Date("2026-08-24T12:00:00.000Z");
|
||||
const start = new Date(now);
|
||||
start.setHours(now.getHours() + 6);
|
||||
|
||||
const mission = await makeMission("buffer-active", "Active", start, true);
|
||||
const { client, send } = mockClient();
|
||||
|
||||
const posted = await reconcileModlistBuffer(client, payload, now);
|
||||
|
||||
expect(posted).toBe(0);
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
expect((await fetchMission(mission.id)).discordModlistBufferSentAt).toBeNull();
|
||||
});
|
||||
|
||||
it("is idempotent — a second sweep finds the already-stamped mission", async () => {
|
||||
const now = new Date("2026-08-24T12:00:00.000Z");
|
||||
const start = new Date(now);
|
||||
start.setHours(now.getHours() + 8);
|
||||
|
||||
const mission = await makeMission("buffer-idempotent", "Scheduled", start, true);
|
||||
const { client: client1, send: send1 } = mockClient();
|
||||
await reconcileModlistBuffer(client1, payload, now);
|
||||
expect(send1).toHaveBeenCalledTimes(1);
|
||||
|
||||
const { client: client2, send: send2 } = mockClient();
|
||||
const posted = await reconcileModlistBuffer(client2, payload, now);
|
||||
|
||||
expect(posted).toBe(0);
|
||||
expect(send2).not.toHaveBeenCalled();
|
||||
expect((await fetchMission(mission.id)).discordModlistBufferSentAt).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { getTestPayload } from "../helpers/get-test-payload";
|
||||
import { Payload } from "payload";
|
||||
|
||||
import type { AccessArgs, AccessResult } from "payload";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import { ModLists } from "@/collections/server/ModLists";
|
||||
|
|
@ -18,17 +19,20 @@ const TIMEOUT = 30_000;
|
|||
* server, so invoking the access function directly is the standard way to
|
||||
* unit-test Payload access control (see admin-page-access.int.spec.ts).
|
||||
*/
|
||||
const readAccess = scopedAdminPageAccess(ModLists.slug, ModLists.access.read);
|
||||
const readAccess = scopedAdminPageAccess(ModLists.slug, ModLists.access?.read) as (
|
||||
args: AccessArgs,
|
||||
) => Promise<AccessResult>;
|
||||
|
||||
/**
|
||||
* A synthetic args object: non-admin pathname (REST/file route), no auth cookie.
|
||||
* `isReadingStaticFile` is a sibling of `req` (Payload builds
|
||||
* `{ data, isReadingStaticFile, req }` for the file route), not nested in `req`.
|
||||
*/
|
||||
const anonReq = (pathname: string, isReadingStaticFile?: boolean) => ({
|
||||
isReadingStaticFile,
|
||||
req: { user: null, payload, pathname },
|
||||
});
|
||||
const anonReq = (pathname: string, isReadingStaticFile?: boolean): AccessArgs =>
|
||||
({
|
||||
isReadingStaticFile,
|
||||
req: { user: null, payload, pathname },
|
||||
}) as unknown as AccessArgs;
|
||||
|
||||
describe("ModLists file access", () => {
|
||||
beforeAll(async () => {
|
||||
|
|
|
|||
Loading…
Reference in a new issue