1
0
Fork 0
polaris-task-force/src/app/(frontend)/intelligence/tech-tree/page.tsx
Z8MB1E 48556c3688 feat(tech-tree): add note nodes with optional frontend visibility
Planners can now drop annotation cards on the Tech Tree canvas without inventing fake technologies. Notes live in their own tech-tree-notes collection (title, body, treePosition) and carry no prerequisites, costs, approval workflow or research state, so the layout engine, edge builder and research rules never see them.

showOnFrontend defaults to false, making notes a backend authoring aid; ticking it publishes the amber card read-only to the member tech tree, which queries showOnFrontend = true.

Canvas work: amber NoteNode card with no connection handles, NoteDialog for create/edit/delete, a New Note toolbar button (technologies:create gated), viewport-centre placement, and namespaced note-<id> React Flow ids so note and technology ids can never collide. Note drags, Save positions and Auto-arrange reuse the single-statement bulk /api/tech-tree/positions write by sending collection: "tech-tree-notes"; no PATCH-per-note path was added.

Also fixes the note card body being clipped by the inherited line-height: the classification strip and footer now have fixed heights with leading-none, and the body takes the remaining flex space instead of line-clamp.

Tests: tech-tree-notes.int.spec.ts (defaults, required title, publication filter, in-place edits, note layout and id namespacing) plus note coverage in tech-tree-positions.int.spec.ts. Migration 20261123_073019_add_tech_tree_notes must be run on prod after deploy.
2026-11-23 03:11:36 -05:00

256 lines
9.1 KiB
TypeScript

import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import type { Metadata } from "next";
import { mapCategoryDoc, mapNoteDoc, mapTechDoc } from "@/components/admin/tech-tree/mappers";
import { TechTreeClient } from "@/components/frontend/techTree/TechTreeClient";
import type {
ActiveResearchView,
BallotView,
QueuedResearchView,
TechDetailView,
TechViewState,
} from "@/components/frontend/techTree/types";
import { relationshipId } from "@/lib/base/storage";
import { loadResearchCapacity } from "@/lib/tech/capacity";
import { eligibleTechs, technologyToEligibility } from "@/lib/tech/research";
export const metadata: Metadata = {
title: "Tech Tree: Polaris Task Force",
};
/**
* Member-facing tech tree (read-only). Guests never reach this route: the
* (frontend) layout renders LandingPage for them. The canvas shows approved
* technologies only; approved-but-locked ones render as blackout veil cards.
*/
export default async function FrontendTechTreePage() {
const payload = await getPayload({ config });
const { user } = await payload.auth({ headers: await nextHeaders(), canSetHeaders: false });
if (!user) return null; // type-guard only; the layout gate handles guests
const [capacity, techsRes, categoriesRes, notesRes, resourcesRes, researchesRes, ballotsRes] =
await Promise.all([
loadResearchCapacity(payload),
payload.find({
collection: "technologies",
where: { approvalStatus: { equals: "approved" } },
depth: 0,
limit: 0,
sort: "name",
user,
overrideAccess: false,
}),
payload.find({
collection: "tech-categories",
depth: 0,
limit: 0,
sort: "position",
user,
overrideAccess: false,
}),
payload.find({
collection: "tech-tree-notes",
// Backend-only notes never reach members: the collection defaults the
// flag to false, so this WHERE is the only publication gate.
where: { showOnFrontend: { equals: true } },
depth: 0,
limit: 0,
sort: "createdAt",
user,
overrideAccess: false,
}),
payload.find({
collection: "resources",
depth: 0,
limit: 0,
sort: "name",
user,
overrideAccess: false,
}),
payload.find({
collection: "tech-researches",
where: { status: { in: ["active", "queued"] } },
sort: "createdAt",
depth: 0,
limit: 50,
user,
overrideAccess: false,
}),
payload.find({
collection: "tech-ballots",
where: { status: { in: ["open", "extended"] } },
sort: "-opensAt",
depth: 0,
limit: 1,
user,
overrideAccess: false,
}),
]);
const techDocs = techsRes.docs as unknown as Record<string, any>[];
const techById = new Map(techDocs.map((doc) => [doc.id as number, doc]));
const resourceNameById = new Map(resourcesRes.docs.map((doc) => [doc.id, doc.name]));
// --- research state -----------------------------------------------------
type BusyEntry = { status: "active" | "queued"; startedAt: string | null; etaAt: string | null };
const busyByTechnology = new Map<number, BusyEntry>();
for (const research of researchesRes.docs) {
const technologyId = relationshipId(research.technology);
if (technologyId == null) continue;
const existing = busyByTechnology.get(technologyId);
// active wins over queued for the node overlay
if (!existing || research.status === "active") {
busyByTechnology.set(technologyId, {
status: research.status as "active" | "queued",
startedAt: research.startedAt ?? null,
etaAt: research.etaAt ?? null,
});
}
}
const researchedIds = new Set(
techDocs.filter((doc) => doc.researchedAt).map((doc) => doc.id as number),
);
const eligibility = eligibleTechs(techDocs.map((doc) => technologyToEligibility(doc)), {
researchedIds,
busyIds: new Set(busyByTechnology.keys()),
});
const eligibleIds = new Set(eligibility.map((tech) => tech.id));
const statuses: Record<number, TechViewState> = {};
for (const doc of techDocs) {
const id = doc.id as number;
const busy = busyByTechnology.get(id);
if (doc.researchedAt) {
statuses[id] = { state: "unlocked", researchedAt: String(doc.researchedAt) };
} else if (busy?.status === "active") {
statuses[id] = { state: "researching", startedAt: busy.startedAt, etaAt: busy.etaAt };
} else if (busy?.status === "queued") {
statuses[id] = { state: "queued" };
} else if (eligibleIds.has(id)) {
statuses[id] = { state: "available" };
} else {
statuses[id] = { state: "locked" };
}
}
// --- dialog details (veiled techs deliberately get none) -----------------
const details: Record<number, TechDetailView> = {};
for (const doc of techDocs) {
const id = doc.id as number;
const state = statuses[id].state;
if (state === "locked") continue;
const eligibilityTech = technologyToEligibility(doc);
details[id] = {
technologyId: id,
name: String(doc.name ?? ""),
type: String(doc.type ?? "upgrade"),
summary: String(doc.summary ?? ""),
description: doc.description ?? null,
state,
researchedAt: doc.researchedAt ? String(doc.researchedAt) : null,
startedAt: statuses[id].startedAt ?? null,
etaAt: statuses[id].etaAt ?? null,
minimumResearchDuration: doc.researchCosts?.minimumResearchDuration ?? null,
maximumResearchDuration: doc.researchCosts?.maximumResearchDuration ?? null,
resourceCosts: (((doc.researchCosts?.resources ?? []) as any[]) ).map((row) => ({
resourceId: relationshipId(row.resource) ?? 0,
name:
typeof row.resource === "object" && row.resource?.name
? String(row.resource.name)
: resourceNameById.get(relationshipId(row.resource) ?? -1) ?? "Resource",
amount: row.amount ?? 0,
})),
prereqAndIds: [...eligibilityTech.prereqAnd],
prereqOrIds: [...eligibilityTech.prereqOr],
};
}
const activeResearch: ActiveResearchView[] = researchesRes.docs
.filter((research) => research.status === "active")
.map((research) => {
const technologyId = relationshipId(research.technology);
return {
id: research.id,
technologyId: technologyId ?? -1,
name: technologyId != null ? String(techById.get(technologyId)?.name ?? "Unknown") : "Unknown",
startedAt: research.startedAt ?? null,
etaAt: research.etaAt ?? null,
};
});
const queuedResearch: QueuedResearchView[] = researchesRes.docs
.filter((research) => research.status === "queued")
.map((research) => {
const technologyId = relationshipId(research.technology);
return {
id: research.id,
technologyId: technologyId ?? -1,
name: technologyId != null ? String(techById.get(technologyId)?.name ?? "Unknown") : "Unknown",
};
});
// --- open ballot + raw tallies -------------------------------------------
const ballotDoc = ballotsRes.docs[0];
let ballot: BallotView | null = null;
if (ballotDoc) {
const votesRes = await payload.find({
collection: "tech-ballot-votes",
where: { ballot: { equals: ballotDoc.id } },
depth: 0,
limit: 2000,
user,
overrideAccess: false,
});
const rawVotes = new Map<number, number>();
let myVote: number | null = null;
for (const vote of votesRes.docs) {
const technologyId = relationshipId(vote.technology);
if (technologyId == null) continue;
rawVotes.set(technologyId, (rawVotes.get(technologyId) ?? 0) + 1);
if (relationshipId(vote.user) === user.id) myVote = technologyId;
}
ballot = {
id: ballotDoc.id,
status: ballotDoc.status as "open" | "extended",
closesAt: ballotDoc.closesAt,
totalVotes: votesRes.totalDocs,
myVote,
options: ballotDoc.options.flatMap((option) => {
const technologyId = relationshipId(option.technology);
if (technologyId == null) return [];
return [
{
technologyId,
name: option.name,
summary: option.summary ?? null,
rawVotes: rawVotes.get(technologyId) ?? 0,
},
];
}),
};
}
return (
<div className="flex h-[calc(100dvh-7.5rem)] min-h-0 flex-col p-4">
<TechTreeClient
techs={techDocs.map((doc) => mapTechDoc(doc))}
categories={categoriesRes.docs.map((doc) => mapCategoryDoc(doc as unknown as Record<string, unknown>))}
notes={notesRes.docs.map((doc) => mapNoteDoc(doc as unknown as Record<string, unknown>))}
statuses={statuses}
details={details}
activeResearch={activeResearch}
queuedResearch={queuedResearch}
ballot={ballot}
stats={{
enabled: capacity.enabled,
slots: capacity.capacity.slots,
facilityCount: capacity.capacity.facilityCount,
totalResearchers: capacity.capacity.totalResearchers,
totalModifier: capacity.capacity.totalModifier,
}}
/>
</div>
);
}