1
0
Fork 0

fix(base): allow admin labor headcount edits while hiring is disabled

The admin game-structures Labor Crew panel writes through setLaborHeadcount, which failed closed whenever Game Rules staffHiringEnabled was off. Back-office operators had to toggle hiring on just to adjust headcount.

setLaborHeadcount now accepts an allowWhenHiringDisabled option. Only the admin API route passes it; player-facing server actions keep the gate.
This commit is contained in:
Jason Fraley 2026-10-19 14:25:42 -04:00
parent 805f6dee84
commit 57b6999e61
8 changed files with 85 additions and 12 deletions

View file

@ -15,7 +15,9 @@ export const runtime = "nodejs";
* structure, delegating to the canonical `setLaborHeadcount` service (which
* enforces caps, wage logic, and emits the resulting events).
*
* Access mirrors the game-structures collection update rule.
* Access mirrors the game-structures collection update rule. This is a
* back-office write, so it bypasses the player-facing `staffHiringEnabled`
* gate: operators can adjust labor headcount without toggling hiring on.
*/
export async function POST(req: NextRequest) {
const payload = await getPayload({ config: await config });
@ -49,12 +51,16 @@ export async function POST(req: NextRequest) {
}
try {
await setLaborHeadcount(payload, {
structureId: structureId as number,
classificationId: classificationId as number,
headcount: Number(headcount) || 0,
unitSalary: Number(unitSalary) || 0,
});
await setLaborHeadcount(
payload,
{
structureId: structureId as number,
classificationId: classificationId as number,
headcount: Number(headcount) || 0,
unitSalary: Number(unitSalary) || 0,
},
{ allowWhenHiringDisabled: true },
);
return NextResponse.json({ success: true });
} catch (err) {
payload.logger.error(

View file

@ -142,7 +142,7 @@ export const GameRules: GlobalConfig = {
defaultValue: false,
admin: {
description:
"When off, logistics officers cannot hire staff anywhere (both labor crews and named NPC staff).",
"When off, logistics officers cannot hire staff anywhere (both labor crews and named NPC staff). Back-office labor headcount edits in the admin panel are not affected.",
},
},
{

View file

@ -9,7 +9,7 @@ Labor/staffing simulation for structures. Collections in `src/collections/game/`
- **Modules (slice 3)**: blueprints declare `moduleSlots` + a `moduleOptions` catalog (name, category, effects, install materials) via `moduleFields.ts`; instances only store `installedModules` (action-managed, readOnly). `src/lib/base/modules.ts`: `installModule`/`uninstallModule` (materials consumed grid+void, no refund; operational structures only), `installedModuleEffects` aggregates `capacity_mass` (extra kg) / `production_multiplier` (output fraction boost) / `storage_slots` (grid slots metric). `effectiveMaxMass` wires the capacity bonus into the deposit/transfer/shipment checks + map route; the production tick applies the multiplier and the raised cap; `getGridSlots`/`calculateUtilization` take the bonuses. Events: `structure:module-install` / `structure:module-uninstall`. UI: `SlotsPanel` (structure detail page + map drawer).
- **Adjacency auras (slice 5)**: blueprint "Adjacency Aura" group (`auraFields.ts`: `effectType` production_multiplier|capacity_mass, `value`, `rangeMeters`) projects one effect onto operational neighbors. `src/lib/base/adjacency.ts` `auraBonusAt` (pure: operational sources only, self excluded, range in meters) is wired into the production tick (multiplier stacks with module multipliers; capacity raises the clamp) and computed from the tick's own site list with no extra queries (scoped runs fetch unscoped sources).
- **Server actions**: `src/app/(frontend)/logistics/base/actions.ts` — `upgradeStructure`, `hireStaff`, `fireStaff`, `setLaborHeadcount` (logistics-qualification gated, canonical ActionResult pattern).
- **Gate**: Game Rules globals `staffHiringEnabled` + `staffHiringDisabledMessage` disable all hiring when off.
- **Gate**: Game Rules globals `staffHiringEnabled` + `staffHiringDisabledMessage` disable all hiring when off. Player-facing `hireStaff`/`setLaborHeadcount` fail closed; the admin game-structures Labor Crew panel write (`POST /api/game-structures/set-labor-headcount`) passes `allowWhenHiringDisabled` so back-office headcount edits work without toggling the gate.
- **Base tick**: see `base-tick` bin under Shipments & game tick.
- **UI**: `src/components/frontend/baseManagement/` (`StaffRoster`, `HireStaffDialog`, `EmploymentCard`, `UpgradeCard`) mounted on the structure detail page (`logistics/structures/[id]`).
- **Compounds (slice 4)**: game-structures `parentStructure` self-rel; children attach at placement (PlacementDialog "Compound" picker, validated: same map, hub not itself a child). Operational children pool storage into the hub via `src/lib/map/compounds.ts` (`aggregateCompoundStorage`); the map feature route folds child storage into the hub feature, force-hides child map labels, and reports `compoundChildren`; the hub ribbon reads "Compound: N buildings" and the popup gains a Compound cell. Structure detail pages show a Compound block (hub link on children; child chips on hubs).

View file

@ -6,6 +6,7 @@ export type {
HireStaffInput,
LaborClassificationOption,
SetLaborHeadcountInput,
SetLaborHeadcountOptions,
StaffingPositionType,
StructureStaffingOption,
} from "./types";

View file

@ -4,7 +4,7 @@ import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { relationshipId } from "./storage";
import { applyCrewRateChange } from "./constructionSpeed";
import type { HireStaffInput, SetLaborHeadcountInput } from "./types";
import type { HireStaffInput, SetLaborHeadcountInput, SetLaborHeadcountOptions } from "./types";
export async function assertStaffHiringEnabled(payload: Payload): Promise<void> {
const rules = await payload.findGlobal({
@ -135,8 +135,11 @@ export async function hireStaff(
export async function setLaborHeadcount(
payload: Payload,
input: SetLaborHeadcountInput,
options: SetLaborHeadcountOptions = {},
): Promise<{ readonly id: number | null }> {
await assertStaffHiringEnabled(payload);
if (!options.allowWhenHiringDisabled) {
await assertStaffHiringEnabled(payload);
}
if (!Number.isInteger(input.headcount) || input.headcount < 0) {
throw new Error("Headcount must be a whole number of 0 or more.");
}

View file

@ -42,6 +42,14 @@ export type SetLaborHeadcountInput = {
readonly unitSalary: number;
};
export type SetLaborHeadcountOptions = {
/**
* Admin/back-office writes may change headcount while the player-facing
* `staffHiringEnabled` gate is off. Player-facing callers must leave this unset.
*/
readonly allowWhenHiringDisabled?: boolean;
};
export type BaseTickResult = {
readonly salariesPaid: number;
readonly salariesUnpaid: number;

View file

@ -12218,7 +12218,7 @@ export interface GameRule {
*/
lockerGridHeight?: number | null;
/**
* When off, logistics officers cannot hire staff anywhere (both labor crews and named NPC staff).
* When off, logistics officers cannot hire staff anywhere (both labor crews and named NPC staff). Back-office labor headcount edits in the admin panel are not affected.
*/
staffHiringEnabled?: boolean | null;
/**

View file

@ -10,6 +10,7 @@ import { NextRequest } from "next/server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Role, Structure, User } from "@/payload-types";
import { POST } from "@/app/api/game-structures/set-labor-headcount/route";
import { setLaborHeadcount } from "@/lib/base/staffing";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
let payload: Payload;
@ -308,6 +309,60 @@ describe("game-structures set-labor-headcount admin route", () => {
expect(active?.headcount).toBe(3);
}, TIMEOUT);
it("updates headcount from the admin route while hiring is disabled", async () => {
const rules = await payload.findGlobal({ slug: "game-rules", depth: 0, overrideAccess: true });
const wasEnabled = Boolean(rules.staffHiringEnabled);
await payload.updateGlobal({
slug: "game-rules",
data: { staffHiringEnabled: false },
overrideAccess: true,
depth: 0,
});
try {
// The player-facing service stays fail-closed without the admin option.
await expect(
setLaborHeadcount(payload, {
structureId: siteId,
classificationId,
headcount: 4,
unitSalary: 5,
}),
).rejects.toBeInstanceOf(Error);
const res = await POST(
request(superUserToken, {
structureId: siteId,
classificationId,
headcount: 4,
unitSalary: 5,
}),
);
expect(res.status).toBe(200);
expect(await res.json()).toMatchObject({ success: true });
const staffing = await payload.find({
collection: "npc-staffing",
where: {
structure: { equals: siteId },
laborClassification: { equals: classificationId },
positionType: { equals: "labor" },
},
overrideAccess: true,
depth: 0,
});
const active = staffing.docs.find((doc) => doc.status === "active");
expect(active?.headcount).toBe(4);
} finally {
await payload.updateGlobal({
slug: "game-rules",
data: { staffHiringEnabled: wasEnabled },
overrideAccess: true,
depth: 0,
});
}
}, TIMEOUT);
it("rejects a headcount over the blueprint cap with 400", async () => {
const res = await POST(
request(superUserToken, { structureId: siteId, classificationId, headcount: 999, unitSalary: 5 }),