From 0370df6c2dee5543b870e85d1b2c9bb885b1771c Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Wed, 7 Oct 2026 23:28:35 -0400 Subject: [PATCH] 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. --- .../set-labor-headcount/route.ts | 70 ++++ src/collections/game/GameStructures.ts | 9 + src/components/admin/game/LaborCrewField.tsx | 268 +++++++++++++++ .../game-structures-labor-route.int.spec.ts | 318 ++++++++++++++++++ 4 files changed, 665 insertions(+) create mode 100644 src/app/api/game-structures/set-labor-headcount/route.ts create mode 100644 src/components/admin/game/LaborCrewField.tsx create mode 100644 tests/int/game-structures-labor-route.int.spec.ts diff --git a/src/app/api/game-structures/set-labor-headcount/route.ts b/src/app/api/game-structures/set-labor-headcount/route.ts new file mode 100644 index 00000000..a19abe79 --- /dev/null +++ b/src/app/api/game-structures/set-labor-headcount/route.ts @@ -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 }, + ); + } +} diff --git a/src/collections/game/GameStructures.ts b/src/collections/game/GameStructures.ts index d8df84b9..8efd747d 100644 --- a/src/collections/game/GameStructures.ts +++ b/src/collections/game/GameStructures.ts @@ -536,5 +536,14 @@ export const GameStructures: CollectionConfig = { ], }, }, + { + name: "laborCrewPanel", + type: "ui", + admin: { + components: { + Field: "@/components/admin/game/LaborCrewField", + }, + }, + }, ], }; diff --git a/src/components/admin/game/LaborCrewField.tsx b/src/components/admin/game/LaborCrewField.tsx new file mode 100644 index 00000000..642e013e --- /dev/null +++ b/src/components/admin/game/LaborCrewField.tsx @@ -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([]); + const [edits, setEdits] = useState>({}); + const [loadingClassifications, setLoadingClassifications] = useState(false); + const [savingId, setSavingId] = useState(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 ( + + + + + Labor Crew + + + Set actual headcount and wages per labor classification for this structure. + Changes apply immediately via the staffing system. + + + + {loadingClassifications ? ( +

Loading crew data...

+ ) : crew.length === 0 ? ( +

No labor classifications configured for this structure.

+ ) : ( +
+ {crew.map((item, index) => { + const edit = getEdit(item); + const isSaving = savingId === item.classificationId; + + return ( +
+ {index > 0 && } +
+
+
+

+ {item.classificationName}: {item.headcount} hired · {item.requiredHeadcount} required · max {item.maxHeadcount} +

+

+ {item.unitSalary}/tick each · {item.unitSalary * item.headcount}/tick total +

+
+
+ +
+
+ + updateEdit(item, "headcount", e.target.value)} + disabled={isSaving} + /> +
+
+ + updateEdit(item, "unitSalary", e.target.value)} + disabled={isSaving || item.enforcedSalary !== null} + /> + {item.enforcedSalary !== null && ( +

+ Enforced by structure blueprint ({item.enforcedSalary}/tick) +

+ )} +
+ +
+
+
+ ); + })} +
+ )} +
+
+ ); +} + +export default LaborCrewPanel; diff --git a/tests/int/game-structures-labor-route.int.spec.ts b/tests/int/game-structures-labor-route.int.spec.ts new file mode 100644 index 00000000..3ecdf3cf --- /dev/null +++ b/tests/int/game-structures-labor-route.int.spec.ts @@ -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 { + 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); +});