File size: 4,033 Bytes
8133df9
 
8729c1d
8133df9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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<CapacityStatus | null>(null);
  const [draft, setDraft] = useState("");
  const [unit, setUnit] = useState("cu ft");
  const [busy, setBusy] = useState(false);
  const [note, setNote] = useState<string | null>(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 <form className="cc-capacity" data-testid="fba-capacity-control"
    onSubmit={(event) => { event.preventDefault(); void save(draft, unit); }}>
    <label className="cc-capacity-field">
      <span>FBA capacity</span>
      <input className="cg-input cc-capacity-value" type="text" inputMode="decimal" aria-label="FBA capacity"
        value={draft} disabled={!status || locked} title={title} placeholder="Not set"
        onChange={(event) => { setDraft(event.target.value); setNote(null); }} />
    </label>
    <select className="cg-select cc-capacity-unit" aria-label="FBA capacity unit" value={unit}
      disabled={!status || locked} title={title}
      onChange={(event) => { setUnit(event.target.value); setNote(null); }}>
      {(status?.units ?? ["cu ft", "cu m"]).map((u) => <option key={u} value={u}>{u}</option>)}
    </select>
    {status?.canEdit && <button type="submit" className="cg-btn" disabled={busy}>Save</button>}
    <span className="cc-capacity-note" role="status">{busy ? "Saving" : note}</span>
  </form>;
}