import { useEffect, useState } from "react"; import { API_V1, CREDENTIALS } from "../../apiContract"; import { refusalMessage } from "../../customer-grid/seam"; type Capacity = { value: number; unit: string } | null; type CapacityStatus = { fbaCapacity: Capacity; units: string[]; canEdit: boolean }; /** The one FBA capacity Command Center and Restock planner share (`/amazon-profit/fba-capacity`). */ export default function FbaCapacityControl() { const [status, setStatus] = useState(null); const [draft, setDraft] = useState(""); const [unit, setUnit] = useState("cu ft"); const [busy, setBusy] = useState(false); const [note, setNote] = useState(null); useEffect(() => { const controller = new AbortController(); void fetch(`${API_V1}/amazon-profit/fba-capacity`, { credentials: CREDENTIALS, cache: "no-store", signal: controller.signal }) .then(async (res) => { if (!res.ok) throw new Error("capacity refused"); const body = await res.json() as CapacityStatus; setStatus(body); setDraft(body.fbaCapacity ? String(body.fbaCapacity.value) : ""); setUnit(body.fbaCapacity?.unit ?? body.units[0] ?? "cu ft"); }) .catch(() => { if (!controller.signal.aborted) setNote("FBA capacity could not be loaded."); }); return () => controller.abort(); }, []); // Save the number and unit together. An empty box clears the stored value. const save = async (text: string, nextUnit: string) => { if (!status?.canEdit || busy) return; const trimmed = text.trim(); const value = trimmed === "" ? null : Number(trimmed.replace(/,/g, "")); if (value !== null && (!Number.isFinite(value) || value <= 0)) { setNote("Enter a number above zero."); return; } const stored = status.fbaCapacity; if (value === null ? stored === null : stored?.value === value && stored.unit === nextUnit) return; setBusy(true); setNote(null); try { const res = await fetch(`${API_V1}/amazon-profit/fba-capacity`, { method: "PUT", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ fbaCapacity: value === null ? null : { value, unit: nextUnit } }), }); const body: unknown = await res.json().catch(() => null); if (!res.ok) { setNote(refusalMessage(body, res.status, "FBA capacity did not save. Try again.")); return; } const saved = (body as { fbaCapacity?: Capacity } | null)?.fbaCapacity ?? null; setStatus({ ...status, fbaCapacity: saved }); setDraft(saved ? String(saved.value) : ""); if (saved) setUnit(saved.unit); setNote("Saved"); } catch { setNote("FBA capacity did not save. Try again."); } finally { setBusy(false); } }; const locked = !status?.canEdit || busy; const title = status && !status.canEdit ? "Only an editor can change FBA capacity." : undefined; return
{ event.preventDefault(); void save(draft, unit); }}> {status?.canEdit && } {busy ? "Saving" : note}
; }