1
0
Fork 0
polaris-task-force/src/components/admin/game/LaborCrewField.tsx
Z8MB1E db98adbcee 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
2026-10-10 13:23:52 -04:00

323 lines
12 KiB
TypeScript

"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { UsersIcon } from "lucide-react";
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";
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;
}
/** 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 [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
useEffect(() => {
let cancelled = false;
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&limit=100"),
fetch(`/api/npc-staffing?${staffingParams.toString()}`),
]);
if (cancelled) return;
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 = requirementsRef.current;
const newCrew: LaborCrew[] = requirementList.flatMap((req) => {
const classification = classifications.find(
(c) => c.id === relId(req.classification),
);
if (!classification) return [];
const crewMembers = crewDocs.filter(
(m) => relId(m.laborClassification) === classification.id,
);
const headcount = crewMembers.reduce((sum, m) => 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 (err) {
console.error("[LaborCrewPanel] Failed to load labor data", err);
setLoadFailed(true);
toast.error("Failed to load labor data");
} finally {
setLoadingClassifications(false);
}
}
if (documentInfo.id) loadData();
return () => { cancelled = true; };
// 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] ?? {
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>
) : 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>
) : (
<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
type="button"
variant="outline"
size="sm"
onClick={() => void handleSave(item)}
disabled={isSaving}
>
{isSaving ? "Saving..." : "Apply"}
</Button>
</div>
</div>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
);
}
export default LaborCrewPanel;