1
0
Fork 0

feat(game-structures): add Labor Crew admin panel for staffing writes

Wire the previously orphaned LaborCrewPanel into the game-structures
editor so staff can set actual headcount and per-worker wage for a
labor classification. Adds a laborCrewPanel ui field on the edit view,
a POST route under /api/game-structures that authenticates and gates on
game-structures:update, delegates to the canonical setLaborHeadcount
service (enforcing caps and wage logic), and an integration test
covering auth, validation, and cap enforcement.
This commit is contained in:
Jason Fraley 2026-10-07 23:28:35 -04:00
parent 02307aa2ee
commit 0370df6c2d
4 changed files with 665 additions and 0 deletions

View file

@ -0,0 +1,70 @@
import { NextRequest, NextResponse } from "next/server";
import config from "@payload-config";
import { getPayload } from "payload";
import { setLaborHeadcount } from "@/lib/base/staffing";
import { hasPermission } from "@/utils/access-control/hasPermission";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* Admin-panel labor-crew write for the game-structures editor. Consumed by the
* Labor Crew panel (`LaborCrewPanel`) on the game-structures edit view: it sets
* the actual headcount and per-worker wage for a labor classification on a
* 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.
*/
export async function POST(req: NextRequest) {
const payload = await getPayload({ config: await config });
const { user } = await payload.auth({ headers: req.headers, canSetHeaders: false });
if (!user) {
return NextResponse.json({ success: false, error: "Unauthorized" }, { status: 401 });
}
if (!(await hasPermission(payload, user, "game-structures:update"))) {
return NextResponse.json({ success: false, error: "Forbidden" }, { status: 403 });
}
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ success: false, error: "Invalid JSON body" }, { status: 400 });
}
const { structureId, classificationId, headcount, unitSalary } = (body ?? {}) as {
structureId?: unknown;
classificationId?: unknown;
headcount?: unknown;
unitSalary?: unknown;
};
if (!Number.isInteger(structureId) || !Number.isInteger(classificationId)) {
return NextResponse.json(
{ success: false, error: "structureId and classificationId are required." },
{ status: 400 },
);
}
try {
await setLaborHeadcount(payload, {
structureId: structureId as number,
classificationId: classificationId as number,
headcount: Number(headcount) || 0,
unitSalary: Number(unitSalary) || 0,
});
return NextResponse.json({ success: true });
} catch (err) {
payload.logger.error(
`[game-structures] set-labor-headcount failed: ${
err instanceof Error ? err.message : String(err)
}`,
);
return NextResponse.json(
{ success: false, error: err instanceof Error ? err.message : "Labor update failed." },
{ status: 400 },
);
}
}

View file

@ -536,5 +536,14 @@ export const GameStructures: CollectionConfig = {
],
},
},
{
name: "laborCrewPanel",
type: "ui",
admin: {
components: {
Field: "@/components/admin/game/LaborCrewField",
},
},
},
],
};

View file

@ -0,0 +1,268 @@
"use client";
import { useEffect, useState } from "react";
import { UsersIcon } from "lucide-react";
import { toast, useDocumentInfo, useField } from "@payloadcms/ui";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import type { LaborClassificationOption } from "@/lib/base/types";
interface LaborCrew {
classificationId: number;
classificationName: string;
headcount: number;
unitSalary: number;
requiredHeadcount: number;
maxHeadcount: number;
enforcedSalary: number | null;
}
interface LaborEdit {
headcount: string;
unitSalary: string;
}
export function LaborCrewPanel() {
const documentInfo = useDocumentInfo();
const laborRequirementsField = useField<{
classificationId?: number | null;
requiredHeadcount?: number | null;
maxHeadcount?: number | null;
enforcedSalary?: number | null;
}[]>({
path: "laborRequirements",
});
const [crew, setCrew] = useState<LaborCrew[]>([]);
const [edits, setEdits] = useState<Record<number, LaborEdit>>({});
const [loadingClassifications, setLoadingClassifications] = useState(false);
const [savingId, setSavingId] = useState<number | null>(null);
// Fetch classifications and current crew from REST
useEffect(() => {
let cancelled = false;
async function loadData() {
setLoadingClassifications(true);
try {
const [classificationsRes, crewRes] = await Promise.all([
fetch("/api/labor-classifications?depth=0"),
fetch(`/api/npc-staffing?where.structure.id=${documentInfo.id}&depth=0`),
]);
if (cancelled) return;
const classifications = (await classificationsRes.json()).docs as LaborClassificationOption[];
const crewDocs = await crewRes.json();
// Build crew list from laborRequirements + current npc-staffing docs
const requirementList = laborRequirementsField.value ?? [];
const newCrew: LaborCrew[] = requirementList.flatMap((req) => {
const classification = classifications.find(
(c) => c.id === req.classificationId,
);
if (!classification) return [];
const crewMembers = (crewDocs.docs ?? []).filter(
(m: any) =>
m.positionType === "labor" &&
m.laborClassification?.id === classification.id,
);
const headcount = crewMembers.reduce((sum: number, m: any) => sum + (m.headcount ?? 1), 0);
const unitSalary = crewMembers[0]?.salary ?? classification.defaultUnitSalary ?? 0;
return {
classificationId: classification.id,
classificationName: classification.name,
headcount,
unitSalary,
requiredHeadcount: req.requiredHeadcount ?? 0,
maxHeadcount: req.maxHeadcount ?? Infinity,
enforcedSalary: req.enforcedSalary ?? null,
};
});
setCrew(newCrew);
} catch {
toast.error("Failed to load labor data");
} finally {
setLoadingClassifications(false);
}
}
if (documentInfo.id) loadData();
return () => { cancelled = true; };
}, [documentInfo.id, laborRequirementsField.value]);
function getEdit(crewItem: LaborCrew): LaborEdit {
return edits[crewItem.classificationId] ?? {
headcount: String(crewItem.headcount),
unitSalary: String(crewItem.unitSalary),
};
}
function updateEdit(crewItem: LaborCrew, field: keyof LaborEdit, value: string) {
setEdits((current) => ({
...current,
[crewItem.classificationId]: {
...getEdit(crewItem),
[field]: value,
},
}));
}
async function handleSave(crewItem: LaborCrew) {
const edit = getEdit(crewItem);
const headcount = Number(edit.headcount);
const unitSalary = Number(edit.unitSalary) || 0;
if (!Number.isInteger(headcount) || headcount < 0) {
toast.error("Headcount must be a whole number of 0 or more.");
return;
}
if (!Number.isFinite(unitSalary) || unitSalary < 0) {
toast.error("Wage cannot be negative.");
return;
}
setSavingId(crewItem.classificationId);
try {
const response = await fetch("/api/game-structures/set-labor-headcount", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
structureId: documentInfo.id,
classificationId: crewItem.classificationId,
headcount,
unitSalary,
}),
});
const result = await response.json();
if (!result.success) {
toast.error(result.error ?? "Labor update failed");
return;
}
// Update local state
setCrew((current) =>
current.map((c) =>
c.classificationId === crewItem.classificationId
? { ...c, headcount, unitSalary }
: c,
),
);
setEdits((current) => {
const next = { ...current };
delete next[crewItem.classificationId];
return next;
});
toast.success(`${crewItem.classificationName} crew updated`);
} catch {
toast.error("Labor update failed");
} finally {
setSavingId(null);
}
}
if (!documentInfo.id) return null;
return (
<Card className="mt-6">
<CardHeader className="gap-2">
<CardTitle className="flex items-center gap-2">
<UsersIcon className="size-4 text-muted-foreground" />
Labor Crew
</CardTitle>
<CardDescription>
Set actual headcount and wages per labor classification for this structure.
Changes apply immediately via the staffing system.
</CardDescription>
</CardHeader>
<CardContent>
{loadingClassifications ? (
<p className="text-sm text-muted-foreground">Loading crew data...</p>
) : crew.length === 0 ? (
<p className="text-sm text-muted-foreground">No labor classifications configured for this structure.</p>
) : (
<div className="flex flex-col gap-3">
{crew.map((item, index) => {
const edit = getEdit(item);
const isSaving = savingId === item.classificationId;
return (
<div key={item.classificationId}>
{index > 0 && <Separator />}
<div className="flex flex-col gap-3 py-3 first:pt-0 last:pb-0">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<p className="font-medium">
{item.classificationName}: {item.headcount} hired · {item.requiredHeadcount} required · max {item.maxHeadcount}
</p>
<p className="font-mono text-sm tabular-nums text-muted-foreground">
{item.unitSalary}/tick each · {item.unitSalary * item.headcount}/tick total
</p>
</div>
</div>
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor={`labor-headcount-${item.classificationId}`}>
Headcount
</Label>
<Input
id={`labor-headcount-${item.classificationId}`}
type="number"
min={0}
max={item.maxHeadcount}
step={1}
inputMode="numeric"
value={edit.headcount}
onChange={(e) => updateEdit(item, "headcount", e.target.value)}
disabled={isSaving}
/>
</div>
<div className="flex flex-1 flex-col gap-1.5">
<Label htmlFor={`labor-wage-${item.classificationId}`}>
Wage per worker
</Label>
<Input
id={`labor-wage-${item.classificationId}`}
type="number"
min={0}
step="any"
value={edit.unitSalary}
onChange={(e) => updateEdit(item, "unitSalary", e.target.value)}
disabled={isSaving || item.enforcedSalary !== null}
/>
{item.enforcedSalary !== null && (
<p className="text-xs text-muted-foreground">
Enforced by structure blueprint ({item.enforcedSalary}/tick)
</p>
)}
</div>
<Button
variant="outline"
size="sm"
onClick={() => void handleSave(item)}
disabled={isSaving}
>
{isSaving ? "Saving..." : "Apply"}
</Button>
</div>
</div>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
);
}
export default LaborCrewPanel;

View file

@ -0,0 +1,318 @@
// @vitest-environment node
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
// the global Uint8Array come from different realms, so signing throws a TypeError.
import { getFieldsToSign, getPayload, jwtSign, type CollectionSlug, type Payload, type Where } from "payload";
import config from "@/payload.config";
import { randomUUID } from "node:crypto";
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 { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
let payload: Payload;
const RUN = `lcr-${Date.now().toString(36)}`;
const LEXICAL_EMPTY = {
root: {
children: [{ text: "", format: "", type: "text", version: 1 }],
direction: null,
format: "",
indent: 0,
version: 1,
},
};
const TIMEOUT = 30_000;
/** Build a NextRequest against the admin route, optionally authenticated + bodied. */
function request(token?: string, body?: unknown): NextRequest {
const headers = new Headers();
if (token) headers.set("cookie", `payload-token=${token}`);
return new NextRequest(
"http://localhost/api/game-structures/set-labor-headcount",
{
headers,
method: "POST",
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
},
);
}
/**
* Mint a payload-token JWT for a user, mirroring the impersonation route:
* persist a session on the user doc, then sign with that session's sid.
*/
async function mintToken(userId: number): Promise<string> {
const collection = payload.collections.users.config;
const user = await payload.findByID({
collection: "users",
id: userId,
depth: 0,
overrideAccess: true,
});
const sid = randomUUID();
const now = new Date();
const expiresAt = new Date(now.getTime() + collection.auth.tokenExpiration * 1000);
const sessions = (user.sessions ?? []).filter(
(session) => new Date(session.expiresAt).getTime() > now.getTime(),
);
sessions.push({ id: sid, createdAt: now.toISOString(), expiresAt: expiresAt.toISOString() });
await payload.update({
collection: "users",
id: userId,
data: { sessions },
overrideAccess: true,
});
const { token } = await jwtSign({
fieldsToSign: getFieldsToSign({
collectionConfig: collection,
email: user.email ?? "",
sid,
user,
}),
secret: payload.secret,
tokenExpiration: collection.auth.tokenExpiration,
});
return token;
}
async function sweep(collection: CollectionSlug, where: Where) {
const found = await payload.find({
collection,
where,
limit: 200,
depth: 0,
overrideAccess: true,
});
await Promise.allSettled(
found.docs.map((doc) =>
payload.delete({ collection, id: doc.id as number, overrideAccess: true }),
),
);
}
describe("game-structures set-labor-headcount admin route", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
const blueprintIds: number[] = [];
const classificationIds: number[] = [];
const mapIds: number[] = [];
let superUserId: number;
let plainUserId: number;
let superUserToken: string;
let plainUserToken: string;
let siteId: number;
let classificationId: number;
let hiringWasEnabled = false;
beforeAll(async () => {
payload = await getPayload({ config: await config });
invalidatePermissionCache();
// enable staffing so setLaborHeadcount does not fail closed.
const rules = await payload.findGlobal({ slug: "game-rules", depth: 0, overrideAccess: true });
hiringWasEnabled = Boolean(rules.staffHiringEnabled);
await payload.updateGlobal({
slug: "game-rules",
data: { staffHiringEnabled: true },
overrideAccess: true,
depth: 0,
});
// A map to seat the structure on (not required, but mirrors real placement).
const map = (await payload.create({
collection: "maps",
data: { name: `${RUN} map`, worldSizeWidth: 8192, worldSizeHeight: 8192, basemapMode: "image" },
overrideAccess: true,
depth: 0,
})) as { id: number };
mapIds.push(map.id);
// A classification with plenty of available workers.
const classification = (await payload.create({
collection: "labor-classifications",
data: { name: `${RUN} Labor`, key: `${RUN}-labor`, defaultUnitSalary: 5, availableHeadcount: 50 },
overrideAccess: true,
depth: 0,
})) as { id: number };
classificationIds.push(classification.id);
classificationId = classification.id;
// A resource so the blueprint can carry required materials.
const materialResource = (await payload.create({
collection: "resources",
data: {
name: `${RUN} Material`,
codeName: `${RUN}-material`,
approvalStatus: "in_progress",
type: "physical",
baseValue: 1,
rarity: "common",
unitOfMeasure: "kg",
massPerUnit: 1,
gridWidth: 1,
gridHeight: 1,
},
overrideAccess: true,
depth: 0,
})) as { id: number };
// A blueprint that requires the classification (laborRequirements is copied into
// the game-structure on create by the beforeChange hook).
const blueprint = (await payload.create({
collection: "structures",
data: {
name: `${RUN} Site`,
codeName: `${RUN}-site`,
approvalStatus: "in_progress",
category: "logistics",
materials: [{ resource: materialResource.id, amount: 1 }],
constructionDurationMinutes: 10,
constructionCrewRequired: 1,
terrainType: "land",
maxHealth: 100,
description: LEXICAL_EMPTY as unknown as Structure["description"],
laborRequirements: [
{ classification: classification.id, requiredHeadcount: 2, maxHeadcount: 6 },
],
},
overrideAccess: true,
depth: 0,
})) as { id: number };
blueprintIds.push(blueprint.id);
const site = (await payload.create({
collection: "game-structures",
data: { name: `${RUN} Site`, type: blueprint.id, map: map.id, coordinates: [500, 500] },
overrideAccess: true,
depth: 0,
})) as { id: number };
siteId = site.id;
// Superuser role + user (passes game-structures:update via the superuser bypass).
const superRole = (await payload.create({
collection: "roles",
data: { name: `${RUN} Labor Admin`, slug: `${RUN}-labor-admin`, isSuperuser: true },
overrideAccess: true,
depth: 0,
})) as { id: number };
roleIds.push(superRole.id);
const superUser = (await payload.create({
collection: "users",
data: {
username: `${RUN}-su`,
discordUsername: `${RUN}-su`,
displayName: "SU",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
// Permission resolution reads roleDocs (dynamic RBAC), not the legacy enum.
roleDocs: [superRole.id],
},
overrideAccess: true,
depth: 0,
})) as User;
userIds.push(superUser.id);
superUserId = superUser.id;
// Plain (no-permission) role + user.
const plainRole = (await payload.create({
collection: "roles",
data: { name: `${RUN} Plain`, slug: `${RUN}-plain`, permissions: [] },
overrideAccess: true,
depth: 0,
})) as { id: number };
roleIds.push(plainRole.id);
const plainUser = (await payload.create({
collection: "users",
data: {
username: `${RUN}-plain`,
discordUsername: `${RUN}-plain`,
displayName: "Plain",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roleDocs: [plainRole.id],
},
overrideAccess: true,
depth: 0,
})) as User;
userIds.push(plainUser.id);
plainUserId = plainUser.id;
superUserToken = await mintToken(superUserId);
plainUserToken = await mintToken(plainUserId);
}, TIMEOUT);
afterAll(async () => {
if (!payload) return;
// FK-safe order, best-effort (the test DB is truncated between runs regardless).
if (typeof siteId === "number") {
await sweep("npc-staffing", { structure: { equals: siteId } });
}
await sweep("game-structures", { name: { like: `${RUN}%` } });
await sweep("structures", { name: { like: `${RUN}%` } });
await sweep("labor-classifications", { name: { like: `${RUN}%` } });
await sweep("maps", { name: { like: `${RUN}%` } });
for (const id of userIds) {
await sweep("profiles", { user: { equals: id } });
await Promise.allSettled([payload.delete({ collection: "users", id, overrideAccess: true })]);
}
for (const id of roleIds) {
await Promise.allSettled([payload.delete({ collection: "roles", id, overrideAccess: true })]);
}
await payload.updateGlobal({
slug: "game-rules",
data: { staffHiringEnabled: hiringWasEnabled },
overrideAccess: true,
depth: 0,
});
}, TIMEOUT);
it("rejects unauthenticated requests with 401", async () => {
const res = await POST(request());
expect(res.status).toBe(401);
}, TIMEOUT);
it("rejects an authenticated non-staff user with 403", async () => {
const res = await POST(request(plainUserToken));
expect(res.status).toBe(403);
}, TIMEOUT);
it("rejects a malformed body with 400", async () => {
const res = await POST(request(superUserToken, { classificationId }));
expect(res.status).toBe(400);
}, TIMEOUT);
it("sets the crew headcount for a valid request", async () => {
const res = await POST(
request(superUserToken, { structureId: siteId, classificationId, headcount: 3, 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(3);
}, 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 }),
);
expect(res.status).toBe(400);
expect(await res.json()).toMatchObject({ success: false });
}, TIMEOUT);
});