1
0
Fork 0

Compare commits

..

No commits in common. "0c685a2f47eafcc1d970e7144d0fa2a5cefd542b" and "35c1a8556060afdd446c15f11f32dccf9d6ad65c" have entirely different histories.

42 changed files with 222 additions and 143638 deletions

View file

@ -334,21 +334,6 @@ Five XP-earning minigames under one parent: routes live at `/minigames/*` (moved
- **Flight Simulator**: `/minigames/flappy` (canvas game + leaderboard). **Minefield Clearance (EOD)**: `/minigames/eod`. **OPORD Recall**: `/minigames/opord` (`src/lib/minigames/opord-recall.ts`).
- Leaderboards match active players by user id (not display name) — see commit 72715c4 if leaderboard queries look wrong.
## Mission Role Sign-Ups
Players meeting a role's minimum rank + MOS can queue for mission roles ahead of op time, with a first-come, first-served waitlist that auto-promotes when a slot holder stops attending.
- **Collections**: `mission-role-signups` (`src/collections/intelligence/MissionRoleSignups.ts`) — one live signup per user per mission: `mission`, `user`, `roleIndex` (index into `missions.missionRoles.providedRoles`), `roleNameSnapshot` (display fallback if the role list is later edited). Access mirrors MissionAttendances; all writes flow through the lib with `overrideAccess`. Slots live on the roles themselves: `missions.missionRoles.providedRoles[].slots` (number, default 1), plus an optional `description` richText (Lexical) shown to players under the role name in the Roles table and the sign-up panel via the shared `RoleDescription` renderer (falls back to plain text for legacy strings).
- **Queue model (stateless)**: slot holders are recomputed from signup order + current RSVP. The first `slots` signups (FCFS: createdAt, then id) whose owner's attendance RSVP is "yes" hold the role; everyone else is waitlisted in signup order. Only "yes" holds a slot (tentative keeps your place but fills nothing). RSVPing No, going tentative, or withdrawing frees the slot and the next committed member slides up. A returning member reclaims their original first-come position, which can displace someone promoted earlier (that is the cost of pure FCFS; there is no promotion state to drift).
- **Lib**: `src/lib/intelligence/roleSignups.ts` — `signupForRole` / `withdrawRoleSignup` / `removeRoleSignup` (staff removal, gated by `missions:update` in the action), `getMissionRoleSignupState` (page render), `getSlotHolders` + `diffPromotedUsers` + `notifySlotHoldersDiff` (promotion reconciliation), `checkRoleEligibilities` (rank vs `loadRankLadder`, MOS vs `progression.qualifications`; admin/developer bypass via `bypassEligibility`), `roleSignupGate` (open until the start time passes; Cancelled/Completed close immediately).
- **Promotion triggers**: the shared attendance write path (`setMissionAttendance` in `src/lib/attendance/index.ts`) diffs slot holders around the write, so both web and Discord RSVP changes promote; signups, switches, withdrawals, and staff removals do the same. Promoted members get an in-app notification (`mission:role-promoted`, muteable, never sent to the acting user) + a `mission:role-promoted` event. Signups/withdrawals emit `mission:role-signup` / `mission:role-withdraw` (all targeting `missions`).
- **Shared time gate**: `src/lib/intelligence/missionTime.ts` (`isMissionPast`, `attendanceClosedMessage`) was extracted from the attendance lib so roleSignups can reuse it without an import cycle; attendance re-exports both for API compatibility.
- **Server actions**: `signupForMissionRole` / `withdrawMissionRoleSignup` / `removeMissionRoleSignup` in `src/app/(frontend)/intelligence/missions/actions.ts` (canonical ActionResult pattern; the first two verify mission visibility via `findByID` with `user` + `overrideAccess: false`).
- **UI**: `MissionRoleSignups` panel under the Roles table on the mission detail page (sign up / switch / withdraw, slot holders, numbered waitlist, per-role eligibility reasons, staff remove buttons when `missions:update`); the read-only Roles table gained a Slots column.
- **Orphan pruning**: a Missions `beforeChange` hook (update-only) deletes signups whose `roleIndex >= providedRoles.length` after a mission's role list is edited.
- **Not covered**: real in-game no-show detection (promotions are RSVP-driven only) and Discord-side signup UI.
- **Tests**: `tests/int/mission-role-signups.int.spec.ts` (eligibility gating, FCFS + multi-slot queue, RSVP-drop and withdrawal promotions with notification/event assertions, role switching, staff bypass + removal, closed gates, holder diff).
## Discord Bot
A Discord bot living in `src/bot/`, run as a standalone long-running process via `bun run bot` — it imports `@payload-config` directly (same pattern as `src/scripts/` and `src/tools/seed/`) and shares the Postgres DB with the web app. **Under active development and testing.** **Full product requirements live in `docs/bot/context.md`; the approved implementation design is in `docs/bot/design.md` — read both before touching bot code.**

View file

@ -43,7 +43,6 @@
"@types/leaflet": "^1.9.22",
"@types/nodemailer": "^8.0.1",
"@xyflow/react": "^12.11.3",
"ajv": "^8.18.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@ -95,9 +94,6 @@
},
},
},
"patchedDependencies": {
"@ai-stack/payloadcms@3.2.30": "patches/@ai-stack%2Fpayloadcms@3.2.30.patch",
},
"packages": {
"@acemir/cssom": ["@acemir/cssom@0.9.29", "", {}, "sha512-G90x0VW+9nW4dFajtjCoT+NM0scAfH9Mb08IcjgFHYbfiL/lU04dTF9JuVOi3/OH+DJCQdcIseSXkdCB9Ky6JA=="],
@ -1129,7 +1125,7 @@
"ai": ["ai@6.0.233", "", { "dependencies": { "@ai-sdk/gateway": "3.0.155", "@ai-sdk/provider": "3.0.14", "@ai-sdk/provider-utils": "4.0.40", "@opentelemetry/api": "^1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-P0dtR/JtnL05CiGZiVVeRePdgeBhe+DZAxwbOK0hpuWAcfysMPHueP6zwWOyEn07bVW4DMIk9nHbW0t9iIiW7g=="],
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
@ -1813,7 +1809,7 @@
"json-schema-to-zod": ["json-schema-to-zod@2.6.1", "", { "bin": { "json-schema-to-zod": "dist/cjs/cli.js" } }, "sha512-uiHmWH21h9FjKJkRBntfVGTLpYlCZ1n98D0izIlByqQLqpmkQpNTBtfbdP04Na6+43lgsvrShFh2uWLkQDKJuQ=="],
"json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
@ -2649,6 +2645,8 @@
"@ai-sdk/react/ai": ["ai@6.0.256", "", { "dependencies": { "@ai-sdk/gateway": "3.0.174", "@ai-sdk/provider": "3.0.15", "@ai-sdk/provider-utils": "4.0.46", "@opentelemetry/api": "^1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-xYvQfvwFG1AsiLv8wSS1o1077q/494HxzI6SIw0G/5zIoirNyJUzFlh/BTZBqbHMa03Pt5EouIGAbGimldiDGg=="],
"@ai-stack/payloadcms/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"@apidevtools/json-schema-ref-parser/js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="],
"@aws-crypto/sha1-browser/@smithy/util-utf8": ["@smithy/util-utf8@2.3.0", "", { "dependencies": { "@smithy/util-buffer-from": "2.2.0", "tslib": "2.8.1" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],
@ -2685,12 +2683,12 @@
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
"@eslint/eslintrc/ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
"@eslint/eslintrc/globals": ["globals@14.0.0", "", {}, "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ=="],
"@google/genai/ws": ["ws@8.21.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw=="],
"@modelcontextprotocol/sdk/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"@modelcontextprotocol/sdk/eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="],
"@modelcontextprotocol/sdk/jose": ["jose@6.2.10", "", {}, "sha512-iiW7J9qRFlGxvCOIBDBDxFePQSn7ZMAnrYGhrrOo6siO/MIqwfyilLR27pkfDgUk+raLuzADS8A3S/KLBisc0g=="],
@ -2771,6 +2769,8 @@
"ai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@4.0.40", "", { "dependencies": { "@ai-sdk/provider": "3.0.14", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-OL5IrpUm9Y8Dwy+w/vvFwPotS6m52O9W0op2oXgXdCROMJIBalBI0oro6OIBYkPxvm5Xg02GSkoQN25RlR0bnw=="],
"ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"amazon-cognito-identity-js/@aws-crypto/sha256-js": ["@aws-crypto/sha256-js@1.2.2", "", { "dependencies": { "@aws-crypto/util": "1.2.2", "@aws-sdk/types": "3.910.0", "tslib": "1.14.1" } }, "sha512-Nr1QJIbW/afYYGzYvrF70LtaHrIRtd4TNAglX8BvlfxJLZ45SAmueIKYl5tWoNBPzp65ymXGFK0Bb1vZUpuc9g=="],
"amazon-cognito-identity-js/buffer": ["buffer@4.9.2", "", { "dependencies": { "base64-js": "1.5.1", "ieee754": "1.2.1", "isarray": "1.0.0" } }, "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg=="],
@ -2793,8 +2793,6 @@
"dom-helpers/csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],
"eslint/ajv": ["ajv@6.15.0", "", { "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", "json-schema-traverse": "^0.4.1", "uri-js": "^4.2.2" } }, "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw=="],
"eslint-import-resolver-node/debug": ["debug@3.2.7", "", { "dependencies": { "ms": "2.1.3" } }, "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ=="],
"eslint-import-resolver-typescript/get-tsconfig": ["get-tsconfig@4.12.0", "", { "dependencies": { "resolve-pkg-maps": "1.0.0" } }, "sha512-LScr2aNr2FbjAjZh2C6X6BxRx1/x+aTDExct/xyq2XKbYOiG5c0aK7pMsSuyc0brz3ibr/lbQiHD9jzt4lccJw=="],
@ -2941,6 +2939,8 @@
"@ai-sdk/react/ai/@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.174", "", { "dependencies": { "@ai-sdk/provider": "3.0.15", "@ai-sdk/provider-utils": "4.0.46", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-RXDYc+FGEuy1Y/HlM4MThtQAzG99AIs8ki4tIoVnVweOlW5HDSfaNGNLw556ZR4TifTRuPfBc6QljX4UkuGG6A=="],
"@ai-stack/payloadcms/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"@aws-crypto/sha1-browser/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "2.2.0", "tslib": "2.8.1" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],
"@aws-crypto/sha256-browser/@smithy/util-utf8/@smithy/util-buffer-from": ["@smithy/util-buffer-from@2.2.0", "", { "dependencies": { "@smithy/is-array-buffer": "2.2.0", "tslib": "2.8.1" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],
@ -3001,7 +3001,7 @@
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.18.20", "", { "os": "win32", "cpu": "x64" }, "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ=="],
"@eslint/eslintrc/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
"@modelcontextprotocol/sdk/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"@payloadcms/graphql/tsx/esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
@ -3043,6 +3043,8 @@
"ai/@ai-sdk/provider-utils/eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="],
"ajv-formats/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"amazon-cognito-identity-js/@aws-crypto/sha256-js/@aws-crypto/util": ["@aws-crypto/util@1.2.2", "", { "dependencies": { "@aws-sdk/types": "3.910.0", "@aws-sdk/util-utf8-browser": "3.259.0", "tslib": "1.14.1" } }, "sha512-H8PjG5WJ4wz0UXAFXeJjWCW1vkvIJ3qUUD+rGRwJ2/hj+xT58Qle2MTql/2MGzkU+1JLAFuR6aJpLAjHwhmwwg=="],
"amazon-cognito-identity-js/@aws-crypto/sha256-js/tslib": ["tslib@1.14.1", "", {}, "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="],
@ -3073,8 +3075,6 @@
"eslint-plugin-react-hooks/@babel/parser/@babel/types": ["@babel/types@7.28.4", "", { "dependencies": { "@babel/helper-string-parser": "7.27.1", "@babel/helper-validator-identifier": "7.27.1" } }, "sha512-bkFqkLhh3pMBUQQkpVgWDWq/lqzc2678eUyDlTBhRqhCHFguYYGM0Efga7tYk4TogG/3x0EEl66/OQ+WGbWB/Q=="],
"eslint/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
"express/mime-types/mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"express/qs/side-channel": ["side-channel@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="],
@ -3087,6 +3087,8 @@
"node-fetch/whatwg-url/webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
"payload/ajv/json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"payload/tsx/esbuild": ["esbuild@0.28.2", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.28.2", "@esbuild/android-arm": "0.28.2", "@esbuild/android-arm64": "0.28.2", "@esbuild/android-x64": "0.28.2", "@esbuild/darwin-arm64": "0.28.2", "@esbuild/darwin-x64": "0.28.2", "@esbuild/freebsd-arm64": "0.28.2", "@esbuild/freebsd-x64": "0.28.2", "@esbuild/linux-arm": "0.28.2", "@esbuild/linux-arm64": "0.28.2", "@esbuild/linux-ia32": "0.28.2", "@esbuild/linux-loong64": "0.28.2", "@esbuild/linux-mips64el": "0.28.2", "@esbuild/linux-ppc64": "0.28.2", "@esbuild/linux-riscv64": "0.28.2", "@esbuild/linux-s390x": "0.28.2", "@esbuild/linux-x64": "0.28.2", "@esbuild/netbsd-arm64": "0.28.2", "@esbuild/netbsd-x64": "0.28.2", "@esbuild/openbsd-arm64": "0.28.2", "@esbuild/openbsd-x64": "0.28.2", "@esbuild/openharmony-arm64": "0.28.2", "@esbuild/sunos-x64": "0.28.2", "@esbuild/win32-arm64": "0.28.2", "@esbuild/win32-ia32": "0.28.2", "@esbuild/win32-x64": "0.28.2" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA=="],
"payload/tsx/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
@ -3231,8 +3233,6 @@
"eslint-module-utils/eslint/@eslint/eslintrc/js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="],
"eslint-module-utils/eslint/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
"express/qs/side-channel/side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
"payload/tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="],

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.2.56",
"version": "0.2.55",
"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",
@ -67,7 +67,6 @@
"@types/leaflet": "^1.9.22",
"@types/nodemailer": "^8.0.1",
"@xyflow/react": "^12.11.3",
"ajv": "^8.18.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@ -128,8 +127,5 @@
"unrs-resolver"
]
},
"packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0",
"patchedDependencies": {
"@ai-stack/payloadcms@3.2.30": "patches/@ai-stack%2Fpayloadcms@3.2.30.patch"
}
"packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0"
}

View file

@ -1,65 +0,0 @@
diff --git a/node_modules/@ai-stack/payloadcms/.bun-tag-e130c3bcd4cfe50c b/.bun-tag-e130c3bcd4cfe50c
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/dist/endpoints/index.js b/dist/endpoints/index.js
index f80e469821efbc3f256c7ef8ba29f549d065e1f8..8113c5fdda9411f19d654110464b2a6b72fcc615 100644
--- a/dist/endpoints/index.js
+++ b/dist/endpoints/index.js
@@ -158,7 +158,7 @@ export const endpoints = (pluginConfig)=>({
// Check authentication and authorization first
await checkAccess(req, pluginConfig);
const data = await req.json?.();
- const { allowedEditorNodes = [], locale = 'en', options } = data;
+ const { allowedEditorNodes = [], locale = 'en', options, activeFieldPath = '' } = data;
const { action, actionParams, instructionId } = options;
const contextData = data.doc;
if (!instructionId) {
@@ -192,6 +192,16 @@ export const endpoints = (pluginConfig)=>({
const collectionName = parts[0];
const fieldPath = parts.slice(1).join('.');
const fieldName = parts.length > 1 ? parts[parts.length - 1] : '';
+ // Array-nested richText: handlebars paths like "briefing.details" cannot traverse
+ // arrays, so the action prompt renders empty. Substitute the active field's real
+ // path (sent by the client, e.g. "briefing.0.details") when it indexes an array.
+ let promptFieldPath = fieldPath || fieldName || '';
+ if (String(instructions['field-type']) === 'richText' && activeFieldPath) {
+ const relPath = activeFieldPath.startsWith(`${collectionName}.`) ? activeFieldPath.slice(collectionName.length + 1) : activeFieldPath;
+ if (relPath !== promptFieldPath && /(^|\.)\d+(\.|$)/.test(relPath)) {
+ promptFieldPath = relPath;
+ }
+ }
registerEditorHelper(req.payload, schemaPath);
let localeInfo = locale;
if (localeData && defaultLocale && localeData.label && typeof localeData.label === 'object' && defaultLocale in localeData.label) {
@@ -212,7 +222,7 @@ export const endpoints = (pluginConfig)=>({
actionParams,
collection: collectionName,
context: contextData,
- field: fieldPath || fieldName || '',
+ field: promptFieldPath,
layout: instructions.layout,
locale: localeInfo,
pluginConfig,
diff --git a/dist/ui/Compose/hooks/useGenerate.js b/dist/ui/Compose/hooks/useGenerate.js
index e0d1f16706f214349921391a2850d7a878143dfc..f1591067cdc9c340871c656b0a383e8584d8d8a1 100644
--- a/dist/ui/Compose/hooks/useGenerate.js
+++ b/dist/ui/Compose/hooks/useGenerate.js
@@ -327,6 +327,7 @@ export const useGenerate = ({ instructionId })=>{
// Snapshot the editor state exactly once, before any streamed updates can mutate it.
originalRootRef.current = editor?.getEditorState ? editor.getEditorState().toJSON()?.root ?? null : null;
submit({
+ activeFieldPath: editorConfigContext.fieldProps?.path ?? pathFromContext ?? '',
allowedEditorNodes: Array.from(editor?._nodes?.keys() || []),
doc: {
...doc,
@@ -340,7 +341,9 @@ export const useGenerate = ({ instructionId })=>{
instructionIdRef,
documentId,
editor,
- cancelPendingApply
+ cancelPendingApply,
+ pathFromContext,
+ editorConfigContext.fieldProps?.path
]);
const generateUpload = useCallback(async ()=>{
const doc = getData();

View file

@ -23,18 +23,11 @@ import { hasPermission } from "@/utils/access-control/hasPermission";
import { redactText } from "@/lib/redaction";
import { MissionFactions } from "@/components/frontend/intelligence/MissionFactions";
import { MissionRoles } from "@/components/frontend/intelligence/MissionRoles";
import { MissionRoleSignups } from "@/components/frontend/intelligence/MissionRoleSignups";
import { MissionLogistics } from "@/components/frontend/intelligence/MissionLogistics";
import { MissionComms } from "@/components/frontend/intelligence/MissionComms";
import { MissionAttendance } from "@/components/frontend/intelligence/MissionAttendance";
import { SideOpControls } from "@/components/frontend/intelligence/SideOpControls";
import type { SideOpDialogOption } from "@/components/frontend/intelligence/CreateSideOpDialog";
import { isAdminOrDeveloper } from "@/lib/promotions/authority";
import {
checkRoleEligibilities,
getMissionRoleSignupState,
roleSignupGate,
} from "@/lib/intelligence/roleSignups";
import {
type AttendanceResponse,
getMissionAttendance,
@ -261,31 +254,6 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
/>
);
const providedRoles = mission.missionRoles?.providedRoles ?? [];
const signupGate = roleSignupGate(mission);
const signupState = await getMissionRoleSignupState(payload, mission.id, currentUser?.id ?? null);
const signupEligibilities = currentUser
? await checkRoleEligibilities(
payload,
currentUser.id as number,
providedRoles.map((role) => ({
requiredMos: role.requiredMos,
minimumRank: role.minimumRank,
})),
isAdminOrDeveloper(currentUser as User),
)
: providedRoles.map(() => null);
const signupRoles = providedRoles.map((role, index) => ({
roleIndex: index,
roleName: role.roleName,
description: role.description ?? null,
missionCritical: role.missionCritical ?? true,
slots: Math.max(1, role.slots ?? 1),
filled: signupState.roles[index]?.filled ?? 0,
entries: signupState.roles[index]?.entries ?? [],
eligibility: signupEligibilities[index] ?? null,
}));
return (
<div className="flex flex-col">
<header className="relative flex min-h-[500px] w-full flex-col overflow-hidden bg-background">
@ -457,16 +425,6 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
maxPlayers={mission.missionRoles?.maxPlayers ?? 32}
/>
<MissionRoleSignups
missionId={mission.id}
currentUserId={currentUser ? (currentUser.id as number) : null}
closed={!signupGate.open}
closedReason={signupGate.reason ?? null}
roles={signupRoles}
mySignup={signupState.mySignup}
canManage={canManage}
/>
<MissionLogistics logisticsAndSupport={mission.logisticsAndSupport ?? null} />
<MissionComms commsAndDocs={mission.commsAndDocs ?? null} />

View file

@ -5,12 +5,6 @@ import { getPayload } from "payload";
import type { AttendanceResponse } from "@/lib/attendance";
import { setMissionAttendance as setAttendance } from "@/lib/attendance";
import { notifyAttendanceChanged } from "@/lib/attendance/realtime";
import { isAdminOrDeveloper } from "@/lib/promotions/authority";
import {
removeRoleSignup,
signupForRole,
withdrawRoleSignup,
} from "@/lib/intelligence/roleSignups";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { emitGameEvent } from "@/utils/event-log/emit";
@ -23,7 +17,7 @@ import {
zonedParts,
zonedWeekday,
} from "@/lib/intelligence/fridayTime";
import type { Mission, User } from "@/payload-types";
import type { Mission } from "@/payload-types";
export interface ActionResult<T = undefined> {
success: boolean;
@ -948,103 +942,3 @@ export async function moveFridaySideOpToCampaign(
: { success: false, error: message };
}
}
// ---------------------------------------------------------------------------
// Role sign-ups
// ---------------------------------------------------------------------------
export async function signupForMissionRole(input: {
missionId: number;
roleIndex: number;
}): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const userId = user.id as number;
const mission = await payload
.findByID({
collection: "missions",
id: input.missionId,
depth: 0,
user,
overrideAccess: false,
})
.catch(() => null);
if (!mission) {
return { success: false, error: "You do not have access to this mission." };
}
await signupForRole(payload, {
missionId: input.missionId,
userId,
roleIndex: input.roleIndex,
bypassEligibility: isAdminOrDeveloper(user as User),
});
return { success: true };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return message === "Unauthorized"
? { success: false, error: "You must be logged in." }
: { success: false, error: message };
}
}
export async function withdrawMissionRoleSignup(input: {
missionId: number;
}): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const userId = user.id as number;
const mission = await payload
.findByID({
collection: "missions",
id: input.missionId,
depth: 0,
user,
overrideAccess: false,
})
.catch(() => null);
if (!mission) {
return { success: false, error: "You do not have access to this mission." };
}
await withdrawRoleSignup(payload, { missionId: input.missionId, userId });
return { success: true };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return message === "Unauthorized"
? { success: false, error: "You must be logged in." }
: { success: false, error: message };
}
}
export async function removeMissionRoleSignup(input: {
missionId: number;
signupId: number;
}): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const userId = user.id as number;
const canManage = await hasPermission(payload, user, "missions:update");
if (!canManage) {
return { success: false, error: "You do not have permission to manage role sign-ups." };
}
await removeRoleSignup(payload, {
missionId: input.missionId,
signupId: input.signupId,
actorId: userId,
});
return { success: true };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return message === "Unauthorized"
? { success: false, error: "You must be logged in." }
: { success: false, error: message };
}
}

View file

@ -62,10 +62,6 @@ export async function placeStructure(params: {
};
}
if (!(await requireMapPermission(payload, user, "maps:place"))) {
return { success: false, error: "Structure placement permission required." };
}
const { mapId, blueprintId, name, x, y } = params;
if (!Number.isFinite(x) || !Number.isFinite(y)) {
@ -293,14 +289,7 @@ export interface MapNodeInput {
async function requireMapPermission(
payload: Awaited<ReturnType<typeof getPayload>>,
user: { id: number | string },
permission:
| "maps:create"
| "maps:update"
| "maps:delete"
| "maps:place"
| "map-roads:author"
| "map-zones:author"
| "resource-nodes:author",
permission: "maps:create" | "maps:update" | "maps:delete",
): Promise<boolean> {
return hasPermission(payload, user, permission);
}
@ -335,8 +324,8 @@ export async function saveMapRoad(input: MapRoadInput): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const editing = input.id != null;
if (!(await requireMapPermission(payload, user, "map-roads:author"))) {
return { success: false, error: "Map road authoring permission required." };
if (!(await requireMapPermission(payload, user, editing ? "maps:update" : "maps:create"))) {
return { success: false, error: "Map configuration permission required." };
}
if (!isPointArray(input.points, 2)) {
return { success: false, error: "A road requires at least two points." };
@ -396,8 +385,8 @@ export async function saveMapZone(input: MapZoneInput): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const editing = input.id != null;
if (!(await requireMapPermission(payload, user, "map-zones:author"))) {
return { success: false, error: "Map zone authoring permission required." };
if (!(await requireMapPermission(payload, user, editing ? "maps:update" : "maps:create"))) {
return { success: false, error: "Map configuration permission required." };
}
if (!isPointArray(input.points, 3)) {
return { success: false, error: "A zone requires at least three points." };
@ -457,8 +446,8 @@ export async function saveMapNode(input: MapNodeInput): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const editing = input.id != null;
if (!(await requireMapPermission(payload, user, "resource-nodes:author"))) {
return { success: false, error: "Map node authoring permission required." };
if (!(await requireMapPermission(payload, user, editing ? "maps:update" : "maps:create"))) {
return { success: false, error: "Map configuration permission required." };
}
if (validatePosition(input.position) !== true) {
return { success: false, error: "A node requires a single [x, y] position." };
@ -527,17 +516,11 @@ export async function deleteMapFeature(
): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
const collection =
kind === "road" ? "map-roads" : kind === "zone" ? "map-zones" : "resource-nodes";
const permission =
kind === "road"
? "map-roads:author"
: kind === "zone"
? "map-zones:author"
: "resource-nodes:author";
if (!(await requireMapPermission(payload, user, permission))) {
if (!(await requireMapPermission(payload, user, "maps:delete"))) {
return { success: false, error: "Map configuration permission required." };
}
const collection =
kind === "road" ? "map-roads" : kind === "zone" ? "map-zones" : "resource-nodes";
await payload.delete({ collection, id, overrideAccess: false });
return { success: true };
} catch (error) {

View file

@ -31,23 +31,14 @@ export default async function MapViewPage({ params }: MapViewPageProps) {
if (!map) notFound();
const [canPlace, canAuthorRoads, canAuthorZones, canAuthorNodes] = await Promise.all([
user
? Promise.all([
hasPermission(payload, user, "maps:place"),
hasLogisticsQualification(payload, user),
]).then(([place, logistics]) => place && logistics)
: Promise.resolve(false),
user ? hasPermission(payload, user, "map-roads:author") : Promise.resolve(false),
user ? hasPermission(payload, user, "map-zones:author") : Promise.resolve(false),
user ? hasPermission(payload, user, "resource-nodes:author") : Promise.resolve(false),
const [canEdit, canPlace] = await Promise.all([
user ? hasPermission(payload, user, "maps:update") : Promise.resolve(false),
user ? hasLogisticsQualification(payload, user) : Promise.resolve(false),
]);
// Inactive maps stay reachable for editors previewing them, but are hidden
// from everyone else.
if (!map.isActive && !(canAuthorRoads || canAuthorZones || canAuthorNodes || canPlace)) {
notFound();
}
if (!map.isActive && !canEdit) notFound();
return (
<div className="relative flex min-h-[240px] flex-1 flex-col">
@ -63,11 +54,7 @@ export default async function MapViewPage({ params }: MapViewPageProps) {
</span>
</div>
</div>
<MapLoader
map={{ id: map.id, name: map.name }}
canAuthor={{ roads: canAuthorRoads, zones: canAuthorZones, nodes: canAuthorNodes }}
canPlace={canPlace}
/>
<MapLoader map={{ id: map.id, name: map.name }} canEdit={canEdit} canPlace={canPlace} />
</div>
);
}

View file

@ -84,18 +84,8 @@ export async function POST(req: NextRequest) {
if (!user) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const [canAuthorRoads, canAuthorZones, canAuthorNodes] = await Promise.all([
hasPermission(payload, user, "map-roads:author"),
hasPermission(payload, user, "map-zones:author"),
hasPermission(payload, user, "resource-nodes:author"),
]);
// A FeatureCollection can carry all three feature types, so importing
// requires the author permission for every type it would create.
if (!(canAuthorRoads && canAuthorZones && canAuthorNodes)) {
return NextResponse.json(
{ error: "Forbidden: road, zone, and node authoring permissions are all required." },
{ status: 403 },
);
if (!(await hasPermission(payload, user, "maps:create"))) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
let body: (GeoJsonCollection & { mapId?: number }) | null = null;

View file

@ -1,92 +0,0 @@
import { CollectionConfig } from "payload";
import { requirePermission, hasPermission } from "@/utils/access-control/hasPermission";
/**
* Role sign-ups for missions. Each row queues a user for one role (by index
* into the mission's `missionRoles.providedRoles` array). All writes flow
* through `src/lib/intelligence/roleSignups.ts` (overrideAccess), which
* enforces one live sign-up per user per mission and eligibility rules, so the
* collection-level access mirrors MissionAttendances.
*/
export const MissionRoleSignups: CollectionConfig = {
slug: "mission-role-signups",
admin: {
group: "Intelligence",
defaultColumns: ["mission", "user", "roleIndex", "createdAt"],
},
access: {
read: async ({ req }) => !!req.user,
create: async ({ req }) => {
return await hasPermission(req.payload, req.user, "mission-role-signups:create");
},
update: async ({ req, data, id }) => {
if (!req.user || typeof id !== "number") return false;
if (await hasPermission(req.payload, req.user, "mission-role-signups:update")) return true;
const ownerId = typeof data?.user === "object" ? data.user?.id : data?.user;
if (ownerId === req.user.id) return true;
const doc = (await req.payload
.findByID({
collection: "mission-role-signups",
id,
depth: 0,
overrideAccess: true,
})
.catch(() => null)) as unknown as { user?: number | { id: number } } | null;
if (!doc) return false;
const docOwner = typeof doc.user === "object" ? doc.user?.id : doc.user;
return docOwner === req.user.id;
},
delete: async ({ req, id }) => {
if (!req.user || typeof id !== "number") return false;
if (await hasPermission(req.payload, req.user, "mission-role-signups:delete")) return true;
const doc = (await req.payload
.findByID({
collection: "mission-role-signups",
id,
depth: 0,
overrideAccess: true,
})
.catch(() => null)) as unknown as { user?: number | { id: number } } | null;
if (!doc) return false;
const docOwner = typeof doc.user === "object" ? doc.user?.id : doc.user;
return docOwner === req.user.id;
},
},
fields: [
{
name: "mission",
type: "relationship",
relationTo: "missions",
required: true,
index: true,
},
{
name: "user",
type: "relationship",
relationTo: "users",
required: true,
},
{
name: "roleIndex",
type: "number",
label: "Role Index",
required: true,
min: 0,
admin: {
description:
"Index into the mission's missionRoles.providedRoles array. A roleName snapshot is kept alongside in case the mission's role list is later edited.",
},
},
{
name: "roleNameSnapshot",
type: "text",
label: "Role Name Snapshot",
admin: {
description: "Copy of the role name at sign-up time, for display if the role list changes.",
},
},
],
};

View file

@ -109,36 +109,6 @@ export const Missions: CollectionConfig = {
},
};
},
// Prune role sign-ups whose roleIndex points past the current role list
// (the mission's roles were edited after people signed up). Update-only:
// a mission cannot have sign-ups before it exists.
async ({ data, originalDoc, req, operation }) => {
if (operation !== "update") return data;
const providedRoles = data?.missionRoles?.providedRoles;
if (!providedRoles) return data;
const missionId = originalDoc?.id;
if (typeof missionId !== "number") return data;
const stale = await req.payload.find({
collection: "mission-role-signups",
where: {
and: [
{ mission: { equals: missionId } },
{ roleIndex: { greater_than_equal: providedRoles.length } },
],
},
limit: 1000,
depth: 0,
overrideAccess: true,
});
for (const signup of stale.docs) {
await req.payload.delete({
collection: "mission-role-signups",
id: signup.id,
overrideAccess: true,
});
}
return data;
},
],
},
access: {
@ -478,14 +448,6 @@ export const Missions: CollectionConfig = {
type: "text",
required: true,
},
{
name: "description",
type: "richText",
admin: {
description:
"Shown to players under the role name: what the role does and what is expected of whoever fills it.",
},
},
{
name: "missionCritical",
type: "checkbox",
@ -515,18 +477,6 @@ export const Missions: CollectionConfig = {
"This role can only be fulfilled by someone of this rank or higher.",
},
},
{
name: "slots",
type: "number",
label: "Slots",
defaultValue: 1,
min: 1,
max: 128,
admin: {
description:
"How many members can hold this role. Extra sign-ups form a first-come, first-served waitlist that auto-promotes when a holder stops attending.",
},
},
],
},
{

View file

@ -17,9 +17,9 @@ export const MapRoads: CollectionConfig = {
},
access: {
read: ({ req }) => !!req.user,
create: requirePermission("map-roads:author"),
update: requirePermission("map-roads:author"),
delete: requirePermission("map-roads:author"),
create: requirePermission("maps:create"),
update: requirePermission("maps:update"),
delete: requirePermission("maps:delete"),
},
fields: [
{

View file

@ -16,9 +16,9 @@ export const MapZones: CollectionConfig = {
},
access: {
read: ({ req }) => !!req.user,
create: requirePermission("map-zones:author"),
update: requirePermission("map-zones:author"),
delete: requirePermission("map-zones:author"),
create: requirePermission("maps:create"),
update: requirePermission("maps:update"),
delete: requirePermission("maps:delete"),
},
fields: [
{

View file

@ -16,9 +16,9 @@ export const ResourceNodes: CollectionConfig = {
},
access: {
read: ({ req }) => !!req.user,
create: requirePermission("resource-nodes:author"),
update: requirePermission("resource-nodes:author"),
delete: requirePermission("resource-nodes:author"),
create: requirePermission("maps:create"),
update: requirePermission("maps:update"),
delete: requirePermission("maps:delete"),
},
fields: [
{

View file

@ -1,252 +0,0 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ClipboardListIcon, UserCheckIcon, UserPlusIcon, UsersIcon, XIcon } from "lucide-react";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import {
RoleDescription,
type RoleDescriptionData,
} from "@/components/frontend/intelligence/RoleDescription";
import {
removeMissionRoleSignup,
signupForMissionRole,
withdrawMissionRoleSignup,
type ActionResult,
} from "@/app/(frontend)/intelligence/missions/actions";
interface SignupPersonView {
signupId: number;
userId: number;
name: string;
holding: boolean;
position: number;
}
interface SignupRoleView {
roleIndex: number;
roleName: string;
description?: RoleDescriptionData;
missionCritical: boolean;
slots: number;
filled: number;
entries: SignupPersonView[];
eligibility: { eligible: boolean; reasons: string[] } | null;
}
interface MissionRoleSignupsProps {
missionId: number;
currentUserId: number | null;
closed: boolean;
closedReason?: string | null;
roles: SignupRoleView[];
mySignup: { roleIndex: number; holding: boolean; position: number } | null;
canManage: boolean;
}
export function MissionRoleSignups({
missionId,
currentUserId,
closed,
closedReason,
roles,
mySignup,
canManage,
}: MissionRoleSignupsProps) {
const router = useRouter();
const [pending, setPending] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
if (roles.length === 0) return null;
async function run(key: string, action: () => Promise<ActionResult>) {
setPending(key);
setError(null);
const res = await action();
if (!res.success) {
setError(res.error ?? "Something went wrong.");
}
setPending(null);
router.refresh();
}
const signup = (role: SignupRoleView) =>
run(`signup:${role.roleIndex}`, () =>
signupForMissionRole({ missionId, roleIndex: role.roleIndex }),
);
const withdraw = () => run("withdraw", () => withdrawMissionRoleSignup({ missionId }));
const remove = (signupId: number) =>
run(`remove:${signupId}`, () => removeMissionRoleSignup({ missionId, signupId }));
return (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ClipboardListIcon className="size-4 text-muted-foreground" />
<ItemTitle>Role Sign-Ups</ItemTitle>
</div>
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
First come, first served
</span>
</ItemHeader>
<ItemContent className="flex flex-col gap-3">
{closed && closedReason && <p className="text-xs text-muted-foreground">{closedReason}</p>}
{!currentUserId && (
<p className="text-xs text-muted-foreground">Log in to sign up for a role.</p>
)}
{error && <p className="text-xs text-red-400">{error}</p>}
{roles.map((role) => {
const holders = role.entries.filter((e) => e.holding);
const waitlist = role.entries.filter((e) => !e.holding);
const isMine = mySignup?.roleIndex === role.roleIndex;
const openSlots = Math.max(0, role.slots - role.filled);
const eligible = role.eligibility?.eligible ?? true;
const reasons = role.eligibility?.reasons ?? [];
return (
<div
key={role.roleIndex}
className={cn(
"rounded-md border p-3 flex flex-col gap-2",
isMine ? "border-primary/40" : "border-border/60",
)}
>
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium">{role.roleName}</span>
{role.missionCritical && (
<span className="rounded-sm bg-red-500/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-red-400">
Critical
</span>
)}
<span className="ml-auto font-mono text-xs text-muted-foreground">
{role.filled}/{role.slots}
</span>
</div>
{role.description && <RoleDescription description={role.description} />}
<div className="flex flex-col gap-1">
<div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider">
<UserCheckIcon className="size-3.5 text-emerald-400" />
<span className="text-emerald-400">Slots</span>
{openSlots > 0 && (
<span className="font-mono text-amber-400">({openSlots} open)</span>
)}
</div>
{holders.length > 0 ? (
<ul className="flex flex-wrap gap-x-3 gap-y-0.5">
{holders.map((person) => (
<li
key={person.signupId}
className={cn(
"flex items-center gap-1 text-sm",
person.userId === currentUserId
? "text-foreground font-medium"
: "text-muted-foreground",
)}
>
{person.name}
{canManage && person.userId !== currentUserId && (
<button
type="button"
title="Remove sign-up"
disabled={pending !== null}
onClick={() => void remove(person.signupId)}
className="text-muted-foreground/50 transition-colors hover:text-red-400 disabled:opacity-50"
>
<XIcon className="size-3" />
</button>
)}
</li>
))}
</ul>
) : (
<p className="text-sm text-muted-foreground italic">Unfilled.</p>
)}
</div>
{waitlist.length > 0 && (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider">
<UsersIcon className="size-3.5 text-muted-foreground" />
<span className="text-muted-foreground">Waitlist</span>
<span className="font-mono text-muted-foreground">({waitlist.length})</span>
</div>
<ul className="flex flex-wrap gap-x-3 gap-y-0.5">
{waitlist.map((person) => (
<li key={person.signupId} className="flex items-center gap-1 text-sm">
<span className="font-mono text-xs text-muted-foreground">
{person.position}.
</span>
<span
className={cn(
person.userId === currentUserId
? "text-foreground font-medium"
: "text-muted-foreground",
)}
>
{person.name}
</span>
{canManage && (
<button
type="button"
title="Remove sign-up"
disabled={pending !== null}
onClick={() => void remove(person.signupId)}
className="text-muted-foreground/50 transition-colors hover:text-red-400 disabled:opacity-50"
>
<XIcon className="size-3" />
</button>
)}
</li>
))}
</ul>
</div>
)}
{isMine && (
<p className="text-xs text-muted-foreground">
{mySignup?.holding
? "You hold a slot for this role."
: `You are waitlisted (#${mySignup?.position}).`}
</p>
)}
{currentUserId !== null && !closed && !eligible && !isMine && reasons.length > 0 && (
<p className="text-xs text-red-400">{reasons.join(" ")}</p>
)}
{currentUserId !== null && !closed && (
<div className="flex items-center gap-2">
{isMine ? (
<Button
size="sm"
variant="outline"
disabled={pending !== null}
onClick={() => void withdraw()}
>
<XIcon className="size-3.5" />
Withdraw
</Button>
) : (
<Button
size="sm"
variant="outline"
disabled={pending !== null || !eligible}
title={eligible ? undefined : reasons.join(" ")}
onClick={() => void signup(role)}
>
<UserPlusIcon className="size-3.5" />
{mySignup ? "Switch to this role" : "Sign up"}
</Button>
)}
</div>
)}
</div>
);
})}
</ItemContent>
</Item>
);
}

View file

@ -1,18 +1,12 @@
import { CheckIcon, UsersIcon, XIcon } from "lucide-react";
import type { Qualification, Rank } from "@/payload-types";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import {
RoleDescription,
type RoleDescriptionData,
} from "@/components/frontend/intelligence/RoleDescription";
interface RoleEntry {
roleName: string;
description?: RoleDescriptionData | null;
missionCritical?: boolean | null;
requiredMos?: (Qualification | number)[] | null;
minimumRank?: Rank | number | null;
slots?: number | null;
}
interface MissionRolesProps {
@ -65,9 +59,6 @@ export function MissionRoles({ roles, notes, maxPlayers }: MissionRolesProps) {
<th className="text-left px-4 py-2.5 font-semibold uppercase text-xs tracking-wider text-muted-foreground">
Role Name
</th>
<th className="text-center px-4 py-2.5 font-semibold uppercase text-xs tracking-wider text-muted-foreground">
Slots
</th>
<th className="text-center px-4 py-2.5 font-semibold uppercase text-xs tracking-wider text-muted-foreground">
Critical
</th>
@ -82,15 +73,7 @@ export function MissionRoles({ roles, notes, maxPlayers }: MissionRolesProps) {
<tbody>
{roles.map((role, index) => (
<tr key={index} className="border-b border-border/50">
<td className="px-4 py-2 font-medium">
{role.roleName}
{role.description && (
<RoleDescription description={role.description} className="mt-1 max-w-md" />
)}
</td>
<td className="px-4 py-2 text-center font-mono text-muted-foreground">
{role.slots ?? 1}
</td>
<td className="px-4 py-2 font-medium">{role.roleName}</td>
<td className="px-4 py-2 text-center">
{role.missionCritical ? (
<CheckIcon className="size-3.5 text-green-400 inline" />

View file

@ -1,31 +0,0 @@
import { RichText } from "@payloadcms/richtext-lexical/react";
import { cn } from "@/lib/utils";
type LexicalData = Parameters<typeof RichText>[0]["data"];
export type RoleDescriptionData = LexicalData | string | null;
interface RoleDescriptionProps {
description: RoleDescriptionData | undefined;
className?: string;
}
/**
* Player-facing mission role description. Renders Lexical richText; plain
* strings (written before the field became richText) still render as text.
*/
export function RoleDescription({ description, className }: RoleDescriptionProps) {
if (typeof description === "string") {
return (
<p className={cn("whitespace-pre-line text-xs text-muted-foreground", className)}>
{description}
</p>
);
}
if (!description || typeof description !== "object") return null;
return (
<div className={cn("lexical-content", className)}>
<RichText data={description as LexicalData} />
</div>
);
}

View file

@ -503,22 +503,9 @@ function ResourcePicker({
);
}
export function AuthoringToolbar({
authoring,
mapId,
canAuthor,
}: {
authoring: MapAuthoring;
mapId: number;
canAuthor: { roads: boolean; zones: boolean; nodes: boolean };
}) {
export function AuthoringToolbar({ authoring, mapId }: { authoring: MapAuthoring; mapId: number }) {
const resources = useResourceOptions();
const { kind, fields } = authoring;
const canDraw = {
road: canAuthor.roads,
zone: canAuthor.zones,
node: canAuthor.nodes,
};
return (
<div className="pointer-events-auto w-[640px] max-w-[calc(100vw-10rem)] overflow-hidden rounded-none border border-white/15 bg-black/80 backdrop-blur-sm">
@ -532,21 +519,19 @@ export function AuthoringToolbar({
</div>
<div className="flex flex-col gap-2 p-2">
<div className="flex items-center gap-1.5">
{(["road", "zone", "node"] as const)
.filter((target) => canDraw[target])
.map((target) => (
<Button
key={target}
size="sm"
variant={kind === target && !authoring.editing ? "secondary" : "outline"}
className="h-8 px-2.5 text-xs capitalize"
onClick={() =>
authoring.setKind(kind === target && !authoring.editing ? null : target)
}
>
{target === "node" ? "New node" : `New ${target}`}
</Button>
))}
{(["road", "zone", "node"] as const).map((target) => (
<Button
key={target}
size="sm"
variant={kind === target && !authoring.editing ? "secondary" : "outline"}
className="h-8 px-2.5 text-xs capitalize"
onClick={() =>
authoring.setKind(kind === target && !authoring.editing ? null : target)
}
>
{target === "node" ? "New node" : `New ${target}`}
</Button>
))}
<span className="ml-auto text-xs text-white/60">
{authoring.draftPoints.length} point{authoring.draftPoints.length === 1 ? "" : "s"}
{kind === "road" && authoring.draftPoints.length < 2 && " (need 2+)"}

View file

@ -53,7 +53,7 @@ import { nodeIconOption } from "@/lib/map/nodeIcons";
export interface MapClientProps {
map: { id: number; name: string };
canAuthor: { roads: boolean; zones: boolean; nodes: boolean };
canEdit: boolean;
canPlace: boolean;
}
@ -1150,8 +1150,7 @@ function ShipmentLayer({ shipments }: { shipments: ShipmentFeature[] }) {
);
}
export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
const canEdit = canAuthor.roads || canAuthor.zones || canAuthor.nodes;
export function MapClient({ map, canEdit, canPlace }: MapClientProps) {
const selectedMapId = map.id;
const [features, setFeatures] = useState<MapFeaturesResponse | null>(null);
const [error, setError] = useState<string | null>(null);
@ -1402,7 +1401,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
{zone.description && (
<div className="mt-1 text-xs text-white/70">{zone.description}</div>
)}
{canAuthor.zones && mode === "edit" && (
{canEdit && mode === "edit" && (
<div className="mt-2 flex gap-1.5">
<Button
size="sm"
@ -1457,7 +1456,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
{road.description && (
<div className="mt-1 text-xs text-white/70">{road.description}</div>
)}
{canAuthor.roads && mode === "edit" && (
{canEdit && mode === "edit" && (
<div className="mt-2 flex gap-1.5">
<Button
size="sm"
@ -1545,7 +1544,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
{node.richness != null && node.resources.length > 0 && (
<div className="text-xs text-white/60">Richness {node.richness}</div>
)}
{canAuthor.nodes && mode === "edit" && (
{canEdit && mode === "edit" && (
<div className="mt-2 flex gap-1.5">
<Button
size="sm"
@ -1720,13 +1719,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) {
</div>
</div>
{mode === "edit" && (
<AuthoringToolbar
authoring={authoring}
mapId={selectedMapId ?? 0}
canAuthor={canAuthor}
/>
)}
{mode === "edit" && <AuthoringToolbar authoring={authoring} mapId={selectedMapId ?? 0} />}
</div>
{error && (

View file

@ -1,19 +1,21 @@
import type { MissionAttendance, User } from "@/payload-types";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { getSlotHolders, notifySlotHoldersDiff } from "@/lib/intelligence/roleSignups";
export type AttendanceResponse = "yes" | "no" | "tentative";
// Shared mission-time gates live in lib/intelligence/missionTime.ts; re-exported
// here to keep the existing public API of this module unchanged.
import {
attendanceClosedMessage as sharedAttendanceClosedMessage,
isMissionPast as sharedIsMissionPast,
} from "@/lib/intelligence/missionTime";
/**
* Returns true when the mission's start time has passed.
* Failures to parse the start date fall open (allow attendance) so a malformed
* timestamp never bricks RSVP on an otherwise valid mission.
*/
export function isMissionPast(startDateTime: string, now: Date = new Date()): boolean {
const start = new Date(startDateTime);
if (Number.isNaN(start.getTime())) return false;
return start.getTime() <= now.getTime();
}
export const isMissionPast = sharedIsMissionPast;
export const attendanceClosedMessage = sharedAttendanceClosedMessage;
export const attendanceClosedMessage = "Attendance is closed for this mission.";
export interface MissionAttendanceCounts {
yes: number;
@ -65,11 +67,6 @@ export async function setMissionAttendance(
throw new Error(attendanceClosedMessage);
}
// Slot holders are derived from RSVP, so an RSVP change can promote the next
// waitlisted role sign-up. Diff around the write (single write path shared by
// web and Discord RSVPs).
const beforeSlotHolders = await getSlotHolders(payload, missionId);
const existing = (await payload.find({
collection: "mission-attendances",
where: {
@ -107,9 +104,6 @@ export async function setMissionAttendance(
data: { response },
});
const afterSlotHolders = await getSlotHolders(payload, missionId);
await notifySlotHoldersDiff(payload, missionId, beforeSlotHolders, afterSlotHolders, [userId]);
return entry;
}

View file

@ -1,18 +0,0 @@
/**
* Shared mission-time gate helpers, extracted from `src/lib/attendance` so the
* role sign-ups lib can reuse them without importing the attendance module
* (which itself depends on the sign-ups lib for slot promotion reconciliation).
*/
/**
* Returns true when the mission's start time has passed.
* Failures to parse the start date fall open (allow attendance) so a malformed
* timestamp never bricks RSVP on an otherwise valid mission.
*/
export function isMissionPast(startDateTime: string, now: Date = new Date()): boolean {
const start = new Date(startDateTime);
if (Number.isNaN(start.getTime())) return false;
return start.getTime() <= now.getTime();
}
export const attendanceClosedMessage = "Attendance is closed for this mission.";

View file

@ -1,616 +0,0 @@
import type { Mission, MissionRoleSignup, Qualification, Rank, User } from "@/payload-types";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { notifyUser } from "@/lib/notifications";
import { loadRankLadder, resolveRankFromLadder, rankIndex } from "@/lib/promotions/authority";
import { isMissionPast } from "@/lib/intelligence/missionTime";
type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
export const roleSignupsClosedMessage = "Role sign-ups are closed for this mission.";
/** Notification type used when a waitlisted member is promoted into a slot. */
export const ROLE_PROMOTED_NOTIFICATION_TYPE = "mission:role-promoted";
export interface RoleRequirementRefs {
requiredMos?: (Qualification | number)[] | null;
minimumRank?: Rank | number | null;
}
export interface RoleEligibility {
eligible: boolean;
reasons: string[];
}
export interface RoleSignupGate {
open: boolean;
reason?: string;
}
export interface RoleQueueEntryView {
signupId: number;
userId: number;
name: string;
holding: boolean;
/** 1-based position within this role's queue (slot holders come first). */
position: number;
}
export interface RoleSignupRoleState {
roleIndex: number;
roleName: string;
slots: number;
filled: number;
entries: RoleQueueEntryView[];
}
export interface MissionRoleSignupState {
roles: RoleSignupRoleState[];
mySignup: { roleIndex: number; holding: boolean; position: number } | null;
}
/** userId -> roleIndex for everyone currently holding a slot on the mission. */
export type SlotHolderMap = Map<number, number>;
/**
* Sign-up gate: sign-ups stay open until the op start passes (mirroring
* attendance) and close permanently on Cancelled/Completed.
*/
export function roleSignupGate(mission: {
ownershipAndStatus?: { status?: string | null } | null;
classification?: { startDateTime?: string | null } | null;
}): RoleSignupGate {
const status = mission.ownershipAndStatus?.status;
if (status === "Cancelled") return { open: false, reason: "This operation was cancelled." };
if (status === "Completed") return { open: false, reason: "This operation has concluded." };
const startDateTime = mission.classification?.startDateTime;
if (startDateTime && isMissionPast(startDateTime)) {
return { open: false, reason: roleSignupsClosedMessage };
}
return { open: true };
}
interface EligibilityProfileData {
rankId: number | null;
qualificationIds: number[];
}
async function loadEligibilityProfileData(
payload: PayloadType,
userId: number,
): Promise<EligibilityProfileData | null> {
const res = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 1,
select: { rank: true, progression: { qualifications: true } },
overrideAccess: true,
});
const doc = res.docs[0] as
| {
rank?: number | { id: number } | null;
progression?: { qualifications?: (Qualification | number)[] | null };
}
| undefined;
if (!doc) return null;
const rankId =
typeof doc.rank === "object" && doc.rank !== null ? doc.rank.id : (doc.rank ?? null);
const qualificationIds = (doc.progression?.qualifications ?? [])
.map((q) => (typeof q === "object" && q !== null ? q.id : q))
.filter((id): id is number => typeof id === "number");
return { rankId: rankId ?? null, qualificationIds };
}
async function resolveQualificationNames(
payload: PayloadType,
refs: (Qualification | number)[],
): Promise<Map<number, string>> {
const names = new Map<number, string>();
const ids: number[] = [];
for (const ref of refs) {
if (typeof ref === "object" && ref !== null) names.set(ref.id, ref.name);
else if (typeof ref === "number") ids.push(ref);
}
if (ids.length > 0) {
const res = await payload.find({
collection: "qualifications",
where: { id: { in: ids } },
limit: ids.length,
depth: 0,
overrideAccess: true,
});
for (const q of res.docs as Qualification[]) names.set(q.id, q.name);
}
return names;
}
/**
* Check the current user against each role's requirements in one pass
* (profile + rank ladder are loaded once). Roles without requirements are
* always eligible. A required rank missing from the ladder fails open so a
* misconfigured rank never bricks sign-ups.
*/
export async function checkRoleEligibilities(
payload: PayloadType,
userId: number,
roles: RoleRequirementRefs[],
bypass = false,
): Promise<RoleEligibility[]> {
if (bypass) return roles.map(() => ({ eligible: true, reasons: [] }));
const hasRequirements = roles.some(
(r) => r.minimumRank != null || (r.requiredMos?.length ?? 0) > 0,
);
if (!hasRequirements) return roles.map(() => ({ eligible: true, reasons: [] }));
const [ladder, profileData] = await Promise.all([
loadRankLadder(payload),
loadEligibilityProfileData(payload, userId),
]);
const results: RoleEligibility[] = [];
for (const role of roles) {
const reasons: string[] = [];
if (role.minimumRank != null) {
const minId = typeof role.minimumRank === "object" ? role.minimumRank.id : role.minimumRank;
const minRank = resolveRankFromLadder(ladder, minId);
if (minRank) {
const profileRank =
profileData?.rankId != null ? resolveRankFromLadder(ladder, profileData.rankId) : null;
if (!profileRank) {
reasons.push("You need a rank on your profile before you can hold this role.");
} else if (rankIndex(ladder, profileRank.id) < rankIndex(ladder, minRank.id)) {
reasons.push(`Requires the rank of ${minRank.name} or higher.`);
}
}
}
const mos = role.requiredMos ?? [];
if (mos.length > 0) {
if (!profileData) {
reasons.push("You need a profile before you can hold this role.");
} else {
const names = await resolveQualificationNames(payload, mos);
const have = new Set(profileData.qualificationIds);
const missing = mos
.map((ref) => (typeof ref === "object" && ref !== null ? ref.id : ref))
.filter((id): id is number => typeof id === "number" && !have.has(id))
.map((id) => names.get(id) ?? `#${id}`);
if (missing.length > 0) {
reasons.push(
missing.length === 1
? `Requires qualification: ${missing[0]}.`
: `Requires qualifications: ${missing.join(", ")}.`,
);
}
}
}
results.push({ eligible: reasons.length === 0, reasons });
}
return results;
}
export async function checkRoleEligibility(
payload: PayloadType,
userId: number,
role: RoleRequirementRefs,
): Promise<RoleEligibility> {
return (await checkRoleEligibilities(payload, userId, [role]))[0];
}
function missionName(mission: { name?: string | null } | null | undefined, id: number): string {
return mission?.name ?? `Mission #${id}`;
}
function signupUserId(signup: MissionRoleSignup): number {
return typeof signup.user === "object" ? signup.user.id : signup.user;
}
/** Stable FCFS order: createdAt ascending, id as the tiebreaker. */
function byFirstCome(a: MissionRoleSignup, b: MissionRoleSignup): number {
if (a.createdAt < b.createdAt) return -1;
if (a.createdAt > b.createdAt) return 1;
return a.id - b.id;
}
async function fetchSignupsForMission(
payload: PayloadType,
missionId: number,
): Promise<MissionRoleSignup[]> {
const res = await payload.find({
collection: "mission-role-signups",
where: { mission: { equals: missionId } },
limit: 1000,
depth: 0,
overrideAccess: true,
});
return (res.docs as MissionRoleSignup[]).slice().sort(byFirstCome);
}
async function fetchAttendingUserIds(
payload: PayloadType,
missionId: number,
): Promise<Set<number>> {
const res = await payload.find({
collection: "mission-attendances",
where: {
and: [{ mission: { equals: missionId } }, { response: { equals: "yes" } }],
},
limit: 1000,
depth: 0,
overrideAccess: true,
});
return new Set(
(res.docs as { user: number | { id: number } }[]).map((d) =>
typeof d.user === "object" ? d.user.id : d.user,
),
);
}
async function resolveUserName(payload: PayloadType, userId: number): Promise<string> {
const user = (await payload
.findByID({ collection: "users", id: userId, depth: 0, overrideAccess: true })
.catch(() => null)) as User | null;
return user ? user.displayName || user.username : `user #${userId}`;
}
/**
* Compute who currently holds each role's slots. Slot holders are the first
* `slots` sign-ups (FCFS) whose owner's attendance RSVP is "yes"; everyone
* else is waitlisted in signup order. Stateless: derived entirely from the
* current signups + attendance rows, so there is no promotion state to drift.
*/
export async function getSlotHolders(
payload: PayloadType,
missionId: number,
): Promise<SlotHolderMap> {
const signups = await fetchSignupsForMission(payload, missionId);
if (signups.length === 0) return new Map();
const mission = (await payload.findByID({
collection: "missions",
id: missionId,
depth: 0,
overrideAccess: true,
})) as Mission;
const roles = mission.missionRoles?.providedRoles ?? [];
const yesUserIds = await fetchAttendingUserIds(payload, missionId);
const holders: SlotHolderMap = new Map();
for (let index = 0; index < roles.length; index++) {
const slots = Math.max(1, roles[index].slots ?? 1);
let held = 0;
for (const signup of signups) {
if (held >= slots) break;
if (signup.roleIndex !== index) continue;
const userId = signupUserId(signup);
if (!yesUserIds.has(userId)) continue;
holders.set(userId, index);
held += 1;
}
}
return holders;
}
export function diffPromotedUsers(
before: SlotHolderMap,
after: SlotHolderMap,
): { userId: number; roleIndex: number }[] {
const promoted: { userId: number; roleIndex: number }[] = [];
for (const [userId, roleIndex] of after) {
if (!before.has(userId)) promoted.push({ userId, roleIndex });
}
return promoted;
}
/**
* Notify members who newly hold a slot (and log a promoted event). Called
* after any mutation that can shift slot ownership: RSVP changes, sign-up
* switches, and withdrawals. `excludeUserIds` silences notifications for the
* acting user (their own action already confirms it in the UI).
*/
export async function notifySlotHoldersDiff(
payload: PayloadType,
missionId: number,
before: SlotHolderMap,
after: SlotHolderMap,
excludeUserIds: number[] = [],
): Promise<void> {
const promoted = diffPromotedUsers(before, after).filter(
(p) => !excludeUserIds.includes(p.userId),
);
if (promoted.length === 0) return;
const mission = (await payload
.findByID({
collection: "missions",
id: missionId,
depth: 0,
overrideAccess: true,
})
.catch(() => null)) as Mission | null;
const roles = mission?.missionRoles?.providedRoles ?? [];
for (const { userId, roleIndex } of promoted) {
const roleName = roles[roleIndex]?.roleName ?? `role #${roleIndex}`;
const userName = await resolveUserName(payload, userId);
await notifyUser(payload, {
userId,
type: ROLE_PROMOTED_NOTIFICATION_TYPE,
title: `Slot granted: ${roleName}`,
message: `You now hold a ${roleName} slot for ${missionName(mission, missionId)}.`,
link: `/intelligence/missions/${missionId}`,
});
await emitGameEvent(payload, {
type: EventTypes.MissionRolePromoted,
message: `${missionName(mission, missionId)}: ${userName} was promoted into the ${roleName} slot.`,
targetCollection: "missions",
targetId: missionId,
data: { userId, roleIndex },
});
}
}
/**
* Full sign-up state for the mission detail page: per-role FCFS queue with
* slot-holding flags, plus the viewer's own position (if any). Sign-ups whose
* roleIndex points past the current role list (the mission's roles were later
* edited) are pruned by the Missions hook, so they are ignored here.
*/
export async function getMissionRoleSignupState(
payload: PayloadType,
missionId: number,
viewerId?: number | null,
): Promise<MissionRoleSignupState> {
const mission = (await payload.findByID({
collection: "missions",
id: missionId,
depth: 0,
overrideAccess: true,
})) as Mission;
const roles = mission.missionRoles?.providedRoles ?? [];
const signups = await fetchSignupsForMission(payload, missionId);
const yesUserIds = await fetchAttendingUserIds(payload, missionId);
const userIds = [...new Set(signups.map(signupUserId))];
const usersRes =
userIds.length > 0
? await payload.find({
collection: "users",
where: { id: { in: userIds } },
limit: userIds.length,
depth: 0,
overrideAccess: true,
})
: { docs: [] as User[] };
const nameById = new Map<number, string>();
for (const u of usersRes.docs as User[]) {
nameById.set(u.id, u.displayName || u.username);
}
const stateRoles: RoleSignupRoleState[] = roles.map((role, index) => {
const slots = Math.max(1, role.slots ?? 1);
const entries = signups.filter((s) => s.roleIndex === index);
let held = 0;
const views: RoleQueueEntryView[] = entries.map((signup, position) => {
const userId = signupUserId(signup);
const holding = yesUserIds.has(userId) && held < slots;
if (holding) held += 1;
return {
signupId: signup.id,
userId,
name: nameById.get(userId) ?? "Unknown",
holding,
position: position + 1,
};
});
return {
roleIndex: index,
roleName: role.roleName,
slots,
filled: views.filter((v) => v.holding).length,
entries: views,
};
});
let mySignup: MissionRoleSignupState["mySignup"] = null;
if (viewerId != null) {
for (const roleState of stateRoles) {
const mine = roleState.entries.find((e) => e.userId === viewerId);
if (mine) {
mySignup = {
roleIndex: roleState.roleIndex,
holding: mine.holding,
position: mine.position,
};
break;
}
}
}
return { roles: stateRoles, mySignup };
}
/**
* Queue the user for a role (FCFS). One live sign-up per user per mission:
* signing up for another role moves the existing sign-up. No-op when already
* signed up for the same role. Throws descriptive errors for the action layer.
*/
export async function signupForRole(
payload: PayloadType,
input: {
missionId: number;
userId: number;
roleIndex: number;
bypassEligibility?: boolean;
},
): Promise<void> {
const { missionId, userId, roleIndex, bypassEligibility = false } = input;
const mission = (await payload.findByID({
collection: "missions",
id: missionId,
depth: 0,
overrideAccess: true,
})) as Mission;
const gate = roleSignupGate(mission);
if (!gate.open) throw new Error(gate.reason ?? roleSignupsClosedMessage);
const roles = mission.missionRoles?.providedRoles ?? [];
const role = roles[roleIndex];
if (!role) throw new Error("This role no longer exists on the mission.");
if (!bypassEligibility) {
const eligibility = await checkRoleEligibility(payload, userId, role);
if (!eligibility.eligible) throw new Error(eligibility.reasons.join(" "));
}
const existingRes = await payload.find({
collection: "mission-role-signups",
where: {
and: [{ mission: { equals: missionId } }, { user: { equals: userId } }],
},
limit: 1,
depth: 0,
overrideAccess: true,
});
const existing = existingRes.docs[0] as MissionRoleSignup | undefined;
if (existing && existing.roleIndex === roleIndex) return;
const beforeHolders = await getSlotHolders(payload, missionId);
if (existing) {
await payload.update({
collection: "mission-role-signups",
id: existing.id,
data: { roleIndex, roleNameSnapshot: role.roleName },
overrideAccess: true,
depth: 0,
});
} else {
await payload.create({
collection: "mission-role-signups",
data: { mission: missionId, user: userId, roleIndex, roleNameSnapshot: role.roleName },
overrideAccess: true,
depth: 0,
});
}
const userName = await resolveUserName(payload, userId);
await emitGameEvent(payload, {
type: EventTypes.MissionRoleSignup,
message: `${missionName(mission, missionId)}: ${userName} signed up for ${role.roleName}.`,
actor: userId,
targetCollection: "missions",
targetId: missionId,
data: { roleIndex },
});
const afterHolders = await getSlotHolders(payload, missionId);
await notifySlotHoldersDiff(payload, missionId, beforeHolders, afterHolders, [userId]);
}
async function deleteSignupAndReconcile(
payload: PayloadType,
mission: Mission,
signup: MissionRoleSignup,
options: { actorId?: number; removedByStaff?: boolean } = {},
): Promise<void> {
const missionId = mission.id;
const roleIndex = signup.roleIndex;
const roleName =
signup.roleNameSnapshot ??
(mission.missionRoles?.providedRoles ?? [])[roleIndex]?.roleName ??
`role #${roleIndex}`;
const userId = signupUserId(signup);
const beforeHolders = await getSlotHolders(payload, missionId);
await payload.delete({
collection: "mission-role-signups",
id: signup.id,
overrideAccess: true,
});
const userName = await resolveUserName(payload, userId);
await emitGameEvent(payload, {
type: EventTypes.MissionRoleWithdraw,
message: options.removedByStaff
? `${missionName(mission, missionId)}: ${userName} was removed from ${roleName} by staff.`
: `${missionName(mission, missionId)}: ${userName} withdrew from ${roleName}.`,
actor: options.removedByStaff ? options.actorId : userId,
targetCollection: "missions",
targetId: missionId,
data: { roleIndex, removedByStaff: options.removedByStaff === true },
});
const afterHolders = await getSlotHolders(payload, missionId);
await notifySlotHoldersDiff(
payload,
missionId,
beforeHolders,
afterHolders,
[options.removedByStaff ? options.actorId : userId].filter(
(id): id is number => typeof id === "number",
),
);
}
/** Remove the user's own sign-up from the mission. */
export async function withdrawRoleSignup(
payload: PayloadType,
input: { missionId: number; userId: number },
): Promise<void> {
const { missionId, userId } = input;
const signups = await fetchSignupsForMission(payload, missionId);
const existing = signups.find((s) => signupUserId(s) === userId);
if (!existing) throw new Error("You are not signed up for a role on this mission.");
const mission = (await payload.findByID({
collection: "missions",
id: missionId,
depth: 0,
overrideAccess: true,
})) as Mission;
await deleteSignupAndReconcile(payload, mission, existing, { actorId: userId });
}
/** Staff removal: delete any sign-up on the mission and reconcile slots. */
export async function removeRoleSignup(
payload: PayloadType,
input: { missionId: number; signupId: number; actorId?: number },
): Promise<void> {
const signup = (await payload
.findByID({
collection: "mission-role-signups",
id: input.signupId,
depth: 0,
overrideAccess: true,
})
.catch(() => null)) as MissionRoleSignup | null;
if (!signup) throw new Error("Sign-up not found.");
const signupMissionId = typeof signup.mission === "object" ? signup.mission.id : signup.mission;
if (signupMissionId !== input.missionId) {
throw new Error("That sign-up belongs to a different mission.");
}
const mission = (await payload.findByID({
collection: "missions",
id: input.missionId,
depth: 0,
overrideAccess: true,
})) as Mission;
await deleteSignupAndReconcile(payload, mission, signup, {
actorId: input.actorId,
removedByStaff: true,
});
}

View file

@ -117,8 +117,6 @@ export function notificationLabel(type?: string | null): string {
return "Ribbon not approved";
case "personnel:promoted":
return "Promotion";
case "mission:role-promoted":
return "Role slot granted";
default:
return type ?? "Notification";
}

View file

@ -21,7 +21,6 @@ export const MUTEABLE_NOTIFICATION_TYPES = [
{ label: "Poker game auto-ended", value: "poker:everyone-left" },
{ label: "Blackjack", value: "blackjack:force-ended" },
{ label: "Blackjack table auto-ended", value: "blackjack:everyone-left" },
{ label: "Role slot promotions", value: "mission:role-promoted" },
] as const;
export type MuteableNotificationType = (typeof MUTEABLE_NOTIFICATION_TYPES)[number]["value"];
export const MUTEABLE_NOTIFICATION_VALUES = MUTEABLE_NOTIFICATION_TYPES.map((t) => t.value);

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

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_mission_roles_provided_roles" ADD COLUMN "description" varchar;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "missions_mission_roles_provided_roles" DROP COLUMN "description";`)
}

View file

@ -1,47 +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_mission_roles_provided_roles" ALTER COLUMN "description" SET DATA TYPE jsonb USING
CASE
WHEN "description" IS NULL OR "description" = '' THEN NULL
ELSE jsonb_build_object(
'root',
jsonb_build_object(
'type', 'root',
'format', '',
'indent', 0,
'version', 1,
'direction', 'ltr',
'children', jsonb_build_array(
jsonb_build_object(
'type', 'paragraph',
'format', '',
'indent', 0,
'version', 1,
'direction', 'ltr',
'children', jsonb_build_array(
jsonb_build_object(
'type', 'text',
'format', 0,
'style', '',
'mode', 'normal',
'text', "description",
'version', 1
)
)
)
)
)
)
END;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "missions_mission_roles_provided_roles" ALTER COLUMN "description" SET DATA TYPE varchar USING
CASE
WHEN "description" IS NULL THEN NULL
ELSE COALESCE("description" #>> '{root,children,0,children,0,text}', '')
END;`)
}

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -90,10 +90,6 @@ import * as migration_20260923_200000_add_missing_role_permission_enum_values fr
import * as migration_20260923_202700_add_form_builder_collections from './20260923_202700_add_form_builder_collections';
import * as migration_20260924_205400_add_story_beat_voiceover from './20260924_205400_add_story_beat_voiceover';
import * as migration_20260924_212353_add_story_voiceover_ai_generated from './20260924_212353_add_story_voiceover_ai_generated';
import * as migration_20260925_235150_add_mission_role_signups from './20260925_235150_add_mission_role_signups';
import * as migration_20260926_030859_add_mission_role_description from './20260926_030859_add_mission_role_description';
import * as migration_20260926_044319_add_mission_role_description_richtext from './20260926_044319_add_mission_role_description_richtext';
import * as migration_20260928_021138_change_ai_model from './20260928_021138_change_ai_model';
export const migrations = [
{
@ -554,26 +550,6 @@ export const migrations = [
{
up: migration_20260924_212353_add_story_voiceover_ai_generated.up,
down: migration_20260924_212353_add_story_voiceover_ai_generated.down,
name: '20260924_212353_add_story_voiceover_ai_generated',
},
{
up: migration_20260925_235150_add_mission_role_signups.up,
down: migration_20260925_235150_add_mission_role_signups.down,
name: '20260925_235150_add_mission_role_signups',
},
{
up: migration_20260926_030859_add_mission_role_description.up,
down: migration_20260926_030859_add_mission_role_description.down,
name: '20260926_030859_add_mission_role_description',
},
{
up: migration_20260926_044319_add_mission_role_description_richtext.up,
down: migration_20260926_044319_add_mission_role_description_richtext.down,
name: '20260926_044319_add_mission_role_description_richtext',
},
{
up: migration_20260928_021138_change_ai_model.up,
down: migration_20260928_021138_change_ai_model.down,
name: '20260928_021138_change_ai_model'
name: '20260924_212353_add_story_voiceover_ai_generated'
},
];

File diff suppressed because it is too large Load diff

View file

@ -91,7 +91,6 @@ export interface Config {
'ribbon-submissions': RibbonSubmission;
missions: Mission;
'mission-attendances': MissionAttendance;
'mission-role-signups': MissionRoleSignup;
campaigns: Campaign;
factions: Faction;
technologies: Technology;
@ -184,7 +183,6 @@ export interface Config {
'ribbon-submissions': RibbonSubmissionsSelect<false> | RibbonSubmissionsSelect<true>;
missions: MissionsSelect<false> | MissionsSelect<true>;
'mission-attendances': MissionAttendancesSelect<false> | MissionAttendancesSelect<true>;
'mission-role-signups': MissionRoleSignupsSelect<false> | MissionRoleSignupsSelect<true>;
campaigns: CampaignsSelect<false> | CampaignsSelect<true>;
factions: FactionsSelect<false> | FactionsSelect<true>;
technologies: TechnologiesSelect<false> | TechnologiesSelect<true>;
@ -463,7 +461,6 @@ export interface User {
| 'poker:everyone-left'
| 'blackjack:force-ended'
| 'blackjack:everyone-left'
| 'mission:role-promoted'
)[]
| null;
};
@ -500,7 +497,6 @@ export interface User {
| 'poker:everyone-left'
| 'blackjack:force-ended'
| 'blackjack:everyone-left'
| 'mission:role-promoted'
)[]
| null;
};
@ -635,11 +631,6 @@ export interface Role {
| 'mission-attendances:update'
| 'mission-attendances:delete'
| 'admin:mission-attendances:manage'
| 'mission-role-signups:create'
| 'mission-role-signups:read'
| 'mission-role-signups:update'
| 'mission-role-signups:delete'
| 'admin:mission-role-signups:manage'
| 'campaigns:create'
| 'campaigns:read'
| 'campaigns:update'
@ -780,16 +771,12 @@ export interface Role {
| 'maps:read'
| 'maps:update'
| 'maps:delete'
| 'maps:place'
| 'admin:maps:manage'
| 'map-roads:read'
| 'map-roads:author'
| 'admin:map-roads:manage'
| 'map-zones:read'
| 'map-zones:author'
| 'admin:map-zones:manage'
| 'resource-nodes:read'
| 'resource-nodes:author'
| 'admin:resource-nodes:manage'
| 'narrative-events:create'
| 'narrative-events:read'
@ -2961,24 +2948,6 @@ export interface Mission {
providedRoles?:
| {
roleName: string;
/**
* Shown to players under the role name: what the role does and what is expected of whoever fills it.
*/
description?: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
} | null;
/**
* If true, this mission cannot be executed without someone fulfilling this role.
*/
@ -2991,10 +2960,6 @@ export interface Mission {
* This role can only be fulfilled by someone of this rank or higher.
*/
minimumRank?: (number | null) | Rank;
/**
* How many members can hold this role. Extra sign-ups form a first-come, first-served waitlist that auto-promotes when a holder stops attending.
*/
slots?: number | null;
id?: string | null;
}[]
| null;
@ -3243,25 +3208,6 @@ export interface MissionAttendance {
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "mission-role-signups".
*/
export interface MissionRoleSignup {
id: number;
mission: number | Mission;
user: number | User;
/**
* Index into the mission's missionRoles.providedRoles array. A roleName snapshot is kept alongside in case the mission's role list is later edited.
*/
roleIndex: number;
/**
* Copy of the role name at sign-up time, for display if the role list changes.
*/
roleNameSnapshot?: string | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "shipments".
@ -5200,7 +5146,7 @@ export interface PluginAiInstruction {
*/
'field-type'?: ('text' | 'textarea' | 'upload' | 'richText') | null;
'relation-to'?: string | null;
'model-id'?: 'unsloth/gemma-4-26B-A4B-it-qat-GGUF' | null;
'model-id'?: 'unsloth-text' | null;
/**
* Please reload your collection after applying the changes
*/
@ -5220,7 +5166,7 @@ export interface PluginAiInstruction {
| null;
system?: string | null;
layout?: string | null;
'gemma-4-settings'?: {
'unsloth-text-settings'?: {
model?: string | null;
};
updatedAt: string;
@ -5660,24 +5606,6 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
missionRoleSignups?: {
/**
* Allow clients to find mission-role-signups.
*/
find?: boolean | null;
/**
* Allow clients to create mission-role-signups.
*/
create?: boolean | null;
/**
* Allow clients to update mission-role-signups.
*/
update?: boolean | null;
/**
* Allow clients to delete mission-role-signups.
*/
delete?: boolean | null;
};
campaigns?: {
/**
* Allow clients to find campaigns.
@ -6719,10 +6647,6 @@ export interface PayloadLockedDocument {
relationTo: 'mission-attendances';
value: number | MissionAttendance;
} | null)
| ({
relationTo: 'mission-role-signups';
value: number | MissionRoleSignup;
} | null)
| ({
relationTo: 'campaigns';
value: number | Campaign;
@ -7683,11 +7607,9 @@ export interface MissionsSelect<T extends boolean = true> {
| T
| {
roleName?: T;
description?: T;
missionCritical?: T;
requiredMos?: T;
minimumRank?: T;
slots?: T;
id?: T;
};
notes?: T;
@ -7777,18 +7699,6 @@ export interface MissionAttendancesSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "mission-role-signups_select".
*/
export interface MissionRoleSignupsSelect<T extends boolean = true> {
mission?: T;
user?: T;
roleIndex?: T;
roleNameSnapshot?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "campaigns_select".
@ -9281,7 +9191,7 @@ export interface PluginAiInstructionsSelect<T extends boolean = true> {
};
system?: T;
layout?: T;
'gemma-4-settings'?:
'unsloth-text-settings'?:
| T
| {
model?: T;
@ -9481,14 +9391,6 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
missionRoleSignups?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
campaigns?:
| T
| {

View file

@ -16,7 +16,6 @@ import { Ranks } from "@/collections/users/Ranks";
import { Profiles } from "@/collections/users/Profiles";
import { Missions } from "@/collections/intelligence/Missions";
import { MissionAttendances } from "@/collections/intelligence/MissionAttendances";
import { MissionRoleSignups } from "@/collections/intelligence/MissionRoleSignups";
import { Maps } from "@/collections/world/Maps";
import { MapRoads } from "@/collections/world/MapRoads";
import { MapZones } from "@/collections/world/MapZones";
@ -101,7 +100,7 @@ const unslothProvider = createOpenAI({
baseURL: process.env.UNSLOTH_URL || "https://uns.onyxsimple.com/v1",
});
const DEFAULT_MODEL = "unsloth/gemma-4-26B-A4B-it-qat-GGUF";
const DEFAULT_MODEL = "unsloth/gemma-4-E4B-it-qat-GGUF";
// AI Compose allowlist: the plugin's default init makes an LLM call per field
// to seed prompts. Returning false here skips a field (no instruction row, no
@ -199,15 +198,6 @@ function plainTextToLexicalJson(text: string): Record<string, unknown> {
};
}
// Gemma tends to answer schema-y prompts with fenced JSON blobs. The plain-text
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
// paragraphs, so strip any markdown code fences before using the output.
const stripCodeFences = (text: string): string =>
text
.replace(/^```[a-zA-Z]*\s*\n?/, "")
.replace(/\n?```\s*$/, "")
.trim();
async function generatePlainText(prompt: string, system: string, model: string): Promise<string> {
const baseUrl = process.env.UNSLOTH_URL || "https://uns.onyxsimple.com/v1";
const response = await fetch(`${baseUrl}/chat/completions`, {
@ -231,7 +221,7 @@ async function generatePlainText(prompt: string, system: string, model: string):
}
const result = await response.json();
return stripCodeFences(result.choices[0].message.content ?? "");
return result.choices[0].message.content;
}
const filename = fileURLToPath(import.meta.url);
@ -271,7 +261,6 @@ const collections = [
// Intel
Missions,
MissionAttendances,
MissionRoleSignups,
Campaigns,
Factions,
Technologies,
@ -568,8 +557,8 @@ export default buildConfig({
},
generationModels: [
{
id: "unsloth/gemma-4-26B-A4B-it-qat-GGUF",
name: "Gemma 4 26B A4B",
id: "unsloth-text",
name: "Unsloth",
fields: ["text", "textarea", "richText"],
handler: async (
prompt: string,
@ -585,11 +574,7 @@ export default buildConfig({
const model = options.model || DEFAULT_MODEL;
if (options.schema?.definitions) {
const text = await generatePlainText(
prompt,
`${options.system}\n\nOUTPUT RULES:\nRespond with plain prose paragraphs only. Do not output JSON, code fences, or schema definitions. Plain sentences and paragraphs are the entire expected output.`,
model,
);
const text = await generatePlainText(prompt, options.system, model);
const lexicalJson = plainTextToLexicalJson(text);
const ts = new ReadableStream({
start(controller) {
@ -641,11 +626,11 @@ export default buildConfig({
},
output: "text",
settings: {
name: "gemma-4-settings",
name: "unsloth-text-settings",
type: "group",
admin: {
condition(data) {
return data["model-id"] === "unsloth/gemma-4-26B-A4B-it-qat-GGUF";
return data["model-id"] === "unsloth-text";
},
},
fields: [
@ -656,7 +641,7 @@ export default buildConfig({
label: "Model",
},
],
label: "Gemma 4 Settings",
label: "Unsloth Settings",
},
},
],

View file

@ -185,16 +185,6 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "admin:mission-attendances:manage", label: "Manage Admin Page" },
],
},
{
group: "Mission Role Sign-Ups",
permissions: [
{ value: "mission-role-signups:create", label: "Create" },
{ value: "mission-role-signups:read", label: "Read" },
{ value: "mission-role-signups:update", label: "Update" },
{ value: "mission-role-signups:delete", label: "Delete" },
{ value: "admin:mission-role-signups:manage", label: "Manage Admin Page" },
],
},
{
group: "Campaigns",
permissions: [
@ -490,7 +480,6 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "maps:read", label: "Read" },
{ value: "maps:update", label: "Update" },
{ value: "maps:delete", label: "Delete" },
{ value: "maps:place", label: "Place Structures" },
{ value: "admin:maps:manage", label: "Manage Admin Page" },
],
},
@ -498,13 +487,10 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
group: "Map Features",
permissions: [
{ value: "map-roads:read", label: "Read Roads" },
{ value: "map-roads:author", label: "Author Roads" },
{ value: "admin:map-roads:manage", label: "Manage Roads Admin Page" },
{ value: "map-zones:read", label: "Read Zones" },
{ value: "map-zones:author", label: "Author Zones" },
{ value: "admin:map-zones:manage", label: "Manage Zones Admin Page" },
{ value: "resource-nodes:read", label: "Read Resource Nodes" },
{ value: "resource-nodes:author", label: "Author Resource Nodes" },
{ value: "admin:resource-nodes:manage", label: "Manage Resource Nodes Admin Page" },
],
},
@ -793,11 +779,6 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"mission-attendances:update",
"mission-attendances:delete",
"admin:mission-attendances:manage",
"mission-role-signups:create",
"mission-role-signups:read",
"mission-role-signups:update",
"mission-role-signups:delete",
"admin:mission-role-signups:manage",
"campaigns:create",
"campaigns:read",
"campaigns:update",
@ -938,16 +919,12 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"maps:read",
"maps:update",
"maps:delete",
"maps:place",
"admin:maps:manage",
"map-roads:read",
"map-roads:author",
"admin:map-roads:manage",
"map-zones:read",
"map-zones:author",
"admin:map-zones:manage",
"resource-nodes:read",
"resource-nodes:author",
"admin:resource-nodes:manage",
"narrative-events:create",
"narrative-events:read",

View file

@ -71,10 +71,6 @@ const ADMIN_PERMISSIONS: Permission[] = [
"form-submissions:read",
"structures:create",
"structures:update",
"maps:place",
"map-roads:author",
"map-zones:author",
"resource-nodes:author",
...ALL_COLLECTION_READS,
...ALL_ADMIN_PAGE_MANAGE,
]),

View file

@ -129,11 +129,6 @@ export const EventTypes = {
// Attendance
MissionAttendanceChange: "mission:attendance-change",
// Mission role sign-ups
MissionRoleSignup: "mission:role-signup",
MissionRoleWithdraw: "mission:role-withdraw",
MissionRolePromoted: "mission:role-promoted",
// Evaluations
EvaluationSubmit: "evaluation:submit",

View file

@ -40,7 +40,7 @@ describe("generic marker nodes (no resources)", () => {
data: {
name: `Generic Node Mapper ${Date.now()}`,
slug: `generic-mapper-${Date.now()}`,
permissions: ["resource-nodes:author"],
permissions: ["maps:create"],
},
overrideAccess: true,
depth: 0,

View file

@ -317,7 +317,7 @@ describe("Game Map System", () => {
data: {
name: `${RUN} logistics`,
slug: `${RUN}-logistics`,
permissions: ["shipments:create", "structures:read", "maps:place"],
permissions: ["shipments:create", "structures:read"],
},
overrideAccess: true,
depth: 0,
@ -356,16 +356,7 @@ describe("Game Map System", () => {
data: {
name: `${RUN} mapper`,
slug: `${RUN}-mapper`,
permissions: [
"maps:create",
"maps:update",
"maps:place",
"map-roads:read",
"map-roads:author",
"map-zones:author",
"resource-nodes:author",
"admin:map-roads:manage",
],
permissions: ["maps:create", "maps:update", "map-roads:read", "admin:map-roads:manage"],
},
overrideAccess: true,
depth: 0,
@ -1568,12 +1559,9 @@ describe("Game Map System", () => {
expect(await createAccess({ req: { payload, user: null } })).toBe(false);
});
it("gates map feature authoring behind per-tool permissions", async () => {
it("grants map feature writes to holders of maps:create", async () => {
const { hasPermission } = await import("@/utils/access-control/hasPermission");
expect(await hasPermission(payload, mapper, "map-roads:author")).toBe(true);
expect(await hasPermission(payload, mapper, "map-zones:author")).toBe(true);
expect(await hasPermission(payload, mapper, "resource-nodes:author")).toBe(true);
expect(await hasPermission(payload, mapper, "maps:place")).toBe(true);
expect(await hasPermission(payload, mapper, "maps:create")).toBe(true);
expect(await hasPermission(payload, mapper, "maps:delete")).toBe(false);
const payloadConfig = await config;
@ -1581,16 +1569,12 @@ describe("Game Map System", () => {
(collection) => collection.slug === "map-roads",
);
const createAccess = roadsConfig!.access?.create as unknown as (args: {
req: { payload: Payload; user: User | null };
req: { payload: Payload; user: User };
}) => Promise<boolean>;
expect(await createAccess({ req: { payload, user: mapper } })).toBe(true);
// A user holding maps:create but no author permission is denied at the
// collection layer too.
expect(await createAccess({ req: { payload, user: null } })).toBe(false);
});
it("edits an existing road when road authoring is granted and guards cross-map edits", async () => {
it("edits an existing road when maps:update is granted and guards cross-map edits", async () => {
authSpy.mockResolvedValue({ user: mapper });
const road = await makeRoad(mapA.id, [
[500, 500],

View file

@ -1,581 +0,0 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type {
Map as MissionMap,
Mission,
MissionRoleSignup,
Qualification,
Rank,
User,
} from "@/payload-types";
import {
diffPromotedUsers,
getMissionRoleSignupState,
getSlotHolders,
removeRoleSignup,
roleSignupGate,
roleSignupsClosedMessage,
signupForRole,
withdrawRoleSignup,
} from "@/lib/intelligence/roleSignups";
import { setMissionAttendance } from "@/lib/attendance";
let payload: Payload;
const RUN = `mrs-${Date.now().toString(36)}`;
/**
* User deletion trips FK constraints unless the hook-provisioned personal bank
* account and profile are removed first, and event/notification rows must go
* before the users they reference.
*/
const deleteUserWithRelations = async (pg: Payload, id: number): Promise<void> => {
const accounts = await pg
.find({
collection: "bank-accounts",
where: { ownerUser: { equals: id } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const account of accounts?.docs ?? []) {
await pg
.delete({ collection: "bank-accounts", id: account.id, overrideAccess: true })
.catch(() => {});
}
const profiles = await pg
.find({
collection: "profiles",
where: { user: { equals: id } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const profile of profiles?.docs ?? []) {
await pg
.delete({ collection: "profiles", id: profile.id, overrideAccess: true })
.catch(() => {});
}
await pg.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
};
const deleteMissionWithRelations = async (pg: Payload, missionId: number): Promise<void> => {
for (const collection of ["mission-role-signups", "mission-attendances"] as const) {
const docs = await pg
.find({
collection,
where: { mission: { equals: missionId } },
limit: 500,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const doc of docs?.docs ?? []) {
await pg.delete({ collection, id: doc.id, overrideAccess: true }).catch(() => {});
}
}
await pg.delete({ collection: "missions", id: missionId, overrideAccess: true }).catch(() => {});
};
describe("Mission role sign-ups", () => {
let mapId: number;
let missionId: number;
let queueMissionId: number;
let switchMissionId: number;
let bypassMissionId: number;
let pastMissionId: number;
let cancelledMissionId: number;
const missionIds: number[] = [];
const rankIds: number[] = [];
const qualIds: number[] = [];
const userIds: number[] = [];
let pvt: Rank;
let cpl: Rank;
let sgt: Rank;
let medic: Qualification;
let memberA: User; // Pvt with the Medic MOS
let memberB: User; // Pvt with no qualifications
let memberC: User; // Cpl, no qualifications
let memberD: User; // Sgt with the Medic MOS
let adminUser: User;
const makeMission = async (
label: string,
options: {
status?: Mission["ownershipAndStatus"]["status"];
start?: Date;
roles: Record<string, unknown>[];
},
): Promise<Mission> => {
const providedRoles = options.roles as NonNullable<Mission["missionRoles"]>["providedRoles"];
const mission = (await payload.create({
collection: "missions",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Role sign-up test mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
startDateTime: (
options.start ?? new Date(Date.now() + 2 * 24 * 60 * 60 * 1000)
).toISOString(),
estimatedDuration: 60,
},
ownershipAndStatus: {
authors: [adminUser.id],
status: options.status ?? "Scheduled",
visibility: "unit",
},
briefing: [],
gameDetails: {
serverDetails: {
serverIp: "127.0.0.1",
serverPort: 2302,
},
},
missionRoles: {
maxPlayers: 32,
providedRoles,
},
},
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id);
return mission;
};
const makeUser = async (username: string, roles: User["roles"] = ["user"]): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: "ROLE SIGNUP TEST",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles,
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const setProfile = async (userId: number, rankId: number, qualificationIds: number[]) => {
const profiles = (await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
})) as unknown as { docs: Array<{ id: number }> };
await payload.update({
collection: "profiles",
id: profiles.docs[0].id,
data: { rank: rankId, progression: { qualifications: qualificationIds } },
overrideAccess: true,
depth: 0,
});
};
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;
// Self-contained 3-rank ladder: Pvt < Cpl < Sgt.
for (const [name, abbreviation] of [
["Pvt", "pvt"],
["Cpl", "cpl"],
["Sgt", "sgt"],
] as const) {
const rank = (await payload.create({
collection: "ranks",
data: {
name: `${RUN} ${name}`,
abbreviation: `${RUN}-${abbreviation}`,
description: `${RUN} test rank`,
},
overrideAccess: true,
depth: 0,
})) as unknown as Rank;
rankIds.push(rank.id);
if (name === "Pvt") pvt = rank;
if (name === "Cpl") cpl = rank;
if (name === "Sgt") sgt = rank;
}
medic = (await payload.create({
collection: "qualifications",
data: { name: `${RUN} Advanced Medic` },
overrideAccess: true,
depth: 0,
})) as unknown as Qualification;
qualIds.push(medic.id);
adminUser = await makeUser(`${RUN}-admin`, ["admin"]);
memberA = await makeUser(`${RUN}-a`);
memberB = await makeUser(`${RUN}-b`);
memberC = await makeUser(`${RUN}-c`);
memberD = await makeUser(`${RUN}-d`);
await setProfile(memberA.id, pvt.id, [medic.id]);
await setProfile(memberB.id, pvt.id, []);
await setProfile(memberC.id, cpl.id, []);
await setProfile(memberD.id, sgt.id, [medic.id]);
const main = await makeMission("Main", {
roles: [
{ roleName: "Squad Leader", slots: 1, minimumRank: cpl.id },
{ roleName: "Medic", slots: 1, requiredMos: [medic.id] },
{ roleName: "Rifleman", slots: 2 },
],
});
missionId = main.id;
const queue = await makeMission("Queue", {
roles: [{ roleName: "Rifleman", slots: 2 }],
});
queueMissionId = queue.id;
const switchMission = await makeMission("Switch", {
roles: [
{ roleName: "Medic", slots: 1, requiredMos: [medic.id] },
{ roleName: "Rifleman", slots: 2 },
],
});
switchMissionId = switchMission.id;
const bypass = await makeMission("Bypass", {
roles: [{ roleName: "Squad Leader", slots: 1, minimumRank: sgt.id }],
});
bypassMissionId = bypass.id;
const past = await makeMission("Past", {
start: new Date(Date.now() - 24 * 60 * 60 * 1000),
roles: [{ roleName: "Rifleman", slots: 2 }],
});
pastMissionId = past.id;
const cancelled = await makeMission("Cancelled", {
status: "Cancelled",
roles: [{ roleName: "Rifleman", slots: 2 }],
});
cancelledMissionId = cancelled.id;
});
afterAll(async () => {
for (const id of missionIds) {
await deleteMissionWithRelations(payload, id);
}
// Events and notifications reference users; remove them before the users.
for (const collection of ["game-event-logs", "user-notifications"] as const) {
const docs = await payload
.find({
collection,
where: { id: { exists: true } },
limit: 500,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const doc of docs?.docs ?? []) {
const event = doc as unknown as {
actor?: number | { id: number } | null;
user?: number | { id: number } | null;
};
const ref = event.actor ?? event.user;
const refId = typeof ref === "object" ? ref?.id : ref;
if (refId != null && userIds.includes(refId)) {
await payload.delete({ collection, id: doc.id, overrideAccess: true }).catch(() => {});
}
}
}
for (const id of userIds) {
await deleteUserWithRelations(payload, id);
}
for (const id of qualIds) {
await payload
.delete({ collection: "qualifications", id, overrideAccess: true })
.catch(() => {});
}
for (const id of rankIds) {
await payload.delete({ collection: "ranks", id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
});
it("gates sign-ups by minimum rank and required MOS", async () => {
// B is a Pvt: the Squad Leader role requires Cpl or higher.
await expect(
signupForRole(payload, { missionId, userId: memberB.id, roleIndex: 0 }),
).rejects.toThrow(/Requires the rank of/);
// C is a Cpl: passes the rank gate and immediately holds the slot once RSVPed.
await setMissionAttendance(payload, { missionId, userId: memberC.id, response: "yes" });
await signupForRole(payload, { missionId, userId: memberC.id, roleIndex: 0 });
const afterC = await getMissionRoleSignupState(payload, missionId);
expect(afterC.roles[0].filled).toBe(1);
expect(afterC.roles[0].entries[0].holding).toBe(true);
// B lacks the Medic MOS.
await expect(
signupForRole(payload, { missionId, userId: memberB.id, roleIndex: 1 }),
).rejects.toThrow(/Requires qualification:/);
// A is a Pvt with the Medic MOS: the Medic role has no rank floor.
await signupForRole(payload, { missionId, userId: memberA.id, roleIndex: 1 });
const afterA = await getMissionRoleSignupState(payload, missionId);
expect(afterA.roles[1].filled).toBe(0); // A has not RSVPed yet, so no slot held
expect(afterA.roles[1].entries[0].holding).toBe(false);
// Re-signing for the same role is a no-op (one signup per user per mission).
await signupForRole(payload, { missionId, userId: memberA.id, roleIndex: 1 });
const signups = await payload.find({
collection: "mission-role-signups",
where: { mission: { equals: missionId } },
limit: 100,
depth: 0,
overrideAccess: true,
});
expect(signups.docs).toHaveLength(2);
// A role index past the end of the mission's role list is refused.
await expect(
signupForRole(payload, { missionId, userId: memberA.id, roleIndex: 99 }),
).rejects.toThrow(/no longer exists/);
});
it("queues by first-come-first-served and auto-promotes on RSVP drop", async () => {
await setMissionAttendance(payload, {
missionId: queueMissionId,
userId: memberA.id,
response: "yes",
});
await setMissionAttendance(payload, {
missionId: queueMissionId,
userId: memberB.id,
response: "yes",
});
await setMissionAttendance(payload, {
missionId: queueMissionId,
userId: memberC.id,
response: "yes",
});
await signupForRole(payload, { missionId: queueMissionId, userId: memberA.id, roleIndex: 0 });
await signupForRole(payload, { missionId: queueMissionId, userId: memberB.id, roleIndex: 0 });
await signupForRole(payload, { missionId: queueMissionId, userId: memberC.id, roleIndex: 0 });
let state = await getMissionRoleSignupState(payload, queueMissionId);
expect(state.roles[0].filled).toBe(2);
expect(state.roles[0].entries.map((e) => [e.position, e.holding])).toEqual([
[1, true],
[2, true],
[3, false],
]);
expect(state.roles[0].slots).toBe(2);
// A (slot holder) RSVPs No: the first waitlisted member takes over.
await setMissionAttendance(payload, {
missionId: queueMissionId,
userId: memberA.id,
response: "no",
});
state = await getMissionRoleSignupState(payload, queueMissionId);
expect(state.roles[0].filled).toBe(2);
expect(state.roles[0].entries.map((e) => [e.holding])).toEqual([[false], [true], [true]]);
// The promoted member is notified and the promotion is logged.
const notifications = await payload.find({
collection: "user-notifications",
where: { user: { equals: memberC.id } },
limit: 100,
depth: 0,
overrideAccess: true,
});
const promotedNotes = notifications.docs.filter(
(n) => (n as unknown as { type: string }).type === "mission:role-promoted",
);
expect(promotedNotes).toHaveLength(1);
expect(promotedNotes[0]).toMatchObject({
title: "Slot granted: Rifleman",
link: `/intelligence/missions/${queueMissionId}`,
});
const events = await payload.find({
collection: "game-event-logs",
where: { type: { equals: "mission:role-promoted" } },
limit: 100,
depth: 0,
overrideAccess: true,
});
const promotionEvent = events.docs.find(
(e) =>
(e as unknown as { targetId: number }).targetId === queueMissionId &&
JSON.stringify((e as unknown as { data?: { userId?: number } }).data ?? {}).includes(
`"userId":${memberC.id}`,
),
);
expect(promotionEvent).toBeDefined();
});
it("promotes on withdrawal and refuses a second withdrawal", async () => {
// D joins the (full) Rifleman queue: two holders, two waitlisted.
await setMissionAttendance(payload, {
missionId: queueMissionId,
userId: memberD.id,
response: "yes",
});
await signupForRole(payload, { missionId: queueMissionId, userId: memberD.id, roleIndex: 0 });
let state = await getMissionRoleSignupState(payload, queueMissionId);
expect(state.roles[0].entries).toHaveLength(4);
// B withdraws: C keeps a slot and D (next committed member) takes B's.
await withdrawRoleSignup(payload, { missionId: queueMissionId, userId: memberB.id });
state = await getMissionRoleSignupState(payload, queueMissionId);
expect(state.roles[0].filled).toBe(2);
expect(state.roles[0].entries.find((e) => e.userId === memberD.id)?.holding).toBe(true);
expect(state.roles[0].entries.find((e) => e.userId === memberB.id)).toBeUndefined();
await expect(
withdrawRoleSignup(payload, { missionId: queueMissionId, userId: memberB.id }),
).rejects.toThrow(/not signed up/);
});
it("moves the signup when switching roles and enforces requirements on the target", async () => {
// A holds a Rifleman slot on the switch mission, then moves to Medic.
await setMissionAttendance(payload, {
missionId: switchMissionId,
userId: memberA.id,
response: "yes",
});
await signupForRole(payload, { missionId: switchMissionId, userId: memberA.id, roleIndex: 1 });
let state = await getMissionRoleSignupState(payload, switchMissionId, memberA.id);
expect(state.roles[1].filled).toBe(1);
expect(state.mySignup).toMatchObject({ roleIndex: 1, holding: true });
// Switching to Medic moves the one live signup (no second row).
await signupForRole(payload, { missionId: switchMissionId, userId: memberA.id, roleIndex: 0 });
state = await getMissionRoleSignupState(payload, switchMissionId, memberA.id);
expect(state.roles[1].entries).toHaveLength(0);
expect(state.roles[0].filled).toBe(1);
expect(state.mySignup).toMatchObject({ roleIndex: 0, holding: true });
// B (Pvt, no MOS) and C (Cpl, no MOS) both fail the Medic MOS gate.
await expect(
signupForRole(payload, { missionId: switchMissionId, userId: memberB.id, roleIndex: 0 }),
).rejects.toThrow(/Requires qualification:/);
await expect(
signupForRole(payload, { missionId: switchMissionId, userId: memberC.id, roleIndex: 0 }),
).rejects.toThrow(/Requires qualification:/);
});
it("lets staff bypass eligibility and remove sign-ups", async () => {
// Admin signs up for the Sgt-floored role despite holding no test rank.
await setMissionAttendance(payload, {
missionId: bypassMissionId,
userId: adminUser.id,
response: "yes",
});
await signupForRole(payload, {
missionId: bypassMissionId,
userId: adminUser.id,
roleIndex: 0,
bypassEligibility: true,
});
const state = await getMissionRoleSignupState(payload, bypassMissionId, adminUser.id);
expect(state.roles[0].filled).toBe(1);
expect(state.mySignup).toMatchObject({ roleIndex: 0, holding: true });
// Staff removal reconciles slots and is marked in the event log.
const signupId = state.roles[0].entries[0].signupId;
await removeRoleSignup(payload, {
missionId: bypassMissionId,
signupId,
actorId: adminUser.id,
});
const after = await getMissionRoleSignupState(payload, bypassMissionId, adminUser.id);
expect(after.roles[0].entries).toHaveLength(0);
expect(after.mySignup).toBeNull();
const withdrawEvents = await payload.find({
collection: "game-event-logs",
where: { type: { equals: "mission:role-withdraw" } },
limit: 100,
depth: 0,
overrideAccess: true,
});
const removal = withdrawEvents.docs.find(
(e) =>
(e as unknown as { targetId: number }).targetId === bypassMissionId &&
(e as unknown as { data?: { removedByStaff?: boolean } }).data?.removedByStaff === true,
);
expect(removal).toBeDefined();
});
it("closes sign-ups for past and cancelled missions", async () => {
const pastGate = roleSignupGate({
ownershipAndStatus: { status: "Scheduled" },
classification: { startDateTime: new Date(Date.now() - 60_000).toISOString() },
});
expect(pastGate.open).toBe(false);
expect(pastGate.reason).toBe(roleSignupsClosedMessage);
await expect(
signupForRole(payload, { missionId: pastMissionId, userId: memberA.id, roleIndex: 0 }),
).rejects.toThrow(roleSignupsClosedMessage);
const cancelledGate = roleSignupGate({
ownershipAndStatus: { status: "Cancelled" },
classification: { startDateTime: new Date(Date.now() + 60_000).toISOString() },
});
expect(cancelledGate.open).toBe(false);
expect(cancelledGate.reason).toBe("This operation was cancelled.");
await expect(
signupForRole(payload, { missionId: cancelledMissionId, userId: memberA.id, roleIndex: 0 }),
).rejects.toThrow("This operation was cancelled.");
});
it("derives slot holders as a userId -> roleIndex map and diffs promotions", async () => {
const holders = await getSlotHolders(payload, missionId);
// C holds Squad Leader (RSVPed yes). A RSVPed no on the main mission, so no
// Medic slot is held there.
expect(holders.get(memberC.id)).toBe(0);
expect(holders.has(memberA.id)).toBe(false);
// A RSVPs yes: they now hold the Medic slot.
await setMissionAttendance(payload, { missionId, userId: memberA.id, response: "yes" });
const holdersAfter = await getSlotHolders(payload, missionId);
expect(holdersAfter.get(memberA.id)).toBe(1);
const promoted = diffPromotedUsers(holders, holdersAfter);
expect(promoted).toEqual([{ userId: memberA.id, roleIndex: 1 }]);
});
});