feat(npc-dialogue): back NEW badges with server-side read markers
The per-browser localStorage tracking reset on every new device and kept re-badging whole conversations whenever a GM edited the flowchart (hash change), which players read as "nothing I read is remembered". Read progress now lives in a npc-dialogue-states collection: one row per (user, dialogue, node) with a unique index, so a node badges NEW exactly once per player and GM edits never re-flag content they already saw. - New collection NpcDialogueStates (own-doc access, staff-visible admin view) plus migration add_npc_dialogue_states. - lib/npc-dialogue/states.ts: listSeenNodeIds for the page and an idempotent markNodeRead; exposed via the markNpcDialogueNodeRead server action, called fire-and-forget as nodes type in. - The contacts page seeds initialSeenNodeIds into NpcConversation; the component keeps an optimistic local set and no longer touches localStorage. seen.ts and its tests are removed. Verified live: fresh account shows NEW on all choices, reading the "Who are you?" branch and reloading drops that badge while unread branches keep theirs; npc_dialogue_states holds exactly the traversed nodes. Interpolation int suite green (30/30).
This commit is contained in:
parent
59f01610ca
commit
799c3216d2
12 changed files with 41302 additions and 187 deletions
|
|
@ -10,6 +10,7 @@ import { notifyUser } from "@/lib/notifications";
|
||||||
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||||
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
|
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
|
||||||
|
import { markNodeRead } from "@/lib/npc-dialogue/states";
|
||||||
import type {
|
import type {
|
||||||
ChoiceGate,
|
ChoiceGate,
|
||||||
DialogueFlagOp,
|
DialogueFlagOp,
|
||||||
|
|
@ -289,3 +290,28 @@ export async function resolveNpcDialogueTexts(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Record that the reading user has seen one conversation node, so its NEW
|
||||||
|
* badge clears on every device. Idempotent; the client fires this off
|
||||||
|
* fire-and-forget as lines land in the log.
|
||||||
|
*/
|
||||||
|
export async function markNpcDialogueNodeRead(
|
||||||
|
dialogueId: number,
|
||||||
|
nodeId: string,
|
||||||
|
): Promise<ActionResult> {
|
||||||
|
try {
|
||||||
|
const { payload, user } = await authenticate();
|
||||||
|
if (!Number.isInteger(dialogueId) || dialogueId <= 0 || !nodeId.trim()) {
|
||||||
|
return { success: false, error: "Invalid conversation node reference." };
|
||||||
|
}
|
||||||
|
await markNodeRead(payload, user.id as number, dialogueId, nodeId.trim());
|
||||||
|
return { success: true };
|
||||||
|
} 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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
|
||||||
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
|
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||||
import { selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
import { selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
||||||
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
|
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
|
||||||
|
import { listSeenNodeIds } from "@/lib/npc-dialogue/states";
|
||||||
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
|
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
|
||||||
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
|
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
|
||||||
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
|
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
|
||||||
|
|
@ -158,12 +159,22 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
||||||
? await pickDialogue(payload, id, user?.id as number | undefined)
|
? await pickDialogue(payload, id, user?.id as number | undefined)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
// Server-side NEW badges: which nodes has this player already read? Empty
|
||||||
|
// when signed out or there's no conversation. Sourced from npc-dialogue-
|
||||||
|
// states so progress follows the account across devices.
|
||||||
|
const seenNodeIds =
|
||||||
|
dialogue && user
|
||||||
|
? await listSeenNodeIds(payload, user.id as number, dialogue.id)
|
||||||
|
: [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-5 flex flex-col gap-6">
|
<div className="p-5 flex flex-col gap-6">
|
||||||
<NpcProfile
|
<NpcProfile
|
||||||
npc={npc}
|
npc={npc}
|
||||||
listings={listings}
|
listings={listings}
|
||||||
conversationSlot={<NpcConversation npc={npc} dialogue={dialogue} />}
|
conversationSlot={
|
||||||
|
<NpcConversation npc={npc} dialogue={dialogue} initialSeenNodeIds={seenNodeIds} />
|
||||||
|
}
|
||||||
employmentSlot={
|
employmentSlot={
|
||||||
<EmploymentCard
|
<EmploymentCard
|
||||||
employment={employment}
|
employment={employment}
|
||||||
|
|
|
||||||
90
src/collections/game/NpcDialogueStates.ts
Normal file
90
src/collections/game/NpcDialogueStates.ts
Normal file
|
|
@ -0,0 +1,90 @@
|
||||||
|
import type { CollectionConfig } from "payload";
|
||||||
|
import hasRoles from "@/utils/access-control/hasRoles";
|
||||||
|
|
||||||
|
const STAFF_ROLES = ["admin", "developer"] as const;
|
||||||
|
|
||||||
|
function isStaff(user: Parameters<typeof hasRoles>[1]): boolean {
|
||||||
|
return hasRoles(["admin", "developer"], user);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-user read markers for conversation nodes, powering the "NEW" badges in
|
||||||
|
* the NPC conversation UI. One row per (user, dialogue, node): a node badges
|
||||||
|
* NEW until this player has read it at least once, and GM edits never
|
||||||
|
* re-flag already-read content. Replaces the old per-browser localStorage
|
||||||
|
* tracking, which reset across devices.
|
||||||
|
*/
|
||||||
|
export const NpcDialogueStates: CollectionConfig = {
|
||||||
|
slug: "npc-dialogue-states",
|
||||||
|
labels: {
|
||||||
|
singular: "Conversation Read Marker",
|
||||||
|
plural: "Conversation Read Markers",
|
||||||
|
},
|
||||||
|
admin: {
|
||||||
|
group: "Game",
|
||||||
|
useAsTitle: "nodeId",
|
||||||
|
defaultColumns: ["user", "dialogue", "nodeId", "readAt"],
|
||||||
|
description: "Per-user read markers for NPC conversation nodes (NEW badges).",
|
||||||
|
// The admin-panel `user` is a client-side user type, so check its roles
|
||||||
|
// structurally rather than through hasRoles.
|
||||||
|
hidden: ({ user }) =>
|
||||||
|
user?.collection !== "users" ||
|
||||||
|
!STAFF_ROLES.some((role) => (user.roles ?? []).includes(role)),
|
||||||
|
},
|
||||||
|
access: {
|
||||||
|
// Users can read/create their own markers; staff see everything.
|
||||||
|
read: ({ req }) => {
|
||||||
|
if (!req.user) return false;
|
||||||
|
if (isStaff(req.user)) return true;
|
||||||
|
return { user: { equals: req.user.id } };
|
||||||
|
},
|
||||||
|
create: ({ req }) => !!req.user,
|
||||||
|
update: ({ req }) => {
|
||||||
|
if (!req.user) return false;
|
||||||
|
if (isStaff(req.user)) return true;
|
||||||
|
return { user: { equals: req.user.id } };
|
||||||
|
},
|
||||||
|
delete: ({ req }) => isStaff(req.user),
|
||||||
|
},
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: "user",
|
||||||
|
type: "relationship",
|
||||||
|
relationTo: "users",
|
||||||
|
required: true,
|
||||||
|
index: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dialogue",
|
||||||
|
type: "relationship",
|
||||||
|
relationTo: "npc-dialogues",
|
||||||
|
required: true,
|
||||||
|
index: true,
|
||||||
|
admin: {
|
||||||
|
description: "The conversation this marker belongs to.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nodeId",
|
||||||
|
type: "text",
|
||||||
|
required: true,
|
||||||
|
admin: {
|
||||||
|
description: "Flowchart node id the player has read.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "readAt",
|
||||||
|
type: "date",
|
||||||
|
admin: {
|
||||||
|
description: "When the user first read the node.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
// One marker per (user, dialogue, node); the mark-read action upserts on it.
|
||||||
|
fields: ["user", "dialogue", "nodeId"],
|
||||||
|
unique: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
@ -9,8 +9,6 @@ import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
|
||||||
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
|
||||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||||
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
|
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 { DOSSIER } from "@/components/frontend/operations";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
|
|
@ -27,6 +25,7 @@ import {
|
||||||
import {
|
import {
|
||||||
evaluateNpcDialogueChoices,
|
evaluateNpcDialogueChoices,
|
||||||
evaluateNpcDialogueCondition,
|
evaluateNpcDialogueCondition,
|
||||||
|
markNpcDialogueNodeRead,
|
||||||
resolveNpcDialogueTexts,
|
resolveNpcDialogueTexts,
|
||||||
triggerNpcDialogueEvent,
|
triggerNpcDialogueEvent,
|
||||||
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||||
|
|
@ -34,6 +33,10 @@ import {
|
||||||
interface NpcConversationProps {
|
interface NpcConversationProps {
|
||||||
readonly npc: GameNpc;
|
readonly npc: GameNpc;
|
||||||
readonly dialogue: { id: number; flowData?: FlowData } | null | undefined;
|
readonly dialogue: { id: number; flowData?: FlowData } | null | undefined;
|
||||||
|
/** Node ids this user has already read (server-side NEW badges). Seeds the
|
||||||
|
* local seen set; reads during the session are sent to the server and
|
||||||
|
* merged optimistically. */
|
||||||
|
readonly initialSeenNodeIds?: readonly string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ResolvedFlow {
|
interface ResolvedFlow {
|
||||||
|
|
@ -70,7 +73,7 @@ function nodeText(node: DialogueNode): string {
|
||||||
return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || "";
|
return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || "";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConversationProps) {
|
||||||
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
|
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [log, setLog] = useState<LogEntry[]>([]);
|
const [log, setLog] = useState<LogEntry[]>([]);
|
||||||
|
|
@ -87,12 +90,12 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
||||||
* the server when the conversation lands on a choice node. Cleared on
|
* the server when the conversation lands on a choice node. Cleared on
|
||||||
* every `begin()` so flags gained mid-conversation are re-checked. */
|
* every `begin()` so flags gained mid-conversation are re-checked. */
|
||||||
const [choiceGates, setChoiceGates] = useState<Record<string, ChoiceGate[]>>({});
|
const [choiceGates, setChoiceGates] = useState<Record<string, ChoiceGate[]>>({});
|
||||||
/** Per-browser read progress powering the NEW badges. Loaded after mount so
|
/** Node ids this player has read, powering the NEW badges. Seeded from the
|
||||||
* server and client markup agree (localStorage is invisible to SSR). */
|
* server (npc-dialogue-states); nodes read in this session are added here
|
||||||
const [seenMap, setSeenMap] = useState<SeenMap>({});
|
* optimistically and persisted via `markNpcDialogueNodeRead`. */
|
||||||
useEffect(() => {
|
const [seenNodes, setSeenNodes] = useState<Set<string>>(
|
||||||
setSeenMap(loadSeenMap());
|
() => new Set(initialSeenNodeIds ?? []),
|
||||||
}, []);
|
);
|
||||||
const seq = useRef(0);
|
const seq = useRef(0);
|
||||||
const sessionRef = useRef(0);
|
const sessionRef = useRef(0);
|
||||||
const scrollRef = useRef<HTMLDivElement>(null);
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
@ -140,30 +143,24 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
|
||||||
};
|
};
|
||||||
}, [open, flow, activeChoiceNodeId, choiceGates, npc.id]);
|
}, [open, flow, activeChoiceNodeId, choiceGates, npc.id]);
|
||||||
|
|
||||||
// NEW badge inputs: current flowchart signature + the nodes this browser
|
// NEW badge input: nodes in this flow the player has never read. Server-
|
||||||
// has not read yet (a GM edit changes the hash and re-flags everything).
|
// sourced, so badges follow the account across devices; GM edits no longer
|
||||||
const seenKey = dialogue ? String(dialogue.id) : "";
|
// re-flag content the player already saw.
|
||||||
const flowSignature = useMemo(() => flowHash(dialogue?.flowData), [dialogue]);
|
|
||||||
const allNodeIds = useMemo(() => (flow ? flow.nodes.map((n) => n.id) : []), [flow]);
|
const allNodeIds = useMemo(() => (flow ? flow.nodes.map((n) => n.id) : []), [flow]);
|
||||||
const unseenTargets = useMemo(
|
const unseenTargets = useMemo(
|
||||||
() => new Set(unseenNodeIds(seenMap[seenKey], flowSignature, allNodeIds)),
|
() => new Set(allNodeIds.filter((id) => !seenNodes.has(id))),
|
||||||
[seenMap, seenKey, flowSignature, allNodeIds],
|
[seenNodes, allNodeIds],
|
||||||
);
|
);
|
||||||
|
|
||||||
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
|
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
|
||||||
|
|
||||||
/** Records that this browser has read a node (persisted, idempotent). */
|
/** Marks a node read: clears its badge locally right away and persists the
|
||||||
|
* marker server-side fire-and-forget (a failed write just re-badges on the
|
||||||
|
* next load; the action itself is idempotent). */
|
||||||
const markSeen = (nodeId: string) => {
|
const markSeen = (nodeId: string) => {
|
||||||
setSeenMap((prev) => {
|
if (!dialogue || seenNodes.has(nodeId)) return;
|
||||||
const entry = prev[seenKey];
|
setSeenNodes((prev) => new Set(prev).add(nodeId));
|
||||||
if (entry && entry.hash === flowSignature && entry.nodes.includes(nodeId)) return prev;
|
void markNpcDialogueNodeRead(dialogue.id, nodeId).catch(() => undefined);
|
||||||
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
|
/** Resolves the node's display strings server-side (flag tokens), then
|
||||||
|
|
|
||||||
|
|
@ -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;
|
|
||||||
}
|
|
||||||
73
src/lib/npc-dialogue/states.ts
Normal file
73
src/lib/npc-dialogue/states.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
||||||
|
import type { Payload } from "payload";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read markers powering the conversation NEW badges (npc-dialogue-states).
|
||||||
|
* One row per (user, dialogue, nodeId): a node badges NEW until the player
|
||||||
|
* has read it at least once. Server-side so progress follows the account
|
||||||
|
* across devices, and GM edits never re-flag already-read content.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Node ids of `dialogueId` this user has already read. */
|
||||||
|
export async function listSeenNodeIds(
|
||||||
|
payload: Payload,
|
||||||
|
userId: number,
|
||||||
|
dialogueId: number,
|
||||||
|
): Promise<string[]> {
|
||||||
|
const res = await payload.find({
|
||||||
|
collection: "npc-dialogue-states",
|
||||||
|
where: {
|
||||||
|
and: [{ user: { equals: userId } }, { dialogue: { equals: dialogueId } }],
|
||||||
|
},
|
||||||
|
limit: 500,
|
||||||
|
depth: 0,
|
||||||
|
select: { nodeId: true },
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
return res.docs.map((doc) => doc.nodeId).filter((id): id is string => Boolean(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Record that the user read one conversation node. Idempotent: repeated
|
||||||
|
* calls for the same node are no-ops (the unique index makes racing writes
|
||||||
|
* safe too - a duplicate just resolves to the existing row).
|
||||||
|
*/
|
||||||
|
export async function markNodeRead(
|
||||||
|
payload: Payload,
|
||||||
|
userId: number,
|
||||||
|
dialogueId: number,
|
||||||
|
nodeId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const existing = await payload.find({
|
||||||
|
collection: "npc-dialogue-states",
|
||||||
|
where: {
|
||||||
|
and: [
|
||||||
|
{ user: { equals: userId } },
|
||||||
|
{ dialogue: { equals: dialogueId } },
|
||||||
|
{ nodeId: { equals: nodeId } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
limit: 1,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
if (existing.docs.length > 0) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await payload.create({
|
||||||
|
collection: "npc-dialogue-states",
|
||||||
|
data: {
|
||||||
|
user: userId,
|
||||||
|
dialogue: dialogueId,
|
||||||
|
nodeId,
|
||||||
|
readAt: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// A concurrent write won the race against the unique index: the marker
|
||||||
|
// exists either way, which is all this call promises.
|
||||||
|
const message = error instanceof Error ? error.message : "";
|
||||||
|
if (!/duplicate key|violates unique constraint/i.test(message)) throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
40958
src/migrations/20261014_192950_add_npc_dialogue_states.json
Normal file
40958
src/migrations/20261014_192950_add_npc_dialogue_states.json
Normal file
File diff suppressed because it is too large
Load diff
43
src/migrations/20261014_192950_add_npc_dialogue_states.ts
Normal file
43
src/migrations/20261014_192950_add_npc_dialogue_states.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
||||||
|
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||||
|
|
||||||
|
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
CREATE TABLE "npc_dialogue_states" (
|
||||||
|
"id" serial PRIMARY KEY NOT NULL,
|
||||||
|
"user_id" integer NOT NULL,
|
||||||
|
"dialogue_id" integer NOT NULL,
|
||||||
|
"node_id" varchar NOT NULL,
|
||||||
|
"read_at" timestamp(3) with time zone,
|
||||||
|
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||||
|
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_find" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_create" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_update" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_delete" boolean DEFAULT false;
|
||||||
|
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "npc_dialogue_states_id" integer;
|
||||||
|
ALTER TABLE "npc_dialogue_states" ADD CONSTRAINT "npc_dialogue_states_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
|
||||||
|
ALTER TABLE "npc_dialogue_states" ADD CONSTRAINT "npc_dialogue_states_dialogue_id_npc_dialogues_id_fk" FOREIGN KEY ("dialogue_id") REFERENCES "public"."npc_dialogues"("id") ON DELETE set null ON UPDATE no action;
|
||||||
|
CREATE INDEX "npc_dialogue_states_user_idx" ON "npc_dialogue_states" USING btree ("user_id");
|
||||||
|
CREATE INDEX "npc_dialogue_states_dialogue_idx" ON "npc_dialogue_states" USING btree ("dialogue_id");
|
||||||
|
CREATE INDEX "npc_dialogue_states_updated_at_idx" ON "npc_dialogue_states" USING btree ("updated_at");
|
||||||
|
CREATE INDEX "npc_dialogue_states_created_at_idx" ON "npc_dialogue_states" USING btree ("created_at");
|
||||||
|
CREATE UNIQUE INDEX "user_dialogue_nodeId_idx" ON "npc_dialogue_states" USING btree ("user_id","dialogue_id","node_id");
|
||||||
|
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_npc_dialogue_states_fk" FOREIGN KEY ("npc_dialogue_states_id") REFERENCES "public"."npc_dialogue_states"("id") ON DELETE cascade ON UPDATE no action;
|
||||||
|
CREATE INDEX "payload_locked_documents_rels_npc_dialogue_states_id_idx" ON "payload_locked_documents_rels" USING btree ("npc_dialogue_states_id");`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "npc_dialogue_states" DISABLE ROW LEVEL SECURITY;
|
||||||
|
DROP TABLE "npc_dialogue_states" CASCADE;
|
||||||
|
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_npc_dialogue_states_fk";
|
||||||
|
|
||||||
|
DROP INDEX "payload_locked_documents_rels_npc_dialogue_states_id_idx";
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_find";
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_create";
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_update";
|
||||||
|
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_delete";
|
||||||
|
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "npc_dialogue_states_id";`)
|
||||||
|
}
|
||||||
|
|
@ -134,6 +134,7 @@ import * as migration_20261012_182016_add_journals_event_target from './20261012
|
||||||
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
|
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
|
||||||
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
|
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
|
||||||
import * as migration_20261013_184745_add_garage_fields from './20261013_184745_add_garage_fields';
|
import * as migration_20261013_184745_add_garage_fields from './20261013_184745_add_garage_fields';
|
||||||
|
import * as migration_20261014_192950_add_npc_dialogue_states from './20261014_192950_add_npc_dialogue_states';
|
||||||
|
|
||||||
export const migrations = [
|
export const migrations = [
|
||||||
{
|
{
|
||||||
|
|
@ -814,6 +815,11 @@ export const migrations = [
|
||||||
{
|
{
|
||||||
up: migration_20261013_184745_add_garage_fields.up,
|
up: migration_20261013_184745_add_garage_fields.up,
|
||||||
down: migration_20261013_184745_add_garage_fields.down,
|
down: migration_20261013_184745_add_garage_fields.down,
|
||||||
name: '20261013_184745_add_garage_fields'
|
name: '20261013_184745_add_garage_fields',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
up: migration_20261014_192950_add_npc_dialogue_states.up,
|
||||||
|
down: migration_20261014_192950_add_npc_dialogue_states.down,
|
||||||
|
name: '20261014_192950_add_npc_dialogue_states'
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -76,6 +76,7 @@ export interface Config {
|
||||||
'game-npcs': GameNpc;
|
'game-npcs': GameNpc;
|
||||||
'npc-staffing': NpcStaffing;
|
'npc-staffing': NpcStaffing;
|
||||||
'npc-dialogues': NpcDialogue;
|
'npc-dialogues': NpcDialogue;
|
||||||
|
'npc-dialogue-states': NpcDialogueState;
|
||||||
'player-flags': PlayerFlag;
|
'player-flags': PlayerFlag;
|
||||||
'reinforcement-pools': ReinforcementPool;
|
'reinforcement-pools': ReinforcementPool;
|
||||||
'labor-classifications': LaborClassification;
|
'labor-classifications': LaborClassification;
|
||||||
|
|
@ -183,6 +184,7 @@ export interface Config {
|
||||||
'game-npcs': GameNpcsSelect<false> | GameNpcsSelect<true>;
|
'game-npcs': GameNpcsSelect<false> | GameNpcsSelect<true>;
|
||||||
'npc-staffing': NpcStaffingSelect<false> | NpcStaffingSelect<true>;
|
'npc-staffing': NpcStaffingSelect<false> | NpcStaffingSelect<true>;
|
||||||
'npc-dialogues': NpcDialoguesSelect<false> | NpcDialoguesSelect<true>;
|
'npc-dialogues': NpcDialoguesSelect<false> | NpcDialoguesSelect<true>;
|
||||||
|
'npc-dialogue-states': NpcDialogueStatesSelect<false> | NpcDialogueStatesSelect<true>;
|
||||||
'player-flags': PlayerFlagsSelect<false> | PlayerFlagsSelect<true>;
|
'player-flags': PlayerFlagsSelect<false> | PlayerFlagsSelect<true>;
|
||||||
'reinforcement-pools': ReinforcementPoolsSelect<false> | ReinforcementPoolsSelect<true>;
|
'reinforcement-pools': ReinforcementPoolsSelect<false> | ReinforcementPoolsSelect<true>;
|
||||||
'labor-classifications': LaborClassificationsSelect<false> | LaborClassificationsSelect<true>;
|
'labor-classifications': LaborClassificationsSelect<false> | LaborClassificationsSelect<true>;
|
||||||
|
|
@ -2668,6 +2670,30 @@ export interface NpcDialogue {
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Per-user read markers for NPC conversation nodes (NEW badges).
|
||||||
|
*
|
||||||
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
|
* via the `definition` "npc-dialogue-states".
|
||||||
|
*/
|
||||||
|
export interface NpcDialogueState {
|
||||||
|
id: number;
|
||||||
|
user: number | User;
|
||||||
|
/**
|
||||||
|
* The conversation this marker belongs to.
|
||||||
|
*/
|
||||||
|
dialogue: number | NpcDialogue;
|
||||||
|
/**
|
||||||
|
* Flowchart node id the player has read.
|
||||||
|
*/
|
||||||
|
nodeId: string;
|
||||||
|
/**
|
||||||
|
* When the user first read the node.
|
||||||
|
*/
|
||||||
|
readAt?: string | null;
|
||||||
|
updatedAt: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* This interface was referenced by `Config`'s JSON-Schema
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "player-flags".
|
* via the `definition` "player-flags".
|
||||||
|
|
@ -6715,6 +6741,24 @@ export interface PayloadMcpApiKey {
|
||||||
*/
|
*/
|
||||||
delete?: boolean | null;
|
delete?: boolean | null;
|
||||||
};
|
};
|
||||||
|
npcDialogueStates?: {
|
||||||
|
/**
|
||||||
|
* Allow clients to find npc-dialogue-states.
|
||||||
|
*/
|
||||||
|
find?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to create npc-dialogue-states.
|
||||||
|
*/
|
||||||
|
create?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to update npc-dialogue-states.
|
||||||
|
*/
|
||||||
|
update?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to delete npc-dialogue-states.
|
||||||
|
*/
|
||||||
|
delete?: boolean | null;
|
||||||
|
};
|
||||||
playerFlags?: {
|
playerFlags?: {
|
||||||
/**
|
/**
|
||||||
* Allow clients to find player-flags.
|
* Allow clients to find player-flags.
|
||||||
|
|
@ -8236,6 +8280,10 @@ export interface PayloadLockedDocument {
|
||||||
relationTo: 'npc-dialogues';
|
relationTo: 'npc-dialogues';
|
||||||
value: number | NpcDialogue;
|
value: number | NpcDialogue;
|
||||||
} | null)
|
} | null)
|
||||||
|
| ({
|
||||||
|
relationTo: 'npc-dialogue-states';
|
||||||
|
value: number | NpcDialogueState;
|
||||||
|
} | null)
|
||||||
| ({
|
| ({
|
||||||
relationTo: 'player-flags';
|
relationTo: 'player-flags';
|
||||||
value: number | PlayerFlag;
|
value: number | PlayerFlag;
|
||||||
|
|
@ -8923,6 +8971,18 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
|
||||||
updatedAt?: T;
|
updatedAt?: T;
|
||||||
createdAt?: T;
|
createdAt?: T;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
|
* via the `definition` "npc-dialogue-states_select".
|
||||||
|
*/
|
||||||
|
export interface NpcDialogueStatesSelect<T extends boolean = true> {
|
||||||
|
user?: T;
|
||||||
|
dialogue?: T;
|
||||||
|
nodeId?: T;
|
||||||
|
readAt?: T;
|
||||||
|
updatedAt?: T;
|
||||||
|
createdAt?: T;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* This interface was referenced by `Config`'s JSON-Schema
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "player-flags_select".
|
* via the `definition` "player-flags_select".
|
||||||
|
|
@ -11356,6 +11416,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
||||||
update?: T;
|
update?: T;
|
||||||
delete?: T;
|
delete?: T;
|
||||||
};
|
};
|
||||||
|
npcDialogueStates?:
|
||||||
|
| T
|
||||||
|
| {
|
||||||
|
find?: T;
|
||||||
|
create?: T;
|
||||||
|
update?: T;
|
||||||
|
delete?: T;
|
||||||
|
};
|
||||||
playerFlags?:
|
playerFlags?:
|
||||||
| T
|
| T
|
||||||
| {
|
| {
|
||||||
|
|
|
||||||
|
|
@ -57,6 +57,7 @@ import { GameVehicles } from "@/collections/game/GameVehicles";
|
||||||
import { GameNpcs } from "@/collections/game/GameNpcs";
|
import { GameNpcs } from "@/collections/game/GameNpcs";
|
||||||
import { NpcStaffing } from "@/collections/game/NpcStaffing";
|
import { NpcStaffing } from "@/collections/game/NpcStaffing";
|
||||||
import { NpcDialogues } from "@/collections/game/NpcDialogues";
|
import { NpcDialogues } from "@/collections/game/NpcDialogues";
|
||||||
|
import { NpcDialogueStates } from "@/collections/game/NpcDialogueStates";
|
||||||
import { PlayerFlags } from "@/collections/game/PlayerFlags";
|
import { PlayerFlags } from "@/collections/game/PlayerFlags";
|
||||||
import { ReinforcementPools } from "@/collections/game/ReinforcementPools";
|
import { ReinforcementPools } from "@/collections/game/ReinforcementPools";
|
||||||
import { LaborClassifications } from "@/collections/game/LaborClassifications";
|
import { LaborClassifications } from "@/collections/game/LaborClassifications";
|
||||||
|
|
@ -280,6 +281,7 @@ const collections = [
|
||||||
GameNpcs,
|
GameNpcs,
|
||||||
NpcStaffing,
|
NpcStaffing,
|
||||||
NpcDialogues,
|
NpcDialogues,
|
||||||
|
NpcDialogueStates,
|
||||||
PlayerFlags,
|
PlayerFlags,
|
||||||
ReinforcementPools,
|
ReinforcementPools,
|
||||||
LaborClassifications,
|
LaborClassifications,
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,6 @@ import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
|
||||||
import { DialogueText, formatRemaining } from "@/lib/npc-dialogue/DialogueText";
|
import { DialogueText, formatRemaining } from "@/lib/npc-dialogue/DialogueText";
|
||||||
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
|
||||||
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
|
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
|
||||||
import { flowHash, mergeSeenNodes, unseenNodeIds } from "@/lib/npc-dialogue/seen";
|
|
||||||
import {
|
import {
|
||||||
collectNodeTokens,
|
collectNodeTokens,
|
||||||
extractCountdownKeys,
|
extractCountdownKeys,
|
||||||
|
|
@ -455,55 +454,3 @@ describe("countdown token resolution (pure)", () => {
|
||||||
expect(out.hints?.[1]).toBe("");
|
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"]);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue