1
0
Fork 0

feat(interior): upgrade completion, tech/labor gates, and module bonuses

Complete-time level advance (clamped to maxLevel), open/upgrade tech and labor gates sourced from npc-staffing and technologies.researchedAt, and pure duration/output math in effects.ts applied to job durations and produce resource output.

Adds interior_job_speed and interior_output_bonus module effect types to the shared module system (additive aggregates; existing consumers unaffected) with a migration, which also closes Step 1 drift making structures_rooms_levels_effects.value nullable and adding its target column.
This commit is contained in:
Jason Fraley 2026-10-20 15:44:36 -04:00
parent 1b8c84be47
commit 0b7959662a
11 changed files with 45518 additions and 37 deletions

View file

@ -8,6 +8,8 @@ export const MODULE_EFFECT_TYPES = [
"capacity_mass",
"production_multiplier",
"storage_slots",
"interior_job_speed",
"interior_output_bonus",
] as const;
/**
@ -74,7 +76,7 @@ export function createModuleFields(context: ModuleFieldContext): Field[] {
required: true,
admin: {
description:
"capacity_mass: extra kg of storage. storage_slots: extra grid slots. production_multiplier: output boost as a fraction (0.25 = +25%).",
"capacity_mass: extra kg of storage. storage_slots: extra grid slots. production_multiplier: output boost as a fraction (0.25 = +25%). interior_job_speed: faster interior jobs as a fraction (0.25 = 25% faster). interior_output_bonus: extra interior job output as a fraction (0.1 = +10%).",
},
},
],

View file

@ -28,6 +28,10 @@ export interface ModuleEffects {
capacityMass: number;
productionMultiplier: number;
storageSlots: number;
/** Fractional speed-up applied to interior job durations (0.2 = 20% faster). */
interiorJobSpeed: number;
/** Additive fraction applied to interior job resource output (0.1 = +10%). */
interiorOutputBonus: number;
}
export interface InstalledModuleLike {
@ -44,6 +48,8 @@ export function installedModuleEffects(
capacityMass: 0,
productionMultiplier: 0,
storageSlots: 0,
interiorJobSpeed: 0,
interiorOutputBonus: 0,
};
for (const name of installedNames) {
const option = (blueprint.moduleOptions ?? []).find((candidate) => candidate.name === name);
@ -53,6 +59,8 @@ export function installedModuleEffects(
if (effect.type === "capacity_mass") effects.capacityMass += value;
else if (effect.type === "production_multiplier") effects.productionMultiplier += value;
else if (effect.type === "storage_slots") effects.storageSlots += Math.floor(value);
else if (effect.type === "interior_job_speed") effects.interiorJobSpeed += value;
else if (effect.type === "interior_output_bonus") effects.interiorOutputBonus += value;
}
}
return effects;

View file

@ -84,6 +84,60 @@ function applyEffect(result: RoomEffects, effect: LevelEffect): void {
}
}
/**
* Apply the level + module speed multipliers and room condition to a job's
* base duration.
*
* `conditionFactor` is the room condition as a fraction of 100, but drops to 0
* when the condition is below the blueprint's effect floor, so a decayed room's
* divisor floors at 0.1 (10x slower work) instead of stalling forever. The
* result never falls below a 60-second floor, so a micro-job still occupies the
* room for a measurable time.
*
* Exception: `baseMs <= 0` returns 0 unchanged, because instant jobs (for
* example an authored 0-minute open) must stay instant rather than jump to the
* floor.
*/
export function applyInteriorDurationFactor({
baseMs,
levelSpeedMultiplier = 1,
moduleSpeedMultiplier = 1,
condition = 0,
effectFloor = 0,
}: {
baseMs: number;
levelSpeedMultiplier?: number;
moduleSpeedMultiplier?: number;
condition?: number;
effectFloor?: number;
}): number {
if (baseMs <= 0) return 0;
const conditionFactor = condition < effectFloor ? 0 : condition / 100;
return Math.max(
60_000,
baseMs / Math.max(0.1, levelSpeedMultiplier * moduleSpeedMultiplier * conditionFactor),
);
}
/**
* Apply the room-level output multiplier plus the installed-module output bonus
* to one produced amount.
*
* Composition: `base * (1 + (levelMultiplier - 1) + moduleBonus)`. The level's
* percentage bonus and the module's additive fraction stack additively, the
* result is rounded to whole units, and it never goes negative.
*/
export function applyOutputBonus(
baseAmount: number,
levelOutputMultiplier = 1,
moduleOutputBonus = 0,
): number {
return Math.max(
0,
Math.round(baseAmount * (1 + (levelOutputMultiplier - 1) + moduleOutputBonus)),
);
}
/** True when the room has unlocked the recipe with the given key. */
export function isRecipeUnlocked(
room: Pick<InteriorBlueprintRoom, "levels">,

View file

@ -19,7 +19,9 @@ export type JobStartError =
| "recipe_locked"
| "station_disabled"
| "room_level_insufficient"
| "recipe_disabled";
| "recipe_disabled"
| "tech_locked"
| "labor_insufficient";
export type JobStartResult = { ok: true } | { ok: false; reason: JobStartError };
@ -32,7 +34,10 @@ export function isBlockingFixtureBroken(fixtures: RoomFixtureState[] | undefined
/**
* Whether a job of `jobType` may start on this room right now.
*
* `opts` carries the recipe/station context needed by produce jobs.
* `opts` carries the recipe/station context needed by produce jobs, plus the
* level requirements (researched tech, staffed labor) that jobs.ts resolves for
* open/upgrade jobs. `undefined` means "met" so callers that do not evaluate a
* requirement never trip the gate.
*/
export function canStartJob(
room: RuntimeRoom,
@ -45,11 +50,18 @@ export function canStartJob(
recipeEnabled?: boolean;
recipeRequiredRoomLevel?: number;
recipeBlockingFixture?: boolean;
techRequirementMet?: boolean;
laborRequirementMet?: boolean;
},
): JobStartResult {
// A room can only run one job at a time (the output slot).
if (room.pendingJob) return { ok: false, reason: "room_busy" };
// Level requirements gate open/upgrade; check them before the type switch so
// the reason is deterministic when several gates would fail.
if (opts?.techRequirementMet === false) return { ok: false, reason: "tech_locked" };
if (opts?.laborRequirementMet === false) return { ok: false, reason: "labor_insufficient" };
switch (roomType) {
case "open":
return (room.level ?? 0) > 0 ? { ok: false, reason: "already_open" } : { ok: true };

View file

@ -3,14 +3,17 @@ import type { GameStructure, InteriorJob } from "@/payload-types";
import type {
InteriorBlueprintRoom,
JunkLootEntry,
LevelDefinition,
RoomFixtureState,
RuntimeRoom,
} from "./types";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { emitGameEvent } from "@/utils/event-log/emit";
import { notifyUser } from "@/lib/notifications";
import { installedModuleEffects, type ModuleEffects } from "@/lib/base/modules";
import { canUserEnterInterior } from "./access";
import { canStartJob } from "./gates";
import { applyInteriorDurationFactor, applyOutputBonus, resolveRoomEffects } from "./effects";
import * as storageBridge from "./storageBridge";
import { relId } from "./relations";
@ -39,7 +42,9 @@ export type JobStartError =
| "insufficient_resources"
| "mass_over_cap"
| "no_room"
| "no_blueprint";
| "no_blueprint"
| "tech_locked"
| "labor_insufficient";
export type JobStartResult =
| { ok: true; job: InteriorJob }
@ -89,6 +94,8 @@ export async function startInteriorJob(
select: {
id: true,
interior: true,
installedModules: true,
type: true,
},
}).catch(() => null);
if (!structure) return { ok: false, error: "not_found" };
@ -137,6 +144,23 @@ export async function startInteriorJob(
if (!blueprint) return { ok: false, error: "no_blueprint" };
// --- Gate evaluation -----------------------------------------------------
// Tech and labor requirements are authored on a level definition, so only
// open (entry level) and upgrade (destination level) evaluate them; every
// other type skips the requirement queries entirely.
const levelDef =
type === "open"
? openLevelDefinition(blueprint, target)
: type === "upgrade"
? blueprint.levels?.find((l) => l.level === Number(target))
: undefined;
const requirements =
type === "open" || type === "upgrade"
? {
techRequirementMet: await techRequirementMet(payload, levelDef),
laborRequirementMet: await laborRequirementMet(payload, relId(structure.id)!, levelDef),
}
: undefined;
const produceOpts =
type === "produce"
? resolveProduceOpts(engineRoom, blueprint, String(target ?? ""))
@ -150,13 +174,22 @@ export async function startInteriorJob(
recipeEnabled: produceOpts?.recipeEnabled,
recipeRequiredRoomLevel: produceOpts?.recipeRequiredRoomLevel,
recipeBlockingFixture: produceOpts?.recipeBlockingFixture ?? false,
techRequirementMet: requirements?.techRequirementMet,
laborRequirementMet: requirements?.laborRequirementMet,
});
if (!gate.ok) {
return { ok: false, error: gate.reason as JobStartError };
}
// --- Effect modifiers (room level + installed modules) --------------------
const roomEffects = resolveRoomEffects(blueprint, engineRoom.level);
const moduleEffects = await resolveModuleEffects(payload, structure);
// --- Compute committed resources + output --------------------------------
const commitment = computeCommitment(engineRoom, blueprint, type, target);
const commitment = computeCommitment(engineRoom, blueprint, type, target, {
levelOutputMultiplier: roomEffects.outputMultiplier,
moduleOutputBonus: moduleEffects.interiorOutputBonus,
});
if (!commitment) {
return { ok: false, error: "insufficient_resources" };
}
@ -176,7 +209,12 @@ export async function startInteriorJob(
// --- Persist job + block the output slot ---------------------------------
const now = new Date();
const endsAt = new Date(now.getTime() + commitmentDurationMs(engineRoom, blueprint, type, target));
const durationMs = commitmentDurationMs(engineRoom, blueprint, type, target, {
levelSpeedMultiplier: roomEffects.productionSpeedMultiplier,
moduleSpeedMultiplier: 1 + moduleEffects.interiorJobSpeed,
effectFloor: blueprint.decay?.effectFloor ?? 0,
});
const endsAt = new Date(now.getTime() + durationMs);
const job = await payload.create({
collection: "interior-jobs",
@ -396,13 +434,13 @@ export async function completeInteriorJob(
};
} = { 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") {
// Apply the room-level effect of open/upgrade/cleanup at completion: opening
// flips the room to its destination level, upgrading advances (and clamps) it,
// and cleanup removes junk and rolls one loot drop written onto the job for
// `collectInteriorJob` to credit. Repair effects land with their own build
// step; produce output is already recorded on the job at start. Effect lookups
// are best-effort so a missing snapshot can never wedge the sweep.
if (job.type === "open" || job.type === "upgrade" || job.type === "cleanup") {
const room = await payload
.findByID({
collection: "structure-rooms",
@ -420,6 +458,19 @@ export async function completeInteriorJob(
overrideAccess: true,
data: { level: Math.max(room.level ?? 0, job.targetLevel ?? 1) },
});
} else if (job.type === "upgrade") {
const blueprint = await structureInteriorRoom(payload, job.structure, room.roomKey);
const maxLevel = blueprint?.maxLevel ?? Number.MAX_SAFE_INTEGER;
const nextLevel = Math.min(
Math.max(room.level ?? 0, job.targetLevel ?? (room.level ?? 0) + 1),
maxLevel,
);
await payload.update({
collection: "structure-rooms",
id: relId(room.id)!,
overrideAccess: true,
data: { level: nextLevel },
});
} else {
await payload.update({
collection: "structure-rooms",
@ -428,18 +479,7 @@ export async function completeInteriorJob(
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 blueprint = await structureInteriorRoom(payload, job.structure, room.roomKey);
const loot = rollJunkLoot(blueprint?.junkLoot as JunkLootEntry[] | undefined, rng);
jobUpdate.output = {
@ -490,6 +530,128 @@ async function clearRoomSlot(
// --- helpers ---------------------------------------------------------------
/**
* Load a game structure's interior snapshot and resolve one authored room.
* Best-effort: a missing snapshot or room returns undefined so completion
* effects never wedge the sweep.
*/
async function structureInteriorRoom(
payload: PayloadType,
structureRef: unknown,
roomKey: string | null | undefined,
): Promise<InteriorBlueprintRoom | undefined> {
const structureId = relId(structureRef);
if (structureId == null || !roomKey) return undefined;
const structure = await payload
.findByID({
collection: "game-structures",
id: structureId,
overrideAccess: true,
depth: 0,
select: { interior: true },
})
.catch(() => null);
return structure ? blueprintRoom(structure as unknown as GameStructure, roomKey) : undefined;
}
/**
* Whether every technology required by a level definition has been researched.
* An absent or empty requirement counts as met.
*/
async function techRequirementMet(
payload: PayloadType,
def: LevelDefinition | undefined,
): Promise<boolean> {
const required = def?.requiredTech ?? [];
if (required.length === 0) return true;
for (const ref of required) {
const id = relId(ref);
if (id == null) return false;
const tech = await payload
.findByID({
collection: "technologies",
id,
overrideAccess: true,
depth: 0,
select: { researchedAt: true },
})
.catch(() => null);
if (!tech?.researchedAt) return false;
}
return true;
}
/**
* Whether the structure staffs enough active NPC labor of the required
* classification. An absent class or a non-positive headcount counts as met.
*/
async function laborRequirementMet(
payload: PayloadType,
structureId: number,
def: LevelDefinition | undefined,
): Promise<boolean> {
const requiredClass = def?.requiredLaborClass;
const requiredHeadcount = def?.requiredHeadcount ?? 0;
if (!requiredClass || requiredHeadcount <= 0) return true;
const rows = await payload
.find({
collection: "npc-staffing",
overrideAccess: true,
depth: 1,
limit: 200,
where: {
AND: [{ structure: { equals: structureId } }, { status: { equals: "active" } }],
},
select: { headcount: true, laborClassification: true },
})
.catch(() => null);
if (!rows) return false;
let staffed = 0;
for (const row of rows.docs) {
const classification = row.laborClassification;
const key =
typeof classification === "object" && classification !== null
? (classification as { key?: string | null }).key
: null;
if (key !== requiredClass) continue;
staffed += row.headcount ?? 0;
}
return staffed >= requiredHeadcount;
}
/**
* Aggregate the installed-module effects that modify interior jobs. Neutral
* zeros when nothing is installed; a missing blueprint contributes nothing.
*/
async function resolveModuleEffects(
payload: PayloadType,
structure: GameStructure,
): Promise<ModuleEffects> {
const installedNames = ((structure.installedModules ?? []) as { name?: string | null }[])
.map((entry) => entry.name)
.filter((name): name is string => Boolean(name));
if (installedNames.length === 0) return installedModuleEffects({}, []);
const blueprintId = relId(structure.type);
const blueprint =
blueprintId == null
? null
: await payload
.findByID({
collection: "structures",
id: blueprintId,
overrideAccess: true,
depth: 0,
select: { moduleOptions: true },
})
.catch(() => null);
return installedModuleEffects(blueprint ?? {}, installedNames);
}
function resolveProduceOpts(
room: { level: number; fixtures?: RoomFixtureState[] },
blueprint: InteriorBlueprintRoom,
@ -545,7 +707,7 @@ function isBlockingFixtureBroken(fixtures?: RoomFixtureState[]): boolean {
/** 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). */
/** Base wall time for one cleanup run, before effect modifiers. */
export const CLEANUP_JOB_MINUTES = 15;
/**
@ -623,6 +785,10 @@ function computeCommitment(
blueprint: InteriorBlueprintRoom,
type: InteriorJob["type"],
target: string | number | undefined,
modifiers?: {
levelOutputMultiplier?: number;
moduleOutputBonus?: number;
},
): {
committedResources: Array<{ resource: unknown; amount: number }>;
output?: {
@ -654,6 +820,8 @@ function computeCommitment(
case "produce": {
const recipe = blueprint.station?.recipes?.find((r) => r.key === String(target ?? ""));
if (!recipe) return { committedResources: [] };
const levelOutputMultiplier = modifiers?.levelOutputMultiplier ?? 1;
const moduleOutputBonus = modifiers?.moduleOutputBonus ?? 0;
return {
committedResources: (recipe.inputs ?? []).map((i) => ({
resource: i.resource,
@ -662,7 +830,11 @@ function computeCommitment(
output: {
resources: (recipe.outputs ?? [])
.filter((o) => o.kind === "resource")
.map((o) => ({ resource: o.item, amount: o.amount })),
.map((o) => ({
resource: o.item,
amount: applyOutputBonus(o.amount, levelOutputMultiplier, moduleOutputBonus),
})),
// Asset outputs are brand items, not bulk production: never scaled.
assets: (recipe.outputs ?? [])
.filter((o) => o.kind === "asset")
.map((o) => ({ asset: o.item, amount: o.amount })),
@ -687,30 +859,55 @@ function computeCommitment(
}
}
function commitmentDurationMs(
room: { level: number },
/** Authored wall time for a job, before level/module/condition modifiers. */
function baseDurationMinutes(
blueprint: InteriorBlueprintRoom,
type: InteriorJob["type"],
target: string | number | undefined,
): number {
if (type === "upgrade") {
const level = blueprint.levels?.find((l) => l.level === Number(target ?? 0));
return (level?.upgradeDurationMinutes ?? 0) * 60_000;
return level?.upgradeDurationMinutes ?? 0;
}
if (type === "repair") {
const fixture = blueprint.fixtures?.find((f) => f.key === String(target ?? ""));
return (fixture?.repairDurationMinutes ?? 0) * 60_000;
return fixture?.repairDurationMinutes ?? 0;
}
if (type === "produce") {
const recipe = blueprint.station?.recipes?.find((r) => r.key === String(target ?? ""));
return (recipe?.durationMinutes ?? 0) * 60_000;
return recipe?.durationMinutes ?? 0;
}
if (type === "open") {
const level = openLevelDefinition(blueprint, target);
return (level?.upgradeDurationMinutes ?? 0) * 60_000;
return level?.upgradeDurationMinutes ?? 0;
}
if (type === "cleanup") {
return CLEANUP_JOB_MINUTES * 60_000;
return CLEANUP_JOB_MINUTES;
}
return 0;
}
/**
* Final wall time for a job: the authored base duration run through the shared
* duration factor (room-level speed, installed-module speed, condition against
* the blueprint's effect floor, and the 60-second floor).
*/
function commitmentDurationMs(
room: { level: number; condition: number },
blueprint: InteriorBlueprintRoom,
type: InteriorJob["type"],
target: string | number | undefined,
modifiers?: {
levelSpeedMultiplier?: number;
moduleSpeedMultiplier?: number;
effectFloor?: number;
},
): number {
return applyInteriorDurationFactor({
baseMs: baseDurationMinutes(blueprint, type, target) * 60_000,
levelSpeedMultiplier: modifiers?.levelSpeedMultiplier ?? 1,
moduleSpeedMultiplier: modifiers?.moduleSpeedMultiplier ?? 1,
condition: room.condition,
effectFloor: modifiers?.effectFloor ?? 0,
});
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,19 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TYPE "public"."enum_structures_module_options_effects_type" ADD VALUE 'interior_job_speed';
ALTER TYPE "public"."enum_structures_module_options_effects_type" ADD VALUE 'interior_output_bonus';
ALTER TABLE "structures_rooms_levels_effects" ALTER COLUMN "value" DROP NOT NULL;
ALTER TABLE "structures_rooms_levels_effects" ADD COLUMN "target" varchar;`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "structures_module_options_effects" ALTER COLUMN "type" SET DATA TYPE text;
DROP TYPE "public"."enum_structures_module_options_effects_type";
CREATE TYPE "public"."enum_structures_module_options_effects_type" AS ENUM('capacity_mass', 'production_multiplier', 'storage_slots');
ALTER TABLE "structures_module_options_effects" ALTER COLUMN "type" SET DATA TYPE "public"."enum_structures_module_options_effects_type" USING "type"::"public"."enum_structures_module_options_effects_type";
ALTER TABLE "structures_rooms_levels_effects" ALTER COLUMN "value" SET NOT NULL;
ALTER TABLE "structures_rooms_levels_effects" DROP COLUMN "target";`)
}

View file

@ -144,6 +144,7 @@ import * as migration_20261019_120000_add_ai_prompt_entity_context from './20261
import * as migration_20261019_121500_use_env_ai_model from './20261019_121500_use_env_ai_model';
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';
export const migrations = [
{
@ -874,6 +875,11 @@ export const migrations = [
{
up: migration_20261020_171725_add_superstructure_interior.up,
down: migration_20261020_171725_add_superstructure_interior.down,
name: '20261020_171725_add_superstructure_interior'
name: '20261020_171725_add_superstructure_interior',
},
{
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'
},
];

View file

@ -1556,9 +1556,14 @@ export interface Structure {
category: 'production' | 'logistics' | 'defense' | 'utility';
description?: string | null;
effects: {
type: 'capacity_mass' | 'production_multiplier' | 'storage_slots';
type:
| 'capacity_mass'
| 'production_multiplier'
| 'storage_slots'
| 'interior_job_speed'
| 'interior_output_bonus';
/**
* capacity_mass: extra kg of storage. storage_slots: extra grid slots. production_multiplier: output boost as a fraction (0.25 = +25%).
* capacity_mass: extra kg of storage. storage_slots: extra grid slots. production_multiplier: output boost as a fraction (0.25 = +25%). interior_job_speed: faster interior jobs as a fraction (0.25 = 25% faster). interior_output_bonus: extra interior job output as a fraction (0.1 = +10%).
*/
value: number;
id?: string | null;

View file

@ -9,15 +9,19 @@ import type {
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 { 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";
@ -68,6 +72,9 @@ const created = {
resources: [] as number[],
blueprints: [] as number[],
structures: [] as number[],
technologies: [] as number[],
classifications: [] as number[],
staffing: [] as number[],
};
// --- fixtures --------------------------------------------------------------
@ -116,6 +123,7 @@ async function makeResource(label: string, massPerUnit: number): Promise<Resourc
async function makeBlueprint(
label: string,
maxCapacityMass: number | null = null,
moduleOptions?: Structure["moduleOptions"],
): Promise<Structure> {
const doc = (await payload.create({
collection: "structures",
@ -130,6 +138,7 @@ async function makeBlueprint(
terrainType: "land",
maxHealth: 100,
maxCapacityMass,
moduleOptions,
},
overrideAccess: true,
depth: 0,
@ -138,6 +147,62 @@ async function makeBlueprint(
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;
@ -246,6 +311,11 @@ beforeAll(async () => {
afterAll(async () => {
const structureIds = created.structures;
// Staffing rows reference game-structures, so they must go first.
for (const id of created.staffing) {
await payload.delete({ collection: "npc-staffing", id, overrideAccess: true }).catch(() => {});
}
if (structureIds.length > 0) {
const rooms = await payload
.find({
@ -314,6 +384,23 @@ afterAll(async () => {
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.resources) {
await payload.delete({ collection: "resources", id, overrideAccess: true }).catch(() => {});
}
@ -781,6 +868,311 @@ describe("Interior job sweep", () => {
});
});
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 },

View file

@ -195,17 +195,23 @@ describe("Module system", () => {
capacityMass: 500,
productionMultiplier: 0.25,
storageSlots: 2,
interiorJobSpeed: 0,
interiorOutputBonus: 0,
});
// Unknown and empty installs contribute nothing.
expect(installedModuleEffects(blueprint, ["Z"])).toEqual({
capacityMass: 0,
productionMultiplier: 0,
storageSlots: 0,
interiorJobSpeed: 0,
interiorOutputBonus: 0,
});
expect(installedModuleEffects({}, [])).toEqual({
capacityMass: 0,
productionMultiplier: 0,
storageSlots: 0,
interiorJobSpeed: 0,
interiorOutputBonus: 0,
});
});
});