import { getPayload, type Payload } from "payload"; import config from "@/payload.config"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import type { GameStructure, InteriorJob, Resource, Role, Structure, StructureRoom, User, } from "@/payload-types"; import { canUserEnterInterior } from "@/lib/interior/access"; import { cancelInteriorJob, collectInteriorJob, rollJunkLoot, startInteriorJob, } from "@/lib/interior/jobs"; 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; const created = { users: [] as number[], roles: [] as number[], resources: [] as number[], blueprints: [] as number[], structures: [] as number[], }; // --- fixtures -------------------------------------------------------------- async function makeUser(label: string, roleDocs?: number[]): Promise { 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 { 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 makeBlueprint( label: string, maxCapacityMass: number | null = null, ): Promise { 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, }, overrideAccess: true, depth: 0, })) as unknown as Structure; created.blueprints.push(doc.id); return doc; } async function makeStructure(args: { label: string; blueprintId: number; rooms: InteriorBlueprintRoom[]; }): Promise { 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[], interiorAccess: { mode: "anyone" }, }, }, overrideAccess: true, depth: 0, })) as unknown as GameStructure; created.structures.push(doc.id); return doc; } async function fetchStructure(id: number): Promise { return (await payload.findByID({ collection: "game-structures", id, depth: 0, overrideAccess: true, })) as unknown as GameStructure; } async function roomByKey(structureId: number, roomKey: string): Promise { 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 { return (await payload.findByID({ collection: "structure-rooms", id, depth: 0, overrideAccess: true, })) as unknown as StructureRoom; } async function jobById(id: number): Promise { return (await payload.findByID({ collection: "interior-jobs", id, depth: 0, overrideAccess: true, })) as unknown as InteriorJob; } async function maxNotificationId(userId: number): Promise { 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); 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; if (structureIds.length > 0) { const rooms = await payload .find({ collection: "structure-rooms", where: { structure: { in: structureIds } }, limit: 200, depth: 0, overrideAccess: true, }) .catch(() => null); for (const room of rooms?.docs ?? []) { await payload .update({ collection: "structure-rooms", id: room.id, data: { pendingJob: null }, overrideAccess: true, }) .catch(() => {}); } const jobs = await payload .find({ collection: "interior-jobs", where: { structure: { in: structureIds } }, limit: 200, depth: 0, overrideAccess: true, }) .catch(() => null); for (const job of jobs?.docs ?? []) { await payload .delete({ collection: "interior-jobs", id: job.id, overrideAccess: true }) .catch(() => {}); } for (const room of rooms?.docs ?? []) { await payload .delete({ collection: "structure-rooms", id: room.id, overrideAccess: true }) .catch(() => {}); } for (const id of structureIds) { await payload .delete({ collection: "game-structures", id, overrideAccess: true }) .catch(() => {}); } const events = await payload .find({ collection: "game-event-logs", where: { targetId: { in: structureIds } }, limit: 200, depth: 0, overrideAccess: true, }) .catch(() => null); for (const event of events?.docs ?? []) { await payload .delete({ collection: "game-event-logs", id: event.id, overrideAccess: true }) .catch(() => {}); } } for (const id of created.blueprints) { await payload.delete({ collection: "structures", id, overrideAccess: true }).catch(() => {}); } for (const id of created.resources) { await payload.delete({ collection: "resources", id, overrideAccess: true }).catch(() => {}); } if (created.users.length > 0) { const notifications = await payload .find({ collection: "user-notifications", where: { user: { in: created.users } }, limit: 200, depth: 0, overrideAccess: true, }) .catch(() => null); for (const notification of notifications?.docs ?? []) { await payload .delete({ collection: "user-notifications", id: notification.id, overrideAccess: true }) .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(() => {}); } }); // --- 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 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); expect((await roomById(room.id)).pendingJob).toBeNull(); // The refund is credited on the normal collect path. await payload.update({ collection: "interior-jobs", id: started.job.id, data: { status: "awaiting_collect" }, overrideAccess: true, }); 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("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: [] }); }); });