1
0
Fork 0
polaris-task-force/src/app/(frontend)/personnel/contacts/[id]/page.tsx
Z8MB1E 799c3216d2 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).
2026-10-14 15:35:47 -04:00

221 lines
7.4 KiB
TypeScript

import config from "@payload-config";
import { getPayload } from "payload";
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 { listSeenNodeIds } from "@/lib/npc-dialogue/states";
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
import { hasLogisticsQualification } from "@/utils/access-control/hasLogisticsQualification";
import type { LaborClassificationOption, StructureStaffingOption } from "@/lib/base";
import { currencyConfigFromGameRules } from "@/lib/banking";
interface NpcContactPageProps {
params: Promise<{ id: string }>;
}
export default async function NpcContactPage({ params }: NpcContactPageProps) {
const { id: idParam } = await params;
const id = Number(idParam);
if (!Number.isInteger(id) || id <= 0) notFound();
const payload = await getPayload({ config });
const headers = await nextHeaders();
const { user } = await payload.auth({ headers, canSetHeaders: false });
let npc: GameNpc;
try {
npc = (await payload.findByID({
collection: "game-npcs",
id,
depth: 2,
})) as unknown as GameNpc;
} catch {
notFound();
}
if (!npc) notFound();
const staffingRes = await payload.find({
collection: "npc-staffing",
where: {
and: [{ npc: { equals: id } }, { status: { equals: "active" } }],
},
limit: 1,
depth: 2,
});
const staffing = staffingRes.docs[0] as NpcStaffing | undefined;
const staffingStructure = staffing?.structure;
const structureName =
typeof staffingStructure === "object" && staffingStructure !== null
? staffingStructure.name
: typeof staffingStructure === "number"
? `Structure #${staffingStructure}`
: null;
const employment =
staffing && structureName
? {
positionTitle: staffing.positionTitle,
positionType: staffing.positionType,
structureName,
salary: staffing.salary ?? 0,
}
: null;
const structuresRes = await payload.find({
collection: "game-structures",
limit: 200,
depth: 0,
});
const activeStaffRes = await payload.find({
collection: "npc-staffing",
where: { status: { equals: "active" } },
limit: 1000,
depth: 0,
overrideAccess: true,
});
const structures: StructureStaffingOption[] = structuresRes.docs.map((structure) => ({
id: structure.id,
name: structure.name,
maintenanceCost: structure.maintenanceCost ?? 0,
laborRequirements: (structure.laborRequirements ?? []).map((requirement) => {
const classificationId =
typeof requirement.classification === "object"
? requirement.classification.id
: requirement.classification;
return {
classificationId,
requiredHeadcount: requirement.requiredHeadcount,
maxHeadcount: requirement.maxHeadcount ?? 0,
enforcedSalary: requirement.enforcedSalary ?? null,
currentHeadcount: activeStaffRes.docs
.filter((entry) => {
const structureId =
typeof entry.structure === "object" ? entry.structure.id : entry.structure;
const laborClassificationId =
typeof entry.laborClassification === "object" && entry.laborClassification !== null
? entry.laborClassification.id
: entry.laborClassification;
return structureId === structure.id && laborClassificationId === classificationId;
})
.reduce((total, entry) => total + (entry.headcount ?? 1), 0),
};
}),
staffPositions: (structure.staffPositions ?? []).map((position) => ({
positionType: position.positionType,
max: position.max ?? null,
enforcedSalary: position.enforcedSalary ?? null,
currentHeadcount: activeStaffRes.docs.filter((entry) => {
const structureId =
typeof entry.structure === "object" ? entry.structure.id : entry.structure;
return (
structureId === structure.id &&
entry.npc !== null &&
entry.positionType === position.positionType
);
}).length,
})),
}));
const classificationsRes = await payload.find({
collection: "labor-classifications",
limit: 100,
depth: 0,
});
const classifications: LaborClassificationOption[] = classificationsRes.docs.map((doc) => ({
id: doc.id,
name: doc.name,
key: doc.key,
defaultUnitSalary: doc.defaultUnitSalary ?? null,
availableHeadcount: doc.availableHeadcount ?? 0,
}));
const rules = await payload.findGlobal({
slug: "game-rules",
depth: 1,
overrideAccess: true,
});
const currencyConfig = currencyConfigFromGameRules(rules);
const canManage = await hasLogisticsQualification(payload, user);
const listingsRes = await payload.find({
collection: "market-listings",
where: {
and: [{ npc: { equals: id } }, { status: { equals: "active" } }],
},
limit: 100,
depth: 1,
});
const listings = listingsRes.docs as unknown as MarketListing[];
const dialogue =
npc.canMessage === true
? await pickDialogue(payload, id, user?.id as number | undefined)
: 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 (
<div className="p-5 flex flex-col gap-6">
<NpcProfile
npc={npc}
listings={listings}
conversationSlot={
<NpcConversation npc={npc} dialogue={dialogue} initialSeenNodeIds={seenNodeIds} />
}
employmentSlot={
<EmploymentCard
employment={employment}
structures={structures}
canManage={canManage}
npcId={npc.id}
npcName={npc.name}
classifications={classifications}
hiringEnabled={Boolean(rules.staffHiringEnabled)}
hiringDisabledMessage={rules.staffHiringDisabledMessage ?? undefined}
currencyConfig={currencyConfig}
/>
}
/>
</div>
);
}
/**
* 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(
payload: Awaited<ReturnType<typeof getPayload>>,
npcId: number,
userId: number | undefined,
) {
const res = await payload.find({
collection: "npc-dialogues",
where: { npc: { equals: npcId } },
limit: 25,
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 };
}