feat(interior): interiors screens, sidebar entry, and launch content seed
This commit is contained in:
parent
f2de7941ca
commit
e52cc83198
14 changed files with 2308 additions and 4 deletions
187
src/app/(frontend)/logistics/interiors/actions.ts
Normal file
187
src/app/(frontend)/logistics/interiors/actions.ts
Normal file
|
|
@ -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<T = undefined> {
|
||||
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<JobStartError | "not_active", string> = {
|
||||
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<string, string> = {
|
||||
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, string>): 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<ReturnType<typeof getPayload>>,
|
||||
jobId: number,
|
||||
): Promise<number | null> {
|
||||
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<ReturnType<typeof getPayload>>,
|
||||
user: Awaited<ReturnType<typeof authenticate>>["user"],
|
||||
structureId: number | string,
|
||||
): Promise<boolean> {
|
||||
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<string, unknown>);
|
||||
}
|
||||
|
||||
export async function startInteriorAction(
|
||||
structureId: number,
|
||||
roomKey: string,
|
||||
type: InteriorJobType,
|
||||
target?: string | number,
|
||||
): Promise<ActionResult<number>> {
|
||||
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<ActionResult> {
|
||||
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<ActionResult> {
|
||||
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 };
|
||||
}
|
||||
}
|
||||
160
src/app/(frontend)/logistics/interiors/page.tsx
Normal file
160
src/app/(frontend)/logistics/interiors/page.tsx
Normal file
|
|
@ -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<string, unknown>))) {
|
||||
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<number>();
|
||||
for (const job of readyRes?.docs ?? []) {
|
||||
const id = relId(job.structure);
|
||||
if (id != null) readyIds.add(id);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 p-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<DoorOpenIcon className="size-5 text-muted-foreground" />
|
||||
<h1 className="text-lg font-semibold">Interiors</h1>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Structures with an interior you can enter. Clean junk, open sealed rooms, upgrade
|
||||
facilities, and run equipment stations.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{accessible.length === 0 ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>No interiors available</CardTitle>
|
||||
<CardDescription>
|
||||
No structure interior is currently open to your account. Check back after the next
|
||||
build or ask a logistics officer for access.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
{accessible.map((structure) => {
|
||||
const rooms = roomCount(structure);
|
||||
const typeName =
|
||||
typeof structure.type === "object" && structure.type !== null
|
||||
? structure.type.name
|
||||
: null;
|
||||
return (
|
||||
<Card key={structure.id} className="flex flex-col">
|
||||
<CardHeader className="flex flex-row items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Building2Icon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<CardTitle className="truncate text-base">{structure.name}</CardTitle>
|
||||
</div>
|
||||
<CardDescription>{typeName ?? "Structure"}</CardDescription>
|
||||
</div>
|
||||
{readyIds.has(structure.id) && (
|
||||
<Badge variant="default" className="shrink-0">
|
||||
Ready to collect
|
||||
</Badge>
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="flex-1">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{rooms} room{rooms === 1 ? "" : "s"}
|
||||
</span>
|
||||
</CardContent>
|
||||
<CardFooter>
|
||||
<Button asChild size="sm">
|
||||
<Link href={`/logistics/structures/${structure.id}/interior`}>
|
||||
Enter interior
|
||||
</Link>
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
404
src/app/(frontend)/logistics/structures/[id]/interior/page.tsx
Normal file
404
src/app/(frontend)/logistics/structures/[id]/interior/page.tsx
Normal file
|
|
@ -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<ReturnType<typeof getPayload>>;
|
||||
|
||||
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 (
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link href={`/logistics/structures/${structureId}`}>
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
Back to structure
|
||||
</Link>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
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<string, unknown>;
|
||||
if (!(await canUserEnterInterior(payload, user, structureRow))) {
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-lg font-semibold">Interior</h1>
|
||||
<p className="text-sm text-muted-foreground">{structure.name}</p>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Access denied</CardTitle>
|
||||
<CardDescription>
|
||||
Your account is not cleared to enter this structure's interior.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BackToStructure structureId={structureId} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const snapshot = structure.interior;
|
||||
const blueprintRooms = Array.isArray(snapshot?.rooms)
|
||||
? (snapshot.rooms as unknown as InteriorBlueprintRoom[])
|
||||
: [];
|
||||
|
||||
if (blueprintRooms.length === 0) {
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<h1 className="text-lg font-semibold">Interior</h1>
|
||||
<p className="text-sm text-muted-foreground">{structure.name}</p>
|
||||
</div>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>No rooms provisioned</CardTitle>
|
||||
<CardDescription>
|
||||
This structure has no authored interior rooms yet. An administrator can add rooms on
|
||||
the structure blueprint.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BackToStructure structureId={structureId} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<number, InteriorJob>((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<number>();
|
||||
const assetIds = new Set<number>();
|
||||
const technologyIds = new Set<number>();
|
||||
const remember = (target: Set<number>, 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 (
|
||||
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-4 p-5">
|
||||
<Link
|
||||
href={`/logistics/structures/${structureId}`}
|
||||
className="flex w-fit items-center gap-1 text-sm text-muted-foreground transition-colors hover:text-primary"
|
||||
>
|
||||
<ArrowLeftIcon className="size-3" />
|
||||
Back to {structure.name}
|
||||
</Link>
|
||||
<InteriorShell
|
||||
structureId={structureId}
|
||||
structureName={structure.name}
|
||||
interiorName={interiorName}
|
||||
floorplanUrl={floorplanUrl}
|
||||
floorplanAlt={snapshot?.floorplanAlt ?? null}
|
||||
rooms={rooms}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -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}
|
||||
</span>
|
||||
)}
|
||||
{user && showInteriorLink && (
|
||||
<Button asChild size="sm" variant="secondary">
|
||||
<Link href={`/logistics/structures/${structure.id}/interior`}>
|
||||
<DoorOpenIcon className="size-4" />
|
||||
Interior
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
{user && (
|
||||
<ManageStorageButton
|
||||
structureId={structure.id}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { RscEntryLexicalCell as RscEntryLexicalCell_44fe37237e0ebf4470c9990d8cb7
|
|||
import { RscEntryLexicalField as RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
|
||||
import { LexicalDiffComponent as LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
|
||||
import { LexicalEditorFeatureClient as LexicalEditorFeatureClient_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
|
||||
import { TextStateFeatureClient as TextStateFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
|
||||
import { FixedToolbarFeatureClient as FixedToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
|
||||
import { InlineToolbarFeatureClient as InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
|
||||
import { HorizontalRuleFeatureClient as HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
|
||||
|
|
@ -33,6 +32,7 @@ import { default as default_c3ea68702b5e5f8f2f98055e01c43c8d } from '@/component
|
|||
import { default as default_2f2033acccb3be245f1a85f7b4271dac } from '@/components/admin/awards/MedalDesigner'
|
||||
import { default as default_701da9bef3b3cc3d8567adf41fa08aa3 } from '@/components/admin/awards/AwardAutomationView'
|
||||
import { default as default_4b88a624e9f0b376cffcc6814d459adb } from '@/components/admin/assignments/AssignmentMembersField'
|
||||
import { TextStateFeatureClient as TextStateFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
|
||||
import { default as default_0edde40a6ccd30c893b1227360f69360 } from '@/components/static/TickDurationDescription'
|
||||
import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/components/static/WarningMessage'
|
||||
import { default as default_8e873aa39584420378774e6c9c4ac54b } from '@/components/admin/VehicleLibraryPicker'
|
||||
|
|
@ -60,7 +60,6 @@ export const importMap = {
|
|||
"@payloadcms/richtext-lexical/rsc#RscEntryLexicalField": RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e,
|
||||
"@payloadcms/richtext-lexical/rsc#LexicalDiffComponent": LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e,
|
||||
"@ai-stack/payloadcms/client#LexicalEditorFeatureClient": LexicalEditorFeatureClient_4490b89d4413c1ffaecdacfe72efaf73,
|
||||
"@payloadcms/richtext-lexical/client#TextStateFeatureClient": TextStateFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
|
||||
"@payloadcms/richtext-lexical/client#FixedToolbarFeatureClient": FixedToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
|
||||
"@payloadcms/richtext-lexical/client#InlineToolbarFeatureClient": InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
|
||||
"@payloadcms/richtext-lexical/client#HorizontalRuleFeatureClient": HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
|
||||
|
|
@ -91,6 +90,7 @@ export const importMap = {
|
|||
"@/components/admin/awards/MedalDesigner#default": default_2f2033acccb3be245f1a85f7b4271dac,
|
||||
"@/components/admin/awards/AwardAutomationView#default": default_701da9bef3b3cc3d8567adf41fa08aa3,
|
||||
"@/components/admin/assignments/AssignmentMembersField#default": default_4b88a624e9f0b376cffcc6814d459adb,
|
||||
"@payloadcms/richtext-lexical/client#TextStateFeatureClient": TextStateFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
|
||||
"@/components/static/TickDurationDescription#default": default_0edde40a6ccd30c893b1227360f69360,
|
||||
"@/components/static/WarningMessage#default": default_2d468cc5cf0b647ffca3201592c20825,
|
||||
"@/components/admin/VehicleLibraryPicker#default": default_8e873aa39584420378774e6c9c4ac54b,
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import {
|
|||
Car,
|
||||
Contact,
|
||||
Crosshair,
|
||||
DoorOpen,
|
||||
Flag,
|
||||
Kanban,
|
||||
Landmark,
|
||||
|
|
@ -111,6 +112,11 @@ export const sidebarData = {
|
|||
url: "/logistics",
|
||||
icon: Building2,
|
||||
},
|
||||
{
|
||||
title: "Interiors",
|
||||
url: "/logistics/interiors",
|
||||
icon: DoorOpen,
|
||||
},
|
||||
{
|
||||
title: "Resources",
|
||||
url: "/logistics/resources",
|
||||
|
|
|
|||
161
src/components/frontend/interiors/InteriorGraphTab.tsx
Normal file
161
src/components/frontend/interiors/InteriorGraphTab.tsx
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import {
|
||||
Background,
|
||||
BackgroundVariant,
|
||||
Controls,
|
||||
Handle,
|
||||
MarkerType,
|
||||
Position,
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
type Edge,
|
||||
type Node,
|
||||
type NodeProps,
|
||||
} from "@xyflow/react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ROOM_STATE_DOT, ROOM_STATE_LABEL, roomState, type InteriorRoomView } from "./types";
|
||||
|
||||
/**
|
||||
* Read-only room graph. Node setup mirrors FrontendTechTreeCanvas: a provider
|
||||
* wrapper, fixed node boxes, and every interaction that implies editing
|
||||
* (drag, connect, select) disabled. Positions come from authored graphX/graphY
|
||||
* or the hotspot center, scaled from the 0-100 authoring space to pixels.
|
||||
*/
|
||||
|
||||
const NODE_WIDTH = 200;
|
||||
const NODE_HEIGHT = 76;
|
||||
const SCALE_X = 12;
|
||||
const SCALE_Y = 8;
|
||||
|
||||
function RoomNode({ data }: NodeProps) {
|
||||
const { room } = data as { room: InteriorRoomView };
|
||||
const state = roomState(room);
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col justify-between border border-white/15 bg-black/70 px-3 py-2 text-white">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="truncate font-mono text-[9px] tracking-widest text-white/50 uppercase">
|
||||
Room // {room.key}
|
||||
</span>
|
||||
<span
|
||||
className={cn("size-2 shrink-0 rounded-full", ROOM_STATE_DOT[state])}
|
||||
title={ROOM_STATE_LABEL[state]}
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="truncate text-sm font-medium">{room.name}</p>
|
||||
<p className="font-mono text-[10px] tracking-widest text-white/50 uppercase">
|
||||
{state === "sealed" ? "Sealed" : `Level ${room.runtime.level} / ${room.maxLevel}`}
|
||||
</p>
|
||||
</div>
|
||||
<Handle type="target" position={Position.Left} className="opacity-0" />
|
||||
<Handle type="source" position={Position.Right} className="opacity-0" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<string>();
|
||||
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 (
|
||||
<div className="relative h-full w-full" style={{ backgroundColor: "#05070a" }}>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
fitView
|
||||
fitViewOptions={{ padding: 0.2, maxZoom: 1 }}
|
||||
minZoom={0.2}
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
elementsSelectable={false}
|
||||
edgesFocusable={false}
|
||||
proOptions={{ hideAttribution: false }}
|
||||
onNodeClick={(_, node) => onSelect(node.id)}
|
||||
>
|
||||
<Background
|
||||
variant={BackgroundVariant.Lines}
|
||||
gap={46}
|
||||
size={1}
|
||||
color="rgba(255,255,255,0.055)"
|
||||
/>
|
||||
<Controls showInteractive={false} />
|
||||
</ReactFlow>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function InteriorGraphTab({ rooms, onSelect }: InteriorGraphTabProps) {
|
||||
return (
|
||||
<div className="h-[min(70dvh,720px)] min-h-[420px] w-full overflow-hidden rounded-none border border-white/15">
|
||||
<ReactFlowProvider>
|
||||
<GraphInner rooms={rooms} onSelect={onSelect} />
|
||||
</ReactFlowProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
250
src/components/frontend/interiors/InteriorShell.tsx
Normal file
250
src/components/frontend/interiors/InteriorShell.tsx
Normal file
|
|
@ -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 (
|
||||
<div aria-hidden className="pointer-events-none absolute inset-2">
|
||||
<span className="absolute top-0 left-0 size-3 border-t border-l border-white/25" />
|
||||
<span className="absolute top-0 right-0 size-3 border-t border-r border-white/25" />
|
||||
<span className="absolute bottom-0 left-0 size-3 border-b border-l border-white/25" />
|
||||
<span className="absolute right-0 bottom-0 size-3 border-r border-b border-white/25" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ReadoutCell({ value, label }: { value: number | string; label: string }) {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center border-r border-white/15 px-3 last:border-r-0">
|
||||
<span className="font-mono text-xs tabular-nums text-white/80">{value}</span>
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/50 uppercase">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function InteriorShell({
|
||||
structureId,
|
||||
structureName,
|
||||
interiorName,
|
||||
floorplanUrl,
|
||||
floorplanAlt,
|
||||
rooms,
|
||||
}: InteriorShellProps) {
|
||||
const router = useRouter();
|
||||
const [selectedKey, setSelectedKey] = useState<string | null>(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<boolean> {
|
||||
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<boolean> {
|
||||
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<boolean> {
|
||||
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 (
|
||||
<div className="flex flex-col gap-5">
|
||||
<section className="relative overflow-hidden rounded-none border border-white/15 bg-card">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-white/15 bg-black/50 px-4 py-1.5 backdrop-blur-sm">
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/60 uppercase">
|
||||
Interior // {structureName}
|
||||
</span>
|
||||
<span className="font-mono text-[9px] tracking-widest text-white/60 uppercase">
|
||||
{reference}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<div
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-0"
|
||||
style={{
|
||||
backgroundImage:
|
||||
"linear-gradient(to right, rgba(255,255,255,0.04) 1px, transparent 1px), linear-gradient(to bottom, rgba(255,255,255,0.04) 1px, transparent 1px)",
|
||||
backgroundSize: "28px 28px",
|
||||
}}
|
||||
/>
|
||||
<Corners />
|
||||
<div className="relative flex flex-col gap-1 p-5">
|
||||
<h1 className="text-lg font-semibold tracking-wide uppercase">
|
||||
{interiorName ?? structureName}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{structureName} · {rooms.length} room{rooms.length === 1 ? "" : "s"} · Pick a room to
|
||||
manage it.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center border-t border-white/15 bg-black/60 py-1.5 backdrop-blur-sm">
|
||||
<ReadoutCell value={rooms.length} label="Rooms" />
|
||||
<ReadoutCell value={ready} label="Ready" />
|
||||
<ReadoutCell value={working} label="Working" />
|
||||
<ReadoutCell value={sealed} label="Sealed" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<Tabs defaultValue="floorplan" className="flex flex-col gap-4">
|
||||
<TabsList variant="line">
|
||||
<TabsTrigger value="floorplan">Floorplan</TabsTrigger>
|
||||
<TabsTrigger value="graph">Graph</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="floorplan" className="flex flex-col gap-3">
|
||||
<div className="relative aspect-video w-full max-w-5xl overflow-hidden rounded-none border border-white/15 bg-muted">
|
||||
{floorplanUrl ? (
|
||||
<img
|
||||
src={floorplanUrl}
|
||||
alt={floorplanAlt ?? `${interiorName ?? structureName} floorplan`}
|
||||
className="absolute inset-0 size-full object-contain"
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
aria-hidden
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
backgroundImage:
|
||||
"linear-gradient(to right, var(--border) 1px, transparent 1px), linear-gradient(to bottom, var(--border) 1px, transparent 1px)",
|
||||
backgroundSize: "6.25% 6.25%",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{rooms.length === 0 && (
|
||||
<p className="absolute inset-0 flex items-center justify-center text-sm text-muted-foreground">
|
||||
No rooms authored for this interior.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{rooms.map((room) => {
|
||||
const state = roomState(room);
|
||||
return (
|
||||
<button
|
||||
key={room.key}
|
||||
type="button"
|
||||
onClick={() => setSelectedKey(room.key)}
|
||||
aria-label={`${room.name}: ${ROOM_STATE_LABEL[state]}`}
|
||||
title={ROOM_STATE_LABEL[state]}
|
||||
className={cn(
|
||||
"absolute flex flex-col items-start justify-end gap-0.5 overflow-hidden border border-border bg-card/80 p-1.5 text-left transition hover:z-10 hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
|
||||
ROOM_STATE_RING[state],
|
||||
)}
|
||||
style={{
|
||||
left: `${room.hotspot.x}%`,
|
||||
top: `${room.hotspot.y}%`,
|
||||
width: `${room.hotspot.width}%`,
|
||||
height: `${room.hotspot.height}%`,
|
||||
}}
|
||||
>
|
||||
<span className="w-full truncate text-xs font-medium">{room.name}</span>
|
||||
<span className="w-full truncate text-[10px] text-muted-foreground">
|
||||
{state === "sealed"
|
||||
? "Sealed"
|
||||
: `Level ${room.runtime.level} / ${room.maxLevel}`}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-muted-foreground">
|
||||
{LEGEND.map((state) => (
|
||||
<span key={state} className="flex items-center gap-2">
|
||||
<span
|
||||
className={cn("size-3 rounded-sm border border-border", ROOM_STATE_RING[state])}
|
||||
/>
|
||||
{ROOM_STATE_LABEL[state]}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="graph">
|
||||
<InteriorGraphTab rooms={rooms} onSelect={setSelectedKey} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{selectedRoom && (
|
||||
<Sheet
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setSelectedKey(null);
|
||||
}}
|
||||
>
|
||||
<SheetContent side="right" className="w-full overflow-y-auto sm:max-w-lg">
|
||||
<RoomSheet
|
||||
key={selectedRoom.key}
|
||||
room={selectedRoom}
|
||||
onStart={handleStart}
|
||||
onCancel={handleCancel}
|
||||
onCollect={handleCollect}
|
||||
onRefresh={() => router.refresh()}
|
||||
/>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
53
src/components/frontend/interiors/JobCountdown.tsx
Normal file
53
src/components/frontend/interiors/JobCountdown.tsx
Normal file
|
|
@ -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 <span>ETA {remaining <= 0 ? "any moment" : formatDuration(remaining)}</span>;
|
||||
}
|
||||
368
src/components/frontend/interiors/RoomSheet.tsx
Normal file
368
src/components/frontend/interiors/RoomSheet.tsx
Normal file
|
|
@ -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<boolean>;
|
||||
onCancel: (jobId: number) => Promise<boolean>;
|
||||
onCollect: (jobId: number) => Promise<boolean>;
|
||||
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<string | null>(null);
|
||||
const job = room.runtime.job;
|
||||
const state = roomState(room);
|
||||
const sealed = room.runtime.level <= 0;
|
||||
|
||||
async function run(key: string, action: () => Promise<boolean>) {
|
||||
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 (
|
||||
<div className="flex flex-col gap-4">
|
||||
<SheetHeader>
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
{room.name}
|
||||
{sealed && <Badge variant="destructive">Sealed</Badge>}
|
||||
</SheetTitle>
|
||||
<SheetDescription>
|
||||
{room.roomType ? `${room.roomType} · ` : ""}
|
||||
{ROOM_STATE_LABEL[state]}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<Tabs defaultValue="status" className="flex flex-col gap-3">
|
||||
<TabsList variant="line">
|
||||
<TabsTrigger value="status">Status</TabsTrigger>
|
||||
<TabsTrigger value="jobs">Jobs</TabsTrigger>
|
||||
{room.station && <TabsTrigger value="station">Station</TabsTrigger>}
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="status" className="flex flex-col gap-4">
|
||||
{room.description && <p className="text-sm text-muted-foreground">{room.description}</p>}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline">
|
||||
Level {room.runtime.level} / {room.maxLevel}
|
||||
</Badge>
|
||||
<Badge variant={room.runtime.junkLevel > 0 ? "secondary" : "outline"}>
|
||||
Junk {room.runtime.junkLevel}
|
||||
</Badge>
|
||||
{room.decay.junkMax > 0 && (
|
||||
<span className="text-xs text-muted-foreground">Junk cap {room.decay.junkMax}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span>Condition</span>
|
||||
<span className="tabular-nums">{room.runtime.condition}%</span>
|
||||
</div>
|
||||
<Progress value={room.runtime.condition} />
|
||||
{room.decay.effectFloor > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Station work stops below {room.decay.effectFloor}% condition.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs tracking-wide text-muted-foreground uppercase">Fixtures</span>
|
||||
{room.runtime.fixtures.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No fixtures installed.</p>
|
||||
) : (
|
||||
room.runtime.fixtures.map((fixture) => {
|
||||
const blueprint = blueprintFixture(fixture.key);
|
||||
const repairKey = `repair-${fixture.key}`;
|
||||
return (
|
||||
<div
|
||||
key={fixture.key}
|
||||
className="flex items-center justify-between gap-3 rounded-md border p-3"
|
||||
>
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="truncate text-sm">{fixture.name}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{fixture.condition}% condition
|
||||
{fixture.blocksStation ? " · blocks station" : ""}
|
||||
</span>
|
||||
</div>
|
||||
{fixture.broken ? (
|
||||
<div className="flex shrink-0 flex-col items-end gap-1">
|
||||
<Badge variant="destructive">Broken</Badge>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={() => run(repairKey, () => onStart("repair", fixture.key))}
|
||||
>
|
||||
{busy === repairKey ? "Starting..." : "Repair"}
|
||||
</Button>
|
||||
<span className="text-right text-xs text-muted-foreground">
|
||||
{materialSummary(blueprint?.repairMaterials ?? [])}
|
||||
{blueprint && blueprint.repairDurationMinutes > 0
|
||||
? ` · ${blueprint.repairDurationMinutes} min`
|
||||
: ""}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<Badge variant="outline">Operational</Badge>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
{sealed ? (
|
||||
<div className="flex flex-col gap-2 rounded-md border p-3">
|
||||
<span className="text-sm font-medium">Open room</span>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{materialSummary(openLevel?.upgradeMaterials ?? [])}
|
||||
{openLevel && openLevel.upgradeDurationMinutes > 0
|
||||
? ` · ${openLevel.upgradeDurationMinutes} min`
|
||||
: ""}
|
||||
</p>
|
||||
{openLevel && openLevel.requiredTechNames.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Requires research: {openLevel.requiredTechNames.join(", ")}
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy !== null}
|
||||
onClick={() => run("open", () => onStart("open"))}
|
||||
>
|
||||
{busy === "open" ? "Starting..." : "Open Room"}
|
||||
</Button>
|
||||
</div>
|
||||
) : atMaxLevel || !nextLevel ? (
|
||||
<div className="rounded-md border p-3">
|
||||
<span className="text-sm font-medium">Maximum level reached</span>
|
||||
<p className="text-xs text-muted-foreground">This room cannot be upgraded further.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2 rounded-md border p-3">
|
||||
<span className="text-sm font-medium">
|
||||
Upgrade to level {nextLevel.level}
|
||||
{nextLevel.label ? ` · ${nextLevel.label}` : ""}
|
||||
</span>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Materials: {materialSummary(nextLevel.upgradeMaterials)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Duration: {nextLevel.upgradeDurationMinutes} min
|
||||
</p>
|
||||
{nextLevel.requiredTechNames.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Requires research: {nextLevel.requiredTechNames.join(", ")}
|
||||
</p>
|
||||
)}
|
||||
{nextLevel.requiredLaborClass && (nextLevel.requiredHeadcount ?? 0) > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Requires {nextLevel.requiredHeadcount}{" "}
|
||||
{humanizeClass(nextLevel.requiredLaborClass)} active
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy !== null}
|
||||
onClick={() => run("upgrade", () => onStart("upgrade", nextLevel.level))}
|
||||
>
|
||||
{busy === "upgrade" ? "Starting..." : "Upgrade"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="jobs" className="flex flex-col gap-3">
|
||||
{job ? (
|
||||
<div className="flex flex-col gap-3 rounded-md border p-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-medium">{JOB_TYPE_LABEL[job.type]}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{JOB_STATUS_LABEL[job.status]}
|
||||
</span>
|
||||
</div>
|
||||
<Badge
|
||||
variant={
|
||||
job.status === "awaiting_collect"
|
||||
? "default"
|
||||
: job.status === "active"
|
||||
? "secondary"
|
||||
: "outline"
|
||||
}
|
||||
>
|
||||
{JOB_STATUS_LABEL[job.status]}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{job.status === "active" && (
|
||||
<p className="text-sm">
|
||||
<JobCountdown endsAt={job.endsAt} onFinished={onRefresh} />
|
||||
</p>
|
||||
)}
|
||||
|
||||
{collectable && (
|
||||
<div className="flex flex-col gap-1 rounded-md bg-muted p-3">
|
||||
<span className="text-xs tracking-wide text-muted-foreground uppercase">
|
||||
Output
|
||||
</span>
|
||||
{job.output.resources.length === 0 && job.output.assets.length === 0 ? (
|
||||
<span className="text-sm text-muted-foreground">No output recorded.</span>
|
||||
) : (
|
||||
<>
|
||||
{job.output.resources.map((row) => (
|
||||
<span key={`resource-${row.name}`} className="text-sm">
|
||||
{row.amount} × {row.name}
|
||||
</span>
|
||||
))}
|
||||
{job.output.assets.map((row) => (
|
||||
<span key={`asset-${row.name}`} className="text-sm">
|
||||
{row.amount} × {row.name}{" "}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
(asset, requires asset outputs enabled)
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{job.status === "active" && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={() => run("cancel", () => onCancel(job.id))}
|
||||
>
|
||||
{busy === "cancel" ? "Cancelling..." : "Cancel Job"}
|
||||
</Button>
|
||||
)}
|
||||
{collectable && (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy !== null}
|
||||
onClick={() => run("collect", () => onCollect(job.id))}
|
||||
>
|
||||
{busy === "collect" ? "Collecting..." : "Collect"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2 rounded-md border p-3">
|
||||
<span className="text-sm font-medium">Junk cleanup</span>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Current junk level: {room.runtime.junkLevel}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A cleanup run clears one junk level and can recover salvage.
|
||||
</p>
|
||||
{room.runtime.junkLevel > 0 ? (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy !== null}
|
||||
onClick={() => run("cleanup", () => onStart("cleanup"))}
|
||||
>
|
||||
{busy === "cleanup" ? "Starting..." : "Start Cleanup"}
|
||||
</Button>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">Nothing to clean up.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
{room.station && (
|
||||
<TabsContent value="station" className="flex flex-col gap-3">
|
||||
{room.station.recipes.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No enabled recipes at this station.</p>
|
||||
) : (
|
||||
room.station.recipes.map((recipe) => {
|
||||
const recipeKey = `recipe-${recipe.key}`;
|
||||
return (
|
||||
<div key={recipe.key} className="flex flex-col gap-2 rounded-md border p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-sm font-medium">{recipe.name}</span>
|
||||
<Badge variant="outline">{recipe.durationMinutes} min</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Inputs: {materialSummary(recipe.inputs)}
|
||||
</p>
|
||||
<div className="flex flex-col gap-0.5 text-xs text-muted-foreground">
|
||||
<span>Outputs:</span>
|
||||
{recipe.outputs.length === 0 ? (
|
||||
<span>None</span>
|
||||
) : (
|
||||
recipe.outputs.map((output) => (
|
||||
<span key={`${output.kind}-${output.id}`}>
|
||||
{output.amount} × {output.name}
|
||||
{output.kind === "asset"
|
||||
? " (asset, requires asset outputs enabled)"
|
||||
: ""}
|
||||
</span>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Requires room level {recipe.requiredRoomLevel}
|
||||
</p>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={busy !== null}
|
||||
onClick={() => run(recipeKey, () => onStart("produce", recipe.key))}
|
||||
>
|
||||
{busy === recipeKey ? "Starting..." : "Start"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</TabsContent>
|
||||
)}
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
178
src/components/frontend/interiors/types.ts
Normal file
178
src/components/frontend/interiors/types.ts
Normal file
|
|
@ -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<InteriorRoomState, string> = {
|
||||
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<InteriorRoomState, string> = {
|
||||
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<InteriorRoomState, string> = {
|
||||
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<InteriorJobType, string> = {
|
||||
open: "Open room",
|
||||
cleanup: "Cleanup",
|
||||
upgrade: "Upgrade",
|
||||
repair: "Repair",
|
||||
produce: "Production",
|
||||
};
|
||||
|
||||
export const JOB_STATUS_LABEL: Record<InteriorJobStatus, string> = {
|
||||
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(", ");
|
||||
}
|
||||
|
|
@ -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();
|
||||
|
|
|
|||
517
src/tools/seed/seedInteriorContent.ts
Normal file
517
src/tools/seed/seedInteriorContent.ts
Normal file
|
|
@ -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<ReturnType<typeof getPayload>>,
|
||||
pool: Pool,
|
||||
args: { name: string; codeName: string; massPerUnit: number; stackSize: number },
|
||||
): Promise<number> => {
|
||||
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<number> => {
|
||||
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<string, unknown>,
|
||||
});
|
||||
|
||||
// --- 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);
|
||||
}
|
||||
|
|
@ -86,5 +86,9 @@ export const seedScrap = async (): Promise<number> => {
|
|||
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);
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue