diff --git a/src/app/(frontend)/intelligence/tech-tree/page.tsx b/src/app/(frontend)/intelligence/tech-tree/page.tsx index c0447937..9d1a073f 100644 --- a/src/app/(frontend)/intelligence/tech-tree/page.tsx +++ b/src/app/(frontend)/intelligence/tech-tree/page.tsx @@ -3,7 +3,7 @@ import { getPayload } from "payload"; import { headers as nextHeaders } from "next/headers"; import type { Metadata } from "next"; -import { mapCategoryDoc, mapTechDoc } from "@/components/admin/tech-tree/mappers"; +import { mapCategoryDoc, mapNoteDoc, mapTechDoc } from "@/components/admin/tech-tree/mappers"; import { TechTreeClient } from "@/components/frontend/techTree/TechTreeClient"; import type { ActiveResearchView, @@ -30,7 +30,7 @@ export default async function FrontendTechTreePage() { 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, resourcesRes, researchesRes, ballotsRes] = + const [capacity, techsRes, categoriesRes, notesRes, resourcesRes, researchesRes, ballotsRes] = await Promise.all([ loadResearchCapacity(payload), payload.find({ @@ -50,6 +50,17 @@ export default async function FrontendTechTreePage() { 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, @@ -226,6 +237,7 @@ export default async function FrontendTechTreePage() { mapTechDoc(doc))} categories={categoriesRes.docs.map((doc) => mapCategoryDoc(doc as unknown as Record))} + notes={notesRes.docs.map((doc) => mapNoteDoc(doc as unknown as Record))} statuses={statuses} details={details} activeResearch={activeResearch} diff --git a/src/app/api/tech-tree/positions/route.ts b/src/app/api/tech-tree/positions/route.ts index 2d7bfa85..9bc7437e 100644 --- a/src/app/api/tech-tree/positions/route.ts +++ b/src/app/api/tech-tree/positions/route.ts @@ -10,16 +10,21 @@ export const dynamic = "force-dynamic"; export const runtime = "nodejs"; /** - * Bulk Tech Tree position write: `{ positions: [{ id, x, y, ifUnmodifiedAt? }] }`, - * where a null x/y returns a technology to the automatic layout and + * Bulk Tech Tree position write: `{ collection?, positions: [{ id, x, y, ifUnmodifiedAt? }] }`, + * where a null x/y returns a node to the automatic layout and * `ifUnmodifiedAt` (the loaded `updatedAt`) makes that row conditional: one * mismatched precondition rejects the whole batch with HTTP 409 and the * conflicting ids. Used by every canvas position write (drags, Save positions, * Auto-arrange, freeze pins) so they cost one request and one SQL statement * instead of a PATCH per node. * + * `collection` defaults to `technologies`; note nodes on the same canvas send + * `tech-tree-notes` and share the exact same write path. + * * Access mirrors the technologies collection's update rule: the - * `technologies:update` permission OR Intelligence division membership. + * `technologies:update` permission OR Intelligence division membership. Note + * nodes reuse the technologies permissions on purpose (they are a canvas + * annotation, not a separate domain). */ export async function POST(req: NextRequest) { const payload = await getPayload({ config: await config }); @@ -46,12 +51,12 @@ export async function POST(req: NextRequest) { } try { - const result = await writeTreePositions(payload, parsed.updates); + const result = await writeTreePositions(payload, parsed.updates, parsed.collection); if (result.conflicts.length > 0) { return NextResponse.json( { error: - "Some positions could not be saved: those technologies changed since you loaded them.", + "Some positions could not be saved: those nodes changed since you loaded them.", conflicts: result.conflicts, }, { status: 409 }, diff --git a/src/collections/intelligence/TechTreeNotes.ts b/src/collections/intelligence/TechTreeNotes.ts new file mode 100644 index 00000000..fc506054 --- /dev/null +++ b/src/collections/intelligence/TechTreeNotes.ts @@ -0,0 +1,88 @@ +import type { CollectionConfig } from "payload"; + +import { requireIntelligencePermission } from "@/utils/access-control/divisionAccess"; +import { requirePermission } from "@/utils/access-control/hasPermission"; + +/** + * Free-standing annotation cards on the Tech Tree canvas. + * + * These are deliberately NOT technologies: they carry no prerequisites, costs, + * approval workflow or research state, so they never enter the research engine + * or the member-facing progression rules. They exist so planners can leave + * explanations, goals or caveats next to the tree without inventing fake + * technologies for them. + * + * `showOnFrontend` is off by default: notes are an authoring aid first, and are + * only published to the member tech tree when someone ticks the box. + * + * The collection is hidden from the admin sidebar on purpose. Notes are created, + * edited, dragged and deleted on the `/admin/tech-tree` canvas, so their write + * access reuses the `technologies` permissions instead of introducing a parallel + * permission group that would also need its own admin-page gate. + */ +export const TechTreeNotes: CollectionConfig = { + slug: "tech-tree-notes", + labels: { + singular: "Tech Tree Note", + plural: "Tech Tree Notes", + }, + admin: { + group: "Intelligence", + useAsTitle: "title", + hidden: true, + description: + "Annotation cards on the Tech Tree canvas. Edited from /admin/tech-tree; hidden from the sidebar.", + }, + access: { + create: requireIntelligencePermission("technologies:create"), + update: requireIntelligencePermission("technologies:update"), + delete: requireIntelligencePermission("technologies:delete"), + read: requirePermission("technologies:read"), + }, + fields: [ + { + name: "title", + type: "text", + required: true, + admin: { + description: "Short heading shown on the note card.", + }, + }, + { + name: "body", + type: "textarea", + admin: { + description: "Free text shown under the title. Line breaks are preserved.", + }, + }, + { + name: "showOnFrontend", + type: "checkbox", + label: "Show on Frontend", + defaultValue: false, + admin: { + description: + "Tick to publish this note on the member-facing Tech Tree. Notes are backend-only until this is enabled.", + }, + }, + { + name: "treePosition", + type: "group", + label: "Tech Tree Position", + admin: { + description: + "Manual position on the Tech Tree canvas (set by dragging a note). Leave empty to park the note in the notes column beside the tree.", + }, + fields: [ + { + name: "x", + type: "number", + }, + { + name: "y", + type: "number", + }, + ], + }, + ], +}; diff --git a/src/components/admin/tech-tree/AGENTS.md b/src/components/admin/tech-tree/AGENTS.md index c8c880c4..1c478f4f 100644 --- a/src/components/admin/tech-tree/AGENTS.md +++ b/src/components/admin/tech-tree/AGENTS.md @@ -6,9 +6,10 @@ `/admin/tech-tree` — visual tech tree editor over `technologies`, built on `@xyflow/react` v12 following the narrative-flow patterns. Custom admin view (root view) + a "Tech Tree" nav entry injected under the Intelligence group; the Technologies list/edit views are untouched. - **Schema**: `tech-categories` collection (`src/collections/intelligence/TechCategories.ts`: `name` unique, `position` number = timeline order, optional hex `color`) + `Technologies.category` relationship (FK `ON DELETE set null`, so deleting a category just unfiles its techs) + `Technologies.treePosition` group (`x`/`y` numbers; manual canvas position from dragging, empty = automatic). Permissions mirror technologies (`tech-categories:*` + `admin:tech-categories:manage`, registered in `src/permissions/index.ts`); `tech-categories` is in `DIVISION_ADMIN_QUALIFICATIONS`, so Intelligence division members get admin-panel access exactly like `technologies`. Migrations: `20260930_230747_add_tech_categories`, `20261001_000320_add_tech_tree_position`. +- **Note nodes**: `tech-tree-notes` (`src/collections/intelligence/TechTreeNotes.ts`, `admin.hidden`, no sidebar page) are amber annotation cards on the canvas, deliberately NOT technologies: no prerequisites, cost rows, approval workflow or research state, so `computeLayout`, edge building and the research rules never see them. Fields: `title` (required), `body` (textarea, line breaks preserved), `showOnFrontend` (checkbox, **false by default**), `treePosition` group. Access reuses the `technologies` permissions (`read`/`create`/`update`/`delete`), so no permission group or admin-page gate was added; notes are created, edited and deleted only from the canvas (`NoteDialog`, "+ New Note" toolbar button) and the delete button is hidden without `technologies:delete`. A new note lands at the viewport centre; untouched notes park in an automatic column one step right of the tree (`notes.ts` `computeNoteLayout`). Note React Flow ids are namespaced `note-` (`noteNodeId`/`parseNoteNodeId`) so they can never collide with technology ids, and note cards have no handles, so they can never become prerequisite endpoints. Note drags, Save positions and Auto-arrange reuse the bulk `/api/tech-tree/positions` write by sending `collection: "tech-tree-notes"` (the route swaps the target table and the token source); never add a PATCH-per-note path. Ticking `showOnFrontend` publishes the note to the member tech tree, which queries `showOnFrontend: { equals: true }` and renders the same amber card read-only; unpublished notes never reach members. Notes are edge-routing obstacles in both canvases. - **View wiring**: `payload.config.ts` `admin.components.views.techTree` (path `/tech-tree`, component `src/components/admin/tech-tree/TechTreeView.tsx`) and `admin.components.Nav` → `TechTreeNav.tsx`. Custom root views are public by default, so the view gates itself (logged-in + `technologies:read` OR Intelligence qualification). The nav replica injects the entry into the group containing `technologies` and reuses public exports (`NavWrapper`/`NavHamburger`/`DefaultNavClient` from `@payloadcms/next/client`, `groupNavItems` from `@payloadcms/ui/shared`); registered admin components must be **default exports** (importMap convention in this repo). - **Layout** (`layout.ts`, pure): a **propagating left-to-right tree**. A technology WITH prerequisites is placed one column to the right of its parents, at their average row, so linking A -> B drops B immediately beside A and B's dependents continue further right; nothing is teleported to a distant column when its depth changes. Technologies in a category stay pinned to that category's column (the category contract); uncategorized roots fill a catalog grid whose slots come from each tech's rank among ALL uncategorized technologies (`MAX_ROWS_PER_COLUMN` = 10 rows, spilling into more columns) so promoting a tech into the tree leaves an empty slot rather than re-shuffling the grid; uncategorized dependents follow their parents inside the uncategorized zone. Collisions search rows outward from the desired row (dependents may also grow upward, and their columns are not height-capped, so a link from a full column still lands beside its parent rather than far right). Category bands are the bounding box of their members' final positions. Prerequisites placed to the RIGHT of their dependent surface as amber warnings (toolbar chip + node icon + preview panel section). - **Edges**: AND prerequisites solid slate, OR prerequisites dashed cyan with an OR label. Connections are editable on the canvas: drag from a node's right handle onto another node (the target card OR its handle) to add it as an AND prerequisite; the drop-on-card case is resolved by an `onConnectEnd` fallback because React Flow only resolves drops onto a handle. Select an edge and press Backspace to remove the prerequisite. Duplicates, self-references, and cycles (direct or transitive) are rejected by the pure `prereqEdits.ts` helpers with an inline error in the toolbar. Lines are also manually routable: selecting an edge reveals a "+" handle at each segment's midpoint (click to add a bend), bends drag to move, and double-clicking a bend removes it (`RoutedEdge.tsx` + `edgeRoutes.ts`). Routes are stored per browser in `localStorage`; making them shared would need a persisted field on the target technology. Edges also route around technologies they are not connected to: `edgeRouting.ts` detours each segment around the node rectangles it would cross (inflated by a clearance margin) and `buildRoutePath` rounds every corner. An unrouted edge keeps its automatic out/across/in shape unless that path would cut through a node, in which case it falls back to a direct line the router can bend around. - **Interactions**: nodes are draggable; dropping one PATCHes its `treePosition` (persisted, survives reload) and the toolbar shows an "Auto-arrange" button (technologies:update gated) that clears every manual position and restores the ordered layout. A **Save positions** button (technologies:update gated), next to Auto-arrange, commits the current on-screen position of every node to `treePosition` in one pass (matching what React Flow rendered, not just dragged/pinned cards) so the exact arrangement survives a reload; Auto-arrange then clears them. Dragging one card of a multi-selection moves and persists the whole selection (React Flow hands the full dragged set to `onNodeDragStop`), and a category band is draggable by its header (`dragHandle`), which moves every technology in that band. A **Snap: On/Off** toggle (default on, remembered per browser, 46px grid that divides `COLUMN_STEP`/`ROW_STEP`) snaps dragged cards to the grid. **Every canvas position write is one bulk request**: drags, Save positions, Auto-arrange, and freeze pins all POST `{ positions: [{ id, x, y }] }` to `/api/tech-tree/positions` (null x/y clears a pin), which `writeTreePositions` (`src/lib/tech-tree/positions.ts`) applies as a single `UPDATE ... FROM (VALUES ...)` on the `tree_position_x/y` columns (access = `technologies:update` or Intelligence membership, the collection's own update rule; batches capped at 2000). Never persist positions with a PATCH per node: firing dozens of concurrent document updates exhausted the database pool and could crash the server on Auto-arrange. Auto-arrange is optimistic (the canvas re-lays out on click, pins are restored if the save fails) and a spinner status chip plus disabled layout controls and node dragging cover the save. **Connecting does not move anything**: if the ordered layout would relocate the connected technology, the canvas pins it to its current spot (`treePosition` written in the same PATCH as the prerequisite) so the edge appears without the card jumping; the catalog grid also uses stable slots (each tech's rank among all uncategorized technologies, so a tech promoted into the tree leaves its slot empty instead of re-shuffling every other root). Pressing "Auto-arrange" clears those pins and moves everything, including the connected node, to its ordered position. Node click opens the side panel, which is a **lite editor** over the fields it shows (name, type, approval status, summary, category with inline create, prerequisites with AND/OR grouping and add/remove, research costs with resource rows and min/max durations): dirty tracking, Save/Reset, and an "Edit in full view" jump to the standard admin edit route. Final approval states stay superuser-only (`canSetFinalApproval` = `system:admin-access`), mirroring the field access. Quick-create dialog (name, type, summary, category, research durations) creates via REST; the category picker is a native input + suggestion list (existing values selectable, new values creatable inline) because Radix Popover inside the admin Dialog proved layer-unstable. New categories get `position = max + 1`. The canvas uses React Flow's `` so the grid scales with zoom (a CSS-background grid does not, and looked broken at low zoom), and `fitView` is capped at `maxZoom: 0.85`. Panel and toolbar controls carry dark tactical chrome (the admin panel's light shadcn defaults would render as white slabs on the dark surface; bare `