Compare commits
No commits in common. "03c8794026271d8f24240d25109e2c212353010e" and "3d93ecafb3e0a080a40bf4ae6b978e929691fab0" have entirely different histories.
03c8794026
...
3d93ecafb3
61 changed files with 278 additions and 230521 deletions
12
AGENTS.md
12
AGENTS.md
|
|
@ -124,14 +124,12 @@ Access control helpers live in `src/utils/access-control/` (isRole, hasRoles). F
|
|||
|
||||
`src/collections/game/GameEventLogs.ts` — `game-event-logs` collection.
|
||||
|
||||
- **Schema**: `system` (boolean, default `true` — system-generated vs GM/narrative), `timestamp`, `type` (text/indexed), `message` (human-readable), `actor` (→ users), `structure` (→ game-structures), `targetCollection` (select — pick from known collections), `targetId` (number, polymorphic ref), `data` (JSON blob), `visibility` (select `public` default | `restricted`, indexed), `requiredPermissions` (select hasMany from the permission registry; any-of gate shown only when restricted).
|
||||
- **Access**: read is visibility-filtered: every logged-in user sees public events; restricted events additionally require one of their `requiredPermissions`, event-log staff (`game-event-logs:update`), superuser status, or being the actor (you always see your own events). Create: any logged-in user. Update restricted to admins/developers. Delete restricted to developers. The admin panel keeps its boolean gate (`scopedAdminPageAccess`), so event-log staff see everything there.
|
||||
- **Visibility policies**: `src/utils/event-log/visibility.ts` maps event TYPES to defaults (`EVENT_VISIBILITY_POLICIES`); `emitGameEvent` stamps documents via `resolveEventVisibility(type, override)`. Restricted today: `npc:dialogue` (gated `npc-dialogues:read` / `player-flags:read`) and `flag:set` (gated `player-flags:read`). Everything else defaults public. Callers may pass `visibility` / `requiredPermissions` per emit.
|
||||
- **Local API gotcha**: `payload.find` on `game-event-logs` defaults to `overrideAccess: true` and bypasses the filter. Consumers that must respect visibility pass `user` + `overrideAccess: false` (the dashboard RecentEvents query in `src/app/(frontend)/page.tsx` does this). REST consumers (`/events` page, `EventLedger`) are filtered automatically.
|
||||
- **Emit**: `emitGameEvent(payload, { type, message, actor?, structure?, targetCollection?, targetId?, data?, visibility?, requiredPermissions? })` in `src/utils/event-log/emit.ts`. Silently catches errors (fire-and-forget). Always sets `system: true`; stamps visibility from the policy map.
|
||||
- **Schema**: `system` (boolean, default `true` — system-generated vs GM/narrative), `timestamp`, `type` (text/indexed), `message` (human-readable), `actor` (→ users), `structure` (→ game-structures), `targetCollection` (select — pick from known collections), `targetId` (number, polymorphic ref), `data` (JSON blob).
|
||||
- **Access**: any logged-in user can read/create. Update restricted to admins/developers. Delete restricted to developers.
|
||||
- **Emit**: `emitGameEvent(payload, { type, message, actor?, structure?, targetCollection?, targetId?, data? })` in `src/utils/event-log/emit.ts`. Silently catches errors (fire-and-forget). Always sets `system: true`.
|
||||
- **Types**: `EventTypes` constants in `src/utils/event-log/eventTypes.ts` — add new event categories there without touching the collection. Using these constants gives TypeScript narrowing on the `type` field.
|
||||
- **Wiring**: Server actions in `actions.ts` emit events after successful mutations. `GameStructures` afterChange hook catches admin-panel storage edits. `Structures` beforeChange hook emits `structure:resize`. `PlayerFlags` afterChange/afterDelete hooks emit restricted `flag:set` audit events for every flag write (admin-panel edits and dialogue effects alike).
|
||||
- **targetCollection options**: `game-structures`, `structures`, `resources`, `assets`, `vehicles`, `game-vehicles`, `game-npcs`, `npc-staffing`, `factions`, `missions`, `campaigns`, `users`, `technologies`, `maps`, `shipments`, `bank-accounts`, `bank-transactions`, `ledger-entries`, `market-listings`, `market-negotiations`, `locker-storages`, `loadouts`, `evaluations`, `tickets`, `wiki-pages`, `wiki-revisions`, `wiki-templates`, `game-servers`, `assignment-transfers`, `player-flags`. If a new collection is added that should be a valid target, add an option here.
|
||||
- **Wiring**: Server actions in `actions.ts` emit events after successful mutations. `GameStructures` afterChange hook catches admin-panel storage edits. `Structures` beforeChange hook emits `structure:resize`.
|
||||
- **targetCollection options**: `game-structures`, `structures`, `resources`, `assets`, `vehicles`, `game-vehicles`, `game-npcs`, `npc-staffing`, `factions`, `missions`, `campaigns`, `users`, `technologies`, `maps`, `shipments`, `bank-accounts`, `bank-transactions`, `ledger-entries`, `market-listings`, `market-negotiations`, `locker-storages`, `loadouts`, `evaluations`, `tickets`, `wiki-pages`, `wiki-revisions`, `wiki-templates`, `game-servers`, `assignment-transfers`. If a new collection is added that should be a valid target, add an option here.
|
||||
- **Narrative events**: admins/developers can create entries manually in the Payload admin panel with `system: false` for GM-written narrative events. These are visually distinct in the UI (amber accent, book icon).
|
||||
|
||||
### UI
|
||||
|
|
|
|||
47
CHANGELOG.md
47
CHANGELOG.md
|
|
@ -1,26 +1,5 @@
|
|||
# Changelog
|
||||
|
||||
# v0.6.0
|
||||
|
||||
NPC conversations get a lot deeper this time: they remember what you have done, mark what you have not seen yet, and some of them only open once you have earned them.
|
||||
|
||||
### Features
|
||||
|
||||
- **Conversations that remember you.** An NPC can now quote your current situation back at you, with specific details from your status woven right into their sentences. Some statuses take hold after a delay or fade on their own, and dialogue shows a live countdown when one is close.
|
||||
|
||||
- **Storylines you unlock.** Contacts offer the conversation that matches where you are in the story. New paths open once you meet their conditions, and choices you do not qualify for show up locked with a hint about what you are missing instead of silently vanishing.
|
||||
|
||||
- **Fresh content, marked.** Converse buttons and reply options carry a NEW badge while there is something you have not read, so you always know who has something new to say.
|
||||
|
||||
- **A better read.** Conversations can now include images and richer text styling, from colored emphasis to bold within color. Hover any reply to preview details before committing, and links open in a popup so your place in the conversation survives the detour.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Contact conversations no longer break their layout on phones: the Converse button sits where it should and the dialog keeps its margins.
|
||||
- The NEW badge stays put when a conversation is edited without changing its content.
|
||||
|
||||
---
|
||||
|
||||
# v0.5.2
|
||||
|
||||
The dialogue flow editor gets a full authoring pass, and connection lines on both the dialogue canvas and the tech tree learn to route around cards instead of through them.
|
||||
|
|
@ -37,32 +16,6 @@ The dialogue flow editor gets a full authoring pass, and connection lines on bot
|
|||
|
||||
---
|
||||
|
||||
# v0.5.1
|
||||
|
||||
Conversations can now react to what you and the rest of the unit have been up to.
|
||||
|
||||
### Features
|
||||
|
||||
- **Unit-wide story developments.** Trackable events that happen across the whole unit are weaved into what contacts say to you. An op everyone took part in, a faction move, a base that fell: some contacts will know about it, and the conversation you get afterwards may be different because of it.
|
||||
|
||||
---
|
||||
|
||||
# v0.5.0
|
||||
|
||||
A big one this time: NPCs talk back. Head over to the contacts directory, find someone who is open to a chat, and see what they have to say.
|
||||
|
||||
### Features
|
||||
|
||||
- **NPC conversations.** Some contacts now carry a Converse button on their profile. The NPC types out its lines live, and when a decision comes up you pick your reply. What you have done shapes what they say: options appear or drop out based on your history, and a few choices only come up once per conversation. Watch for lines that come through in color.
|
||||
|
||||
- **Contact profiles.** Profiles now show each contact's level and description, plus a current activity line that shifts as time passes, so you can see what someone is up to before you reach out.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed status chips rendering too tall on contact cards.
|
||||
|
||||
---
|
||||
|
||||
# v0.4.1
|
||||
|
||||
NPCs get portraits and bios, your limited arsenal now syncs with in-game, and the maps pick up an Arma-style grid.
|
||||
|
|
|
|||
|
|
@ -5,11 +5,6 @@ import packageJson from "./package.json" with { type: "json" };
|
|||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
// Next 16 blocks dev-mode resources (HMR, chunks, fonts) for any Host header
|
||||
// not listed here. Without this, loading the dev server from a LAN IP (e.g. a
|
||||
// phone on http://192.168.1.2:3000) serves HTML whose JS never hydrates, so
|
||||
// forms fall back to native GET submits (login "resets" with no request).
|
||||
allowedDevOrigins: ["192.168.1.2", "192.168.1.*"],
|
||||
// Your Next.js config here
|
||||
env: {
|
||||
version: packageJson.version,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.6.0",
|
||||
"version": "0.5.2",
|
||||
"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",
|
||||
|
|
|
|||
|
|
@ -39,8 +39,7 @@ export default async function TicketPage({ params }: TicketPageProps) {
|
|||
})
|
||||
.catch(() => null);
|
||||
|
||||
// Archived tickets are hidden from the front-end for everyone, staff included.
|
||||
if (!ticket || (ticket as unknown as Ticket).archived) {
|
||||
if (!ticket) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import config from "@payload-config";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { getPayload } from "payload";
|
||||
|
|
@ -70,9 +69,7 @@ async function getTicketOrThrow(
|
|||
const ticket = (await payload
|
||||
.findByID({ collection: "tickets", id: ticketId, depth: 0, overrideAccess: true })
|
||||
.catch(() => null)) as unknown as Ticket | null;
|
||||
// Archived tickets are invisible to the front-end; stale links behave as
|
||||
// if the ticket never existed.
|
||||
if (!ticket || ticket.archived) throw new Error("Ticket not found.");
|
||||
if (!ticket) throw new Error("Ticket not found.");
|
||||
return ticket;
|
||||
}
|
||||
|
||||
|
|
@ -404,48 +401,3 @@ export async function assignTicket(
|
|||
: { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
export async function archiveTicket(ticketId: number): Promise<ActionResult> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
const userId = user.id as number;
|
||||
|
||||
if (!(await hasPermission(payload, user, "tickets:staff"))) {
|
||||
throw new Error("Only staff can archive tickets.");
|
||||
}
|
||||
|
||||
// getTicketOrThrow rejects archived tickets, so this only ever archives
|
||||
// a visible ticket.
|
||||
const ticket = await getTicketOrThrow(payload, ticketId);
|
||||
|
||||
await payload.update({
|
||||
collection: "tickets",
|
||||
id: ticketId,
|
||||
data: { archived: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
|
||||
// No notifications: the ticket is hidden from every front-end surface,
|
||||
// so there is no link target to point anyone at. Un-archiving happens in
|
||||
// the admin panel only.
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.TicketArchive,
|
||||
message: `Ticket #${ticketId} archived: ${ticket.title}`,
|
||||
actor: userId,
|
||||
targetCollection: "tickets",
|
||||
targetId: ticketId,
|
||||
});
|
||||
|
||||
// The client navigates to the list after archiving; make sure the
|
||||
// server-rendered queue is refetched without the archived ticket.
|
||||
revalidatePath("/helpdesk");
|
||||
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import { TicketsView } from "@/components/frontend/helpdesk/TicketsView";
|
|||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { LifeBuoyIcon } from "lucide-react";
|
||||
import { getTicketVoteSummaries } from "@/lib/tickets/voteState";
|
||||
import { NON_ARCHIVED_WHERE } from "@/lib/tickets/ticketMeta";
|
||||
|
||||
export const metadata = {
|
||||
title: "Helpdesk: Polaris Task Force",
|
||||
|
|
@ -49,7 +48,6 @@ export default async function HelpdeskPage() {
|
|||
|
||||
const ticketsRes = await payload.find({
|
||||
collection: "tickets",
|
||||
where: NON_ARCHIVED_WHERE,
|
||||
sort: "-updatedAt",
|
||||
limit: 200,
|
||||
depth: 2,
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { resolveLevel } from "@/utils/xp/resolveLevel";
|
|||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { canViewIntelligence } from "@/utils/access-control/canViewIntelligence";
|
||||
import { getCurrencyConfig } from "@/lib/banking";
|
||||
import { CLOSING_STATUSES, NON_ARCHIVED_WHERE } from "@/lib/tickets/ticketMeta";
|
||||
import { CLOSING_STATUSES } from "@/lib/tickets/ticketMeta";
|
||||
import { ProfileSummary } from "@/components/frontend/dashboard/ProfileSummary";
|
||||
import { MissionBriefing } from "@/components/frontend/dashboard/MissionBriefing";
|
||||
import { RecentEvents } from "@/components/frontend/dashboard/RecentEvents";
|
||||
|
|
@ -160,16 +160,12 @@ export default async function HomePage() {
|
|||
coverImage: m.coverImage,
|
||||
}));
|
||||
|
||||
// Fetch recent events. Runs as the viewer with access control applied so
|
||||
// restricted events (dialogue effects, flag changes) stay hidden from
|
||||
// members who lack the required permissions.
|
||||
// Fetch recent events
|
||||
const eventsRes = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
sort: "-timestamp",
|
||||
limit: 8,
|
||||
depth: 1,
|
||||
user,
|
||||
overrideAccess: false,
|
||||
});
|
||||
|
||||
const events = eventsRes.docs.map((e) => ({
|
||||
|
|
@ -258,7 +254,7 @@ export default async function HomePage() {
|
|||
payload
|
||||
.find({
|
||||
collection: "tickets",
|
||||
where: { and: [{ reporter: { equals: userId } }, NON_ARCHIVED_WHERE] },
|
||||
where: { reporter: { equals: userId } },
|
||||
sort: "-updatedAt",
|
||||
limit: 10,
|
||||
depth: 0,
|
||||
|
|
|
|||
|
|
@ -7,11 +7,8 @@ import type { User } from "@/payload-types";
|
|||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { notifyUser } from "@/lib/notifications";
|
||||
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
|
||||
import type {
|
||||
ChoiceGate,
|
||||
DialogueCondition,
|
||||
DialogueFlagOp,
|
||||
FlowData,
|
||||
NpcDialogueEffect,
|
||||
|
|
@ -127,15 +124,7 @@ async function runEffect(
|
|||
if (!key) break;
|
||||
const op: DialogueFlagOp = effect.flagOp ?? "set_true";
|
||||
const amount = effect.flagAmount ?? 0;
|
||||
await applyFlagEffect(
|
||||
payload,
|
||||
userId,
|
||||
key,
|
||||
op,
|
||||
amount,
|
||||
effect.flagText,
|
||||
effect.flagDelayMinutes,
|
||||
);
|
||||
await applyFlagEffect(payload, userId, key, op, amount);
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `Conversation set flag "${key}" (${op}).`,
|
||||
|
|
@ -149,22 +138,65 @@ async function runEffect(
|
|||
}
|
||||
}
|
||||
|
||||
/** Create-or-update a player flag according to the effect's write mode. A
|
||||
* positive `delayMinutes` stamps the flag with a future `activatesAt`, so it
|
||||
* reads as false until then (conditions fail, countdowns tick toward it). */
|
||||
/**
|
||||
* Effective value of a flag: player-specific entry takes priority; if absent,
|
||||
* fall back to the global entry (user is null). Missing flags read false / 0.
|
||||
*/
|
||||
async function readFlag(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
key: string,
|
||||
): Promise<{ bool: boolean; num: number }> {
|
||||
// Player-specific flag (priority).
|
||||
const playerRes = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: {
|
||||
user: { equals: userId },
|
||||
key: { equals: key },
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const playerDoc = playerRes.docs[0];
|
||||
if (playerDoc) {
|
||||
if (playerDoc.flagType === "number") {
|
||||
const num = playerDoc.numberValue ?? 0;
|
||||
return { bool: num !== 0, num };
|
||||
}
|
||||
const bool = playerDoc.boolValue === true;
|
||||
return { bool, num: bool ? 1 : 0 };
|
||||
}
|
||||
|
||||
// Global fallback (user is null).
|
||||
const globalRes = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: {
|
||||
user: { equals: null },
|
||||
key: { equals: key },
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const globalDoc = globalRes.docs[0];
|
||||
if (!globalDoc) return { bool: false, num: 0 };
|
||||
if (globalDoc.flagType === "number") {
|
||||
const num = globalDoc.numberValue ?? 0;
|
||||
return { bool: num !== 0, num };
|
||||
}
|
||||
const bool = globalDoc.boolValue === true;
|
||||
return { bool, num: bool ? 1 : 0 };
|
||||
}
|
||||
|
||||
/** Create-or-update a player flag according to the effect's write mode. */
|
||||
async function applyFlagEffect(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
key: string,
|
||||
op: DialogueFlagOp,
|
||||
amount: number,
|
||||
effectText?: string,
|
||||
delayMinutes?: number,
|
||||
): Promise<void> {
|
||||
const activatesAt =
|
||||
delayMinutes && delayMinutes > 0
|
||||
? new Date(Date.now() + delayMinutes * 60_000).toISOString()
|
||||
: null;
|
||||
const existing = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: {
|
||||
|
|
@ -183,13 +215,13 @@ async function applyFlagEffect(
|
|||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "boolean", boolValue, activatesAt },
|
||||
data: { flagType: "boolean", boolValue },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "boolean", boolValue, activatesAt },
|
||||
data: { user: userId, key, flagType: "boolean", boolValue },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
|
|
@ -201,32 +233,13 @@ async function applyFlagEffect(
|
|||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "number", numberValue: amount, activatesAt },
|
||||
data: { flagType: "number", numberValue: amount },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "number", numberValue: amount, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (op === "set_text") {
|
||||
const textValue = effectText ?? "";
|
||||
if (doc) {
|
||||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "text", textValue, activatesAt },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "text", textValue, activatesAt },
|
||||
data: { user: userId, key, flagType: "number", numberValue: amount },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
|
|
@ -246,13 +259,13 @@ async function applyFlagEffect(
|
|||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: doc.id,
|
||||
data: { flagType: "number", numberValue, activatesAt },
|
||||
data: { flagType: "number", numberValue },
|
||||
overrideAccess: true,
|
||||
});
|
||||
} else {
|
||||
await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: userId, key, flagType: "number", numberValue, activatesAt },
|
||||
data: { user: userId, key, flagType: "number", numberValue },
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
|
|
@ -298,16 +311,15 @@ export async function evaluateNpcDialogueCondition(
|
|||
|
||||
/**
|
||||
* Evaluate every choice's visibility gate for a `choice` node in one round
|
||||
* trip. Ungated choices always pass; gated ones report whether the reading
|
||||
* user's flags satisfy their condition and whether a failing choice should
|
||||
* still render locked (with its authored hint) instead of hiding. The node is
|
||||
* looked up server-side from the stored flowchart, so clients never see gate
|
||||
* config for conversations an admin has not authored.
|
||||
* trip. Ungated choices are always visible; gated ones appear only while the
|
||||
* reading user's flags satisfy their condition. The node is looked up
|
||||
* server-side from the stored flowchart, so clients never see gate config
|
||||
* for conversations an admin has not authored.
|
||||
*/
|
||||
export async function evaluateNpcDialogueChoices(
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult<ChoiceGate[]>> {
|
||||
): Promise<ActionResult<boolean[]>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
|
|
@ -325,17 +337,15 @@ export async function evaluateNpcDialogueChoices(
|
|||
return { success: true, data: [] };
|
||||
}
|
||||
|
||||
const gates: ChoiceGate[] = [];
|
||||
const visible: boolean[] = [];
|
||||
for (const choice of node.data.choices ?? []) {
|
||||
const showLocked = Boolean(choice.lockedHint?.trim());
|
||||
if (!choice.condition?.key?.trim()) {
|
||||
gates.push({ pass: true, showLocked });
|
||||
visible.push(true);
|
||||
continue;
|
||||
}
|
||||
const pass = await evaluateCondition(payload, user.id as number, choice.condition);
|
||||
gates.push({ pass, showLocked });
|
||||
visible.push(await evaluateCondition(payload, user.id as number, choice.condition));
|
||||
}
|
||||
return { success: true, data: gates };
|
||||
return { success: true, data: visible };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") {
|
||||
|
|
@ -345,48 +355,28 @@ export async function evaluateNpcDialogueChoices(
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve every interpolatable display string of one node against the reading
|
||||
* user's live flags. Tokens (`{{key}}`) are replaced server-side at render
|
||||
* time, so interpolated values may contain dialogue markup (colors) and stay
|
||||
* fresh when flags change mid-conversation. Only the flag keys a node actually
|
||||
* references are read; substituted values are never re-scanned for tokens.
|
||||
*/
|
||||
export async function resolveNpcDialogueTexts(
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult<ResolvedNodeTexts>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined;
|
||||
const node = flowData?.nodes?.find((n) => n.id === nodeId);
|
||||
if (!node) return { success: true, data: {} };
|
||||
|
||||
const keys = collectNodeTokens(node);
|
||||
const values: Record<string, string> = {};
|
||||
const countdowns: Record<string, string> = {};
|
||||
for (const key of keys) {
|
||||
const flag = await readFlag(payload, user.id as number, key);
|
||||
values[key] = flag.text;
|
||||
// Countdown leaf: pending flags tick toward activation, active ones read
|
||||
// "done", missing ones render nothing.
|
||||
countdowns[key] = flag.activatesAt ?? (flag.exists ? "done" : "");
|
||||
}
|
||||
return { success: true, data: resolveNodeTexts(node, values, countdowns) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") {
|
||||
return { success: false, error: "You must be logged in." };
|
||||
}
|
||||
return { success: false, error: message };
|
||||
async function evaluateCondition(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
condition: DialogueCondition,
|
||||
): Promise<boolean> {
|
||||
const flag = await readFlag(payload, userId, condition.key);
|
||||
const amount = condition.amount ?? 0;
|
||||
switch (condition.op) {
|
||||
case "is_true":
|
||||
return flag.bool;
|
||||
case "is_false":
|
||||
return !flag.bool;
|
||||
case "gte":
|
||||
return flag.num >= amount;
|
||||
case "lte":
|
||||
return flag.num <= amount;
|
||||
case "gt":
|
||||
return flag.num > amount;
|
||||
case "lt":
|
||||
return flag.num < amount;
|
||||
case "eq":
|
||||
return flag.num === amount;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,8 +4,6 @@ import { notFound } from "next/navigation";
|
|||
import { headers as nextHeaders } from "next/headers";
|
||||
import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
|
||||
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
||||
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
|
||||
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
|
||||
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
|
||||
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
|
||||
|
|
@ -155,7 +153,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
|
||||
const dialogue =
|
||||
npc.canMessage === true
|
||||
? await pickDialogue(payload, id, user?.id as number | undefined)
|
||||
? await firstDialogue(payload, id)
|
||||
: null;
|
||||
|
||||
return (
|
||||
|
|
@ -182,29 +180,16 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the conversation to offer this player: among all of the NPC's
|
||||
* conversations, the highest-priority one whose entry gate passes (ungated
|
||||
* always passes). Only the winner's flowchart leaves the server, so gated
|
||||
* story content never reaches a client that has not unlocked it.
|
||||
*/
|
||||
async function pickDialogue(
|
||||
/** Fetches the single dialogue flowchart for an NPC, if one exists. */
|
||||
async function firstDialogue(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
npcId: number,
|
||||
userId: number | undefined,
|
||||
) {
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npcId } },
|
||||
limit: 25,
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
});
|
||||
if (res.docs.length === 0) return null;
|
||||
|
||||
const chosen = await selectDialogueForUser(res.docs, async (condition) => {
|
||||
if (!userId) return false;
|
||||
return evaluateCondition(payload, userId, condition);
|
||||
});
|
||||
if (!chosen) return null;
|
||||
return { id: chosen.id, flowData: chosen.flowData as unknown as FlowData | undefined };
|
||||
return res.docs[0] as unknown as { id: number; flowData?: FlowData } | null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { notFound, redirect } from "next/navigation";
|
|||
import { getPayload } from "payload";
|
||||
import { ProjectBoardView } from "@/components/frontend/projects/ProjectBoardView";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { NON_ARCHIVED_WHERE } from "@/lib/tickets/ticketMeta";
|
||||
|
||||
export const metadata = {
|
||||
title: "Board | Polaris Task Force",
|
||||
|
|
@ -54,7 +53,7 @@ export default async function BoardPage({
|
|||
const [ticketResult, sprintResult, labelResult] = await Promise.all([
|
||||
payload.find({
|
||||
collection: "tickets" as any,
|
||||
where: { and: [{ project: { equals: project.id } }, NON_ARCHIVED_WHERE] },
|
||||
where: { project: { equals: project.id } },
|
||||
depth: 2,
|
||||
limit: 500,
|
||||
overrideAccess: true,
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import { getPayload } from "payload";
|
|||
import { ReleasesView } from "@/components/frontend/projects/ReleasesView";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { richTextToPlaintext } from "@/lib/projects/projectMeta";
|
||||
import { NON_ARCHIVED_WHERE } from "@/lib/tickets/ticketMeta";
|
||||
|
||||
export const metadata = {
|
||||
title: "Releases: Polaris Task Force",
|
||||
|
|
@ -48,7 +47,7 @@ export default async function ReleasesPage({ params }: { params: Promise<{ key:
|
|||
}),
|
||||
payload.find({
|
||||
collection: "tickets" as any,
|
||||
where: { and: [{ project: { equals: project.id } }, NON_ARCHIVED_WHERE] },
|
||||
where: { project: { equals: project.id } },
|
||||
depth: 0,
|
||||
limit: 500,
|
||||
overrideAccess: true,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { notFound, redirect } from "next/navigation";
|
|||
import { getPayload } from "payload";
|
||||
import { SprintsView } from "@/components/frontend/projects/SprintsView";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { NON_ARCHIVED_WHERE } from "@/lib/tickets/ticketMeta";
|
||||
|
||||
export const metadata = {
|
||||
title: "Sprints: Polaris Task Force",
|
||||
|
|
@ -51,7 +50,7 @@ export default async function SprintsPage({
|
|||
}),
|
||||
payload.find({
|
||||
collection: "tickets" as any,
|
||||
where: { and: [{ project: { equals: project.id } }, NON_ARCHIVED_WHERE] },
|
||||
where: { project: { equals: project.id } },
|
||||
depth: 0,
|
||||
limit: 500,
|
||||
overrideAccess: true,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import { headers as nextHeaders } from "next/headers";
|
|||
import { redirect } from "next/navigation";
|
||||
import { getPayload } from "payload";
|
||||
import { ProjectSearchView } from "@/components/frontend/projects/ProjectSearchView";
|
||||
import { NON_ARCHIVED_WHERE } from "@/lib/tickets/ticketMeta";
|
||||
|
||||
export const metadata = {
|
||||
title: "Search: Polaris Task Force",
|
||||
|
|
@ -21,7 +20,7 @@ export default async function SearchPage() {
|
|||
const [ticketResult, labelResult] = await Promise.all([
|
||||
payload.find({
|
||||
collection: "tickets" as any,
|
||||
where: { and: [{ project: { exists: true } }, NON_ARCHIVED_WHERE] },
|
||||
where: { project: { exists: true } },
|
||||
depth: 2,
|
||||
pagination: false,
|
||||
overrideAccess: true,
|
||||
|
|
|
|||
|
|
@ -1,35 +0,0 @@
|
|||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireArmaServer } from "@/lib/arma-bridge/server";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Called by the Arma 3 bridge (get_reinforcements) on the server's ~15 s
|
||||
* reinforcement cycle. Returns every enabled reinforcement pool with its
|
||||
* current balance and the Arma faction classes it counts, so the game can
|
||||
* attribute curator placements and render the Zeus HUD.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireArmaServer(req);
|
||||
if (auth instanceof NextResponse) return auth;
|
||||
const { payload } = auth;
|
||||
|
||||
const pools = await payload.find({
|
||||
collection: "reinforcement-pools",
|
||||
where: { enabled: { equals: true } },
|
||||
limit: 200,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
pools: pools.docs.map((pool) => ({
|
||||
poolId: pool.id,
|
||||
name: pool.name,
|
||||
available: pool.available ?? 0,
|
||||
armaFactions: pool.armaFactions ?? [],
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
|
@ -29,7 +29,7 @@ collections/
|
|||
server/ 5 files # MissionFiles, ModLists, GameServers, ArmaCommands, ArmaSyncEvents
|
||||
world/ 5 files # Maps (basemap config), MapRoads/MapZones/ResourceNodes (map features), NarrativeEvents
|
||||
projects/ 4 files # Projects, Labels, Releases, Sprints (Jira-like)
|
||||
tickets/ 2 files # Tickets (Lexical rich text; `archived` hides from all front-ends, admin panel only), TicketVotes
|
||||
tickets/ 2 files # Tickets (Lexical rich text), TicketVotes
|
||||
wiki/ 3 files # WikiPages, WikiRevisions, WikiTemplates
|
||||
story/ 3 files # StoryBeats (Chronicle chapters), StoryBeatStates (read markers/reactions),
|
||||
# Voiceovers (audio narration uploads for the Chronicle, attached to beats)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
import { CollectionConfig, type Where } from "payload";
|
||||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission, hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { loadUserPermissions } from "@/utils/access-control/loadUserPermissions";
|
||||
import { permissionSelectOptions } from "@/permissions";
|
||||
|
||||
const TARGET_COLLECTIONS = [
|
||||
{ label: "Game Structures", value: "game-structures" },
|
||||
|
|
@ -45,8 +43,6 @@ const TARGET_COLLECTIONS = [
|
|||
{ label: "Ribbon Submissions", value: "ribbon-submissions" },
|
||||
{ label: "Promotion Nominations", value: "promotion-nominations" },
|
||||
{ label: "Leadership Transfers", value: "leadership-transfers" },
|
||||
{ label: "Player Flags", value: "player-flags" },
|
||||
{ label: "Reinforcement Pools", value: "reinforcement-pools" },
|
||||
] as const;
|
||||
|
||||
export const GameEventLogs: CollectionConfig = {
|
||||
|
|
@ -54,31 +50,12 @@ export const GameEventLogs: CollectionConfig = {
|
|||
admin: {
|
||||
group: "Game",
|
||||
useAsTitle: "message",
|
||||
defaultColumns: ["timestamp", "type", "system", "visibility", "message", "actor", "structure"],
|
||||
defaultColumns: ["timestamp", "type", "system", "message", "actor", "structure"],
|
||||
listSearchableFields: ["message", "type"],
|
||||
pagination: { defaultLimit: 50 },
|
||||
},
|
||||
access: {
|
||||
// Visibility-filtered read: every logged-in user sees public events;
|
||||
// restricted events additionally require one of their
|
||||
// `requiredPermissions`, an event-log staff permission
|
||||
// (`game-event-logs:update`), superuser status, or being the actor.
|
||||
// The admin panel bypasses this (boolean gate via scopedAdminPageAccess),
|
||||
// so event-log staff keep a full view there.
|
||||
read: async ({ req }): Promise<Where | boolean> => {
|
||||
if (!req.user) return false;
|
||||
const { permissions, isSuperuser } = await loadUserPermissions(req.payload, req.user);
|
||||
if (isSuperuser) return true;
|
||||
if (permissions.has("game-event-logs:update")) return true;
|
||||
const or: Where[] = [
|
||||
{ visibility: { equals: "public" } },
|
||||
{ actor: { equals: req.user.id } },
|
||||
];
|
||||
if (permissions.size > 0) {
|
||||
or.push({ requiredPermissions: { in: [...permissions] } });
|
||||
}
|
||||
return { or };
|
||||
},
|
||||
read: ({ req }) => !!req.user,
|
||||
create: ({ req }) => !!req.user,
|
||||
update: async ({ req }) => {
|
||||
if (!req.user) return false;
|
||||
|
|
@ -98,29 +75,6 @@ export const GameEventLogs: CollectionConfig = {
|
|||
"System-generated events are created automatically. Uncheck for manual/GM narrative entries.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "visibility",
|
||||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "public",
|
||||
index: true,
|
||||
options: ["public", "restricted"],
|
||||
admin: {
|
||||
description:
|
||||
"Public events are visible to every logged-in user. Restricted events additionally require one of the required permissions below (or event-log staff / superuser status; the actor always sees their own events).",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "requiredPermissions",
|
||||
type: "select",
|
||||
hasMany: true,
|
||||
options: permissionSelectOptions,
|
||||
admin: {
|
||||
condition: (_data, blockData) => blockData?.visibility === "restricted",
|
||||
description:
|
||||
"Any-of gate: a user holding ANY one of these permissions sees this event. Leave empty to hide it from everyone except event-log staff, superusers, and the actor.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "timestamp",
|
||||
type: "date",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { CONDITION_OPS } from "@/lib/npc-dialogue/dialogue";
|
||||
|
||||
export const NpcDialogues: CollectionConfig = {
|
||||
slug: "npc-dialogues",
|
||||
|
|
@ -8,7 +7,7 @@ export const NpcDialogues: CollectionConfig = {
|
|||
group: "Game",
|
||||
useAsTitle: "name",
|
||||
listSearchableFields: ["name"],
|
||||
defaultColumns: ["name", "npc", "priority"],
|
||||
defaultColumns: ["name", "npc"],
|
||||
pagination: { defaultLimit: 50 },
|
||||
},
|
||||
access: {
|
||||
|
|
@ -39,51 +38,6 @@ export const NpcDialogues: CollectionConfig = {
|
|||
canMessage: { equals: true },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "priority",
|
||||
type: "number",
|
||||
defaultValue: 0,
|
||||
admin: {
|
||||
description:
|
||||
"When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "entryGate",
|
||||
type: "group",
|
||||
admin: {
|
||||
description:
|
||||
"Only offer this conversation to players whose flags pass this condition. Leave the key empty to always offer it (ungated conversations are the fallback).",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "key",
|
||||
type: "text",
|
||||
admin: {
|
||||
description:
|
||||
"player-flags key checked for the reading player. Player-specific flag takes priority; falls back to global. Missing = false / 0.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "op",
|
||||
type: "select",
|
||||
defaultValue: "is_true",
|
||||
options: CONDITION_OPS,
|
||||
admin: {
|
||||
description: "Comparison applied to the flag's effective value.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "amount",
|
||||
type: "number",
|
||||
admin: {
|
||||
condition: (_data, blockData) =>
|
||||
["gte", "lte", "gt", "lt", "eq"].includes(String(blockData?.op)),
|
||||
description: "Right-hand side for the numeric comparisons.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "tabs",
|
||||
tabs: [
|
||||
|
|
|
|||
|
|
@ -1,41 +1,12 @@
|
|||
import { CollectionConfig, type PayloadRequest } from "payload";
|
||||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { flagValues } from "@/lib/npc-dialogue/flags";
|
||||
|
||||
/** Human label for a flag's owner ("global" or "@username") in audit messages. */
|
||||
async function flagOwnerLabel(
|
||||
payload: PayloadRequest["payload"],
|
||||
userRef: number | { id: number } | null | undefined,
|
||||
): Promise<string> {
|
||||
if (userRef == null) return "global";
|
||||
const userId = typeof userRef === "object" ? userRef.id : userRef;
|
||||
try {
|
||||
const target = await payload.findByID({
|
||||
collection: "users",
|
||||
id: userId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
select: { username: true },
|
||||
});
|
||||
return `@${target.username}`;
|
||||
} catch {
|
||||
return `user #${userId}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** Where beforeDelete stashes the doomed doc so afterDelete can describe it. */
|
||||
interface FlagDeleteContext {
|
||||
__deletedPlayerFlag?: { key: string; owner: string; value: string };
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic flags — per-player (when `user` is set) or global (when null).
|
||||
* The lightweight state layer conversations branch on. Event nodes write
|
||||
* player flags; condition nodes read them, falling back to global if the
|
||||
* player-specific flag is absent. GMs can seed or correct both here in the
|
||||
* admin panel. Every write emits a restricted `flag:set` audit event.
|
||||
* admin panel.
|
||||
*/
|
||||
export const PlayerFlags: CollectionConfig = {
|
||||
slug: "player-flags",
|
||||
|
|
@ -75,10 +46,9 @@ export const PlayerFlags: CollectionConfig = {
|
|||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "boolean",
|
||||
options: ["boolean", "number", "text"],
|
||||
options: ["boolean", "number"],
|
||||
admin: {
|
||||
description:
|
||||
"Boolean flags read as true/false; numeric flags track statistics; text flags carry a string that conversations can interpolate with {{key}}.",
|
||||
description: "Boolean flags read as true/false; numeric flags track statistics.",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -99,99 +69,7 @@ export const PlayerFlags: CollectionConfig = {
|
|||
description: "A missing numeric flag counts as 0.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "textValue",
|
||||
type: "text",
|
||||
admin: {
|
||||
condition: (_data, blockData) => blockData?.flagType === "text",
|
||||
description:
|
||||
"Inserted into conversation text wherever {{key}} appears. May contain dialogue markup like {green}NOMINAL{/}. A missing text flag reads as empty.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "activatesAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
date: { pickerAppearance: "dayAndTime" },
|
||||
description:
|
||||
"Time-gated narrative: until this moment the flag reads as false / 0 / empty (conditions fail, {{countdown:key}} ticks). Leave empty for immediate.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "expiresAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
date: { pickerAppearance: "dayAndTime" },
|
||||
description:
|
||||
"After this moment the flag reads as missing again (falls back to a global flag of the same key, else false / 0 / empty). Use for offers and windows that lapse.",
|
||||
},
|
||||
},
|
||||
],
|
||||
hooks: {
|
||||
// Audit every flag write (admin-panel edits and dialogue effects alike)
|
||||
// as a restricted flag:set event; visibility comes from the policy map.
|
||||
afterChange: [
|
||||
async ({ doc, req, operation }) => {
|
||||
const owner = await flagOwnerLabel(req.payload, doc.user);
|
||||
const value = flagValues(doc).text;
|
||||
const verb = operation === "create" ? "created" : "updated";
|
||||
await emitGameEvent(req.payload, {
|
||||
type: EventTypes.FlagSet,
|
||||
message: `Flag "${doc.key}" ${verb} for ${owner}: ${value}`,
|
||||
actor: req.user ? Number(req.user.id) : undefined,
|
||||
targetCollection: "player-flags",
|
||||
targetId: doc.id,
|
||||
data: {
|
||||
operation,
|
||||
key: doc.key,
|
||||
flagType: doc.flagType,
|
||||
value,
|
||||
ownerUserId: typeof doc.user === "object" ? (doc.user?.id ?? null) : (doc.user ?? null),
|
||||
},
|
||||
});
|
||||
return doc;
|
||||
},
|
||||
],
|
||||
beforeDelete: [
|
||||
async ({ id, req }) => {
|
||||
// beforeDelete gets no doc; read it while it still exists so
|
||||
// afterDelete can describe what was removed.
|
||||
const ctx = req as PayloadRequest & FlagDeleteContext;
|
||||
try {
|
||||
const doc = await req.payload.findByID({
|
||||
collection: "player-flags",
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
ctx.__deletedPlayerFlag = {
|
||||
key: doc.key,
|
||||
owner: await flagOwnerLabel(req.payload, doc.user),
|
||||
value: flagValues(doc).text,
|
||||
};
|
||||
} catch {
|
||||
// Doc unreadable (already gone): afterDelete falls back to the id.
|
||||
}
|
||||
},
|
||||
],
|
||||
afterDelete: [
|
||||
async ({ id, req }) => {
|
||||
const ctx = req as PayloadRequest & FlagDeleteContext;
|
||||
const snapshot = ctx.__deletedPlayerFlag;
|
||||
await emitGameEvent(req.payload, {
|
||||
type: EventTypes.FlagSet,
|
||||
message: snapshot
|
||||
? `Flag "${snapshot.key}" deleted for ${snapshot.owner} (was: ${snapshot.value})`
|
||||
: `Flag #${id} deleted`,
|
||||
actor: req.user ? Number(req.user.id) : undefined,
|
||||
targetCollection: "player-flags",
|
||||
targetId: Number(id),
|
||||
data: { operation: "delete", key: snapshot?.key, value: snapshot?.value },
|
||||
});
|
||||
return id;
|
||||
},
|
||||
],
|
||||
},
|
||||
timestamps: true,
|
||||
indexes: [{ fields: ["user", "key"], unique: true }],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,105 +0,0 @@
|
|||
import { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { REINFORCEMENT_SYSTEM_HEADER } from "@/lib/arma-bridge/reinforcements";
|
||||
|
||||
/**
|
||||
* Reinforcement pools: per-pool "units available" balances that the Arma
|
||||
* game server pulls every ~15 s and decrements as curators place units
|
||||
* (soft limits: spawns are never blocked, balances may go negative).
|
||||
* GMs manage the balance manually here in the admin panel; every manual
|
||||
* write is audited as a restricted-free `reinforcement:adjust` event. Bridge
|
||||
* writes carry the system marker header and are audited by the processor as
|
||||
* spawn/refund events instead, so this hook stays quiet for them.
|
||||
*/
|
||||
export const ReinforcementPools: CollectionConfig = {
|
||||
slug: "reinforcement-pools",
|
||||
admin: {
|
||||
group: "Game",
|
||||
useAsTitle: "name",
|
||||
listSearchableFields: ["name"],
|
||||
defaultColumns: ["name", "faction", "available", "enabled"],
|
||||
},
|
||||
access: {
|
||||
read: requirePermission("reinforcement-pools:read"),
|
||||
create: requirePermission("reinforcement-pools:create"),
|
||||
update: requirePermission("reinforcement-pools:update"),
|
||||
delete: requirePermission("reinforcement-pools:delete"),
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "name",
|
||||
type: "text",
|
||||
required: true,
|
||||
unique: true,
|
||||
admin: {
|
||||
description: "Pool name shown on the in-game Zeus HUD (e.g. 'PTF').",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "faction",
|
||||
type: "relationship",
|
||||
relationTo: "factions",
|
||||
admin: {
|
||||
description:
|
||||
"Optional web-app faction this pool belongs to. Grouping only; in-game attribution uses the Arma faction classes below.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "armaFactions",
|
||||
type: "text",
|
||||
hasMany: true,
|
||||
admin: {
|
||||
description:
|
||||
"Arma CfgVehicles faction classes counted by this pool (e.g. 'BLU_F', 'PTF'). Matched case-insensitively against the placed unit's faction; units of unmatched factions are free.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "available",
|
||||
type: "number",
|
||||
defaultValue: 0,
|
||||
admin: {
|
||||
description:
|
||||
"Units available. Decremented by counted Zeus placements, refunded on curator deletions. May go negative (overdraft is allowed; spawning is never blocked).",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "enabled",
|
||||
type: "checkbox",
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
description: "Disabled pools are hidden from the game server and the Zeus HUD.",
|
||||
},
|
||||
},
|
||||
],
|
||||
hooks: {
|
||||
afterChange: [
|
||||
async ({ doc, req, operation, previousDoc }) => {
|
||||
// Bridge processor writes carry the system marker header and are
|
||||
// audited as reinforcement:spawn / reinforcement:refund events by the
|
||||
// processor itself; only manual GM/admin edits need an adjust audit.
|
||||
if (req.headers.get(REINFORCEMENT_SYSTEM_HEADER) === "1") return doc;
|
||||
if (operation === "update" && previousDoc?.available === doc.available) return doc;
|
||||
await emitGameEvent(req.payload, {
|
||||
type: EventTypes.ReinforcementAdjust,
|
||||
message:
|
||||
operation === "create"
|
||||
? `Reinforcement pool "${doc.name}" created with balance ${doc.available ?? 0}`
|
||||
: `Reinforcement pool "${doc.name}" adjusted: ${previousDoc?.available ?? 0} -> ${doc.available}`,
|
||||
actor: req.user ? Number(req.user.id) : undefined,
|
||||
targetCollection: "reinforcement-pools",
|
||||
targetId: doc.id,
|
||||
data: {
|
||||
operation,
|
||||
name: doc.name,
|
||||
availableBefore: operation === "create" ? null : (previousDoc?.available ?? null),
|
||||
availableAfter: doc.available,
|
||||
},
|
||||
});
|
||||
return doc;
|
||||
},
|
||||
],
|
||||
},
|
||||
timestamps: true,
|
||||
};
|
||||
|
|
@ -2,7 +2,6 @@ import { CollectionConfig } from "payload";
|
|||
import { processPlayerKill } from "@/lib/arma-bridge/processSyncEvents";
|
||||
import { processBoxEvent } from "@/lib/arma-bridge/crates";
|
||||
import { processMoneyEvent } from "@/lib/arma-bridge/money";
|
||||
import { processReinforcementEvent } from "@/lib/arma-bridge/reinforcements";
|
||||
import { processLockerEvent } from "@/lib/arma-bridge/lockers";
|
||||
import { isOperationLedgerEnabled } from "@/lib/operations/rollout";
|
||||
import { processOperationEvent } from "@/lib/operations/process";
|
||||
|
|
@ -42,12 +41,6 @@ export const ArmaSyncEvents: CollectionConfig = {
|
|||
// flushing). processMoneyEvent never throws.
|
||||
await processMoneyEvent(req.payload, doc);
|
||||
}
|
||||
if (doc.type.startsWith("reinforcement.")) {
|
||||
// Awaited (same posture as money.delta): the pool balance must be
|
||||
// current before the game's next reinforcement pull, and
|
||||
// processReinforcementEvent never throws.
|
||||
await processReinforcementEvent(req.payload, doc, req);
|
||||
}
|
||||
if (doc.type.startsWith("locker.")) {
|
||||
// Awaited (same posture as box.*): locker writes join the raw-event
|
||||
// transaction; processLockerEvent never throws.
|
||||
|
|
|
|||
|
|
@ -56,7 +56,6 @@ export const Tickets: CollectionConfig = {
|
|||
"category",
|
||||
"reporter",
|
||||
"assignee",
|
||||
"archived",
|
||||
"updatedAt",
|
||||
],
|
||||
listSearchableFields: ["title", "id"],
|
||||
|
|
@ -142,19 +141,6 @@ export const Tickets: CollectionConfig = {
|
|||
}
|
||||
}
|
||||
|
||||
// Archive toggles → system entry + archivedAt management. Archived
|
||||
// tickets are hidden from every front-end surface; un-archiving only
|
||||
// happens in the admin panel.
|
||||
if (next.archived !== undefined && Boolean(prev.archived) !== Boolean(next.archived)) {
|
||||
if (next.archived) {
|
||||
next.archivedAt = now;
|
||||
changes.push("Ticket archived");
|
||||
} else {
|
||||
next.archivedAt = null;
|
||||
changes.push("Ticket restored from archive");
|
||||
}
|
||||
}
|
||||
|
||||
for (const message of changes) {
|
||||
entries.push(systemEntry(message, now));
|
||||
}
|
||||
|
|
@ -313,24 +299,6 @@ export const Tickets: CollectionConfig = {
|
|||
date: { pickerAppearance: "dayAndTime" },
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "archived",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Archived tickets are hidden from the front-end for everyone (staff included) and remain accessible only here in the admin panel. Uncheck to restore the ticket.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "archivedAt",
|
||||
type: "date",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "Set automatically when the ticket is archived.",
|
||||
date: { pickerAppearance: "dayAndTime" },
|
||||
},
|
||||
},
|
||||
|
||||
// --- Project tracking fields (Phase 1) ---
|
||||
{
|
||||
|
|
|
|||
|
|
@ -47,7 +47,6 @@ const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
|
|||
set_true: "Set to true",
|
||||
set_false: "Set to false",
|
||||
set_number: "Set number to",
|
||||
set_text: "Set text to",
|
||||
add: "Add to number",
|
||||
};
|
||||
|
||||
|
|
@ -192,10 +191,7 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
<p className="text-[10px] text-white/40">
|
||||
Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render
|
||||
in the conversation. Colors take a friendly name (red, amber, cyan, emerald,
|
||||
violet, pink, slate, ...) or a hex code like {`{#ff00ff}`}. Insert flag values
|
||||
with {'{{flag_key}}'}; text flags may carry their own color markup. Inline
|
||||
images use {''} (e.g. {``}) and
|
||||
render at text height.
|
||||
violet, pink, slate, ...) or a hex code like {`{#ff00ff}`}.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -239,20 +235,6 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[9px] uppercase tracking-wider text-white/40">
|
||||
Tooltip (optional)
|
||||
</Label>
|
||||
<Textarea
|
||||
value={choice.tooltip ?? ""}
|
||||
onChange={(e) =>
|
||||
setChoice(index, { ...choice, tooltip: e.target.value || undefined })
|
||||
}
|
||||
placeholder="Hover card. Supports markup, {{flags}} and  images."
|
||||
rows={2}
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[9px] uppercase tracking-wider text-white/40">Goes to</Label>
|
||||
<select
|
||||
|
|
@ -337,23 +319,9 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
/>
|
||||
</div>
|
||||
)}
|
||||
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
|
||||
Lock message (optional)
|
||||
</Label>
|
||||
<Textarea
|
||||
value={choice.lockedHint ?? ""}
|
||||
onChange={(e) =>
|
||||
setChoice(index, { ...choice, lockedHint: e.target.value || undefined })
|
||||
}
|
||||
placeholder='Shown on the disabled choice, e.g. "Needs {amber}trusted{/} standing."'
|
||||
rows={2}
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Player-specific flag takes priority; falls back to global (no user).
|
||||
Missing = false / 0. With a lock message the choice stays visible but
|
||||
disabled (tooltip explains why) while the condition fails; without one
|
||||
it is hidden entirely.
|
||||
Missing = false / 0. The choice button is hidden until this passes.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -388,9 +356,6 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
rows={3}
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
|
|
@ -465,54 +430,9 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
/>
|
||||
</div>
|
||||
)}
|
||||
{draft.effect.flagOp === "set_text" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Text value
|
||||
</Label>
|
||||
<Input
|
||||
value={draft.effect.flagText ?? ""}
|
||||
onChange={(e) => patchEffect({ flagText: e.target.value || undefined })}
|
||||
placeholder="{green}NOMINAL{/}"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Conversations insert this value wherever {'{{key}}'} appears. Colors like
|
||||
{` {green}...{/}`} render in dialogue lines.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{(draft.effect.flagOp === "set_true" ||
|
||||
draft.effect.flagOp === "set_false" ||
|
||||
draft.effect.flagOp === "set_number" ||
|
||||
draft.effect.flagOp === "set_text") && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Delay activation (minutes, optional)
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
value={draft.effect.flagDelayMinutes ?? ""}
|
||||
onChange={(e) =>
|
||||
patchEffect({
|
||||
flagDelayMinutes:
|
||||
Number(e.target.value) > 0 ? Number(e.target.value) : undefined,
|
||||
})
|
||||
}
|
||||
placeholder="0 = immediate"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
For slow-burn narrative: the flag reads as false / 0 until this many
|
||||
minutes have passed, so conditions fail and {"{{countdown:key}}"} tokens
|
||||
tick down to it. Leave empty for an immediate write.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-[10px] text-white/40">
|
||||
Creates the flag when the player does not have it yet. "Add" keeps numeric
|
||||
flags running totals; "Set text to" converts the flag to a text flag.
|
||||
flags running totals.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -648,9 +568,6 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
rows={3}
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { ChevronLeft, ChevronRight, Lock, RotateCcw, Search } from "lucide-react";
|
||||
import { ChevronLeft, ChevronRight, RotateCcw, Search } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Combobox } from "@/components/ui/combobox";
|
||||
|
|
@ -70,7 +70,6 @@ const TARGET_COLLECTION_LABELS: Record<string, string> = {
|
|||
"assignment-transfers": "Assignment Transfers",
|
||||
"voice-scripts": "Voice Scripts",
|
||||
"voice-submissions": "Voice Submissions",
|
||||
"player-flags": "Player Flags",
|
||||
};
|
||||
|
||||
const TARGET_COLLECTION_OPTIONS = Object.entries(TARGET_COLLECTION_LABELS).sort((a, b) =>
|
||||
|
|
@ -85,7 +84,6 @@ type SortDir = "desc" | "asc";
|
|||
interface EventRow {
|
||||
id: number;
|
||||
system?: boolean | null;
|
||||
visibility?: string | null;
|
||||
timestamp: string;
|
||||
type: string;
|
||||
message: string;
|
||||
|
|
@ -418,21 +416,9 @@ export default function EventLogTable() {
|
|||
{formatTimestamp(row.timestamp)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-1">
|
||||
<Badge variant="outline" className="max-w-40 truncate font-normal">
|
||||
{formatType(row.type)}
|
||||
</Badge>
|
||||
{row.visibility === "restricted" && (
|
||||
<span
|
||||
className="inline-flex shrink-0 text-amber-400"
|
||||
role="img"
|
||||
aria-label="Restricted event"
|
||||
title="Restricted: visible only to staff with the required permissions and to its actor"
|
||||
>
|
||||
<Lock className="size-3" aria-hidden />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Badge variant="outline" className="max-w-40 truncate font-normal">
|
||||
{formatType(row.type)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="max-w-md whitespace-normal">{row.message}</TableCell>
|
||||
<TableCell className="text-xs">{actorLabel(row.actor)}</TableCell>
|
||||
|
|
|
|||
|
|
@ -20,20 +20,9 @@ import {
|
|||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { TicketBadges, TicketCategoryBadge } from "@/components/frontend/helpdesk/TicketBadges";
|
||||
import { TicketTimeline } from "@/components/frontend/helpdesk/TicketTimeline";
|
||||
import {
|
||||
archiveTicket,
|
||||
assignTicket,
|
||||
replyToTicket,
|
||||
updateTicketStatus,
|
||||
} from "@/app/(frontend)/helpdesk/actions";
|
||||
import { assignTicket, replyToTicket, updateTicketStatus } from "@/app/(frontend)/helpdesk/actions";
|
||||
import { CLOSING_STATUSES, TICKET_STATUSES, type TicketStatus } from "@/lib/tickets/ticketMeta";
|
||||
import {
|
||||
ArchiveIcon,
|
||||
CalendarClockIcon,
|
||||
HistoryIcon,
|
||||
SendIcon,
|
||||
Settings2Icon,
|
||||
} from "lucide-react";
|
||||
import { CalendarClockIcon, HistoryIcon, SendIcon, Settings2Icon } from "lucide-react";
|
||||
import { EditTicketDialog } from "@/components/frontend/helpdesk/EditTicketDialog";
|
||||
import { TicketVoteButton } from "@/components/frontend/helpdesk/TicketVoteButton";
|
||||
import type { TicketVoteSummary } from "@/lib/tickets/voteState";
|
||||
|
|
@ -109,14 +98,10 @@ export function TicketDetail({
|
|||
const [confirmCancel, setConfirmCancel] = useState(false);
|
||||
const [cancelBusy, setCancelBusy] = useState(false);
|
||||
const cancelTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [confirmArchive, setConfirmArchive] = useState(false);
|
||||
const [archiveBusy, setArchiveBusy] = useState(false);
|
||||
const archiveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (cancelTimerRef.current) clearTimeout(cancelTimerRef.current);
|
||||
if (archiveTimerRef.current) clearTimeout(archiveTimerRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
|
@ -195,37 +180,6 @@ export function TicketDetail({
|
|||
}, 3000);
|
||||
}
|
||||
|
||||
async function handleArchive() {
|
||||
setArchiveBusy(true);
|
||||
setControlError(null);
|
||||
const result = await archiveTicket(ticket.id);
|
||||
setArchiveBusy(false);
|
||||
if (result.success) {
|
||||
setConfirmArchive(false);
|
||||
toast.success("Ticket archived");
|
||||
// The ticket is hidden from the front-end now, so leave the detail page.
|
||||
// The archiveTicket action revalidates /helpdesk; refresh() after push()
|
||||
// makes the client refetch instead of serving a prefetched RSC payload.
|
||||
router.push("/helpdesk");
|
||||
router.refresh();
|
||||
} else {
|
||||
setControlError(result.error ?? "Could not archive the ticket.");
|
||||
}
|
||||
}
|
||||
|
||||
function requestArchive() {
|
||||
if (confirmArchive) {
|
||||
void handleArchive();
|
||||
return;
|
||||
}
|
||||
setConfirmArchive(true);
|
||||
if (archiveTimerRef.current) clearTimeout(archiveTimerRef.current);
|
||||
archiveTimerRef.current = setTimeout(() => {
|
||||
setConfirmArchive(false);
|
||||
archiveTimerRef.current = null;
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex w-full max-w-5xl flex-col gap-6">
|
||||
<section className="flex flex-col gap-4">
|
||||
|
|
@ -335,21 +289,6 @@ export function TicketDetail({
|
|||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-t pt-3 sm:col-span-2">
|
||||
<p className="text-xs text-muted-foreground sm:max-w-[60%]">
|
||||
Archiving hides this ticket from the Helpdesk for everyone, including staff. It can
|
||||
only be restored from the admin panel.
|
||||
</p>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={requestArchive}
|
||||
disabled={archiveBusy || controlBusy !== null}
|
||||
>
|
||||
<ArchiveIcon className="mr-1.5 size-3.5" />
|
||||
{archiveBusy ? "Archiving..." : confirmArchive ? "Confirm archive?" : "Archive ticket"}
|
||||
</Button>
|
||||
</div>
|
||||
{controlError && (
|
||||
<p role="alert" className="text-sm text-red-400 sm:col-span-2">
|
||||
{controlError}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,12 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState, Fragment } from "react";
|
||||
import { LockIcon, MessageCircleIcon, XIcon } from "lucide-react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { MessageCircleIcon, XIcon } from "lucide-react";
|
||||
|
||||
import type { GameNpc } from "@/payload-types";
|
||||
import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
|
||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||
import type { DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
|
||||
import { flowHash, loadSeenMap, mergeSeenNodes, saveSeenMap, unseenNodeIds } from "@/lib/npc-dialogue/seen";
|
||||
import type { SeenMap } from "@/lib/npc-dialogue/seen";
|
||||
import { DOSSIER } from "@/components/frontend/operations";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
|
|
@ -18,16 +14,9 @@ import {
|
|||
DialogContent,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import {
|
||||
evaluateNpcDialogueChoices,
|
||||
evaluateNpcDialogueCondition,
|
||||
resolveNpcDialogueTexts,
|
||||
triggerNpcDialogueEvent,
|
||||
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
|
||||
|
|
@ -42,14 +31,7 @@ interface ResolvedFlow {
|
|||
}
|
||||
|
||||
type LogEntry =
|
||||
| {
|
||||
kind: "node";
|
||||
id: string;
|
||||
node: DialogueNode;
|
||||
/** Server-resolved display strings (flag tokens interpolated), when the
|
||||
* node had tokens. Undefined = render the raw authored strings. */
|
||||
resolved?: ResolvedNodeTexts;
|
||||
}
|
||||
| { kind: "node"; id: string; node: DialogueNode; triggered: boolean }
|
||||
| { kind: "player"; id: string; text: string };
|
||||
|
||||
/** Resolves the authored flowchart into a shape the runtime can walk. */
|
||||
|
|
@ -86,13 +68,7 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
/** Per-node visibility gates for condition-gated choices, fetched from
|
||||
* the server when the conversation lands on a choice node. Cleared on
|
||||
* every `begin()` so flags gained mid-conversation are re-checked. */
|
||||
const [choiceGates, setChoiceGates] = useState<Record<string, ChoiceGate[]>>({});
|
||||
/** Per-browser read progress powering the NEW badges. Loaded after mount so
|
||||
* server and client markup agree (localStorage is invisible to SSR). */
|
||||
const [seenMap, setSeenMap] = useState<SeenMap>({});
|
||||
useEffect(() => {
|
||||
setSeenMap(loadSeenMap());
|
||||
}, []);
|
||||
const [choiceGates, setChoiceGates] = useState<Record<string, boolean[]>>({});
|
||||
const seq = useRef(0);
|
||||
const sessionRef = useRef(0);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
|
@ -107,6 +83,23 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
[],
|
||||
);
|
||||
|
||||
// Trigger every arrived event node's effect exactly once, in order (the
|
||||
// opening cascade can land on several events at once).
|
||||
useEffect(() => {
|
||||
const pending = log.find(
|
||||
(entry) =>
|
||||
entry.kind === "node" &&
|
||||
entry.node.type === "event" &&
|
||||
!!entry.node.data.effect &&
|
||||
!entry.triggered,
|
||||
);
|
||||
if (!pending || pending.kind !== "node") return;
|
||||
void triggerNpcDialogueEvent(Number(npc.id), pending.node.id).catch(() => undefined);
|
||||
setLog((prev) =>
|
||||
prev.map((entry) => (entry.id === pending.id ? { ...entry, triggered: true } : entry)),
|
||||
);
|
||||
}, [log, npc.id]);
|
||||
|
||||
// Keep the newest line in view.
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
|
|
@ -140,48 +133,15 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
};
|
||||
}, [open, flow, activeChoiceNodeId, choiceGates, npc.id]);
|
||||
|
||||
// NEW badge inputs: current flowchart signature + the nodes this browser
|
||||
// has not read yet (a GM edit changes the hash and re-flags everything).
|
||||
const seenKey = dialogue ? String(dialogue.id) : "";
|
||||
const flowSignature = useMemo(() => flowHash(dialogue?.flowData), [dialogue]);
|
||||
const allNodeIds = useMemo(() => (flow ? flow.nodes.map((n) => n.id) : []), [flow]);
|
||||
const unseenTargets = useMemo(
|
||||
() => new Set(unseenNodeIds(seenMap[seenKey], flowSignature, allNodeIds)),
|
||||
[seenMap, seenKey, flowSignature, allNodeIds],
|
||||
);
|
||||
|
||||
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
|
||||
|
||||
/** Records that this browser has read a node (persisted, idempotent). */
|
||||
const markSeen = (nodeId: string) => {
|
||||
setSeenMap((prev) => {
|
||||
const entry = prev[seenKey];
|
||||
if (entry && entry.hash === flowSignature && entry.nodes.includes(nodeId)) return prev;
|
||||
const next: SeenMap = {
|
||||
...prev,
|
||||
[seenKey]: { hash: flowSignature, nodes: mergeSeenNodes(entry, flowSignature, nodeId) },
|
||||
};
|
||||
saveSeenMap(next);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
/** Resolves the node's display strings server-side (flag tokens), then
|
||||
* appends it to the log after a length-based "typing" delay. Nodes without
|
||||
* tokens skip the round trip and render their raw authored text. */
|
||||
/** Appends a node to the log after a length-based "typing" delay. */
|
||||
const typeIn = async (node: DialogueNode, token: number) => {
|
||||
let resolved: ResolvedNodeTexts | undefined;
|
||||
if (collectNodeTokens(node).length > 0) {
|
||||
const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
|
||||
if (sessionRef.current !== token) return;
|
||||
if (res.success && res.data) resolved = res.data;
|
||||
}
|
||||
setTyping(node.type === "event" ? "" : node.data.speaker?.trim() || npc.name);
|
||||
await sleep(typingDelayMs(nodeText(node)));
|
||||
if (sessionRef.current !== token) return;
|
||||
setTyping(null);
|
||||
setLog((prev) => [...prev, { kind: "node", id: nextId(), node, resolved }]);
|
||||
markSeen(node.id);
|
||||
setLog((prev) => [...prev, { kind: "node", id: nextId(), node, triggered: false }]);
|
||||
};
|
||||
|
||||
// Opening the conversation walks the start node and auto-advances through
|
||||
|
|
@ -236,12 +196,6 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
await typeIn(current, token);
|
||||
if (sessionRef.current !== token) return;
|
||||
if (current.type === "dialogue" || current.type === "event") {
|
||||
if (current.type === "event" && current.data.effect) {
|
||||
// Await the effect so flags it writes are visible to the lines
|
||||
// that follow (interpolated text and later condition nodes).
|
||||
await triggerNpcDialogueEvent(Number(npc.id), current.id).catch(() => undefined);
|
||||
if (sessionRef.current !== token) return;
|
||||
}
|
||||
const target: string | undefined = current.data.next?.target;
|
||||
current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
|
||||
} else {
|
||||
|
|
@ -260,11 +214,10 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
const lastNode = [...log].reverse().find((entry) => entry.kind === "node");
|
||||
|
||||
// The player's line types out (shorter than NPC pacing), lands, and then
|
||||
// the NPC starts typing its reply. `displayText` is the label as shown on
|
||||
// the button (flag tokens already interpolated server-side).
|
||||
const pick = (hop: DialogueNext, choiceIndex: number, displayText?: string) => {
|
||||
// the NPC starts typing its reply.
|
||||
const pick = (hop: DialogueNext, choiceIndex: number) => {
|
||||
const token = sessionRef.current;
|
||||
const text = displayText || hop.label || "…";
|
||||
const text = hop.label || "…";
|
||||
if (hop.once && lastNode && lastNode.kind === "node") {
|
||||
const key = `${lastNode.node.id}:${choiceIndex}`;
|
||||
setTakenChoices((prev) => (prev.has(key) ? prev : new Set(prev).add(key)));
|
||||
|
|
@ -288,85 +241,40 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
? lastNode.node
|
||||
: null;
|
||||
const visibleChoices = choiceNode
|
||||
? (choiceNode.data.choices ?? []).reduce<
|
||||
{ hop: DialogueNext; index: number; locked: boolean }[]
|
||||
>((acc, hop, index) => {
|
||||
if (hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) return acc;
|
||||
if (!hop.condition?.key?.trim()) {
|
||||
acc.push({ hop, index, locked: false });
|
||||
return acc;
|
||||
}
|
||||
// Gated choices stay hidden until the server confirms them; a failing
|
||||
// gate with an authored hint renders the choice locked instead.
|
||||
const gate = choiceGates[choiceNode.id]?.[index];
|
||||
if (!gate) return acc;
|
||||
if (gate.pass) acc.push({ hop, index, locked: false });
|
||||
else if (gate.showLocked) acc.push({ hop, index, locked: true });
|
||||
return acc;
|
||||
}, [])
|
||||
? (choiceNode.data.choices ?? [])
|
||||
.map((hop, index) => ({ hop, index }))
|
||||
.filter(
|
||||
({ hop, index }) =>
|
||||
!(hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) &&
|
||||
(!hop.condition?.key?.trim() || choiceGates[choiceNode.id]?.[index] === true),
|
||||
)
|
||||
: [];
|
||||
const anySelectableChoice = visibleChoices.some((choice) => !choice.locked);
|
||||
|
||||
/** Button text for a choice: the server-resolved label when the choice
|
||||
* node's strings contained flag tokens, the raw label otherwise. */
|
||||
const choiceLabel = (hop: DialogueNext, index: number): string =>
|
||||
((lastNode?.kind === "node" ? lastNode.resolved?.labels?.[index] : undefined) ??
|
||||
hop.label) ||
|
||||
"…";
|
||||
|
||||
/** Rich hover tooltip for a choice (resolved like labels); undefined when
|
||||
* the author left it empty. */
|
||||
const choiceTooltip = (hop: DialogueNext, index: number): string | undefined => {
|
||||
const raw =
|
||||
(lastNode?.kind === "node" ? lastNode.resolved?.tooltips?.[index] : undefined) ??
|
||||
hop.tooltip;
|
||||
return raw?.trim() ? raw : undefined;
|
||||
};
|
||||
|
||||
/** Tooltip for a locked choice (resolved like labels); generic fallback
|
||||
* when the author left the hint blank. */
|
||||
const choiceHint = (hop: DialogueNext, index: number): string => {
|
||||
const raw =
|
||||
(lastNode?.kind === "node" ? lastNode.resolved?.hints?.[index] : undefined) ??
|
||||
hop.lockedHint;
|
||||
return raw?.trim() ? raw : "Locked.";
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<span className="relative inline-flex">
|
||||
<Button
|
||||
onClick={begin}
|
||||
className="group/converse relative overflow-hidden rounded-none border border-white/20 bg-black/40 text-white hover:border-cyan-400/60 hover:bg-zinc-800 hover:text-cyan-400"
|
||||
>
|
||||
<span className="absolute -left-8 h-full w-8 bg-gradient-to-r from-cyan-500/40 via-cyan-500/15 to-transparent transition-transform group-hover/converse:translate-x-8" />
|
||||
<MessageCircleIcon className="relative z-10 size-3.5 text-cyan-400" />
|
||||
<span className="relative z-10 ml-2 text-xs uppercase tracking-widest">Converse</span>
|
||||
</Button>
|
||||
{unseenTargets.size > 0 && (
|
||||
<span
|
||||
aria-label="New or updated dialogue"
|
||||
className="pointer-events-none absolute -right-1.5 -top-1.5 z-10 rounded-sm bg-cyan-400 px-1 py-px font-mono text-[9px] font-bold uppercase leading-none text-black"
|
||||
>
|
||||
New
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<Button
|
||||
onClick={begin}
|
||||
className="group/converse relative overflow-hidden rounded-none border border-white/20 bg-black/40 text-white hover:border-cyan-400/60 hover:bg-zinc-800 hover:text-cyan-400"
|
||||
>
|
||||
<span className="absolute -left-8 h-full w-8 bg-gradient-to-r from-cyan-500/40 via-cyan-500/15 to-transparent transition-transform group-hover/converse:translate-x-8" />
|
||||
<MessageCircleIcon className="relative z-10 size-3.5 text-cyan-400" />
|
||||
<span className="relative z-10 ml-2 text-xs uppercase tracking-widest">Converse</span>
|
||||
</Button>
|
||||
|
||||
<Dialog open={open} onOpenChange={(next) => !next && close()}>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="flex w-[calc(100%-1.5rem)] max-w-2xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:w-full sm:rounded-none"
|
||||
className="flex max-w-2xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:rounded-none"
|
||||
>
|
||||
<div className={`relative flex items-center justify-between ${DOSSIER.strip}`}>
|
||||
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
|
||||
<DialogTitle className="font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
|
||||
Conversation // {npc.name}
|
||||
</DialogTitle>
|
||||
<button
|
||||
type="button"
|
||||
onClick={close}
|
||||
aria-label="Close conversation"
|
||||
className="shrink-0 text-white/40 transition-colors hover:text-white/90"
|
||||
className="text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
|
|
@ -397,52 +305,18 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
|||
lastNode.kind === "node" &&
|
||||
(lastNode.node.type === "choice" || lastNode.node.type === "end") && (
|
||||
<div className="flex flex-col gap-2 border-t border-white/15 bg-black/50 p-4">
|
||||
{lastNode.node.type === "choice" && visibleChoices.length > 0 && (
|
||||
<TooltipProvider delayDuration={150}>
|
||||
{visibleChoices.map(({ hop, index, locked }) => {
|
||||
const isNew = unseenTargets.has(hop.target);
|
||||
const button = (
|
||||
<button
|
||||
type="button"
|
||||
disabled={locked}
|
||||
onClick={() => pick(hop, index, choiceLabel(hop, index))}
|
||||
className={`w-full rounded-none border px-3 py-2 text-left text-sm transition-colors ${
|
||||
locked
|
||||
? "cursor-not-allowed border-white/10 bg-black/20 text-white/35"
|
||||
: "border-white/20 bg-black/40 text-white/80 hover:border-cyan-500/60 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
{locked && (
|
||||
<LockIcon className="size-3 shrink-0 text-amber-400/70" />
|
||||
)}
|
||||
<DialogueText text={choiceLabel(hop, index)} />
|
||||
{isNew && !locked && (
|
||||
<span className="ml-auto shrink-0 rounded-sm bg-cyan-400 px-1 font-mono text-[9px] font-bold uppercase leading-tight text-black">
|
||||
New
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
const tip = locked ? choiceHint(hop, index) : choiceTooltip(hop, index);
|
||||
if (!tip) return <Fragment key={index}>{button}</Fragment>;
|
||||
return (
|
||||
<Tooltip key={index}>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="top"
|
||||
sideOffset={8}
|
||||
className="max-w-xs rounded-none border border-white/20 bg-zinc-900 p-3 text-left text-sm font-normal leading-relaxed text-white/85"
|
||||
>
|
||||
<DialogueText text={tip} />
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</TooltipProvider>
|
||||
)}
|
||||
{(lastNode.node.type === "end" || !anySelectableChoice) && (
|
||||
{lastNode.node.type === "choice" && visibleChoices.length > 0 ? (
|
||||
visibleChoices.map(({ hop, index }) => (
|
||||
<button
|
||||
key={index}
|
||||
type="button"
|
||||
onClick={() => pick(hop, index)}
|
||||
className="w-full rounded-none border border-white/20 bg-black/40 px-3 py-2 text-left text-sm text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white"
|
||||
>
|
||||
{hop.label || "…"}
|
||||
</button>
|
||||
))
|
||||
) : (
|
||||
<Button
|
||||
onClick={close}
|
||||
className="w-full rounded-none border border-white/20 bg-black/40 text-xs uppercase tracking-widest text-white/80 hover:border-cyan-500/60 hover:bg-black/40 hover:text-white"
|
||||
|
|
@ -472,19 +346,17 @@ function TimelineEntry({
|
|||
<div className="flex flex-col items-end gap-1">
|
||||
<span className={`${DOSSIER.readoutLabel} text-cyan-400/70`}>You</span>
|
||||
<p className="max-w-[85%] rounded-none border border-cyan-500/30 bg-cyan-500/10 px-3 py-1.5 text-sm text-cyan-50">
|
||||
<DialogueText text={entry.text} />
|
||||
{entry.text}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { node, resolved } = entry;
|
||||
const { node } = entry;
|
||||
|
||||
if (node.type === "event") {
|
||||
// Narration: no speaker, styled like a mission briefing line.
|
||||
const body = resolved?.body ?? node.data.body;
|
||||
const message = resolved?.message ?? node.data.effect?.message;
|
||||
const text = body || message || "An event unfolds…";
|
||||
const text = node.data.body || node.data.effect?.message || "An event unfolds…";
|
||||
return (
|
||||
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
|
||||
<DialogueText text={text} />
|
||||
|
|
@ -493,33 +365,30 @@ function TimelineEntry({
|
|||
}
|
||||
|
||||
if (node.type === "end") {
|
||||
const text = (resolved?.closing ?? node.data.closing) || "The conversation ends.";
|
||||
return (
|
||||
<p className="text-sm italic text-white/50">
|
||||
<DialogueText text={text} />
|
||||
<DialogueText text={node.data.closing || "The conversation ends."} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
if (node.type === "choice") {
|
||||
// The choice buttons live in the footer; only the lead-in joins the log.
|
||||
const leadIn = resolved?.leadIn ?? node.data.leadIn;
|
||||
if (!leadIn) return null;
|
||||
if (!node.data.leadIn) return null;
|
||||
return (
|
||||
<p className="text-sm italic text-white/60">
|
||||
<DialogueText text={leadIn} />
|
||||
<DialogueText text={node.data.leadIn} />
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
const speaker = node.data.speaker?.trim() || speakerDefault;
|
||||
const body = resolved?.body ?? node.data.body;
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<span className={DOSSIER.readoutLabel}>{speaker}</span>
|
||||
<p className="text-sm text-white/90">
|
||||
{body ? (
|
||||
<DialogueText text={body} />
|
||||
{node.data.body ? (
|
||||
<DialogueText text={node.data.body} />
|
||||
) : (
|
||||
<span className="italic text-white/30">…</span>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -154,6 +154,12 @@ export function NpcProfile({ npc, listings, employmentSlot, conversationSlot }:
|
|||
<ClassificationStrip left="Personnel File // Theater Contacts" right={`REF ${refCode}`} />
|
||||
<CornerBrackets />
|
||||
|
||||
{conversationSlot ? (
|
||||
<div className="absolute right-6 top-1/2 z-20 -translate-y-1/2 md:right-12">
|
||||
{conversationSlot}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="relative z-10 flex flex-col gap-3 px-6 py-10 md:py-14">
|
||||
<h1
|
||||
data-text={npc.name}
|
||||
|
|
@ -178,13 +184,6 @@ export function NpcProfile({ npc, listings, employmentSlot, conversationSlot }:
|
|||
activityOptions={activityOptions}
|
||||
/>
|
||||
<NpcStatusChips npc={npc} className="mt-1" />
|
||||
{conversationSlot ? (
|
||||
// Mobile: a normal button in the card's flow so it never covers
|
||||
// the bio text. md+: floated to the hero's right edge as before.
|
||||
<div className="z-20 self-start pt-1 md:absolute md:right-12 md:top-1/2 md:-translate-y-1/2 md:self-auto md:pt-0">
|
||||
{conversationSlot}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="relative z-10">
|
||||
|
|
|
|||
|
|
@ -1,129 +0,0 @@
|
|||
import type { Payload, PayloadRequest } from "payload";
|
||||
import type { ReinforcementPool } from "@/payload-types";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
|
||||
/**
|
||||
* Reinforcement pools <-> Arma game server sync (bridge).
|
||||
*
|
||||
* The game queues a `reinforcement.spawn` event for every curator placement
|
||||
* that matches a pool's Arma factions and a `reinforcement.refund` event when
|
||||
* a curator deletes such a unit (killed units stay spent). The events route
|
||||
* dedupes by `serverId:eventId`, so a retried delivery never double-spends.
|
||||
* Balances are soft limits: they may go negative and nothing ever blocks.
|
||||
*
|
||||
* Pool balances live on `reinforcement-pools.available`. The game pulls them
|
||||
* through GET /api/arma/v1/reinforcements, so this processor must have applied
|
||||
* an event before the next pull returns (the ArmaSyncEvents hook awaits it).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Marker header the processor passes through the local API `req` option so the
|
||||
* ReinforcementPools afterChange audit hook can tell bridge writes apart from
|
||||
* manual GM edits (manual edits emit `reinforcement:adjust`, bridge writes are
|
||||
* audited here as spawn/refund events instead).
|
||||
*/
|
||||
export const REINFORCEMENT_SYSTEM_HEADER = "x-reinforcement-system";
|
||||
|
||||
interface ReinforcementDelta {
|
||||
poolId: number;
|
||||
count: number;
|
||||
unitClass: string;
|
||||
}
|
||||
|
||||
/** Payload shape from ptf_reinforcements: [poolId, count, unitClass]. */
|
||||
export function parseReinforcementPayload(raw: unknown): ReinforcementDelta | null {
|
||||
if (!Array.isArray(raw) || raw.length < 2) return null;
|
||||
const poolId =
|
||||
typeof raw[0] === "number" ? Math.trunc(raw[0]) : Number.parseInt(String(raw[0]), 10);
|
||||
if (!Number.isInteger(poolId) || poolId <= 0) return null;
|
||||
const count = typeof raw[1] === "number" ? Math.trunc(raw[1]) : 0;
|
||||
if (!Number.isInteger(count) || count <= 0) return null;
|
||||
const unitClass = typeof raw[2] === "string" ? raw[2].slice(0, 128) : "";
|
||||
return { poolId, count, unitClass };
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one `reinforcement.spawn` / `reinforcement.refund` event to the
|
||||
* pool balance (spawn subtracts, refund adds, no floor at zero). Never
|
||||
* throws: a malformed payload or unknown pool is logged and skipped, and the
|
||||
* game's next pull corrects its displayed value.
|
||||
*/
|
||||
export async function processReinforcementEvent(
|
||||
payload: Payload,
|
||||
raw: { eventId: string; type: string; payload: unknown },
|
||||
req?: PayloadRequest,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const isSpawn = raw.type === "reinforcement.spawn";
|
||||
const isRefund = raw.type === "reinforcement.refund";
|
||||
if (!isSpawn && !isRefund) return;
|
||||
|
||||
const delta = parseReinforcementPayload(raw.payload);
|
||||
if (!delta) {
|
||||
payload.logger.warn(
|
||||
`[Reinforcements] ${raw.type} event ${raw.eventId} has a malformed payload; skipping`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let pool: ReinforcementPool | null = null;
|
||||
try {
|
||||
pool = await payload.findByID({
|
||||
collection: "reinforcement-pools",
|
||||
id: delta.poolId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
} catch {
|
||||
pool = null;
|
||||
}
|
||||
if (!pool) {
|
||||
payload.logger.warn(
|
||||
`[Reinforcements] ${raw.type} event ${raw.eventId} references unknown pool ${delta.poolId}; skipping`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const before = pool.available ?? 0;
|
||||
// Soft limits: overdraft is allowed, so no floor at zero.
|
||||
const after = isSpawn ? before - delta.count : before + delta.count;
|
||||
|
||||
const headers = new Headers(req?.headers);
|
||||
headers.set(REINFORCEMENT_SYSTEM_HEADER, "1");
|
||||
await payload.update({
|
||||
collection: "reinforcement-pools",
|
||||
id: pool.id,
|
||||
data: { available: after },
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
// Pass the marker through the local API req so the collection's
|
||||
// afterChange hook skips its manual-edit audit for this write.
|
||||
req: { headers } as Partial<PayloadRequest>,
|
||||
});
|
||||
|
||||
await emitGameEvent(payload, {
|
||||
type: isSpawn ? EventTypes.ReinforcementSpawn : EventTypes.ReinforcementRefund,
|
||||
message: isSpawn
|
||||
? `Zeus spawn spent ${delta.count} from reinforcement pool "${pool.name}"${
|
||||
delta.unitClass ? ` (${delta.unitClass})` : ""
|
||||
}: ${before} -> ${after}`
|
||||
: `Curator deletion refunded ${delta.count} to reinforcement pool "${pool.name}"${
|
||||
delta.unitClass ? ` (${delta.unitClass})` : ""
|
||||
}: ${before} -> ${after}`,
|
||||
targetCollection: "reinforcement-pools",
|
||||
targetId: pool.id,
|
||||
data: {
|
||||
eventId: raw.eventId,
|
||||
poolId: pool.id,
|
||||
name: pool.name,
|
||||
count: delta.count,
|
||||
unitClass: delta.unitClass,
|
||||
availableBefore: before,
|
||||
availableAfter: after,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
payload.logger.error(`[Reinforcements] Failed to apply event ${raw.eventId}: ${err}`);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,30 +1,14 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { ExternalLinkIcon, XIcon } from "lucide-react";
|
||||
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* Renders a dialogue string for display. Newlines are preserved and a tiny
|
||||
* inline markup subset is honoured, freely NESTABLE (markup accumulates):
|
||||
*
|
||||
* **bold**, *italic*, `code`
|
||||
* {green}colored{/} or {#ff00ff} — wraps bold/italic/images/links inside it
|
||||
*  inline images at text height (http(s) or site-relative URLs)
|
||||
* [label](url) links opening in an in-page popup frame (same-origin pages
|
||||
* stay put; no navigation, so conversation progress survives)
|
||||
* {cd|<iso|done>} countdown leaf produced by `{{countdown:key}}` resolution
|
||||
*
|
||||
* Shared by the admin flow editor previews and the frontend conversation
|
||||
* dialog, so it must stay client-safe (no Payload imports).
|
||||
* Renders a dialogue string for display: newlines are preserved and a tiny
|
||||
* inline markup subset is honoured (**bold**, *italic*, `code`, and
|
||||
* {color}text{/}). Colors take a friendly name ({red}, {cyan}, ...) or a hex
|
||||
* code ({#ff00ff}). Shared by the admin flow editor previews and the frontend
|
||||
* conversation dialog, so it must stay client-safe (no Payload imports).
|
||||
*/
|
||||
export function DialogueText({ text, className }: { text: string; className?: string }) {
|
||||
return (
|
||||
<span className={`whitespace-pre-wrap ${className ?? ""}`}>
|
||||
{parseSegment(text, 0, { i: 0 }, false).nodes}
|
||||
</span>
|
||||
);
|
||||
return <span className={`whitespace-pre-wrap ${className ?? ""}`}>{renderInline(text)}</span>;
|
||||
}
|
||||
|
||||
/** Friendly color names mapped to Tailwind text classes (400 shades read well
|
||||
|
|
@ -48,293 +32,60 @@ const FRIENDLY_COLORS: Record<string, string> = {
|
|||
|
||||
const HEX_COLOR = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
|
||||
|
||||
/** Guards against pathological nesting like `**{red}**{red}**...`. */
|
||||
const MAX_DEPTH = 8;
|
||||
const INLINE_PATTERN =
|
||||
/(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\{(?:#[0-9a-fA-F]{3,6}|[a-zA-Z]+)\}[^{}]*\{\/\})/g;
|
||||
|
||||
const IMG_RE = /^!\[([^\]]*)\]\(([^()\s]*)\)/;
|
||||
const LINK_RE = /^\[([^\]]*)\]\(([^()\s]*)\)/;
|
||||
const COLOR_OPEN_RE = /^\{([^{}|]{1,20})\}/;
|
||||
const COUNTDOWN_RE = /^\{cd\|([^}]*)\}/;
|
||||
/** Matches one colour token produced by INLINE_PATTERN. */
|
||||
const COLOR_TOKEN = /^\{(#?[a-zA-Z0-9#]+)\}([^{}]*)\{\/\}$/;
|
||||
|
||||
/** Only http(s) and site-relative URLs render; anything else stays literal. */
|
||||
function safeUrl(url: string): string | null {
|
||||
if (/^https?:\/\//i.test(url)) return url;
|
||||
if (url.startsWith("/") && !url.startsWith("//")) return url;
|
||||
return null;
|
||||
}
|
||||
|
||||
interface ParseResult {
|
||||
nodes: ReactNode[];
|
||||
/** True when the segment ended at a `{/}` (consumed by the caller's color). */
|
||||
closed: boolean;
|
||||
/** Characters consumed, including the closing `{/}` when closed. */
|
||||
consumed: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans `text` left to right, turning markup runs into elements and recursing
|
||||
* into their contents so styling accumulates (a bold run inside a color span
|
||||
* keeps both). When `insideColor` is set, scanning stops at the matching
|
||||
* `{/}` so nested colors close inner-first.
|
||||
*/
|
||||
function parseSegment(text: string, depth: number, keys: { i: number }, insideColor: boolean): ParseResult {
|
||||
const nodes: ReactNode[] = [];
|
||||
let plain = "";
|
||||
let i = 0;
|
||||
const key = () => `${depth}:${keys.i++}`;
|
||||
const flush = () => {
|
||||
if (plain) {
|
||||
nodes.push(plain);
|
||||
plain = "";
|
||||
function renderInline(text: string): ReactNode {
|
||||
const parts = text.split(INLINE_PATTERN);
|
||||
return parts.map((part, index) => {
|
||||
if (part.length > 4 && part.startsWith("**") && part.endsWith("**")) {
|
||||
return (
|
||||
<strong key={index} className="font-semibold">
|
||||
{part.slice(2, -2)}
|
||||
</strong>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
while (i < text.length) {
|
||||
const rest = text.slice(i);
|
||||
|
||||
if (insideColor && rest.startsWith("{/}")) {
|
||||
flush();
|
||||
return { nodes, closed: true, consumed: i + 3 };
|
||||
if (part.length > 2 && part.startsWith("*") && part.endsWith("*")) {
|
||||
return <em key={index}>{part.slice(1, -1)}</em>;
|
||||
}
|
||||
|
||||
if (depth < MAX_DEPTH) {
|
||||
// Inline code (literal content, no nesting).
|
||||
if (rest[0] === "`") {
|
||||
const end = rest.indexOf("`", 1);
|
||||
if (end > 1) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<code
|
||||
key={key()}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
{rest.slice(1, end)}
|
||||
</code>,
|
||||
);
|
||||
i += end + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Countdown leaf.
|
||||
const cd = COUNTDOWN_RE.exec(rest);
|
||||
if (cd) {
|
||||
flush();
|
||||
nodes.push(<Countdown key={key()} value={cd[1]} />);
|
||||
i += cd[0].length;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Image (leaf).
|
||||
if (rest.startsWith("![")) {
|
||||
const img = IMG_RE.exec(rest);
|
||||
if (img) {
|
||||
const src = safeUrl(img[2]);
|
||||
if (src) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<img
|
||||
key={key()}
|
||||
src={src}
|
||||
alt={img[1]}
|
||||
className="mx-0.5 inline-block h-[1.15em] w-auto align-[-0.2em] object-contain"
|
||||
/>,
|
||||
);
|
||||
i += img[0].length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Link: label keeps its own markup; the popup frame preserves context.
|
||||
if (rest[0] === "[") {
|
||||
const link = LINK_RE.exec(rest);
|
||||
if (link) {
|
||||
const href = safeUrl(link[2]);
|
||||
if (href) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<DialogueLink key={key()} href={href}>
|
||||
{parseSegment(link[1], depth + 1, keys, false).nodes}
|
||||
</DialogueLink>,
|
||||
);
|
||||
i += link[0].length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Color run: recurse so inner markup renders inside the colored span.
|
||||
if (rest[0] === "{") {
|
||||
const open = COLOR_OPEN_RE.exec(rest);
|
||||
if (open && open[1] !== "/") {
|
||||
const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true);
|
||||
const style = colorStyle(open[1]);
|
||||
if (inner.closed && style) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<span key={key()} className={style.className} style={style.style}>
|
||||
{inner.nodes}
|
||||
</span>,
|
||||
);
|
||||
i += open[0].length + inner.consumed;
|
||||
continue;
|
||||
}
|
||||
// Unknown token or unclosed: fall through and render literally.
|
||||
}
|
||||
}
|
||||
|
||||
// Bold, then italic (bold checked first so `**` never reads as two stars).
|
||||
if (rest.startsWith("**")) {
|
||||
const end = rest.indexOf("**", 2);
|
||||
if (end > 2) {
|
||||
flush();
|
||||
nodes.push(
|
||||
<strong key={key()} className="font-semibold">
|
||||
{parseSegment(rest.slice(2, end), depth + 1, keys, false).nodes}
|
||||
</strong>,
|
||||
);
|
||||
i += end + 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (rest[0] === "*" && rest[1] !== "*") {
|
||||
const end = rest.indexOf("*", 1);
|
||||
if (end > 1 && rest[end + 1] !== "*") {
|
||||
flush();
|
||||
nodes.push(
|
||||
<em key={key()}>
|
||||
{parseSegment(rest.slice(1, end), depth + 1, keys, false).nodes}
|
||||
</em>,
|
||||
);
|
||||
i += end + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
plain += text[i];
|
||||
i += 1;
|
||||
}
|
||||
|
||||
flush();
|
||||
return { nodes, closed: false, consumed: text.length };
|
||||
}
|
||||
|
||||
/** Resolves a color token to a className or inline style; null = not a color. */
|
||||
function colorStyle(token: string): { className?: string; style?: { color: string } } | null {
|
||||
if (token.startsWith("#")) {
|
||||
// Only well-formed hex codes reach the style attribute; anything else
|
||||
// (e.g. {#12345}) renders as literal text.
|
||||
return HEX_COLOR.test(token) ? { style: { color: token } } : null;
|
||||
}
|
||||
const cls = FRIENDLY_COLORS[token.toLowerCase()];
|
||||
return cls ? { className: cls } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A dialogue link. Clicking opens the destination in a popup frame instead of
|
||||
* navigating, so the conversation (and its progress) stays mounted behind it.
|
||||
*/
|
||||
function DialogueLink({ href, children }: { href: string; children: ReactNode }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<a
|
||||
href={href}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
setOpen(true);
|
||||
}}
|
||||
className="font-medium text-cyan-400 underline decoration-cyan-500/40 underline-offset-2 transition-colors hover:text-cyan-300"
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next) setOpen(false);
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
className="flex h-[85vh] w-[92vw] max-w-6xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white sm:max-w-6xl"
|
||||
if (part.length > 2 && part.startsWith("`") && part.endsWith("`")) {
|
||||
return (
|
||||
<code
|
||||
key={index}
|
||||
className="rounded-sm bg-white/10 px-1 py-0.5 font-mono text-[0.85em] text-cyan-300"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-4 border-b border-white/15 bg-black/50 px-4 py-2 backdrop-blur-sm">
|
||||
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
|
||||
Attachment // {href.slice(0, 96)}
|
||||
</DialogTitle>
|
||||
<div className="flex shrink-0 items-center gap-3">
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
|
||||
>
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
Open in new tab
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(false)}
|
||||
aria-label="Close attachment"
|
||||
className="text-white/40 transition-colors hover:text-white/90"
|
||||
>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<iframe
|
||||
src={href}
|
||||
title="Dialogue link"
|
||||
className="min-h-0 flex-1 bg-zinc-900"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Formats a countdown duration: `2d 07h`, `7h 05m`, `12m 03s`, `9s`. */
|
||||
export function formatRemaining(ms: number): string {
|
||||
const total = Math.max(0, Math.floor(ms / 1000));
|
||||
const days = Math.floor(total / 86400);
|
||||
const hours = Math.floor((total % 86400) / 3600);
|
||||
const minutes = Math.floor((total % 3600) / 60);
|
||||
const seconds = total % 60;
|
||||
if (days > 0) return `${days}d ${hours}h`;
|
||||
if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m`;
|
||||
if (minutes > 0) return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live countdown leaf. Value is an ISO activation time (ticks every second),
|
||||
* `done` (the flag already activated), or empty (flag missing: renders
|
||||
* nothing). Ticks client-side from the mount-time clock.
|
||||
*/
|
||||
function Countdown({ value }: { value: string }) {
|
||||
const target = value === "done" || value === "" ? null : Date.parse(value);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
if (target === null || Number.isNaN(target)) return;
|
||||
const timer = setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [target]);
|
||||
|
||||
if (value === "done") return <span className="font-mono text-emerald-400">ready</span>;
|
||||
if (value === "") return null;
|
||||
if (target === null || Number.isNaN(target)) return null;
|
||||
|
||||
const remaining = target - now;
|
||||
if (remaining <= 0) return <span className="font-mono text-emerald-400">ready</span>;
|
||||
return (
|
||||
<span
|
||||
className="font-mono tabular-nums text-cyan-300"
|
||||
title={new Date(target).toISOString()}
|
||||
>
|
||||
{formatRemaining(remaining)}
|
||||
</span>
|
||||
);
|
||||
{part.slice(1, -1)}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
const colorMatch = part.match(COLOR_TOKEN);
|
||||
if (colorMatch) {
|
||||
const token = colorMatch[1];
|
||||
const inner = colorMatch[2];
|
||||
if (token.startsWith("#")) {
|
||||
// Only well-formed hex codes reach the style attribute; anything else
|
||||
// (e.g. {#12345}) renders as literal text.
|
||||
if (HEX_COLOR.test(token)) {
|
||||
return (
|
||||
<span key={index} style={{ color: token }}>
|
||||
{inner}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <span key={index}>{part}</span>;
|
||||
}
|
||||
const cls = FRIENDLY_COLORS[token.toLowerCase()];
|
||||
if (cls) {
|
||||
return (
|
||||
<span key={index} className={cls}>
|
||||
{inner}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
return <span key={index}>{part}</span>;
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,32 +27,12 @@ export interface DialogueNext {
|
|||
* `dlg-once:` player flag).
|
||||
*/
|
||||
once?: boolean;
|
||||
/**
|
||||
* Choice hops only: optional rich tooltip shown when the player hovers or
|
||||
* focuses the choice button. Supports the same inline markup as dialogue
|
||||
* lines (colors, bold, images) plus `{{flag}}` interpolation.
|
||||
*/
|
||||
tooltip?: string;
|
||||
/**
|
||||
* Choice hops only: when set, the choice button is only offered to players
|
||||
* whose live flags satisfy this condition (evaluated server-side, same
|
||||
* flag semantics as condition nodes). Missing key = ungated.
|
||||
*/
|
||||
condition?: DialogueCondition;
|
||||
/**
|
||||
* Choice hops only: when the condition fails, show the choice disabled
|
||||
* with this rich tooltip explaining why (supports markup + {{flags}})
|
||||
* instead of hiding it. Empty/missing keeps the hide-when-failed behavior.
|
||||
*/
|
||||
lockedHint?: string;
|
||||
}
|
||||
|
||||
/** Server-resolved visibility state for one gated choice. */
|
||||
export interface ChoiceGate {
|
||||
/** True while the player's flags satisfy the choice condition. */
|
||||
pass: boolean;
|
||||
/** True when a failing choice should still render, locked, with its hint. */
|
||||
showLocked: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -72,19 +52,8 @@ export interface DialogueCondition {
|
|||
amount?: number;
|
||||
}
|
||||
|
||||
/** All condition operators, in UI order. */
|
||||
export const CONDITION_OPS: DialogueCondition["op"][] = [
|
||||
"is_true",
|
||||
"is_false",
|
||||
"gte",
|
||||
"lte",
|
||||
"gt",
|
||||
"lt",
|
||||
"eq",
|
||||
];
|
||||
|
||||
/** How a flag effect writes the flag. */
|
||||
export type DialogueFlagOp = "set_true" | "set_false" | "set_number" | "set_text" | "add";
|
||||
export type DialogueFlagOp = "set_true" | "set_false" | "set_number" | "add";
|
||||
|
||||
/** Configured effect for an `event` node. */
|
||||
export interface NpcDialogueEffect {
|
||||
|
|
@ -99,14 +68,6 @@ export interface NpcDialogueEffect {
|
|||
flagOp?: DialogueFlagOp;
|
||||
/** Value for set_number / addend for add (flag). */
|
||||
flagAmount?: number;
|
||||
/** Value for set_text (flag). May contain display markup, e.g. {green}OK{/}. */
|
||||
flagText?: string;
|
||||
/**
|
||||
* Flag effects only: delay the write's effect this many minutes by stamping
|
||||
* the flag with `activatesAt = now + N`. Conditions read it as false until
|
||||
* then, and `{{countdown:key}}` tokens tick down to it.
|
||||
*/
|
||||
flagDelayMinutes?: number;
|
||||
}
|
||||
|
||||
export type DialogueNodeData = {
|
||||
|
|
|
|||
|
|
@ -1,148 +0,0 @@
|
|||
/**
|
||||
* Server-side flag reads for NPC conversations. Shared by the conversation
|
||||
* runtime actions and the contact page's conversation picker so condition
|
||||
* semantics never drift apart.
|
||||
*/
|
||||
|
||||
import type { Payload } from "payload";
|
||||
import type { DialogueCondition } from "./dialogue";
|
||||
|
||||
/** Effective value of a flag for reading + interpolation. */
|
||||
export interface FlagValues {
|
||||
bool: boolean;
|
||||
num: number;
|
||||
text: string;
|
||||
/** True when a non-expired flag document exists (even if not yet active). */
|
||||
exists: boolean;
|
||||
/**
|
||||
* When the flag is time-gated and not yet active, its ISO activation time
|
||||
* (so `{{countdown:key}}` tokens can tick toward it). Undefined otherwise.
|
||||
*/
|
||||
activatesAt?: string;
|
||||
}
|
||||
|
||||
/** True when the doc's activation window covers now (missing bounds = open). */
|
||||
function activeNow(
|
||||
doc: { activatesAt?: string | null; expiresAt?: string | null },
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
if (doc.activatesAt) {
|
||||
const t = Date.parse(doc.activatesAt);
|
||||
if (!Number.isNaN(t) && t > now) return false;
|
||||
}
|
||||
if (doc.expiresAt) {
|
||||
const t = Date.parse(doc.expiresAt);
|
||||
if (!Number.isNaN(t) && t <= now) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** True while the doc has an activation time strictly in the future. */
|
||||
function pendingActivation(
|
||||
doc: { activatesAt?: string | null },
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
if (!doc.activatesAt) return false;
|
||||
const t = Date.parse(doc.activatesAt);
|
||||
return !Number.isNaN(t) && t > now;
|
||||
}
|
||||
|
||||
/** The inactive read value, carrying the countdown target when pending. */
|
||||
function inactiveValues(doc: { activatesAt?: string | null }, now = Date.now()): FlagValues {
|
||||
return pendingActivation(doc, now)
|
||||
? { bool: false, num: 0, text: "", exists: true, activatesAt: doc.activatesAt ?? undefined }
|
||||
: { bool: false, num: 0, text: "", exists: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Effective value of a flag: player-specific entry takes priority; if absent,
|
||||
* fall back to the global entry (user is null). Missing flags read false / 0 /
|
||||
* empty. `text` is the string the flag contributes to interpolated dialogue
|
||||
* (booleans render "true"/"false", numbers their digits, text flags verbatim).
|
||||
* Time windows apply: a not-yet-active flag reads as false (and reports its
|
||||
* `activatesAt` for countdowns); an expired flag reads as missing and falls
|
||||
* through to the global fallback.
|
||||
*/
|
||||
export async function readFlag(
|
||||
payload: Payload,
|
||||
userId: number,
|
||||
key: string,
|
||||
): Promise<FlagValues> {
|
||||
// Player-specific flag (priority).
|
||||
const playerRes = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: {
|
||||
user: { equals: userId },
|
||||
key: { equals: key },
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const playerDoc = playerRes.docs[0];
|
||||
if (playerDoc) {
|
||||
if (!activeNow(playerDoc)) return inactiveValues(playerDoc);
|
||||
return flagValues(playerDoc);
|
||||
}
|
||||
|
||||
// Global fallback (user is null).
|
||||
const globalRes = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: {
|
||||
user: { equals: null },
|
||||
key: { equals: key },
|
||||
},
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const globalDoc = globalRes.docs[0];
|
||||
if (!globalDoc) return { bool: false, num: 0, text: "", exists: false };
|
||||
if (!activeNow(globalDoc)) return inactiveValues(globalDoc);
|
||||
return flagValues(globalDoc);
|
||||
}
|
||||
|
||||
/** Reads a stored flag doc into its condition + interpolation values. */
|
||||
export function flagValues(doc: {
|
||||
flagType: "boolean" | "number" | "text";
|
||||
boolValue?: boolean | null;
|
||||
numberValue?: number | null;
|
||||
textValue?: string | null;
|
||||
}): FlagValues {
|
||||
if (doc.flagType === "number") {
|
||||
const num = doc.numberValue ?? 0;
|
||||
return { bool: num !== 0, num, text: String(num), exists: true };
|
||||
}
|
||||
if (doc.flagType === "text") {
|
||||
const text = doc.textValue ?? "";
|
||||
return { bool: text.trim().length > 0, num: 0, text, exists: true };
|
||||
}
|
||||
const bool = doc.boolValue === true;
|
||||
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false", exists: true };
|
||||
}
|
||||
|
||||
/** Evaluates one authored condition against the user's live flags. */
|
||||
export async function evaluateCondition(
|
||||
payload: Payload,
|
||||
userId: number,
|
||||
condition: DialogueCondition,
|
||||
): Promise<boolean> {
|
||||
const flag = await readFlag(payload, userId, condition.key);
|
||||
const amount = condition.amount ?? 0;
|
||||
switch (condition.op) {
|
||||
case "is_true":
|
||||
return flag.bool;
|
||||
case "is_false":
|
||||
return !flag.bool;
|
||||
case "gte":
|
||||
return flag.num >= amount;
|
||||
case "lte":
|
||||
return flag.num <= amount;
|
||||
case "gt":
|
||||
return flag.num > amount;
|
||||
case "lt":
|
||||
return flag.num < amount;
|
||||
case "eq":
|
||||
return flag.num === amount;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,164 +0,0 @@
|
|||
/**
|
||||
* Dynamic text interpolation for NPC conversation strings.
|
||||
*
|
||||
* Authors embed flag values with double-brace tokens: `{{network_status}}`.
|
||||
* Resolution happens server-side when a conversation line is about to render
|
||||
* (see the `resolveNpcDialogueTexts` action), so an interpolated value may
|
||||
* itself contain display markup like `{green}NOMINAL{/}` and still render
|
||||
* colored through DialogueText. Values are substituted in a single pass and
|
||||
* never re-scanned, so a flag value can never smuggle in another token.
|
||||
*
|
||||
* Pure module: client-safe (no Payload imports).
|
||||
*/
|
||||
|
||||
import type { DialogueNode } from "./dialogue";
|
||||
|
||||
/** One `{{key}}` token. Keys are matched leniently and lowercased; flag keys
|
||||
* are documented as lowercase-with-underscores. */
|
||||
const FLAG_TOKEN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g;
|
||||
|
||||
/**
|
||||
* One `{{countdown:key}}` token: a live timer ticking toward the flag's
|
||||
* activation time. Server-side resolution rewrites it to the internal
|
||||
* `{cd|<iso|done|>}` leaf that DialogueText renders as a ticking span.
|
||||
*/
|
||||
const COUNTDOWN_TOKEN = /\{\{countdown:\s*([a-zA-Z0-9_]+)\s*\}\}/g;
|
||||
|
||||
/** Every distinct countdown key referenced by `text`, lowercased. */
|
||||
export function extractCountdownKeys(text: string | undefined): string[] {
|
||||
if (!text) return [];
|
||||
const keys = new Set<string>();
|
||||
for (const match of text.matchAll(COUNTDOWN_TOKEN)) {
|
||||
keys.add(match[1].toLowerCase());
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace every `{{countdown:key}}` token with its `{cd|value}` leaf.
|
||||
* Values: an ISO activation time (pending), "done" (flag active), or empty
|
||||
* (flag missing, renders nothing).
|
||||
*/
|
||||
export function replaceCountdowns(
|
||||
text: string | undefined,
|
||||
countdowns: Record<string, string>,
|
||||
): string {
|
||||
if (!text) return "";
|
||||
return text.replace(COUNTDOWN_TOKEN, (_match, key: string) => `{cd|${countdowns[key.toLowerCase()] ?? ""}}`);
|
||||
}
|
||||
|
||||
/** The display strings of a node that support interpolation. */
|
||||
export interface ResolvedNodeTexts {
|
||||
body?: string;
|
||||
leadIn?: string;
|
||||
closing?: string;
|
||||
/** Event node narration fallback (`effect.message`). */
|
||||
message?: string;
|
||||
/** Choice button labels, index-aligned with the node's choices. */
|
||||
labels?: string[];
|
||||
/** Choice tooltips, index-aligned with the node's choices. */
|
||||
tooltips?: string[];
|
||||
/** Locked-choice hints, index-aligned with the node's choices. */
|
||||
hints?: string[];
|
||||
}
|
||||
|
||||
/** Every distinct flag key referenced by `text`, lowercased. */
|
||||
export function extractFlagTokens(text: string | undefined): string[] {
|
||||
if (!text) return [];
|
||||
const keys = new Set<string>();
|
||||
for (const match of text.matchAll(FLAG_TOKEN)) {
|
||||
keys.add(match[1].toLowerCase());
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
/** True when `text` contains at least one interpolation token. */
|
||||
export function hasFlagTokens(text: string | undefined): boolean {
|
||||
if (!text) return false;
|
||||
FLAG_TOKEN.lastIndex = 0;
|
||||
return FLAG_TOKEN.test(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace every `{{key}}` token with its value. Keys missing from `values`
|
||||
* resolve to an empty string; substituted values are NOT re-scanned.
|
||||
*/
|
||||
export function interpolateFlags(
|
||||
text: string | undefined,
|
||||
values: Record<string, string>,
|
||||
): string {
|
||||
if (!text) return "";
|
||||
return text.replace(FLAG_TOKEN, (_match, key: string) => values[key.toLowerCase()] ?? "");
|
||||
}
|
||||
|
||||
/** Minimal shape needed to format a flag's value for interpolation. */
|
||||
export interface FlagValueLike {
|
||||
flagType: "boolean" | "number" | "text";
|
||||
boolValue?: boolean | null;
|
||||
numberValue?: number | null;
|
||||
textValue?: string | null;
|
||||
}
|
||||
|
||||
/** The string a flag contributes to interpolated text. */
|
||||
export function formatFlagValue(flag: FlagValueLike): string {
|
||||
switch (flag.flagType) {
|
||||
case "number":
|
||||
return String(flag.numberValue ?? 0);
|
||||
case "text":
|
||||
return flag.textValue ?? "";
|
||||
default:
|
||||
return flag.boolValue === true ? "true" : "false";
|
||||
}
|
||||
}
|
||||
|
||||
/** All flag keys the node's display strings reference (deduped, lowercased).
|
||||
* Countdown (`{{countdown:key}}`) keys join this set too: they need the same
|
||||
* server-side flag read to resolve their activation time. */
|
||||
export function collectNodeTokens(node: DialogueNode): string[] {
|
||||
const keys = new Set<string>();
|
||||
const texts = [
|
||||
node.data.body,
|
||||
node.data.leadIn,
|
||||
node.data.closing,
|
||||
node.data.effect?.message,
|
||||
...(node.data.choices?.flatMap((c) => [c.label, c.tooltip, c.lockedHint]) ?? []),
|
||||
];
|
||||
for (const text of texts) {
|
||||
for (const key of extractFlagTokens(text)) keys.add(key);
|
||||
for (const key of extractCountdownKeys(text)) keys.add(key);
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
/**
|
||||
* Interpolates every display string of a node against resolved flag values.
|
||||
* Only fields the node actually defines are returned, so the client can tell
|
||||
* "resolved to empty" apart from "no such field".
|
||||
*/
|
||||
export function resolveNodeTexts(
|
||||
node: DialogueNode,
|
||||
values: Record<string, string>,
|
||||
countdowns: Record<string, string> = {},
|
||||
): ResolvedNodeTexts {
|
||||
const finish = (text: string | undefined): string =>
|
||||
replaceCountdowns(interpolateFlags(text, values), countdowns);
|
||||
const resolved: ResolvedNodeTexts = {};
|
||||
if (node.data.body !== undefined) resolved.body = finish(node.data.body);
|
||||
if (node.data.leadIn !== undefined) resolved.leadIn = finish(node.data.leadIn);
|
||||
if (node.data.closing !== undefined) resolved.closing = finish(node.data.closing);
|
||||
if (node.data.effect?.message !== undefined) resolved.message = finish(node.data.effect.message);
|
||||
if (node.data.choices) {
|
||||
resolved.labels = node.data.choices.map((choice) => finish(choice.label));
|
||||
if (node.data.choices.some((choice) => choice.tooltip !== undefined)) {
|
||||
resolved.tooltips = node.data.choices.map((choice) =>
|
||||
choice.tooltip === undefined ? "" : finish(choice.tooltip),
|
||||
);
|
||||
}
|
||||
if (node.data.choices.some((choice) => choice.lockedHint !== undefined)) {
|
||||
resolved.hints = node.data.choices.map((choice) =>
|
||||
choice.lockedHint === undefined ? "" : finish(choice.lockedHint),
|
||||
);
|
||||
}
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
/**
|
||||
* Per-browser conversation progress tracking that powers the "NEW" badges.
|
||||
*
|
||||
* For each conversation (npc-dialogues id) we remember a hash of its
|
||||
* flowchart plus the node ids this browser has read. The Converse button
|
||||
* shows a badge when the flow changed (GM added paths -> new hash) or when
|
||||
* nodes remain unread; choice buttons badge their unseen targets. Stored in
|
||||
* localStorage like the tour/announcement dismissals: no server state, and a
|
||||
* fresh device rediscovers every path once. Pure module, client-safe.
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = "ptf:npc-dialogue-seen";
|
||||
|
||||
export interface SeenEntry {
|
||||
/** flowHash of the flowchart these node ids belong to. */
|
||||
hash: string;
|
||||
/** Node ids rendered at least once. */
|
||||
nodes: string[];
|
||||
}
|
||||
|
||||
export type SeenMap = Record<string, SeenEntry>;
|
||||
|
||||
/** Deterministic djb2 hash of the flowchart's CONTENT (base36). Node
|
||||
* positions and edge plumbing (ids, handles, styling) are excluded on
|
||||
* purpose: rearranging the canvas is not a story change and must not
|
||||
* re-badge conversations as NEW. Object keys are sorted so an equivalent
|
||||
* document serialized with a different key order hashes the same. */
|
||||
export function flowHash(flowData: unknown): string {
|
||||
const json = stableStringify(contentOnly(flowData));
|
||||
let h = 5381;
|
||||
for (let i = 0; i < json.length; i += 1) {
|
||||
h = ((h << 5) + h + json.charCodeAt(i)) | 0;
|
||||
}
|
||||
return (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
/** Strips layout from a flowchart, keeping node identity/branching/text. */
|
||||
function contentOnly(flowData: unknown): unknown {
|
||||
const doc = (flowData ?? {}) as { nodes?: unknown; edges?: unknown };
|
||||
const nodes = Array.isArray(doc.nodes) ? doc.nodes : [];
|
||||
const edges = Array.isArray(doc.edges) ? doc.edges : [];
|
||||
return {
|
||||
nodes: nodes.map((node) => {
|
||||
const n = (node ?? {}) as { id?: unknown; type?: unknown; data?: unknown };
|
||||
return { id: n.id, type: n.type, data: n.data };
|
||||
}),
|
||||
edges: edges.map((edge) => {
|
||||
const e = (edge ?? {}) as { source?: unknown; target?: unknown };
|
||||
return { source: e.source, target: e.target };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** JSON.stringify with sorted object keys for order-independent hashing. */
|
||||
function stableStringify(value: unknown): string {
|
||||
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
||||
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
||||
const entries = Object.entries(value as Record<string, unknown>)
|
||||
.filter(([, v]) => v !== undefined)
|
||||
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
|
||||
}
|
||||
|
||||
/** Reads the seen map; corrupt or absent storage reads empty. */
|
||||
export function loadSeenMap(): SeenMap {
|
||||
if (typeof window === "undefined") return {};
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return {};
|
||||
const parsed = JSON.parse(raw) as SeenMap;
|
||||
return parsed && typeof parsed === "object" ? parsed : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** Persists the seen map; storage failures (private mode) are ignored. */
|
||||
export function saveSeenMap(map: SeenMap): void {
|
||||
if (typeof window === "undefined") return;
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
|
||||
} catch {
|
||||
// Best effort only.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Node ids from `nodeIds` this browser has not read yet. A missing entry or a
|
||||
* hash mismatch (the GM edited the flowchart) counts everything as unseen.
|
||||
*/
|
||||
export function unseenNodeIds(
|
||||
entry: SeenEntry | undefined,
|
||||
hash: string,
|
||||
nodeIds: readonly string[],
|
||||
): string[] {
|
||||
if (!entry || entry.hash !== hash) return [...nodeIds];
|
||||
const seen = new Set(entry.nodes);
|
||||
return nodeIds.filter((id) => !seen.has(id));
|
||||
}
|
||||
|
||||
/** Returns the updated node list for one conversation (deduped, sorted-free). */
|
||||
export function mergeSeenNodes(entry: SeenEntry | undefined, hash: string, nodeId: string): string[] {
|
||||
const nodes = entry && entry.hash === hash ? [...entry.nodes] : [];
|
||||
if (!nodes.includes(nodeId)) nodes.push(nodeId);
|
||||
return nodes;
|
||||
}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
/**
|
||||
* Conversation selection when an NPC has multiple conversations.
|
||||
*
|
||||
* Each conversation may declare an entry gate (a flag condition evaluated
|
||||
* against the reading player) and a priority. The offer order is priority
|
||||
* descending, oldest first; the first conversation whose gate passes wins.
|
||||
* An empty gate key always passes, which makes ungated conversations the
|
||||
* natural fallback. Pure module: the caller injects the condition evaluator
|
||||
* so this stays testable and client-safe.
|
||||
*/
|
||||
|
||||
import type { DialogueCondition } from "./dialogue";
|
||||
|
||||
/** The stored entry gate shape on an npc-dialogues document. */
|
||||
export interface DialogueEntryGate {
|
||||
key?: string | null;
|
||||
op?: DialogueCondition["op"] | null;
|
||||
amount?: number | null;
|
||||
}
|
||||
|
||||
/** Minimal candidate shape the selector reads from a conversation doc. */
|
||||
export interface GateCandidate {
|
||||
id: number;
|
||||
priority?: number | null;
|
||||
entryGate?: DialogueEntryGate | null;
|
||||
}
|
||||
|
||||
/** Turns a stored gate into a runtime condition; null when ungated. */
|
||||
export function gateCondition(gate: DialogueEntryGate | null | undefined): DialogueCondition | null {
|
||||
const key = gate?.key?.trim();
|
||||
if (!key || !gate) return null;
|
||||
return { kind: "flag", key, op: gate.op ?? "is_true", amount: gate.amount ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the conversation to offer: highest priority first (ties break by
|
||||
* oldest id), gated conversations skipped unless `evaluate` passes their
|
||||
* condition. Returns null when every candidate is gated shut.
|
||||
*/
|
||||
export async function selectDialogueForUser<T extends GateCandidate>(
|
||||
docs: readonly T[],
|
||||
evaluate: (condition: DialogueCondition) => Promise<boolean>,
|
||||
): Promise<T | null> {
|
||||
const ordered = [...docs].sort(
|
||||
(a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id - b.id,
|
||||
);
|
||||
for (const doc of ordered) {
|
||||
const condition = gateCondition(doc.entryGate);
|
||||
if (!condition) return doc;
|
||||
if (await evaluate(condition)) return doc;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -43,20 +43,12 @@ async function ticketById(payload: Payload, ticketId: number): Promise<Ticket> {
|
|||
if (!Number.isInteger(ticketId) || ticketId <= 0) {
|
||||
throw new Error("Ticket not found.");
|
||||
}
|
||||
const ticket = (await payload
|
||||
.findByID({
|
||||
collection: "tickets",
|
||||
id: ticketId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => null)) as Ticket | null;
|
||||
// Archived tickets are invisible to the front-end; treat them as missing so
|
||||
// stale links cannot be edited or voted on.
|
||||
if (!ticket || ticket.archived) {
|
||||
throw new Error("Ticket not found.");
|
||||
}
|
||||
return ticket;
|
||||
return payload.findByID({
|
||||
collection: "tickets",
|
||||
id: ticketId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
|
||||
function snapshotOf(ticket: Ticket): TicketEditSnapshot {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@
|
|||
* UI style maps. Single source of truth used by the collection, server actions,
|
||||
* and the frontend.
|
||||
*/
|
||||
import type { Where } from "payload";
|
||||
|
||||
export const TICKET_STATUSES = [
|
||||
{ label: "Open", value: "open" },
|
||||
|
|
@ -85,16 +84,6 @@ export const CLOSING_STATUSES: readonly TicketStatus[] = [
|
|||
"closed",
|
||||
];
|
||||
|
||||
/**
|
||||
* Where-clause fragment excluding archived tickets. Archived tickets are
|
||||
* hidden from every front-end surface for all users (staff included) and stay
|
||||
* accessible only through the Payload admin panel. Combine with other
|
||||
* conditions via `and: [...]`.
|
||||
*/
|
||||
export const NON_ARCHIVED_WHERE: Where = {
|
||||
archived: { not_equals: true },
|
||||
};
|
||||
|
||||
/** Badge color classes per status, keyed for use with the shadcn `Badge` component. */
|
||||
export const STATUS_STYLES: Record<TicketStatus, string> = {
|
||||
open: "bg-sky-500/15 text-sky-400 border-sky-500/30",
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,18 +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 TYPE "public"."enum_player_flags_flag_type" ADD VALUE 'text';
|
||||
ALTER TABLE "player_flags" ADD COLUMN "text_value" varchar;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "player_flags" ALTER COLUMN "flag_type" SET DATA TYPE text;
|
||||
ALTER TABLE "player_flags" ALTER COLUMN "flag_type" SET DEFAULT 'boolean'::text;
|
||||
DROP TYPE "public"."enum_player_flags_flag_type";
|
||||
CREATE TYPE "public"."enum_player_flags_flag_type" AS ENUM('boolean', 'number');
|
||||
ALTER TABLE "player_flags" ALTER COLUMN "flag_type" SET DEFAULT 'boolean'::"public"."enum_player_flags_flag_type";
|
||||
ALTER TABLE "player_flags" ALTER COLUMN "flag_type" SET DATA TYPE "public"."enum_player_flags_flag_type" USING "flag_type"::"public"."enum_player_flags_flag_type";
|
||||
ALTER TABLE "player_flags" DROP COLUMN "text_value";`)
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,19 +0,0 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TYPE "public"."enum_npc_dialogues_entry_gate_op" AS ENUM('is_true', 'is_false', 'gte', 'lte', 'gt', 'lt', 'eq');
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "priority" numeric DEFAULT 0;
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "entry_gate_key" varchar;
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "entry_gate_op" "enum_npc_dialogues_entry_gate_op" DEFAULT 'is_true';
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "entry_gate_amount" numeric;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "priority";
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "entry_gate_key";
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "entry_gate_op";
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "entry_gate_amount";
|
||||
DROP TYPE "public"."enum_npc_dialogues_entry_gate_op";`)
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,13 +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 "player_flags" ADD COLUMN "activates_at" timestamp(3) with time zone;
|
||||
ALTER TABLE "player_flags" ADD COLUMN "expires_at" timestamp(3) with time zone;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "player_flags" DROP COLUMN "activates_at";
|
||||
ALTER TABLE "player_flags" DROP COLUMN "expires_at";`)
|
||||
}
|
||||
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
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load diff
|
|
@ -1,13 +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 "tickets" ADD COLUMN "archived" boolean DEFAULT false;
|
||||
ALTER TABLE "tickets" ADD COLUMN "archived_at" timestamp(3) with time zone;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "tickets" DROP COLUMN "archived";
|
||||
ALTER TABLE "tickets" DROP COLUMN "archived_at";`)
|
||||
}
|
||||
|
|
@ -109,12 +109,6 @@ import * as migration_20261005_063613_add_game_npc_image from './20261005_063613
|
|||
import * as migration_20261005_185014_add_player_flags from './20261005_185014_add_player_flags';
|
||||
import * as migration_20261006_000000_add_npc_dialogue_and_activity_fields from './20261006_000000_add_npc_dialogue_and_activity_fields';
|
||||
import * as migration_20261006_155244_add_global_flag_support from './20261006_155244_add_global_flag_support';
|
||||
import * as migration_20261006_195605_add_text_flag_type from './20261006_195605_add_text_flag_type';
|
||||
import * as migration_20261006_203217_add_dialogue_entry_gate from './20261006_203217_add_dialogue_entry_gate';
|
||||
import * as migration_20261006_205845_add_flag_time_windows from './20261006_205845_add_flag_time_windows';
|
||||
import * as migration_20261007_025942_add_event_log_visibility from './20261007_025942_add_event_log_visibility';
|
||||
import * as migration_20261007_040914_add_reinforcement_pools from './20261007_040914_add_reinforcement_pools';
|
||||
import * as migration_20261007_044017_add_ticket_archival from './20261007_044017_add_ticket_archival';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -670,36 +664,6 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261006_155244_add_global_flag_support.up,
|
||||
down: migration_20261006_155244_add_global_flag_support.down,
|
||||
name: '20261006_155244_add_global_flag_support',
|
||||
},
|
||||
{
|
||||
up: migration_20261006_195605_add_text_flag_type.up,
|
||||
down: migration_20261006_195605_add_text_flag_type.down,
|
||||
name: '20261006_195605_add_text_flag_type',
|
||||
},
|
||||
{
|
||||
up: migration_20261006_203217_add_dialogue_entry_gate.up,
|
||||
down: migration_20261006_203217_add_dialogue_entry_gate.down,
|
||||
name: '20261006_203217_add_dialogue_entry_gate',
|
||||
},
|
||||
{
|
||||
up: migration_20261006_205845_add_flag_time_windows.up,
|
||||
down: migration_20261006_205845_add_flag_time_windows.down,
|
||||
name: '20261006_205845_add_flag_time_windows',
|
||||
},
|
||||
{
|
||||
up: migration_20261007_025942_add_event_log_visibility.up,
|
||||
down: migration_20261007_025942_add_event_log_visibility.down,
|
||||
name: '20261007_025942_add_event_log_visibility',
|
||||
},
|
||||
{
|
||||
up: migration_20261007_040914_add_reinforcement_pools.up,
|
||||
down: migration_20261007_040914_add_reinforcement_pools.down,
|
||||
name: '20261007_040914_add_reinforcement_pools',
|
||||
},
|
||||
{
|
||||
up: migration_20261007_044017_add_ticket_archival.up,
|
||||
down: migration_20261007_044017_add_ticket_archival.down,
|
||||
name: '20261007_044017_add_ticket_archival'
|
||||
name: '20261006_155244_add_global_flag_support'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -77,7 +77,6 @@ export interface Config {
|
|||
'npc-staffing': NpcStaffing;
|
||||
'npc-dialogues': NpcDialogue;
|
||||
'player-flags': PlayerFlag;
|
||||
'reinforcement-pools': ReinforcementPool;
|
||||
'labor-classifications': LaborClassification;
|
||||
'game-event-logs': GameEventLog;
|
||||
users: User;
|
||||
|
|
@ -177,7 +176,6 @@ export interface Config {
|
|||
'npc-staffing': NpcStaffingSelect<false> | NpcStaffingSelect<true>;
|
||||
'npc-dialogues': NpcDialoguesSelect<false> | NpcDialoguesSelect<true>;
|
||||
'player-flags': PlayerFlagsSelect<false> | PlayerFlagsSelect<true>;
|
||||
'reinforcement-pools': ReinforcementPoolsSelect<false> | ReinforcementPoolsSelect<true>;
|
||||
'labor-classifications': LaborClassificationsSelect<false> | LaborClassificationsSelect<true>;
|
||||
'game-event-logs': GameEventLogsSelect<false> | GameEventLogsSelect<true>;
|
||||
users: UsersSelect<false> | UsersSelect<true>;
|
||||
|
|
@ -800,11 +798,6 @@ export interface Role {
|
|||
| 'game-event-logs:update'
|
||||
| 'game-event-logs:delete'
|
||||
| 'admin:game-event-logs:manage'
|
||||
| 'reinforcement-pools:create'
|
||||
| 'reinforcement-pools:read'
|
||||
| 'reinforcement-pools:update'
|
||||
| 'reinforcement-pools:delete'
|
||||
| 'admin:reinforcement-pools:manage'
|
||||
| 'maps:create'
|
||||
| 'maps:read'
|
||||
| 'maps:update'
|
||||
|
|
@ -2533,27 +2526,6 @@ export interface NpcDialogue {
|
|||
* The contact this conversation belongs to.
|
||||
*/
|
||||
npc: number | GameNpc;
|
||||
/**
|
||||
* When a contact has several conversations, the highest-priority one whose entry gate passes is the one offered. Ties break by oldest first.
|
||||
*/
|
||||
priority?: number | null;
|
||||
/**
|
||||
* Only offer this conversation to players whose flags pass this condition. Leave the key empty to always offer it (ungated conversations are the fallback).
|
||||
*/
|
||||
entryGate?: {
|
||||
/**
|
||||
* player-flags key checked for the reading player. Player-specific flag takes priority; falls back to global. Missing = false / 0.
|
||||
*/
|
||||
key?: string | null;
|
||||
/**
|
||||
* Comparison applied to the flag's effective value.
|
||||
*/
|
||||
op?: ('is_true' | 'is_false' | 'gte' | 'lte' | 'gt' | 'lt' | 'eq') | null;
|
||||
/**
|
||||
* Right-hand side for the numeric comparisons.
|
||||
*/
|
||||
amount?: number | null;
|
||||
};
|
||||
flowData:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
|
|
@ -2581,9 +2553,9 @@ export interface PlayerFlag {
|
|||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Boolean flags read as true/false; numeric flags track statistics; text flags carry a string that conversations can interpolate with {{key}}.
|
||||
* Boolean flags read as true/false; numeric flags track statistics.
|
||||
*/
|
||||
flagType: 'boolean' | 'number' | 'text';
|
||||
flagType: 'boolean' | 'number';
|
||||
/**
|
||||
* A missing boolean flag counts as false.
|
||||
*/
|
||||
|
|
@ -2592,47 +2564,6 @@ export interface PlayerFlag {
|
|||
* A missing numeric flag counts as 0.
|
||||
*/
|
||||
numberValue?: number | null;
|
||||
/**
|
||||
* Inserted into conversation text wherever {{key}} appears. May contain dialogue markup like {green}NOMINAL{/}. A missing text flag reads as empty.
|
||||
*/
|
||||
textValue?: string | null;
|
||||
/**
|
||||
* Time-gated narrative: until this moment the flag reads as false / 0 / empty (conditions fail, {{countdown:key}} ticks). Leave empty for immediate.
|
||||
*/
|
||||
activatesAt?: string | null;
|
||||
/**
|
||||
* After this moment the flag reads as missing again (falls back to a global flag of the same key, else false / 0 / empty). Use for offers and windows that lapse.
|
||||
*/
|
||||
expiresAt?: string | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "reinforcement-pools".
|
||||
*/
|
||||
export interface ReinforcementPool {
|
||||
id: number;
|
||||
/**
|
||||
* Pool name shown on the in-game Zeus HUD (e.g. 'PTF').
|
||||
*/
|
||||
name: string;
|
||||
/**
|
||||
* Optional web-app faction this pool belongs to. Grouping only; in-game attribution uses the Arma faction classes below.
|
||||
*/
|
||||
faction?: (number | null) | Faction;
|
||||
/**
|
||||
* Arma CfgVehicles faction classes counted by this pool (e.g. 'BLU_F', 'PTF'). Matched case-insensitively against the placed unit's faction; units of unmatched factions are free.
|
||||
*/
|
||||
armaFactions?: string[] | null;
|
||||
/**
|
||||
* Units available. Decremented by counted Zeus placements, refunded on curator deletions. May go negative (overdraft is allowed; spawning is never blocked).
|
||||
*/
|
||||
available?: number | null;
|
||||
/**
|
||||
* Disabled pools are hidden from the game server and the Zeus HUD.
|
||||
*/
|
||||
enabled?: boolean | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -2646,362 +2577,6 @@ export interface GameEventLog {
|
|||
* System-generated events are created automatically. Uncheck for manual/GM narrative entries.
|
||||
*/
|
||||
system?: boolean | null;
|
||||
/**
|
||||
* Public events are visible to every logged-in user. Restricted events additionally require one of the required permissions below (or event-log staff / superuser status; the actor always sees their own events).
|
||||
*/
|
||||
visibility: 'public' | 'restricted';
|
||||
/**
|
||||
* Any-of gate: a user holding ANY one of these permissions sees this event. Leave empty to hide it from everyone except event-log staff, superusers, and the actor.
|
||||
*/
|
||||
requiredPermissions?:
|
||||
| (
|
||||
| 'system:admin-access'
|
||||
| 'media:create'
|
||||
| 'media:read'
|
||||
| 'media:update'
|
||||
| 'media:delete'
|
||||
| 'admin:media:manage'
|
||||
| 'users:create'
|
||||
| 'users:read'
|
||||
| 'users:update'
|
||||
| 'users:delete'
|
||||
| 'users:unlock'
|
||||
| 'users:assign-roles'
|
||||
| 'admin:users:manage'
|
||||
| 'roles:create'
|
||||
| 'roles:read'
|
||||
| 'roles:update'
|
||||
| 'roles:delete'
|
||||
| 'admin:roles:manage'
|
||||
| 'ranks:create'
|
||||
| 'ranks:read'
|
||||
| 'ranks:update'
|
||||
| 'ranks:delete'
|
||||
| 'admin:ranks:manage'
|
||||
| 'profiles:create'
|
||||
| 'profiles:read'
|
||||
| 'profiles:update'
|
||||
| 'profiles:delete'
|
||||
| 'admin:profiles:manage'
|
||||
| 'awards:create'
|
||||
| 'awards:read'
|
||||
| 'awards:update'
|
||||
| 'awards:delete'
|
||||
| 'admin:awards:manage'
|
||||
| 'qualifications:create'
|
||||
| 'qualifications:read'
|
||||
| 'qualifications:update'
|
||||
| 'qualifications:delete'
|
||||
| 'admin:qualifications:manage'
|
||||
| 'assignments:create'
|
||||
| 'assignments:read'
|
||||
| 'assignments:update'
|
||||
| 'assignments:delete'
|
||||
| 'admin:assignments:manage'
|
||||
| 'assignment-transfers:create'
|
||||
| 'assignment-transfers:read'
|
||||
| 'assignment-transfers:update'
|
||||
| 'assignment-transfers:delete'
|
||||
| 'admin:assignment-transfers:manage'
|
||||
| 'experience:create'
|
||||
| 'experience:read'
|
||||
| 'experience:update'
|
||||
| 'experience:delete'
|
||||
| 'admin:experience:manage'
|
||||
| 'user-notifications:create'
|
||||
| 'user-notifications:read'
|
||||
| 'user-notifications:update'
|
||||
| 'user-notifications:delete'
|
||||
| 'admin:user-notifications:manage'
|
||||
| 'evaluations:create'
|
||||
| 'evaluations:read'
|
||||
| 'evaluations:update'
|
||||
| 'evaluations:delete'
|
||||
| 'admin:evaluations:manage'
|
||||
| 'missions:create'
|
||||
| 'missions:read'
|
||||
| 'missions:update'
|
||||
| 'missions:delete'
|
||||
| 'missions:read-sensitive'
|
||||
| 'admin:missions:manage'
|
||||
| 'mission-attendances:create'
|
||||
| 'mission-attendances:read'
|
||||
| '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'
|
||||
| 'mission-map-markers:create'
|
||||
| 'mission-map-markers:read'
|
||||
| 'mission-map-markers:update'
|
||||
| 'mission-map-markers:delete'
|
||||
| 'admin:mission-map-markers:manage'
|
||||
| 'campaigns:create'
|
||||
| 'campaigns:read'
|
||||
| 'campaigns:update'
|
||||
| 'campaigns:delete'
|
||||
| 'admin:campaigns:manage'
|
||||
| 'campaigns:manage'
|
||||
| 'factions:create'
|
||||
| 'factions:read'
|
||||
| 'factions:update'
|
||||
| 'factions:delete'
|
||||
| 'admin:factions:manage'
|
||||
| 'technologies:create'
|
||||
| 'technologies:read'
|
||||
| 'technologies:update'
|
||||
| 'technologies:delete'
|
||||
| 'admin:technologies:manage'
|
||||
| 'tech-categories:create'
|
||||
| 'tech-categories:read'
|
||||
| 'tech-categories:update'
|
||||
| 'tech-categories:delete'
|
||||
| 'admin:tech-categories:manage'
|
||||
| 'assets:create'
|
||||
| 'assets:read'
|
||||
| 'assets:update'
|
||||
| 'assets:delete'
|
||||
| 'admin:assets:manage'
|
||||
| 'resources:create'
|
||||
| 'resources:read'
|
||||
| 'resources:update'
|
||||
| 'resources:delete'
|
||||
| 'admin:resources:manage'
|
||||
| 'vehicles:create'
|
||||
| 'vehicles:read'
|
||||
| 'vehicles:update'
|
||||
| 'vehicles:delete'
|
||||
| 'admin:vehicles:manage'
|
||||
| 'structures:create'
|
||||
| 'structures:read'
|
||||
| 'structures:update'
|
||||
| 'structures:delete'
|
||||
| 'admin:structures:manage'
|
||||
| 'shipments:create'
|
||||
| 'shipments:read'
|
||||
| 'shipments:update'
|
||||
| 'shipments:delete'
|
||||
| 'admin:shipments:manage'
|
||||
| 'bank-accounts:create'
|
||||
| 'bank-accounts:read'
|
||||
| 'bank-accounts:update'
|
||||
| 'bank-accounts:delete'
|
||||
| 'admin:bank-accounts:manage'
|
||||
| 'bank-transactions:create'
|
||||
| 'bank-transactions:read'
|
||||
| 'bank-transactions:update'
|
||||
| 'bank-transactions:delete'
|
||||
| 'admin:bank-transactions:manage'
|
||||
| 'ledger-entries:create'
|
||||
| 'ledger-entries:read'
|
||||
| 'ledger-entries:update'
|
||||
| 'ledger-entries:delete'
|
||||
| 'admin:ledger-entries:manage'
|
||||
| 'locker-storages:create'
|
||||
| 'locker-storages:read'
|
||||
| 'locker-storages:update'
|
||||
| 'locker-storages:delete'
|
||||
| 'admin:locker-storages:manage'
|
||||
| 'loadouts:create'
|
||||
| 'loadouts:read'
|
||||
| 'loadouts:update'
|
||||
| 'loadouts:delete'
|
||||
| 'admin:loadouts:manage'
|
||||
| 'market-listings:create'
|
||||
| 'market-listings:read'
|
||||
| 'market-listings:update'
|
||||
| 'market-listings:delete'
|
||||
| 'admin:market-listings:manage'
|
||||
| 'market-negotiations:create'
|
||||
| 'market-negotiations:read'
|
||||
| 'market-negotiations:update'
|
||||
| 'market-negotiations:delete'
|
||||
| 'admin:market-negotiations:manage'
|
||||
| 'market-state:create'
|
||||
| 'market-state:read'
|
||||
| 'market-state:update'
|
||||
| 'market-state:delete'
|
||||
| 'admin:market-state:manage'
|
||||
| 'projects:create'
|
||||
| 'projects:read'
|
||||
| 'projects:update'
|
||||
| 'projects:delete'
|
||||
| 'admin:projects:manage'
|
||||
| 'labels:create'
|
||||
| 'labels:read'
|
||||
| 'labels:update'
|
||||
| 'labels:delete'
|
||||
| 'admin:labels:manage'
|
||||
| 'sprints:create'
|
||||
| 'sprints:read'
|
||||
| 'sprints:update'
|
||||
| 'sprints:delete'
|
||||
| 'admin:sprints:manage'
|
||||
| 'releases:create'
|
||||
| 'releases:read'
|
||||
| 'releases:update'
|
||||
| 'releases:delete'
|
||||
| 'admin:releases:manage'
|
||||
| 'tickets:create'
|
||||
| 'tickets:read'
|
||||
| 'tickets:update'
|
||||
| 'tickets:delete'
|
||||
| 'admin:tickets:manage'
|
||||
| 'ticket-votes:create'
|
||||
| 'ticket-votes:read'
|
||||
| 'ticket-votes:update'
|
||||
| 'ticket-votes:delete'
|
||||
| 'admin:ticket-votes:manage'
|
||||
| 'game-structures:create'
|
||||
| 'game-structures:read'
|
||||
| 'game-structures:update'
|
||||
| 'game-structures:delete'
|
||||
| 'admin:game-structures:manage'
|
||||
| 'game-vehicles:create'
|
||||
| 'game-vehicles:read'
|
||||
| 'game-vehicles:update'
|
||||
| 'game-vehicles:delete'
|
||||
| 'admin:game-vehicles:manage'
|
||||
| 'game-npcs:create'
|
||||
| 'game-npcs:read'
|
||||
| 'game-npcs:update'
|
||||
| 'game-npcs:delete'
|
||||
| 'admin:game-npcs:manage'
|
||||
| 'game-hard-resources:create'
|
||||
| 'game-hard-resources:read'
|
||||
| 'game-hard-resources:update'
|
||||
| 'game-hard-resources:delete'
|
||||
| 'admin:game-hard-resources:manage'
|
||||
| 'game-event-logs:create'
|
||||
| 'game-event-logs:read'
|
||||
| 'game-event-logs:update'
|
||||
| 'game-event-logs:delete'
|
||||
| 'admin:game-event-logs:manage'
|
||||
| 'reinforcement-pools:create'
|
||||
| 'reinforcement-pools:read'
|
||||
| 'reinforcement-pools:update'
|
||||
| 'reinforcement-pools:delete'
|
||||
| 'admin:reinforcement-pools:manage'
|
||||
| 'maps:create'
|
||||
| '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'
|
||||
| 'narrative-events:update'
|
||||
| 'narrative-events:delete'
|
||||
| 'admin:narrative-events:manage'
|
||||
| 'npc-dialogues:create'
|
||||
| 'npc-dialogues:read'
|
||||
| 'npc-dialogues:update'
|
||||
| 'npc-dialogues:delete'
|
||||
| 'admin:npc-dialogues:manage'
|
||||
| 'player-flags:create'
|
||||
| 'player-flags:read'
|
||||
| 'player-flags:update'
|
||||
| 'player-flags:delete'
|
||||
| 'admin:player-flags:manage'
|
||||
| 'mission-files:create'
|
||||
| 'mission-files:read'
|
||||
| 'mission-files:update'
|
||||
| 'mission-files:delete'
|
||||
| 'admin:mission-files:manage'
|
||||
| 'mod-lists:create'
|
||||
| 'mod-lists:read'
|
||||
| 'mod-lists:update'
|
||||
| 'mod-lists:delete'
|
||||
| 'admin:mod-lists:manage'
|
||||
| 'respawn-tickets:create'
|
||||
| 'respawn-tickets:read'
|
||||
| 'respawn-tickets:update'
|
||||
| 'respawn-tickets:delete'
|
||||
| 'admin:respawn-tickets:manage'
|
||||
| 'game-servers:create'
|
||||
| 'game-servers:read'
|
||||
| 'game-servers:update'
|
||||
| 'game-servers:delete'
|
||||
| 'admin:game-servers:manage'
|
||||
| 'arma-sync-events:create'
|
||||
| 'arma-sync-events:read'
|
||||
| 'arma-sync-events:update'
|
||||
| 'arma-sync-events:delete'
|
||||
| 'admin:arma-sync-events:manage'
|
||||
| 'arma-commands:create'
|
||||
| 'arma-commands:read'
|
||||
| 'arma-commands:update'
|
||||
| 'arma-commands:delete'
|
||||
| 'admin:arma-commands:manage'
|
||||
| 'operation-events:create'
|
||||
| 'operation-events:read'
|
||||
| 'operation-events:update'
|
||||
| 'operation-events:delete'
|
||||
| 'admin:operation-events:manage'
|
||||
| 'operation-effects:create'
|
||||
| 'operation-effects:read'
|
||||
| 'operation-effects:update'
|
||||
| 'operation-effects:delete'
|
||||
| 'admin:operation-effects:manage'
|
||||
| 'operation-reservations:create'
|
||||
| 'operation-reservations:read'
|
||||
| 'operation-reservations:update'
|
||||
| 'operation-reservations:delete'
|
||||
| 'admin:operation-reservations:manage'
|
||||
| 'operation-readiness:create'
|
||||
| 'operation-readiness:read'
|
||||
| 'operation-readiness:update'
|
||||
| 'operation-readiness:delete'
|
||||
| 'admin:operation-readiness:manage'
|
||||
| 'zone-pressure:create'
|
||||
| 'zone-pressure:read'
|
||||
| 'zone-pressure:update'
|
||||
| 'zone-pressure:delete'
|
||||
| 'admin:zone-pressure:manage'
|
||||
| 'announcements:create'
|
||||
| 'announcements:read'
|
||||
| 'announcements:update'
|
||||
| 'announcements:delete'
|
||||
| 'admin:announcements:manage'
|
||||
| 'forms:create'
|
||||
| 'forms:read'
|
||||
| 'forms:update'
|
||||
| 'forms:delete'
|
||||
| 'form-submissions:read'
|
||||
| 'form-submissions:delete'
|
||||
| 'admin:forms:manage'
|
||||
| 'admin:form-submissions:manage'
|
||||
| 'game-rules:read'
|
||||
| 'game-rules:update'
|
||||
| 'shims:read'
|
||||
| 'shims:update'
|
||||
| 'logistics:manage'
|
||||
| 'intelligence:manage'
|
||||
| 'profiles:intel_excerpt:update'
|
||||
| 'banking:manage'
|
||||
| 'tickets:staff'
|
||||
| 'discord:staff'
|
||||
| 'discord:announce'
|
||||
| 'custom-minefields:update'
|
||||
| 'custom-minefields:delete'
|
||||
| 'custom-minefield-scores:delete'
|
||||
| 'custom-radio-tests:update'
|
||||
| 'custom-radio-tests:delete'
|
||||
| 'custom-radio-test-scores:delete'
|
||||
)[]
|
||||
| null;
|
||||
timestamp: string;
|
||||
type: string;
|
||||
message: string;
|
||||
|
|
@ -3053,8 +2628,6 @@ export interface GameEventLog {
|
|||
| 'ribbon-submissions'
|
||||
| 'promotion-nominations'
|
||||
| 'leadership-transfers'
|
||||
| 'player-flags'
|
||||
| 'reinforcement-pools'
|
||||
)
|
||||
| null;
|
||||
targetId?: number | null;
|
||||
|
|
@ -4760,14 +4333,6 @@ export interface Ticket {
|
|||
* Set automatically when the ticket reaches a closing status.
|
||||
*/
|
||||
closedAt?: string | null;
|
||||
/**
|
||||
* Archived tickets are hidden from the front-end for everyone (staff included) and remain accessible only here in the admin panel. Uncheck to restore the ticket.
|
||||
*/
|
||||
archived?: boolean | null;
|
||||
/**
|
||||
* Set automatically when the ticket is archived.
|
||||
*/
|
||||
archivedAt?: string | null;
|
||||
/**
|
||||
* Project this ticket belongs to. Null = standalone/backlog.
|
||||
*/
|
||||
|
|
@ -6269,24 +5834,6 @@ export interface PayloadMcpApiKey {
|
|||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
reinforcementPools?: {
|
||||
/**
|
||||
* Allow clients to find reinforcement-pools.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create reinforcement-pools.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update reinforcement-pools.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete reinforcement-pools.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
laborClassifications?: {
|
||||
/**
|
||||
* Allow clients to find labor-classifications.
|
||||
|
|
@ -7650,10 +7197,6 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'player-flags';
|
||||
value: number | PlayerFlag;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'reinforcement-pools';
|
||||
value: number | ReinforcementPool;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'labor-classifications';
|
||||
value: number | LaborClassification;
|
||||
|
|
@ -8289,14 +7832,6 @@ export interface NpcStaffingSelect<T extends boolean = true> {
|
|||
export interface NpcDialoguesSelect<T extends boolean = true> {
|
||||
name?: T;
|
||||
npc?: T;
|
||||
priority?: T;
|
||||
entryGate?:
|
||||
| T
|
||||
| {
|
||||
key?: T;
|
||||
op?: T;
|
||||
amount?: T;
|
||||
};
|
||||
flowData?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
|
|
@ -8311,22 +7846,6 @@ export interface PlayerFlagsSelect<T extends boolean = true> {
|
|||
flagType?: T;
|
||||
boolValue?: T;
|
||||
numberValue?: T;
|
||||
textValue?: T;
|
||||
activatesAt?: T;
|
||||
expiresAt?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "reinforcement-pools_select".
|
||||
*/
|
||||
export interface ReinforcementPoolsSelect<T extends boolean = true> {
|
||||
name?: T;
|
||||
faction?: T;
|
||||
armaFactions?: T;
|
||||
available?: T;
|
||||
enabled?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
|
|
@ -8350,8 +7869,6 @@ export interface LaborClassificationsSelect<T extends boolean = true> {
|
|||
*/
|
||||
export interface GameEventLogsSelect<T extends boolean = true> {
|
||||
system?: T;
|
||||
visibility?: T;
|
||||
requiredPermissions?: T;
|
||||
timestamp?: T;
|
||||
type?: T;
|
||||
message?: T;
|
||||
|
|
@ -9701,8 +9218,6 @@ export interface TicketsSelect<T extends boolean = true> {
|
|||
id?: T;
|
||||
};
|
||||
closedAt?: T;
|
||||
archived?: T;
|
||||
archivedAt?: T;
|
||||
project?: T;
|
||||
sprint?: T;
|
||||
release?: T;
|
||||
|
|
@ -10568,14 +10083,6 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
|||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
reinforcementPools?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
laborClassifications?:
|
||||
| T
|
||||
| {
|
||||
|
|
|
|||
|
|
@ -56,7 +56,6 @@ import { GameNpcs } from "@/collections/game/GameNpcs";
|
|||
import { NpcStaffing } from "@/collections/game/NpcStaffing";
|
||||
import { NpcDialogues } from "@/collections/game/NpcDialogues";
|
||||
import { PlayerFlags } from "@/collections/game/PlayerFlags";
|
||||
import { ReinforcementPools } from "@/collections/game/ReinforcementPools";
|
||||
import { LaborClassifications } from "@/collections/game/LaborClassifications";
|
||||
import { Experience } from "@/collections/users/Experience";
|
||||
import { BankAccounts } from "@/collections/banking/BankAccounts";
|
||||
|
|
@ -273,7 +272,6 @@ const collections = [
|
|||
NpcStaffing,
|
||||
NpcDialogues,
|
||||
PlayerFlags,
|
||||
ReinforcementPools,
|
||||
LaborClassifications,
|
||||
GameEventLogs,
|
||||
|
||||
|
|
|
|||
|
|
@ -501,16 +501,6 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
|||
{ value: "admin:game-event-logs:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Reinforcement Pools",
|
||||
permissions: [
|
||||
{ value: "reinforcement-pools:create", label: "Create" },
|
||||
{ value: "reinforcement-pools:read", label: "Read" },
|
||||
{ value: "reinforcement-pools:update", label: "Update" },
|
||||
{ value: "reinforcement-pools:delete", label: "Delete" },
|
||||
{ value: "admin:reinforcement-pools:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
|
||||
// ---- World ---------------------------------------------------------------
|
||||
{
|
||||
|
|
@ -994,11 +984,6 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
|
|||
"game-event-logs:update",
|
||||
"game-event-logs:delete",
|
||||
"admin:game-event-logs:manage",
|
||||
"reinforcement-pools:create",
|
||||
"reinforcement-pools:read",
|
||||
"reinforcement-pools:update",
|
||||
"reinforcement-pools:delete",
|
||||
"admin:reinforcement-pools:manage",
|
||||
"maps:create",
|
||||
"maps:read",
|
||||
"maps:update",
|
||||
|
|
|
|||
|
|
@ -40,10 +40,7 @@ Read-permission visibility check (`missions:read` / `campaigns:read` / `factions
|
|||
## Event log system
|
||||
|
||||
### Emitter: `emitGameEvent(payload, { type, message, ... })`
|
||||
Fire-and-forget create on `game-event-logs`. Always sets `system: true`. Silent error catch (no throw). Always called AFTER successful mutation in server actions. Stamps `visibility` + `requiredPermissions` from the policy map (see below); callers may override per event.
|
||||
|
||||
### Visibility policies: `visibility.ts`
|
||||
`EVENT_VISIBILITY_POLICIES` maps event types to defaults (`public`, or `restricted` with an any-of `requiredPermissions` gate); `resolveEventVisibility(type, override)` merges per-emit overrides with independent fallbacks. Restricted today: `npc:dialogue`, `flag:set`. The `game-event-logs` read access turns this into a Where clause (public OR required-permission OR actor-is-me; staff/superusers see all). Local API consumers must pass `user` + `overrideAccess: false` to respect it.
|
||||
Fire-and-forget create on `game-event-logs`. Always sets `system: true`. Silent error catch (no throw). Always called AFTER successful mutation in server actions.
|
||||
|
||||
### Event types: `EventTypes` constants (~105 types across 15+ categories)
|
||||
Defined in `eventTypes.ts`. Use these constants for TypeScript narrowing on the `type` field. Categories include: `mission:*`, `finance:*`, `market:*`, `structure:*`, `staff:*`, `logistics:*`, `bank:*`, `notification:*`, `locker:*`, `xp:*`, `ticket:*`, `wiki:*`, `minigame:*`, `attendance:*`, `system:*`.
|
||||
|
|
@ -57,7 +54,6 @@ Defined in `eventTypes.ts`. Use these constants for TypeScript narrowing on the
|
|||
| Add new RBAC permission | `src/permissions/index.ts` + use in `hasPermission` calls |
|
||||
| Add qualification gate | `access-control/hasLogisticsQualification.ts` (or create similar) |
|
||||
| Add event type constant | `event-log/eventTypes.ts` (add to `EventTypes` object) |
|
||||
| Gate an event type's visibility | `event-log/visibility.ts` (`EVENT_VISIBILITY_POLICIES`) |
|
||||
| Emit event from action | `import { emitGameEvent } from "@/utils/event-log/emit"` |
|
||||
| Check qualification in layout | Use `hasLogisticsQualification(payload, user)` |
|
||||
| Modify XP calculation | `xp/resolveLevel.ts` |
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
import type { EventType } from "./eventTypes";
|
||||
import type { EventVisibility } from "./visibility";
|
||||
import { resolveEventVisibility } from "./visibility";
|
||||
import { broadcast } from "@/lib/realtime/bus";
|
||||
import type { Permission } from "@/permissions";
|
||||
|
||||
interface GameEventInput {
|
||||
type: EventType;
|
||||
|
|
@ -50,28 +47,15 @@ interface GameEventInput {
|
|||
| "custom-radio-test-scores"
|
||||
| "ribbon-submissions"
|
||||
| "promotion-nominations"
|
||||
| "leadership-transfers"
|
||||
| "player-flags"
|
||||
| "reinforcement-pools";
|
||||
| "leadership-transfers";
|
||||
targetId?: number;
|
||||
data?: Record<string, unknown>;
|
||||
/**
|
||||
* Override the per-type visibility default (see `EVENT_VISIBILITY_POLICIES`).
|
||||
* Omit to use the type's policy, which falls back to "public".
|
||||
*/
|
||||
visibility?: EventVisibility;
|
||||
/** Any-of permission gate for restricted events. See `visibility`. */
|
||||
requiredPermissions?: Permission[];
|
||||
}
|
||||
|
||||
export async function emitGameEvent(
|
||||
payload: Awaited<ReturnType<typeof import("payload").getPayload>>,
|
||||
event: GameEventInput,
|
||||
) {
|
||||
const policy = resolveEventVisibility(event.type, {
|
||||
visibility: event.visibility,
|
||||
requiredPermissions: event.requiredPermissions,
|
||||
});
|
||||
try {
|
||||
await payload.create({
|
||||
collection: "game-event-logs",
|
||||
|
|
@ -85,29 +69,18 @@ export async function emitGameEvent(
|
|||
targetCollection: event.targetCollection,
|
||||
targetId: event.targetId,
|
||||
structure: event.structure,
|
||||
visibility: policy.visibility,
|
||||
requiredPermissions: policy.requiredPermissions,
|
||||
},
|
||||
depth: 0,
|
||||
// Bins and tests run without an authenticated user; create access on
|
||||
// game-event-logs requires one, so system events would be silently dropped.
|
||||
overrideAccess: true,
|
||||
});
|
||||
// Public events broadcast their metadata; restricted events broadcast an
|
||||
// opaque nudge so the SSE stream itself never leaks who did what. The
|
||||
// client listener ignores the payload and refetches through access-
|
||||
// filtered queries anyway.
|
||||
broadcast(
|
||||
"game-event",
|
||||
policy.visibility === "restricted"
|
||||
? { restricted: true }
|
||||
: {
|
||||
type: event.type,
|
||||
actor: event.actor ?? null,
|
||||
targetCollection: event.targetCollection ?? null,
|
||||
targetId: event.targetId ?? null,
|
||||
},
|
||||
);
|
||||
broadcast("game-event", {
|
||||
type: event.type,
|
||||
actor: event.actor ?? null,
|
||||
targetCollection: event.targetCollection ?? null,
|
||||
targetId: event.targetId ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[EventLog] Failed to emit event:", err);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,9 +117,6 @@ export const EventTypes = {
|
|||
NpcGenerate: "npc:generate",
|
||||
NpcDialogue: "npc:dialogue",
|
||||
|
||||
// Flags
|
||||
FlagSet: "flag:set",
|
||||
|
||||
// Account
|
||||
AccountPasswordChange: "account:password-change",
|
||||
AccountProfileUpdate: "account:profile-update",
|
||||
|
|
@ -172,11 +169,6 @@ export const EventTypes = {
|
|||
PlayerKill: "combat:kill",
|
||||
PlayerDeath: "combat:death",
|
||||
|
||||
// Reinforcement pools (Arma Zeus soft limits)
|
||||
ReinforcementSpawn: "reinforcement:spawn",
|
||||
ReinforcementRefund: "reinforcement:refund",
|
||||
ReinforcementAdjust: "reinforcement:adjust",
|
||||
|
||||
// Helpdesk
|
||||
TicketCreate: "ticket:create",
|
||||
TicketReply: "ticket:reply",
|
||||
|
|
@ -185,7 +177,6 @@ export const EventTypes = {
|
|||
TicketEdit: "ticket:edit",
|
||||
TicketVote: "ticket:vote",
|
||||
TicketUnvote: "ticket:unvote",
|
||||
TicketArchive: "ticket:archive",
|
||||
|
||||
// Wiki
|
||||
WikiPageCreate: "wiki:page-create",
|
||||
|
|
|
|||
|
|
@ -1,66 +0,0 @@
|
|||
/**
|
||||
* Visibility policies for game events.
|
||||
*
|
||||
* Every `game-event-logs` document carries a `visibility` ("public" or
|
||||
* "restricted") plus an optional `requiredPermissions` list. Restricted
|
||||
* events are hidden from users who hold none of the required permissions
|
||||
* (superusers, event-log staff with `game-event-logs:update`, and the event's
|
||||
* actor always see them). The collection's read access enforces this.
|
||||
*
|
||||
* This module maps event TYPES to their default policy so emitters don't
|
||||
* repeat themselves; `emitGameEvent` stamps documents from it, and callers
|
||||
* may override per event. Pure module (type-only imports, client-safe).
|
||||
*/
|
||||
|
||||
import type { Permission } from "@/permissions";
|
||||
import { EventTypes, type EventType } from "./eventTypes";
|
||||
|
||||
export type EventVisibility = "public" | "restricted";
|
||||
|
||||
export interface EventVisibilityPolicy {
|
||||
visibility: EventVisibility;
|
||||
/**
|
||||
* Any-of gate for restricted events: a user holding ANY one of these
|
||||
* permissions sees the event. Empty on a restricted event means only
|
||||
* superusers, event-log staff, and the actor can see it.
|
||||
*/
|
||||
requiredPermissions?: Permission[];
|
||||
}
|
||||
|
||||
/** Default for every type not listed below: visible to all logged-in users. */
|
||||
export const PUBLIC_EVENT_VISIBILITY: EventVisibilityPolicy = { visibility: "public" };
|
||||
|
||||
/**
|
||||
* Per-type defaults applied by `emitGameEvent` when the caller does not
|
||||
* override. Narrative/state-leaking types belong here; routine game chatter
|
||||
* (minigame scores, Chronicle reads, market sales) stays public.
|
||||
*/
|
||||
export const EVENT_VISIBILITY_POLICIES: Partial<Record<EventType, EventVisibilityPolicy>> = {
|
||||
// Conversation effects (including flag writes triggered by dialogue) can
|
||||
// spoil narrative branches: gate them to conversation/flag authoring staff.
|
||||
[EventTypes.NpcDialogue]: {
|
||||
visibility: "restricted",
|
||||
requiredPermissions: ["npc-dialogues:read", "player-flags:read"],
|
||||
},
|
||||
// Direct player-flag edits (GM admin-panel surgery) are narrative state.
|
||||
[EventTypes.FlagSet]: {
|
||||
visibility: "restricted",
|
||||
requiredPermissions: ["player-flags:read"],
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve the effective policy for an event: per-type default, with optional
|
||||
* per-emit overrides. Each key falls back independently, so passing only a
|
||||
* `visibility` keeps the type's permission list and vice versa.
|
||||
*/
|
||||
export function resolveEventVisibility(
|
||||
type: EventType,
|
||||
override?: Partial<EventVisibilityPolicy>,
|
||||
): { visibility: EventVisibility; requiredPermissions: Permission[] } {
|
||||
const base = EVENT_VISIBILITY_POLICIES[type] ?? PUBLIC_EVENT_VISIBILITY;
|
||||
return {
|
||||
visibility: override?.visibility ?? base.visibility,
|
||||
requiredPermissions: override?.requiredPermissions ?? base.requiredPermissions ?? [],
|
||||
};
|
||||
}
|
||||
|
|
@ -59,20 +59,7 @@ async function findLockerApplyCommands(): Promise<{ id: number; payload: unknown
|
|||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
// Scope to this run's instances: other spec files leave game-servers online,
|
||||
// so their web-originated locker edits also enqueue locker.apply commands.
|
||||
// An unscoped count made this file order-dependent (25 foreign rows once
|
||||
// vitest's timing-based file order put those files first).
|
||||
return found.docs
|
||||
.filter((doc) => {
|
||||
const commandPayload = (doc as { payload?: unknown }).payload;
|
||||
const instanceRef = Array.isArray(commandPayload) ? commandPayload[0] : undefined;
|
||||
return (
|
||||
typeof instanceRef === "string" &&
|
||||
(instanceRef.includes(STEAM_ID) || instanceRef.includes(SLUG))
|
||||
);
|
||||
})
|
||||
.map((doc) => ({ id: doc.id, payload: (doc as { payload?: unknown }).payload }));
|
||||
return found.docs.map((doc) => ({ id: doc.id, payload: (doc as { payload?: unknown }).payload }));
|
||||
}
|
||||
|
||||
async function lockerDoc() {
|
||||
|
|
@ -313,10 +300,6 @@ describe("Arma locker sync", () => {
|
|||
},
|
||||
],
|
||||
} as never,
|
||||
// Fixture write, not an echo-guard test: suppress the locker.apply
|
||||
// enqueue so this file's absolute command counts stay stable even
|
||||
// when other spec files leave a game-server online.
|
||||
context: { lockerSyncOrigin: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,286 +0,0 @@
|
|||
import { getPayload, Payload, type Where } from "payload";
|
||||
import config from "@/payload.config";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import type { GameEventLog, Role, User } from "@/payload-types";
|
||||
import { GameEventLogs } from "@/collections/game/GameEventLogs";
|
||||
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { resolveEventVisibility } from "@/utils/event-log/visibility";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `evlogvis-${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
describe("event visibility policies (pure)", () => {
|
||||
it("defaults unlisted types to public with no gates", () => {
|
||||
expect(resolveEventVisibility(EventTypes.MinigameFlappy)).toEqual({
|
||||
visibility: "public",
|
||||
requiredPermissions: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("restricts dialogue events to conversation/flag authoring staff", () => {
|
||||
expect(resolveEventVisibility(EventTypes.NpcDialogue)).toEqual({
|
||||
visibility: "restricted",
|
||||
requiredPermissions: ["npc-dialogues:read", "player-flags:read"],
|
||||
});
|
||||
});
|
||||
|
||||
it("restricts flag:set events to flag readers", () => {
|
||||
expect(resolveEventVisibility(EventTypes.FlagSet)).toEqual({
|
||||
visibility: "restricted",
|
||||
requiredPermissions: ["player-flags:read"],
|
||||
});
|
||||
});
|
||||
|
||||
it("applies per-emit overrides with independent fallbacks", () => {
|
||||
// Visibility override keeps the type's permission list.
|
||||
expect(
|
||||
resolveEventVisibility(EventTypes.NpcDialogue, { visibility: "public" }).visibility,
|
||||
).toBe("public");
|
||||
expect(
|
||||
resolveEventVisibility(EventTypes.NpcDialogue, { visibility: "public" })
|
||||
.requiredPermissions,
|
||||
).toContain("player-flags:read");
|
||||
// Permission override keeps the type's visibility.
|
||||
expect(
|
||||
resolveEventVisibility(EventTypes.StoryBeatRead, {
|
||||
requiredPermissions: ["missions:read"],
|
||||
}),
|
||||
).toEqual({ visibility: "public", requiredPermissions: ["missions:read"] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("event visibility enforcement (database)", () => {
|
||||
const roleIds: number[] = [];
|
||||
const userIds: number[] = [];
|
||||
const eventIds: number[] = [];
|
||||
const flagIds: number[] = [];
|
||||
|
||||
let plainUser: User;
|
||||
let gateUser: User;
|
||||
let staffUser: User;
|
||||
let superUser: User;
|
||||
|
||||
/** Ids of events created by this suite, newest first. */
|
||||
const makeRole = async (label: string, extra: Partial<Role> = {}): Promise<Role> => {
|
||||
const role = (await payload.create({
|
||||
collection: "roles",
|
||||
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, ...extra },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Role;
|
||||
roleIds.push(role.id);
|
||||
return role;
|
||||
};
|
||||
|
||||
const makeUser = async (label: string, roleId: number): Promise<User> => {
|
||||
const user = (await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username: `${RUN}-${label}`,
|
||||
discordUsername: `${RUN}-${label}`,
|
||||
displayName: label.toUpperCase(),
|
||||
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
roleDocs: [roleId],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as User;
|
||||
userIds.push(user.id);
|
||||
return user;
|
||||
};
|
||||
|
||||
/** Emit an event and remember its id for cleanup. */
|
||||
const emit = async (
|
||||
input: Parameters<typeof emitGameEvent>[1],
|
||||
): Promise<GameEventLog> => {
|
||||
await emitGameEvent(payload, input);
|
||||
const res = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { message: { equals: input.message } },
|
||||
sort: "-id",
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
const doc = res.docs[0];
|
||||
expect(doc).toBeDefined();
|
||||
eventIds.push(doc.id);
|
||||
return doc;
|
||||
};
|
||||
|
||||
/** Event ids visible to `user` among the given ids (access-filtered find). */
|
||||
const visibleIds = async (user: User, ids: number[]): Promise<Set<number>> => {
|
||||
const res = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { id: { in: ids } },
|
||||
limit: ids.length,
|
||||
overrideAccess: false,
|
||||
user,
|
||||
depth: 0,
|
||||
});
|
||||
return new Set(res.docs.map((d) => d.id));
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
const payloadConfig = await config;
|
||||
payload = await getPayload({ config: payloadConfig });
|
||||
|
||||
const plainRole = await makeRole("plain", { permissions: [] });
|
||||
const gateRole = await makeRole("gate", { permissions: ["player-flags:read"] });
|
||||
const staffRole = await makeRole("staff", { permissions: ["game-event-logs:update"] });
|
||||
const superRole = await makeRole("super", { isSuperuser: true });
|
||||
|
||||
plainUser = await makeUser("plain", plainRole.id);
|
||||
gateUser = await makeUser("gate", gateRole.id);
|
||||
staffUser = await makeUser("staff", staffRole.id);
|
||||
superUser = await makeUser("super", superRole.id);
|
||||
|
||||
invalidatePermissionCache();
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
if (!payload) return;
|
||||
for (const id of flagIds) {
|
||||
await payload.delete({ collection: "player-flags", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of eventIds) {
|
||||
await payload.delete({ collection: "game-event-logs", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of userIds) {
|
||||
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of roleIds) {
|
||||
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it("emitGameEvent stamps the per-type policy onto documents", async () => {
|
||||
const publicEvent = await emit({
|
||||
type: EventTypes.MinigameFlappy,
|
||||
message: `${RUN} public score`,
|
||||
});
|
||||
expect(publicEvent.visibility).toBe("public");
|
||||
|
||||
const dialogueEvent = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} dialogue effect`,
|
||||
actor: plainUser.id,
|
||||
});
|
||||
expect(dialogueEvent.visibility).toBe("restricted");
|
||||
expect(dialogueEvent.requiredPermissions).toEqual(
|
||||
expect.arrayContaining(["npc-dialogues:read", "player-flags:read"]),
|
||||
);
|
||||
|
||||
const overridden = await emit({
|
||||
type: EventTypes.FlagSet,
|
||||
message: `${RUN} flag override`,
|
||||
visibility: "public",
|
||||
});
|
||||
expect(overridden.visibility).toBe("public");
|
||||
}, TIMEOUT);
|
||||
|
||||
it("hides restricted events from members and shows them to permission holders, staff, superusers, and actors", async () => {
|
||||
const publicEvent = await emit({
|
||||
type: EventTypes.WikiPageEdit,
|
||||
message: `${RUN} filtered public`,
|
||||
});
|
||||
const restrictedForeign = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} restricted foreign`,
|
||||
actor: gateUser.id,
|
||||
});
|
||||
const restrictedOwn = await emit({
|
||||
type: EventTypes.NpcDialogue,
|
||||
message: `${RUN} restricted own`,
|
||||
actor: plainUser.id,
|
||||
});
|
||||
const ids = [publicEvent.id, restrictedForeign.id, restrictedOwn.id];
|
||||
|
||||
// Plain member: public events + their own restricted events only.
|
||||
const plainView = await visibleIds(plainUser, ids);
|
||||
expect(plainView.has(publicEvent.id)).toBe(true);
|
||||
expect(plainView.has(restrictedOwn.id)).toBe(true);
|
||||
expect(plainView.has(restrictedForeign.id)).toBe(false);
|
||||
|
||||
// player-flags:read holder satisfies the any-of gate.
|
||||
const gateView = await visibleIds(gateUser, ids);
|
||||
expect(gateView.has(restrictedForeign.id)).toBe(true);
|
||||
|
||||
// Event-log staff and superusers see everything.
|
||||
const staffView = await visibleIds(staffUser, ids);
|
||||
expect(staffView.size).toBe(ids.length);
|
||||
const superView = await visibleIds(superUser, ids);
|
||||
expect(superView.size).toBe(ids.length);
|
||||
}, TIMEOUT);
|
||||
|
||||
it("returns a Where clause for members and true for superusers from read access", async () => {
|
||||
const read = GameEventLogs.access?.read;
|
||||
expect(typeof read).toBe("function");
|
||||
const fn = read as (args: { req: unknown }) => Promise<Where | boolean>;
|
||||
|
||||
const memberClause = await fn({ req: { user: plainUser, payload } });
|
||||
expect(typeof memberClause).toBe("object");
|
||||
const or = (memberClause as Where).or;
|
||||
expect(or).toEqual(expect.arrayContaining([{ visibility: { equals: "public" } }]));
|
||||
|
||||
expect(await fn({ req: { user: superUser, payload } })).toBe(true);
|
||||
expect(await fn({ req: { user: null, payload } })).toBe(false);
|
||||
}, TIMEOUT);
|
||||
|
||||
it("emits restricted flag:set audit events for player-flag writes", async () => {
|
||||
const flag = await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { key: `${RUN}_met_informant`, flagType: "boolean", boolValue: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
flagIds.push(flag.id);
|
||||
|
||||
const createdEvents = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { type: { equals: EventTypes.FlagSet }, targetId: { equals: flag.id } },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
expect(createdEvents.docs).toHaveLength(1);
|
||||
const created = createdEvents.docs[0];
|
||||
eventIds.push(created.id);
|
||||
expect(created.visibility).toBe("restricted");
|
||||
expect(created.requiredPermissions).toEqual(["player-flags:read"]);
|
||||
expect(created.message).toContain(`${RUN}_met_informant`);
|
||||
expect(created.message).toContain("global");
|
||||
expect(created.targetCollection).toBe("player-flags");
|
||||
|
||||
await payload.update({
|
||||
collection: "player-flags",
|
||||
id: flag.id,
|
||||
data: { boolValue: false },
|
||||
overrideAccess: true,
|
||||
});
|
||||
await payload.delete({
|
||||
collection: "player-flags",
|
||||
id: flag.id,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const allEvents = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { type: { equals: EventTypes.FlagSet }, targetId: { equals: flag.id } },
|
||||
sort: "id",
|
||||
limit: 10,
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
eventIds.push(...allEvents.docs.map((d) => d.id));
|
||||
const messages = allEvents.docs.map((d) => d.message).join(" | ");
|
||||
expect(messages).toContain("updated for global");
|
||||
expect(messages).toContain("deleted for global");
|
||||
}, TIMEOUT);
|
||||
});
|
||||
|
|
@ -1,504 +0,0 @@
|
|||
import { getPayload, Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
|
||||
import { DialogueText, formatRemaining } from "@/lib/npc-dialogue/DialogueText";
|
||||
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
||||
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
|
||||
import { flowHash, mergeSeenNodes, unseenNodeIds } from "@/lib/npc-dialogue/seen";
|
||||
import {
|
||||
collectNodeTokens,
|
||||
extractCountdownKeys,
|
||||
extractFlagTokens,
|
||||
formatFlagValue,
|
||||
hasFlagTokens,
|
||||
interpolateFlags,
|
||||
replaceCountdowns,
|
||||
resolveNodeTexts,
|
||||
} from "@/lib/npc-dialogue/interpolate";
|
||||
|
||||
let payload: Payload;
|
||||
|
||||
const RUN = `dlg_${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
describe("flag token extraction + interpolation (pure)", () => {
|
||||
it("extracts distinct lowercased keys and ignores single-brace markup", () => {
|
||||
expect(extractFlagTokens("Status: {{network_status}}. {{NETWORK_STATUS}} again")).toEqual([
|
||||
"network_status",
|
||||
]);
|
||||
expect(extractFlagTokens("{green}no tokens here{/} **bold**")).toEqual([]);
|
||||
expect(extractFlagTokens(undefined)).toEqual([]);
|
||||
expect(hasFlagTokens("a {{x}} b")).toBe(true);
|
||||
expect(hasFlagTokens("{red}x{/}")).toBe(false);
|
||||
});
|
||||
|
||||
it("substitutes values, resolves missing keys to empty, keeps markup intact", () => {
|
||||
const out = interpolateFlags("Link {{network_status}}, rep {{rep_merchants}}", {
|
||||
network_status: "{green}NOMINAL{/}",
|
||||
});
|
||||
expect(out).toBe("Link {green}NOMINAL{/}, rep ");
|
||||
});
|
||||
|
||||
it("is case-insensitive on keys and never re-scans substituted values", () => {
|
||||
const out = interpolateFlags("{{Key}} says {{key}}", {
|
||||
key: "{{key}}",
|
||||
});
|
||||
// Single pass: the injected token must survive literally, not expand.
|
||||
expect(out).toBe("{{key}} says {{key}}");
|
||||
});
|
||||
|
||||
it("formats flag values per type for interpolation", () => {
|
||||
expect(formatFlagValue({ flagType: "text", textValue: "{green}OK{/}" })).toBe("{green}OK{/}");
|
||||
expect(formatFlagValue({ flagType: "text" })).toBe("");
|
||||
expect(formatFlagValue({ flagType: "number", numberValue: 7 })).toBe("7");
|
||||
expect(formatFlagValue({ flagType: "number" })).toBe("0");
|
||||
expect(formatFlagValue({ flagType: "boolean", boolValue: true })).toBe("true");
|
||||
expect(formatFlagValue({ flagType: "boolean", boolValue: false })).toBe("false");
|
||||
});
|
||||
|
||||
it("collects node tokens across body, lead-in, closing, effect message, labels", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n1",
|
||||
type: "choice",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
leadIn: "Ops report: {{ops_status}}",
|
||||
choices: [
|
||||
{ label: "Ack ({{clearance_level}})", target: "a" },
|
||||
{ label: "No tokens", target: "b" },
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(new Set(collectNodeTokens(node))).toEqual(new Set(["ops_status", "clearance_level"]));
|
||||
});
|
||||
|
||||
it("resolves only the fields a node defines, index-aligning labels", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n1",
|
||||
type: "dialogue",
|
||||
position: { x: 0, y: 0 },
|
||||
data: { body: "Status {{network_status}}", next: { target: "x" } },
|
||||
};
|
||||
const resolved = resolveNodeTexts(node, { network_status: "{red}DOWN{/}" });
|
||||
expect(resolved).toEqual({ body: "Status {red}DOWN{/}" });
|
||||
|
||||
const choice: DialogueNode = {
|
||||
id: "n2",
|
||||
type: "choice",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
leadIn: "{{greeting}}",
|
||||
choices: [
|
||||
{ label: "{{a}}", target: "t" },
|
||||
{ label: "plain", target: "u" },
|
||||
],
|
||||
},
|
||||
};
|
||||
const r2 = resolveNodeTexts(choice, { greeting: "Hi", a: "1" });
|
||||
expect(r2.leadIn).toBe("Hi");
|
||||
expect(r2.labels).toEqual(["1", "plain"]);
|
||||
expect(r2.body).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("text flags (player-flags collection)", () => {
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config });
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
const res = await payload.find({
|
||||
collection: "player-flags",
|
||||
where: { key: { like: `${RUN}%` } },
|
||||
limit: 50,
|
||||
overrideAccess: true,
|
||||
});
|
||||
for (const doc of res.docs) {
|
||||
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("stores and reads a global text flag with markup", async () => {
|
||||
const created = await payload.create({
|
||||
collection: "player-flags",
|
||||
data: {
|
||||
user: null,
|
||||
key: `${RUN}_network_status`,
|
||||
flagType: "text",
|
||||
textValue: "{green}NOMINAL{/}",
|
||||
},
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(created.flagType).toBe("text");
|
||||
expect(created.textValue).toBe("{green}NOMINAL{/}");
|
||||
|
||||
const fetched = await payload.findByID({
|
||||
collection: "player-flags",
|
||||
id: created.id,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(fetched.textValue).toBe("{green}NOMINAL{/}");
|
||||
|
||||
// Interpolates into dialogue text exactly as authored.
|
||||
const values = { [`${RUN}_network_status`]: formatFlagValue(fetched) };
|
||||
const line = interpolateFlags(`Grid says {{${RUN}_network_status}}`, values);
|
||||
expect(line).toBe(`Grid says {green}NOMINAL{/}`);
|
||||
});
|
||||
|
||||
it("converts an existing boolean flag to text via update (set_text semantics)", async () => {
|
||||
const created = await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { user: null, key: `${RUN}_converted`, flagType: "boolean", boolValue: true },
|
||||
overrideAccess: true,
|
||||
});
|
||||
const updated = await payload.update({
|
||||
collection: "player-flags",
|
||||
id: created.id,
|
||||
data: { flagType: "text", textValue: "{amber}REDACTED{/}" },
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(updated.flagType).toBe("text");
|
||||
expect(updated.textValue).toBe("{amber}REDACTED{/}");
|
||||
expect(formatFlagValue(updated)).toBe("{amber}REDACTED{/}");
|
||||
});
|
||||
|
||||
it("stores conversation priority + entry gate and drives selection", async () => {
|
||||
const npc = await payload.create({
|
||||
collection: "game-npcs",
|
||||
data: { name: `${RUN}_gate_npc`, canMessage: true },
|
||||
overrideAccess: true,
|
||||
});
|
||||
const flow = { nodes: [], edges: [] };
|
||||
const gated = await payload.create({
|
||||
collection: "npc-dialogues",
|
||||
data: {
|
||||
name: `${RUN}_gated`,
|
||||
npc: npc.id,
|
||||
flowData: flow,
|
||||
priority: 10,
|
||||
entryGate: { key: `${RUN}_met`, op: "is_true" },
|
||||
},
|
||||
overrideAccess: true,
|
||||
});
|
||||
const fallback = await payload.create({
|
||||
collection: "npc-dialogues",
|
||||
data: { name: `${RUN}_fallback`, npc: npc.id, flowData: flow },
|
||||
overrideAccess: true,
|
||||
});
|
||||
try {
|
||||
const res = await payload.find({
|
||||
collection: "npc-dialogues",
|
||||
where: { npc: { equals: npc.id } },
|
||||
limit: 10,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(res.docs).toHaveLength(2);
|
||||
|
||||
const unlocked = new Set([`${RUN}_met`]);
|
||||
const chosen = await selectDialogueForUser(res.docs, async (c) => unlocked.has(c.key));
|
||||
expect(chosen?.id).toBe(gated.id);
|
||||
|
||||
const fallen = await selectDialogueForUser(res.docs, async () => false);
|
||||
expect(fallen?.id).toBe(fallback.id);
|
||||
} finally {
|
||||
for (const doc of [gated, fallback]) {
|
||||
await payload.delete({ collection: "npc-dialogues", id: doc.id, overrideAccess: true });
|
||||
}
|
||||
await payload.delete({ collection: "game-npcs", id: npc.id, overrideAccess: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reads time-gated flags: pending fails with a countdown target, expired reads missing", async () => {
|
||||
const future = new Date(Date.now() + 3_600_000).toISOString();
|
||||
const past = new Date(Date.now() - 3_600_000).toISOString();
|
||||
const pending = await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { key: `${RUN}_pending`, flagType: "boolean", boolValue: true, activatesAt: future },
|
||||
overrideAccess: true,
|
||||
});
|
||||
const expired = await payload.create({
|
||||
collection: "player-flags",
|
||||
data: { key: `${RUN}_expired`, flagType: "number", numberValue: 9, expiresAt: past },
|
||||
overrideAccess: true,
|
||||
});
|
||||
try {
|
||||
const userId = 999_999; // no player docs for this id; exercises the global path
|
||||
const pendingRead = await readFlag(payload, userId, `${RUN}_pending`);
|
||||
expect(pendingRead.bool).toBe(false);
|
||||
expect(pendingRead.exists).toBe(true);
|
||||
expect(pendingRead.activatesAt).toBe(future);
|
||||
await expect(
|
||||
evaluateCondition(payload, userId, { kind: "flag", key: `${RUN}_pending`, op: "is_true" }),
|
||||
).resolves.toBe(false);
|
||||
|
||||
const expiredRead = await readFlag(payload, userId, `${RUN}_expired`);
|
||||
expect(expiredRead.exists).toBe(false);
|
||||
expect(expiredRead.num).toBe(0);
|
||||
await expect(
|
||||
evaluateCondition(payload, userId, { kind: "flag", key: `${RUN}_expired`, op: "gte", amount: 1 }),
|
||||
).resolves.toBe(false);
|
||||
} finally {
|
||||
for (const doc of [pending, expired]) {
|
||||
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("inline images in dialogue markup", () => {
|
||||
const render = (text: string) =>
|
||||
renderToStaticMarkup(createElement(DialogueText, { text }));
|
||||
|
||||
it("renders site-relative and absolute-http images as inline icons", () => {
|
||||
const html = render("Pay 5  now");
|
||||
expect(html).toContain('<img src="/api/media/file/coin.png" alt="coin"');
|
||||
expect(render("")).toContain("<img");
|
||||
});
|
||||
|
||||
it("leaves unsafe or malformed image URLs literal", () => {
|
||||
// Protocol-relative and scheme-less/bad URLs never become <img>.
|
||||
expect(render("")).not.toContain("<img");
|
||||
expect(render("")).not.toContain("<img");
|
||||
expect(render("")).not.toContain("<img");
|
||||
});
|
||||
|
||||
it("keeps existing markup working alongside images", () => {
|
||||
const html = render("**b** {green}g{/}  `code`");
|
||||
expect(html).toContain("<strong");
|
||||
expect(html).toContain("text-green-400");
|
||||
expect(html).toContain("<img");
|
||||
expect(html).toContain("<code");
|
||||
});
|
||||
});
|
||||
|
||||
describe("conversation selection (entry gates + priority)", () => {
|
||||
const pass = async () => true;
|
||||
const fail = async () => false;
|
||||
|
||||
it("prefers higher priority regardless of input order", async () => {
|
||||
const docs = [
|
||||
{ id: 1, priority: 0 },
|
||||
{ id: 2, priority: 10 },
|
||||
{ id: 3, priority: 5 },
|
||||
];
|
||||
expect((await selectDialogueForUser(docs, pass))?.id).toBe(2);
|
||||
});
|
||||
|
||||
it("breaks ties by oldest id", async () => {
|
||||
const docs = [{ id: 7 }, { id: 3, priority: 0 }];
|
||||
expect((await selectDialogueForUser(docs, pass))?.id).toBe(3);
|
||||
});
|
||||
|
||||
it("skips gated conversations whose condition fails, falling back to ungated", async () => {
|
||||
const docs = [
|
||||
{ id: 1, priority: 10, entryGate: { key: "met_fixer", op: "is_true" as const } },
|
||||
{ id: 2, priority: 0 },
|
||||
];
|
||||
expect((await selectDialogueForUser(docs, fail))?.id).toBe(2);
|
||||
expect((await selectDialogueForUser(docs, pass))?.id).toBe(1);
|
||||
});
|
||||
|
||||
it("returns null when every candidate is gated shut", async () => {
|
||||
const docs = [{ id: 1, entryGate: { key: "secret", op: "is_true" as const } }];
|
||||
expect(await selectDialogueForUser(docs, fail)).toBeNull();
|
||||
});
|
||||
|
||||
it("treats blank gate keys as ungated and defaults the op", () => {
|
||||
expect(gateCondition({ key: " " })).toBeNull();
|
||||
expect(gateCondition(null)).toBeNull();
|
||||
expect(gateCondition({ key: "x" })).toEqual({
|
||||
kind: "flag",
|
||||
key: "x",
|
||||
op: "is_true",
|
||||
amount: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("choice tooltip interpolation", () => {
|
||||
it("collects tokens from tooltips and resolves them index-aligned", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n",
|
||||
type: "choice",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
choices: [
|
||||
{ label: "A", target: "t", tooltip: "Cost {{cost}} " },
|
||||
{ label: "B", target: "u" },
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(collectNodeTokens(node)).toContain("cost");
|
||||
const resolved = resolveNodeTexts(node, { cost: "5" });
|
||||
expect(resolved.tooltips?.[0]).toBe("Cost 5 ");
|
||||
expect(resolved.tooltips?.[1]).toBe("");
|
||||
});
|
||||
|
||||
it("omits the tooltips array when no choice has a tooltip", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n",
|
||||
type: "choice",
|
||||
position: { x: 0, y: 0 },
|
||||
data: { choices: [{ label: "A", target: "t" }] },
|
||||
};
|
||||
expect(resolveNodeTexts(node, {}).tooltips).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("markup accumulation + links + countdowns", () => {
|
||||
const render = (text: string) =>
|
||||
renderToStaticMarkup(createElement(DialogueText, { text }));
|
||||
|
||||
it("accumulates bold inside color and color inside bold", () => {
|
||||
const stacked = render("{green}**cargo** secured{/}");
|
||||
expect(stacked).toContain("text-green-400");
|
||||
expect(stacked).toContain("<strong");
|
||||
const wrapped = render("**{red}danger{/} zone**");
|
||||
expect(wrapped).toContain("<strong");
|
||||
expect(wrapped).toContain("text-red-400");
|
||||
});
|
||||
|
||||
it("closes nested colors inner-first", () => {
|
||||
const html = render("{cyan}outer {red}inner{/} tail{/}");
|
||||
expect(html).toContain("text-cyan-400");
|
||||
expect(html).toContain("text-red-400");
|
||||
expect(html).toContain("tail");
|
||||
expect(html).not.toContain("{/}");
|
||||
});
|
||||
|
||||
it("renders hex colors wrapping nested markup", () => {
|
||||
const html = render("{#ff00ff}*wow*{/}");
|
||||
expect(html).toContain("color:#ff00ff");
|
||||
expect(html).toContain("<em");
|
||||
});
|
||||
|
||||
it("renders safe links as anchors and refuses javascript: urls", () => {
|
||||
const ok = render("[After Action Report](/intelligence/missions/12)");
|
||||
expect(ok).toContain('href="/intelligence/missions/12"');
|
||||
expect(ok).toContain("After Action Report");
|
||||
const bad = render("[trap](javascript:alert(1))");
|
||||
expect(bad).not.toContain("href=");
|
||||
expect(bad).toContain("[trap]");
|
||||
});
|
||||
|
||||
it("renders countdown leaves: ticking, ready, and empty", () => {
|
||||
const future = new Date(Date.now() + 3_600_000).toISOString();
|
||||
expect(render(`{cd|${future}}`)).toContain("text-cyan-300");
|
||||
expect(render("{cd|done}")).toContain("ready");
|
||||
const empty = render("x{cd|}y");
|
||||
expect(empty).toContain("xy");
|
||||
expect(empty).not.toContain("cd|");
|
||||
});
|
||||
|
||||
it("formats remaining time compactly", () => {
|
||||
expect(formatRemaining(9_000)).toBe("9s");
|
||||
expect(formatRemaining(63_000)).toBe("1m 03s");
|
||||
expect(formatRemaining(3_661_000)).toBe("1h 01m");
|
||||
expect(formatRemaining(93_600_000)).toBe("1d 2h");
|
||||
expect(formatRemaining(-5)).toBe("0s");
|
||||
});
|
||||
});
|
||||
|
||||
describe("countdown token resolution (pure)", () => {
|
||||
it("collects countdown keys so nodes get resolved", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n",
|
||||
type: "dialogue",
|
||||
position: { x: 0, y: 0 },
|
||||
data: { body: "Analysis done in {{countdown:device_scan}}." },
|
||||
};
|
||||
expect(collectNodeTokens(node)).toContain("device_scan");
|
||||
expect(extractCountdownKeys("{{countdown:A}} {{countdown:a}} {{flag}}")).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("rewrites tokens to leaves with resolved values", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n",
|
||||
type: "dialogue",
|
||||
position: { x: 0, y: 0 },
|
||||
data: { body: "{{countdown:device_scan}} / {{countdown:missing}}" },
|
||||
};
|
||||
const out = resolveNodeTexts(node, {}, { device_scan: "2030-01-01T00:00:00.000Z" });
|
||||
expect(out.body).toBe("{cd|2030-01-01T00:00:00.000Z} / {cd|}");
|
||||
});
|
||||
|
||||
it("replaceCountdowns lowercases keys and defaults missing to empty", () => {
|
||||
expect(replaceCountdowns("{{countdown:KEY}}", { key: "done" })).toBe("{cd|done}");
|
||||
expect(replaceCountdowns("{{countdown:key}}", {})).toBe("{cd|}");
|
||||
});
|
||||
|
||||
it("resolves locked hints index-aligned with the choices", () => {
|
||||
const node: DialogueNode = {
|
||||
id: "n",
|
||||
type: "choice",
|
||||
position: { x: 0, y: 0 },
|
||||
data: {
|
||||
choices: [
|
||||
{ label: "A", target: "t", lockedHint: "Needs {{rep}} rep" },
|
||||
{ label: "B", target: "u" },
|
||||
],
|
||||
},
|
||||
};
|
||||
const out = resolveNodeTexts(node, { rep: "3" });
|
||||
expect(out.hints?.[0]).toBe("Needs 3 rep");
|
||||
expect(out.hints?.[1]).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("seen tracking (NEW badges)", () => {
|
||||
it("hashes flowcharts deterministically and differently on change", () => {
|
||||
expect(flowHash({ nodes: [{ id: "a" }] })).toBe(flowHash({ nodes: [{ id: "a" }] }));
|
||||
expect(flowHash({ nodes: [{ id: "a" }] })).not.toBe(flowHash({ nodes: [{ id: "b" }] }));
|
||||
});
|
||||
|
||||
it("ignores layout (positions, edge ids/styling) and key order", () => {
|
||||
const base = {
|
||||
nodes: [{ id: "a", type: "dialogue", position: { x: 0, y: 0 }, data: { body: "hi" } }],
|
||||
edges: [{ id: "e1", source: "a", target: "b", style: {} }],
|
||||
};
|
||||
const rearranged = {
|
||||
nodes: [{ id: "a", type: "dialogue", position: { x: 900, y: 400 }, data: { body: "hi" } }],
|
||||
edges: [{ id: "zzz", source: "a", target: "b", style: { stroke: "red" } }],
|
||||
};
|
||||
expect(flowHash(rearranged)).toBe(flowHash(base));
|
||||
const reordered = {
|
||||
nodes: [{ data: { body: "hi" }, type: "dialogue", id: "a" }],
|
||||
edges: [{ target: "b", source: "a" }],
|
||||
};
|
||||
expect(flowHash(reordered)).toBe(flowHash(base));
|
||||
});
|
||||
|
||||
it("re-flags when node content changes", () => {
|
||||
const base = { nodes: [{ id: "a", type: "dialogue", data: { body: "hi" } }] };
|
||||
const edited = { nodes: [{ id: "a", type: "dialogue", data: { body: "changed" } }] };
|
||||
expect(flowHash(edited)).not.toBe(flowHash(base));
|
||||
const addedChoice = {
|
||||
nodes: [
|
||||
{ id: "a", type: "dialogue", data: { body: "hi" } },
|
||||
{ id: "b", type: "choice", data: { choices: [{ label: "New path", target: "a" }] } },
|
||||
],
|
||||
};
|
||||
expect(flowHash(addedChoice)).not.toBe(flowHash(base));
|
||||
});
|
||||
|
||||
it("treats a hash mismatch as everything unseen", () => {
|
||||
expect(unseenNodeIds({ hash: "old", nodes: ["a", "b"] }, "new", ["a", "b"])).toEqual([
|
||||
"a",
|
||||
"b",
|
||||
]);
|
||||
expect(unseenNodeIds({ hash: "x", nodes: ["a"] }, "x", ["a", "b"])).toEqual(["b"]);
|
||||
expect(unseenNodeIds(undefined, "x", ["a"])).toEqual(["a"]);
|
||||
});
|
||||
|
||||
it("merges seen nodes without duplicates and resets on new hash", () => {
|
||||
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "a")).toEqual(["a"]);
|
||||
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "b")).toEqual(["a", "b"]);
|
||||
expect(mergeSeenNodes({ hash: "old", nodes: ["a"] }, "new", "b")).toEqual(["b"]);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,249 +0,0 @@
|
|||
import { getPayload, Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { processReinforcementEvent } from "@/lib/arma-bridge/reinforcements";
|
||||
import { GET } from "@/app/api/arma/v1/reinforcements/route";
|
||||
import { POST as postEvents } from "@/app/api/arma/v1/events/route";
|
||||
|
||||
/**
|
||||
* Reinforcement pools (web app -> Zeus soft limits).
|
||||
*
|
||||
* Processor delta math is tested directly; idempotency lives at the events
|
||||
* route (unique eventId), so it is exercised through that endpoint, together
|
||||
* with the reinforcements endpoint's shape and auth gating.
|
||||
*/
|
||||
|
||||
let payload: Payload;
|
||||
const RUN = `reinf-${Date.now().toString(36)}`;
|
||||
const SERVER_ID = `${RUN}-srv`.replace(/[^a-zA-Z0-9_-]/g, "");
|
||||
const BRIDGE_KEY = process.env.ARMA_BRIDGE_API_KEY || "test-bridge-key";
|
||||
|
||||
async function availableOf(id: number): Promise<number> {
|
||||
const pool = await payload.findByID({
|
||||
collection: "reinforcement-pools",
|
||||
id,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return pool.available ?? 0;
|
||||
}
|
||||
|
||||
async function eventLogs(type: string, targetId: number) {
|
||||
const res = await payload.find({
|
||||
collection: "game-event-logs",
|
||||
where: { type: { equals: type }, targetId: { equals: targetId } },
|
||||
limit: 50,
|
||||
sort: "-createdAt",
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return res.docs;
|
||||
}
|
||||
|
||||
let eventSeq = 0;
|
||||
function bridgeEvent(type: "reinforcement.spawn" | "reinforcement.refund", body: unknown) {
|
||||
eventSeq += 1;
|
||||
return { eventId: `${RUN}:${eventSeq}`, type, payload: body };
|
||||
}
|
||||
|
||||
describe("Reinforcement pools", () => {
|
||||
let poolAId: number;
|
||||
let poolBId: number;
|
||||
let serverDocId: number;
|
||||
const createdPoolIds: number[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.ARMA_BRIDGE_API_KEY = BRIDGE_KEY;
|
||||
const payloadConfig = await config;
|
||||
payload = await getPayload({ config: payloadConfig });
|
||||
|
||||
const server = await payload.create({
|
||||
collection: "game-servers",
|
||||
data: { serverId: SERVER_ID, name: `${RUN} Server`, status: "online" },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
serverDocId = server.id;
|
||||
|
||||
const poolA = await payload.create({
|
||||
collection: "reinforcement-pools",
|
||||
data: { name: `${RUN}-A`, armaFactions: ["BLU_F", "PTF"], available: 16, enabled: true },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
poolAId = poolA.id;
|
||||
createdPoolIds.push(poolAId);
|
||||
|
||||
const poolB = await payload.create({
|
||||
collection: "reinforcement-pools",
|
||||
data: { name: `${RUN}-B-disabled`, available: 5, enabled: false },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
poolBId = poolB.id;
|
||||
createdPoolIds.push(poolBId);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of createdPoolIds) {
|
||||
await payload.delete({ collection: "reinforcement-pools", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
if (serverDocId) {
|
||||
await payload.delete({ collection: "game-servers", id: serverDocId, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
describe("processReinforcementEvent delta math", () => {
|
||||
it("spawn decrements and refund increments the pool balance", async () => {
|
||||
const before = await availableOf(poolAId);
|
||||
await processReinforcementEvent(
|
||||
payload,
|
||||
bridgeEvent("reinforcement.spawn", [poolAId, 1, "B_Soldier_F"]),
|
||||
);
|
||||
expect(await availableOf(poolAId)).toBe(before - 1);
|
||||
|
||||
await processReinforcementEvent(
|
||||
payload,
|
||||
bridgeEvent("reinforcement.refund", [poolAId, 1, "B_Soldier_F"]),
|
||||
);
|
||||
expect(await availableOf(poolAId)).toBe(before);
|
||||
|
||||
const spawns = await eventLogs("reinforcement:spawn", poolAId);
|
||||
expect(spawns.length).toBeGreaterThan(0);
|
||||
const refunds = await eventLogs("reinforcement:refund", poolAId);
|
||||
expect(refunds.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("allows overdraft: balances may go negative (no floor)", async () => {
|
||||
await payload.update({
|
||||
collection: "reinforcement-pools",
|
||||
id: poolAId,
|
||||
data: { available: 2 },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
await processReinforcementEvent(
|
||||
payload,
|
||||
bridgeEvent("reinforcement.spawn", [poolAId, 5, "B_soldier_F"]),
|
||||
);
|
||||
expect(await availableOf(poolAId)).toBe(-3);
|
||||
});
|
||||
|
||||
it("skips unknown pools and malformed payloads without throwing", async () => {
|
||||
const before = await availableOf(poolAId);
|
||||
await expect(
|
||||
processReinforcementEvent(payload, bridgeEvent("reinforcement.spawn", [999999999, 1, "X"])),
|
||||
).resolves.toBeUndefined();
|
||||
await expect(
|
||||
processReinforcementEvent(payload, bridgeEvent("reinforcement.spawn", "nope")),
|
||||
).resolves.toBeUndefined();
|
||||
await expect(
|
||||
processReinforcementEvent(payload, bridgeEvent("reinforcement.spawn", [poolAId, 0, "X"])),
|
||||
).resolves.toBeUndefined();
|
||||
expect(await availableOf(poolAId)).toBe(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe("manual-edit audit (reinforcement:adjust)", () => {
|
||||
it("bridge writes emit no adjust event; admin writes do", async () => {
|
||||
// Pool creation itself was a manual write, so count from the current baseline.
|
||||
const baseline = (await eventLogs("reinforcement:adjust", poolAId)).length;
|
||||
|
||||
// A bridge processor write carries the system marker: no adjust audit.
|
||||
await processReinforcementEvent(
|
||||
payload,
|
||||
bridgeEvent("reinforcement.spawn", [poolAId, 1, "B_Soldier_F"]),
|
||||
);
|
||||
const afterBridge = await availableOf(poolAId);
|
||||
expect((await eventLogs("reinforcement:adjust", poolAId)).length).toBe(baseline);
|
||||
|
||||
// Admin-panel style write (no system marker header) is audited old -> new.
|
||||
await payload.update({
|
||||
collection: "reinforcement-pools",
|
||||
id: poolAId,
|
||||
data: { available: 42 },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
const adjusts = await eventLogs("reinforcement:adjust", poolAId);
|
||||
expect(adjusts.length).toBe(baseline + 1);
|
||||
expect(adjusts[0].data).toMatchObject({ operation: "update", availableBefore: afterBridge, availableAfter: 42 });
|
||||
|
||||
// A write that does not touch the balance emits nothing new.
|
||||
await payload.update({
|
||||
collection: "reinforcement-pools",
|
||||
id: poolAId,
|
||||
data: { name: `${RUN}-A-renamed` },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
expect((await eventLogs("reinforcement:adjust", poolAId)).length).toBe(baseline + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/arma/v1/reinforcements", () => {
|
||||
function request(headers: Record<string, string>) {
|
||||
return new NextRequest("http://localhost/api/arma/v1/reinforcements", { headers });
|
||||
}
|
||||
|
||||
it("gates on the bridge key and a known server", async () => {
|
||||
let res = await GET(request({}));
|
||||
expect(res.status).toBe(401);
|
||||
|
||||
res = await GET(
|
||||
request({ "x-arma-bridge-key": "wrong", "x-arma-server-id": SERVER_ID }),
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
|
||||
res = await GET(
|
||||
request({ "x-arma-bridge-key": BRIDGE_KEY, "x-arma-server-id": "never-beaten" }),
|
||||
);
|
||||
expect(res.status).toBe(409);
|
||||
});
|
||||
|
||||
it("returns enabled pools with poolId, name, available and armaFactions", async () => {
|
||||
const res = await GET(
|
||||
request({ "x-arma-bridge-key": BRIDGE_KEY, "x-arma-server-id": SERVER_ID }),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
ok: boolean;
|
||||
pools: { poolId: number; name: string; available: number; armaFactions: string[] }[];
|
||||
};
|
||||
expect(body.ok).toBe(true);
|
||||
const a = body.pools.find((pool) => pool.poolId === poolAId);
|
||||
expect(a).toMatchObject({ name: `${RUN}-A-renamed`, available: 42, armaFactions: ["BLU_F", "PTF"] });
|
||||
expect(body.pools.some((pool) => pool.poolId === poolBId)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("events route idempotency (duplicate eventId)", () => {
|
||||
function eventsRequest(events: unknown[]) {
|
||||
return new NextRequest("http://localhost/api/arma/v1/events", {
|
||||
method: "POST",
|
||||
headers: { "x-arma-bridge-key": BRIDGE_KEY, "x-arma-server-id": SERVER_ID },
|
||||
body: JSON.stringify({ events }),
|
||||
});
|
||||
}
|
||||
|
||||
it("applies a reinforcement event once and ignores the redelivery", async () => {
|
||||
const before = await availableOf(poolAId);
|
||||
const event = {
|
||||
id: `${RUN}-dup-1`,
|
||||
type: "reinforcement.spawn",
|
||||
payload: [poolAId, 1, "B_Soldier_F"],
|
||||
occurredAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
let res = await postEvents(eventsRequest([event]));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toMatchObject({ ok: true, accepted: 1, duplicates: 0 });
|
||||
expect(await availableOf(poolAId)).toBe(before - 1);
|
||||
|
||||
res = await postEvents(eventsRequest([event]));
|
||||
expect(await res.json()).toMatchObject({ ok: true, accepted: 0, duplicates: 1 });
|
||||
expect(await availableOf(poolAId)).toBe(before - 1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -6,7 +6,7 @@ import { beforeAll, afterAll, describe, expect, it } from "vitest";
|
|||
import type { Ticket, User } from "@/payload-types";
|
||||
import { plaintextToLexical } from "@/lib/tickets/lexical";
|
||||
import { getStaffUserIds } from "@/lib/tickets/staff";
|
||||
import { NON_ARCHIVED_WHERE, STATUS_LABEL, TICKET_STATUSES } from "@/lib/tickets/ticketMeta";
|
||||
import { STATUS_LABEL, TICKET_STATUSES } from "@/lib/tickets/ticketMeta";
|
||||
import { setTicketVoteForUser, updateTicketByAuthor } from "@/lib/tickets/mutations";
|
||||
|
||||
let payload: Payload;
|
||||
|
|
@ -479,106 +479,4 @@ describe("Tickets", () => {
|
|||
"Canceled tickets cannot receive votes",
|
||||
);
|
||||
});
|
||||
|
||||
it("stamps archivedAt and appends system entries on archive and restore", async () => {
|
||||
const ticket = await createTicket(reporter.id, `${RUN} Archivable`);
|
||||
expect(ticket.archived).toBeFalsy();
|
||||
|
||||
await payload.update({
|
||||
collection: "tickets",
|
||||
id: ticket.id,
|
||||
data: { archived: true },
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const archived = await fetchTicket(ticket.id);
|
||||
expect(archived.archived).toBe(true);
|
||||
expect(archived.archivedAt).toBeTruthy();
|
||||
expect(activityTexts(archived)).toContain("Ticket archived");
|
||||
|
||||
// Restoring (admin panel only) clears the stamp and logs the restore.
|
||||
await payload.update({
|
||||
collection: "tickets",
|
||||
id: ticket.id,
|
||||
data: { archived: false },
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
const restored = await fetchTicket(ticket.id);
|
||||
expect(restored.archived).toBe(false);
|
||||
expect(restored.archivedAt).toBeNull();
|
||||
expect(activityTexts(restored)).toContain("Ticket restored from archive");
|
||||
});
|
||||
|
||||
it("excludes archived tickets from front-end queries but keeps them in the admin panel", async () => {
|
||||
const visible = await createTicket(reporter.id, `${RUN} Archive visible`);
|
||||
const hidden = await createTicket(reporter.id, `${RUN} Archive hidden`);
|
||||
await payload.update({
|
||||
collection: "tickets",
|
||||
id: hidden.id,
|
||||
data: { archived: true },
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
// Front-end list pattern (helpdesk page): NON_ARCHIVED_WHERE hides it.
|
||||
const frontendRes = await payload.find({
|
||||
collection: "tickets",
|
||||
where: { and: [{ title: { contains: RUN } }, NON_ARCHIVED_WHERE] },
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const frontendIds = frontendRes.docs.map((ticket) => ticket.id);
|
||||
expect(frontendIds).toContain(visible.id);
|
||||
expect(frontendIds).not.toContain(hidden.id);
|
||||
|
||||
// Admin panel pattern: unfiltered reads still see archived tickets.
|
||||
const adminRes = await payload.find({
|
||||
collection: "tickets",
|
||||
where: { title: { contains: RUN } },
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(adminRes.docs.map((ticket) => ticket.id)).toContain(hidden.id);
|
||||
|
||||
// Even the reporter's own scoped read with the front-end filter hides it.
|
||||
const scopedRes = await payload.find({
|
||||
collection: "tickets",
|
||||
where: { and: [{ reporter: { equals: reporter.id } }, NON_ARCHIVED_WHERE] },
|
||||
limit: 100,
|
||||
depth: 0,
|
||||
user: reporter,
|
||||
overrideAccess: false,
|
||||
});
|
||||
const scopedIds = scopedRes.docs.map((ticket) => ticket.id);
|
||||
expect(scopedIds).toContain(visible.id);
|
||||
expect(scopedIds).not.toContain(hidden.id);
|
||||
});
|
||||
|
||||
it("treats archived tickets as missing for edits and votes", async () => {
|
||||
const ticket = await createTicket(reporter.id, `${RUN} Archived mutations`);
|
||||
await payload.update({
|
||||
collection: "tickets",
|
||||
id: ticket.id,
|
||||
data: { archived: true },
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
await expect(
|
||||
updateTicketByAuthor(payload, reporter, {
|
||||
ticketId: ticket.id,
|
||||
title: `${RUN} Should not stick`,
|
||||
description: `${RUN} should not stick`,
|
||||
category: "bug_report",
|
||||
priority: "high",
|
||||
}),
|
||||
).rejects.toThrow("Ticket not found");
|
||||
|
||||
await expect(setTicketVoteForUser(payload, reporter, ticket.id, true)).rejects.toThrow(
|
||||
"Ticket not found",
|
||||
);
|
||||
|
||||
expect((await fetchTicket(ticket.id)).title).toBe(`${RUN} Archived mutations`);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue