1
0
Fork 0

feat(interior): add superstructure interior schema and engine core

Adds the interior authoring fields on structure blueprints, runtime interior snapshot fields on game structures, the structure-rooms and interior-jobs collections, GameRules toggles, and a Scrap resource seed.

Adds the src/lib/interior engine: access gate, room provisioning, job-start gates, structure storage bridge, job lifecycle (start, cancel, complete, collect), completion sweep, and the interior-tick bin.

Registers interior event types and the interior:job-ready notification type.
This commit is contained in:
Jason Fraley 2026-10-20 14:37:13 -04:00
parent f62f5265fa
commit c57fc3d23d
25 changed files with 48449 additions and 2 deletions

View file

@ -276,6 +276,34 @@ export const GameRules: GlobalConfig = {
},
],
},
{
name: "interior",
type: "group",
label: "Superstructure Interior",
admin: {
description: "Global knobs for the Superstructure interior system (interior-tick).",
},
fields: [
{
name: "decayEnabled",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Master gate for interior condition/junk decay. When off, the interior-tick skips decay.",
},
},
{
name: "decayMultiplier",
type: "number",
min: 0,
defaultValue: 1,
admin: {
description: "Multiplier applied to per-room decay while the master gate is on.",
},
},
],
},
{
name: "zonePressureEnabled",
type: "checkbox",

View file

@ -569,5 +569,74 @@ export const GameStructures: CollectionConfig = {
},
},
},
{
name: "interior",
type: "group",
label: "Superstructure Interior",
admin: {
description:
"Runtime interior state, provisioned from the structure blueprint. Rooms live on structure-rooms; this snapshot preserves the floorplan + access so blueprint edits never retarget live rooms.",
},
fields: [
{
name: "provisionedAt",
type: "date",
admin: { readOnly: true, description: "When the interior rooms were first provisioned." },
},
{
name: "lastDecayAt",
type: "date",
admin: { readOnly: true, description: "Last interior decay sweep." },
},
{
name: "floorplan",
type: "upload",
relationTo: "media",
admin: { description: "Snapshot of the blueprint floorplan at provisioning." },
},
{
name: "floorplanAlt",
type: "text",
},
{
name: "rooms",
type: "json",
admin: {
description: "Authoritative copy of the blueprint rooms array at provisioning time.",
},
},
{
name: "interiorAccess",
type: "group",
label: "Interior Access",
admin: { description: "Snapshot of the blueprint interior access at provisioning." },
fields: [
{
name: "mode",
type: "select",
defaultValue: "anyone",
options: [
{ label: "Anyone (all members)", value: "anyone" },
{ label: "Specific roles", value: "roles" },
{ label: "Specific users", value: "users" },
],
},
{
name: "roles",
type: "relationship",
relationTo: "roles",
hasMany: true,
},
{
name: "users",
type: "relationship",
relationTo: "users",
hasMany: true,
},
],
},
],
},
],
};

View file

@ -0,0 +1,173 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
/**
* One row per interior job (open / cleanup / upgrade / repair / produce).
*
* One job per room at a time. A room with an awaiting_collect or cancelled job
* blocks new jobs until its output is collected (the "output slot"). Inputs are
* consumed at start and recorded on committedResources so cancel always refunds;
* a job can therefore never fail to credit its starter.
*
* Access mirrors structure-rooms: reads authenticated, writes gated at the
* collection level and enforced per-structure by the engine + actions.
*/
export const InteriorJobs: CollectionConfig = {
slug: "interior-jobs",
admin: {
group: "Interior",
useAsTitle: "id",
defaultColumns: ["structure", "room", "type", "status", "endsAt"],
},
access: {
read: ({ req }) => Boolean(req.user),
create: requirePermission("game-structures:update"),
update: requirePermission("game-structures:update"),
delete: requirePermission("game-structures:update"),
},
fields: [
{
name: "structure",
type: "relationship",
relationTo: "game-structures",
required: true,
index: true,
},
{
name: "room",
type: "relationship",
relationTo: "structure-rooms",
required: true,
index: true,
},
{
name: "type",
type: "select",
required: true,
options: [
{ label: "Open (sealed room)", value: "open" },
{ label: "Cleanup junk", value: "cleanup" },
{ label: "Upgrade room", value: "upgrade" },
{ label: "Repair fixture", value: "repair" },
{ label: "Produce", value: "produce" },
],
},
{
name: "status",
type: "select",
required: true,
defaultValue: "active",
options: [
{ label: "Active", value: "active" },
{ label: "Ready to collect", value: "awaiting_collect" },
{ label: "Cancelled", value: "cancelled" },
{ label: "Collected", value: "collected" },
{ label: "Failed", value: "failed" },
],
},
{
name: "stationRecipeKey",
type: "text",
admin: { description: "Recipe key for a produce job." },
},
{
name: "fixtureKey",
type: "text",
admin: { description: "Fixture key for a repair job." },
},
{
name: "targetLevel",
type: "number",
admin: { description: "Destination level for an upgrade job." },
},
{
name: "startedBy",
type: "relationship",
relationTo: "users",
},
{
name: "startedAt",
type: "date",
},
{
name: "endsAt",
type: "date",
index: true,
},
{
name: "laborClass",
type: "text",
admin: { description: "Labor class the job was started under." },
},
{
name: "headcount",
type: "number",
min: 0,
},
{
name: "committedResources",
type: "array",
label: "Committed Resources",
admin: { description: "Resources consumed at start; refunded on cancel." },
fields: [
{
name: "resource",
type: "relationship",
relationTo: "resources",
required: true,
},
{ name: "amount", type: "number", required: true },
],
},
{
name: "output",
type: "group",
label: "Output",
fields: [
{
name: "resources",
type: "array",
label: "Resources",
fields: [
{
name: "resource",
type: "relationship",
relationTo: "resources",
required: true,
},
{ name: "amount", type: "number", required: true },
],
},
{
name: "assets",
type: "array",
label: "Assets",
fields: [
{
name: "asset",
type: "relationship",
relationTo: "assets",
required: true,
},
{ name: "amount", type: "number", required: true },
],
},
],
},
{
name: "resultNote",
type: "text",
admin: { description: "Human-readable summary of what the job produced or refunded." },
},
{
name: "collectedAt",
type: "date",
},
{
name: "collectedBy",
type: "relationship",
relationTo: "users",
},
],
timestamps: true,
};

View file

@ -0,0 +1,134 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
/**
* Runtime state for one room instance inside a game-structure interior.
*
* One row per (game-structure, roomKey), provisioned idempotently from the
* structure blueprint on first entry (see src/lib/interior/provision.ts).
* Blueprint authoring lives on the Structures collection; this collection is
* the live, per-instance truth (level, condition, junk, fixtures, station).
*
* Access mirrors game-structures: reads are authenticated and the interior
* access gate (canUserEnterInterior) is enforced on page load and every
* action. Writes go through the engine with overrideAccess, so the collection
* write gate is a safety net (game-structures:update), not the real gate.
*/
export const StructureRooms: CollectionConfig = {
slug: "structure-rooms",
admin: {
group: "Interior",
useAsTitle: "name",
defaultColumns: ["structure", "roomKey", "name", "level", "condition"],
},
access: {
read: ({ req }) => Boolean(req.user),
create: requirePermission("game-structures:update"),
update: requirePermission("game-structures:update"),
delete: requirePermission("game-structures:update"),
},
hooks: {
beforeChange: [
// Keep the display name in sync with the room key so the admin list reads
// "barracks (Barracks)" even before a human renames it.
({ data }) => {
if (!data) return data;
const room = data as { name?: string; roomKey?: string };
if (!room.name && room.roomKey) {
return { ...data, name: room.roomKey };
}
return data;
},
],
},
fields: [
{
name: "structure",
type: "relationship",
relationTo: "game-structures",
required: true,
index: true,
},
{
name: "roomKey",
type: "text",
required: true,
index: true,
},
{
name: "name",
type: "text",
required: true,
},
{
name: "level",
type: "number",
defaultValue: 0,
min: 0,
admin: { description: "Current room level. 0 = sealed." },
},
{
name: "condition",
type: "number",
defaultValue: 100,
min: 0,
max: 100,
admin: { readOnly: true, description: "100 = pristine, 0 = fully degraded." },
},
{
name: "junkLevel",
type: "number",
defaultValue: 0,
min: 0,
admin: { description: "Accumulated junk; cleaned via a cleanup job." },
},
{
name: "stationLevel",
type: "number",
defaultValue: 0,
min: 0,
admin: { description: "Level at which the room's station is currently running." },
},
{
name: "lastDecayAt",
type: "date",
admin: { readOnly: true },
},
{
name: "pendingJob",
type: "relationship",
relationTo: "interior-jobs",
label: "Output Slot Job",
admin: {
description: "The job occupying this room's output slot, if any. Set only when the room is busy.",
},
},
{
name: "fixtures",
type: "array",
label: "Fixture State",
admin: { description: "Provisioned from the blueprint fixtures; condition tracked here." },
fields: [
{ name: "key", type: "text", required: true },
{ name: "name", type: "text", required: true },
{
name: "broken",
type: "checkbox",
defaultValue: false,
},
{
name: "condition",
type: "number",
defaultValue: 100,
min: 0,
max: 100,
},
{
name: "brokenAt",
type: "date",
},
],
},
],
timestamps: true,
};

View file

@ -1,5 +1,9 @@
import { CollectionConfig } from "payload";
import { approvalStatusFieldAccess, resetApprovalStatusOnEdit } from "@/utils/access-control/divisionAccess";
import {
approvalStatusFieldAccess,
requireApprovalPermission,
resetApprovalStatusOnEdit,
} from "@/utils/access-control/divisionAccess";
import type { Resource } from "@/payload-types";
import { emitGameEvent } from "@/utils/event-log/emit";
import { createStaffingFields } from "@/collections/game/staffingFields";
@ -761,5 +765,426 @@ export const Structures: CollectionConfig = {
},
],
},
{
label: "Superstructure Interior",
type: "group",
admin: {
description:
"The room interior for the Superstructure: enter floorplans, clean junk, open sealed rooms, upgrade rooms, repair damage, and run production stations.",
},
fields: [
{
name: "interiorEnabled",
type: "checkbox",
label: "Enable Interior",
access: {
create: requireApprovalPermission(),
update: requireApprovalPermission(),
},
admin: {
description:
"Superuser-only toggle. When off, the interior is hidden from members. The Superstructure enables this.",
},
},
{
name: "interiorName",
type: "text",
admin: {
description: 'The member-facing name for the interior, e.g. "The Superstructure".',
},
},
{
name: "floorplan",
type: "upload",
relationTo: "media",
admin: {
description:
"The floorplan image with clickable room hotspots. If left empty the UI renders a generated schematic from the room hotspot rectangles.",
},
},
{
name: "floorplanAlt",
type: "text",
admin: {
description: "Optional alt label shown alongside the floorplan.",
},
},
{
name: "interiorAccess",
type: "group",
label: "Interior Access",
admin: {
description:
"Who can enter this structure's interior in the member UI. Mirrors Item Storage Access.",
},
fields: [
{
name: "mode",
type: "select",
defaultValue: "anyone",
options: [
{ label: "Anyone (all members)", value: "anyone" },
{ label: "Specific roles", value: "roles" },
{ label: "Specific users", value: "users" },
],
},
{
name: "roles",
type: "relationship",
relationTo: "roles",
hasMany: true,
admin: {
condition: (_data, siblingData) => siblingData?.mode === "roles",
},
},
{
name: "users",
type: "relationship",
relationTo: "users",
hasMany: true,
admin: {
condition: (_data, siblingData) => siblingData?.mode === "users",
},
},
],
},
{
name: "rooms",
type: "array",
label: "Interior Rooms",
admin: {
description:
"The authored room blueprint. One row per room; the runtime state lives on structure-rooms at provisioning.",
},
fields: [
{
name: "key",
type: "text",
required: true,
admin: {
description: "Stable slug, unique within the structure (e.g. 'barracks').",
},
},
{
name: "name",
type: "text",
required: true,
},
{
name: "description",
type: "richText",
},
{
name: "roomType",
type: "text",
admin: {
description: "Free-type label (e.g. barracks, workshop, annex).",
},
},
{
name: "hotspot",
type: "group",
admin: {
description: "Position and size as percentages of the floorplan (0-100).",
},
fields: [
{ name: "x", type: "number", required: true },
{ name: "y", type: "number", required: true },
{ name: "width", type: "number", required: true },
{ name: "height", type: "number", required: true },
{
name: "graphX",
type: "number",
admin: { description: "Optional read-only graph node position (0-100). Overrides hotspot center when set." },
},
{
name: "graphY",
type: "number",
admin: { description: "Optional read-only graph node position (0-100). Overrides hotspot center when set." },
},
],
},
{
name: "initialLevel",
type: "number",
defaultValue: 0,
admin: {
description: "Starting room level. 0 means the room is sealed and must be opened.",
},
},
{
name: "maxLevel",
type: "number",
required: true,
min: 0,
},
{
name: "levels",
type: "array",
label: "Level Progression",
admin: {
description: "One row per level, ordered by level. Drives upgrade costs, gates, and effects.",
},
fields: [
{ name: "level", type: "number", required: true },
{ name: "label", type: "text" },
{
name: "upgradeMaterials",
type: "array",
label: "Upgrade Materials",
fields: [
{
name: "resource",
type: "relationship",
relationTo: "resources",
required: true,
},
{ name: "amount", type: "number", required: true },
],
},
{
name: "upgradeDurationMinutes",
type: "number",
required: true,
min: 1,
},
{
name: "requiredTech",
type: "relationship",
relationTo: "technologies",
hasMany: true,
admin: {
description: "Research that must be completed (researchedAt) before this level is reachable.",
},
},
{
name: "requiredLaborClass",
type: "text",
admin: {
description: "Labor classification required to start the upgrade. Empty = none.",
},
},
{
name: "requiredHeadcount",
type: "number",
min: 0,
admin: { description: "Minimum active labor headcount for this class to start the job." },
},
{
name: "effects",
type: "array",
label: "Level Effects",
admin: {
description: "Multipliers applied at this level: production speed, output bonus, storage/labor capacity, and recipe/station unlocks.",
},
fields: [
{
name: "type",
type: "select",
required: true,
options: [
{ label: "Production Speed", value: "production_speed" },
{ label: "Output Bonus", value: "output_bonus" },
{ label: "Storage Capacity", value: "storage_capacity" },
{ label: "Labor Capacity", value: "labor_capacity" },
{ label: "Unlocks Recipe", value: "unlocks_recipe" },
{ label: "Unlocks Station", value: "unlocks_station" },
],
},
{ name: "value", type: "number" },
{
name: "target",
type: "text",
admin: {
description:
"Target for unlock effects: the recipe key (unlocks_recipe) or a station marker (unlocks_station). Ignored by numeric effects.",
},
},
],
},
],
},
{
name: "station",
type: "group",
label: "Production Station",
admin: {
description: "Optional equipment station that runs recipes to produce resources or assets.",
},
fields: [
{ name: "name", type: "text" },
{
name: "enabled",
type: "checkbox",
defaultValue: false,
},
{
name: "recipes",
type: "array",
label: "Recipes",
fields: [
{ name: "key", type: "text", required: true },
{ name: "name", type: "text", required: true },
{
name: "enabled",
type: "checkbox",
defaultValue: true,
admin: {
description: "Asset-output recipes stay disabled at launch until locker apply is verified.",
},
},
{ name: "durationMinutes", type: "number", required: true, min: 1 },
{
name: "requiredLaborClass",
type: "text",
},
{ name: "requiredHeadcount", type: "number", min: 0 },
{ name: "requiredRoomLevel", type: "number", defaultValue: 1, min: 1 },
{
name: "inputs",
type: "array",
label: "Inputs",
fields: [
{
name: "resource",
type: "relationship",
relationTo: "resources",
required: true,
},
{ name: "amount", type: "number", required: true, min: 0 },
],
},
{
name: "outputs",
type: "array",
label: "Outputs",
fields: [
{
name: "kind",
type: "select",
required: true,
options: [
{ label: "Resource", value: "resource" },
{ label: "Asset", value: "asset" },
],
},
{
name: "item",
type: "relationship",
relationTo: ["resources", "assets"],
required: true,
},
{ name: "amount", type: "number", required: true, min: 0 },
],
},
],
},
],
},
{
name: "fixtures",
type: "array",
label: "Fixtures",
admin: { description: "Physical fixtures that can break and be repaired." },
fields: [
{ name: "key", type: "text", required: true },
{ name: "name", type: "text", required: true },
{
name: "condition",
type: "number",
admin: { description: "Starting condition. Empty defaults to 100 at provisioning." },
},
{
name: "brokenByDefault",
type: "checkbox",
defaultValue: false,
},
{
name: "repairMaterials",
type: "array",
label: "Repair Materials",
fields: [
{
name: "resource",
type: "relationship",
relationTo: "resources",
required: true,
},
{ name: "amount", type: "number", required: true },
],
},
{ name: "repairDurationMinutes", type: "number", min: 1 },
{
name: "blocksStation",
type: "checkbox",
defaultValue: false,
admin: { description: "When broken, this fixture blocks the room's station until repaired." },
},
],
},
{
name: "decay",
type: "group",
label: "Decay",
admin: { description: "Per-room condition and junk decay parameters." },
fields: [
{
name: "conditionPerDay",
type: "number",
defaultValue: 0,
admin: { description: "Condition lost per elapsed game day." },
},
{
name: "effectFloor",
type: "number",
defaultValue: 0,
admin: {
description: "Condition at or below which the room no longer functions (0 output).",
},
},
{
name: "junkMax",
type: "number",
defaultValue: 0,
admin: { description: "Maximum junk level before the room is blocked." },
},
{
name: "initialJunkLevel",
type: "number",
defaultValue: 0,
},
],
},
{
name: "junkLoot",
type: "array",
label: "Junk Loot Table",
admin: { description: "Rolled when a junk-cleanup job completes." },
fields: [
{
name: "kind",
type: "select",
required: true,
options: [
{ label: "Resource", value: "resource" },
{ label: "Asset", value: "asset" },
],
},
{
name: "item",
type: "relationship",
relationTo: ["resources", "assets"],
required: true,
},
{ name: "amountMin", type: "number", required: true },
{ name: "amountMax", type: "number", required: true },
{ name: "weight", type: "number", required: true, defaultValue: 1 },
],
},
],
},
],
},
],
};

View file

@ -0,0 +1,74 @@
import type { PayloadRequest } from "payload";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { InteriorAccessMode } from "@/lib/interior/types";
type PayloadLike = Parameters<typeof hasPermission>[0];
type UserInput = { id: number | string; roleDocs?: unknown } | null | undefined;
function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
/**
* Interior access gate for the Superstructure. Mirrors
* `canUserAccessStructureStorage` exactly, but reads the structure's
* `interiorAccess` snapshot (mode anyone/roles/users) instead of storageAccess.
*
* Admins holding `game-structures:update` always pass; otherwise the interior
* access mode decides. This is the single source of truth for "who may enter
* this structure's interior" and is evaluated on page load and on every action
* (see the plan's access model).
*
* `doc` is expected to be a game-structure row that carries the snapshot
* (`game-structures.interior.interiorAccess`).
*/
export async function canUserEnterInterior(
payload: PayloadLike,
user: UserInput,
doc?: Record<string, unknown> | null,
): Promise<boolean> {
if (!user) return false;
if (await hasPermission(payload, user, "game-structures:update")) return true;
// The access config lives on the runtime snapshot. Fall back to the blueprint
// group only if the snapshot is absent (e.g. pre-provisioning admin reads).
const access = (doc?.interiorAccess ?? (doc?.interior as Record<string, unknown>)?.interiorAccess) as
| { mode?: InteriorAccessMode; roles?: unknown; users?: unknown }
| undefined;
const mode = access?.mode ?? "anyone";
if (mode === "anyone") return true;
if (mode === "roles") {
const allowed = (Array.isArray(access?.roles) ? (access.roles as unknown[]) : [])
.map(relId)
.filter((v): v is number => v != null);
const userRoles = (Array.isArray((user as { roleDocs?: unknown }).roleDocs)
? ((user as { roleDocs: unknown[] }).roleDocs as unknown[])
: []
)
.map(relId)
.filter((v): v is number => v != null);
return allowed.length > 0 && userRoles.some((role) => allowed.includes(role));
}
if (mode === "users") {
const allowed = (Array.isArray(access?.users) ? (access.users as unknown[]) : []).map(relId);
return allowed.some((id) => id != null && String(id) === String(user.id));
}
return false;
}
/** Field-level gate used by the game-structures collection (web UI only). */
export async function canAccessInterior({
req,
doc,
}: {
req: PayloadRequest;
doc?: Record<string, unknown> | null;
}): Promise<boolean> {
return canUserEnterInterior(req.payload, req.user, doc);
}

103
src/lib/interior/effects.ts Normal file
View file

@ -0,0 +1,103 @@
import type { InteriorBlueprintRoom, LevelEffect } from "@/lib/interior/types";
/**
* Pure effect-resolution logic for interior rooms.
*
* A blueprint room carries a `levels` array; each level defines its own
* `effects`. The room's *effective* effects at a given runtime level are the
* sum of every effect from level 1 up to and including that level. This module
* is framework-free (no Payload) so it can be unit-tested in isolation.
*/
export type RoomEffects = {
/** Production speed multiplier (1 = base, 1.25 = 25% faster). */
productionSpeedMultiplier: number;
/** Output multiplier from output_bonus (1 = base, 1.10 = +10%). */
outputMultiplier: number;
/** Additive storage capacity points granted so far this level. */
storageCapacityPoints: number;
/** Additive labor slots granted so far this level. */
laborCapacityPoints: number;
/** Recipe keys unlocked by unlocks_recipe effects at or below this level. */
unlockedRecipes: string[];
/** Station markers unlocked by unlocks_station effects at or below this level. */
unlockedStations: string[];
};
function effectsAtLevel(levels: InteriorBlueprintRoom["levels"], level: number): LevelEffect[] {
const def = levels?.find((l) => l.level === level);
return def?.effects ?? [];
}
/** Sum every effect from level 1..=target for the given room blueprint. */
export function resolveRoomEffects(
room: Pick<InteriorBlueprintRoom, "levels">,
targetLevel: number,
): RoomEffects {
const result: RoomEffects = {
productionSpeedMultiplier: 1,
outputMultiplier: 1,
storageCapacityPoints: 0,
laborCapacityPoints: 0,
unlockedRecipes: [],
unlockedStations: [],
};
const maxLevel = room.levels?.reduce((max, l) => Math.max(max, l.level ?? 0), 0) ?? 0;
if (targetLevel > maxLevel) targetLevel = maxLevel;
for (let level = 1; level <= targetLevel; level++) {
for (const effect of effectsAtLevel(room.levels, level)) {
applyEffect(result, effect);
}
}
return result;
}
function applyEffect(result: RoomEffects, effect: LevelEffect): void {
switch (effect.type) {
case "production_speed":
result.productionSpeedMultiplier += effect.value ?? 0;
break;
case "output_bonus":
result.outputMultiplier += effect.value ?? 0;
break;
case "storage_capacity":
result.storageCapacityPoints += effect.value ?? 0;
break;
case "labor_capacity":
result.laborCapacityPoints += effect.value ?? 0;
break;
case "unlocks_recipe":
if (effect.target && !result.unlockedRecipes.includes(effect.target)) {
result.unlockedRecipes.push(effect.target);
}
break;
case "unlocks_station":
if (effect.target && !result.unlockedStations.includes(effect.target)) {
result.unlockedStations.push(effect.target);
}
break;
default:
break;
}
}
/** True when the room has unlocked the recipe with the given key. */
export function isRecipeUnlocked(
room: Pick<InteriorBlueprintRoom, "levels">,
targetLevel: number,
recipeKey: string,
): boolean {
return resolveRoomEffects(room, targetLevel).unlockedRecipes.includes(recipeKey);
}
/** True when the room has unlocked the given station marker. */
export function isStationUnlocked(
room: Pick<InteriorBlueprintRoom, "levels">,
targetLevel: number,
stationMarker: string,
): boolean {
return resolveRoomEffects(room, targetLevel).unlockedStations.includes(stationMarker);
}

112
src/lib/interior/gates.ts Normal file
View file

@ -0,0 +1,112 @@
import type { InteriorBlueprintRoom, JobType, RoomEffectType, RoomFixtureState, RuntimeRoom } from "@/lib/interior/types";
/**
* Pure job-start gates for the interior.
*
* These functions take a room's runtime state + its blueprint definition and
* decide whether a job of a given type may start. They contain no Payload I/O
* so they are fully unit-testable; the Payload-aware orchestration in jobs.ts
* calls them after loading docs.
*/
export type JobStartError =
| "no_access"
| "room_busy"
| "already_open"
| "nothing_to_cleanup"
| "max_level_reached"
| "fixture_blocks_station"
| "recipe_locked"
| "station_disabled"
| "room_level_insufficient"
| "recipe_disabled";
export type JobStartResult = { ok: true } | { ok: false; reason: JobStartError };
/** A fixture that blocks the room's station when broken. */
export function isBlockingFixtureBroken(fixtures: RoomFixtureState[] | undefined): boolean {
if (!fixtures) return false;
return fixtures.some((f) => f.broken && f.blocksStation);
}
/**
* Whether a job of `jobType` may start on this room right now.
*
* `opts` carries the recipe/station context needed by produce jobs.
*/
export function canStartJob(
room: RuntimeRoom,
roomType: "open" | "upgrade" | "cleanup" | "repair" | "produce",
opts?: {
maxLevel?: number;
stationEnabled?: boolean;
stationUnlocked?: boolean;
recipeUnlocked?: boolean;
recipeEnabled?: boolean;
recipeRequiredRoomLevel?: number;
recipeBlockingFixture?: boolean;
},
): JobStartResult {
// A room can only run one job at a time (the output slot).
if (room.pendingJob) return { ok: false, reason: "room_busy" };
switch (roomType) {
case "open":
return (room.level ?? 0) > 0 ? { ok: false, reason: "already_open" } : { ok: true };
case "cleanup":
return (room.junkLevel ?? 0) > 0 ? { ok: true } : { ok: false, reason: "nothing_to_cleanup" };
case "upgrade": {
const max = opts?.maxLevel ?? (room.level ?? 0);
if ((room.level ?? 0) >= max) return { ok: false, reason: "max_level_reached" };
if (opts?.recipeBlockingFixture && isBlockingFixtureBroken(room.fixtures)) {
return { ok: false, reason: "fixture_blocks_station" };
}
return { ok: true };
}
case "repair":
return { ok: true };
case "produce": {
if (!opts?.stationEnabled) return { ok: false, reason: "station_disabled" };
if (opts?.recipeBlockingFixture && isBlockingFixtureBroken(room.fixtures)) {
return { ok: false, reason: "fixture_blocks_station" };
}
if (!opts?.recipeUnlocked) return { ok: false, reason: "recipe_locked" };
if (!opts?.recipeEnabled) return { ok: false, reason: "recipe_disabled" };
if (
opts?.recipeRequiredRoomLevel != null &&
(room.level ?? 0) < opts.recipeRequiredRoomLevel
) {
return { ok: false, reason: "room_level_insufficient" };
}
return { ok: true };
}
}
}
/**
* Convenience: does the room have a fixture that blocks the station and is
* currently broken? Used by produce/upgrade gating.
*/
export function stationBlockedByFixture(
room: { fixtures?: RoomFixtureState[] },
): boolean {
return isBlockingFixtureBroken(room.fixtures);
}
/**
* Whether the room currently has any decay-driven issues that block work
* (condition below the effect floor, or junk at junkMax).
*/
export function roomBlockedByDecay(room: { condition: number; junkLevel: number }): boolean {
return room.condition <= 0 || room.junkLevel >= 0;
}
/** Type guard so callers can narrow effect types without a switch. */
export function isRoomEffectType(value: unknown): value is RoomEffectType {
return (
typeof value === "string" &&
(["production_speed", "output_bonus", "storage_capacity", "labor_capacity", "unlocks_recipe", "unlocks_station"] as string[]).includes(value)
);
}
export type { RoomEffectType, InteriorBlueprintRoom, JobType };

552
src/lib/interior/jobs.ts Normal file
View file

@ -0,0 +1,552 @@
import type { Payload } from "payload";
import type { GameStructure, InteriorJob } from "@/payload-types";
import type { InteriorBlueprintRoom, RoomFixtureState, RuntimeRoom } from "./types";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { emitGameEvent } from "@/utils/event-log/emit";
import { notifyUser } from "@/lib/notifications";
import { canUserEnterInterior } from "./access";
import { canStartJob } from "./gates";
import * as storageBridge from "./storageBridge";
import { relId } from "./relations";
/**
* Interior job lifecycle: start, cancel, collect.
*
* One job occupies a room's output slot at a time. Inputs are consumed
* (committed) at start and recorded on `committedResources` so a cancel always
* refunds them; a job can therefore never fail to credit its starter. The room
* is blocked from new jobs until the job is collected (awaiting_collect /
* cancelled) or cleared by the sweep.
*/
export type JobStartError =
| "no_access"
| "not_found"
| "room_busy"
| "already_open"
| "nothing_to_cleanup"
| "max_level_reached"
| "fixture_blocked"
| "recipe_locked"
| "station_disabled"
| "room_level_insufficient"
| "recipe_disabled"
| "insufficient_resources"
| "mass_over_cap"
| "no_room"
| "no_blueprint";
export type JobStartResult =
| { ok: true; job: InteriorJob }
| { ok: false; error: JobStartError };
export type PayloadType = Awaited<ReturnType<typeof import("payload").getPayload>>;
/** Resolve the blueprint room from a game-structure's runtime snapshot. */
function blueprintRoom(
structure: GameStructure,
roomKey: string,
): InteriorBlueprintRoom | undefined {
const rooms = (structure.interior as { rooms?: InteriorBlueprintRoom[] } | undefined)?.rooms;
return rooms?.find((r) => r.key === roomKey);
}
/** Build the payload `update` fragment that occupies the room's output slot. */
function busyFragment(jobId: number): Record<string, unknown> {
return { pendingJob: jobId };
}
/**
* Start an interior job of the given type. Validates access + the room's
* job-start gates, consumes committed resources, persists the job row, and
* blocks the room's output slot until the job is collected.
*/
export async function startInteriorJob(
payload: PayloadType,
user: { id: number | string; roleDocs?: unknown } | null,
args: {
structureId: number | string;
roomKey: string;
type: InteriorJob["type"];
/** Produce: recipe key. Upgrade: destination level. Repair: fixture key. */
target?: string | number;
laborClass?: string | null;
headcount?: number | null;
},
): Promise<JobStartResult> {
const { structureId, roomKey, type, target, laborClass, headcount } = args;
if (!(await canUserEnterInterior(payload, user, { interiorAccess: undefined }))) {
// Access is evaluated against the resolved structure below; this early
// guard keeps the types narrow until we have the doc.
}
const structure = await payload.findByID({
collection: "game-structures",
id: relId(structureId)!,
overrideAccess: true,
depth: 0,
select: {
id: true,
interior: true,
},
}).catch(() => null);
if (!structure) return { ok: false, error: "not_found" };
if (!(await canUserEnterInterior(payload, user, structure as unknown as Record<string, unknown>))) {
return { ok: false, error: "no_access" };
}
const roomDoc = await payload
.find({
collection: "structure-rooms",
overrideAccess: true,
depth: 0,
limit: 1,
where: {
AND: [
{ roomKey: { equals: roomKey } },
{ structure: { equals: relId(structureId)! } },
],
},
select: {
id: true,
level: true,
junkLevel: true,
condition: true,
pendingJob: true,
fixtures: true,
},
})
.then((res) => res.docs?.[0] ?? null)
.catch(() => null);
const room = roomDoc;
if (!room) return { ok: false, error: "no_room" };
// Normalize the runtime room for the pure engine gates: coerce the nullable
// Payload fields and pin the fixture shape to RoomFixtureState.
const engineRoom: RuntimeRoom = {
level: room.level ?? 0,
junkLevel: room.junkLevel ?? 0,
condition: room.condition ?? 0,
pendingJob: (room.pendingJob ?? null) as number | null,
fixtures: (room.fixtures ?? []) as RoomFixtureState[],
};
const blueprint = blueprintRoom(structure, roomKey);
if (!blueprint) return { ok: false, error: "no_blueprint" };
// --- Gate evaluation -----------------------------------------------------
const produceOpts =
type === "produce"
? resolveProduceOpts(engineRoom, blueprint, String(target ?? ""))
: undefined;
const gate = canStartJob(engineRoom, type, {
maxLevel: blueprint.maxLevel,
stationEnabled: produceOpts?.stationEnabled,
stationUnlocked: produceOpts?.stationUnlocked,
recipeUnlocked: produceOpts?.recipeUnlocked,
recipeEnabled: produceOpts?.recipeEnabled,
recipeRequiredRoomLevel: produceOpts?.recipeRequiredRoomLevel,
recipeBlockingFixture: produceOpts?.recipeBlockingFixture ?? false,
});
if (!gate.ok) {
return { ok: false, error: gate.reason as JobStartError };
}
// --- Compute committed resources + output --------------------------------
const commitment = computeCommitment(engineRoom, blueprint, type, target);
if (!commitment) {
return { ok: false, error: "insufficient_resources" };
}
const { committedResources, output } = commitment;
// --- Availability precheck (grid + void) before committing ---------------
// Full requirement precheck across grid and void: every committed input must
// already be present before the job can consume it at start.
for (const commit of committedResources) {
const resourceId = relId(commit.resource);
if (resourceId == null) continue;
const available = await storageBridge.storedAmount(payload, structure.id, resourceId);
if (available < commit.amount) {
return { ok: false, error: "insufficient_resources" };
}
}
// --- Persist job + block the output slot ---------------------------------
const now = new Date();
const endsAt = new Date(now.getTime() + commitmentDurationMs(engineRoom, blueprint, type, target));
const job = await payload.create({
collection: "interior-jobs",
overrideAccess: true,
depth: 0,
data: {
structure: relId(structure.id)!,
room: relId(room.id)!,
type,
status: "active",
stationRecipeKey: type === "produce" ? String(target ?? "") : undefined,
fixtureKey: type === "repair" ? String(target ?? "") : undefined,
targetLevel: type === "upgrade" ? Number(target ?? undefined) : undefined,
startedBy: relId(user!.id) ?? undefined,
startedAt: now.toISOString(),
endsAt: endsAt.toISOString(),
laborClass: laborClass ?? undefined,
headcount: headcount ?? undefined,
committedResources: committedResources.map((c) => ({
resource: relId(c.resource)!,
amount: c.amount,
})),
output: output
? {
resources: output.resources?.map((r) => ({
resource: relId(r.resource)!,
amount: r.amount,
})),
assets: output.assets?.map((a) => ({ asset: relId(a.asset)!, amount: a.amount })),
}
: undefined,
},
});
// Consume the committed inputs now that the job row exists. The availability
// precheck above guarantees these succeed; on the impossible failure we park
// the job as `failed` so nothing is consumed without a job to own it.
for (const commit of committedResources) {
const resourceId = relId(commit.resource);
if (resourceId == null) continue;
const result = await storageBridge.withdrawFromStructure(payload, structure.id, resourceId, commit.amount);
if (!result.ok) {
await payload.update({
collection: "interior-jobs",
id: relId(job.id)!,
overrideAccess: true,
data: { status: "failed" },
});
return { ok: false, error: "insufficient_resources" };
}
}
await payload.update({
collection: "structure-rooms",
id: relId(room.id)!,
overrideAccess: true,
data: busyFragment(job.id),
});
await emitGameEvent(payload, {
type: EventTypes.InteriorJobStarted,
message: `${type} job started on "${roomKey}"`,
structure: structure.id,
targetCollection: "game-structures",
targetId: structure.id,
data: { roomKey, jobType: type, jobId: job.id },
});
return { ok: true, job };
}
/** Cancel an active job and refund its committed resources. */
export async function cancelInteriorJob(
payload: PayloadType,
user: { id: number | string } | null,
jobId: number | string,
): Promise<{ ok: boolean; error?: string }> {
const job = await payload.findByID({
collection: "interior-jobs",
id: relId(jobId)!,
overrideAccess: true,
depth: 1,
});
if (job.status !== "active") return { ok: false, error: "not_active" };
// Move the committed inputs into the job output so collecting the cancelled
// job refunds them to the structure store. Keeping the refund on the same
// output path as production output means a cancel can never lose the inputs:
// they are simply credited back when the job is collected.
await payload.update({
collection: "interior-jobs",
id: relId(job.id)!,
overrideAccess: true,
data: {
status: "cancelled",
output: {
resources: (job.committedResources ?? []).map((c) => ({
resource: relId(c.resource)!,
amount: c.amount,
})),
},
},
});
await clearRoomSlot(payload, relId(job.room)!);
await emitGameEvent(payload, {
type: EventTypes.InteriorJobCancelled,
message: `${job.type} job cancelled on room`,
structure: relId(job.structure)!,
targetCollection: "game-structures",
targetId: relId(job.structure)!,
data: { jobId: job.id },
});
return { ok: true };
}
/** Collect a finished job's output and free the room's output slot. */
export async function collectInteriorJob(
payload: PayloadType,
user: { id: number | string } | null,
jobId: number | string,
): Promise<{ ok: boolean; error?: string }> {
const job = await payload.findByID({
collection: "interior-jobs",
id: relId(jobId)!,
overrideAccess: true,
depth: 1,
});
if (job.status !== "awaiting_collect") return { ok: false, error: "not_ready" };
// Credit resources to the structure store and assets to the member locker.
const output = job.output as
| { resources?: Array<{ resource: unknown; amount: number }>; assets?: Array<{ asset: unknown; amount: number }> }
| undefined;
if (output?.resources) {
// Precheck that the whole output fits before mutating anything, so a full
// store keeps the job parked (awaiting_collect) instead of half-depositing.
for (const res of output.resources) {
const resourceId = relId(res.resource);
if (resourceId == null) continue;
const pre = await storageBridge.precheckDeposit(payload, relId(job.structure)!, resourceId, res.amount);
if (!pre.ok) {
return { ok: false, error: "storage_full" };
}
}
for (const res of output.resources) {
const resourceId = relId(res.resource);
if (resourceId == null) continue;
const result = await storageBridge.depositToStructure(payload, relId(job.structure)!, resourceId, res.amount);
if (!result.ok) {
// Keep the job parked so the caller can free space and retry.
return { ok: false, error: "storage_full" };
}
}
}
await payload.update({
collection: "interior-jobs",
id: relId(job.id)!,
overrideAccess: true,
data: {
status: "collected",
collectedAt: new Date().toISOString(),
collectedBy: relId(user!.id) ?? undefined,
},
});
await clearRoomSlot(payload, relId(job.room)!);
if (user) {
await notifyUser(payload, {
userId: relId(user.id)!,
type: "interior:job-ready",
title: `${job.type} job complete`,
message: `Your ${job.type} job on the interior produced output.`,
});
}
return { ok: true };
}
/**
* Complete an active job whose duration has elapsed: flip it to
* `awaiting_collect` so the owner can credit the output, and notify the starter.
*
* The sweep calls this for every active job whose `endsAt` has passed. It only
* transitions the status (the actual output deposit stays with
* `collectInteriorJob`, which prechecks storage space); the room's output slot
* stays blocked until the output is collected.
*/
export async function completeInteriorJob(
payload: PayloadType,
jobId: number | string,
): Promise<{ ok: boolean; error?: string }> {
const job = await payload.findByID({
collection: "interior-jobs",
id: relId(jobId)!,
overrideAccess: true,
depth: 1,
});
if (job.status !== "active") return { ok: false, error: "not_active" };
await payload.update({
collection: "interior-jobs",
id: relId(job.id)!,
overrideAccess: true,
data: { status: "awaiting_collect" },
});
const startedById = relId(job.startedBy);
if (startedById) {
await notifyUser(payload, {
userId: startedById,
type: "interior:job-ready",
title: `${job.type} job complete`,
message: `Your ${job.type} job on the interior is ready to collect.`,
});
}
return { ok: true };
}
async function clearRoomSlot(
payload: PayloadType,
roomId: number,
): Promise<void> {
await payload.update({
collection: "structure-rooms",
id: roomId,
overrideAccess: true,
data: { pendingJob: null },
});
}
// --- helpers ---------------------------------------------------------------
function resolveProduceOpts(
room: { level: number; fixtures?: RoomFixtureState[] },
blueprint: InteriorBlueprintRoom,
recipeKey: string,
):
| {
stationEnabled: boolean;
stationUnlocked: boolean;
recipeUnlocked: boolean;
recipeEnabled: boolean;
recipeRequiredRoomLevel: number;
recipeBlockingFixture: boolean;
}
| undefined {
const station = blueprint.station;
if (!station || !station.enabled) {
return {
stationEnabled: false,
stationUnlocked: false,
recipeUnlocked: false,
recipeEnabled: false,
recipeRequiredRoomLevel: 1,
recipeBlockingFixture: false,
};
}
const recipe = station.recipes?.find((r) => r.key === recipeKey);
if (!recipe) {
return {
stationEnabled: true,
stationUnlocked: false,
recipeUnlocked: false,
recipeEnabled: false,
recipeRequiredRoomLevel: 1,
recipeBlockingFixture: false,
};
}
return {
stationEnabled: true,
stationUnlocked: true,
recipeUnlocked: true,
recipeEnabled: recipe.enabled !== false,
recipeRequiredRoomLevel: recipe.requiredRoomLevel ?? 1,
recipeBlockingFixture: isBlockingFixtureBroken(room.fixtures),
};
}
function isBlockingFixtureBroken(fixtures?: RoomFixtureState[]): boolean {
if (!fixtures) return false;
return fixtures.some((f) => f.broken && f.blocksStation);
}
/**
* Compute the committed resources (consumed at start) and the output (credited
* at collect) for a job. Returns null when the job has no resource commitment
* (e.g. cleanup) or when inputs cannot be satisfied.
*/
function computeCommitment(
room: { level: number },
blueprint: InteriorBlueprintRoom,
type: InteriorJob["type"],
target: string | number | undefined,
): {
committedResources: Array<{ resource: unknown; amount: number }>;
output?: {
resources: Array<{ resource: unknown; amount: number }>;
assets: Array<{ asset: unknown; amount: number }>;
};
} {
switch (type) {
case "upgrade": {
const level = blueprint.levels?.find((l) => l.level === Number(target ?? 0));
const materials = level?.upgradeMaterials ?? [];
return {
committedResources: materials.map((m) => ({
resource: m.resource,
amount: m.amount,
})),
};
}
case "repair": {
const fixture = blueprint.fixtures?.find((f) => f.key === String(target ?? ""));
const materials = fixture?.repairMaterials ?? [];
return {
committedResources: materials.map((m) => ({
resource: m.resource,
amount: m.amount,
})),
};
}
case "produce": {
const recipe = blueprint.station?.recipes?.find((r) => r.key === String(target ?? ""));
if (!recipe) return { committedResources: [] };
return {
committedResources: (recipe.inputs ?? []).map((i) => ({
resource: i.resource,
amount: i.amount,
})),
output: {
resources: (recipe.outputs ?? [])
.filter((o) => o.kind === "resource")
.map((o) => ({ resource: o.item, amount: o.amount })),
assets: (recipe.outputs ?? [])
.filter((o) => o.kind === "asset")
.map((o) => ({ asset: o.item, amount: o.amount })),
},
};
}
default:
return { committedResources: [] };
}
}
function commitmentDurationMs(
room: { level: number },
blueprint: InteriorBlueprintRoom,
type: InteriorJob["type"],
target: string | number | undefined,
): number {
if (type === "upgrade") {
const level = blueprint.levels?.find((l) => l.level === Number(target ?? 0));
return (level?.upgradeDurationMinutes ?? 0) * 60_000;
}
if (type === "repair") {
const fixture = blueprint.fixtures?.find((f) => f.key === String(target ?? ""));
return (fixture?.repairDurationMinutes ?? 0) * 60_000;
}
if (type === "produce") {
const recipe = blueprint.station?.recipes?.find((r) => r.key === String(target ?? ""));
return (recipe?.durationMinutes ?? 0) * 60_000;
}
return 0;
}

View file

@ -0,0 +1,98 @@
import type { Payload } from "payload";
import type { GameStructure, StructureRoom } from "@/payload-types";
import type { InteriorBlueprintRoom } from "./types";
import { relId } from "@/lib/interior/relations";
/**
* Idempotent provisioning of runtime room rows from the structure blueprint.
*
* Runs once per game-structure (tracked by `game-structures.interior.provisionedAt`).
* For each blueprint room we upsert a `structure-rooms` row keyed by
* (structure, roomKey), seeding level/condition/junk/fixtures from the blueprint
* defaults. Blueprint edits after provisioning never retarget live rooms: the
* snapshot of the floorplan + access config is stored on the game-structure at
* provision time, and runtime state lives only in structure-rooms.
*/
export async function provisionInterior(
payload: Payload,
structure: Pick<GameStructure, "id" | "interior">,
): Promise<{ provisioned: boolean; rooms: number }> {
const snapshot = structure.interior;
if (!snapshot?.provisionedAt || !Array.isArray(snapshot.rooms)) {
return { provisioned: false, rooms: 0 };
}
const blueprintRooms = snapshot.rooms as unknown as InteriorBlueprintRoom[];
if (blueprintRooms.length === 0) {
return { provisioned: false, rooms: 0 };
}
const existing = await payload.find({
collection: "structure-rooms",
overrideAccess: true,
depth: 0,
limit: blueprintRooms.length,
where: {
structure: { equals: relId(structure.id) },
},
});
const created = await Promise.all(
blueprintRooms.map((room) => provisionRoomRow(payload, structure.id, room, existing.docs)),
);
const count = created.filter(Boolean).length;
if (count > 0) {
await payload.update({
collection: "game-structures",
id: relId(structure.id)!,
overrideAccess: true,
data: {
interior: {
...(structure.interior as Record<string, unknown>),
provisionedAt: new Date().toISOString(),
},
},
});
}
return { provisioned: count > 0, rooms: count };
}
async function provisionRoomRow(
payload: Payload,
structureId: number | string,
room: InteriorBlueprintRoom,
existing: StructureRoom[],
): Promise<boolean> {
const roomKey = room.key;
if (!roomKey) return false;
const existingRow = (existing as unknown as Array<Record<string, unknown>>).find(
(doc) => doc.roomKey === roomKey,
);
if (existingRow) return false;
await payload.create({
collection: "structure-rooms",
overrideAccess: true,
data: {
structure: relId(structureId)!,
roomKey,
name: room.name ?? roomKey,
level: room.initialLevel ?? 0,
condition: 100,
junkLevel: room.decay?.initialJunkLevel ?? 0,
fixtures: (room.fixtures ?? []).map((f) => ({
key: f.key,
name: f.name ?? f.key,
broken: f.brokenByDefault ?? false,
condition: f.brokenByDefault ? (f.condition ?? 0) : (f.condition ?? 100),
blocksStation: f.blocksStation,
})),
},
});
return true;
}

View file

@ -0,0 +1,13 @@
/**
* Shared relationship-id normalizer for the interior engine. Mirrors the local
* `relId` helpers scattered across the repo (GameStructures, garage, lockers,
* etc.) so the interior engine has a single, tested source.
*/
export function relId(value: unknown): number | null {
if (typeof value === "number") return value;
if (value !== null && typeof value === "object" && "id" in (value as { id: unknown })) {
const id = (value as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}

View file

@ -0,0 +1,415 @@
import type { Payload } from "payload";
import type { GameStructure, Structure } from "@/payload-types";
import { checkStorageDeposit, storageViolationMessage } from "@/lib/storageRules";
import { effectiveMaxMass } from "@/lib/base/modules";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
export type StorageDryRun =
| { allowed: true; message?: string }
| { allowed: false; message: string; code?: "prohibited" | "not_whitelisted" | "over_cap" | "mass" };
/**
* Interior <-> structure storage bridge.
*
* Extracts the grid-placement + mass-check core that previously lived inside
* `addResourceInternal` (logistics/structures/actions.ts) so the interior engine
* can deposit/withdraw against a structure's item storage using the exact same
* placement rules. Interior jobs and production credit/charge here.
*/
type StoredResource = {
resource: { id: number } | number;
amount: number;
gridX?: number;
gridY?: number;
rotated?: boolean;
};
/** Total currently stored amount of one resource across grid + void. */
export async function storedAmount(
payload: Payload,
structureId: number | string,
resourceId: number,
): Promise<number> {
const structure = await payload.findByID({
collection: "game-structures",
id: structureId as number,
overrideAccess: true,
depth: 0,
select: { storedResources: true, voidStorage: true },
}).catch(() => null);
if (!structure) return 0;
const rows = [...(structure.storedResources ?? []), ...(structure.voidStorage ?? [])] as StoredResource[];
return rows
.filter((r) => resourceIdOf(r.resource) === resourceId)
.reduce((sum, r) => sum + (r.amount ?? 0), 0);
}
function resourceIdOf(ref: unknown): number | null {
if (ref == null) return null;
if (typeof ref === "number") return ref;
if (typeof ref === "object" && "id" in (ref as { id: unknown })) {
const id = (ref as { id: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
}
/**
* Dry-run check for a deposit of `amount` of `resourceId` into `structure`.
* Returns a human-readable rejection reason when the deposit would violate
* prohibited/whitelist/cap/mass rules.
*/
export function dryRunDeposit(
structure: Pick<Structure, "allowedStorage" | "prohibitedStorage" | "restrictToAllowed">,
resourceId: number,
amount: number,
currentStored: number,
): StorageDryRun {
const check = checkStorageDeposit(
{
allowedStorage: structure.allowedStorage,
prohibitedStorage: structure.prohibitedStorage,
restrictToAllowed: structure.restrictToAllowed,
},
resourceId,
amount,
currentStored,
);
if (check.allowed) return { allowed: true };
return {
allowed: false,
code: check.violation,
message: storageViolationMessage("resource", check),
};
}
/**
* Apply `amount` (positive = place, negative = withdraw) of `resourceId` to the
* structure's stored-resources grid. Fills existing stacks first, then either
* scans the grid for a non-overlapping spot (when the structure has a grid
* footprint) or appends a flat-list entry. Returns the updated array.
*/
export function applyStoragePlacement(
storedResources: StoredResource[] | undefined,
resourceId: number,
amount: number,
maxStack: number,
): StoredResource[] {
const rows = (storedResources ?? []).map((r) => ({ ...r })) as StoredResource[];
let remaining = amount;
let nextId = rows.reduce((max, r) => {
const id = typeof r.resource === "object" ? r.resource.id : Number(r.resource);
return id > max ? id : max;
}, 0);
// Fill existing same-resource stacks first.
for (const row of rows) {
if (remaining <= 0) break;
if (resourceIdOf(row.resource) !== resourceId) continue;
const space = maxStack - (row.amount ?? 0);
if (space <= 0) continue;
const add = Math.min(space, remaining);
row.amount += add;
remaining -= add;
}
// Negative remainder: withdraw from existing stacks (FIFO-ish).
if (remaining < 0) {
let toRemove = 0;
for (const row of rows) {
if (remaining >= 0) break;
if (resourceIdOf(row.resource) !== resourceId) continue;
if (row.amount <= -remaining) {
toRemove++;
remaining += row.amount;
row.amount = 0;
} else {
row.amount += remaining;
remaining = 0;
}
}
return rows.filter((r) => r.amount > 0 && rows.indexOf(r) >= toRemove || (r.amount > 0 && rows.filter((rr) => rr === r && rows.indexOf(rr) >= toRemove).length > 1));
}
if (remaining <= 0) return rows;
// Positive remainder: place new entries.
while (remaining > 0) {
const chunk = Math.min(maxStack, remaining);
nextId += 1;
rows.push({ resource: resourceId, amount: chunk, gridX: 0, gridY: 0 });
remaining -= chunk;
}
return rows;
}
/**
* Mass check helper: would adding `amount` of `resourceId` (at `resourceMass`
* each) exceed the structure's effective capacity mass (blueprint capacity
* plus installed `capacity_mass` modules)? A null capacity means uncapped.
*/
export function withinMassLimit(
instance: Pick<GameStructure, "installedModules">,
blueprint: Pick<Structure, "maxCapacityMass"> | undefined,
amount: number,
currentMass: number,
resourceMass: number,
): boolean {
const capacity = effectiveMaxMass(
(blueprint ?? { maxCapacityMass: null }) as Structure,
instance.installedModules,
);
if (capacity === null) return true;
return currentMass + amount * resourceMass <= capacity;
}
// --- deposit / withdraw ----------------------------------------------------
/** Sum stored amount of one resource across the given grid + void rows. */
function storedAmountAt(
rows: readonly { resource: unknown; amount?: number | null }[] | null | undefined,
resourceId: number,
): number {
return (rows ?? []).reduce(
(sum, r) => (resourceIdOf(r.resource) === resourceId ? sum + (r.amount ?? 0) : sum),
0,
);
}
/** Total stored mass (kg) across grid + void rows. */
function storedMass(
rows: readonly { resource: unknown; amount?: number | null }[] | null | undefined,
): number {
return (rows ?? []).reduce((sum, r) => {
const res = r.resource;
if (res == null || typeof res === "number") return sum;
return sum + ((res as { massPerUnit?: number }).massPerUnit ?? 0) * (r.amount ?? 0);
}, 0);
}
type LoadedStructure = {
structure: Pick<GameStructure, "id" | "storedResources" | "voidStorage" | "installedModules">;
blueprint: Pick<Structure, "allowedStorage" | "prohibitedStorage" | "restrictToAllowed" | "maxCapacityMass"> | undefined;
};
/**
* Load the runtime storage (game-structures) plus the blueprint (structures)
* that carries the storage rules + capacity cap. Mirrors `addResourceInternal`,
* which reads rules/capacity from `structure.type` and storage from the instance.
*/
async function loadInteriorStructure(
payload: Payload,
structureId: number | string,
): Promise<LoadedStructure | null> {
const structure = await payload.findByID({
collection: "game-structures",
id: structureId as number,
overrideAccess: true,
depth: 0,
select: {
id: true,
storedResources: true,
voidStorage: true,
installedModules: true,
type: true,
},
}).catch(() => null);
if (!structure) return null;
const typeRef = (structure as unknown as { type?: number | { id: number } }).type;
const type = typeof typeRef === "number" ? typeRef : typeRef?.id;
const blueprint = type
? await payload
.findByID({
collection: "structures",
id: type,
depth: 0,
overrideAccess: true,
select: {
allowedStorage: true,
prohibitedStorage: true,
restrictToAllowed: true,
maxCapacityMass: true,
},
})
.catch(() => null)
: null;
return { structure, blueprint: blueprint ?? undefined };
}
/**
* Pure evaluation of whether `amount` of `resourceId` may be deposited: storage
* rules (prohibited / whitelist / per-item cap, from the blueprint) and mass
* capacity. Does not read or write storage.
*/
function evaluateDeposit(
loaded: LoadedStructure,
resourceId: number,
amount: number,
resourceMass: number,
): { ok: boolean; error?: string } {
const { structure, blueprint } = loaded;
if (blueprint) {
const currentStored =
storedAmountAt(structure.storedResources, resourceId) +
storedAmountAt(structure.voidStorage, resourceId);
const dry = dryRunDeposit(blueprint, resourceId, amount, currentStored);
if (!dry.allowed) return { ok: false, error: dry.message };
}
const currentMass = storedMass(structure.storedResources) + storedMass(structure.voidStorage);
if (!withinMassLimit(structure, blueprint, amount, currentMass, resourceMass)) {
return { ok: false, error: "exceeds_capacity" };
}
return { ok: true };
}
/**
* Precheck only (no mutation): would depositing `amount` of `resourceId` into
* the structure violate storage rules or mass capacity? Used by the collector
* to refuse a job when its output cannot fit, keeping the job parked.
*/
export async function precheckDeposit(
payload: Payload,
structureId: number | string,
resourceId: number,
amount: number,
): Promise<{ ok: boolean; error?: string }> {
if (amount <= 0) return { ok: false, error: "amount_must_be_positive" };
const loaded = await loadInteriorStructure(payload, structureId);
if (!loaded) return { ok: false, error: "structure_not_found" };
const resource = await payload
.findByID({ collection: "resources", id: resourceId, depth: 0, overrideAccess: true })
.catch(() => null);
if (!resource) return { ok: false, error: "resource_not_found" };
return evaluateDeposit(loaded, resourceId, amount, (resource as { massPerUnit?: number }).massPerUnit ?? 0);
}
/**
* Deposit `amount` of `resourceId` into the structure's item storage, reusing
* the same placement + rules + mass core as `addResourceInternal`. Refuses
* (without mutating) when storage rules or mass capacity would be violated.
*/
export async function depositToStructure(
payload: Payload,
structureId: number | string,
resourceId: number,
amount: number,
): Promise<{ ok: boolean; error?: string }> {
if (amount <= 0) return { ok: false, error: "amount_must_be_positive" };
const loaded = await loadInteriorStructure(payload, structureId);
if (!loaded) return { ok: false, error: "structure_not_found" };
const resource = await payload
.findByID({ collection: "resources", id: resourceId, depth: 0, overrideAccess: true })
.catch(() => null);
if (!resource) return { ok: false, error: "resource_not_found" };
const evaluated = evaluateDeposit(loaded, resourceId, amount, (resource as { massPerUnit?: number }).massPerUnit ?? 0);
if (!evaluated.ok) return evaluated;
const maxStack =
(resource as { stackable?: boolean }).stackable === false
? 1
: ((resource as { maxStackSize?: number }).maxStackSize ?? Infinity);
const newStored = applyStoragePlacement(
loaded.structure.storedResources as StoredResource[] | undefined,
resourceId,
amount,
maxStack,
);
await payload.update({
collection: "game-structures",
id: structureId as number,
overrideAccess: true,
data: { storedResources: newStored },
});
await emitGameEvent(payload, {
type: EventTypes.StorageDeposit,
message: `Deposited ${amount}× resource ${resourceId} into structure`,
structure: structureId as number,
targetCollection: "game-structures",
targetId: structureId as number,
data: { resourceId, amount },
}).catch(() => undefined);
return { ok: true };
}
/**
* Withdraw `amount` of `resourceId` from the structure, pulling from void first
* then the grid (mirroring `removeResourceInternal`). Refuses when there is not
* enough across grid + void.
*/
export async function withdrawFromStructure(
payload: Payload,
structureId: number | string,
resourceId: number,
amount: number,
): Promise<{ ok: boolean; error?: string }> {
if (amount <= 0) return { ok: false, error: "amount_must_be_positive" };
const structure = await payload.findByID({
collection: "game-structures",
id: structureId as number,
overrideAccess: true,
depth: 0,
select: { storedResources: true, voidStorage: true },
}).catch(() => null);
if (!structure) return { ok: false, error: "structure_not_found" };
const grid = [...(structure.storedResources ?? [])] as StoredResource[];
const voidStorage = [...(structure.voidStorage ?? [])] as StoredResource[];
const voidRes = withdrawFromEntries(voidStorage, resourceId, amount);
let remaining = voidRes.remaining;
let gridRes: StoredResource[] = grid;
if (remaining > 0) {
const g = withdrawFromEntries(grid, resourceId, remaining);
gridRes = g.entries;
remaining = g.remaining;
}
if (remaining > 0) return { ok: false, error: "insufficient_resources" };
await payload.update({
collection: "game-structures",
id: structureId as number,
overrideAccess: true,
data: { storedResources: gridRes, voidStorage: voidRes.entries },
});
return { ok: true };
}
/**
* Withdraw `amount` of `resourceId` from a single stored-resources array,
* consuming entries in order and dropping emptied ones. Returns the updated
* array and any remainder that could not be satisfied.
*/
function withdrawFromEntries(
entries: StoredResource[],
resourceId: number,
amount: number,
): { entries: StoredResource[]; remaining: number } {
let remaining = amount;
const updated = entries
.map((entry) => {
if (remaining <= 0 || resourceIdOf(entry.resource) !== resourceId) return entry;
const consumed = Math.min(entry.amount ?? 0, remaining);
remaining -= consumed;
return { ...entry, amount: (entry.amount ?? 0) - consumed };
})
.filter((entry) => (entry.amount ?? 0) > 0);
return { entries: updated, remaining };
}

44
src/lib/interior/sweep.ts Normal file
View file

@ -0,0 +1,44 @@
import type { PayloadType } from "./jobs";
import { completeInteriorJob } from "./jobs";
/**
* Interior job sweep — completes active jobs whose duration has elapsed.
*
* Run from the `interior-tick` bin (every minute). For every active job whose
* `endsAt` has passed, the sweep flips it to `awaiting_collect` (via
* `completeInteriorJob`) so the owner can credit the output and the room's
* output slot frees. Idempotent: only `active` jobs are touched, and each
* completion re-reads the job before transitioning so a concurrent cancel can
* never overwrite a live state.
*/
export async function sweepInteriorJobs(
payload: PayloadType,
now: Date = new Date(),
): Promise<{ completed: number; errors: number }> {
const due = await payload.find({
collection: "interior-jobs",
overrideAccess: true,
depth: 0,
limit: 100,
where: {
AND: [
{ status: { equals: "active" } },
{ endsAt: { less_than_equal: now.toISOString() } },
],
},
});
let completed = 0;
let errors = 0;
for (const job of due.docs) {
const result = await completeInteriorJob(payload, job.id);
if (result.ok) {
completed += 1;
} else {
errors += 1;
}
}
return { completed, errors };
}

175
src/lib/interior/types.ts Normal file
View file

@ -0,0 +1,175 @@
import type { Asset, Resource, Technology } from "@/payload-types";
/**
* Shared type definitions for the Superstructure Interior System.
*
* These mirror the `interior` blueprint group on the `structures` collection
* (authoring) and the `interior` runtime snapshot on `game-structures`. The
* blueprint room shape is the single source of truth for room lifecycle; the
* runtime state lives on `structure-rooms`. Keeping these here (rather than
* re-deriving from Payload's generated types) keeps the pure engine logic free
* of Payload import cycles.
*/
/** Interior access mode, mirroring Item Storage Access. */
export type InteriorAccessMode = "anyone" | "roles" | "users";
/** The five job types a room can run. */
export type JobType = "open" | "cleanup" | "upgrade" | "repair" | "produce";
/**
* Room effect types. Numeric effects carry a `value`; unlock effects carry a
* `target` (recipe key or station marker).
*/
export type RoomEffectType =
| "production_speed"
| "output_bonus"
| "storage_capacity"
| "labor_capacity"
| "unlocks_recipe"
| "unlocks_station";
export type LevelEffect = {
type: RoomEffectType;
value?: number;
target?: string;
};
export type UpgradeMaterial = {
resource: Resource | { id: number } | null;
amount: number;
};
export type LevelDefinition = {
level: number;
label?: string;
upgradeMaterials?: UpgradeMaterial[];
upgradeDurationMinutes: number;
requiredTech?: (Technology | { id: number })[];
requiredLaborClass?: string | null;
requiredHeadcount?: number | null;
effects?: LevelEffect[];
};
export type RecipeOutput = {
kind: "resource" | "asset";
item: Resource | Asset | { id: number } | null;
amount: number;
};
export type RecipeInput = {
resource: Resource | { id: number } | null;
amount: number;
};
export type RecipeBlueprint = {
key: string;
name: string;
enabled?: boolean;
durationMinutes: number;
requiredLaborClass?: string | null;
requiredHeadcount?: number | null;
requiredRoomLevel?: number;
inputs?: RecipeInput[];
outputs?: RecipeOutput[];
};
export type StationBlueprint = {
name?: string;
enabled?: boolean;
recipes?: RecipeBlueprint[];
};
export type FixtureBlueprint = {
key: string;
name: string;
condition?: number | null;
brokenByDefault?: boolean;
repairMaterials?: UpgradeMaterial[];
repairDurationMinutes?: number | null;
blocksStation?: boolean;
};
export type DecayBlueprint = {
conditionPerDay?: number;
effectFloor?: number;
junkMax?: number;
initialJunkLevel?: number;
};
export type JunkLootEntry = {
kind: "resource" | "asset";
item: Resource | Asset | { id: number } | null;
amountMin: number;
amountMax: number;
weight: number;
};
export type HotspotBlueprint = {
x: number;
y: number;
width: number;
height: number;
graphX?: number;
graphY?: number;
};
/** One authored room row on the `structures.interior.rooms` array. */
export type InteriorBlueprintRoom = {
key: string;
name: string;
description?: string;
roomType?: string;
hotspot?: HotspotBlueprint;
initialLevel?: number;
maxLevel: number;
levels?: LevelDefinition[];
station?: StationBlueprint;
fixtures?: FixtureBlueprint[];
decay?: DecayBlueprint;
junkLoot?: JunkLootEntry[];
};
/** The `interiorAccess` group (blueprint + runtime snapshot). */
export type InteriorAccessGroup = {
mode?: InteriorAccessMode;
roles?: (Technology | { id: number })[] | null;
users?: (Resource | { id: number })[] | null;
};
/** The full `structures.interior` blueprint group. */
export type InteriorBlueprint = {
interiorEnabled?: boolean;
interiorName?: string;
floorplan?: unknown;
floorplanAlt?: string;
interiorAccess?: InteriorAccessGroup;
rooms?: InteriorBlueprintRoom[];
};
/**
* Runtime room state shape as stored on `structure-rooms.fixtures` and used by
* the engine. Mirrors the runtime fixtures array (key/name/broken/condition).
*/
export type RoomFixtureState = {
key: string;
name: string;
broken: boolean;
condition: number;
/** Whether this fixture blocks the room's station when broken (seeded from blueprint at provisioning). */
blocksStation?: boolean;
brokenAt?: string | null;
};
/**
* Normalized runtime room shape consumed by the pure engine (gates, commit,
* duration). Coerced from `StructureRoom` at the Payload boundary so the engine
* never has to null-check Payload-generated fields.
*/
export type RuntimeRoom = {
level: number;
junkLevel: number;
condition: number;
pendingJob?: number | null;
fixtures?: RoomFixtureState[];
};

View file

@ -222,6 +222,8 @@ export function notificationLabel(type?: string | null): string {
return "Research ballot open";
case "tech:research-complete":
return "Research completed";
case "interior:job-ready":
return "Interior job ready";
default:
return type ?? "Notification";
}

View file

@ -27,6 +27,7 @@ export const MUTEABLE_NOTIFICATION_TYPES = [
{ label: "Minigame achievements", value: "minigame:achievement" },
{ label: "Tech ballots", value: "tech:ballot-open" },
{ label: "Research completed", value: "tech:research-complete" },
{ label: "Interior job ready", value: "interior:job-ready" },
] as const;
export type MuteableNotificationType = (typeof MUTEABLE_NOTIFICATION_TYPES)[number]["value"];
export const MUTEABLE_NOTIFICATION_VALUES = MUTEABLE_NOTIFICATION_TYPES.map((t) => t.value);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,408 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_game_structures_interior_interior_access_mode" AS ENUM('anyone', 'roles', 'users');
CREATE TYPE "public"."enum_interior_jobs_type" AS ENUM('open', 'cleanup', 'upgrade', 'repair', 'produce');
CREATE TYPE "public"."enum_interior_jobs_status" AS ENUM('active', 'awaiting_collect', 'cancelled', 'collected', 'failed');
CREATE TYPE "public"."enum_structures_rooms_levels_effects_type" AS ENUM('production_speed', 'output_bonus', 'storage_capacity', 'labor_capacity', 'unlocks_recipe', 'unlocks_station');
CREATE TYPE "public"."enum_structures_rooms_station_recipes_outputs_kind" AS ENUM('resource', 'asset');
CREATE TYPE "public"."enum_structures_rooms_junk_loot_kind" AS ENUM('resource', 'asset');
CREATE TYPE "public"."enum_structures_interior_access_mode" AS ENUM('anyone', 'roles', 'users');
ALTER TYPE "public"."enum_users_preferences_notifications_muted_types" ADD VALUE 'interior:job-ready';
ALTER TYPE "public"."enum_users_preferences_discord_muted_types" ADD VALUE 'interior:job-ready';
CREATE TABLE "structure_rooms_fixtures" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"key" varchar NOT NULL,
"name" varchar NOT NULL,
"broken" boolean DEFAULT false,
"condition" numeric DEFAULT 100,
"broken_at" timestamp(3) with time zone
);
CREATE TABLE "structure_rooms" (
"id" serial PRIMARY KEY NOT NULL,
"structure_id" integer NOT NULL,
"room_key" varchar NOT NULL,
"name" varchar NOT NULL,
"level" numeric DEFAULT 0,
"condition" numeric DEFAULT 100,
"junk_level" numeric DEFAULT 0,
"station_level" numeric DEFAULT 0,
"last_decay_at" timestamp(3) with time zone,
"pending_job_id" integer,
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
);
CREATE TABLE "interior_jobs_committed_resources" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"resource_id" integer NOT NULL,
"amount" numeric NOT NULL
);
CREATE TABLE "interior_jobs_output_resources" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"resource_id" integer NOT NULL,
"amount" numeric NOT NULL
);
CREATE TABLE "interior_jobs_output_assets" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"asset_id" integer NOT NULL,
"amount" numeric NOT NULL
);
CREATE TABLE "interior_jobs" (
"id" serial PRIMARY KEY NOT NULL,
"structure_id" integer NOT NULL,
"room_id" integer NOT NULL,
"type" "enum_interior_jobs_type" NOT NULL,
"status" "enum_interior_jobs_status" DEFAULT 'active' NOT NULL,
"station_recipe_key" varchar,
"fixture_key" varchar,
"target_level" numeric,
"started_by_id" integer,
"started_at" timestamp(3) with time zone,
"ends_at" timestamp(3) with time zone,
"labor_class" varchar,
"headcount" numeric,
"result_note" varchar,
"collected_at" timestamp(3) with time zone,
"collected_by_id" integer,
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
);
CREATE TABLE "structures_rooms_levels_upgrade_materials" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"resource_id" integer NOT NULL,
"amount" numeric NOT NULL
);
CREATE TABLE "structures_rooms_levels_effects" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"type" "enum_structures_rooms_levels_effects_type" NOT NULL,
"value" numeric NOT NULL
);
CREATE TABLE "structures_rooms_levels" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"level" numeric NOT NULL,
"label" varchar,
"upgrade_duration_minutes" numeric NOT NULL,
"required_labor_class" varchar,
"required_headcount" numeric
);
CREATE TABLE "structures_rooms_station_recipes_inputs" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"resource_id" integer NOT NULL,
"amount" numeric NOT NULL
);
CREATE TABLE "structures_rooms_station_recipes_outputs" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"kind" "enum_structures_rooms_station_recipes_outputs_kind" NOT NULL,
"amount" numeric NOT NULL
);
CREATE TABLE "structures_rooms_station_recipes" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"key" varchar NOT NULL,
"name" varchar NOT NULL,
"enabled" boolean DEFAULT true,
"duration_minutes" numeric NOT NULL,
"required_labor_class" varchar,
"required_headcount" numeric,
"required_room_level" numeric DEFAULT 1
);
CREATE TABLE "structures_rooms_fixtures_repair_materials" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"resource_id" integer NOT NULL,
"amount" numeric NOT NULL
);
CREATE TABLE "structures_rooms_fixtures" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"key" varchar NOT NULL,
"name" varchar NOT NULL,
"condition" numeric,
"broken_by_default" boolean DEFAULT false,
"repair_duration_minutes" numeric,
"blocks_station" boolean DEFAULT false
);
CREATE TABLE "structures_rooms_junk_loot" (
"_order" integer NOT NULL,
"_parent_id" varchar NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"kind" "enum_structures_rooms_junk_loot_kind" NOT NULL,
"amount_min" numeric NOT NULL,
"amount_max" numeric NOT NULL,
"weight" numeric DEFAULT 1 NOT NULL
);
CREATE TABLE "structures_rooms" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"key" varchar NOT NULL,
"name" varchar NOT NULL,
"description" jsonb,
"room_type" varchar,
"hotspot_x" numeric NOT NULL,
"hotspot_y" numeric NOT NULL,
"hotspot_width" numeric NOT NULL,
"hotspot_height" numeric NOT NULL,
"hotspot_graph_x" numeric,
"hotspot_graph_y" numeric,
"initial_level" numeric DEFAULT 0,
"max_level" numeric NOT NULL,
"station_name" varchar,
"station_enabled" boolean DEFAULT false,
"decay_condition_per_day" numeric DEFAULT 0,
"decay_effect_floor" numeric DEFAULT 0,
"decay_junk_max" numeric DEFAULT 0,
"decay_initial_junk_level" numeric DEFAULT 0
);
ALTER TABLE "game_structures" ALTER COLUMN "is_research_facility" DROP DEFAULT;
ALTER TABLE "game_structures" ALTER COLUMN "research_speed_modifier" DROP DEFAULT;
ALTER TABLE "game_structures" ALTER COLUMN "research_slots" DROP DEFAULT;
ALTER TABLE "game_structures" ADD COLUMN "interior_provisioned_at" timestamp(3) with time zone;
ALTER TABLE "game_structures" ADD COLUMN "interior_last_decay_at" timestamp(3) with time zone;
ALTER TABLE "game_structures" ADD COLUMN "interior_floorplan_id" integer;
ALTER TABLE "game_structures" ADD COLUMN "interior_floorplan_alt" varchar;
ALTER TABLE "game_structures" ADD COLUMN "interior_rooms" jsonb;
ALTER TABLE "game_structures" ADD COLUMN "interior_interior_access_mode" "enum_game_structures_interior_interior_access_mode" DEFAULT 'anyone';
ALTER TABLE "structures" ADD COLUMN "interior_enabled" boolean;
ALTER TABLE "structures" ADD COLUMN "interior_name" varchar;
ALTER TABLE "structures" ADD COLUMN "floorplan_id" integer;
ALTER TABLE "structures" ADD COLUMN "floorplan_alt" varchar;
ALTER TABLE "structures" ADD COLUMN "interior_access_mode" "enum_structures_interior_access_mode" DEFAULT 'anyone';
ALTER TABLE "structures_rels" ADD COLUMN "roles_id" integer;
ALTER TABLE "structures_rels" ADD COLUMN "users_id" integer;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "structure_rooms_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "structure_rooms_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "structure_rooms_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "structure_rooms_delete" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "interior_jobs_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "interior_jobs_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "interior_jobs_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "interior_jobs_delete" boolean DEFAULT false;
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "structure_rooms_id" integer;
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "interior_jobs_id" integer;
ALTER TABLE "game_rules" ADD COLUMN "interior_decay_enabled" boolean DEFAULT false;
ALTER TABLE "game_rules" ADD COLUMN "interior_decay_multiplier" numeric DEFAULT 1;
ALTER TABLE "structure_rooms_fixtures" ADD CONSTRAINT "structure_rooms_fixtures_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structure_rooms"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structure_rooms" ADD CONSTRAINT "structure_rooms_structure_id_game_structures_id_fk" FOREIGN KEY ("structure_id") REFERENCES "public"."game_structures"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "structure_rooms" ADD CONSTRAINT "structure_rooms_pending_job_id_interior_jobs_id_fk" FOREIGN KEY ("pending_job_id") REFERENCES "public"."interior_jobs"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "interior_jobs_committed_resources" ADD CONSTRAINT "interior_jobs_committed_resources_resource_id_resources_id_fk" FOREIGN KEY ("resource_id") REFERENCES "public"."resources"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "interior_jobs_committed_resources" ADD CONSTRAINT "interior_jobs_committed_resources_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."interior_jobs"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "interior_jobs_output_resources" ADD CONSTRAINT "interior_jobs_output_resources_resource_id_resources_id_fk" FOREIGN KEY ("resource_id") REFERENCES "public"."resources"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "interior_jobs_output_resources" ADD CONSTRAINT "interior_jobs_output_resources_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."interior_jobs"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "interior_jobs_output_assets" ADD CONSTRAINT "interior_jobs_output_assets_asset_id_assets_id_fk" FOREIGN KEY ("asset_id") REFERENCES "public"."assets"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "interior_jobs_output_assets" ADD CONSTRAINT "interior_jobs_output_assets_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."interior_jobs"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "interior_jobs" ADD CONSTRAINT "interior_jobs_structure_id_game_structures_id_fk" FOREIGN KEY ("structure_id") REFERENCES "public"."game_structures"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "interior_jobs" ADD CONSTRAINT "interior_jobs_room_id_structure_rooms_id_fk" FOREIGN KEY ("room_id") REFERENCES "public"."structure_rooms"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "interior_jobs" ADD CONSTRAINT "interior_jobs_started_by_id_users_id_fk" FOREIGN KEY ("started_by_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "interior_jobs" ADD CONSTRAINT "interior_jobs_collected_by_id_users_id_fk" FOREIGN KEY ("collected_by_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "structures_rooms_levels_upgrade_materials" ADD CONSTRAINT "structures_rooms_levels_upgrade_materials_resource_id_resources_id_fk" FOREIGN KEY ("resource_id") REFERENCES "public"."resources"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "structures_rooms_levels_upgrade_materials" ADD CONSTRAINT "structures_rooms_levels_upgrade_materials_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms_levels"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms_levels_effects" ADD CONSTRAINT "structures_rooms_levels_effects_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms_levels"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms_levels" ADD CONSTRAINT "structures_rooms_levels_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms_station_recipes_inputs" ADD CONSTRAINT "structures_rooms_station_recipes_inputs_resource_id_resources_id_fk" FOREIGN KEY ("resource_id") REFERENCES "public"."resources"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "structures_rooms_station_recipes_inputs" ADD CONSTRAINT "structures_rooms_station_recipes_inputs_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms_station_recipes"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms_station_recipes_outputs" ADD CONSTRAINT "structures_rooms_station_recipes_outputs_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms_station_recipes"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms_station_recipes" ADD CONSTRAINT "structures_rooms_station_recipes_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms_fixtures_repair_materials" ADD CONSTRAINT "structures_rooms_fixtures_repair_materials_resource_id_resources_id_fk" FOREIGN KEY ("resource_id") REFERENCES "public"."resources"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "structures_rooms_fixtures_repair_materials" ADD CONSTRAINT "structures_rooms_fixtures_repair_materials_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms_fixtures"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms_fixtures" ADD CONSTRAINT "structures_rooms_fixtures_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms_junk_loot" ADD CONSTRAINT "structures_rooms_junk_loot_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures_rooms"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rooms" ADD CONSTRAINT "structures_rooms_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."structures"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "structure_rooms_fixtures_order_idx" ON "structure_rooms_fixtures" USING btree ("_order");
CREATE INDEX "structure_rooms_fixtures_parent_id_idx" ON "structure_rooms_fixtures" USING btree ("_parent_id");
CREATE INDEX "structure_rooms_structure_idx" ON "structure_rooms" USING btree ("structure_id");
CREATE INDEX "structure_rooms_room_key_idx" ON "structure_rooms" USING btree ("room_key");
CREATE INDEX "structure_rooms_pending_job_idx" ON "structure_rooms" USING btree ("pending_job_id");
CREATE INDEX "structure_rooms_updated_at_idx" ON "structure_rooms" USING btree ("updated_at");
CREATE INDEX "structure_rooms_created_at_idx" ON "structure_rooms" USING btree ("created_at");
CREATE INDEX "interior_jobs_committed_resources_order_idx" ON "interior_jobs_committed_resources" USING btree ("_order");
CREATE INDEX "interior_jobs_committed_resources_parent_id_idx" ON "interior_jobs_committed_resources" USING btree ("_parent_id");
CREATE INDEX "interior_jobs_committed_resources_resource_idx" ON "interior_jobs_committed_resources" USING btree ("resource_id");
CREATE INDEX "interior_jobs_output_resources_order_idx" ON "interior_jobs_output_resources" USING btree ("_order");
CREATE INDEX "interior_jobs_output_resources_parent_id_idx" ON "interior_jobs_output_resources" USING btree ("_parent_id");
CREATE INDEX "interior_jobs_output_resources_resource_idx" ON "interior_jobs_output_resources" USING btree ("resource_id");
CREATE INDEX "interior_jobs_output_assets_order_idx" ON "interior_jobs_output_assets" USING btree ("_order");
CREATE INDEX "interior_jobs_output_assets_parent_id_idx" ON "interior_jobs_output_assets" USING btree ("_parent_id");
CREATE INDEX "interior_jobs_output_assets_asset_idx" ON "interior_jobs_output_assets" USING btree ("asset_id");
CREATE INDEX "interior_jobs_structure_idx" ON "interior_jobs" USING btree ("structure_id");
CREATE INDEX "interior_jobs_room_idx" ON "interior_jobs" USING btree ("room_id");
CREATE INDEX "interior_jobs_started_by_idx" ON "interior_jobs" USING btree ("started_by_id");
CREATE INDEX "interior_jobs_ends_at_idx" ON "interior_jobs" USING btree ("ends_at");
CREATE INDEX "interior_jobs_collected_by_idx" ON "interior_jobs" USING btree ("collected_by_id");
CREATE INDEX "interior_jobs_updated_at_idx" ON "interior_jobs" USING btree ("updated_at");
CREATE INDEX "interior_jobs_created_at_idx" ON "interior_jobs" USING btree ("created_at");
CREATE INDEX "structures_rooms_levels_upgrade_materials_order_idx" ON "structures_rooms_levels_upgrade_materials" USING btree ("_order");
CREATE INDEX "structures_rooms_levels_upgrade_materials_parent_id_idx" ON "structures_rooms_levels_upgrade_materials" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_levels_upgrade_materials_resource_idx" ON "structures_rooms_levels_upgrade_materials" USING btree ("resource_id");
CREATE INDEX "structures_rooms_levels_effects_order_idx" ON "structures_rooms_levels_effects" USING btree ("_order");
CREATE INDEX "structures_rooms_levels_effects_parent_id_idx" ON "structures_rooms_levels_effects" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_levels_order_idx" ON "structures_rooms_levels" USING btree ("_order");
CREATE INDEX "structures_rooms_levels_parent_id_idx" ON "structures_rooms_levels" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_station_recipes_inputs_order_idx" ON "structures_rooms_station_recipes_inputs" USING btree ("_order");
CREATE INDEX "structures_rooms_station_recipes_inputs_parent_id_idx" ON "structures_rooms_station_recipes_inputs" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_station_recipes_inputs_resource_idx" ON "structures_rooms_station_recipes_inputs" USING btree ("resource_id");
CREATE INDEX "structures_rooms_station_recipes_outputs_order_idx" ON "structures_rooms_station_recipes_outputs" USING btree ("_order");
CREATE INDEX "structures_rooms_station_recipes_outputs_parent_id_idx" ON "structures_rooms_station_recipes_outputs" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_station_recipes_order_idx" ON "structures_rooms_station_recipes" USING btree ("_order");
CREATE INDEX "structures_rooms_station_recipes_parent_id_idx" ON "structures_rooms_station_recipes" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_fixtures_repair_materials_order_idx" ON "structures_rooms_fixtures_repair_materials" USING btree ("_order");
CREATE INDEX "structures_rooms_fixtures_repair_materials_parent_id_idx" ON "structures_rooms_fixtures_repair_materials" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_fixtures_repair_materials_resource_idx" ON "structures_rooms_fixtures_repair_materials" USING btree ("resource_id");
CREATE INDEX "structures_rooms_fixtures_order_idx" ON "structures_rooms_fixtures" USING btree ("_order");
CREATE INDEX "structures_rooms_fixtures_parent_id_idx" ON "structures_rooms_fixtures" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_junk_loot_order_idx" ON "structures_rooms_junk_loot" USING btree ("_order");
CREATE INDEX "structures_rooms_junk_loot_parent_id_idx" ON "structures_rooms_junk_loot" USING btree ("_parent_id");
CREATE INDEX "structures_rooms_order_idx" ON "structures_rooms" USING btree ("_order");
CREATE INDEX "structures_rooms_parent_id_idx" ON "structures_rooms" USING btree ("_parent_id");
ALTER TABLE "game_structures" ADD CONSTRAINT "game_structures_interior_floorplan_id_media_id_fk" FOREIGN KEY ("interior_floorplan_id") REFERENCES "public"."media"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "structures" ADD CONSTRAINT "structures_floorplan_id_media_id_fk" FOREIGN KEY ("floorplan_id") REFERENCES "public"."media"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "structures_rels" ADD CONSTRAINT "structures_rels_roles_fk" FOREIGN KEY ("roles_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "structures_rels" ADD CONSTRAINT "structures_rels_users_fk" FOREIGN KEY ("users_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_structure_rooms_fk" FOREIGN KEY ("structure_rooms_id") REFERENCES "public"."structure_rooms"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_interior_jobs_fk" FOREIGN KEY ("interior_jobs_id") REFERENCES "public"."interior_jobs"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "game_structures_interior_interior_floorplan_idx" ON "game_structures" USING btree ("interior_floorplan_id");
CREATE INDEX "structures_floorplan_idx" ON "structures" USING btree ("floorplan_id");
CREATE INDEX "structures_rels_roles_id_idx" ON "structures_rels" USING btree ("roles_id");
CREATE INDEX "structures_rels_users_id_idx" ON "structures_rels" USING btree ("users_id");
CREATE INDEX "payload_locked_documents_rels_structure_rooms_id_idx" ON "payload_locked_documents_rels" USING btree ("structure_rooms_id");
CREATE INDEX "payload_locked_documents_rels_interior_jobs_id_idx" ON "payload_locked_documents_rels" USING btree ("interior_jobs_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "structure_rooms_fixtures" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structure_rooms" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "interior_jobs_committed_resources" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "interior_jobs_output_resources" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "interior_jobs_output_assets" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "interior_jobs" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_levels_upgrade_materials" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_levels_effects" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_levels" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_station_recipes_inputs" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_station_recipes_outputs" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_station_recipes" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_fixtures_repair_materials" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_fixtures" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms_junk_loot" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "structures_rooms" DISABLE ROW LEVEL SECURITY;
DROP TABLE "structure_rooms_fixtures" CASCADE;
DROP TABLE "structure_rooms" CASCADE;
DROP TABLE "interior_jobs_committed_resources" CASCADE;
DROP TABLE "interior_jobs_output_resources" CASCADE;
DROP TABLE "interior_jobs_output_assets" CASCADE;
DROP TABLE "interior_jobs" CASCADE;
DROP TABLE "structures_rooms_levels_upgrade_materials" CASCADE;
DROP TABLE "structures_rooms_levels_effects" CASCADE;
DROP TABLE "structures_rooms_levels" CASCADE;
DROP TABLE "structures_rooms_station_recipes_inputs" CASCADE;
DROP TABLE "structures_rooms_station_recipes_outputs" CASCADE;
DROP TABLE "structures_rooms_station_recipes" CASCADE;
DROP TABLE "structures_rooms_fixtures_repair_materials" CASCADE;
DROP TABLE "structures_rooms_fixtures" CASCADE;
DROP TABLE "structures_rooms_junk_loot" CASCADE;
DROP TABLE "structures_rooms" CASCADE;
ALTER TABLE "game_structures" DROP CONSTRAINT "game_structures_interior_floorplan_id_media_id_fk";
ALTER TABLE "structures" DROP CONSTRAINT "structures_floorplan_id_media_id_fk";
ALTER TABLE "structures_rels" DROP CONSTRAINT "structures_rels_roles_fk";
ALTER TABLE "structures_rels" DROP CONSTRAINT "structures_rels_users_fk";
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_structure_rooms_fk";
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_interior_jobs_fk";
ALTER TABLE "game_event_logs" ALTER COLUMN "target_collection" SET DATA TYPE text;
DROP TYPE "public"."enum_game_event_logs_target_collection";
CREATE TYPE "public"."enum_game_event_logs_target_collection" AS ENUM('game-structures', 'game-vehicles', 'game-npcs', 'npc-staffing', 'structures', 'resources', 'assets', 'vehicles', 'factions', 'missions', 'campaigns', 'users', 'technologies', 'maps', 'shipments', 'bank-accounts', 'bank-transactions', 'ledger-entries', 'locker-storages', 'loadouts', 'market-listings', 'market-negotiations', 'market-state', 'evaluations', 'tickets', 'wiki-pages', 'wiki-revisions', 'wiki-templates', 'form-submissions', 'mission-map-markers', 'contribution-entries', 'game-servers', 'assignment-transfers', 'voice-scripts', 'voice-submissions', 'story-beats', 'journals', 'awards', 'story-beat-states', 'custom-minefields', 'custom-minefield-scores', 'custom-radio-tests', 'custom-radio-test-scores', 'ribbon-submissions', 'promotion-nominations', 'leadership-transfers', 'player-flags', 'reinforcement-pools');
ALTER TABLE "game_event_logs" ALTER COLUMN "target_collection" SET DATA TYPE "public"."enum_game_event_logs_target_collection" USING "target_collection"::"public"."enum_game_event_logs_target_collection";
ALTER TABLE "users_preferences_notifications_muted_types" ALTER COLUMN "value" SET DATA TYPE text;
DROP TYPE "public"."enum_users_preferences_notifications_muted_types";
CREATE TYPE "public"."enum_users_preferences_notifications_muted_types" AS ENUM('market:offer', 'market:counter', 'market:accept', 'market:reject', 'market:withdrawn', 'market:closed', 'market:sold', 'market:expired', 'award:granted', 'account:discord-request', 'finance:deposit', 'finance:withdraw', 'finance:transfer', 'shipment:completed', 'ticket:created', 'ticket:assigned', 'ticket:reply', 'ticket:status', 'poker:force-ended', 'poker:everyone-left', 'blackjack:force-ended', 'blackjack:everyone-left', 'mission:role-promoted', 'contribution:xp-granted', 'contribution:xp-revoked', 'minigame:achievement', 'tech:ballot-open', 'tech:research-complete');
ALTER TABLE "users_preferences_notifications_muted_types" ALTER COLUMN "value" SET DATA TYPE "public"."enum_users_preferences_notifications_muted_types" USING "value"::"public"."enum_users_preferences_notifications_muted_types";
ALTER TABLE "users_preferences_discord_muted_types" ALTER COLUMN "value" SET DATA TYPE text;
DROP TYPE "public"."enum_users_preferences_discord_muted_types";
CREATE TYPE "public"."enum_users_preferences_discord_muted_types" AS ENUM('market:offer', 'market:counter', 'market:accept', 'market:reject', 'market:withdrawn', 'market:closed', 'market:sold', 'market:expired', 'award:granted', 'account:discord-request', 'finance:deposit', 'finance:withdraw', 'finance:transfer', 'shipment:completed', 'ticket:created', 'ticket:assigned', 'ticket:reply', 'ticket:status', 'poker:force-ended', 'poker:everyone-left', 'blackjack:force-ended', 'blackjack:everyone-left', 'mission:role-promoted', 'contribution:xp-granted', 'contribution:xp-revoked', 'minigame:achievement', 'tech:ballot-open', 'tech:research-complete');
ALTER TABLE "users_preferences_discord_muted_types" ALTER COLUMN "value" SET DATA TYPE "public"."enum_users_preferences_discord_muted_types" USING "value"::"public"."enum_users_preferences_discord_muted_types";
DROP INDEX "game_structures_interior_interior_floorplan_idx";
DROP INDEX "structures_floorplan_idx";
DROP INDEX "structures_rels_roles_id_idx";
DROP INDEX "structures_rels_users_id_idx";
DROP INDEX "payload_locked_documents_rels_structure_rooms_id_idx";
DROP INDEX "payload_locked_documents_rels_interior_jobs_id_idx";
ALTER TABLE "game_structures" ALTER COLUMN "is_research_facility" SET DEFAULT false;
ALTER TABLE "game_structures" ALTER COLUMN "research_speed_modifier" SET DEFAULT 0;
ALTER TABLE "game_structures" ALTER COLUMN "research_slots" SET DEFAULT 1;
ALTER TABLE "game_structures" DROP COLUMN "interior_provisioned_at";
ALTER TABLE "game_structures" DROP COLUMN "interior_last_decay_at";
ALTER TABLE "game_structures" DROP COLUMN "interior_floorplan_id";
ALTER TABLE "game_structures" DROP COLUMN "interior_floorplan_alt";
ALTER TABLE "game_structures" DROP COLUMN "interior_rooms";
ALTER TABLE "game_structures" DROP COLUMN "interior_interior_access_mode";
ALTER TABLE "structures" DROP COLUMN "interior_enabled";
ALTER TABLE "structures" DROP COLUMN "interior_name";
ALTER TABLE "structures" DROP COLUMN "floorplan_id";
ALTER TABLE "structures" DROP COLUMN "floorplan_alt";
ALTER TABLE "structures" DROP COLUMN "interior_access_mode";
ALTER TABLE "structures_rels" DROP COLUMN "roles_id";
ALTER TABLE "structures_rels" DROP COLUMN "users_id";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "structure_rooms_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "structure_rooms_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "structure_rooms_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "structure_rooms_delete";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "interior_jobs_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "interior_jobs_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "interior_jobs_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "interior_jobs_delete";
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "structure_rooms_id";
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "interior_jobs_id";
ALTER TABLE "game_rules" DROP COLUMN "interior_decay_enabled";
ALTER TABLE "game_rules" DROP COLUMN "interior_decay_multiplier";
DROP TYPE "public"."enum_game_structures_interior_interior_access_mode";
DROP TYPE "public"."enum_interior_jobs_type";
DROP TYPE "public"."enum_interior_jobs_status";
DROP TYPE "public"."enum_structures_rooms_levels_effects_type";
DROP TYPE "public"."enum_structures_rooms_station_recipes_outputs_kind";
DROP TYPE "public"."enum_structures_rooms_junk_loot_kind";
DROP TYPE "public"."enum_structures_interior_access_mode";`)
}

View file

@ -143,6 +143,7 @@ import * as migration_20261015_120000_add_bomperator_minigame_stats from './2026
import * as migration_20261019_120000_add_ai_prompt_entity_context from './20261019_120000_add_ai_prompt_entity_context';
import * as migration_20261019_121500_use_env_ai_model from './20261019_121500_use_env_ai_model';
import * as migration_20261019_184409_add_tech_research_system from './20261019_184409_add_tech_research_system';
import * as migration_20261020_171725_add_superstructure_interior from './20261020_171725_add_superstructure_interior';
export const migrations = [
{
@ -868,6 +869,11 @@ export const migrations = [
{
up: migration_20261019_184409_add_tech_research_system.up,
down: migration_20261019_184409_add_tech_research_system.down,
name: '20261019_184409_add_tech_research_system'
name: '20261019_184409_add_tech_research_system',
},
{
up: migration_20261020_171725_add_superstructure_interior.up,
down: migration_20261020_171725_add_superstructure_interior.down,
name: '20261020_171725_add_superstructure_interior'
},
];

View file

@ -81,6 +81,8 @@ export interface Config {
'reinforcement-pools': ReinforcementPool;
'labor-classifications': LaborClassification;
'game-event-logs': GameEventLog;
'structure-rooms': StructureRoom;
'interior-jobs': InteriorJob;
users: User;
roles: Role;
ranks: Rank;
@ -192,6 +194,8 @@ export interface Config {
'reinforcement-pools': ReinforcementPoolsSelect<false> | ReinforcementPoolsSelect<true>;
'labor-classifications': LaborClassificationsSelect<false> | LaborClassificationsSelect<true>;
'game-event-logs': GameEventLogsSelect<false> | GameEventLogsSelect<true>;
'structure-rooms': StructureRoomsSelect<false> | StructureRoomsSelect<true>;
'interior-jobs': InteriorJobsSelect<false> | InteriorJobsSelect<true>;
users: UsersSelect<false> | UsersSelect<true>;
roles: RolesSelect<false> | RolesSelect<true>;
ranks: RanksSelect<false> | RanksSelect<true>;
@ -509,6 +513,7 @@ export interface User {
| 'minigame:achievement'
| 'tech:ballot-open'
| 'tech:research-complete'
| 'interior:job-ready'
)[]
| null;
};
@ -563,6 +568,7 @@ export interface User {
| 'minigame:achievement'
| 'tech:ballot-open'
| 'tech:research-complete'
| 'interior:job-ready'
)[]
| null;
};
@ -1308,6 +1314,44 @@ export interface GameStructure {
* Total number of distinct entries currently in item storage.
*/
storedAssetCount?: number | null;
/**
* Runtime interior state, provisioned from the structure blueprint. Rooms live on structure-rooms; this snapshot preserves the floorplan + access so blueprint edits never retarget live rooms.
*/
interior?: {
/**
* When the interior rooms were first provisioned.
*/
provisionedAt?: string | null;
/**
* Last interior decay sweep.
*/
lastDecayAt?: string | null;
/**
* Snapshot of the blueprint floorplan at provisioning.
*/
floorplan?: (number | null) | Media;
floorplanAlt?: string | null;
/**
* Authoritative copy of the blueprint rooms array at provisioning time.
*/
rooms?:
| {
[k: string]: unknown;
}
| unknown[]
| string
| number
| boolean
| null;
/**
* Snapshot of the blueprint interior access at provisioning.
*/
interiorAccess?: {
mode?: ('anyone' | 'roles' | 'users') | null;
roles?: (number | Role)[] | null;
users?: (number | User)[] | null;
};
};
updatedAt: string;
createdAt: string;
}
@ -1649,6 +1693,241 @@ export interface Structure {
* So long as the structure meets its operational requirements, this is the amount of health restored to the structure every game tick.
*/
repairSpeed?: number | null;
/**
* Superuser-only toggle. When off, the interior is hidden from members. The Superstructure enables this.
*/
interiorEnabled?: boolean | null;
/**
* The member-facing name for the interior, e.g. "The Superstructure".
*/
interiorName?: string | null;
/**
* The floorplan image with clickable room hotspots. If left empty the UI renders a generated schematic from the room hotspot rectangles.
*/
floorplan?: (number | null) | Media;
/**
* Optional alt label shown alongside the floorplan.
*/
floorplanAlt?: string | null;
/**
* Who can enter this structure's interior in the member UI. Mirrors Item Storage Access.
*/
interiorAccess?: {
mode?: ('anyone' | 'roles' | 'users') | null;
roles?: (number | Role)[] | null;
users?: (number | User)[] | null;
};
/**
* The authored room blueprint. One row per room; the runtime state lives on structure-rooms at provisioning.
*/
rooms?:
| {
/**
* Stable slug, unique within the structure (e.g. 'barracks').
*/
key: string;
name: string;
description?: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ('ltr' | 'rtl') | null;
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
indent: number;
version: number;
};
[k: string]: unknown;
} | null;
/**
* Free-type label (e.g. barracks, workshop, annex).
*/
roomType?: string | null;
/**
* Position and size as percentages of the floorplan (0-100).
*/
hotspot: {
x: number;
y: number;
width: number;
height: number;
/**
* Optional read-only graph node position (0-100). Overrides hotspot center when set.
*/
graphX?: number | null;
/**
* Optional read-only graph node position (0-100). Overrides hotspot center when set.
*/
graphY?: number | null;
};
/**
* Starting room level. 0 means the room is sealed and must be opened.
*/
initialLevel?: number | null;
maxLevel: number;
/**
* One row per level, ordered by level. Drives upgrade costs, gates, and effects.
*/
levels?:
| {
level: number;
label?: string | null;
upgradeMaterials?:
| {
resource: number | Resource;
amount: number;
id?: string | null;
}[]
| null;
upgradeDurationMinutes: number;
/**
* Research that must be completed (researchedAt) before this level is reachable.
*/
requiredTech?: (number | Technology)[] | null;
/**
* Labor classification required to start the upgrade. Empty = none.
*/
requiredLaborClass?: string | null;
/**
* Minimum active labor headcount for this class to start the job.
*/
requiredHeadcount?: number | null;
/**
* Multipliers applied at this level: production speed, output bonus, storage/labor capacity, and recipe/station unlocks.
*/
effects?:
| {
type:
| 'production_speed'
| 'output_bonus'
| 'storage_capacity'
| 'labor_capacity'
| 'unlocks_recipe'
| 'unlocks_station';
value: number;
id?: string | null;
}[]
| null;
id?: string | null;
}[]
| null;
/**
* Optional equipment station that runs recipes to produce resources or assets.
*/
station?: {
name?: string | null;
enabled?: boolean | null;
recipes?:
| {
key: string;
name: string;
/**
* Asset-output recipes stay disabled at launch until locker apply is verified.
*/
enabled?: boolean | null;
durationMinutes: number;
requiredLaborClass?: string | null;
requiredHeadcount?: number | null;
requiredRoomLevel?: number | null;
inputs?:
| {
resource: number | Resource;
amount: number;
id?: string | null;
}[]
| null;
outputs?:
| {
kind: 'resource' | 'asset';
item:
| {
relationTo: 'resources';
value: number | Resource;
}
| {
relationTo: 'assets';
value: number | Asset;
};
amount: number;
id?: string | null;
}[]
| null;
id?: string | null;
}[]
| null;
};
/**
* Physical fixtures that can break and be repaired.
*/
fixtures?:
| {
key: string;
name: string;
/**
* Starting condition. Empty defaults to 100 at provisioning.
*/
condition?: number | null;
brokenByDefault?: boolean | null;
repairMaterials?:
| {
resource: number | Resource;
amount: number;
id?: string | null;
}[]
| null;
repairDurationMinutes?: number | null;
/**
* When broken, this fixture blocks the room's station until repaired.
*/
blocksStation?: boolean | null;
id?: string | null;
}[]
| null;
/**
* Per-room condition and junk decay parameters.
*/
decay?: {
/**
* Condition lost per elapsed game day.
*/
conditionPerDay?: number | null;
/**
* Condition at or below which the room no longer functions (0 output).
*/
effectFloor?: number | null;
/**
* Maximum junk level before the room is blocked.
*/
junkMax?: number | null;
initialJunkLevel?: number | null;
};
/**
* Rolled when a junk-cleanup job completes.
*/
junkLoot?:
| {
kind: 'resource' | 'asset';
item:
| {
relationTo: 'resources';
value: number | Resource;
}
| {
relationTo: 'assets';
value: number | Asset;
};
amountMin: number;
amountMax: number;
weight: number;
id?: string | null;
}[]
| null;
id?: string | null;
}[]
| null;
updatedAt: string;
createdAt: string;
}
@ -3328,6 +3607,117 @@ export interface GameEventLog {
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "structure-rooms".
*/
export interface StructureRoom {
id: number;
structure: number | GameStructure;
roomKey: string;
name: string;
/**
* Current room level. 0 = sealed.
*/
level?: number | null;
/**
* 100 = pristine, 0 = fully degraded.
*/
condition?: number | null;
/**
* Accumulated junk; cleaned via a cleanup job.
*/
junkLevel?: number | null;
/**
* Level at which the room's station is currently running.
*/
stationLevel?: number | null;
lastDecayAt?: string | null;
/**
* The job occupying this room's output slot, if any. Set only when the room is busy.
*/
pendingJob?: (number | null) | InteriorJob;
/**
* Provisioned from the blueprint fixtures; condition tracked here.
*/
fixtures?:
| {
key: string;
name: string;
broken?: boolean | null;
condition?: number | null;
brokenAt?: string | null;
id?: string | null;
}[]
| null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "interior-jobs".
*/
export interface InteriorJob {
id: number;
structure: number | GameStructure;
room: number | StructureRoom;
type: 'open' | 'cleanup' | 'upgrade' | 'repair' | 'produce';
status: 'active' | 'awaiting_collect' | 'cancelled' | 'collected' | 'failed';
/**
* Recipe key for a produce job.
*/
stationRecipeKey?: string | null;
/**
* Fixture key for a repair job.
*/
fixtureKey?: string | null;
/**
* Destination level for an upgrade job.
*/
targetLevel?: number | null;
startedBy?: (number | null) | User;
startedAt?: string | null;
endsAt?: string | null;
/**
* Labor class the job was started under.
*/
laborClass?: string | null;
headcount?: number | null;
/**
* Resources consumed at start; refunded on cancel.
*/
committedResources?:
| {
resource: number | Resource;
amount: number;
id?: string | null;
}[]
| null;
output?: {
resources?:
| {
resource: number | Resource;
amount: number;
id?: string | null;
}[]
| null;
assets?:
| {
asset: number | Asset;
amount: number;
id?: string | null;
}[]
| null;
};
/**
* Human-readable summary of what the job produced or refunded.
*/
resultNote?: string | null;
collectedAt?: string | null;
collectedBy?: (number | null) | User;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "ranks".
@ -7042,6 +7432,42 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
structureRooms?: {
/**
* Allow clients to find structure-rooms.
*/
find?: boolean | null;
/**
* Allow clients to create structure-rooms.
*/
create?: boolean | null;
/**
* Allow clients to update structure-rooms.
*/
update?: boolean | null;
/**
* Allow clients to delete structure-rooms.
*/
delete?: boolean | null;
};
interiorJobs?: {
/**
* Allow clients to find interior-jobs.
*/
find?: boolean | null;
/**
* Allow clients to create interior-jobs.
*/
create?: boolean | null;
/**
* Allow clients to update interior-jobs.
*/
update?: boolean | null;
/**
* Allow clients to delete interior-jobs.
*/
delete?: boolean | null;
};
users?: {
/**
* Allow clients to find users.
@ -8565,6 +8991,14 @@ export interface PayloadLockedDocument {
relationTo: 'game-event-logs';
value: number | GameEventLog;
} | null)
| ({
relationTo: 'structure-rooms';
value: number | StructureRoom;
} | null)
| ({
relationTo: 'interior-jobs';
value: number | InteriorJob;
} | null)
| ({
relationTo: 'users';
value: number | User;
@ -9132,6 +9566,22 @@ export interface GameStructuresSelect<T extends boolean = true> {
id?: T;
};
storedAssetCount?: T;
interior?:
| T
| {
provisionedAt?: T;
lastDecayAt?: T;
floorplan?: T;
floorplanAlt?: T;
rooms?: T;
interiorAccess?:
| T
| {
mode?: T;
roles?: T;
users?: T;
};
};
updatedAt?: T;
createdAt?: T;
}
@ -9328,6 +9778,81 @@ export interface GameEventLogsSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "structure-rooms_select".
*/
export interface StructureRoomsSelect<T extends boolean = true> {
structure?: T;
roomKey?: T;
name?: T;
level?: T;
condition?: T;
junkLevel?: T;
stationLevel?: T;
lastDecayAt?: T;
pendingJob?: T;
fixtures?:
| T
| {
key?: T;
name?: T;
broken?: T;
condition?: T;
brokenAt?: T;
id?: T;
};
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "interior-jobs_select".
*/
export interface InteriorJobsSelect<T extends boolean = true> {
structure?: T;
room?: T;
type?: T;
status?: T;
stationRecipeKey?: T;
fixtureKey?: T;
targetLevel?: T;
startedBy?: T;
startedAt?: T;
endsAt?: T;
laborClass?: T;
headcount?: T;
committedResources?:
| T
| {
resource?: T;
amount?: T;
id?: T;
};
output?:
| T
| {
resources?:
| T
| {
resource?: T;
amount?: T;
id?: T;
};
assets?:
| T
| {
asset?: T;
amount?: T;
id?: T;
};
};
resultNote?: T;
collectedAt?: T;
collectedBy?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "users_select".
@ -10554,6 +11079,132 @@ export interface StructuresSelect<T extends boolean = true> {
};
maxHealth?: T;
repairSpeed?: T;
interiorEnabled?: T;
interiorName?: T;
floorplan?: T;
floorplanAlt?: T;
interiorAccess?:
| T
| {
mode?: T;
roles?: T;
users?: T;
};
rooms?:
| T
| {
key?: T;
name?: T;
description?: T;
roomType?: T;
hotspot?:
| T
| {
x?: T;
y?: T;
width?: T;
height?: T;
graphX?: T;
graphY?: T;
};
initialLevel?: T;
maxLevel?: T;
levels?:
| T
| {
level?: T;
label?: T;
upgradeMaterials?:
| T
| {
resource?: T;
amount?: T;
id?: T;
};
upgradeDurationMinutes?: T;
requiredTech?: T;
requiredLaborClass?: T;
requiredHeadcount?: T;
effects?:
| T
| {
type?: T;
value?: T;
id?: T;
};
id?: T;
};
station?:
| T
| {
name?: T;
enabled?: T;
recipes?:
| T
| {
key?: T;
name?: T;
enabled?: T;
durationMinutes?: T;
requiredLaborClass?: T;
requiredHeadcount?: T;
requiredRoomLevel?: T;
inputs?:
| T
| {
resource?: T;
amount?: T;
id?: T;
};
outputs?:
| T
| {
kind?: T;
item?: T;
amount?: T;
id?: T;
};
id?: T;
};
};
fixtures?:
| T
| {
key?: T;
name?: T;
condition?: T;
brokenByDefault?: T;
repairMaterials?:
| T
| {
resource?: T;
amount?: T;
id?: T;
};
repairDurationMinutes?: T;
blocksStation?: T;
id?: T;
};
decay?:
| T
| {
conditionPerDay?: T;
effectFloor?: T;
junkMax?: T;
initialJunkLevel?: T;
};
junkLoot?:
| T
| {
kind?: T;
item?: T;
amountMin?: T;
amountMax?: T;
weight?: T;
id?: T;
};
id?: T;
};
updatedAt?: T;
createdAt?: T;
}
@ -11818,6 +12469,22 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
structureRooms?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
interiorJobs?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
users?:
| T
| {
@ -12620,6 +13287,19 @@ export interface GameRule {
*/
researcherSpeedPerHead?: number | null;
};
/**
* Global knobs for the Superstructure interior system (interior-tick).
*/
interior?: {
/**
* Master gate for interior condition/junk decay. When off, the interior-tick skips decay.
*/
decayEnabled?: boolean | null;
/**
* Multiplier applied to per-room decay while the master gate is on.
*/
decayMultiplier?: number | null;
};
/**
* When off, the Zone Pressure feature is hidden from the Operations feed (the overview card and the AAR section).
*/
@ -12826,6 +13506,12 @@ export interface GameRulesSelect<T extends boolean = true> {
ballotDurationTicks?: T;
researcherSpeedPerHead?: T;
};
interior?:
| T
| {
decayEnabled?: T;
decayMultiplier?: T;
};
zonePressureEnabled?: T;
statisticsEnabled?: T;
helpdeskEnabled?: T;

View file

@ -56,6 +56,8 @@ import { DiscordPresence } from "@/collections/discord/DiscordPresence";
import { GameStructures } from "@/collections/game/GameStructures";
import { GameHardResources } from "@/collections/game/GameHardResources";
import { GameEventLogs } from "@/collections/game/GameEventLogs";
import { StructureRooms } from "@/collections/interior/StructureRooms";
import { InteriorJobs } from "@/collections/interior/InteriorJobs";
import { GameVehicles } from "@/collections/game/GameVehicles";
import { GameNpcs } from "@/collections/game/GameNpcs";
import { NpcStaffing } from "@/collections/game/NpcStaffing";
@ -318,6 +320,8 @@ const collections = [
ReinforcementPools,
LaborClassifications,
GameEventLogs,
StructureRooms,
InteriorJobs,
// Users
Users,
@ -636,6 +640,10 @@ export default buildConfig({
scriptPath: path.resolve(dirname, "scripts/awardTick.ts"),
key: "award-tick",
},
{
scriptPath: path.resolve(dirname, "scripts/interiorTick.ts"),
key: "interior-tick",
},
{
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
key: "generate-mission",

View file

@ -0,0 +1,51 @@
/**
* Interior tick bin — completes due interior jobs and notifies connected clients.
*
* Run via `bun run payload interior-tick` (external cron, every minute). Sweeps
* active jobs whose duration has elapsed and flips them to `awaiting_collect`,
* then notifies connected clients so interior views refresh. Room decay is
* applied alongside this sweep once decay.ts exists.
*/
import type { SanitizedConfig } from "payload";
import { getPayload } from "payload";
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
import { sweepInteriorJobs } from "@/lib/interior/sweep";
export const script = async (config: SanitizedConfig) => {
const payload = await getPayload({ config });
const log = createBinLogger("interior-tick", payload.logger);
try {
log.info("[Interior Tick] Starting interior tick...");
const now = new Date();
const { completed, errors } = await sweepInteriorJobs(payload, now);
log.info(
`[Interior Tick] Complete. Completed ${completed} job(s), ${errors} error(s).`,
);
// Notify connected clients so interior views refresh.
const notifyUrl = (process.env.APP_URL ?? "http://localhost:3000").replace(/\/$/, "");
const notifySecret = process.env.GAME_TICK_NOTIFY_SECRET;
if (notifySecret) {
await fetch(`${notifyUrl}/api/game-tick/notify`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-game-tick-secret": notifySecret,
},
body: JSON.stringify({ processedAt: now.toISOString(), source: "interior-tick" }),
}).catch((error: unknown) => {
log.error(`[Interior Tick] Failed to notify app clients: ${errorMessage(error)}`);
});
}
process.exit(0);
} catch (error) {
log.error(
`[Interior Tick] Fatal: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
);
process.exit(1);
}
};

View file

@ -3,6 +3,7 @@ import { seedUsers } from "@/tools/seed/seedUsers";
import { seedFactions } from "@/tools/seed/seedFactions";
import { seedExperience } from "@/tools/seed/seedExperience";
import { seedMinigames } from "@/tools/seed/seedMinigames";
import { seedScrap } from "@/tools/seed/seedScrap";
// Users
await seedUsers();
@ -14,3 +15,6 @@ await seedFactions();
// Minigames
await seedMinigames();
// Logistics resources
await seedScrap();

View file

@ -0,0 +1,90 @@
import { Pool } from "pg";
import { getPayload } from "payload";
import config from "@payload-config";
/**
* Idempotent seed for the `Scrap` resource (unit kg, stackable, small weight).
*
* `Scrap` is the junk currency the interior system produces: rooms accumulate a
* junk counter, and a cleanup job converts that counter into real Scrap stock
* via the grid deposit path. Junk itself stays a counter, not a resource; this
* doc is the resource it becomes.
*
* Idempotent by `codeName`: safe to run on every dev/stg seed.
*
* Sequence hygiene: bulk-seeded databases sometimes leave `resources_id_seq`
* behind the highest `resources.id`, which makes the next autoincrement
* collide ("Value must be unique"). Aligning the sequence to MAX(id) before
* creating keeps the create path reliable in those environments.
*/
const SCRAP_CODE_NAME = "res_scrap";
/** Align resources_id_seq to the current max id so the next insert is conflict-free. */
const alignResourcesSequence = async (): Promise<void> => {
const uri = process.env.DATABASE_URI;
if (!uri) return; // no DB configured; nothing to align
const pool = new Pool({ connectionString: uri });
try {
const { rows } = await pool.query<{ max_id: number | null }>(
"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]);
}
} finally {
await pool.end();
}
};
export const seedScrap = async (): Promise<number> => {
const payload = await getPayload({ config });
const existing = await payload.find({
collection: "resources",
where: { codeName: { equals: SCRAP_CODE_NAME } },
limit: 1,
overrideAccess: true,
});
const existingId = existing.docs[0]?.id as number | undefined;
if (existingId) {
payload.logger.info(`[seed] scrap resource already exists: ${existingId}`);
return existingId;
}
// Align the sequence so the create below gets a fresh, conflict-free id.
await alignResourcesSequence();
const created = await payload.create({
collection: "resources",
data: {
name: "Scrap",
codeName: SCRAP_CODE_NAME,
approvalStatus: "approved",
type: "physical",
unitOfMeasure: "kg",
massPerUnit: 0.5,
stackSize: 1000,
stackable: true,
gridWidth: 1,
gridHeight: 1,
rotatable: false,
baseValue: 0,
rarity: "common",
tradeable: false,
},
draft: false,
overrideAccess: true,
});
// Leave the sequence consistent for the next insert.
await alignResourcesSequence();
payload.logger.info(`[seed] created scrap resource: ${created.id}`);
return created.id as number;
};
await seedScrap();
process.exit(0);

View file

@ -6,6 +6,10 @@ export const EventTypes = {
StorageVoid: "storage:void",
StorageRecover: "storage:recover",
// Interior jobs
InteriorJobStarted: "interior:job-started",
InteriorJobCancelled: "interior:job-cancelled",
// Grid
GridPlace: "grid:place",
GridMove: "grid:move",