From e52cc8319894c009f7c4a326586ab00d55bc004b Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 20 Oct 2026 18:33:43 -0400 Subject: [PATCH] feat(interior): interiors screens, sidebar entry, and launch content seed --- .../(frontend)/logistics/interiors/actions.ts | 187 +++++++ .../(frontend)/logistics/interiors/page.tsx | 160 ++++++ .../structures/[id]/interior/page.tsx | 404 ++++++++++++++ .../logistics/structures/[id]/page.tsx | 12 + src/app/(payload)/admin/importMap.js | 4 +- src/components/frontend/blocks/sidebarData.ts | 6 + .../frontend/interiors/InteriorGraphTab.tsx | 161 ++++++ .../frontend/interiors/InteriorShell.tsx | 250 +++++++++ .../frontend/interiors/JobCountdown.tsx | 53 ++ .../frontend/interiors/RoomSheet.tsx | 368 +++++++++++++ src/components/frontend/interiors/types.ts | 178 ++++++ src/tools/seed/seedEverything.ts | 4 + src/tools/seed/seedInteriorContent.ts | 517 ++++++++++++++++++ src/tools/seed/seedScrap.ts | 8 +- 14 files changed, 2308 insertions(+), 4 deletions(-) create mode 100644 src/app/(frontend)/logistics/interiors/actions.ts create mode 100644 src/app/(frontend)/logistics/interiors/page.tsx create mode 100644 src/app/(frontend)/logistics/structures/[id]/interior/page.tsx create mode 100644 src/components/frontend/interiors/InteriorGraphTab.tsx create mode 100644 src/components/frontend/interiors/InteriorShell.tsx create mode 100644 src/components/frontend/interiors/JobCountdown.tsx create mode 100644 src/components/frontend/interiors/RoomSheet.tsx create mode 100644 src/components/frontend/interiors/types.ts create mode 100644 src/tools/seed/seedInteriorContent.ts diff --git a/src/app/(frontend)/logistics/interiors/actions.ts b/src/app/(frontend)/logistics/interiors/actions.ts new file mode 100644 index 00000000..cbc0baf1 --- /dev/null +++ b/src/app/(frontend)/logistics/interiors/actions.ts @@ -0,0 +1,187 @@ +"use server"; + +import config from "@payload-config"; +import { getPayload } from "payload"; +import { revalidatePath } from "next/cache"; +import { + cancelInteriorJob, + collectInteriorJob, + startInteriorJob, + type JobStartError, +} from "@/lib/interior/jobs"; +import { canUserEnterInterior } from "@/lib/interior/access"; +import { relId } from "@/lib/interior/relations"; +import type { InteriorJobType } from "@/components/frontend/interiors/types"; + +interface ActionResult { + success: boolean; + error?: string; + data?: T; +} + +async function authenticate() { + const payloadConfig = await config; + const payload = await getPayload({ config: payloadConfig }); + const { headers } = await import("next/headers"); + const hdrs = await headers(); + const { user } = await payload.auth({ + headers: hdrs, + canSetHeaders: false, + }); + + if (!user) { + throw new Error("Unauthorized"); + } + + return { payload, user }; +} + +const START_ERRORS: Record = { + no_access: "You cannot access this interior.", + not_found: "That structure no longer exists.", + room_busy: "This room already has a job in its output slot. Collect or cancel it first.", + already_open: "This room is already open.", + nothing_to_cleanup: "There is no junk left to clear in this room.", + max_level_reached: "This room is already at its maximum level.", + fixture_blocked: "A broken fixture is blocking the station. Repair it first.", + recipe_locked: "That recipe is not unlocked at this room level.", + station_disabled: "This room's station is not enabled.", + station_locked: "That station is not unlocked at this room level.", + room_level_insufficient: "This room is below the level that recipe requires.", + recipe_disabled: "That recipe is disabled.", + insufficient_resources: "The structure does not hold the materials this job needs.", + mass_over_cap: "The structure's storage cannot hold the job output.", + no_room: "That room has not been provisioned yet. Reload the interior and try again.", + no_blueprint: "The room blueprint is missing from this structure.", + tech_locked: "The required technology has not been researched.", + labor_insufficient: "Not enough active labor of the required classification.", + room_damaged: "This room is too damaged to run that job.", + not_active: "That job is no longer active.", +}; + +const COLLECT_ERRORS: Record = { + not_ready: "That job is not ready to collect.", + storage_full: "The structure's storage cannot hold this output. Free some space and retry.", + asset_outputs_disabled: + "Asset outputs are disabled until locker storage is verified on a live server.", +}; + +function describeError(error: string | undefined, mapping: Record): string { + if (!error) return "The interior engine rejected that action."; + return mapping[error] ?? "The interior engine rejected that action."; +} + +/** Resolve the structure a job belongs to so a caller cannot act across structures. */ +async function jobStructureId( + payload: Awaited>, + jobId: number, +): Promise { + const job = await payload + .findByID({ + collection: "interior-jobs", + id: jobId, + depth: 0, + select: { structure: true }, + }) + .catch(() => null); + return job ? relId(job.structure) : null; +} + +/** Re-check the interior access gate for job actions that take only a job id. */ +async function canActOnStructure( + payload: Awaited>, + user: Awaited>["user"], + structureId: number | string, +): Promise { + const id = relId(structureId); + if (id == null) return false; + const structure = await payload + .findByID({ + collection: "game-structures", + id, + depth: 0, + select: { id: true, interior: true }, + }) + .catch(() => null); + if (!structure) return false; + return canUserEnterInterior(payload, user, structure as unknown as Record); +} + +export async function startInteriorAction( + structureId: number, + roomKey: string, + type: InteriorJobType, + target?: string | number, +): Promise> { + try { + const { payload, user } = await authenticate(); + const result = await startInteriorJob(payload, user, { structureId, roomKey, type, target }); + if (!result.ok) { + return { success: false, error: describeError(result.error, START_ERRORS) }; + } + revalidatePath(`/logistics/structures/${structureId}/interior`); + return { success: true, data: result.job.id }; + } 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 }; + } +} + +export async function cancelJobAction(jobId: number, structureId: number): Promise { + try { + const { payload, user } = await authenticate(); + const jobStructure = await jobStructureId(payload, jobId); + if (jobStructure == null) { + return { success: false, error: "That job no longer exists." }; + } + if (jobStructure !== structureId) { + return { success: false, error: "That job does not belong to this structure." }; + } + if (!(await canActOnStructure(payload, user, structureId))) { + return { success: false, error: "You cannot access this interior." }; + } + const result = await cancelInteriorJob(payload, user, jobId); + if (!result.ok) { + return { success: false, error: describeError(result.error, START_ERRORS) }; + } + revalidatePath(`/logistics/structures/${structureId}/interior`); + 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 }; + } +} + +export async function collectJobAction(jobId: number, structureId: number): Promise { + try { + const { payload, user } = await authenticate(); + const jobStructure = await jobStructureId(payload, jobId); + if (jobStructure == null) { + return { success: false, error: "That job no longer exists." }; + } + if (jobStructure !== structureId) { + return { success: false, error: "That job does not belong to this structure." }; + } + if (!(await canActOnStructure(payload, user, structureId))) { + return { success: false, error: "You cannot access this interior." }; + } + const result = await collectInteriorJob(payload, user, jobId); + if (!result.ok) { + return { success: false, error: describeError(result.error, COLLECT_ERRORS) }; + } + revalidatePath(`/logistics/structures/${structureId}/interior`); + 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 }; + } +} diff --git a/src/app/(frontend)/logistics/interiors/page.tsx b/src/app/(frontend)/logistics/interiors/page.tsx new file mode 100644 index 00000000..e2d497de --- /dev/null +++ b/src/app/(frontend)/logistics/interiors/page.tsx @@ -0,0 +1,160 @@ +import config from "@payload-config"; +import { getPayload } from "payload"; +import { headers as nextHeaders } from "next/headers"; +import Link from "next/link"; +import { Building2Icon, DoorOpenIcon } from "lucide-react"; +import type { GameStructure, Structure } from "@/payload-types"; +import { canUserEnterInterior } from "@/lib/interior/access"; +import { relId } from "@/lib/interior/relations"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@/components/ui/card"; + +/** + * Interiors list: the structures whose interior this user may enter. + * + * Discovery accepts either signal: a provisioned runtime snapshot + * (`game-structures.interior.rooms`) or a blueprint whose interior is enabled + * with authored rooms (first entry bootstraps the snapshot from it). The access + * gate is the same helper every interior action uses. + */ + +function roomCount(structure: GameStructure & { type?: Structure | number | null }): number { + const snapshot = structure.interior?.rooms; + if (Array.isArray(snapshot) && snapshot.length > 0) return snapshot.length; + // Not yet bootstrapped: fall back to the authored blueprint (depth-populated). + const blueprint = typeof structure.type === "object" ? structure.type : null; + if (blueprint?.interiorEnabled && Array.isArray(blueprint.rooms)) { + return blueprint.rooms.length; + } + return 0; +} + +export default async function InteriorsPage() { + const payloadConfig = await config; + const payload = await getPayload({ config: payloadConfig }); + const headers = await nextHeaders(); + const { user } = await payload.auth({ headers, canSetHeaders: false }); + + const structuresRes = await payload + .find({ + collection: "game-structures", + depth: 1, + limit: 50, + overrideAccess: false, + user, + }) + .catch(() => null); + + const accessible: (GameStructure & { type?: Structure | number | null })[] = []; + for (const doc of structuresRes?.docs ?? []) { + if (roomCount(doc) === 0) continue; + if (!(await canUserEnterInterior(payload, user, doc as unknown as Record))) { + continue; + } + accessible.push(doc as unknown as GameStructure & { type?: Structure | number | null }); + } + + const structureIds = accessible.map((structure) => structure.id); + const readyRes = + structureIds.length > 0 + ? await payload + .find({ + collection: "interior-jobs", + where: { + AND: [ + { structure: { in: structureIds } }, + // Cancelled jobs count as ready too: cancelling parks the + // refund on the job row and keeps the room slot occupied until + // it is collected through the normal collect path. + { status: { in: ["awaiting_collect", "cancelled"] } }, + ], + }, + limit: 100, + depth: 0, + overrideAccess: false, + user, + }) + .catch(() => null) + : null; + + const readyIds = new Set(); + for (const job of readyRes?.docs ?? []) { + const id = relId(job.structure); + if (id != null) readyIds.add(id); + } + + return ( +
+
+
+ +

Interiors

+
+

+ Structures with an interior you can enter. Clean junk, open sealed rooms, upgrade + facilities, and run equipment stations. +

+
+ + {accessible.length === 0 ? ( + + + No interiors available + + No structure interior is currently open to your account. Check back after the next + build or ask a logistics officer for access. + + + + ) : ( +
+ {accessible.map((structure) => { + const rooms = roomCount(structure); + const typeName = + typeof structure.type === "object" && structure.type !== null + ? structure.type.name + : null; + return ( + + +
+
+ + {structure.name} +
+ {typeName ?? "Structure"} +
+ {readyIds.has(structure.id) && ( + + Ready to collect + + )} +
+ + + {rooms} room{rooms === 1 ? "" : "s"} + + + + + +
+ ); + })} +
+ )} +
+ ); +} diff --git a/src/app/(frontend)/logistics/structures/[id]/interior/page.tsx b/src/app/(frontend)/logistics/structures/[id]/interior/page.tsx new file mode 100644 index 00000000..22f4fdf3 --- /dev/null +++ b/src/app/(frontend)/logistics/structures/[id]/interior/page.tsx @@ -0,0 +1,404 @@ +import config from "@payload-config"; +import { getPayload } from "payload"; +import { headers as nextHeaders } from "next/headers"; +import { notFound } from "next/navigation"; +import Link from "next/link"; +import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext"; +import { ArrowLeftIcon } from "lucide-react"; +import type { GameStructure, InteriorJob, StructureRoom } from "@/payload-types"; +import { provisionInterior } from "@/lib/interior/provision"; +import { canUserEnterInterior } from "@/lib/interior/access"; +import { relId } from "@/lib/interior/relations"; +import type { InteriorBlueprintRoom } from "@/lib/interior/types"; +import { Button } from "@/components/ui/button"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { InteriorShell } from "@/components/frontend/interiors/InteriorShell"; +import type { InteriorJobView, InteriorRoomView } from "@/components/frontend/interiors/types"; + +interface InteriorPageProps { + params: Promise<{ id: string }>; +} + +type PayloadClient = Awaited>; + +function loadStructure(payload: PayloadClient, id: number) { + return payload + .findByID({ + collection: "game-structures", + id, + depth: 1, + overrideAccess: true, + }) + .catch(() => null); +} + +function roomDescription(room: InteriorBlueprintRoom): string | null { + const value = (room as unknown as { description?: unknown }).description; + if (typeof value === "string") return value.trim() || null; + if (value && typeof value === "object") { + try { + return convertLexicalToPlaintext({ data: value as never }) || null; + } catch { + return null; + } + } + return null; +} + +function BackToStructure({ structureId }: { structureId: number }) { + return ( + + ); +} + +export default async function InteriorPage({ params }: InteriorPageProps) { + const { id } = await params; + const structureId = Number(id); + if (!Number.isFinite(structureId)) notFound(); + + const payloadConfig = await config; + const payload = await getPayload({ config: payloadConfig }); + const headers = await nextHeaders(); + const { user } = await payload.auth({ headers, canSetHeaders: false }); + + let structure = (await loadStructure(payload, structureId)) as unknown as GameStructure | null; + if (!structure) notFound(); + + // Idempotent provisioning: creates runtime room rows from the blueprint + // snapshot on first entry, then reload so the page reads the fresh snapshot. + const provisioned = await provisionInterior(payload, structure).catch(() => null); + if (provisioned?.provisioned) { + structure = + ((await loadStructure(payload, structureId)) as unknown as GameStructure | null) ?? structure; + } + + const structureRow = structure as unknown as Record; + if (!(await canUserEnterInterior(payload, user, structureRow))) { + return ( +
+
+

Interior

+

{structure.name}

+
+ + + Access denied + + Your account is not cleared to enter this structure's interior. + + + + + + +
+ ); + } + + const snapshot = structure.interior; + const blueprintRooms = Array.isArray(snapshot?.rooms) + ? (snapshot.rooms as unknown as InteriorBlueprintRoom[]) + : []; + + if (blueprintRooms.length === 0) { + return ( +
+
+

Interior

+

{structure.name}

+
+ + + No rooms provisioned + + This structure has no authored interior rooms yet. An administrator can add rooms on + the structure blueprint. + + + + + + +
+ ); + } + + const roomsRes = await payload.find({ + collection: "structure-rooms", + where: { structure: { equals: structureId } }, + limit: 100, + depth: 0, + overrideAccess: true, + }); + const runtimeRooms = roomsRes.docs as StructureRoom[]; + + const pendingJobIds = runtimeRooms + .map((room) => relId(room.pendingJob)) + .filter((value): value is number => value != null); + const jobsRes = + pendingJobIds.length > 0 + ? await payload.find({ + collection: "interior-jobs", + where: { id: { in: pendingJobIds } }, + limit: pendingJobIds.length, + depth: 0, + overrideAccess: true, + }) + : null; + const jobById = new Map((jobsRes?.docs ?? []).map((job) => [job.id, job])); + + // Collect every relationship id the UI needs to render names for, then load + // them in batch. Nothing here widens the game-structure query itself. + const resourceIds = new Set(); + const assetIds = new Set(); + const technologyIds = new Set(); + const remember = (target: Set, ref: unknown) => { + const value = relId(ref); + if (value != null) target.add(value); + }; + + for (const room of blueprintRooms) { + for (const level of room.levels ?? []) { + for (const material of level.upgradeMaterials ?? []) { + remember(resourceIds, material.resource); + } + for (const tech of level.requiredTech ?? []) remember(technologyIds, tech); + } + for (const fixture of room.fixtures ?? []) { + for (const material of fixture.repairMaterials ?? []) { + remember(resourceIds, material.resource); + } + } + for (const recipe of room.station?.recipes ?? []) { + for (const input of recipe.inputs ?? []) remember(resourceIds, input.resource); + for (const output of recipe.outputs ?? []) { + if (output.kind === "asset") remember(assetIds, output.item); + else remember(resourceIds, output.item); + } + } + } + for (const job of jobById.values()) { + for (const row of job.output?.resources ?? []) remember(resourceIds, row.resource); + for (const row of job.output?.assets ?? []) remember(assetIds, row.asset); + } + + const [resourcesRes, assetsRes, technologiesRes] = await Promise.all([ + resourceIds.size > 0 + ? payload.find({ + collection: "resources", + where: { id: { in: [...resourceIds] } }, + limit: Math.max(1, resourceIds.size), + depth: 0, + overrideAccess: true, + }) + : null, + assetIds.size > 0 + ? payload.find({ + collection: "assets", + where: { id: { in: [...assetIds] } }, + limit: Math.max(1, assetIds.size), + depth: 0, + overrideAccess: true, + }) + : null, + technologyIds.size > 0 + ? payload.find({ + collection: "technologies", + where: { id: { in: [...technologyIds] } }, + limit: Math.max(1, technologyIds.size), + depth: 0, + overrideAccess: true, + }) + : null, + ]); + + const resourceNameById = new Map( + (resourcesRes?.docs ?? []).map((resource) => [resource.id, resource.name]), + ); + const assetNameById = new Map((assetsRes?.docs ?? []).map((asset) => [asset.id, asset.name])); + const technologyNameById = new Map( + (technologiesRes?.docs ?? []).map((technology) => [technology.id, technology.name]), + ); + + const resourceName = (ref: unknown): string => { + const value = relId(ref); + if (value == null) return "Unknown resource"; + return resourceNameById.get(value) ?? `Resource #${value}`; + }; + const assetName = (ref: unknown): string => { + const value = relId(ref); + if (value == null) return "Unknown asset"; + return assetNameById.get(value) ?? `Asset #${value}`; + }; + const technologyName = (ref: unknown): string => { + const value = relId(ref); + if (value == null) return "Unknown technology"; + return technologyNameById.get(value) ?? `Technology #${value}`; + }; + + const toJobView = (job: InteriorJob | null): InteriorJobView | null => { + if (!job) return null; + return { + id: job.id, + type: job.type, + status: job.status, + endsAt: job.endsAt ?? null, + targetLevel: job.targetLevel ?? null, + fixtureKey: job.fixtureKey ?? null, + stationRecipeKey: job.stationRecipeKey ?? null, + output: { + resources: (job.output?.resources ?? []).map((row) => ({ + name: resourceName(row.resource), + amount: row.amount, + })), + assets: (job.output?.assets ?? []).map((row) => ({ + name: assetName(row.asset), + amount: row.amount, + })), + }, + }; + }; + + const runtimeByKey = new Map(runtimeRooms.map((room) => [room.roomKey, room])); + + const rooms: InteriorRoomView[] = blueprintRooms.map((room) => { + const runtime = runtimeByKey.get(room.key); + const hotspot = { + x: room.hotspot?.x ?? 0, + y: room.hotspot?.y ?? 0, + width: room.hotspot?.width ?? 20, + height: room.hotspot?.height ?? 20, + }; + const seededFixtures = (room.fixtures ?? []).map((fixture) => ({ + key: fixture.key, + name: fixture.name, + broken: fixture.brokenByDefault ?? false, + condition: fixture.brokenByDefault ? (fixture.condition ?? 0) : (fixture.condition ?? 100), + blocksStation: fixture.blocksStation ?? false, + })); + + const station = + room.station && room.station.enabled + ? { + name: room.station.name ?? "Station", + enabled: true, + recipes: (room.station.recipes ?? []) + .filter((recipe) => recipe.enabled !== false) + .map((recipe) => ({ + key: recipe.key, + name: recipe.name, + enabled: true, + inputs: (recipe.inputs ?? []).map((input) => ({ + resourceId: relId(input.resource) ?? -1, + name: resourceName(input.resource), + amount: input.amount, + })), + outputs: (recipe.outputs ?? []).map((output) => ({ + kind: output.kind, + id: relId(output.item) ?? -1, + name: + output.kind === "asset" ? assetName(output.item) : resourceName(output.item), + amount: output.amount, + })), + durationMinutes: recipe.durationMinutes ?? 0, + requiredRoomLevel: recipe.requiredRoomLevel ?? 1, + })), + } + : null; + + return { + key: room.key, + name: room.name ?? room.key, + description: roomDescription(room), + roomType: room.roomType ?? null, + hotspot, + graphPosition: { + x: room.hotspot?.graphX ?? hotspot.x + hotspot.width / 2, + y: room.hotspot?.graphY ?? hotspot.y + hotspot.height / 2, + }, + maxLevel: room.maxLevel, + levels: [...(room.levels ?? [])] + .sort((a, b) => a.level - b.level) + .map((level) => ({ + level: level.level, + label: level.label ?? null, + upgradeMaterials: (level.upgradeMaterials ?? []).map((material) => ({ + resourceId: relId(material.resource) ?? -1, + name: resourceName(material.resource), + amount: material.amount, + })), + upgradeDurationMinutes: level.upgradeDurationMinutes ?? 0, + requiredTechNames: (level.requiredTech ?? []).map((tech) => technologyName(tech)), + requiredLaborClass: level.requiredLaborClass ?? null, + requiredHeadcount: level.requiredHeadcount ?? null, + })), + station, + fixtures: (room.fixtures ?? []).map((fixture) => ({ + key: fixture.key, + name: fixture.name, + repairMaterials: (fixture.repairMaterials ?? []).map((material) => ({ + resourceId: relId(material.resource) ?? -1, + name: resourceName(material.resource), + amount: material.amount, + })), + repairDurationMinutes: fixture.repairDurationMinutes ?? 0, + })), + decay: { + effectFloor: room.decay?.effectFloor ?? 0, + junkMax: room.decay?.junkMax ?? 0, + }, + runtime: { + level: runtime?.level ?? room.initialLevel ?? 0, + condition: runtime?.condition ?? 100, + junkLevel: runtime?.junkLevel ?? room.decay?.initialJunkLevel ?? 0, + fixtures: (runtime?.fixtures ?? seededFixtures).map((fixture) => ({ + key: fixture.key, + name: fixture.name, + broken: fixture.broken ?? false, + condition: fixture.condition ?? 0, + blocksStation: fixture.blocksStation ?? false, + })), + job: toJobView( + (() => { + const jobId = relId(runtime?.pendingJob); + return jobId != null ? (jobById.get(jobId) ?? null) : null; + })(), + ), + }, + }; + }); + + const floorplanRelation = snapshot?.floorplan ?? null; + const floorplanUrl = + typeof floorplanRelation === "object" && floorplanRelation !== null + ? (floorplanRelation.url ?? null) + : null; + const blueprintType = + typeof structure.type === "object" && structure.type !== null ? structure.type : null; + const interiorName = blueprintType?.interiorName ?? null; + + return ( +
+ + + Back to {structure.name} + + +
+ ); +} diff --git a/src/app/(frontend)/logistics/structures/[id]/page.tsx b/src/app/(frontend)/logistics/structures/[id]/page.tsx index 5e5bd55f..680aef40 100644 --- a/src/app/(frontend)/logistics/structures/[id]/page.tsx +++ b/src/app/(frontend)/logistics/structures/[id]/page.tsx @@ -32,6 +32,7 @@ import { BoxIcon, Building2Icon, CoinsIcon, + DoorOpenIcon, MapPinIcon, WrenchIcon, } from "lucide-react"; @@ -44,6 +45,7 @@ import { ItemTitle, } from "@/components/ui/item"; import { ManageStorageButton } from "@/components/frontend/storage/ManageStorageButton"; +import { Button } from "@/components/ui/button"; interface StructureDetailPageProps { params: Promise<{ id: string }>; @@ -74,6 +76,8 @@ export default async function StructureDetailPage({ params }: StructureDetailPag }; const structureType = structure.type; + const interiorRoomCount = Array.isArray(structureType.rooms) ? structureType.rooms.length : 0; + const showInteriorLink = Boolean(structureType.interiorEnabled) && interiorRoomCount > 0; const storedResources = structure.storedResources ?? []; const compoundHub = typeof structure.parentStructure === "object" && structure.parentStructure !== null @@ -380,6 +384,14 @@ export default async function StructureDetailPage({ params }: StructureDetailPag {structure.faction.name} )} + {user && showInteriorLink && ( + + )} {user && ( +
+ + Room // {room.key} + + +
+
+

{room.name}

+

+ {state === "sealed" ? "Sealed" : `Level ${room.runtime.level} / ${room.maxLevel}`} +

+
+ + + + ); +} + +const nodeTypes = { roomNode: RoomNode }; + +/** Producer -> consumer edges where an enabled resource output feeds an enabled input. */ +function buildEdges(rooms: InteriorRoomView[]): Edge[] { + const edges: Edge[] = []; + const seen = new Set(); + const stations = rooms.filter((room) => room.station?.enabled); + + for (const consumer of stations) { + for (const recipe of consumer.station!.recipes) { + if (!recipe.enabled) continue; + for (const input of recipe.inputs) { + for (const producer of stations) { + if (producer.key === consumer.key) continue; + const feeds = producer.station!.recipes.some( + (producerRecipe) => + producerRecipe.enabled && + producerRecipe.outputs.some( + (output) => output.kind === "resource" && output.id === input.resourceId, + ), + ); + if (!feeds) continue; + const id = `feed-${producer.key}-${consumer.key}`; + if (seen.has(id)) continue; + seen.add(id); + edges.push({ + id, + source: producer.key, + target: consumer.key, + type: "smoothstep", + style: { stroke: "rgba(34,211,238,0.55)", strokeWidth: 1.5 }, + markerEnd: { type: MarkerType.ArrowClosed, color: "rgba(34,211,238,0.75)" }, + }); + } + } + } + } + + return edges; +} + +function buildNodes(rooms: InteriorRoomView[]): Node[] { + return rooms.map((room) => ({ + id: room.key, + type: "roomNode", + position: { + x: room.graphPosition.x * SCALE_X - NODE_WIDTH / 2, + y: room.graphPosition.y * SCALE_Y - NODE_HEIGHT / 2, + }, + style: { width: NODE_WIDTH, height: NODE_HEIGHT }, + draggable: false, + selectable: false, + deletable: false, + data: { room }, + })); +} + +interface InteriorGraphTabProps { + rooms: InteriorRoomView[]; + onSelect: (roomKey: string) => void; +} + +function GraphInner({ rooms, onSelect }: InteriorGraphTabProps) { + const nodes = useMemo(() => buildNodes(rooms), [rooms]); + const edges = useMemo(() => buildEdges(rooms), [rooms]); + + return ( +
+ onSelect(node.id)} + > + + + +
+ ); +} + +export function InteriorGraphTab({ rooms, onSelect }: InteriorGraphTabProps) { + return ( +
+ + + +
+ ); +} diff --git a/src/components/frontend/interiors/InteriorShell.tsx b/src/components/frontend/interiors/InteriorShell.tsx new file mode 100644 index 00000000..895e1606 --- /dev/null +++ b/src/components/frontend/interiors/InteriorShell.tsx @@ -0,0 +1,250 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { toast } from "sonner"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Sheet, SheetContent } from "@/components/ui/sheet"; +import { cn } from "@/lib/utils"; +import { + cancelJobAction, + collectJobAction, + startInteriorAction, +} from "@/app/(frontend)/logistics/interiors/actions"; +import { InteriorGraphTab } from "./InteriorGraphTab"; +import { RoomSheet } from "./RoomSheet"; +import { + ROOM_STATE_LABEL, + ROOM_STATE_RING, + roomState, + type InteriorJobType, + type InteriorRoomState, + type InteriorRoomView, +} from "./types"; + +interface InteriorShellProps { + structureId: number; + structureName: string; + interiorName: string | null; + floorplanUrl: string | null; + floorplanAlt: string | null; + rooms: InteriorRoomView[]; +} + +const LEGEND: InteriorRoomState[] = ["ready", "working", "sealed", "damaged", "dirty"]; + +function Corners() { + return ( +
+ + + + +
+ ); +} + +function ReadoutCell({ value, label }: { value: number | string; label: string }) { + return ( +
+ {value} + {label} +
+ ); +} + +export function InteriorShell({ + structureId, + structureName, + interiorName, + floorplanUrl, + floorplanAlt, + rooms, +}: InteriorShellProps) { + const router = useRouter(); + const [selectedKey, setSelectedKey] = useState(null); + const selectedRoom = rooms.find((room) => room.key === selectedKey) ?? null; + + const ready = rooms.filter((room) => roomState(room) === "ready").length; + const working = rooms.filter((room) => roomState(room) === "working").length; + const sealed = rooms.filter((room) => roomState(room) === "sealed").length; + const reference = `REF ${String(structureId).padStart(3, "0")}`; + + async function handleStart(type: InteriorJobType, target?: string | number): Promise { + if (!selectedRoom) return false; + const result = await startInteriorAction(structureId, selectedRoom.key, type, target); + if (!result.success) { + toast.error(result.error ?? "Could not start that job."); + return false; + } + toast.success("Job started."); + router.refresh(); + return true; + } + + async function handleCancel(jobId: number): Promise { + const result = await cancelJobAction(jobId, structureId); + if (!result.success) { + toast.error(result.error ?? "Could not cancel that job."); + return false; + } + toast.success("Job cancelled."); + router.refresh(); + return true; + } + + async function handleCollect(jobId: number): Promise { + const result = await collectJobAction(jobId, structureId); + if (!result.success) { + toast.error(result.error ?? "Could not collect that job."); + return false; + } + toast.success("Output collected into structure storage."); + router.refresh(); + return true; + } + + return ( +
+
+
+ + Interior // {structureName} + + + {reference} + +
+ +
+
+ +
+

+ {interiorName ?? structureName} +

+

+ {structureName} · {rooms.length} room{rooms.length === 1 ? "" : "s"} · Pick a room to + manage it. +

+
+
+ +
+ + + + +
+
+ + + + Floorplan + Graph + + + +
+ {floorplanUrl ? ( + {floorplanAlt + ) : ( +
+ )} + + {rooms.length === 0 && ( +

+ No rooms authored for this interior. +

+ )} + + {rooms.map((room) => { + const state = roomState(room); + return ( + + ); + })} +
+ +
+ {LEGEND.map((state) => ( + + + {ROOM_STATE_LABEL[state]} + + ))} +
+ + + + + + + + {selectedRoom && ( + { + if (!open) setSelectedKey(null); + }} + > + + router.refresh()} + /> + + + )} +
+ ); +} diff --git a/src/components/frontend/interiors/JobCountdown.tsx b/src/components/frontend/interiors/JobCountdown.tsx new file mode 100644 index 00000000..897155ab --- /dev/null +++ b/src/components/frontend/interiors/JobCountdown.tsx @@ -0,0 +1,53 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; + +interface JobCountdownProps { + endsAt: string | Date | null; + /** Called once, shortly after the deadline, so the server can refresh the job state. */ + onFinished?: () => void; +} + +function formatDuration(ms: number): string { + const totalSeconds = Math.max(0, Math.round(ms / 1000)); + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`; + return `${minutes}m ${seconds}s`; +} + +/** + * Live countdown to an interior job's endsAt, following the ConstructionEta + * pattern (client tick every second). When the deadline passes it fires + * `onFinished` once so the page can refresh into the await-collect state; the + * one-shot ref keeps a stale endsAt from triggering a refresh loop. + */ +export function JobCountdown({ endsAt, onFinished }: JobCountdownProps) { + const [nowMs, setNowMs] = useState(() => Date.now()); + const firedRef = useRef(false); + const onFinishedRef = useRef(onFinished); + onFinishedRef.current = onFinished; + + useEffect(() => { + const timer = setInterval(() => setNowMs(Date.now()), 1000); + return () => clearInterval(timer); + }, []); + + useEffect(() => { + const deadline = endsAt ? new Date(endsAt).getTime() : NaN; + if (!Number.isFinite(deadline)) return; + const delay = Math.max(0, deadline - Date.now()) + 1500; + const timer = setTimeout(() => { + if (firedRef.current) return; + firedRef.current = true; + onFinishedRef.current?.(); + }, delay); + return () => clearTimeout(timer); + }, [endsAt]); + + const deadline = endsAt ? new Date(endsAt).getTime() : NaN; + const remaining = Number.isFinite(deadline) ? deadline - nowMs : 0; + + return ETA {remaining <= 0 ? "any moment" : formatDuration(remaining)}; +} diff --git a/src/components/frontend/interiors/RoomSheet.tsx b/src/components/frontend/interiors/RoomSheet.tsx new file mode 100644 index 00000000..8909b255 --- /dev/null +++ b/src/components/frontend/interiors/RoomSheet.tsx @@ -0,0 +1,368 @@ +"use client"; + +import { useState } from "react"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Progress } from "@/components/ui/progress"; +import { SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { JobCountdown } from "./JobCountdown"; +import { + JOB_STATUS_LABEL, + JOB_TYPE_LABEL, + ROOM_STATE_LABEL, + materialSummary, + roomState, + type InteriorJobType, + type InteriorRoomView, +} from "./types"; + +interface RoomSheetProps { + room: InteriorRoomView; + onStart: (type: InteriorJobType, target?: string | number) => Promise; + onCancel: (jobId: number) => Promise; + onCollect: (jobId: number) => Promise; + onRefresh: () => void; +} + +function humanizeClass(value: string): string { + return value.replace(/_/g, " "); +} + +/** + * Room detail sheet. Every control here is a plain shadcn control; the tactical + * dossier treatment is reserved for the page shell (see the frontend AGENTS + * recipe). Errors and confirmations surface as sonner toasts from the shell. + */ +export function RoomSheet({ room, onStart, onCancel, onCollect, onRefresh }: RoomSheetProps) { + const [busy, setBusy] = useState(null); + const job = room.runtime.job; + const state = roomState(room); + const sealed = room.runtime.level <= 0; + + async function run(key: string, action: () => Promise) { + setBusy(key); + try { + await action(); + } finally { + setBusy(null); + } + } + + const blueprintFixture = (key: string) => room.fixtures.find((fixture) => fixture.key === key); + const openLevel = room.levels[0] ?? null; + const nextLevel = room.levels.find((level) => level.level === room.runtime.level + 1) ?? null; + const atMaxLevel = room.runtime.level >= room.maxLevel; + const collectable = + job != null && (job.status === "awaiting_collect" || job.status === "cancelled"); + + return ( +
+ + + {room.name} + {sealed && Sealed} + + + {room.roomType ? `${room.roomType} · ` : ""} + {ROOM_STATE_LABEL[state]} + + + + + + Status + Jobs + {room.station && Station} + + + + {room.description &&

{room.description}

} + +
+ + Level {room.runtime.level} / {room.maxLevel} + + 0 ? "secondary" : "outline"}> + Junk {room.runtime.junkLevel} + + {room.decay.junkMax > 0 && ( + Junk cap {room.decay.junkMax} + )} +
+ +
+
+ Condition + {room.runtime.condition}% +
+ + {room.decay.effectFloor > 0 && ( +

+ Station work stops below {room.decay.effectFloor}% condition. +

+ )} +
+ +
+ Fixtures + {room.runtime.fixtures.length === 0 ? ( +

No fixtures installed.

+ ) : ( + room.runtime.fixtures.map((fixture) => { + const blueprint = blueprintFixture(fixture.key); + const repairKey = `repair-${fixture.key}`; + return ( +
+
+ {fixture.name} + + {fixture.condition}% condition + {fixture.blocksStation ? " · blocks station" : ""} + +
+ {fixture.broken ? ( +
+ Broken + + + {materialSummary(blueprint?.repairMaterials ?? [])} + {blueprint && blueprint.repairDurationMinutes > 0 + ? ` · ${blueprint.repairDurationMinutes} min` + : ""} + +
+ ) : ( + Operational + )} +
+ ); + }) + )} +
+ + {sealed ? ( +
+ Open room +

+ {materialSummary(openLevel?.upgradeMaterials ?? [])} + {openLevel && openLevel.upgradeDurationMinutes > 0 + ? ` · ${openLevel.upgradeDurationMinutes} min` + : ""} +

+ {openLevel && openLevel.requiredTechNames.length > 0 && ( +

+ Requires research: {openLevel.requiredTechNames.join(", ")} +

+ )} + +
+ ) : atMaxLevel || !nextLevel ? ( +
+ Maximum level reached +

This room cannot be upgraded further.

+
+ ) : ( +
+ + Upgrade to level {nextLevel.level} + {nextLevel.label ? ` · ${nextLevel.label}` : ""} + +

+ Materials: {materialSummary(nextLevel.upgradeMaterials)} +

+

+ Duration: {nextLevel.upgradeDurationMinutes} min +

+ {nextLevel.requiredTechNames.length > 0 && ( +

+ Requires research: {nextLevel.requiredTechNames.join(", ")} +

+ )} + {nextLevel.requiredLaborClass && (nextLevel.requiredHeadcount ?? 0) > 0 && ( +

+ Requires {nextLevel.requiredHeadcount}{" "} + {humanizeClass(nextLevel.requiredLaborClass)} active +

+ )} + +
+ )} +
+ + + {job ? ( +
+
+
+ {JOB_TYPE_LABEL[job.type]} + + {JOB_STATUS_LABEL[job.status]} + +
+ + {JOB_STATUS_LABEL[job.status]} + +
+ + {job.status === "active" && ( +

+ +

+ )} + + {collectable && ( +
+ + Output + + {job.output.resources.length === 0 && job.output.assets.length === 0 ? ( + No output recorded. + ) : ( + <> + {job.output.resources.map((row) => ( + + {row.amount} × {row.name} + + ))} + {job.output.assets.map((row) => ( + + {row.amount} × {row.name}{" "} + + (asset, requires asset outputs enabled) + + + ))} + + )} +
+ )} + +
+ {job.status === "active" && ( + + )} + {collectable && ( + + )} +
+
+ ) : ( +
+ Junk cleanup +

+ Current junk level: {room.runtime.junkLevel} +

+

+ A cleanup run clears one junk level and can recover salvage. +

+ {room.runtime.junkLevel > 0 ? ( + + ) : ( +

Nothing to clean up.

+ )} +
+ )} +
+ + {room.station && ( + + {room.station.recipes.length === 0 ? ( +

No enabled recipes at this station.

+ ) : ( + room.station.recipes.map((recipe) => { + const recipeKey = `recipe-${recipe.key}`; + return ( +
+
+ {recipe.name} + {recipe.durationMinutes} min +
+

+ Inputs: {materialSummary(recipe.inputs)} +

+
+ Outputs: + {recipe.outputs.length === 0 ? ( + None + ) : ( + recipe.outputs.map((output) => ( + + {output.amount} × {output.name} + {output.kind === "asset" + ? " (asset, requires asset outputs enabled)" + : ""} + + )) + )} +
+

+ Requires room level {recipe.requiredRoomLevel} +

+ +
+ ); + }) + )} +
+ )} +
+
+ ); +} diff --git a/src/components/frontend/interiors/types.ts b/src/components/frontend/interiors/types.ts new file mode 100644 index 00000000..3027549b --- /dev/null +++ b/src/components/frontend/interiors/types.ts @@ -0,0 +1,178 @@ +/** + * Plain, serializable view models for the Superstructure interior UI. + * + * The server page resolves every Payload relationship (resource names, asset + * names, technology names, the merged blueprint/runtime state) into these + * shapes so client components never touch Payload. The helpers at the bottom + * are pure and shared by the floorplan, the room sheet and the graph. + */ + +export type InteriorJobType = "open" | "cleanup" | "upgrade" | "repair" | "produce"; + +export type InteriorJobStatus = + "active" | "awaiting_collect" | "cancelled" | "collected" | "failed"; + +export interface InteriorOutputView { + resources: { name: string; amount: number }[]; + assets: { name: string; amount: number }[]; +} + +export interface InteriorJobView { + id: number; + type: InteriorJobType; + status: InteriorJobStatus; + endsAt: string | null; + targetLevel: number | null; + fixtureKey: string | null; + stationRecipeKey: string | null; + output: InteriorOutputView; +} + +export interface InteriorMaterialView { + resourceId: number; + name: string; + amount: number; +} + +export interface InteriorRecipeOutputView { + kind: "resource" | "asset"; + id: number; + name: string; + amount: number; +} + +export interface InteriorRecipeView { + key: string; + name: string; + enabled: boolean; + inputs: InteriorMaterialView[]; + outputs: InteriorRecipeOutputView[]; + durationMinutes: number; + requiredRoomLevel: number; +} + +export interface InteriorStationView { + name: string; + enabled: boolean; + recipes: InteriorRecipeView[]; +} + +export interface InteriorLevelView { + level: number; + label: string | null; + upgradeMaterials: InteriorMaterialView[]; + upgradeDurationMinutes: number; + requiredTechNames: string[]; + requiredLaborClass: string | null; + requiredHeadcount: number | null; +} + +export interface InteriorFixtureBlueprintView { + key: string; + name: string; + repairMaterials: InteriorMaterialView[]; + repairDurationMinutes: number; +} + +export interface InteriorFixtureRuntimeView { + key: string; + name: string; + broken: boolean; + condition: number; + blocksStation: boolean; +} + +export interface InteriorRoomRuntimeView { + level: number; + condition: number; + junkLevel: number; + fixtures: InteriorFixtureRuntimeView[]; + job: InteriorJobView | null; +} + +export interface InteriorRoomView { + key: string; + name: string; + description: string | null; + roomType: string | null; + hotspot: { x: number; y: number; width: number; height: number }; + graphPosition: { x: number; y: number }; + maxLevel: number; + levels: InteriorLevelView[]; + station: InteriorStationView | null; + fixtures: InteriorFixtureBlueprintView[]; + decay: { effectFloor: number; junkMax: number }; + runtime: InteriorRoomRuntimeView; +} + +export type InteriorRoomState = "ready" | "working" | "sealed" | "damaged" | "dirty" | "normal"; + +/** + * Priority is deliberately strict: ready > working > sealed > damaged > dirty. + * A sealed room that also has junk reads as sealed, and so on. + */ +export function roomState(room: InteriorRoomView): InteriorRoomState { + const job = room.runtime.job; + if (job && (job.status === "awaiting_collect" || job.status === "cancelled")) return "ready"; + if (job && job.status === "active") return "working"; + if ((room.runtime.level ?? 0) <= 0) return "sealed"; + + const effectFloor = room.decay.effectFloor; + const condition = room.runtime.condition ?? 0; + const belowFloor = effectFloor > 0 ? condition <= effectFloor : condition <= 0; + const brokenFixture = room.runtime.fixtures.some((fixture) => fixture.broken); + if (belowFloor || brokenFixture) return "damaged"; + + if ((room.runtime.junkLevel ?? 0) > 0) return "dirty"; + return "normal"; +} + +export const ROOM_STATE_LABEL: Record = { + ready: "Ready to collect", + working: "Working", + sealed: "Sealed", + damaged: "Damaged", + dirty: "Dirty", + normal: "Operational", +}; + +/** Ring treatment shared by the floorplan hotspots and the legend swatches. */ +export const ROOM_STATE_RING: Record = { + ready: "ring-2 ring-emerald-500", + working: "ring-2 ring-sky-500 animate-pulse", + sealed: "opacity-60 ring-2 ring-muted-foreground", + damaged: "ring-2 ring-destructive", + dirty: "ring-2 ring-amber-500/70", + normal: "", +}; + +/** Node dot treatment for the read-only graph. */ +export const ROOM_STATE_DOT: Record = { + ready: "bg-emerald-500", + working: "bg-sky-500", + sealed: "bg-muted-foreground", + damaged: "bg-destructive", + dirty: "bg-amber-500", + normal: "bg-muted-foreground/40", +}; + +export const JOB_TYPE_LABEL: Record = { + open: "Open room", + cleanup: "Cleanup", + upgrade: "Upgrade", + repair: "Repair", + produce: "Production", +}; + +export const JOB_STATUS_LABEL: Record = { + active: "In progress", + awaiting_collect: "Ready to collect", + cancelled: "Cancelled, refund pending", + collected: "Collected", + failed: "Failed", +}; + +export function materialSummary(materials: InteriorMaterialView[]): string { + if (materials.length === 0) return "No materials required"; + return materials.map((material) => `${material.amount} ${material.name}`).join(", "); +} diff --git a/src/tools/seed/seedEverything.ts b/src/tools/seed/seedEverything.ts index 95ddd5cd..4381d03e 100644 --- a/src/tools/seed/seedEverything.ts +++ b/src/tools/seed/seedEverything.ts @@ -4,6 +4,7 @@ import { seedFactions } from "@/tools/seed/seedFactions"; import { seedExperience } from "@/tools/seed/seedExperience"; import { seedMinigames } from "@/tools/seed/seedMinigames"; import { seedScrap } from "@/tools/seed/seedScrap"; +import { seedInteriorContent } from "@/tools/seed/seedInteriorContent"; // Users await seedUsers(); @@ -18,3 +19,6 @@ await seedMinigames(); // Logistics resources await seedScrap(); + +// Superstructure interior launch content (requires seedScrap first) +await seedInteriorContent(); diff --git a/src/tools/seed/seedInteriorContent.ts b/src/tools/seed/seedInteriorContent.ts new file mode 100644 index 00000000..300e6a8d --- /dev/null +++ b/src/tools/seed/seedInteriorContent.ts @@ -0,0 +1,517 @@ +import { Pool } from "pg"; +import { getPayload } from "payload"; +import config from "@payload-config"; +import "dotenv/config"; + +/** + * Idempotent seed for the Superstructure interior launch content. + * + * Authors the blueprint interior (three rooms per the plan's Launch Content + * section), plus the resources, labor class, technology, and asset the rooms + * reference: + * + * 1. Barracks: open at level 1; the L2 upgrade gates on Scrap materials, a + * labor class requirement, and an (unresearched) technology. Proves the + * upgrade path, tech gating, and labor gates. + * 2. Workshop: Fabricator station with two enabled resource recipes and one + * disabled asset-output recipe kept as the authoring template (asset credit + * stays behind the Game Rules `interior.assetOutputsEnabled` flag). + * 3. Rubble Annex: sealed at level 0 with an open-room job, starting junk + * level 3 with a loot table, and a broken doorway fixture that blocks its + * station until repaired. Proves open, cleanup, and repair. + * + * No floorplan image is uploaded: the UI falls back to the generated hotspot + * schematic, so the feature works before art lands. + * + * Idempotent: existing rows are matched by codeName / key / name and updated + * in place, so re-running after tuning edits converges instead of duplicating. + */ + +const SCRAP_CODE_NAME = "res_scrap"; +const ENERGY_CODE_NAME = "res_interior_energy"; +const ALLOY_CODE_NAME = "res_interior_alloy"; +const BLUEPRINT_CODE_NAME = "structure_superstructure_interior"; + +// Polymorphic relationship fields (recipe outputs, junk loot items) require the +// canonical `{ relationTo, value }` shape; plain ids fail validation on write. +const resRef = (id: number) => ({ relationTo: "resources" as const, value: id }); +const assetRef = (id: number) => ({ relationTo: "assets" as const, value: id }); + +const alignResourcesSequence = async (pool: Pool) => { + const { rows } = await pool.query("SELECT MAX(id) AS max_id FROM resources"); + const maxId = rows[0]?.max_id; + if (maxId != null) { + await pool.query("SELECT setval('resources_id_seq', $1, true)", [maxId]); + } +}; + +const ensureResource = async ( + payload: Awaited>, + pool: Pool, + args: { name: string; codeName: string; massPerUnit: number; stackSize: number }, +): Promise => { + const existing = await payload.find({ + collection: "resources", + where: { codeName: { equals: args.codeName } }, + limit: 1, + overrideAccess: true, + }); + const found = existing.docs[0]?.id as number | undefined; + if (found) return found; + + await alignResourcesSequence(pool); + const created = await payload.create({ + collection: "resources", + data: { + name: args.name, + codeName: args.codeName, + approvalStatus: "approved", + type: "physical", + unitOfMeasure: "kg", + massPerUnit: args.massPerUnit, + stackSize: args.stackSize, + stackable: true, + gridWidth: 1, + gridHeight: 1, + rotatable: false, + baseValue: 0, + rarity: "common", + tradeable: true, + }, + draft: false, + overrideAccess: true, + }); + await alignResourcesSequence(pool); + payload.logger.info(`[seed-interior] created resource ${args.name}: ${created.id}`); + return created.id as number; +}; + +export const seedInteriorContent = async (): Promise => { + const payload = await getPayload({ config }); + const dbUri = process.env.DATABASE_URI; + if (!dbUri) throw new Error("[seed-interior] DATABASE_URI is not set"); + const pool = new Pool({ connectionString: dbUri }); + + try { + // --- Supporting docs --------------------------------------------------- + + const scrapId = await ensureResource(payload, pool, { + name: "Scrap", + codeName: SCRAP_CODE_NAME, + massPerUnit: 0.5, + stackSize: 1000, + }); + const energyId = await ensureResource(payload, pool, { + name: "Energy Cells", + codeName: ENERGY_CODE_NAME, + massPerUnit: 0.2, + stackSize: 500, + }); + const alloyId = await ensureResource(payload, pool, { + name: "Reclaimed Alloy", + codeName: ALLOY_CODE_NAME, + massPerUnit: 1.5, + stackSize: 200, + }); + + // Labor class the barracks/workshop upgrade gates reference. Key must + // match the requiredLaborClass strings below. + let engineerClass = await payload.find({ + collection: "labor-classifications", + where: { key: { equals: "engineer" } }, + limit: 1, + overrideAccess: true, + }); + if (!engineerClass.docs[0]) { + engineerClass = { + docs: [ + await payload.create({ + collection: "labor-classifications", + data: { + name: "Interior Engineer", + key: "engineer", + defaultUnitSalary: 20, + availableHeadcount: 8, + description: "Trades crew for Superstructure interior work (upgrades, repairs, stations).", + }, + overrideAccess: true, + }), + ], + }; + payload.logger.info("[seed-interior] created labor class engineer"); + } + + // Technology gate for the barracks L2 upgrade. Left unresearched on + // purpose so the gate is live; research it from the tech tree to open L2. + const techName = "Modular Habitation"; + let tech = await payload.find({ + collection: "technologies", + where: { name: { equals: techName } }, + limit: 1, + overrideAccess: true, + }); + if (!tech.docs[0]) { + tech = { + docs: [ + await payload.create({ + collection: "technologies", + data: { + name: techName, + approvalStatus: "approved", + type: "upgrade", + summary: + "Prefab habitation modules; unlocks expanded berths in the Superstructure barracks.", + researchCosts: { minimumResearchDuration: 240 }, + }, + overrideAccess: true, + }), + ], + }; + payload.logger.info("[seed-interior] created technology 'Modular Habitation' (unresearched)"); + } + const techId = tech.docs[0]!.id as number; + + // Asset produced by the disabled template recipe. + const assetName = "Field Repair Kit"; + let kit = await payload.find({ + collection: "assets", + where: { name: { equals: assetName } }, + limit: 1, + overrideAccess: true, + }); + if (!kit.docs[0]) { + kit = { + docs: [ + await payload.create({ + collection: "assets", + data: { + name: assetName, + approvalStatus: "approved", + className: "ptf_repair_kit", + assetType: "tool", + description: "A packed kit of shims, sealant, and hand tools for interior fixture repairs.", + crafting: { craftable: false }, + gridWidth: 1, + gridHeight: 1, + }, + overrideAccess: true, + }), + ], + }; + payload.logger.info(`[seed-interior] created asset ${assetName}`); + } + const kitId = kit.docs[0]!.id as number; + + // --- Blueprint ----------------------------------------------------------- + + const rooms = [ + { + key: "barracks", + name: "Barracks", + roomType: "barracks", + description: { + root: { + type: "root", + children: [ + { + type: "paragraph", + children: [ + { + type: "text", + text: "Sleeping quarters for the garrison. Upgrades add berths and stores capacity.", + }, + ], + }, + ], + }, + }, + hotspot: { x: 8, y: 12, width: 26, height: 34 }, + initialLevel: 1, + maxLevel: 3, + levels: [ + { level: 1, label: "Bunked", upgradeDurationMinutes: 60 }, + { + level: 2, + label: "Expanded berths", + upgradeDurationMinutes: 720, + upgradeMaterials: [{ resource: scrapId, amount: 40 }], + requiredTech: [techId], + requiredLaborClass: "engineer", + requiredHeadcount: 1, + effects: [{ type: "storage_capacity" as const, value: 500 }], + }, + { + level: 3, + label: "NCO wing", + upgradeDurationMinutes: 1440, + upgradeMaterials: [ + { resource: scrapId, amount: 60 }, + { resource: energyId, amount: 10 }, + ], + requiredLaborClass: "engineer", + requiredHeadcount: 1, + effects: [{ type: "labor_capacity" as const, value: 2 }], + }, + ], + decay: { conditionPerDay: 0.5, effectFloor: 20, junkMax: 3, initialJunkLevel: 1 }, + junkLoot: [{ kind: "resource" as const, item: resRef(scrapId), amountMin: 3, amountMax: 12, weight: 1 }], + }, + { + key: "workshop", + name: "Workshop", + roomType: "workshop", + description: { + root: { + type: "root", + children: [ + { + type: "paragraph", + children: [ + { + type: "text", + text: "The Fabricator presses Scrap and Energy Cells into reclaimed alloy.", + }, + ], + }, + ], + }, + }, + hotspot: { x: 42, y: 16, width: 22, height: 30 }, + initialLevel: 1, + maxLevel: 2, + levels: [ + { level: 1, label: "Fitted out", upgradeDurationMinutes: 60 }, + { + level: 2, + label: "Tuned line", + upgradeDurationMinutes: 1440, + upgradeMaterials: [ + { resource: scrapId, amount: 80 }, + { resource: energyId, amount: 20 }, + ], + requiredLaborClass: "engineer", + requiredHeadcount: 1, + effects: [{ type: "output_bonus" as const, value: 0.25 }], + }, + ], + station: { + name: "Fabricator", + enabled: true, + recipes: [ + { + key: "alloy_cast", + name: "Alloy Casting", + enabled: true, + durationMinutes: 30, + requiredRoomLevel: 1, + inputs: [ + { resource: scrapId, amount: 8 }, + { resource: energyId, amount: 2 }, + ], + outputs: [{ kind: "resource" as const, item: resRef(alloyId), amount: 1 }], + }, + { + key: "alloy_batch", + name: "Batch Smelting", + enabled: true, + durationMinutes: 240, + requiredRoomLevel: 2, + inputs: [ + { resource: scrapId, amount: 30 }, + { resource: energyId, amount: 8 }, + ], + outputs: [{ kind: "resource" as const, item: resRef(alloyId), amount: 4 }], + }, + { + // Asset-output template. Stays disabled at launch: asset credit + // is gated behind Game Rules > interior assetOutputsEnabled. + key: "repair_kit_assembly", + name: "Field Repair Kit Assembly", + enabled: false, + durationMinutes: 120, + requiredRoomLevel: 1, + inputs: [ + { resource: scrapId, amount: 15 }, + { resource: energyId, amount: 1 }, + ], + outputs: [{ kind: "asset" as const, item: assetRef(kitId), amount: 1 }], + }, + ], + }, + fixtures: [ + { + key: "lathe", + name: "Lathe", + repairMaterials: [{ resource: scrapId, amount: 10 }], + repairDurationMinutes: 60, + }, + ], + decay: { conditionPerDay: 0.5, effectFloor: 25, junkMax: 4, initialJunkLevel: 0 }, + junkLoot: [{ kind: "resource" as const, item: resRef(scrapId), amountMin: 2, amountMax: 8, weight: 1 }], + }, + { + key: "rubble_annex", + name: "Rubble Annex", + roomType: "annex", + description: { + root: { + type: "root", + children: [ + { + type: "paragraph", + children: [ + { + type: "text", + text: "A collapsed side hall. Clear the doorway, clean out the rubble, and the salvage bench pays for itself.", + }, + ], + }, + ], + }, + }, + hotspot: { x: 70, y: 54, width: 22, height: 32 }, + initialLevel: 0, + maxLevel: 2, + levels: [ + { + level: 1, + label: "Opened up", + upgradeDurationMinutes: 180, + upgradeMaterials: [{ resource: scrapId, amount: 10 }], + }, + { + level: 2, + label: "Reclaimed", + upgradeDurationMinutes: 720, + upgradeMaterials: [{ resource: scrapId, amount: 30 }], + }, + ], + station: { + name: "Salvage Bench", + enabled: true, + recipes: [ + { + key: "strip_salvage", + name: "Strip Salvage", + enabled: true, + durationMinutes: 30, + requiredRoomLevel: 1, + inputs: [{ resource: energyId, amount: 1 }], + outputs: [{ kind: "resource" as const, item: resRef(scrapId), amount: 12 }], + }, + ], + }, + fixtures: [ + { + key: "doorway", + name: "Collapsed Doorway", + condition: 0, + brokenByDefault: true, + blocksStation: true, + repairMaterials: [{ resource: scrapId, amount: 15 }], + repairDurationMinutes: 90, + }, + ], + decay: { conditionPerDay: 1, effectFloor: 25, junkMax: 5, initialJunkLevel: 3 }, + junkLoot: [ + { kind: "resource" as const, item: resRef(scrapId), amountMin: 5, amountMax: 20, weight: 6 }, + { kind: "resource" as const, item: resRef(energyId), amountMin: 1, amountMax: 3, weight: 2 }, + ], + }, + ]; + + let blueprint = await payload.find({ + collection: "structures", + where: { codeName: { equals: BLUEPRINT_CODE_NAME } }, + limit: 1, + overrideAccess: true, + }); + + let blueprintId: number; + if (blueprint.docs[0]) { + blueprintId = blueprint.docs[0].id as number; + } else { + const created = await payload.create({ + collection: "structures", + data: { + name: "Superstructure", + codeName: BLUEPRINT_CODE_NAME, + approvalStatus: "approved", + category: "civilian", + description: { + root: { + type: "root", + children: [ + { + type: "paragraph", + children: [ + { + type: "text", + text: "The unit's main base structure. Its interior is the Superstructure Interior System.", + }, + ], + }, + ], + }, + }, + materials: [{ resource: scrapId, amount: 100 }], + constructionDurationMinutes: 1, + terrainType: "land", + maxHealth: 100, + }, + draft: false, + overrideAccess: true, + }); + blueprintId = created.id as number; + payload.logger.info(`[seed-interior] created Superstructure blueprint: ${blueprintId}`); + } + + await payload.update({ + collection: "structures", + id: blueprintId, + overrideAccess: true, + data: { + interiorEnabled: true, + interiorName: "The Superstructure", + interiorAccess: { mode: "anyone" }, + rooms, + } as Record, + }); + + // --- Instance ------------------------------------------------------------ + + const instances = await payload.find({ + collection: "game-structures", + where: { type: { equals: blueprintId } }, + limit: 5, + overrideAccess: true, + }); + if (!instances.docs[0]) { + await payload.create({ + collection: "game-structures", + data: { + name: "Superstructure", + type: blueprintId, + constructionStatus: "complete", + }, + draft: false, + overrideAccess: true, + }); + payload.logger.info("[seed-interior] created Superstructure game instance"); + } + + payload.logger.info( + `[seed-interior] done; blueprint ${blueprintId} (interior enabled, ${rooms.length} rooms)`, + ); + return blueprintId; + } finally { + await pool.end(); + } +}; + +// Standalone entry point (`bun src/tools/seed/seedInteriorContent.ts`). +// Skipped when imported by seedEverything, which awaits the export itself. +if ((import.meta as { main?: boolean }).main) { + await seedInteriorContent(); + process.exit(0); +} diff --git a/src/tools/seed/seedScrap.ts b/src/tools/seed/seedScrap.ts index 5c0542d9..65fcc224 100644 --- a/src/tools/seed/seedScrap.ts +++ b/src/tools/seed/seedScrap.ts @@ -86,5 +86,9 @@ export const seedScrap = async (): Promise => { return created.id as number; }; -await seedScrap(); -process.exit(0); +// Standalone entry point (`bun src/tools/seed/seedScrap.ts`). Skipped when +// imported by seedEverything, which awaits the export itself. +if ((import.meta as { main?: boolean }).main) { + await seedScrap(); + process.exit(0); +}