From db98adbcee1fcc2626b589f016cd88c9af190d45 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Sat, 10 Oct 2026 13:23:52 -0400 Subject: [PATCH] fix(game-structures): repair Labor Crew panel data loading - Read labor requirements via useAllFormFields + reduceFieldsToValues: useField on an array path returns the row count, not rows, so requirementList.flatMap threw and raised the "Failed to load labor data" toast on every page load - Use valid REST where syntax (where[structure][equals]= plus positionType/status filters); the dot-notation key was silently ignored and returned every staffing doc unfiltered - Match staffing rows by raw relationship id at depth=0; m.laborClassification?.id never matched numeric ids - Validate fetch responses and show a distinct load-failure message instead of the misleading "no classifications configured" empty state - Give the Apply button type="button" so it stops submitting the whole document form on every click --- src/components/admin/game/LaborCrewField.tsx | 101 ++++++++++++++----- 1 file changed, 78 insertions(+), 23 deletions(-) diff --git a/src/components/admin/game/LaborCrewField.tsx b/src/components/admin/game/LaborCrewField.tsx index 642e013e..59abe542 100644 --- a/src/components/admin/game/LaborCrewField.tsx +++ b/src/components/admin/game/LaborCrewField.tsx @@ -1,8 +1,9 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { UsersIcon } from "lucide-react"; -import { toast, useDocumentInfo, useField } from "@payloadcms/ui"; +import { toast, useAllFormFields, useDocumentInfo } from "@payloadcms/ui"; +import { reduceFieldsToValues } from "payload/shared"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -25,20 +26,45 @@ interface LaborEdit { unitSalary: string; } +/** Form-state shape of a laborRequirements row (collection field names). */ +interface LaborRequirementRow { + classification?: number | { id: number } | null; + requiredHeadcount?: number | null; + maxHeadcount?: number | null; + enforcedSalary?: number | null; +} + +/** Relationship values arrive as raw ids (depth=0) or populated objects. */ +function relId(value: unknown): number | null { + if (typeof value === "number") return value; + if (value !== null && typeof value === "object" && "id" in value) { + const id = (value as { id: unknown }).id; + return typeof id === "number" ? id : null; + } + return null; +} + export function LaborCrewPanel() { const documentInfo = useDocumentInfo(); - const laborRequirementsField = useField<{ - classificationId?: number | null; - requiredHeadcount?: number | null; - maxHeadcount?: number | null; - enforcedSalary?: number | null; - }[]>({ - path: "laborRequirements", - }); + const [formFields] = useAllFormFields(); + + // Array fields store only a row count at their own path in Payload's form + // state; rebuild the actual rows from the flattened field tree instead. + const laborRequirements = useMemo(() => { + const data = reduceFieldsToValues(formFields, true) as { + laborRequirements?: LaborRequirementRow[]; + }; + return Array.isArray(data.laborRequirements) ? data.laborRequirements : []; + }, [formFields]); + + const requirementsKey = JSON.stringify(laborRequirements); + const requirementsRef = useRef(laborRequirements); + requirementsRef.current = laborRequirements; const [crew, setCrew] = useState([]); const [edits, setEdits] = useState>({}); const [loadingClassifications, setLoadingClassifications] = useState(false); + const [loadFailed, setLoadFailed] = useState(false); const [savingId, setSavingId] = useState(null); // Fetch classifications and current crew from REST @@ -47,31 +73,50 @@ export function LaborCrewPanel() { async function loadData() { setLoadingClassifications(true); + setLoadFailed(false); try { + const staffingParams = new URLSearchParams({ + depth: "0", + limit: "100", + "where[structure][equals]": String(documentInfo.id), + "where[positionType][equals]": "labor", + "where[status][equals]": "active", + }); const [classificationsRes, crewRes] = await Promise.all([ - fetch("/api/labor-classifications?depth=0"), - fetch(`/api/npc-staffing?where.structure.id=${documentInfo.id}&depth=0`), + fetch("/api/labor-classifications?depth=0&limit=100"), + fetch(`/api/npc-staffing?${staffingParams.toString()}`), ]); if (cancelled) return; - const classifications = (await classificationsRes.json()).docs as LaborClassificationOption[]; - const crewDocs = await crewRes.json(); + if (!classificationsRes.ok || !crewRes.ok) { + throw new Error( + `Labor data request failed (classifications ${classificationsRes.status}, staffing ${crewRes.status})`, + ); + } + + const classificationsBody = await classificationsRes.json(); + const crewBody = await crewRes.json(); + const classifications = classificationsBody?.docs as + | LaborClassificationOption[] + | undefined; + if (!Array.isArray(classifications)) { + throw new Error("Unexpected labor classifications response shape"); + } + const crewDocs: any[] = Array.isArray(crewBody?.docs) ? crewBody.docs : []; // Build crew list from laborRequirements + current npc-staffing docs - const requirementList = laborRequirementsField.value ?? []; + const requirementList = requirementsRef.current; const newCrew: LaborCrew[] = requirementList.flatMap((req) => { const classification = classifications.find( - (c) => c.id === req.classificationId, + (c) => c.id === relId(req.classification), ); if (!classification) return []; - const crewMembers = (crewDocs.docs ?? []).filter( - (m: any) => - m.positionType === "labor" && - m.laborClassification?.id === classification.id, + const crewMembers = crewDocs.filter( + (m) => relId(m.laborClassification) === classification.id, ); - const headcount = crewMembers.reduce((sum: number, m: any) => sum + (m.headcount ?? 1), 0); + const headcount = crewMembers.reduce((sum, m) => sum + (m.headcount ?? 1), 0); const unitSalary = crewMembers[0]?.salary ?? classification.defaultUnitSalary ?? 0; return { @@ -86,7 +131,9 @@ export function LaborCrewPanel() { }); setCrew(newCrew); - } catch { + } catch (err) { + console.error("[LaborCrewPanel] Failed to load labor data", err); + setLoadFailed(true); toast.error("Failed to load labor data"); } finally { setLoadingClassifications(false); @@ -95,7 +142,10 @@ export function LaborCrewPanel() { if (documentInfo.id) loadData(); return () => { cancelled = true; }; - }, [documentInfo.id, laborRequirementsField.value]); + // requirementsKey tracks the labor requirements content; requirementsRef + // always holds the latest rows without retriggering the effect. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [documentInfo.id, requirementsKey]); function getEdit(crewItem: LaborCrew): LaborEdit { return edits[crewItem.classificationId] ?? { @@ -186,6 +236,10 @@ export function LaborCrewPanel() { {loadingClassifications ? (

Loading crew data...

+ ) : loadFailed ? ( +

+ Labor data could not be loaded. Reload the page to try again. +

) : crew.length === 0 ? (

No labor classifications configured for this structure.

) : ( @@ -246,6 +300,7 @@ export function LaborCrewPanel() { )}