Compare commits
5 commits
948109e362
...
21cced3ad9
| Author | SHA1 | Date | |
|---|---|---|---|
| 21cced3ad9 | |||
| 3b89170293 | |||
| 99ef9ec73c | |||
| e9bc929213 | |||
| a6709e4cf3 |
15 changed files with 600 additions and 9 deletions
15
CHANGELOG.md
15
CHANGELOG.md
|
|
@ -1,5 +1,20 @@
|
|||
# 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
|
||||
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.14.0",
|
||||
"version": "0.14.1",
|
||||
"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",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ collections/
|
|||
game/ 9 files # GameRules (global, currency + staffing flags), GameStructures,
|
||||
# GameVehicles, GameNpcs, GameHardResources, GameEventLogs,
|
||||
# NpcStaffing, LaborClassifications (+ shared staffingFields.ts factory)
|
||||
server/ 5 files # MissionFiles, ModLists, GameServers, ArmaCommands, ArmaSyncEvents
|
||||
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
|
||||
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)
|
||||
tickets/ 2 files # Tickets (Lexical rich text; `archived` hides from all front-ends, admin panel only), TicketVotes
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { CollectionConfig, type AccessArgs, type AccessResult } from "payload";
|
||||
import path from "path";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
|
||||
|
|
@ -11,7 +11,14 @@ export const ModLists: CollectionConfig = {
|
|||
create: requirePermission("mod-lists:create"),
|
||||
update: requirePermission("mod-lists:update"),
|
||||
delete: requirePermission("mod-lists:delete"),
|
||||
read: requirePermission("mod-lists:read"),
|
||||
// The file-serving route (`/api/mod-lists/file/<name>`) runs `read` with
|
||||
// `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: [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -340,11 +340,16 @@ export function MissionRating({
|
|||
The rating window for this mission is closed.
|
||||
</p>
|
||||
)}
|
||||
{!showForm && !ratingLocked && !windowClosed && notEligible && (
|
||||
{!showForm && !ratingLocked && !windowClosed && notEligible && !state.isAuthor && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You need a Yes RSVP for this mission to rate it.
|
||||
</p>
|
||||
)}
|
||||
{!showForm && !ratingLocked && state.isAuthor && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Mission authors cannot rate their own mission.
|
||||
</p>
|
||||
)}
|
||||
</ItemContent>
|
||||
</Item>
|
||||
|
||||
|
|
|
|||
|
|
@ -22,9 +22,23 @@ interface MissionRatingMission {
|
|||
ownershipAndStatus?: {
|
||||
status?: string | null;
|
||||
completedAt?: string | null;
|
||||
authors?: Array<number | { id: number }> | 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
|
||||
* when the mission is marked Completed and stays open for RATING_WINDOW_DAYS from
|
||||
|
|
@ -96,6 +110,7 @@ export async function isRatingAvailable(
|
|||
if (!isRatingWindowOpen(mission.ownershipAndStatus?.status, mission.ownershipAndStatus?.completedAt, now)) {
|
||||
return false;
|
||||
}
|
||||
if (isMissionAuthor(mission, userId)) return false;
|
||||
if (!(await hasYesAttendance(payload, userId, mission.id))) return false;
|
||||
if (await hasRated(payload, mission.id, userId)) return false;
|
||||
return true;
|
||||
|
|
@ -136,10 +151,21 @@ export async function submitMissionRating(
|
|||
overrideAccess: true,
|
||||
})
|
||||
.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;
|
||||
|
||||
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)) {
|
||||
throw new Error("The rating window for this mission is closed.");
|
||||
}
|
||||
|
|
@ -188,6 +214,8 @@ export interface MissionRatingState {
|
|||
windowClosed: boolean;
|
||||
/** The current user has a yes-RSVP for the mission. */
|
||||
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. */
|
||||
canRate: boolean;
|
||||
/** The user's existing ratings, or null when they have not rated yet. */
|
||||
|
|
@ -213,7 +241,9 @@ export async function getMissionRatingState(
|
|||
now,
|
||||
);
|
||||
|
||||
const isEligible = userId !== null && (await hasYesAttendance(payload, userId, mission.id));
|
||||
const isAuthor = userId !== null && isMissionAuthor(mission, userId);
|
||||
const isEligible =
|
||||
userId !== null && !isAuthor && (await hasYesAttendance(payload, userId, mission.id));
|
||||
|
||||
let myValues: MissionRatingEntry[] | null = null;
|
||||
if (userId !== null) {
|
||||
|
|
@ -238,6 +268,7 @@ export async function getMissionRatingState(
|
|||
windowOpen,
|
||||
windowClosed: !windowOpen,
|
||||
isEligible,
|
||||
isAuthor,
|
||||
canRate,
|
||||
myValues,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ describe("Mission ratings (post-op survey)", () => {
|
|||
const userIds: number[] = [];
|
||||
|
||||
// Raters shared across scenarios.
|
||||
let author: User;
|
||||
let rater1: User;
|
||||
let rater2: User;
|
||||
let rater3: User;
|
||||
|
|
@ -98,7 +99,7 @@ describe("Mission ratings (post-op survey)", () => {
|
|||
status: "Completed",
|
||||
completedAt: past.toISOString(),
|
||||
visibility: "unit",
|
||||
authors: [rater1.id],
|
||||
authors: [author.id],
|
||||
},
|
||||
...(opts?.customFactors ? { missionRating: { customFactors: opts.customFactors } } : {}),
|
||||
missionRoles: { maxPlayers: 16 },
|
||||
|
|
@ -130,7 +131,7 @@ describe("Mission ratings (post-op survey)", () => {
|
|||
ownershipAndStatus: {
|
||||
status: "Scheduled",
|
||||
visibility: "unit",
|
||||
authors: [rater1.id],
|
||||
authors: [author.id],
|
||||
},
|
||||
missionRoles: { maxPlayers: 16 },
|
||||
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
|
||||
|
|
@ -174,6 +175,7 @@ describe("Mission ratings (post-op survey)", () => {
|
|||
})) as unknown as Campaign;
|
||||
campaignId = campaign.id;
|
||||
|
||||
author = await makeUser("author");
|
||||
rater1 = await makeUser("rater1");
|
||||
rater2 = await makeUser("rater2");
|
||||
rater3 = await makeUser("rater3");
|
||||
|
|
@ -296,6 +298,47 @@ describe("Mission ratings (post-op survey)", () => {
|
|||
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 () => {
|
||||
await rsvp(rater3.id, aggMissionId);
|
||||
|
||||
|
|
|
|||
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();
|
||||
});
|
||||
});
|
||||
69
tests/int/modlist-file-access.int.spec.ts
Normal file
69
tests/int/modlist-file-access.int.spec.ts
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
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,
|
||||
);
|
||||
});
|
||||
Loading…
Reference in a new issue