1
0
Fork 0
polaris-task-force/tests/int/interior.int.spec.ts

2198 lines
70 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { getPayload, type Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type {
Asset,
GameStructure,
InteriorJob,
Resource,
Role,
Structure,
StructureRoom,
Technology,
User,
} from "@/payload-types";
import { canUserEnterInterior } from "@/lib/interior/access";
import {
cancelInteriorJob,
collectInteriorJob,
completeInteriorJob,
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";
import { depositToStructure, storedAmount } from "@/lib/interior/storageBridge";
import { sweepInteriorJobs } from "@/lib/interior/sweep";
import type { InteriorBlueprintRoom, JunkLootEntry } from "@/lib/interior/types";
/**
* Superstructure Interior System engine: provisioning, access modes, job start
* gates, cancel/collect refund path, collect refusal on full storage, the
* completion sweep, and the weighted junk-loot roll.
*
* Every fixture is created per run (RUN token) and removed in afterAll so the
* shared test database is left as it was found.
*/
const RUN = `int-${Date.now().toString(36)}`;
/**
* The interior engine normalizes relationship refs with `relId`, which accepts
* plain numeric ids (authored JSON is not relationship-aware). The generated
* blueprint types only model populated / `{ id }` refs, so numeric refs are cast
* at the fixture boundary. The cast is type-level only: the runtime value stays
* a number, which is the shape under test.
*/
const numericRef = (id: number): { id: number } => id as unknown as { id: number };
const LEXICAL_EMPTY = {
root: {
children: [{ text: "" }],
direction: null,
format: "" as const,
indent: 0,
type: "text",
version: 1,
},
};
let payload: Payload;
let member: User;
let otherUser: User;
let roleHolder: User;
let role: Role;
let scrap: Resource;
let ore: Resource;
let asset: Asset;
const created = {
users: [] as number[],
roles: [] as number[],
resources: [] as number[],
assets: [] as number[],
blueprints: [] as number[],
structures: [] as number[],
technologies: [] as number[],
classifications: [] as number[],
staffing: [] as number[],
};
// --- fixtures --------------------------------------------------------------
async function makeUser(label: string, roleDocs?: number[]): Promise<User> {
const doc = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: `${RUN} ${label}`.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
roleDocs,
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
created.users.push(doc.id);
return doc;
}
async function makeResource(label: string, massPerUnit: number): Promise<Resource> {
const doc = (await payload.create({
collection: "resources",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
massPerUnit,
gridWidth: 1,
gridHeight: 1,
},
overrideAccess: true,
depth: 0,
})) as unknown as Resource;
created.resources.push(doc.id);
return doc;
}
async function makeAsset(label: string): Promise<Asset> {
const doc = (await payload.create({
collection: "assets",
data: {
name: `${RUN} ${label}`,
className: "test",
assetType: "miscellaneous",
approvalStatus: "in_progress",
tradeable: false,
isLive: true,
crafting: { craftable: false, craftingData: { craftingTimePerUnit: 1, batchSize: 1 } },
storageDimensions: { gridWidth: 1, gridHeight: 1 },
},
overrideAccess: true,
depth: 0,
})) as unknown as Asset;
created.assets.push(doc.id);
return doc;
}
async function makeBlueprint(
label: string,
maxCapacityMass: number | null = null,
moduleOptions?: Structure["moduleOptions"],
): Promise<Structure> {
const doc = (await payload.create({
collection: "structures",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
approvalStatus: "in_progress",
description: LEXICAL_EMPTY as unknown as Structure["description"],
category: "logistics",
materials: [{ resource: scrap.id, amount: 1 }],
constructionDurationMinutes: 1,
terrainType: "land",
maxHealth: 100,
maxCapacityMass,
moduleOptions,
},
overrideAccess: true,
depth: 0,
})) as unknown as Structure;
created.blueprints.push(doc.id);
return doc;
}
async function makeTechnology(label: string): Promise<Technology> {
const doc = (await payload.create({
collection: "technologies",
data: {
name: `${RUN} ${label}`,
approvalStatus: "approved",
type: "upgrade",
summary: "Interior gate fixture",
researchCosts: { resources: [], minimumResearchDuration: 1 },
},
overrideAccess: true,
depth: 0,
})) as unknown as Technology;
created.technologies.push(doc.id);
return doc;
}
async function makeClassification(label: string): Promise<{ id: number; key: string }> {
const key = `${RUN}-${label}`;
const doc = (await payload.create({
collection: "labor-classifications",
data: {
name: `${RUN} ${label}`,
key,
defaultUnitSalary: 1,
availableHeadcount: 10,
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
created.classifications.push(doc.id);
return { id: doc.id, key };
}
async function makeStaffing(args: {
structureId: number;
classificationId: number;
headcount: number;
status?: "active" | "terminated";
}): Promise<void> {
const doc = (await payload.create({
collection: "npc-staffing",
data: {
structure: args.structureId,
positionType: "labor",
positionTitle: `${RUN} crew`,
headcount: args.headcount,
laborClassification: args.classificationId,
status: args.status ?? "active",
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
created.staffing.push(doc.id);
}
async function makeStructure(args: {
label: string;
blueprintId: number;
rooms: InteriorBlueprintRoom[];
}): Promise<GameStructure> {
const doc = (await payload.create({
collection: "game-structures",
data: {
name: `${RUN} ${args.label}`,
type: args.blueprintId,
constructionStatus: "complete",
interior: {
rooms: args.rooms as unknown as Record<string, unknown>[],
interiorAccess: { mode: "anyone" },
},
},
overrideAccess: true,
depth: 0,
})) as unknown as GameStructure;
created.structures.push(doc.id);
return doc;
}
async function fetchStructure(id: number): Promise<GameStructure> {
return (await payload.findByID({
collection: "game-structures",
id,
depth: 0,
overrideAccess: true,
})) as unknown as GameStructure;
}
async function roomByKey(structureId: number, roomKey: string): Promise<StructureRoom> {
const result = await payload.find({
collection: "structure-rooms",
where: {
AND: [{ structure: { equals: structureId } }, { roomKey: { equals: roomKey } }],
},
limit: 1,
depth: 0,
overrideAccess: true,
});
const room = result.docs[0];
if (!room) throw new Error(`room ${roomKey} not found on structure ${structureId}`);
return room as unknown as StructureRoom;
}
async function roomById(id: number): Promise<StructureRoom> {
return (await payload.findByID({
collection: "structure-rooms",
id,
depth: 0,
overrideAccess: true,
})) as unknown as StructureRoom;
}
async function jobById(id: number): Promise<InteriorJob> {
return (await payload.findByID({
collection: "interior-jobs",
id,
depth: 0,
overrideAccess: true,
})) as unknown as InteriorJob;
}
async function maxNotificationId(userId: number): Promise<number> {
const result = await payload.find({
collection: "user-notifications",
where: { user: { equals: userId } },
sort: "-id",
limit: 1,
depth: 0,
overrideAccess: true,
});
return result.docs[0]?.id ?? 0;
}
// --- setup / teardown ------------------------------------------------------
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
scrap = await makeResource("scrap", 1);
ore = await makeResource("ore", 1);
asset = await makeAsset("kit");
role = (await payload.create({
collection: "roles",
data: {
name: `${RUN}-interior-role`,
slug: `${RUN}-interior-role`,
description: "Interior access fixture role",
permissions: [],
isSystem: false,
isSuperuser: false,
},
overrideAccess: true,
depth: 0,
})) as unknown as Role;
created.roles.push(role.id);
member = await makeUser("member");
otherUser = await makeUser("other");
roleHolder = await makeUser("role-holder", [role.id]);
});
afterAll(async () => {
const structureIds = created.structures;
// Bulk where-deletes (not per-row round-trips): this hook races vitest's
// timeout otherwise, and orphan deletes bleeding into the next file
// cross-contaminate its row counts.
const bulk = (collection: Parameters<typeof payload.delete>[0]["collection"], where: unknown) =>
payload.delete({ collection, where: where as never, overrideAccess: true } as never).catch(() => {});
if (created.staffing.length > 0) await bulk("npc-staffing", { id: { in: created.staffing } });
if (structureIds.length > 0) {
// Rooms and jobs cross-reference each other (room.pendingJob -> job,
// job.room -> room): clear the pointer first, then children, then parents.
await payload
.update({
collection: "structure-rooms",
where: { structure: { in: structureIds } },
data: { pendingJob: null },
overrideAccess: true,
} as never)
.catch(() => {});
await bulk("interior-jobs", { structure: { in: structureIds } });
await bulk("structure-rooms", { structure: { in: structureIds } });
await bulk("game-structures", { id: { in: structureIds } });
const events = await payload
.find({
collection: "game-event-logs",
where: { targetId: { in: structureIds } },
limit: 200,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
if (events && events.totalDocs > 0) {
await bulk(
"game-event-logs",
{ id: { in: events.docs.map((e) => e.id) } },
);
}
}
for (const id of created.blueprints) {
await payload.delete({ collection: "structures", id, overrideAccess: true }).catch(() => {});
}
for (const id of created.classifications) {
await payload
.delete({ collection: "labor-classifications", id, overrideAccess: true })
.catch(() => {});
}
// Researched technologies refuse deletion, so clear the stamp first.
for (const id of created.technologies) {
await payload
.update({
collection: "technologies",
id,
data: { researchedAt: null },
overrideAccess: true,
})
.catch(() => {});
await payload.delete({ collection: "technologies", id, overrideAccess: true }).catch(() => {});
}
for (const id of created.assets) {
await payload.delete({ collection: "assets", id, overrideAccess: true }).catch(() => {});
}
for (const id of created.resources) {
await payload.delete({ collection: "resources", id, overrideAccess: true }).catch(() => {});
}
if (created.users.length > 0) {
// Bulk-delete notifications (where-based) so this hook never trips its timeout.
await payload
.delete({
collection: "user-notifications",
where: { user: { in: created.users } },
overrideAccess: true,
} as never)
.catch(() => {});
}
for (const id of created.users) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
for (const id of created.roles) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
}
}, 60_000);
// --- tests -----------------------------------------------------------------
describe("Interior provisioning", () => {
it("creates one runtime room per blueprint room, seeds level/junk/fixtures, and is idempotent", async () => {
const blueprint = await makeBlueprint("provision-blueprint");
const structure = await makeStructure({
label: "provision-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "bay",
name: "Loading Bay",
initialLevel: 1,
maxLevel: 2,
fixtures: [{ key: "crate", name: "Crate Rack" }],
},
{
key: "vault",
name: "Vault",
initialLevel: 0,
maxLevel: 1,
decay: { initialJunkLevel: 3 },
},
],
});
const first = await provisionInterior(payload, await fetchStructure(structure.id));
expect(first).toEqual({ provisioned: true, rooms: 2 });
const rows = await payload.find({
collection: "structure-rooms",
where: { structure: { equals: structure.id } },
limit: 10,
depth: 0,
overrideAccess: true,
});
expect(rows.docs).toHaveLength(2);
const bay = await roomByKey(structure.id, "bay");
expect(bay.level).toBe(1);
expect(bay.junkLevel).toBe(0);
expect(bay.condition).toBe(100);
expect(bay.fixtures).toHaveLength(1);
expect(bay.fixtures?.[0]).toMatchObject({ key: "crate", name: "Crate Rack", broken: false });
const vault = await roomByKey(structure.id, "vault");
expect(vault.level).toBe(0);
expect(vault.junkLevel).toBe(3);
const stamped = await fetchStructure(structure.id);
expect(stamped.interior?.provisionedAt).toBeTruthy();
const provisionedAt = stamped.interior?.provisionedAt;
// Second call is a no-op: no duplicate rows, stamp untouched.
const second = await provisionInterior(payload, await fetchStructure(structure.id));
expect(second).toEqual({ provisioned: false, rooms: 0 });
const rowsAgain = await payload.find({
collection: "structure-rooms",
where: { structure: { equals: structure.id } },
limit: 10,
depth: 0,
overrideAccess: true,
});
expect(rowsAgain.docs).toHaveLength(2);
expect((await fetchStructure(structure.id)).interior?.provisionedAt).toBe(provisionedAt);
});
});
describe("Interior access modes", () => {
it("honours anyone, specific users, and specific roles", async () => {
const memberLike = { id: member.id, roleDocs: [] };
await expect(
canUserEnterInterior(payload, memberLike, {
interior: { interiorAccess: { mode: "anyone" } },
}),
).resolves.toBe(true);
// mode=users: only the listed user passes.
await expect(
canUserEnterInterior(payload, memberLike, {
interior: { interiorAccess: { mode: "users", users: [otherUser.id] } },
}),
).resolves.toBe(false);
await expect(
canUserEnterInterior(payload, memberLike, {
interior: { interiorAccess: { mode: "users", users: [otherUser.id, member.id] } },
}),
).resolves.toBe(true);
// mode=roles: a member with no roleDocs fails even when the role is listed.
await expect(
canUserEnterInterior(payload, memberLike, {
interior: { interiorAccess: { mode: "roles", roles: [role.id] } },
}),
).resolves.toBe(false);
await expect(
canUserEnterInterior(
payload,
{ id: roleHolder.id, roleDocs: [role.id] },
{ interior: { interiorAccess: { mode: "roles", roles: [role.id] } } },
),
).resolves.toBe(true);
// No snapshot access config defaults to anyone.
await expect(canUserEnterInterior(payload, memberLike, { interior: {} })).resolves.toBe(
true,
);
});
});
describe("Interior job start gates", () => {
let structureId: number;
beforeAll(async () => {
const blueprint = await makeBlueprint("gates-blueprint");
const structure = await makeStructure({
label: "gates-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "hall",
name: "Hall",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
},
{
key: "cellar",
name: "Cellar",
initialLevel: 0,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
decay: { initialJunkLevel: 0 },
},
{
key: "busy",
name: "Busy Room",
initialLevel: 0,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
decay: { initialJunkLevel: 2 },
},
{
key: "workshop",
name: "Workshop",
initialLevel: 1,
maxLevel: 2,
levels: [
{ level: 1, upgradeDurationMinutes: 5 },
{
level: 2,
upgradeDurationMinutes: 5,
upgradeMaterials: [{ resource: numericRef(scrap.id), amount: 10 }],
},
],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
structureId = structure.id;
});
it("rejects open on an already-open room and cleanup with no junk", async () => {
const open = await startInteriorJob(payload, { id: member.id }, {
structureId,
roomKey: "hall",
type: "open",
});
expect(open).toEqual({ ok: false, error: "already_open" });
const cleanup = await startInteriorJob(payload, { id: member.id }, {
structureId,
roomKey: "cellar",
type: "cleanup",
});
expect(cleanup).toEqual({ ok: false, error: "nothing_to_cleanup" });
});
it("rejects any job while the room's output slot is occupied", async () => {
const room = await roomByKey(structureId, "busy");
const now = new Date().toISOString();
const blocker = (await payload.create({
collection: "interior-jobs",
data: {
structure: structureId,
room: room.id,
type: "open",
status: "collected",
targetLevel: 1,
startedBy: member.id,
startedAt: now,
endsAt: now,
},
overrideAccess: true,
depth: 0,
})) as unknown as InteriorJob;
await payload.update({
collection: "structure-rooms",
id: room.id,
data: { pendingJob: blocker.id },
overrideAccess: true,
});
const busy = await startInteriorJob(payload, { id: member.id }, {
structureId,
roomKey: "busy",
type: "cleanup",
});
expect(busy).toEqual({ ok: false, error: "room_busy" });
// Release the slot so the room cannot block later fixtures.
await payload.update({
collection: "structure-rooms",
id: room.id,
data: { pendingJob: null },
overrideAccess: true,
});
});
it("rejects an upgrade whose materials are not in storage", async () => {
const upgrade = await startInteriorJob(payload, { id: member.id }, {
structureId,
roomKey: "workshop",
type: "upgrade",
target: 2,
});
expect(upgrade).toEqual({ ok: false, error: "insufficient_resources" });
expect((await roomByKey(structureId, "workshop")).pendingJob).toBeNull();
});
});
describe("Interior snapshot bootstrap from blueprint", () => {
it("copies an authored blueprint interior into the runtime snapshot on first entry and never retargets", async () => {
const blueprint = await makeBlueprint("bootstrap-blueprint");
const authoredRooms = [
{
key: "hall",
name: "Hall",
hotspot: { x: 5, y: 5, width: 40, height: 40 },
initialLevel: 1,
maxLevel: 2,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
},
];
await payload.update({
collection: "structures",
id: blueprint.id,
overrideAccess: true,
data: {
interiorEnabled: true,
rooms: authoredRooms,
interiorAccess: { mode: "anyone" },
} as Record<string, unknown>,
});
// A game structure created WITHOUT any interior snapshot.
const fresh = (await payload.create({
collection: "game-structures",
data: {
name: `${RUN} bootstrap-structure`,
type: blueprint.id,
constructionStatus: "complete",
},
overrideAccess: true,
depth: 0,
})) as unknown as GameStructure;
created.structures.push(fresh.id);
const first = await provisionInterior(payload, await fetchStructure(fresh.id));
expect(first).toEqual({ provisioned: true, rooms: 1 });
let stored = await fetchStructure(fresh.id);
const snapshotRooms = stored.interior?.rooms as Array<Record<string, unknown>>;
expect(Array.isArray(snapshotRooms) && snapshotRooms.length).toBe(1);
expect(snapshotRooms[0]?.key).toBe("hall");
expect((stored.interior as { provisionedAt?: string }).provisionedAt).toBeTruthy();
const hall = await roomByKey(fresh.id, "hall");
expect(hall.level).toBe(1);
// Editing the blueprint afterwards must not retarget the live snapshot.
await payload.update({
collection: "structures",
id: blueprint.id,
overrideAccess: true,
data: {
rooms: [
{ key: "hall", name: "Hall", hotspot: { x: 5, y: 5, width: 40, height: 40 }, initialLevel: 1, maxLevel: 2, levels: [] },
{ key: "wing", name: "Wing", hotspot: { x: 55, y: 5, width: 40, height: 40 }, initialLevel: 0, maxLevel: 1, levels: [] },
],
} as Record<string, unknown>,
});
const second = await provisionInterior(payload, await fetchStructure(fresh.id));
expect(second.provisioned).toBe(false);
stored = await fetchStructure(fresh.id);
const after = stored.interior?.rooms as Array<Record<string, unknown>>;
expect(after.length).toBe(1);
});
});
describe("Interior cancel refund and collect credit", () => {
it("withdraws committed materials at start, refunds them on cancel, and credits them on collect", async () => {
const blueprint = await makeBlueprint("refund-blueprint", 1000);
const structure = await makeStructure({
label: "refund-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "workshop",
name: "Workshop",
initialLevel: 1,
maxLevel: 2,
levels: [
{ level: 1, upgradeDurationMinutes: 5 },
{
level: 2,
upgradeDurationMinutes: 5,
upgradeMaterials: [{ resource: numericRef(scrap.id), amount: 10 }],
},
],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const room = await roomByKey(structure.id, "workshop");
const deposit = await depositToStructure(payload, structure.id, scrap.id, 40);
expect(deposit.ok).toBe(true);
expect(await storedAmount(payload, structure.id, scrap.id)).toBe(40);
const started = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "workshop",
type: "upgrade",
target: 2,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
expect(started.job.status).toBe("active");
expect(await storedAmount(payload, structure.id, scrap.id)).toBe(30);
const cancelled = await cancelInteriorJob(payload, { id: member.id }, started.job.id);
expect(cancelled.ok).toBe(true);
const cancelledJob = await jobById(started.job.id);
expect(cancelledJob.status).toBe("cancelled");
expect(cancelledJob.output?.resources).toHaveLength(1);
expect(Number(cancelledJob.output?.resources?.[0]?.resource)).toBe(scrap.id);
expect(cancelledJob.output?.resources?.[0]?.amount).toBe(10);
// The output slot stays occupied by the parked refund until it is collected.
expect((await roomById(room.id)).pendingJob).toBe(started.job.id);
const busyStart = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "workshop",
type: "cleanup",
});
expect(!busyStart.ok && busyStart.error === "room_busy").toBe(true);
// The refund is credited on the normal collect path, straight from
// `cancelled` - no status faking required.
const collected = await collectInteriorJob(payload, { id: member.id }, started.job.id);
expect(collected.ok).toBe(true);
expect(await storedAmount(payload, structure.id, scrap.id)).toBe(40);
const collectedJob = await jobById(started.job.id);
expect(collectedJob.status).toBe("collected");
expect(collectedJob.collectedBy).toBe(member.id);
expect((await roomById(room.id)).pendingJob).toBeNull();
});
});
describe("Interior collect refusal", () => {
it("refuses collection when the output does not fit and leaves the job parked", async () => {
const blueprint = await makeBlueprint("full-blueprint", 100);
const structure = await makeStructure({
label: "full-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "vault",
name: "Vault",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const room = await roomByKey(structure.id, "vault");
const now = new Date().toISOString();
const job = (await payload.create({
collection: "interior-jobs",
data: {
structure: structure.id,
room: room.id,
type: "open",
status: "awaiting_collect",
targetLevel: 1,
startedBy: member.id,
startedAt: now,
endsAt: now,
// 150 units × 1 kg exceeds the blueprint's 100 kg capacity.
output: { resources: [{ resource: scrap.id, amount: 150 }] },
},
overrideAccess: true,
depth: 0,
})) as unknown as InteriorJob;
await payload.update({
collection: "structure-rooms",
id: room.id,
data: { pendingJob: job.id },
overrideAccess: true,
});
const result = await collectInteriorJob(payload, { id: member.id }, job.id);
expect(result).toEqual({ ok: false, error: "storage_full" });
expect((await jobById(job.id)).status).toBe("awaiting_collect");
expect((await roomById(room.id)).pendingJob).toBe(job.id);
expect(await storedAmount(payload, structure.id, scrap.id)).toBe(0);
});
});
describe("Interior job sweep", () => {
it("completes due jobs, applies open/cleanup effects, notifies the starter, and is idempotent", async () => {
const blueprint = await makeBlueprint("sweep-blueprint", 1000);
const structure = await makeStructure({
label: "sweep-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "vault",
name: "Vault",
initialLevel: 0,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 0 }],
},
{
key: "storage",
name: "Storage",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
decay: { initialJunkLevel: 2 },
junkLoot: [
{ kind: "resource", item: numericRef(scrap.id), amountMin: 5, amountMax: 5, weight: 1 },
],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const openStart = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "vault",
type: "open",
});
expect(openStart.ok).toBe(true);
if (!openStart.ok) return;
const cleanupStart = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "storage",
type: "cleanup",
});
expect(cleanupStart.ok).toBe(true);
if (!cleanupStart.ok) return;
const lastNotificationId = await maxNotificationId(member.id);
const futureNow = new Date(Date.now() + 24 * 60 * 60 * 1000);
const sweep = await sweepInteriorJobs(payload, futureNow);
expect(sweep).toEqual({ completed: 2, errors: 0 });
const openJob = await jobById(openStart.job.id);
expect(openJob.status).toBe("awaiting_collect");
expect((await roomByKey(structure.id, "vault")).level).toBe(1);
const cleanupJob = await jobById(cleanupStart.job.id);
expect(cleanupJob.status).toBe("awaiting_collect");
expect(cleanupJob.output?.resources).toHaveLength(1);
expect(Number(cleanupJob.output?.resources?.[0]?.resource)).toBe(scrap.id);
expect(cleanupJob.output?.resources?.[0]?.amount).toBe(5);
expect((await roomByKey(structure.id, "storage")).junkLevel).toBe(1);
const notifications = await payload.find({
collection: "user-notifications",
where: {
AND: [{ user: { equals: member.id } }, { id: { greater_than: lastNotificationId } }],
},
limit: 10,
depth: 0,
overrideAccess: true,
});
expect(notifications.docs).toHaveLength(2);
expect(notifications.docs.every((n) => n.type === "interior:job-ready")).toBe(true);
// Idempotent: nothing is active any more.
const secondSweep = await sweepInteriorJobs(payload, futureNow);
expect(secondSweep).toEqual({ completed: 0, errors: 0 });
expect((await jobById(openStart.job.id)).status).toBe("awaiting_collect");
expect((await jobById(cleanupStart.job.id)).status).toBe("awaiting_collect");
});
});
describe("Interior upgrade completion", () => {
it("advances the room to the target level and clamps at maxLevel", async () => {
const blueprint = await makeBlueprint("upgrade-blueprint", 1000);
const structure = await makeStructure({
label: "upgrade-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "office",
name: "Office",
initialLevel: 1,
maxLevel: 3,
levels: [
{ level: 1, upgradeDurationMinutes: 5 },
{ level: 2, upgradeDurationMinutes: 5 },
{ level: 3, upgradeDurationMinutes: 5 },
],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const first = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "office",
type: "upgrade",
target: 2,
});
expect(first.ok).toBe(true);
if (!first.ok) return;
expect(await completeInteriorJob(payload, first.job.id)).toEqual({ ok: true });
expect((await roomByKey(structure.id, "office")).level).toBe(2);
// Collecting frees the output slot so the room can upgrade again.
expect(await collectInteriorJob(payload, { id: member.id }, first.job.id)).toEqual({
ok: true,
});
// A target above the authored ceiling is clamped to maxLevel.
const second = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "office",
type: "upgrade",
target: 99,
});
expect(second.ok).toBe(true);
if (!second.ok) return;
expect(await completeInteriorJob(payload, second.job.id)).toEqual({ ok: true });
expect((await roomByKey(structure.id, "office")).level).toBe(3);
});
it("scales the job duration by room level, installed module speed, and condition", async () => {
const moduleName = `${RUN} Fast Lift`;
const blueprint = await makeBlueprint("speed-blueprint", null, [
{
name: moduleName,
category: "utility",
effects: [{ type: "interior_job_speed", value: 0.5 }],
materials: [{ resource: scrap.id, amount: 1 }],
},
]);
const structure = await makeStructure({
label: "speed-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "bay",
name: "Bay",
initialLevel: 1,
maxLevel: 2,
levels: [
{
level: 1,
upgradeDurationMinutes: 10,
effects: [{ type: "production_speed", value: 0.25 }],
},
{ level: 2, upgradeDurationMinutes: 10 },
],
},
],
});
await payload.update({
collection: "game-structures",
id: structure.id,
data: { installedModules: [{ name: moduleName, installedAt: new Date().toISOString() }] },
overrideAccess: true,
});
await provisionInterior(payload, await fetchStructure(structure.id));
const started = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "bay",
type: "upgrade",
target: 2,
});
expect(started.ok).toBe(true);
if (!started.ok) return;
// 10 min base / (1.25 room speed x 1.5 module speed x 1.0 condition).
const durationMs =
new Date(started.job.endsAt as string).getTime() -
new Date(started.job.startedAt as string).getTime();
expect(durationMs).toBe(320_000);
});
});
describe("Interior tech and labor gates", () => {
it("rejects an upgrade whose required technology is not researched, then allows it once researched", async () => {
const tech = await makeTechnology("fabrication");
const blueprint = await makeBlueprint("tech-blueprint");
const structure = await makeStructure({
label: "tech-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "lab",
name: "Lab",
initialLevel: 1,
maxLevel: 2,
levels: [
{ level: 1, upgradeDurationMinutes: 5 },
{
level: 2,
upgradeDurationMinutes: 5,
requiredTech: [numericRef(tech.id)],
},
],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const blocked = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "lab",
type: "upgrade",
target: 2,
});
expect(blocked).toEqual({ ok: false, error: "tech_locked" });
expect((await roomByKey(structure.id, "lab")).pendingJob).toBeNull();
await payload.update({
collection: "technologies",
id: tech.id,
data: { researchedAt: new Date().toISOString() },
overrideAccess: true,
});
const started = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "lab",
type: "upgrade",
target: 2,
});
expect(started.ok).toBe(true);
});
it("rejects an upgrade without enough active labor of the required classification", async () => {
const classification = await makeClassification("mechanic");
const blueprint = await makeBlueprint("labor-blueprint");
const structure = await makeStructure({
label: "labor-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "garage",
name: "Garage",
initialLevel: 1,
maxLevel: 2,
levels: [
{ level: 1, upgradeDurationMinutes: 5 },
{
level: 2,
upgradeDurationMinutes: 5,
requiredLaborClass: classification.key,
requiredHeadcount: 2,
},
],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const unstaffed = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "garage",
type: "upgrade",
target: 2,
});
expect(unstaffed).toEqual({ ok: false, error: "labor_insufficient" });
// Terminated staff and other classifications do not count.
await makeStaffing({
structureId: structure.id,
classificationId: classification.id,
headcount: 2,
status: "terminated",
});
const otherClassification = await makeClassification("welder");
await makeStaffing({
structureId: structure.id,
classificationId: otherClassification.id,
headcount: 2,
});
const wrongClass = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "garage",
type: "upgrade",
target: 2,
});
expect(wrongClass).toEqual({ ok: false, error: "labor_insufficient" });
// Two active workers of the right classification satisfy the requirement.
await makeStaffing({
structureId: structure.id,
classificationId: classification.id,
headcount: 2,
});
const staffed = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "garage",
type: "upgrade",
target: 2,
});
expect(staffed.ok).toBe(true);
});
});
describe("applyInteriorDurationFactor", () => {
it("applies the 60-second floor to short jobs", () => {
expect(applyInteriorDurationFactor({ baseMs: 10_000, condition: 100 })).toBe(60_000);
expect(applyInteriorDurationFactor({ baseMs: 0, condition: 100 })).toBe(0);
});
it("floors the divisor at 0.1 when condition is below the effect floor", () => {
// Below the floor the condition factor is 0, so the divisor floors at 0.1:
// 10 minutes of work becomes 100 minutes.
expect(applyInteriorDurationFactor({ baseMs: 600_000, condition: 20, effectFloor: 30 })).toBe(
6_000_000,
);
// The 60-second minimum still applies to the scaled result.
expect(applyInteriorDurationFactor({ baseMs: 3_000, condition: 20, effectFloor: 30 })).toBe(
60_000,
);
});
it("returns 0 for a non-positive base duration", () => {
expect(applyInteriorDurationFactor({ baseMs: 0 })).toBe(0);
expect(applyInteriorDurationFactor({ baseMs: -5, condition: 0 })).toBe(0);
});
it("divides by the stacked level and module multipliers", () => {
expect(
applyInteriorDurationFactor({
baseMs: 600_000,
levelSpeedMultiplier: 2,
moduleSpeedMultiplier: 1.5,
condition: 100,
}),
).toBe(200_000);
// Half condition halves the factor: 100% condition -> 0.5x speed.
expect(applyInteriorDurationFactor({ baseMs: 600_000, condition: 50 })).toBe(1_200_000);
});
});
describe("applyOutputBonus", () => {
it("composes the level multiplier with the module bonus and rounds", () => {
expect(applyOutputBonus(10)).toBe(10);
expect(applyOutputBonus(10, 1.25)).toBe(13); // 12.5 rounds up
expect(applyOutputBonus(10, 1.25, 0.1)).toBe(14); // 13.5 rounds up
expect(applyOutputBonus(3, 1, 0.5)).toBe(5); // 4.5 rounds up
expect(applyOutputBonus(-5, 1, 0.5)).toBe(0); // never negative
});
});
describe("installedModuleEffects interior bonuses", () => {
it("aggregates interior job speed and output bonus additively", () => {
const blueprint = {
moduleOptions: [
{ name: "A", effects: [{ type: "interior_job_speed", value: 0.15 }] },
{
name: "B",
effects: [
{ type: "interior_job_speed", value: 0.1 },
{ type: "interior_output_bonus", value: 0.05 },
],
},
{ name: "C", effects: [{ type: "interior_output_bonus", value: 0.07 }] },
],
};
const effects = installedModuleEffects(blueprint, ["A", "B", "C"]);
expect(effects.interiorJobSpeed).toBeCloseTo(0.25, 10);
expect(effects.interiorOutputBonus).toBeCloseTo(0.12, 10);
// The legacy interior-neutral aggregates stay untouched.
expect(effects.capacityMass).toBe(0);
expect(effects.productionMultiplier).toBe(0);
expect(effects.storageSlots).toBe(0);
expect(installedModuleEffects(blueprint, ["Z"]).interiorJobSpeed).toBe(0);
expect(installedModuleEffects({}, []).interiorOutputBonus).toBe(0);
});
});
describe("rollJunkLoot", () => {
const entries: JunkLootEntry[] = [
{ kind: "resource", item: { id: 101 }, amountMin: 1, amountMax: 3, weight: 1 },
{ kind: "asset", item: { id: 202 }, amountMin: 2, amountMax: 2, weight: 1 },
];
it("picks a weighted entry deterministically from an injected rng", () => {
const first = rollJunkLoot(entries, () => 0);
expect(first.resources).toEqual([{ resource: { id: 101 }, amount: 1 }]);
expect(first.assets).toEqual([]);
const rolls = [0.999, 0.999];
let index = 0;
const last = rollJunkLoot(entries, () => rolls[index++] ?? 0.999);
expect(last.resources).toEqual([]);
expect(last.assets).toEqual([{ asset: { id: 202 }, amount: 2 }]);
});
it("keeps rolled amounts inside [amountMin, amountMax]", () => {
const singleEntry: JunkLootEntry[] = [
{ kind: "resource", item: numericRef(5), amountMin: 2, amountMax: 6, weight: 1 },
];
for (const amountRoll of [0, 0.1, 0.5, 0.9, 0.999]) {
let calls = 0;
const result = rollJunkLoot(singleEntry, () => (calls++ === 0 ? 0 : amountRoll));
expect(result.resources).toHaveLength(1);
const amount = (result.resources[0] as { amount: number }).amount;
expect(amount).toBeGreaterThanOrEqual(2);
expect(amount).toBeLessThanOrEqual(6);
}
});
it("returns empty results for an empty or missing loot table", () => {
expect(rollJunkLoot(undefined, () => 0)).toEqual({ resources: [], assets: [] });
expect(rollJunkLoot([], () => 0)).toEqual({ resources: [], assets: [] });
expect(
rollJunkLoot(
[{ kind: "resource", item: numericRef(5), amountMin: 1, amountMax: 1, weight: 0 }],
() => 0,
),
).toEqual({ resources: [], assets: [] });
});
});
describe("Interior produce output", () => {
it("consumes recipe inputs at start and records the scaled resource output", async () => {
const blueprint = await makeBlueprint("produce-blueprint", 1000);
const structure = await makeStructure({
label: "produce-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "forge",
name: "Forge",
initialLevel: 1,
maxLevel: 1,
levels: [
{
level: 1,
upgradeDurationMinutes: 5,
effects: [{ type: "output_bonus", value: 0.25 }],
},
],
station: {
name: "Workbench",
enabled: true,
recipes: [
{
key: "smelt",
name: "Smelt",
durationMinutes: 10,
inputs: [{ resource: numericRef(ore.id), amount: 4 }],
outputs: [{ kind: "resource", item: numericRef(ore.id), amount: 10 }],
},
],
},
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
expect((await depositToStructure(payload, structure.id, ore.id, 10)).ok).toBe(true);
const started = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "forge",
type: "produce",
target: "smelt",
});
expect(started.ok).toBe(true);
if (!started.ok) return;
// Inputs are withdrawn at start; the output is only recorded on the job.
expect(await storedAmount(payload, structure.id, ore.id)).toBe(6);
const job = await jobById(started.job.id);
expect(job.committedResources).toHaveLength(1);
expect(Number(job.committedResources?.[0]?.resource)).toBe(ore.id);
expect(job.committedResources?.[0]?.amount).toBe(4);
expect(job.output?.resources).toHaveLength(1);
expect(Number(job.output?.resources?.[0]?.resource)).toBe(ore.id);
expect(job.output?.resources?.[0]?.amount).toBe(applyOutputBonus(10, 1.25, 0));
});
it("rejects a disabled recipe", async () => {
const blueprint = await makeBlueprint("disabled-recipe-blueprint");
const structure = await makeStructure({
label: "disabled-recipe-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "line",
name: "Line",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
station: {
name: "Workbench",
enabled: true,
recipes: [{ key: "off", name: "Off", enabled: false, durationMinutes: 1 }],
},
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const started = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "line",
type: "produce",
target: "off",
});
expect(started).toEqual({ ok: false, error: "recipe_disabled" });
});
});
describe("Interior presence-based unlocks", () => {
it("gates only recipes named by an unlocks_recipe effect", async () => {
const blueprint = await makeBlueprint("recipe-unlock-blueprint");
const structure = await makeStructure({
label: "recipe-unlock-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "lab",
name: "Lab",
initialLevel: 1,
maxLevel: 2,
levels: [
{ level: 1, upgradeDurationMinutes: 5 },
{
level: 2,
upgradeDurationMinutes: 5,
effects: [{ type: "unlocks_recipe", target: "gated" }],
},
],
station: {
name: "Workbench",
enabled: true,
recipes: [
{ key: "gated", name: "Gated", durationMinutes: 1 },
{ key: "plain", name: "Plain", durationMinutes: 1 },
],
},
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const gated = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "lab",
type: "produce",
target: "gated",
});
expect(gated).toEqual({ ok: false, error: "recipe_locked" });
// A recipe never mentioned by an unlocks_recipe effect is available.
const plain = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "lab",
type: "produce",
target: "plain",
});
expect(plain.ok).toBe(true);
if (!plain.ok) return;
expect((await cancelInteriorJob(payload, { id: member.id }, plain.job.id)).ok).toBe(true);
// Collecting the parked cancellation releases the room's output slot.
expect(
(await collectInteriorJob(payload, { id: member.id }, plain.job.id)).ok,
).toBe(true);
// Raising the runtime room level applies the unlocking level's effects.
await payload.update({
collection: "structure-rooms",
id: (await roomByKey(structure.id, "lab")).id,
data: { level: 2 },
overrideAccess: true,
});
const unlocked = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "lab",
type: "produce",
target: "gated",
});
expect(unlocked.ok).toBe(true);
});
it("gates only stations named by an unlocks_station effect", async () => {
const blueprint = await makeBlueprint("station-unlock-blueprint");
const structure = await makeStructure({
label: "station-unlock-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "shop",
name: "Shop",
initialLevel: 1,
maxLevel: 2,
levels: [
{ level: 1, upgradeDurationMinutes: 5 },
{
level: 2,
upgradeDurationMinutes: 5,
effects: [{ type: "unlocks_station", target: "Workbench" }],
},
],
station: {
name: "Workbench",
enabled: true,
recipes: [{ key: "build", name: "Build", durationMinutes: 1 }],
},
},
{
key: "bench",
name: "Bench",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
station: {
name: "Plain Bench",
enabled: true,
recipes: [{ key: "build", name: "Build", durationMinutes: 1 }],
},
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const locked = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "shop",
type: "produce",
target: "build",
});
expect(locked).toEqual({ ok: false, error: "station_locked" });
// A station whose room mentions no unlocks_station effect is never gated.
const ungated = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "bench",
type: "produce",
target: "build",
});
expect(ungated.ok).toBe(true);
await payload.update({
collection: "structure-rooms",
id: (await roomByKey(structure.id, "shop")).id,
data: { level: 2 },
overrideAccess: true,
});
const unlocked = await startInteriorJob(payload, { id: member.id }, {
structureId: structure.id,
roomKey: "shop",
type: "produce",
target: "build",
});
expect(unlocked.ok).toBe(true);
});
});
describe("Interior asset output credit", () => {
let assetOutputsWereEnabled = false;
const setAssetOutputsEnabled = async (enabled: boolean) => {
const rules = await payload.findGlobal({ slug: "game-rules", depth: 0, overrideAccess: true });
await payload.updateGlobal({
slug: "game-rules",
data: {
interior: {
decayEnabled: rules.interior?.decayEnabled ?? false,
decayMultiplier: rules.interior?.decayMultiplier ?? 1,
assetOutputsEnabled: enabled,
},
},
overrideAccess: true,
});
};
const makeStructureWithRoom = async (label: string): Promise<GameStructure> => {
const blueprint = await makeBlueprint(`${label}-blueprint`, 1000);
const structure = await makeStructure({
label: `${label}-structure`,
blueprintId: blueprint.id,
rooms: [
{
key: "locker",
name: "Locker",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
return structure;
};
const makeAwaitingAssetJob = async (
structureId: number,
amount: number,
): Promise<InteriorJob> => {
const room = await roomByKey(structureId, "locker");
const now = new Date().toISOString();
return (await payload.create({
collection: "interior-jobs",
data: {
structure: structureId,
room: room.id,
type: "produce",
status: "awaiting_collect",
targetLevel: 1,
startedBy: member.id,
startedAt: now,
endsAt: now,
output: { assets: [{ asset: asset.id, amount }] },
},
overrideAccess: true,
depth: 0,
})) as unknown as InteriorJob;
};
beforeAll(async () => {
const rules = await payload.findGlobal({ slug: "game-rules", depth: 0, overrideAccess: true });
assetOutputsWereEnabled = Boolean(rules.interior?.assetOutputsEnabled);
await setAssetOutputsEnabled(false);
});
afterAll(async () => {
await setAssetOutputsEnabled(assetOutputsWereEnabled);
});
it("refuses asset outputs while the master switch is off", async () => {
const structure = await makeStructureWithRoom("asset-off");
const job = await makeAwaitingAssetJob(structure.id, 2);
const collected = await collectInteriorJob(payload, { id: member.id }, job.id);
expect(collected).toEqual({ ok: false, error: "asset_outputs_disabled" });
expect((await jobById(job.id)).status).toBe("awaiting_collect");
expect((await fetchStructure(structure.id)).storedAssets ?? []).toHaveLength(0);
});
it("credits assets once enabled and merges repeat outputs into one row", async () => {
await setAssetOutputsEnabled(true);
const structure = await makeStructureWithRoom("asset-on");
const first = await makeAwaitingAssetJob(structure.id, 2);
expect(await collectInteriorJob(payload, { id: member.id }, first.id)).toEqual({ ok: true });
const afterFirst = (await fetchStructure(structure.id)).storedAssets ?? [];
expect(afterFirst).toHaveLength(1);
expect(Number(afterFirst[0]?.asset)).toBe(asset.id);
expect(afterFirst[0]?.quantity).toBe(2);
const second = await makeAwaitingAssetJob(structure.id, 3);
expect(await collectInteriorJob(payload, { id: member.id }, second.id)).toEqual({ ok: true });
const afterSecond = (await fetchStructure(structure.id)).storedAssets ?? [];
expect(afterSecond).toHaveLength(1);
expect(Number(afterSecond[0]?.asset)).toBe(asset.id);
expect(afterSecond[0]?.quantity).toBe(5);
});
it("credits resource outputs of a mixed job while its asset leg stays parked", async () => {
await setAssetOutputsEnabled(false);
const blueprint = await makeBlueprint("mixed-blueprint", 1000);
const structure = await makeStructure({
label: "mixed-structure",
blueprintId: blueprint.id,
rooms: [
{
key: "bay",
name: "Bay",
initialLevel: 1,
maxLevel: 1,
levels: [{ level: 1, upgradeDurationMinutes: 5 }],
},
],
});
await provisionInterior(payload, await fetchStructure(structure.id));
const room = await roomByKey(structure.id, "bay");
const now = new Date().toISOString();
const job = (await payload.create({
collection: "interior-jobs",
data: {
structure: structure.id,
room: room.id,
type: "produce",
status: "awaiting_collect",
targetLevel: 1,
startedBy: member.id,
startedAt: now,
endsAt: now,
output: {
resources: [{ resource: scrap.id, amount: 4 }],
assets: [{ asset: asset.id, amount: 1 }],
},
},
overrideAccess: true,
depth: 0,
})) as unknown as InteriorJob;
const first = await collectInteriorJob(payload, { id: member.id }, job.id);
expect(first).toEqual({ ok: false, error: "asset_outputs_disabled" });
// The whole collect is atomic: nothing was credited and the job stays parked.
expect(await storedAmount(payload, structure.id, scrap.id)).toBe(0);
expect((await jobById(job.id)).status).toBe("awaiting_collect");
// Enabling the switch lets the same job collect in full, exactly once.
await setAssetOutputsEnabled(true);
expect(await collectInteriorJob(payload, { id: member.id }, job.id)).toEqual({ ok: true });
expect(await storedAmount(payload, structure.id, scrap.id)).toBe(4);
const assets = (await fetchStructure(structure.id)).storedAssets ?? [];
expect(assets).toHaveLength(1);
expect(assets[0]?.quantity).toBe(1);
expect((await jobById(job.id)).status).toBe("collected");
});
});
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();
});
});
// Heavy suite: each test builds a full blueprint + instance and runs sweeps;
// under full-suite load the default 5s test budget flakes. Give them room.
describe("Interior decay", { timeout: 60_000 }, () => {
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);
// Release the slot before the final condition-0 probe in this same room.
expect(
(await collectInteriorJob(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);
});
});