feat(interior): station recipes unlock gating and flagged asset outputs
Produce starts now honor presence-based unlocks_recipe/unlocks_station effects (station marker is its authored name) and reject unknown or gated recipes with recipe_locked, locked stations with station_locked. Asset outputs credit game-structures.storedAssets behind a new Game Rules interior.assetOutputsEnabled switch (default off), prechecked before any deposit so a disabled switch parks the job untouched; storageBridge.depositAssetsToStructure merges quantities by asset without duplicate rows.
This commit is contained in:
parent
0b7959662a
commit
6bc295b630
9 changed files with 45358 additions and 29 deletions
|
|
@ -302,6 +302,15 @@ export const GameRules: GlobalConfig = {
|
|||
description: "Multiplier applied to per-room decay while the master gate is on.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "assetOutputsEnabled",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Master switch for crediting asset (Arma item) outputs from interior jobs into structure locker storage. Keep off until locker.apply is verified on a live server.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ export type JobStartError =
|
|||
| "fixture_blocks_station"
|
||||
| "recipe_locked"
|
||||
| "station_disabled"
|
||||
| "station_locked"
|
||||
| "room_level_insufficient"
|
||||
| "recipe_disabled"
|
||||
| "tech_locked"
|
||||
|
|
@ -79,6 +80,7 @@ export function canStartJob(
|
|||
return { ok: true };
|
||||
case "produce": {
|
||||
if (!opts?.stationEnabled) return { ok: false, reason: "station_disabled" };
|
||||
if (opts?.stationUnlocked === false) return { ok: false, reason: "station_locked" };
|
||||
if (opts?.recipeBlockingFixture && isBlockingFixtureBroken(room.fixtures)) {
|
||||
return { ok: false, reason: "fixture_blocks_station" };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ export type JobStartError =
|
|||
| "fixture_blocked"
|
||||
| "recipe_locked"
|
||||
| "station_disabled"
|
||||
| "station_locked"
|
||||
| "room_level_insufficient"
|
||||
| "recipe_disabled"
|
||||
| "insufficient_resources"
|
||||
|
|
@ -352,30 +353,61 @@ export async function collectInteriorJob(
|
|||
});
|
||||
if (job.status !== "awaiting_collect") return { ok: false, error: "not_ready" };
|
||||
|
||||
// Credit resources to the structure store and assets to the member locker.
|
||||
// Credit resources to the structure store and asset outputs to structure
|
||||
// locker storage.
|
||||
const output = job.output as
|
||||
| { resources?: Array<{ resource: unknown; amount: number }>; assets?: Array<{ asset: unknown; amount: number }> }
|
||||
| undefined;
|
||||
|
||||
if (output?.resources) {
|
||||
// Precheck that the whole output fits before mutating anything, so a full
|
||||
// store keeps the job parked (awaiting_collect) instead of half-depositing.
|
||||
for (const res of output.resources) {
|
||||
const resourceId = relId(res.resource);
|
||||
if (resourceId == null) continue;
|
||||
const pre = await storageBridge.precheckDeposit(payload, relId(job.structure)!, resourceId, res.amount);
|
||||
if (!pre.ok) {
|
||||
return { ok: false, error: "storage_full" };
|
||||
}
|
||||
const resourceRows = output?.resources ?? [];
|
||||
const assetRows = (output?.assets ?? []).flatMap((a) => {
|
||||
const assetId = relId(a.asset);
|
||||
return assetId == null ? [] : [{ asset: assetId, quantity: a.amount }];
|
||||
});
|
||||
|
||||
// Precheck that the whole output fits before mutating anything, so a full
|
||||
// store keeps the job parked (awaiting_collect) instead of half-depositing.
|
||||
for (const res of resourceRows) {
|
||||
const resourceId = relId(res.resource);
|
||||
if (resourceId == null) continue;
|
||||
const pre = await storageBridge.precheckDeposit(payload, relId(job.structure)!, resourceId, res.amount);
|
||||
if (!pre.ok) {
|
||||
return { ok: false, error: "storage_full" };
|
||||
}
|
||||
for (const res of output.resources) {
|
||||
const resourceId = relId(res.resource);
|
||||
if (resourceId == null) continue;
|
||||
const result = await storageBridge.depositToStructure(payload, relId(job.structure)!, resourceId, res.amount);
|
||||
if (!result.ok) {
|
||||
// Keep the job parked so the caller can free space and retry.
|
||||
return { ok: false, error: "storage_full" };
|
||||
}
|
||||
}
|
||||
|
||||
// Asset outputs are gated behind a global kill switch until the game-side
|
||||
// locker.apply path is verified. This runs before any deposit, so a disabled
|
||||
// switch leaves the job and the structure untouched.
|
||||
if (assetRows.length > 0) {
|
||||
const rules = await payload
|
||||
.findGlobal({ slug: "game-rules", overrideAccess: true, depth: 0 })
|
||||
.catch(() => null);
|
||||
if (rules?.interior?.assetOutputsEnabled !== true) {
|
||||
return { ok: false, error: "asset_outputs_disabled" };
|
||||
}
|
||||
}
|
||||
|
||||
for (const res of resourceRows) {
|
||||
const resourceId = relId(res.resource);
|
||||
if (resourceId == null) continue;
|
||||
const result = await storageBridge.depositToStructure(payload, relId(job.structure)!, resourceId, res.amount);
|
||||
if (!result.ok) {
|
||||
// Keep the job parked so the caller can free space and retry.
|
||||
return { ok: false, error: "storage_full" };
|
||||
}
|
||||
}
|
||||
|
||||
// Asset rows are written exactly once, after every resource deposit has
|
||||
// succeeded, so a parked job never leaves a partial asset credit behind.
|
||||
if (assetRows.length > 0) {
|
||||
const result = await storageBridge.depositAssetsToStructure(
|
||||
payload,
|
||||
relId(job.structure)!,
|
||||
assetRows,
|
||||
);
|
||||
if (!result.ok) {
|
||||
return { ok: false, error: result.error ?? "storage_full" };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -652,6 +684,15 @@ async function resolveModuleEffects(
|
|||
return installedModuleEffects(blueprint ?? {}, installedNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the produce-job gate inputs for one recipe.
|
||||
*
|
||||
* Unlock semantics are presence-based: a recipe or station "requires unlock"
|
||||
* only when its key/marker appears in an `unlocks_recipe` / `unlocks_station`
|
||||
* effect on some authored level of the room. Anything never mentioned there is
|
||||
* available as soon as its station/recipe is enabled, so authored rooms without
|
||||
* unlock effects keep working exactly as before.
|
||||
*/
|
||||
function resolveProduceOpts(
|
||||
room: { level: number; fixtures?: RoomFixtureState[] },
|
||||
blueprint: InteriorBlueprintRoom,
|
||||
|
|
@ -680,9 +721,11 @@ function resolveProduceOpts(
|
|||
|
||||
const recipe = station.recipes?.find((r) => r.key === recipeKey);
|
||||
if (!recipe) {
|
||||
// Unknown key: report the station's real unlock state but no recipe so the
|
||||
// gate surfaces `recipe_locked` rather than masking it as `station_locked`.
|
||||
return {
|
||||
stationEnabled: true,
|
||||
stationUnlocked: false,
|
||||
stationUnlocked: stationUnlockedAt(blueprint, station, room.level),
|
||||
recipeUnlocked: false,
|
||||
recipeEnabled: false,
|
||||
recipeRequiredRoomLevel: 1,
|
||||
|
|
@ -692,14 +735,53 @@ function resolveProduceOpts(
|
|||
|
||||
return {
|
||||
stationEnabled: true,
|
||||
stationUnlocked: true,
|
||||
recipeUnlocked: true,
|
||||
stationUnlocked: stationUnlockedAt(blueprint, station, room.level),
|
||||
recipeUnlocked: recipeUnlockedAt(blueprint, recipeKey, room.level),
|
||||
recipeEnabled: recipe.enabled !== false,
|
||||
recipeRequiredRoomLevel: recipe.requiredRoomLevel ?? 1,
|
||||
recipeBlockingFixture: isBlockingFixtureBroken(room.fixtures),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Presence-based station unlock. A station is only gated when any authored
|
||||
* level carries an `unlocks_station` effect; the marker compared is the
|
||||
* station's own `name` (trimmed, case-insensitive), so authors must name a
|
||||
* station they gate. A gated station with no name can never unlock.
|
||||
*/
|
||||
function stationUnlockedAt(
|
||||
blueprint: InteriorBlueprintRoom,
|
||||
station: { name?: string | null },
|
||||
runtimeLevel: number,
|
||||
): boolean {
|
||||
const everUnlocked = resolveRoomEffects(blueprint, Number.POSITIVE_INFINITY);
|
||||
if (everUnlocked.unlockedStations.length === 0) return true;
|
||||
|
||||
const marker = station.name?.trim().toLowerCase();
|
||||
if (!marker) return false;
|
||||
|
||||
return resolveRoomEffects(blueprint, runtimeLevel).unlockedStations.some(
|
||||
(unlocked) => unlocked.trim().toLowerCase() === marker,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Presence-based recipe unlock. A recipe is only gated when its key appears in
|
||||
* an `unlocks_recipe` effect on some authored level; otherwise it is available
|
||||
* at any room level. Gated recipes unlock when the current level's accumulated
|
||||
* effects include the key.
|
||||
*/
|
||||
function recipeUnlockedAt(
|
||||
blueprint: InteriorBlueprintRoom,
|
||||
recipeKey: string,
|
||||
runtimeLevel: number,
|
||||
): boolean {
|
||||
const everUnlocked = resolveRoomEffects(blueprint, Number.POSITIVE_INFINITY);
|
||||
if (!everUnlocked.unlockedRecipes.includes(recipeKey)) return true;
|
||||
|
||||
return resolveRoomEffects(blueprint, runtimeLevel).unlockedRecipes.includes(recipeKey);
|
||||
}
|
||||
|
||||
function isBlockingFixtureBroken(fixtures?: RoomFixtureState[]): boolean {
|
||||
if (!fixtures) return false;
|
||||
return fixtures.some((f) => f.broken && f.blocksStation);
|
||||
|
|
|
|||
|
|
@ -26,6 +26,9 @@ type StoredResource = {
|
|||
rotated?: boolean;
|
||||
};
|
||||
|
||||
/** One stored locker asset row (quantity is always >= 1). */
|
||||
type StoredAssetRow = NonNullable<GameStructure["storedAssets"]>[number];
|
||||
|
||||
/** Total currently stored amount of one resource across grid + void. */
|
||||
export async function storedAmount(
|
||||
payload: Payload,
|
||||
|
|
@ -43,11 +46,12 @@ export async function storedAmount(
|
|||
|
||||
const rows = [...(structure.storedResources ?? []), ...(structure.voidStorage ?? [])] as StoredResource[];
|
||||
return rows
|
||||
.filter((r) => resourceIdOf(r.resource) === resourceId)
|
||||
.filter((r) => refId(r.resource) === resourceId)
|
||||
.reduce((sum, r) => sum + (r.amount ?? 0), 0);
|
||||
}
|
||||
|
||||
function resourceIdOf(ref: unknown): number | null {
|
||||
/** Relationship id for a resource or asset ref (number or populated `{ id }`). */
|
||||
function refId(ref: unknown): number | null {
|
||||
if (ref == null) return null;
|
||||
if (typeof ref === "number") return ref;
|
||||
if (typeof ref === "object" && "id" in (ref as { id: unknown })) {
|
||||
|
|
@ -108,7 +112,7 @@ export function applyStoragePlacement(
|
|||
// Fill existing same-resource stacks first.
|
||||
for (const row of rows) {
|
||||
if (remaining <= 0) break;
|
||||
if (resourceIdOf(row.resource) !== resourceId) continue;
|
||||
if (refId(row.resource) !== resourceId) continue;
|
||||
const space = maxStack - (row.amount ?? 0);
|
||||
if (space <= 0) continue;
|
||||
const add = Math.min(space, remaining);
|
||||
|
|
@ -121,7 +125,7 @@ export function applyStoragePlacement(
|
|||
let toRemove = 0;
|
||||
for (const row of rows) {
|
||||
if (remaining >= 0) break;
|
||||
if (resourceIdOf(row.resource) !== resourceId) continue;
|
||||
if (refId(row.resource) !== resourceId) continue;
|
||||
if (row.amount <= -remaining) {
|
||||
toRemove++;
|
||||
remaining += row.amount;
|
||||
|
|
@ -174,7 +178,7 @@ function storedAmountAt(
|
|||
resourceId: number,
|
||||
): number {
|
||||
return (rows ?? []).reduce(
|
||||
(sum, r) => (resourceIdOf(r.resource) === resourceId ? sum + (r.amount ?? 0) : sum),
|
||||
(sum, r) => (refId(r.resource) === resourceId ? sum + (r.amount ?? 0) : sum),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
|
@ -347,6 +351,60 @@ export async function depositToStructure(
|
|||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge produced assets into a structure's locker storage (`storedAssets`).
|
||||
*
|
||||
* Assets are stack rows rather than gridded resources: an incoming row whose
|
||||
* asset already has a stored row increments that row's quantity, otherwise a
|
||||
* new zero-position row is appended. Quantity must stay >= 1, and the grid
|
||||
* position is reconciled later by the game-side locker sync, so the placeholder
|
||||
* `{ gridX: 0, gridY: 0 }` is intentional. No event is emitted here: the
|
||||
* GameStructures afterChange hook already reacts to storedAssets edits.
|
||||
*/
|
||||
export async function depositAssetsToStructure(
|
||||
payload: Payload,
|
||||
structureId: number | string,
|
||||
rows: Array<{ asset: number; quantity: number }>,
|
||||
): Promise<{ ok: boolean; error?: string }> {
|
||||
const structure = await payload
|
||||
.findByID({
|
||||
collection: "game-structures",
|
||||
id: structureId as number,
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
select: { storedAssets: true },
|
||||
})
|
||||
.catch(() => null);
|
||||
if (!structure) return { ok: false, error: "structure_not_found" };
|
||||
|
||||
const merged = ((structure.storedAssets ?? []) as StoredAssetRow[]).map((row) => ({ ...row }));
|
||||
|
||||
for (const incoming of rows) {
|
||||
if (incoming.quantity < 1) continue;
|
||||
const existing = merged.find((row) => refId(row.asset) === incoming.asset);
|
||||
if (existing) {
|
||||
existing.quantity += incoming.quantity;
|
||||
continue;
|
||||
}
|
||||
merged.push({
|
||||
asset: incoming.asset,
|
||||
quantity: incoming.quantity,
|
||||
gridX: 0,
|
||||
gridY: 0,
|
||||
rotated: false,
|
||||
});
|
||||
}
|
||||
|
||||
await payload.update({
|
||||
collection: "game-structures",
|
||||
id: structureId as number,
|
||||
overrideAccess: true,
|
||||
data: { storedAssets: merged },
|
||||
});
|
||||
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Withdraw `amount` of `resourceId` from the structure, pulling from void first
|
||||
* then the grid (mirroring `removeResourceInternal`). Refuses when there is not
|
||||
|
|
@ -405,7 +463,7 @@ function withdrawFromEntries(
|
|||
let remaining = amount;
|
||||
const updated = entries
|
||||
.map((entry) => {
|
||||
if (remaining <= 0 || resourceIdOf(entry.resource) !== resourceId) return entry;
|
||||
if (remaining <= 0 || refId(entry.resource) !== resourceId) return entry;
|
||||
const consumed = Math.min(entry.amount ?? 0, remaining);
|
||||
remaining -= consumed;
|
||||
return { ...entry, amount: (entry.amount ?? 0) - consumed };
|
||||
|
|
|
|||
44787
src/migrations/20261020_200000_add_interior_asset_outputs_flag.json
Normal file
44787
src/migrations/20261020_200000_add_interior_asset_outputs_flag.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,11 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "game_rules" ADD COLUMN "interior_asset_outputs_enabled" boolean DEFAULT false;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "game_rules" DROP COLUMN "interior_asset_outputs_enabled";`)
|
||||
}
|
||||
|
|
@ -145,6 +145,7 @@ import * as migration_20261019_121500_use_env_ai_model from './20261019_121500_u
|
|||
import * as migration_20261019_184409_add_tech_research_system from './20261019_184409_add_tech_research_system';
|
||||
import * as migration_20261020_171725_add_superstructure_interior from './20261020_171725_add_superstructure_interior';
|
||||
import * as migration_20261020_191433_add_interior_module_effect_types from './20261020_191433_add_interior_module_effect_types';
|
||||
import * as migration_20261020_200000_add_interior_asset_outputs_flag from './20261020_200000_add_interior_asset_outputs_flag';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -880,6 +881,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261020_191433_add_interior_module_effect_types.up,
|
||||
down: migration_20261020_191433_add_interior_module_effect_types.down,
|
||||
name: '20261020_191433_add_interior_module_effect_types'
|
||||
name: '20261020_191433_add_interior_module_effect_types',
|
||||
},
|
||||
{
|
||||
up: migration_20261020_200000_add_interior_asset_outputs_flag.up,
|
||||
down: migration_20261020_200000_add_interior_asset_outputs_flag.down,
|
||||
name: '20261020_200000_add_interior_asset_outputs_flag'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -13309,6 +13309,10 @@ export interface GameRule {
|
|||
* Multiplier applied to per-room decay while the master gate is on.
|
||||
*/
|
||||
decayMultiplier?: number | null;
|
||||
/**
|
||||
* Master switch for crediting asset (Arma item) outputs from interior jobs into structure locker storage. Keep off until locker.apply is verified on a live server.
|
||||
*/
|
||||
assetOutputsEnabled?: boolean | null;
|
||||
};
|
||||
/**
|
||||
* When off, the Zone Pressure feature is hidden from the Operations feed (the overview card and the AAR section).
|
||||
|
|
@ -13521,6 +13525,7 @@ export interface GameRulesSelect<T extends boolean = true> {
|
|||
| {
|
||||
decayEnabled?: T;
|
||||
decayMultiplier?: T;
|
||||
assetOutputsEnabled?: T;
|
||||
};
|
||||
zonePressureEnabled?: T;
|
||||
statisticsEnabled?: T;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import config from "@/payload.config";
|
|||
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import type {
|
||||
Asset,
|
||||
GameStructure,
|
||||
InteriorJob,
|
||||
Resource,
|
||||
|
|
@ -65,11 +66,14 @@ 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[],
|
||||
|
|
@ -120,6 +124,26 @@ async function makeResource(label: string, massPerUnit: number): Promise<Resourc
|
|||
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,
|
||||
|
|
@ -287,6 +311,8 @@ beforeAll(async () => {
|
|||
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",
|
||||
|
|
@ -401,6 +427,9 @@ afterAll(async () => {
|
|||
.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(() => {});
|
||||
}
|
||||
|
|
@ -1217,3 +1246,343 @@ describe("rollJunkLoot", () => {
|
|||
).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);
|
||||
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue