diff --git a/src/lib/interior/jobs.ts b/src/lib/interior/jobs.ts index 4cb4f7ed..7564b9d5 100644 --- a/src/lib/interior/jobs.ts +++ b/src/lib/interior/jobs.ts @@ -1,6 +1,11 @@ import type { Payload } from "payload"; import type { GameStructure, InteriorJob } from "@/payload-types"; -import type { InteriorBlueprintRoom, RoomFixtureState, RuntimeRoom } from "./types"; +import type { + InteriorBlueprintRoom, + JunkLootEntry, + RoomFixtureState, + RuntimeRoom, +} from "./types"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { emitGameEvent } from "@/utils/event-log/emit"; import { notifyUser } from "@/lib/notifications"; @@ -76,11 +81,6 @@ export async function startInteriorJob( ): Promise { const { structureId, roomKey, type, target, laborClass, headcount } = args; - if (!(await canUserEnterInterior(payload, user, { interiorAccess: undefined }))) { - // Access is evaluated against the resolved structure below; this early - // guard keeps the types narrow until we have the doc. - } - const structure = await payload.findByID({ collection: "game-structures", id: relId(structureId)!, @@ -189,7 +189,12 @@ export async function startInteriorJob( status: "active", stationRecipeKey: type === "produce" ? String(target ?? "") : undefined, fixtureKey: type === "repair" ? String(target ?? "") : undefined, - targetLevel: type === "upgrade" ? Number(target ?? undefined) : undefined, + targetLevel: + type === "upgrade" + ? Number(target ?? undefined) + : type === "open" + ? openDestinationLevel(blueprint, target) + : undefined, startedBy: relId(user!.id) ?? undefined, startedAt: now.toISOString(), endsAt: endsAt.toISOString(), @@ -373,6 +378,7 @@ export async function collectInteriorJob( export async function completeInteriorJob( payload: PayloadType, jobId: number | string, + rng: () => number = Math.random, ): Promise<{ ok: boolean; error?: string }> { const job = await payload.findByID({ collection: "interior-jobs", @@ -382,11 +388,79 @@ export async function completeInteriorJob( }); if (job.status !== "active") return { ok: false, error: "not_active" }; + const jobUpdate: { + status: "awaiting_collect"; + output?: { + resources: Array<{ resource: number; amount: number }>; + assets: Array<{ asset: number; amount: number }>; + }; + } = { status: "awaiting_collect" }; + + // Apply the room-level effect of open/cleanup at completion: opening flips + // the room to its destination level, cleanup removes junk and rolls one loot + // drop written onto the job for `collectInteriorJob` to credit. Upgrade and + // repair effects land with their own build steps; 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 === "cleanup") { + const room = await payload + .findByID({ + collection: "structure-rooms", + id: relId(job.room)!, + overrideAccess: true, + depth: 0, + }) + .catch(() => null); + + if (room) { + if (job.type === "open") { + await payload.update({ + collection: "structure-rooms", + id: relId(room.id)!, + overrideAccess: true, + data: { level: Math.max(room.level ?? 0, job.targetLevel ?? 1) }, + }); + } else { + await payload.update({ + collection: "structure-rooms", + id: relId(room.id)!, + overrideAccess: true, + data: { junkLevel: Math.max(0, (room.junkLevel ?? 0) - CLEANUP_JUNK_PER_RUN) }, + }); + + const structure = await payload + .findByID({ + collection: "game-structures", + id: relId(job.structure)!, + overrideAccess: true, + depth: 0, + select: { interior: true }, + }) + .catch(() => null); + const blueprint = structure + ? blueprintRoom(structure as unknown as GameStructure, room.roomKey) + : undefined; + const loot = rollJunkLoot(blueprint?.junkLoot as JunkLootEntry[] | undefined, rng); + + jobUpdate.output = { + resources: loot.resources.flatMap((r) => { + const id = relId(r.resource); + return id == null ? [] : [{ resource: id, amount: r.amount }]; + }), + assets: loot.assets.flatMap((a) => { + const id = relId(a.asset); + return id == null ? [] : [{ asset: id, amount: a.amount }]; + }), + }; + } + } + } + await payload.update({ collection: "interior-jobs", id: relId(job.id)!, overrideAccess: true, - data: { status: "awaiting_collect" }, + data: jobUpdate, }); const startedById = relId(job.startedBy); @@ -469,6 +543,76 @@ function isBlockingFixtureBroken(fixtures?: RoomFixtureState[]): boolean { return fixtures.some((f) => f.broken && f.blocksStation); } +/** A cleanup run clears this many junk levels. */ +const CLEANUP_JUNK_PER_RUN = 1; +/** Base wall time for one cleanup run, before effect modifiers (Step 4). */ +export const CLEANUP_JOB_MINUTES = 15; + +/** + * Destination level for an open job: an explicit target wins, otherwise the + * lowest authored level (level 1 for a room sealed at level 0). + */ +function openDestinationLevel( + blueprint: InteriorBlueprintRoom, + target?: string | number, +): number { + if (target != null && String(target) !== "") return Number(target); + const levels = [...(blueprint.levels ?? [])].sort((a, b) => a.level - b.level); + return levels[0]?.level ?? 1; +} + +/** The authored level definition describing how breaking in costs and takes. */ +function openLevelDefinition( + blueprint: InteriorBlueprintRoom, + target?: string | number, +) { + const wanted = openDestinationLevel(blueprint, target); + return blueprint.levels?.find((l) => l.level === wanted); +} + +/** + * Roll one weighted loot drop from a room's junk table. Deterministic under an + * injected `rng` so tests can pin outcomes; returns empty when no entries are + * authored or every weight is zero. + */ +export function rollJunkLoot( + entries: JunkLootEntry[] | undefined, + rng: () => number = Math.random, +): { + resources: Array<{ resource: unknown; amount: number }>; + assets: Array<{ asset: unknown; amount: number }>; +} { + const resources: Array<{ resource: unknown; amount: number }> = []; + const assets: Array<{ asset: unknown; amount: number }> = []; + + const pool = (entries ?? []).filter((e) => e.item != null && e.weight > 0); + if (pool.length === 0) return { resources, assets }; + + const totalWeight = pool.reduce((sum, e) => sum + Math.max(0, e.weight), 0); + let roll = rng() * totalWeight; + let picked: JunkLootEntry | undefined; + for (const entry of pool) { + roll -= Math.max(0, entry.weight); + if (roll <= 0) { + picked = entry; + break; + } + } + picked ??= pool[pool.length - 1]; + + const min = Math.min(picked.amountMin, picked.amountMax); + const max = Math.max(picked.amountMin, picked.amountMax); + const amount = Math.floor(min + rng() * (max - min + 1)); + const clamped = Math.min(max, Math.max(min, amount)); + + if (picked.kind === "asset") { + assets.push({ asset: picked.item, amount: clamped }); + } else { + resources.push({ resource: picked.item, amount: clamped }); + } + return { resources, assets }; +} + /** * Compute the committed resources (consumed at start) and the output (credited * at collect) for a job. Returns null when the job has no resource commitment @@ -525,7 +669,20 @@ function computeCommitment( }, }; } + case "open": { + // Breaking into a sealed room can cost materials: the entry level's + // authored upgrade materials double as the door-opening cost. + const level = openLevelDefinition(blueprint, target); + const materials = level?.upgradeMaterials ?? []; + return { + committedResources: materials.map((m) => ({ + resource: m.resource, + amount: m.amount, + })), + }; + } default: + // Cleanup has no material commitment; junk and loot land at completion. return { committedResources: [] }; } } @@ -548,5 +705,12 @@ function commitmentDurationMs( const recipe = blueprint.station?.recipes?.find((r) => r.key === String(target ?? "")); return (recipe?.durationMinutes ?? 0) * 60_000; } + if (type === "open") { + const level = openLevelDefinition(blueprint, target); + return (level?.upgradeDurationMinutes ?? 0) * 60_000; + } + if (type === "cleanup") { + return CLEANUP_JOB_MINUTES * 60_000; + } return 0; } diff --git a/src/lib/interior/provision.ts b/src/lib/interior/provision.ts index 9920c8d6..822163e5 100644 --- a/src/lib/interior/provision.ts +++ b/src/lib/interior/provision.ts @@ -18,7 +18,7 @@ export async function provisionInterior( structure: Pick, ): Promise<{ provisioned: boolean; rooms: number }> { const snapshot = structure.interior; - if (!snapshot?.provisionedAt || !Array.isArray(snapshot.rooms)) { + if (!snapshot || !Array.isArray(snapshot.rooms)) { return { provisioned: false, rooms: 0 }; } @@ -43,7 +43,7 @@ export async function provisionInterior( const count = created.filter(Boolean).length; - if (count > 0) { + if (count > 0 || !snapshot.provisionedAt) { await payload.update({ collection: "game-structures", id: relId(structure.id)!, diff --git a/src/payload-types.ts b/src/payload-types.ts index 64454bff..89645f8e 100644 --- a/src/payload-types.ts +++ b/src/payload-types.ts @@ -1807,7 +1807,11 @@ export interface Structure { | 'labor_capacity' | 'unlocks_recipe' | 'unlocks_station'; - value: number; + value?: number | null; + /** + * Target for unlock effects: the recipe key (unlocks_recipe) or a station marker (unlocks_station). Ignored by numeric effects. + */ + target?: string | null; id?: string | null; }[] | null; @@ -11130,6 +11134,7 @@ export interface StructuresSelect { | { type?: T; value?: T; + target?: T; id?: T; }; id?: T; diff --git a/tests/int/interior.int.spec.ts b/tests/int/interior.int.spec.ts new file mode 100644 index 00000000..7ec115bc --- /dev/null +++ b/tests/int/interior.int.spec.ts @@ -0,0 +1,827 @@ +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: [] }); + }); +});