1
0
Fork 0

Compare commits

..

No commits in common. "21cced3ad9d9d831de4a769958d193c630b42de4" and "948109e3627ebbc63f8ed7e04d67833de1c1620a" have entirely different histories.

15 changed files with 9 additions and 600 deletions

View file

@ -1,20 +1,5 @@
# Changelog # Changelog
# v0.14.1
Modlist links work without signing in, operators get a modlist reminder eight hours before each scheduled operation, and mission authors can no longer rate their own missions.
### Features
- **Modlist reminder.** A scheduled operation with a modlist attached gets the modlist message again eight hours before its start. It posts once per operation and is independent of roll-call updates.
### Fixes
- **Modlist downloads.** Anyone with a modlist link can download the preset without signing in. Browsing modlist details still requires the mod-list permission.
- **Mission authors.** Authors can no longer rate a mission they ran or planned, and the rating panel explains why.
---
# v0.14.0 # v0.14.0
Post-op mission ratings: operators rate each factor after a mission, anonymous aggregates surface on the mission page, the bot prompts for ratings in Discord, and completing the survey grants contribution XP. Post-op mission ratings: operators rate each factor after a mission, anonymous aggregates surface on the mission page, the bot prompts for ratings in Discord, and completing the survey grants contribution XP.

View file

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

View file

@ -20,8 +20,6 @@ export interface BotConfig {
achievementPollMs: number; achievementPollMs: number;
presencePollMs: number; presencePollMs: number;
npcEventPollMs: number; npcEventPollMs: number;
/** Hours before a scheduled operation the modlist buffer reminder fires. */
modlistBufferHours: number;
} }
const required = (name: string): string => { const required = (name: string): string => {
@ -49,19 +47,6 @@ const pollMs = (name: string, fallback: number): number => {
return value; 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 = { export const botConfig: BotConfig = {
token: required("DISCORD_TOKEN"), token: required("DISCORD_TOKEN"),
guildId: required("DISCORD_GUILD_ID"), guildId: required("DISCORD_GUILD_ID"),
@ -87,5 +72,4 @@ export const botConfig: BotConfig = {
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000), achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000), presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000),
npcEventPollMs: pollMs("DISCORD_NPC_EVENT_POLL_MS", 60_000), npcEventPollMs: pollMs("DISCORD_NPC_EVENT_POLL_MS", 60_000),
modlistBufferHours: parseHours("DISCORD_MODLIST_BUFFER_HOURS", 8),
}; };

View file

@ -550,87 +550,6 @@ 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 ( const manageMission = async (
client: Client, client: Client,
payload: Payload, payload: Payload,
@ -913,16 +832,6 @@ 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) { } catch (error) {
payload.logger.error(`[Bot] Attendance embed reconcile failed: ${errorMessage(error)}`); payload.logger.error(`[Bot] Attendance embed reconcile failed: ${errorMessage(error)}`);
} finally { } finally {

View file

@ -27,7 +27,7 @@ collections/
game/ 9 files # GameRules (global, currency + staffing flags), GameStructures, game/ 9 files # GameRules (global, currency + staffing flags), GameStructures,
# GameVehicles, GameNpcs, GameHardResources, GameEventLogs, # GameVehicles, GameNpcs, GameHardResources, GameEventLogs,
# NpcStaffing, LaborClassifications (+ shared staffingFields.ts factory) # NpcStaffing, LaborClassifications (+ shared staffingFields.ts factory)
server/ 5 files # MissionFiles, ModLists (file route `/file/<name>` is public download for anyone with the link; REST/admin reads still need `mod-lists:read`), GameServers, ArmaCommands, ArmaSyncEvents server/ 5 files # MissionFiles, ModLists, GameServers, ArmaCommands, ArmaSyncEvents
world/ 6 files # Maps (basemap config), MapRoads/MapZones/ResourceNodes (map features), MapObjectives (superuser strategic objectives), NarrativeEvents world/ 6 files # Maps (basemap config), MapRoads/MapZones/ResourceNodes (map features), MapObjectives (superuser strategic objectives), NarrativeEvents
projects/ 4 files # Projects, Labels, Releases, Sprints (Jira-like) projects/ 4 files # Projects, Labels, Releases, Sprints (Jira-like)
tickets/ 2 files # Tickets (Lexical rich text; `archived` hides from all front-ends, admin panel only), TicketVotes tickets/ 2 files # Tickets (Lexical rich text; `archived` hides from all front-ends, admin panel only), TicketVotes

View file

@ -339,15 +339,6 @@ export const Missions: CollectionConfig = {
hidden: true, 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", name: "discordRatingSentAt",
type: "date", type: "date",

View file

@ -1,4 +1,4 @@
import { CollectionConfig, type AccessArgs, type AccessResult } from "payload"; import { CollectionConfig } from "payload";
import path from "path"; import path from "path";
import { requirePermission } from "@/utils/access-control/hasPermission"; import { requirePermission } from "@/utils/access-control/hasPermission";
@ -11,14 +11,7 @@ export const ModLists: CollectionConfig = {
create: requirePermission("mod-lists:create"), create: requirePermission("mod-lists:create"),
update: requirePermission("mod-lists:update"), update: requirePermission("mod-lists:update"),
delete: requirePermission("mod-lists:delete"), delete: requirePermission("mod-lists:delete"),
// The file-serving route (`/api/mod-lists/file/<name>`) runs `read` with read: requirePermission("mod-lists:read"),
// `isReadingStaticFile: true`. Allow anyone with the link to download the
// preset without signing in; REST and admin-panel reads still require
// `mod-lists:read`, so the document metadata stays permission-gated.
read: async (args: AccessArgs): Promise<AccessResult> => {
if (args.isReadingStaticFile) return true;
return requirePermission("mod-lists:read")(args);
},
}, },
fields: [ fields: [
{ {

View file

@ -340,16 +340,11 @@ export function MissionRating({
The rating window for this mission is closed. The rating window for this mission is closed.
</p> </p>
)} )}
{!showForm && !ratingLocked && !windowClosed && notEligible && !state.isAuthor && ( {!showForm && !ratingLocked && !windowClosed && notEligible && (
<p className="text-sm text-muted-foreground"> <p className="text-sm text-muted-foreground">
You need a Yes RSVP for this mission to rate it. You need a Yes RSVP for this mission to rate it.
</p> </p>
)} )}
{!showForm && !ratingLocked && state.isAuthor && (
<p className="text-sm text-muted-foreground">
Mission authors cannot rate their own mission.
</p>
)}
</ItemContent> </ItemContent>
</Item> </Item>

View file

@ -22,23 +22,9 @@ interface MissionRatingMission {
ownershipAndStatus?: { ownershipAndStatus?: {
status?: string | null; status?: string | null;
completedAt?: string | null; completedAt?: string | null;
authors?: Array<number | { id: number }> | null;
} | null; } | null;
} }
/**
* Whether `userId` is one of the mission's authors. Authors ran or planned the
* op, so they may not rate it. Authors are a relationship array: entries are
* either bare ids or populated docs, depending on depth.
*/
export function isMissionAuthor(
mission: MissionRatingMission,
userId: number,
): boolean {
const authors = mission.ownershipAndStatus?.authors ?? [];
return authors.some((a) => (typeof a === "number" ? a : a.id) === userId);
}
/** /**
* Whether the rating window is open for a mission at `now`. The window opens * Whether the rating window is open for a mission at `now`. The window opens
* when the mission is marked Completed and stays open for RATING_WINDOW_DAYS from * when the mission is marked Completed and stays open for RATING_WINDOW_DAYS from
@ -110,7 +96,6 @@ export async function isRatingAvailable(
if (!isRatingWindowOpen(mission.ownershipAndStatus?.status, mission.ownershipAndStatus?.completedAt, now)) { if (!isRatingWindowOpen(mission.ownershipAndStatus?.status, mission.ownershipAndStatus?.completedAt, now)) {
return false; return false;
} }
if (isMissionAuthor(mission, userId)) return false;
if (!(await hasYesAttendance(payload, userId, mission.id))) return false; if (!(await hasYesAttendance(payload, userId, mission.id))) return false;
if (await hasRated(payload, mission.id, userId)) return false; if (await hasRated(payload, mission.id, userId)) return false;
return true; return true;
@ -151,21 +136,10 @@ export async function submitMissionRating(
overrideAccess: true, overrideAccess: true,
}) })
.catch(() => null)) as unknown as .catch(() => null)) as unknown as
| { | { ownershipAndStatus?: { status?: string | null; completedAt?: string | null }; missionRating?: { customFactors?: Array<{ label: string }> | null } }
id: number;
ownershipAndStatus?: {
status?: string | null;
completedAt?: string | null;
authors?: Array<number | { id: number }> | null;
};
missionRating?: { customFactors?: Array<{ label: string }> | null };
}
| null; | null;
if (!mission) throw new Error("Mission not found."); if (!mission) throw new Error("Mission not found.");
if (isMissionAuthor(mission, userId)) {
throw new Error("Mission authors cannot rate their own mission.");
}
if (!isRatingWindowOpen(mission.ownershipAndStatus?.status, mission.ownershipAndStatus?.completedAt)) { if (!isRatingWindowOpen(mission.ownershipAndStatus?.status, mission.ownershipAndStatus?.completedAt)) {
throw new Error("The rating window for this mission is closed."); throw new Error("The rating window for this mission is closed.");
} }
@ -214,8 +188,6 @@ export interface MissionRatingState {
windowClosed: boolean; windowClosed: boolean;
/** The current user has a yes-RSVP for the mission. */ /** The current user has a yes-RSVP for the mission. */
isEligible: boolean; isEligible: boolean;
/** The current user is an author of the mission (authors never rate it). */
isAuthor: boolean;
/** Window open AND eligible AND the user has not already rated. */ /** Window open AND eligible AND the user has not already rated. */
canRate: boolean; canRate: boolean;
/** The user's existing ratings, or null when they have not rated yet. */ /** The user's existing ratings, or null when they have not rated yet. */
@ -241,9 +213,7 @@ export async function getMissionRatingState(
now, now,
); );
const isAuthor = userId !== null && isMissionAuthor(mission, userId); const isEligible = userId !== null && (await hasYesAttendance(payload, userId, mission.id));
const isEligible =
userId !== null && !isAuthor && (await hasYesAttendance(payload, userId, mission.id));
let myValues: MissionRatingEntry[] | null = null; let myValues: MissionRatingEntry[] | null = null;
if (userId !== null) { if (userId !== null) {
@ -268,7 +238,6 @@ export async function getMissionRatingState(
windowOpen, windowOpen,
windowClosed: !windowOpen, windowClosed: !windowOpen,
isEligible, isEligible,
isAuthor,
canRate, canRate,
myValues, myValues,
}; };

View file

@ -1,11 +0,0 @@
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";`)
}

View file

@ -154,7 +154,6 @@ 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_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_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_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 = [ export const migrations = [
{ {
@ -937,9 +936,4 @@ export const migrations = [
down: migration_20261031_085035_add_mission_rating_sent_at_marker.down, down: migration_20261031_085035_add_mission_rating_sent_at_marker.down,
name: '20261031_085035_add_mission_rating_sent_at_marker' 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'
},
]; ];

View file

@ -4387,10 +4387,6 @@ export interface Mission {
* Fingerprint of the attached modlist last announced to Discord (managed by the bot). * Fingerprint of the attached modlist last announced to Discord (managed by the bot).
*/ */
discordModlistHash?: string | null; 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). * When the post-op survey prompt was first posted to Discord (managed by the bot, one-shot).
*/ */
@ -10583,7 +10579,6 @@ export interface MissionsSelect<T extends boolean = true> {
discordAttendanceHash?: T; discordAttendanceHash?: T;
discordAttendanceSentAt?: T; discordAttendanceSentAt?: T;
discordModlistHash?: T; discordModlistHash?: T;
discordModlistBufferSentAt?: T;
discordRatingSentAt?: T; discordRatingSentAt?: T;
discordCancelledAt?: T; discordCancelledAt?: T;
evaluationRemindersSentAt?: T; evaluationRemindersSentAt?: T;

View file

@ -30,7 +30,6 @@ describe("Mission ratings (post-op survey)", () => {
const userIds: number[] = []; const userIds: number[] = [];
// Raters shared across scenarios. // Raters shared across scenarios.
let author: User;
let rater1: User; let rater1: User;
let rater2: User; let rater2: User;
let rater3: User; let rater3: User;
@ -99,7 +98,7 @@ describe("Mission ratings (post-op survey)", () => {
status: "Completed", status: "Completed",
completedAt: past.toISOString(), completedAt: past.toISOString(),
visibility: "unit", visibility: "unit",
authors: [author.id], authors: [rater1.id],
}, },
...(opts?.customFactors ? { missionRating: { customFactors: opts.customFactors } } : {}), ...(opts?.customFactors ? { missionRating: { customFactors: opts.customFactors } } : {}),
missionRoles: { maxPlayers: 16 }, missionRoles: { maxPlayers: 16 },
@ -131,7 +130,7 @@ describe("Mission ratings (post-op survey)", () => {
ownershipAndStatus: { ownershipAndStatus: {
status: "Scheduled", status: "Scheduled",
visibility: "unit", visibility: "unit",
authors: [author.id], authors: [rater1.id],
}, },
missionRoles: { maxPlayers: 16 }, missionRoles: { maxPlayers: 16 },
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } }, gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
@ -175,7 +174,6 @@ describe("Mission ratings (post-op survey)", () => {
})) as unknown as Campaign; })) as unknown as Campaign;
campaignId = campaign.id; campaignId = campaign.id;
author = await makeUser("author");
rater1 = await makeUser("rater1"); rater1 = await makeUser("rater1");
rater2 = await makeUser("rater2"); rater2 = await makeUser("rater2");
rater3 = await makeUser("rater3"); rater3 = await makeUser("rater3");
@ -298,47 +296,6 @@ describe("Mission ratings (post-op survey)", () => {
expect(second).toHaveLength(5); expect(second).toHaveLength(5);
}); });
it("blocks a mission author from rating their own mission", async () => {
// author authored aggMission and has a yes-RSVP, so only the author rule can block them.
await rsvp(author.id, aggMissionId);
expect(
await isRatingAvailable(
payload,
{ id: aggMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString(), authors: [author.id] } },
author.id,
),
).toBe(false);
const state = await getMissionRatingState(
payload,
{ id: aggMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString(), authors: [author.id] } },
author.id,
);
expect(state.isAuthor).toBe(true);
expect(state.isEligible).toBe(false);
expect(state.canRate).toBe(false);
await expect(
submitMissionRating(payload, {
missionId: aggMissionId,
userId: author.id,
values: { Briefing: 5 },
}),
).rejects.toThrow(/cannot rate their own mission/i);
});
it("still lets a non-author with a yes-RSVP rate an authored mission", async () => {
// rater2 is not an author of eligMission (authored by author) and has a yes-RSVP.
await rsvp(rater2.id, eligMissionId);
const mission = { id: eligMissionId, ownershipAndStatus: { status: "Completed", completedAt: past.toISOString(), authors: [author.id] } };
expect(await isRatingAvailable(payload, mission, rater2.id)).toBe(true);
const state = await getMissionRatingState(payload, mission, rater2.id);
expect(state.isAuthor).toBe(false);
expect(state.isEligible).toBe(true);
});
it("validates factor values before writing (unknown / out-of-range / closed)", async () => { it("validates factor values before writing (unknown / out-of-range / closed)", async () => {
await rsvp(rater3.id, aggMissionId); await rsvp(rater3.id, aggMissionId);

View file

@ -1,283 +0,0 @@
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();
});
});

View file

@ -1,69 +0,0 @@
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";
import { scopedAdminPageAccess } from "@/utils/access-control/divisionAccess";
let payload: Payload;
const TIMEOUT = 30_000;
/**
* Replicate the production wrapping exactly: payload.config.ts maps every
* collection through `scopedAdminPageAccess(slug, read)`, and the file-serving
* route (`/api/mod-lists/file/<name>`) invokes `read` with
* `isReadingStaticFile: true`. The vitest environment has no Next.js HTTP
* 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) 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): AccessArgs =>
({
isReadingStaticFile,
req: { user: null, payload, pathname },
}) as unknown as AccessArgs;
describe("ModLists file access", () => {
beforeAll(async () => {
payload = await getTestPayload();
}, TIMEOUT);
afterAll(async () => {
// Nothing persists.
});
it(
"lets anyone with the link download the preset without signing in",
async () => {
// The file-serving route runs read with isReadingStaticFile: true.
const result = await readAccess(anonReq("/api/mod-lists/file/x.html", true));
expect(result).toBe(true);
},
TIMEOUT,
);
it(
"still requires mod-lists:read for anonymous REST and admin-panel reads",
async () => {
// A logged-out REST read of the document metadata is denied.
const api = await readAccess(anonReq("/api/mod-lists/1"));
expect(api).toBe(false);
// The admin-panel path keeps its permission gate (no user → denied).
const admin = await readAccess(anonReq("/admin/collections/mod-lists", true));
expect(admin).toBe(false);
},
TIMEOUT,
);
});