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
This commit is contained in:
parent
9a0b78fcf0
commit
db98adbcee
1 changed files with 78 additions and 23 deletions
|
|
@ -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<LaborCrew[]>([]);
|
||||
const [edits, setEdits] = useState<Record<number, LaborEdit>>({});
|
||||
const [loadingClassifications, setLoadingClassifications] = useState(false);
|
||||
const [loadFailed, setLoadFailed] = useState(false);
|
||||
const [savingId, setSavingId] = useState<number | null>(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() {
|
|||
<CardContent>
|
||||
{loadingClassifications ? (
|
||||
<p className="text-sm text-muted-foreground">Loading crew data...</p>
|
||||
) : loadFailed ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Labor data could not be loaded. Reload the page to try again.
|
||||
</p>
|
||||
) : crew.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No labor classifications configured for this structure.</p>
|
||||
) : (
|
||||
|
|
@ -246,6 +300,7 @@ export function LaborCrewPanel() {
|
|||
)}
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => void handleSave(item)}
|
||||
|
|
|
|||
Loading…
Reference in a new issue