1
0
Fork 0

feat(interior): fixture repairs, condition decay, and station blocking

completeInteriorJob restores broken fixtures on repair jobs. New decay.ts applies per-room condition loss (elapsed days x conditionPerDay x Game Rules multiplier) on the interior-tick bin, gated by interior.decayEnabled with a baseline first run that only stamps the structure clock; fixtures at or below the authored effectFloor break with new interior:fixture-broken events, floors condition at 0, and station starts fail room_damaged below the floor.

Declares blocksStation on structure-rooms fixture state: provisioning wrote it but the missing column silently stripped it, so broken doorway fixtures could never block stations. Regression test covers persistence through provisioning plus the end-to-end gate.
This commit is contained in:
Jason Fraley 2026-10-20 16:17:01 -04:00
parent 6bc295b630
commit 68cd3cce7c
11 changed files with 45579 additions and 15 deletions

View file

@ -127,6 +127,15 @@ export const StructureRooms: CollectionConfig = {
name: "brokenAt",
type: "date",
},
{
name: "blocksStation",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Copied from the blueprint fixture at provisioning. A broken fixture with this flag blocks station jobs until repaired.",
},
},
],
},
],

185
src/lib/interior/decay.ts Normal file
View file

@ -0,0 +1,185 @@
import type { Payload } from "payload";
import type { GameStructure, StructureRoom } from "@/payload-types";
import type { InteriorBlueprintRoom, RoomFixtureState } from "./types";
import { relId } from "./relations";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { emitGameEvent } from "@/utils/event-log/emit";
/**
* Interior condition decay sweep.
*
* Runs from the interior-tick bin after the job sweep, gated on Game Rules
* `interior.decayEnabled`. Each structure keeps a single decay clock on
* `game-structures.interior.lastDecayAt`; every provisioned room then loses
* `conditionPerDay * elapsedDays * decayMultiplier` condition and breaks its
* fixtures once it reaches the authored effect floor.
*
* Enabling decay on an existing structure starts the clock at enable time: the
* first sweep only stamps `lastDecayAt` and never decays retroactively.
*/
const MS_PER_DAY = 86_400_000;
const PAGE_SIZE = 100;
type InteriorSnapshot = {
rooms?: InteriorBlueprintRoom[];
provisionedAt?: string | null;
lastDecayAt?: string | null;
[key: string]: unknown;
};
type RoomRow = Pick<StructureRoom, "id" | "condition" | "fixtures">;
export async function applyInteriorDecay(
payload: Payload,
now: Date = new Date(),
): Promise<{ roomsDecayed: number; fixturesBroken: number }> {
const rules = await payload.findGlobal({
slug: "game-rules",
overrideAccess: true,
depth: 0,
});
if (rules?.interior?.decayEnabled !== true) {
return { roomsDecayed: 0, fixturesBroken: 0 };
}
const multiplier = Number(rules.interior?.decayMultiplier ?? 1);
let roomsDecayed = 0;
let fixturesBroken = 0;
let page = 1;
let totalPages = 1;
do {
const structures = await payload.find({
collection: "game-structures",
overrideAccess: true,
depth: 0,
limit: PAGE_SIZE,
page,
select: { name: true, interior: true },
where: { "interior.provisionedAt": { exists: true } },
});
totalPages = structures.totalPages ?? 1;
for (const doc of structures.docs) {
const structure = doc as unknown as Pick<GameStructure, "id" | "name" | "interior">;
const snapshot = structure.interior as InteriorSnapshot | null | undefined;
if (!snapshot || !Array.isArray(snapshot.rooms)) continue;
const lastDecayAt = snapshot.lastDecayAt ? new Date(snapshot.lastDecayAt) : null;
const hasClock = lastDecayAt !== null && !Number.isNaN(lastDecayAt.getTime());
if (hasClock) {
const elapsedDays = Math.max(0, (now.getTime() - lastDecayAt.getTime()) / MS_PER_DAY);
for (const blueprintRoom of snapshot.rooms) {
const roomKey = blueprintRoom.key;
if (!roomKey) continue;
const row = await findRoomRow(payload, relId(structure.id), roomKey);
if (!row) continue;
const roomName = blueprintRoom.name ?? roomKey;
const conditionPerDay = Number(blueprintRoom.decay?.conditionPerDay ?? 0);
const effectFloor = Number(blueprintRoom.decay?.effectFloor ?? 0);
const drop = elapsedDays * conditionPerDay * multiplier;
const storedCondition = Number(row.condition ?? 100);
const nextCondition = drop > 0 ? Math.max(0, storedCondition - drop) : storedCondition;
const roundedCondition = Math.round(nextCondition * 100) / 100;
const conditionChanged = drop > 0 && roundedCondition !== storedCondition;
// Break every intact fixture once the room reaches (or falls below)
// its authored effect floor. The per-fixture flag makes this
// idempotent, and it also runs when drop is 0 so an already-damaged
// room is reconciled without touching its condition.
const fixtures = (row.fixtures ?? []) as RoomFixtureState[];
const newlyBroken: RoomFixtureState[] = [];
let fixturesChanged = false;
const nextFixtures = fixtures.map((fixture) => {
if (fixture.broken === true || nextCondition > effectFloor) return fixture;
fixturesChanged = true;
newlyBroken.push(fixture);
return {
...fixture,
broken: true,
condition: 0,
brokenAt: now.toISOString(),
};
});
if (drop > 0 || fixturesChanged) {
const data: Record<string, unknown> = {};
if (drop > 0) {
data.condition = roundedCondition;
data.lastDecayAt = now.toISOString();
}
if (fixturesChanged) data.fixtures = nextFixtures;
await payload.update({
collection: "structure-rooms",
id: relId(row.id)!,
overrideAccess: true,
data,
});
}
if (conditionChanged) roomsDecayed += 1;
for (const fixture of newlyBroken) {
fixturesBroken += 1;
await emitGameEvent(payload, {
type: EventTypes.InteriorFixtureBroken,
message: `${fixture.name} in ${roomName} broke down (structure ${structure.name})`,
structure: relId(structure.id)!,
targetCollection: "game-structures",
targetId: relId(structure.id)!,
data: { roomKey, fixtureKey: fixture.key },
});
}
}
}
// Stamp the per-structure clock on every run, including the baseline one,
// while keeping the rest of the interior snapshot (rooms, floorplan,
// access, provisionedAt) intact.
await payload.update({
collection: "game-structures",
id: relId(structure.id)!,
overrideAccess: true,
data: {
interior: { ...snapshot, lastDecayAt: now.toISOString() },
},
});
}
page += 1;
} while (page <= totalPages);
return { roomsDecayed, fixturesBroken };
}
async function findRoomRow(
payload: Payload,
structureId: number | null,
roomKey: string,
): Promise<RoomRow | null> {
if (structureId == null) return null;
const result = await payload
.find({
collection: "structure-rooms",
overrideAccess: true,
depth: 0,
limit: 1,
where: {
AND: [
{ structure: { equals: structureId } },
{ roomKey: { equals: roomKey } },
],
},
select: { condition: true, fixtures: true },
})
.catch(() => null);
return (result?.docs?.[0] as unknown as RoomRow | undefined) ?? null;
}

View file

@ -22,7 +22,8 @@ export type JobStartError =
| "room_level_insufficient"
| "recipe_disabled"
| "tech_locked"
| "labor_insufficient";
| "labor_insufficient"
| "room_damaged";
export type JobStartResult = { ok: true } | { ok: false; reason: JobStartError };
@ -51,6 +52,12 @@ export function canStartJob(
recipeEnabled?: boolean;
recipeRequiredRoomLevel?: number;
recipeBlockingFixture?: boolean;
/**
* Produce only: the room's condition is at or below its effect floor. An
* authored positive floor blocks at `condition <= floor`; a room with no
* authored floor blocks only at `condition <= 0` (fully degraded).
*/
conditionBlocked?: boolean;
techRequirementMet?: boolean;
laborRequirementMet?: boolean;
},
@ -81,6 +88,7 @@ export function canStartJob(
case "produce": {
if (!opts?.stationEnabled) return { ok: false, reason: "station_disabled" };
if (opts?.stationUnlocked === false) return { ok: false, reason: "station_locked" };
if (opts?.conditionBlocked === true) return { ok: false, reason: "room_damaged" };
if (opts?.recipeBlockingFixture && isBlockingFixtureBroken(room.fixtures)) {
return { ok: false, reason: "fixture_blocks_station" };
}

View file

@ -45,7 +45,8 @@ export type JobStartError =
| "no_room"
| "no_blueprint"
| "tech_locked"
| "labor_insufficient";
| "labor_insufficient"
| "room_damaged";
export type JobStartResult =
| { ok: true; job: InteriorJob }
@ -144,6 +145,12 @@ export async function startInteriorJob(
const blueprint = blueprintRoom(structure, roomKey);
if (!blueprint) return { ok: false, error: "no_blueprint" };
// A room at or below its authored effect floor cannot run station work.
// Rooms with no authored floor only block at condition 0 (fully degraded).
const effectFloor = blueprint.decay?.effectFloor ?? 0;
const conditionBlocked =
effectFloor > 0 ? engineRoom.condition <= effectFloor : engineRoom.condition <= 0;
// --- Gate evaluation -----------------------------------------------------
// Tech and labor requirements are authored on a level definition, so only
// open (entry level) and upgrade (destination level) evaluate them; every
@ -175,6 +182,7 @@ export async function startInteriorJob(
recipeEnabled: produceOpts?.recipeEnabled,
recipeRequiredRoomLevel: produceOpts?.recipeRequiredRoomLevel,
recipeBlockingFixture: produceOpts?.recipeBlockingFixture ?? false,
conditionBlocked,
techRequirementMet: requirements?.techRequirementMet,
laborRequirementMet: requirements?.laborRequirementMet,
});
@ -466,13 +474,18 @@ export async function completeInteriorJob(
};
} = { status: "awaiting_collect" };
// Apply the room-level effect of open/upgrade/cleanup at completion: opening
// flips the room to its destination level, upgrading advances (and clamps) it,
// and cleanup removes junk and rolls one loot drop written onto the job for
// `collectInteriorJob` to credit. Repair effects land with their own build
// step; produce output is already recorded on the job at start. Effect lookups
// are best-effort so a missing snapshot can never wedge the sweep.
if (job.type === "open" || job.type === "upgrade" || job.type === "cleanup") {
// Apply the room-level effect of open/upgrade/cleanup/repair at completion:
// opening flips the room to its destination level, upgrading advances (and
// clamps) it, cleanup removes junk and rolls one loot drop written onto the
// job for `collectInteriorJob` to credit, and repair restores its fixture.
// Produce output is already recorded on the job at start. Effect lookups are
// best-effort so a missing snapshot can never wedge the sweep.
if (
job.type === "open" ||
job.type === "upgrade" ||
job.type === "cleanup" ||
job.type === "repair"
) {
const room = await payload
.findByID({
collection: "structure-rooms",
@ -503,7 +516,7 @@ export async function completeInteriorJob(
overrideAccess: true,
data: { level: nextLevel },
});
} else {
} else if (job.type === "cleanup") {
await payload.update({
collection: "structure-rooms",
id: relId(room.id)!,
@ -524,6 +537,24 @@ export async function completeInteriorJob(
return id == null ? [] : [{ asset: id, amount: a.amount }];
}),
};
} else {
// Repair restores one fixture by key. A key that is no longer present
// in the room's runtime state is a silent no-op.
const fixtures = (room.fixtures ?? []) as RoomFixtureState[];
if (fixtures.some((fixture) => fixture.key === job.fixtureKey)) {
await payload.update({
collection: "structure-rooms",
id: relId(room.id)!,
overrideAccess: true,
data: {
fixtures: fixtures.map((fixture) =>
fixture.key === job.fixtureKey
? { ...fixture, broken: false, condition: 100, brokenAt: null }
: fixture,
),
},
});
}
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "structure_rooms_fixtures" ADD COLUMN "blocks_station" boolean DEFAULT false;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "structure_rooms_fixtures" DROP COLUMN "blocks_station";`)
}

View file

@ -146,6 +146,7 @@ import * as migration_20261019_184409_add_tech_research_system from './20261019_
import * as migration_20261020_171725_add_superstructure_interior from './20261020_171725_add_superstructure_interior';
import * as migration_20261020_191433_add_interior_module_effect_types from './20261020_191433_add_interior_module_effect_types';
import * as migration_20261020_200000_add_interior_asset_outputs_flag from './20261020_200000_add_interior_asset_outputs_flag';
import * as migration_20261020_201242_add_room_fixture_blocks_station from './20261020_201242_add_room_fixture_blocks_station';
export const migrations = [
{
@ -886,6 +887,11 @@ export const migrations = [
{
up: migration_20261020_200000_add_interior_asset_outputs_flag.up,
down: migration_20261020_200000_add_interior_asset_outputs_flag.down,
name: '20261020_200000_add_interior_asset_outputs_flag'
name: '20261020_200000_add_interior_asset_outputs_flag',
},
{
up: migration_20261020_201242_add_room_fixture_blocks_station.up,
down: migration_20261020_201242_add_room_fixture_blocks_station.down,
name: '20261020_201242_add_room_fixture_blocks_station'
},
];

View file

@ -3656,6 +3656,10 @@ export interface StructureRoom {
broken?: boolean | null;
condition?: number | null;
brokenAt?: string | null;
/**
* Copied from the blueprint fixture at provisioning. A broken fixture with this flag blocks station jobs until repaired.
*/
blocksStation?: boolean | null;
id?: string | null;
}[]
| null;
@ -9809,6 +9813,7 @@ export interface StructureRoomsSelect<T extends boolean = true> {
broken?: T;
condition?: T;
brokenAt?: T;
blocksStation?: T;
id?: T;
};
updatedAt?: T;

View file

@ -1,15 +1,16 @@
/**
* Interior tick bin — completes due interior jobs and notifies connected clients.
* 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.
* applies interior decay, then notifies connected clients so interior views
* refresh.
*/
import type { SanitizedConfig } from "payload";
import { getPayload } from "payload";
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
import { sweepInteriorJobs } from "@/lib/interior/sweep";
import { applyInteriorDecay } from "@/lib/interior/decay";
export const script = async (config: SanitizedConfig) => {
const payload = await getPayload({ config });
@ -20,9 +21,12 @@ export const script = async (config: SanitizedConfig) => {
const now = new Date();
const { completed, errors } = await sweepInteriorJobs(payload, now);
// Decay self-gates on Game Rules `interior.decayEnabled`.
const { roomsDecayed, fixturesBroken } = await applyInteriorDecay(payload, now);
log.info(
`[Interior Tick] Complete. Completed ${completed} job(s), ${errors} error(s).`,
`[Interior Tick] Complete. Completed ${completed} job(s), ${errors} error(s); ` +
`decayed ${roomsDecayed} room(s), broke ${fixturesBroken} fixture(s).`,
);
// Notify connected clients so interior views refresh.

View file

@ -9,6 +9,7 @@ export const EventTypes = {
// Interior jobs
InteriorJobStarted: "interior:job-started",
InteriorJobCancelled: "interior:job-cancelled",
InteriorFixtureBroken: "interior:fixture-broken",
// Grid
GridPlace: "grid:place",

View file

@ -21,6 +21,7 @@ import {
rollJunkLoot,
startInteriorJob,
} from "@/lib/interior/jobs";
import { applyInteriorDecay } from "@/lib/interior/decay";
import { applyInteriorDurationFactor, applyOutputBonus } from "@/lib/interior/effects";
import { installedModuleEffects } from "@/lib/base/modules";
import { provisionInterior } from "@/lib/interior/provision";
@ -1586,3 +1587,512 @@ describe("Interior asset output credit", () => {
expect(afterSecond[0]?.quantity).toBe(5);
});
});
describe("Interior repair completion", () => {
it("restores a broken fixture and flips the job to awaiting_collect", async () => {
const blueprint = await makeBlueprint("repair-blueprint", 1000);
const structure = await makeStructure({
label: "repair-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "plant",
name: "Plant Room",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
fixtures: [{ key: "pump", name: "Pump" }],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const room = await roomByKey(structure.id, "plant");
const brokenAt = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
await payload.update({
collection: "structure-rooms",
id: room.id,
overrideAccess: true,
data: {
fixtures: [
{ key: "pump", name: "Pump", broken: true, condition: 0, brokenAt },
],
},
});
const now = new Date().toISOString();
const job = (await payload.create({
collection: "interior-jobs",
data: {
structure: structure.id,
room: room.id,
type: "repair",
status: "active",
fixtureKey: "pump",
startedBy: member.id,
startedAt: now,
endsAt: now,
},
overrideAccess: true,
depth: 0,
})) as unknown as InteriorJob;
const result = await completeInteriorJob(payload, job.id);
expect(result).toEqual({ ok: true });
expect((await jobById(job.id)).status).toBe("awaiting_collect");
const fixtures = (await roomById(room.id)).fixtures ?? [];
const fixture = fixtures.find((f) => f.key === "pump");
expect(fixture?.broken).toBe(false);
expect(fixture?.condition).toBe(100);
expect(fixture?.brokenAt).toBeNull();
});
});
describe("Interior decay", () => {
let decayWasEnabled = false;
let multiplierWas = 1;
const setDecayRules = async (enabled: boolean, multiplier = 1) => {
const rules = await payload.findGlobal({
slug: "game-rules",
depth: 0,
overrideAccess: true,
});
await payload.updateGlobal({
slug: "game-rules",
data: {
interior: {
...rules.interior,
decayEnabled: enabled,
decayMultiplier: multiplier,
},
},
overrideAccess: true,
});
};
const setDecayClock = async (structureId: number, iso: string | null) => {
const structure = await fetchStructure(structureId);
await payload.update({
collection: "game-structures",
id: structureId,
overrideAccess: true,
data: {
interior: {
...(structure.interior as Record<string, unknown>),
lastDecayAt: iso,
},
},
});
};
const decayStructures: number[] = [];
/**
* Pin every earlier decay fixture's clock to the wall clock so a test only
* measures the structure it just backdated.
*/
const resetDecayClocks = async () => {
for (const id of decayStructures) {
await setDecayClock(id, new Date().toISOString());
}
};
const makeDecayStructure = async (
label: string,
rooms: InteriorBlueprintRoom[],
): Promise<GameStructure> => {
const blueprint = await makeBlueprint(`${label}-blueprint`, 1000);
const structure = await makeStructure({
label: `${label}-structure`,
blueprintId: blueprint.id,
rooms,
});
await provisionInterior(payload, await fetchStructure(structure.id));
decayStructures.push(structure.id);
return structure;
};
beforeAll(async () => {
const rules = await payload.findGlobal({
slug: "game-rules",
depth: 0,
overrideAccess: true,
});
decayWasEnabled = Boolean(rules.interior?.decayEnabled);
multiplierWas = rules.interior?.decayMultiplier ?? 1;
});
afterAll(async () => {
await setDecayRules(decayWasEnabled, multiplierWas);
});
it("applies condition loss from the structure clock and multiplier", async () => {
await setDecayRules(true, 1.5);
const structure = await makeDecayStructure("decay-math", [
{
key: "boiler",
name: "Boiler Room",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
decay: { conditionPerDay: 2, effectFloor: 0 },
},
]);
const room = await roomByKey(structure.id, "boiler");
await payload.update({
collection: "structure-rooms",
id: room.id,
overrideAccess: true,
data: { condition: 80 },
});
const now = new Date();
const tenDaysAgo = new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000);
await setDecayClock(structure.id, tenDaysAgo.toISOString());
const result = await applyInteriorDecay(payload, now);
expect(result).toEqual({ roomsDecayed: 1, fixturesBroken: 0 });
expect((await roomByKey(structure.id, "boiler")).condition).toBe(50);
const after = await fetchStructure(structure.id);
expect(after.interior?.lastDecayAt).toBe(now.toISOString());
expect(after.interior?.provisionedAt).toBeTruthy();
expect(after.interior?.rooms).toHaveLength(1);
});
it("does nothing while the decay master gate is off", async () => {
await setDecayRules(false, 1.5);
const structure = await makeDecayStructure("decay-off", [
{
key: "freezer",
name: "Freezer",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
decay: { conditionPerDay: 2 },
},
]);
const room = await roomByKey(structure.id, "freezer");
await payload.update({
collection: "structure-rooms",
id: room.id,
overrideAccess: true,
data: { condition: 80 },
});
const clock = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString();
await setDecayClock(structure.id, clock);
const result = await applyInteriorDecay(payload);
expect(result).toEqual({ roomsDecayed: 0, fixturesBroken: 0 });
expect((await roomByKey(structure.id, "freezer")).condition).toBe(80);
expect((await fetchStructure(structure.id)).interior?.lastDecayAt).toBe(clock);
});
it("baseline-stamps a structure with no clock instead of decaying retroactively", async () => {
await setDecayRules(true, 1);
await resetDecayClocks();
const structure = await makeDecayStructure("decay-baseline", [
{
key: "attic",
name: "Attic",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
decay: { conditionPerDay: 2 },
},
]);
const room = await roomByKey(structure.id, "attic");
await payload.update({
collection: "structure-rooms",
id: room.id,
overrideAccess: true,
data: { condition: 80 },
});
expect((await fetchStructure(structure.id)).interior?.lastDecayAt ?? null).toBeNull();
const firstNow = new Date();
const first = await applyInteriorDecay(payload, firstNow);
expect(first.roomsDecayed).toBe(0);
expect((await roomByKey(structure.id, "attic")).condition).toBe(80);
expect((await fetchStructure(structure.id)).interior?.lastDecayAt).toBe(
firstNow.toISOString(),
);
await setDecayClock(
structure.id,
new Date(firstNow.getTime() - 10 * 24 * 60 * 60 * 1000).toISOString(),
);
const second = await applyInteriorDecay(payload, firstNow);
expect(second.roomsDecayed).toBe(1);
expect((await roomByKey(structure.id, "attic")).condition).toBe(60);
expect((await fetchStructure(structure.id)).interior?.lastDecayAt).toBe(
firstNow.toISOString(),
);
});
it("breaks intact fixtures at the effect floor and emits one event each", async () => {
await setDecayRules(true, 1);
await resetDecayClocks();
const structure = await makeDecayStructure("decay-floor", [
{
key: "pump-room",
name: "Pump Room",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
decay: { conditionPerDay: 2, effectFloor: 30 },
fixtures: [
{ key: "pump-a", name: "Pump A" },
{ key: "pump-b", name: "Pump B" },
],
},
]);
const room = await roomByKey(structure.id, "pump-room");
const oldBrokenAt = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();
await payload.update({
collection: "structure-rooms",
id: room.id,
overrideAccess: true,
data: {
condition: 40,
fixtures: [
{ key: "pump-a", name: "Pump A", broken: false, condition: 100 },
{
key: "pump-b",
name: "Pump B",
broken: true,
condition: 0,
brokenAt: oldBrokenAt,
},
],
},
});
const now = new Date();
const tenDaysAgo = new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000);
await setDecayClock(structure.id, tenDaysAgo.toISOString());
const result = await applyInteriorDecay(payload, now);
expect(result).toEqual({ roomsDecayed: 1, fixturesBroken: 1 });
const updated = await roomByKey(structure.id, "pump-room");
expect(updated.condition).toBe(20);
const pumpA = updated.fixtures?.find((f) => f.key === "pump-a");
const pumpB = updated.fixtures?.find((f) => f.key === "pump-b");
expect(pumpA?.broken).toBe(true);
expect(pumpA?.condition).toBe(0);
expect(pumpA?.brokenAt).toBe(now.toISOString());
expect(pumpB?.broken).toBe(true);
expect(pumpB?.condition).toBe(0);
expect(pumpB?.brokenAt).toBe(oldBrokenAt);
const events = await payload.find({
collection: "game-event-logs",
where: {
AND: [
{ targetId: { equals: structure.id } },
{ type: { equals: "interior:fixture-broken" } },
],
},
limit: 20,
depth: 0,
overrideAccess: true,
});
const matching = events.docs.filter(
(event) => (event.data as { roomKey?: string } | undefined)?.roomKey === "pump-room",
);
expect(matching).toHaveLength(1);
expect((matching[0]?.data as { fixtureKey?: string }).fixtureKey).toBe("pump-a");
expect(matching[0]?.message).toContain("Pump A");
// Idempotent: nothing is newly broken on the next sweep.
const again = await applyInteriorDecay(payload, now);
expect(again.fixturesBroken).toBe(0);
});
});
describe("Interior room condition gate", () => {
let structureId: number;
beforeAll(async () => {
const blueprint = await makeBlueprint("condition-gate-blueprint", 1000);
const structure = await makeStructure({
label: "condition-gate-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "damaged",
name: "Damaged Shop",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
decay: { effectFloor: 30 },
station: {
name: "Workbench",
enabled: true,
recipes: [{ key: "make", name: "Make", durationMinutes: 1 }],
},
},
{
key: "aged",
name: "Aged Shop",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
station: {
name: "Workbench",
enabled: true,
recipes: [{ key: "make", name: "Make", durationMinutes: 1 }],
},
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
structureId = structure.id;
});
it("blocks produce at or below an authored effect floor, and at zero without one", async () => {
const damaged = await roomByKey(structureId, "damaged");
await payload.update({
collection: "structure-rooms",
id: damaged.id,
overrideAccess: true,
data: { condition: 20 },
});
const blocked = await startInteriorJob(payload, { id: member.id }, {
structureId,
roomKey: "damaged",
type: "produce",
target: "make",
});
expect(blocked).toEqual({ ok: false, error: "room_damaged" });
await payload.update({
collection: "structure-rooms",
id: damaged.id,
overrideAccess: true,
data: { condition: 40 },
});
const repaired = await startInteriorJob(payload, { id: member.id }, {
structureId,
roomKey: "damaged",
type: "produce",
target: "make",
});
expect(repaired.ok).toBe(true);
if (repaired.ok) {
expect(
(await cancelInteriorJob(payload, { id: member.id }, repaired.job.id)).ok,
).toBe(true);
}
// No authored floor: condition 60 is fine, but 0 is fully degraded.
const aged = await roomByKey(structureId, "aged");
await payload.update({
collection: "structure-rooms",
id: aged.id,
overrideAccess: true,
data: { condition: 60 },
});
const healthy = await startInteriorJob(payload, { id: member.id }, {
structureId,
roomKey: "aged",
type: "produce",
target: "make",
});
expect(healthy.ok).toBe(true);
if (healthy.ok) {
expect(
(await cancelInteriorJob(payload, { id: member.id }, healthy.job.id)).ok,
).toBe(true);
}
await payload.update({
collection: "structure-rooms",
id: aged.id,
overrideAccess: true,
data: { condition: 0 },
});
const degraded = await startInteriorJob(payload, { id: member.id }, {
structureId,
roomKey: "aged",
type: "produce",
target: "make",
});
expect(degraded).toEqual({ ok: false, error: "room_damaged" });
});
});
describe("Interior blocking fixtures", () => {
it("persists blocksStation through provisioning and blocks station work while broken", async () => {
const blueprint = await makeBlueprint("doorway-blueprint");
const structure = await makeStructure({
label: "doorway-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "annex",
name: "Rubble Annex",
initialLevel: 1,
maxLevel: 2,
fixtures: [
{ key: "door", name: "Doorway", brokenByDefault: true, blocksStation: true },
],
station: {
name: "Bench",
enabled: true,
recipes: [
{
key: "patch",
name: "Patch",
durationMinutes: 5,
inputs: [],
outputs: [{ kind: "resource", item: numericRef(scrap.id), amount: 1 }],
},
],
},
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
// The flag is a declared column and survives the provision write; the
// broken default carries over too.
const room = await roomByKey(structure.id, "annex");
expect(room.fixtures?.[0]?.blocksStation).toBe(true);
expect(room.fixtures?.[0]?.broken).toBe(true);
const blocked = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "annex",
type: "produce",
target: "patch",
});
expect(blocked).toEqual({ ok: false, error: "fixture_blocks_station" });
// A repaired doorway lets station work through.
await payload.update({
collection: "structure-rooms",
id: room.id,
overrideAccess: true,
data: {
fixtures: [{ ...room.fixtures![0]!, broken: false, condition: 100, brokenAt: null }],
},
});
const started = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "annex",
type: "produce",
target: "patch",
});
expect(started.ok).toBe(true);
});
});