import { useCallback, useEffect, useRef, useState, type ComponentType } from "react"; import { Dashboard } from "./Dashboard"; import type { DashboardKit } from "./Dashboard"; import { API_V1, CREDENTIALS } from "../../apiContract"; import { ConfirmDialog } from "../../ui/ConfirmDialog"; import { AppGrid } from "../AppGrid"; import { ActionCadence } from "../actions/ActionCadence"; import { SkuActions } from "../actions/SkuActions"; import { Kpi, KpiStrip } from "../../viz/kit/Kpi"; import type { KpiProps } from "../../viz/kit/Kpi"; import "../../styles/sdlc79/restock-planner.css"; import "../../styles/sdlc81/restock-loop.css"; import "../../styles/sdlc81/restock-reorder.css"; import "../../styles/sdlc82/restock-grid.css"; // The App frame owns navigation. This view shares Dashboard, the SKU Grid and the SKU drawer. /** C2: the App as the dispatcher passes it. Structurally equal to lane A's TemplateApplication. */ interface RestockApplication { id: string; name: string; templateKind?: string; templateView?: string; templateMark?: string; templateConnector?: string; capabilities?: Record; } interface RestockAppViewProps { application: RestockApplication; canEdit: boolean } // C6 fixture compilers replace this glob with injected module loaders, never substitute the inbound UI kit. const dashboardModules = import.meta.glob("../App{Tabs,Dashboard}.tsx"); function useDashboardKit() { const [kit, setKit] = useState(undefined); useEffect(() => { let alive = true; const tabs = dashboardModules["../AppTabs.tsx"]; const dashboard = dashboardModules["../AppDashboard.tsx"]; if (!tabs || !dashboard) { setKit(null); return; } void Promise.all([tabs(), dashboard()]).then(([tabModule, dashboardModule]) => { const t = tabModule as { AppTabs?: DashboardKit["AppTabs"]; default?: DashboardKit["AppTabs"] }; const d = dashboardModule as { AppDashboard?: DashboardKit["AppDashboard"]; default?: DashboardKit["AppDashboard"] }; const AppTabs = t.AppTabs ?? t.default; const AppDashboard = d.AppDashboard ?? d.default; if (alive) setKit(AppTabs && AppDashboard ? { AppTabs, AppDashboard } : null); }).catch(() => { if (alive) setKit(null); }); return () => { alive = false; }; }, []); return kit; } interface Item { id: string; sku: string; asin: string; title: string; band: string; reason: string; status: string; owner: string; due: string; fbaAvailable: number | null; daysOfSupply: number | null; units30d: number | null; recommendedQty: number | null; recommendedShipDate: string; odooOnHand: number | null; odooFba: number | null; odooNote: string; openPurchaseQty: number | null; inReport: boolean; label_owner: string; prep_owner: string; amazonRecommendedQty: number | null; odooNonFbaOnHand: number | null; sentQty: number | null; inboundPlanId: string; sendToAmazonUrl: string; inboundState: string; inboundReason: string; cancelledPlanId: string; cancelledBy: string; cancelledAt: string; } interface Warehouse { warehouse: string; fba: boolean; onHand: number | null } interface PurchaseOrder { order: string; vendor: string; openQty: number | null; expected: string } interface Point { date: string; fbaAvailable: number | null; daysOfSupply: number | null; units30d: number | null; inbound: number | null; band: string; } /** The two band thresholds in days of supply, from the App settings (R49). */ interface Thresholds { sendToFbaDays: number; overstockDays: number } type InboundOwner = "Seller" | "Amazon"; interface ShipFromAddress { name: string; addressLine1: string; addressLine2: string; city: string; stateOrProvinceCode: string; postalCode: string; countryCode: string; phoneNumber: string; } interface RestockSettings extends Thresholds { label_owner: InboundOwner; prep_owner: InboundOwner; ship_from: ShipFromAddress; fba_capacity: { value: number; unit: string } | null; } interface CapacityCause { cause: string; count: number; skus: string[] } interface CapacitySummary { unit: string | null; fba_capacity: RestockSettings["fba_capacity"]; remaining: number | null; storageVolume: number | null; plannedVolume: number | null; plannedSkuCount: number; capacityReason: string; quantityBasis: string; storageCauses: CapacityCause[]; plannedCauses: CapacityCause[]; } interface FeeCoverage { coverage: string; basis: string; source: string } type AppUrl = (path: string, params?: Record) => string; interface Detail { item: Item; warehouses: Warehouse[]; openPurchaseOrders: PurchaseOrder[]; points: Point[]; thresholds: Thresholds | null; offset: number; limit: number; total: number; totals: Record; } interface ListPage { items: Item[]; cursor: string | null; previousCursor: string | null; offset: number; total: number; ready: boolean; message: string; notices: string[]; refreshedAt: string; lastError: string; statuses: string[]; owners: string[]; thresholds: Thresholds | null; canEdit: boolean; lowInventoryFee: FeeCoverage | null; } type Load = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T }; interface RestockTile extends KpiProps { id: string; trend: number[] } // C4: lane C adds the optional trend prop. The current kit still shows value and change. const RestockKpi: ComponentType = Kpi; function RestockTiles({ url, revision }: { url: AppUrl; revision: unknown }) { const [state, setState] = useState>({ phase: "loading" }); const [attempt, setAttempt] = useState(0); useEffect(() => { const controller = new AbortController(); setState({ phase: "loading" }); void fetch(url("/tiles"), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "Restock tiles could not be loaded")) .then((body) => { const entries = list((body as { tiles?: unknown } | null)?.tiles); const tiles = entries.map((entry): RestockTile => { const tile = entry as RestockTile; return { id: text(tile.id), label: text(tile.label), value: num(tile.value), unit: text(tile.unit), validated: tile.validated === true, reason: text(tile.reason), trend: list(tile.trend).filter((point): point is number => num(point) !== null), change: tile.change }; }); if (tiles.length !== 3 || new Set(tiles.map((tile) => tile.id)).size !== 3) { throw new Error("Restock tiles could not be loaded"); } if (!controller.signal.aborted) setState({ phase: "ready", value: tiles }); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setState({ phase: "error", message: failure(reason, "Restock tiles could not be loaded") }); }); return () => controller.abort(); }, [url, revision, attempt]); if (state.phase === "loading") return

Loading restock tiles

; if (state.phase === "error") return setAttempt((n) => n + 1)} />; return {state.value.map((tile) => )} ; } /** S82-T26: the work tab lists every SKU in this module table. Band and Status are pill columns there. */ const RESTOCK_TABLE = "ut_amazon_restock"; const WORK_TAB = "skus"; const STATUSES = ["Open", "Accepted", "Ordered", "Sent to FBA", "Watching", "Done", "Dismissed"]; /** The server's page bound. A SKU lookup follows the cursor past it, so no SKU is out of reach (rule 1). */ const LOOKUP_PAGE = 200; const EMPTY_PLAN = "Nothing to restock"; /** Used only when an answer carries no thresholds; the server's settings win. */ const FALLBACK_THRESHOLDS: Thresholds = { sendToFbaDays: 30, overstockDays: 90 }; const text = (value: unknown) => (typeof value === "string" ? value : ""); const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null); const list = (value: unknown) => (Array.isArray(value) ? value : []); const words = (value: unknown) => list(value).map(text).filter(Boolean); const pageButtonStyle = (disabled: boolean) => disabled ? { opacity: "var(--lp-home-disabled-opacity)", cursor: "not-allowed" } : undefined; async function readJson(response: Response, fallback: string): Promise { const body: unknown = await response.json().catch(() => null); if (response.ok) return body; // The server sends a refusal as top-level {error}; a bare router sends it under {detail: {error}}. const shaped = body as { error?: { message?: unknown }; detail?: { error?: { message?: unknown } } } | null; throw new Error(text(shaped?.error?.message) || text(shaped?.detail?.error?.message) || fallback); } const failure = (reason: unknown, fallback: string) => (reason instanceof Error && reason.message ? reason.message : fallback); function parseItem(raw: unknown): Item | null { const row = (raw ?? {}) as Record; const id = text(row.id); if (!id) return null; return { id, sku: text(row.sku), asin: text(row.asin), title: text(row.title) || text(row.sku), band: text(row.band), reason: text(row.reason), status: text(row.status), owner: text(row.owner), due: text(row.due), fbaAvailable: num(row.fbaAvailable), daysOfSupply: num(row.daysOfSupply), units30d: num(row.units30d), recommendedQty: num(row.recommendedQty), recommendedShipDate: text(row.recommendedShipDate), odooOnHand: num(row.odooOnHand), odooFba: num(row.odooFba), odooNote: text(row.odooNote), openPurchaseQty: num(row.openPurchaseQty), inReport: row.inReport !== false, label_owner: text(row.label_owner), prep_owner: text(row.prep_owner), amazonRecommendedQty: num(row.amazonRecommendedQty), odooNonFbaOnHand: num(row.odooNonFbaOnHand), sentQty: num(row.sentQty), inboundPlanId: text(row.inboundPlanId), sendToAmazonUrl: text(row.sendToAmazonUrl), inboundState: text(row.inboundState), inboundReason: text(row.inboundReason), cancelledPlanId: text(row.cancelledPlanId), cancelledBy: text(row.cancelledBy), cancelledAt: text(row.cancelledAt), }; } function parseThresholds(raw: unknown): Thresholds | null { const body = (raw ?? {}) as Record; const send = num(body.sendToFbaDays); const over = num(body.overstockDays); return send !== null && over !== null && send > 0 && over > send ? { sendToFbaDays: send, overstockDays: over } : null; } function parseSettings(raw: unknown): RestockSettings { const body = (raw ?? {}) as Record; const thresholds = parseThresholds(body); if (!thresholds || !["Seller", "Amazon"].includes(text(body.label_owner)) || !["Seller", "Amazon"].includes(text(body.prep_owner))) throw new Error("Restock settings could not be loaded."); const address = (body.ship_from ?? {}) as Record; const capacity = body.fba_capacity as { value?: unknown; unit?: unknown } | null | undefined; if (capacity && (num(capacity.value) === null || !["cu ft", "cu m"].includes(text(capacity.unit)))) { throw new Error("FBA capacity needs a value and volume unit."); } return { ...thresholds, label_owner: body.label_owner as InboundOwner, prep_owner: body.prep_owner as InboundOwner, fba_capacity: capacity ? { value: Number(capacity.value), unit: text(capacity.unit) } : null, ship_from: { name: text(address.name), addressLine1: text(address.addressLine1), addressLine2: text(address.addressLine2), city: text(address.city), stateOrProvinceCode: text(address.stateOrProvinceCode), postalCode: text(address.postalCode), countryCode: text(address.countryCode), phoneNumber: text(address.phoneNumber) } }; } function parsePage(raw: unknown): ListPage { const body = (raw ?? {}) as Record; const statuses = words(body.statuses); return { items: list(body.items).map(parseItem).filter((row): row is Item => row !== null), cursor: text(body.cursor) || null, ready: body.ready === true, message: text(body.message), previousCursor: text(body.previousCursor) || null, offset: num(body.offset) ?? 0, total: num(body.total) ?? 0, notices: words(body.notices), refreshedAt: text(body.refreshedAt), lastError: text(body.lastError), statuses: statuses.length ? statuses : STATUSES, owners: words(body.owners), thresholds: parseThresholds(body.thresholds), canEdit: body.canEdit === true, lowInventoryFee: body.lowInventoryFee ? body.lowInventoryFee as FeeCoverage : null, }; } function parseDetail(raw: unknown, fallback: Item): Detail { const body = (raw ?? {}) as Record; const rawTotals = (body.detailTotals ?? {}) as Record; const totals: Record = {}; for (const field of ["warehouses", "openPurchaseOrders", "events", "points"]) totals[field] = num(rawTotals[field]) ?? 0; return { item: parseItem(body) ?? fallback, thresholds: parseThresholds(body.thresholds), offset: num(body.detailOffset) ?? 0, limit: num(body.detailLimit) ?? 50, total: num(body.detailTotal) ?? 0, totals, warehouses: list(body.warehouses).map((entry) => { const row = (entry ?? {}) as Record; return { warehouse: text(row.warehouse), fba: row.fba === true, onHand: num(row.onHand) }; }), openPurchaseOrders: list(body.openPurchaseOrders).map((entry) => { const row = (entry ?? {}) as Record; return { order: text(row.order), vendor: text(row.vendor), openQty: num(row.openQty), expected: text(row.expected) }; }), points: list(body.points).map((entry) => { const row = (entry ?? {}) as Record; return { date: text(row.date), fbaAvailable: num(row.fbaAvailable), daysOfSupply: num(row.daysOfSupply), units30d: num(row.units30d), inbound: num(row.inbound), band: text(row.band) }; }), }; } /** A quantity with at most one decimal, or nothing when the source does not know it. */ const qty = (value: number | null) => (value === null ? "" : value.toLocaleString(undefined, { maximumFractionDigits: 1 })); /** "Oct 24" from an ISO day. A calendar day is read in UTC. */ function day(iso: string) { if (!iso) return ""; const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso); return Number.isNaN(date.getTime()) ? iso : date.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" }); } const statusTone = (status: string) => status.toLowerCase().replace(/[^a-z]+/g, "-"); type Zone = "critical" | "healthy" | "overstock"; /** The zone of a days of supply value, by the same rule the module bands with. */ function zoneOf(days: number, t: Thresholds): Zone { if (days < t.sendToFbaDays) return "critical"; if (days > t.overstockDays) return "overstock"; return "healthy"; } /** The meter's words: its aria-label and title. */ function meterWords(days: number, t: Thresholds): string { const zone = zoneOf(days, t); if (zone === "critical") return `${qty(days)} days of supply, under the ${qty(t.sendToFbaDays)} day Send to FBA threshold`; if (zone === "overstock") return `${qty(days)} days of supply, over the ${qty(t.overstockDays)} day Overstock threshold`; return `${qty(days)} days of supply, inside the ${qty(t.sendToFbaDays)} to ${qty(t.overstockDays)} day range`; } /** The three levels, named once, from the server's thresholds. */ function levelLabels(t: Thresholds): [Zone, string][] { return [["critical", `Under ${qty(t.sendToFbaDays)} days`], ["healthy", `${qty(t.sendToFbaDays)} to ${qty(t.overstockDays)} days`], ["overstock", `Over ${qty(t.overstockDays)} days`]]; } /** Piecewise position in percent: 0 to send fills 40, send to overstock the next 40, overstock to twice overstock 20. */ function meterPosition(days: number, t: Thresholds): number { const send = t.sendToFbaDays; const over = t.overstockDays; if (days <= 0) return 0; if (days <= send) return (days / send) * 40; if (days <= over) return 40 + ((days - send) / (over - send)) * 40; if (days <= over * 2) return 80 + ((days - over) / over) * 20; return 100; } /** A bar meter for days of supply over a track zoned at the server thresholds, with a tick at each threshold. */ function DaysMeter({ days, thresholds, size, labels = false }: { days: number | null; thresholds: Thresholds; size: "cell" | "wide" | "mini"; labels?: boolean; }) { if (days === null) return null; const at = (value: number) => `${meterPosition(value, thresholds)}%`; const sendAt = meterPosition(thresholds.sendToFbaDays, thresholds); const overAt = meterPosition(thresholds.overstockDays, thresholds); const zone = zoneOf(days, thresholds); const words = meterWords(days, thresholds); return thresholds.overstockDays * 2 ? " is-past" : ""}`} role="img" aria-label={words} title={words}> {labels && } ; } /** The number and its meter in one cell. A critical number reads red and heavier, so it stands out without colour. */ function DaysCell({ days, units, thresholds, size }: { days: number | null; units: number | null; thresholds: Thresholds; size: "cell" | "mini"; }) { if (days === null && units === 0) return No sales; const zone = days === null ? "" : zoneOf(days, thresholds); return {qty(days)} ; } function Legend({ thresholds }: { thresholds: Thresholds }) { return
    {levelLabels(thresholds).map(([zone, label]) =>
  • )}
; } function Skeleton({ rows = 4 }: { rows?: number }) { return
{Array.from({ length: rows }, (_v, index) =>
)}
; } function Failed({ message, onRetry }: { message: string; onRetry: () => void }) { return

{message}{" "}

; } const ADDRESS_FIELDS: { key: keyof ShipFromAddress; label: string; wide?: boolean }[] = [ { key: "name", label: "Name", wide: true }, { key: "addressLine1", label: "Street address", wide: true }, { key: "addressLine2", label: "Address line 2", wide: true }, { key: "city", label: "City" }, { key: "stateOrProvinceCode", label: "State or province" }, { key: "postalCode", label: "Postal code" }, { key: "countryCode", label: "Country code" }, { key: "phoneNumber", label: "Phone", wide: true }, ]; function CapacityHeader({ url, revision }: { url: AppUrl; revision: unknown }) { const [state, setState] = useState>({ phase: "loading" }); const [retry, setRetry] = useState(0); useEffect(() => { const controller = new AbortController(); setState({ phase: "loading" }); void fetch(url("/capacity"), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "FBA capacity could not be loaded.")) .then((body) => { if (!controller.signal.aborted) setState({ phase: "ready", value: body as CapacitySummary }); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setState({ phase: "error", message: failure(reason, "FBA capacity could not be loaded.") }); }); return () => controller.abort(); }, [url, revision, retry]); if (state.phase === "loading") return

Loading FBA capacity

; if (state.phase === "error") return setRetry((value) => value + 1)} />; const value = state.value; const causes = new Map(); for (const group of [...value.storageCauses, ...value.plannedCauses]) { const skus = [...new Set([...(causes.get(group.cause)?.skus ?? []), ...group.skus])]; causes.set(group.cause, { cause: group.cause, count: skus.length, skus }); } const volume = (number: number | null) => number === null || !value.unit ? "Not known" : `${qty(number)} ${value.unit}`; return
Planned Send to FBA
{volume(value.plannedVolume)}
{value.capacityReason &&

{value.capacityReason}

} {causes.size > 0 &&
{[...causes.values()].map(({ cause, count, skus }) =>

{count > 0 ? `${qty(count)} ${count === 1 ? "SKU has" : "SKUs have"} ${cause}` : cause}

{skus.length > 0 &&
Show SKUs
    {skus.map((sku) =>
  • {sku}
  • )}
}
)}

Enter carton size and CBM in Command Center Data Entry.

}
; } function RestockSettingsFields({ value, editable, saving, onChange }: { value: RestockSettings; editable: boolean; saving: boolean; onChange: (value: RestockSettings) => void; }) { const [capacityUnit, setCapacityUnit] = useState(value.fba_capacity?.unit ?? "cu ft"); if (!editable) return
Ship from
{Object.values(value.ship_from).some(Boolean) ?
{[value.ship_from.name, value.ship_from.addressLine1, value.ship_from.addressLine2, [value.ship_from.city, value.ship_from.stateOrProvinceCode, value.ship_from.postalCode].filter(Boolean).join(", "), value.ship_from.countryCode, value.ship_from.phoneNumber].filter(Boolean) .map((line, index) => {line})}
: "No address"}
; return
{(["sendToFbaDays", "overstockDays"] as const).map((field) => )} {(["label_owner", "prep_owner"] as const).map((field) => )}
Ship from
{ADDRESS_FIELDS.map(({ key, label, wide }) => )}
; } function RestockSettingsPanel({ url, editable, onSaved }: { url: AppUrl; editable: boolean; onSaved: (value: RestockSettings) => void; }) { const [loaded, setLoaded] = useState>({ phase: "loading" }); const [draft, setDraft] = useState(null); const [editing, setEditing] = useState(false); const [saving, setSaving] = useState(false); const [message, setMessage] = useState(""); const [saveError, setSaveError] = useState(""); const [attempt, setAttempt] = useState(0); const saveRequest = useRef(null); useEffect(() => { const controller = new AbortController(); void fetch(url("/settings"), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "Restock settings could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseSettings(body); setLoaded({ phase: "ready", value }); onSaved(value); }).catch((reason: unknown) => { if (!controller.signal.aborted) setLoaded({ phase: "error", message: failure(reason, "Restock settings could not be loaded.") }); }); return () => { controller.abort(); saveRequest.current?.abort(); }; }, [url, onSaved, attempt]); const save = async () => { if (!editable || !draft || saving) return; const controller = new AbortController(); saveRequest.current = controller; setSaving(true); setMessage(""); setSaveError(""); try { const response = await fetch(url("/settings"), { method: "PATCH", credentials: CREDENTIALS, signal: controller.signal, headers: { "Content-Type": "application/json" }, body: JSON.stringify(draft) }); const value = parseSettings(await readJson(response, "Restock settings were not saved.")); if (controller.signal.aborted) return; setLoaded({ phase: "ready", value }); setEditing(false); setDraft(null); setMessage("Settings saved"); onSaved(value); } catch (reason) { if (!controller.signal.aborted) setSaveError(failure(reason, "Restock settings were not saved.")); } finally { if (!controller.signal.aborted) setSaving(false); } }; return
Settings
{loaded.phase === "loading" && } {loaded.phase === "error" && { setLoaded({ phase: "loading" }); setAttempt((count) => count + 1); }} />} {loaded.phase === "ready" && <> {editable && editing && draft ?
{ event.preventDefault(); void save(); }}>
: } {editable && !editing && } } {saveError &&

{saveError}

} {message &&

{message}

}
; } function StatusPill({ status }: { status: string }) { return status ? {status} : null; } function Fact({ label, value, numeric = false }: { label: string; value: string; numeric?: boolean }) { return
{label}
{value || "Not known"}
; } interface Reorder { quantityUnit: string; dailySalesUnit: string; product: string; unitsPerSku: number | null; dailySales: { amazon: number | null; odoo: number | null; total: number | null }; leadTimeDays: number | null; purchaseOrderCount: number | null; coverDays: number | null; onHand: number | null; openOrders: number | null; suggestedQuantity: number | null; cause: string; fix: string; } function parseReorder(raw: unknown): Reorder { const body = (raw ?? {}) as Record; const sales = (body.daily_sales ?? {}) as Record; if (body.state !== "ready" && body.state !== "unavailable") throw new Error("Reorder could not be loaded."); const quantityUnit = text(body.quantity_unit); const dailySalesUnit = text(body.daily_sales_unit); if (body.state === "ready" && (!quantityUnit || !dailySalesUnit || num(body.suggested_quantity) === null)) { throw new Error("Reorder units or quantity are missing. Retry after syncing."); } return { quantityUnit, dailySalesUnit, product: text(body.odoo_product), unitsPerSku: num(body.units_per_sku), dailySales: { amazon: num(sales.amazon), odoo: num(sales.odoo), total: num(sales.total) }, leadTimeDays: num(body.lead_time_days), purchaseOrderCount: num(body.purchase_order_count), coverDays: num(body.cover_days), onHand: num(body.on_hand), openOrders: num(body.open_order_quantity), suggestedQuantity: body.state === "ready" ? num(body.suggested_quantity) : null, cause: text(body.cause), fix: text(body.fix) || text(body.message), }; } function SupplierReorder({ itemId, url }: { itemId: string; url: AppUrl }) { const [state, setState] = useState>({ phase: "loading" }); const [coverDays, setCoverDays] = useState(null); const [defaultCover, setDefaultCover] = useState(""); const [attempt, setAttempt] = useState(0); const validCover = coverDays === null || (coverDays.trim() !== "" && Number.isFinite(Number(coverDays)) && Number(coverDays) >= 0); useEffect(() => { const controller = new AbortController(); setState({ phase: "loading" }); if (!validCover) return () => controller.abort(); const params: Record = coverDays === null ? {} : { cover_days: coverDays }; void fetch(url(`/items/${encodeURIComponent(itemId)}/reorder`, params), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "Reorder could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseReorder(body); if (coverDays === null) setDefaultCover(value.coverDays === null ? "" : String(value.coverDays)); setState({ phase: "ready", value }); }).catch((reason: unknown) => { if (!controller.signal.aborted) setState({ phase: "error", message: failure(reason, "Reorder could not be loaded.") }); }); return () => controller.abort(); }, [itemId, url, coverDays, validCover, attempt]); const value = state.phase === "ready" ? state.value : null; const amount = (quantity: number | null) => quantity === null || !value?.quantityUnit ? "Not known" : `${qty(quantity)} ${value.quantityUnit}`; return

Reorder from supplier

{!validCover ?

Enter cover days at or above 0.

: state.phase === "loading" ? : state.phase === "error" ? setAttempt((count) => count + 1)} /> : value &&
{value.fix &&

{value.fix}

} {value.quantityUnit && <>
{([["Amazon", value.dailySales.amazon], ["Odoo", value.dailySales.odoo], ["Total", value.dailySales.total]] as const) .map(([channel, daily]) => )}
Daily sales ({value.dailySalesUnit || "Unit not known"})
ChannelDaily sales
{channel} {daily === null || !value.dailySalesUnit ? "Not known" : qty(daily)}

Suggested quantity {amount(value.suggestedQuantity)}

}
}
; } function InboundPlan({ item, editable, busy, onCancel }: { item: Item; editable: boolean; busy: boolean; onCancel: () => void; }) { if (!item.inboundState && !item.inboundPlanId && !item.cancelledPlanId) return null; const cancelled = item.inboundState === "cancelled"; const title = cancelled ? "Plan cancelled" : item.inboundState === "sent" ? "Sent to FBA" : item.inboundState.startsWith("cancel_") ? "Cancellation unconfirmed" : item.inboundState === "held" ? "Held back" : (item.inboundState === "failed" || item.inboundState === "refused") ? "Plan refused" : "Plan unconfirmed"; return

{title}

{cancelled && <> }
{item.inboundReason &&

{item.inboundReason}

} {!cancelled && item.sendToAmazonUrl && Open in Send to Amazon} {editable && !cancelled && item.inboundPlanId && }
; } /** One SKU from the plan by its exact SKU. It follows every cursor, so a large plan never hides a SKU (rule 1). */ async function findItem(url: AppUrl, sku: string, signal: AbortSignal): Promise { const wanted = sku.trim(); const seen = new Set(); let cursor: string | null = null; do { const params: Record = { q: wanted, limit: String(LOOKUP_PAGE) }; if (cursor) params.cursor = cursor; const response = await fetch(url("/items", params), { credentials: CREDENTIALS, signal }); const page = parsePage(await readJson(response, "This SKU could not be loaded.")); const hit = page.items.find((item) => item.sku.trim() === wanted); if (hit) return hit; cursor = page.cursor && !seen.has(page.cursor) ? page.cursor : null; if (cursor) seen.add(cursor); } while (cursor); return null; } interface DetailProps { editable: boolean; owners: string[]; statuses: string[]; thresholds: Thresholds; inboundSettings: RestockSettings | null; url: AppUrl; onSaved: (item: Item) => void; onPlanSaved: (items: Item[]) => Promise; } interface DrawerProps extends DetailProps { appId: string; sku: string; title: string; onClose: () => void } /** D-12058: the Restock drawer is the shared SkuActions drawer. Its body holds the reorder and inbound sections. */ function Drawer({ appId, sku, title, onClose, ...detail }: DrawerProps) { // Set while a plan cancellation is in flight, so Close and Escape keep the drawer open. const lock = useRef(false); const [found, setFound] = useState>({ phase: "loading" }); const [attempt, setAttempt] = useState(0); const { url } = detail; useEffect(() => { const controller = new AbortController(); setFound({ phase: "loading" }); void findItem(url, sku, controller.signal) .then((item) => { if (!controller.signal.aborted) setFound(item ? { phase: "ready", value: item } : { phase: "error", message: "This SKU is not in the plan. Refresh the plan." }); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setFound({ phase: "error", message: failure(reason, "This SKU could not be loaded.") }); }); return () => controller.abort(); }, [url, sku, attempt]); return { if (!lock.current) onClose(); }}> {found.phase === "loading" && } {found.phase === "error" && setAttempt((count) => count + 1)} />} {found.phase === "ready" && } ; } function SkuDetail({ row, lock, editable, owners, statuses, thresholds: listThresholds, inboundSettings, url, onSaved, onPlanSaved }: DetailProps & { row: Item; lock: { current: boolean } }) { const [detail, setDetail] = useState>({ phase: "loading" }); const [attempt, setAttempt] = useState(0); const [offset, setOffset] = useState(0); const [saving, setSaving] = useState(false); const [saveError, setSaveError] = useState(""); const [confirmCancel, setConfirmCancel] = useState(false); const [cancelling, setCancelling] = useState(false); const [cancelMessage, setCancelMessage] = useState(""); const cancelRequest = lock; // The row object changes after a save. Only a different SKU reloads the detail. const latest = useRef(row); latest.current = row; useEffect(() => { const controller = new AbortController(); setDetail({ phase: "loading" }); void fetch(url(`/items/${encodeURIComponent(row.id)}`, { offset: String(offset) }), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "This SKU could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseDetail(body, latest.current); setOffset(value.offset); setDetail({ phase: "ready", value }); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setDetail({ phase: "error", message: failure(reason, "This SKU could not be loaded.") }); }); return () => controller.abort(); }, [url, row.id, attempt, offset]); /** Store one change, then show the value the server answered. */ const save = async (change: { owner?: string; status?: string; label_owner?: string; prep_owner?: string }) => { if (!editable || saving || cancelRequest.current || confirmCancel) return; setSaving(true); setSaveError(""); try { const response = await fetch(url(`/items/${encodeURIComponent(row.id)}`), { method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify(change), }); const stored = parseItem(await readJson(response, "The change was not saved.")); if (!stored) throw new Error("The change was not saved."); onSaved(stored); setDetail((current) => current.phase !== "ready" ? current : { phase: "ready", value: { ...current.value, item: { ...current.value.item, ...stored } } }); } catch (reason) { setSaveError(failure(reason, "The change was not saved.")); } finally { setSaving(false); } }; const item = detail.phase === "ready" ? detail.value.item : row; const cancelPlan = async () => { if (!editable || !confirmCancel || !item.inboundPlanId || saving || cancelRequest.current) return; cancelRequest.current = true; setCancelling(true); setCancelMessage(""); try { const response = await fetch(url(`/items/${encodeURIComponent(item.id)}/cancel-plan`), { method: "POST", credentials: CREDENTIALS, }); const result = await readJson(response, "Cancellation is unconfirmed. Check Send to Amazon.") as { state?: string; message?: string; items?: unknown[]; } | null; const items = list(result?.items).map(parseItem).filter((entry): entry is Item => entry !== null); const stored = items.find((entry) => entry.id === item.id); if (!stored) throw new Error(text(result?.message) || "Cancellation is unconfirmed. Check Send to Amazon."); if (result?.state === "cancelled") { if (stored.inboundState !== "cancelled" || stored.status !== "Open" || !stored.cancelledPlanId || stored.inboundPlanId || stored.sendToAmazonUrl) throw new Error("Cancellation is unconfirmed. Reload this item."); } else if (stored.inboundState === "cancelled" || stored.inboundPlanId !== item.inboundPlanId || stored.sendToAmazonUrl !== item.sendToAmazonUrl || (item.status === "Sent to FBA" && stored.status !== "Sent to FBA")) { throw new Error("Cancellation is unconfirmed. Reload this item."); } setDetail((current) => current.phase !== "ready" ? current : { phase: "ready", value: { ...current.value, item: stored } }); setCancelMessage(text(result?.message) || (result?.state === "cancelled" ? "Amazon cancelled this plan." : "Cancellation is unconfirmed. Check Send to Amazon.")); await onPlanSaved(items); } catch (reason) { setCancelMessage(failure(reason, "Cancellation is unconfirmed. Check Send to Amazon.")); } finally { cancelRequest.current = false; setCancelling(false); setConfirmCancel(false); } }; const busy = saving || cancelling || confirmCancel; const thresholds = (detail.phase === "ready" ? detail.value.thresholds : null) ?? listThresholds; const ownerOptions = item.owner && !owners.includes(item.owner) ? [item.owner, ...owners] : owners; return
{item.asin && {item.asin}}

{item.reason}

{(["label_owner", "prep_owner"] as const).map((field) => )} {saveError &&

{saveError}

}
setConfirmCancel(true)} /> {cancelMessage && cancelMessage !== item.inboundReason &&

{cancelMessage}

} {editable && Cancel this plan for every SKU it contains? Items return to Open after Amazon confirms.

} confirmLabel={cancelling ? "Cancelling" : "Cancel plan"} cancelLabel="Keep plan" busy={cancelling} onConfirm={() => void cancelPlan()} onCancel={() => setConfirmCancel(false)} />}
Days of supply
{item.daysOfSupply === null ? "Not known" : qty(item.daysOfSupply)}
{item.daysOfSupply !== null && }
{item.odooNote &&

{item.odooNote}

} {detail.phase === "loading" && } {detail.phase === "error" && setAttempt((count) => count + 1)} />} {detail.phase === "ready" && <>

Warehouses

{detail.value.warehouses.length === 0 ?

{detail.value.totals.warehouses ? "No warehouses on this page" : "No Odoo stock"}

: {detail.value.warehouses.map((row) => )}
WarehouseOn hand
{row.warehouse}{row.fba && !/fba/i.test(row.warehouse) && FBA} {qty(row.onHand)}
}

Open purchase orders

{detail.value.openPurchaseOrders.length === 0 ?

{detail.value.totals.openPurchaseOrders ? "No orders on this page" : "No open orders"}

: {detail.value.openPurchaseOrders.map((row, index) => )}
OrderVendor OpenExpected
{row.order}{row.vendor} {qty(row.openQty)}{day(row.expected)}
}

History

{detail.value.points.length === 0 ?

{detail.value.totals.points ? "No history on this page" : "No history yet"}

: {detail.value.points.map((point) => )}
DayFBA Days30-day Band
{day(point.date)} {qty(point.fbaAvailable)} {qty(point.units30d)} {point.band}
}
}
; } /** A Grid row as the host passes it: the module table's cells by field key. */ type GridRow = Record; export default function RestockPlannerView({ application, canEdit }: RestockAppViewProps) { const appId = application.id; const kit = useDashboardKit(); const [tab, setTab] = useState(WORK_TAB); const url = useCallback((path: string, params: Record = {}) => { const query = new URLSearchParams({ app: appId, ...params }); return `${API_V1}/app-kinds/restock_planner${path}?${query.toString()}`; }, [appId]); const [capacityRevision, setCapacityRevision] = useState(0); const [status, setStatus] = useState>({ phase: "loading" }); const [attempt, setAttempt] = useState(0); const [serverThresholds, setServerThresholds] = useState(null); const [inboundSettings, setInboundSettings] = useState(null); const settingsSaved = useCallback((value: RestockSettings) => { setInboundSettings(value); setCapacityRevision((revision) => revision + 1); setServerThresholds({ sendToFbaDays: value.sendToFbaDays, overstockDays: value.overstockDays }); }, []); const [refreshing, setRefreshing] = useState(false); const [refreshError, setRefreshError] = useState(""); const [opened, setOpened] = useState<{ sku: string; title: string } | null>(null); // A drawer save changes table cells. The Grid remounts on close so it reads them. const [gridRevision, setGridRevision] = useState(0); const changed = useRef(false); const alive = useRef(true); useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); // D-12043: the Grid's Filter, Sort and Group replace the list query. This one read carries the refresh time, // notices, people and the edit grant, and adopts every Status set in the Grid before it answers. useEffect(() => { const controller = new AbortController(); void fetch(url("/items", { limit: "1" }), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "The restock plan could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parsePage(body); setStatus({ phase: "ready", value }); if (value.thresholds) setServerThresholds(value.thresholds); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setStatus({ phase: "error", message: failure(reason, "The restock plan could not be loaded.") }); }); return () => controller.abort(); }, [url, attempt]); const screen = status.phase === "ready" ? status.value : null; const editable = canEdit === true && screen?.canEdit === true; const refresh = async () => { setRefreshing(true); setRefreshError(""); try { const response = await fetch(url("/refresh"), { method: "POST", credentials: CREDENTIALS }); const queued = await readJson(response, "The restock plan could not be refreshed.") as { requestId?: string }; const deadline = Date.now() + 120000; while (alive.current) { if (Date.now() >= deadline) throw new Error("The refresh is still running. Try again shortly."); await new Promise((resolve) => window.setTimeout(resolve, 1000)); if (!alive.current) return; const state = await readJson(await fetch(url("/refresh"), { credentials: CREDENTIALS }), "The refresh status could not be read.") as { state?: string; requestId?: string; message?: string; result?: { message?: string } }; if (state.requestId !== queued.requestId) throw new Error("Another refresh started. Reload the plan."); if (state.state === "failed") throw new Error(state.message || state.result?.message || "The restock plan could not be refreshed."); if (state.state === "done") { setAttempt((count) => count + 1); setCapacityRevision((revision) => revision + 1); setGridRevision((revision) => revision + 1); break; } } } catch (reason) { if (alive.current) setRefreshError(failure(reason, "The restock plan could not be refreshed.")); } finally { if (alive.current) setRefreshing(false); } }; const openRow = useCallback((row: GridRow) => { const sku = typeof row.sku === "number" ? String(row.sku) : text(row.sku).trim(); if (sku) setOpened({ sku, title: text(row.product) || sku }); }, []); const closeRow = useCallback(() => { setOpened(null); if (changed.current) { changed.current = false; setGridRevision((revision) => revision + 1); } }, []); const saved = useCallback((_item: Item) => { changed.current = true; setCapacityRevision((revision) => revision + 1); }, []); // A plan change moves sibling SKUs too, so the Grid reads them at once. const planSaved = useCallback(async (_items: Item[]) => { setCapacityRevision((revision) => revision + 1); setAttempt((count) => count + 1); setGridRevision((revision) => revision + 1); }, []); const pickTab = (next: string) => { setTab(next); setOpened(null); }; const statuses = screen?.statuses ?? STATUSES; const thresholds = serverThresholds ?? FALLBACK_THRESHOLDS; const tabs = [{ id: WORK_TAB, label: "SKUs", count: screen ? screen.total : null }, { id: "dashboard", label: "Dashboard" }]; return
{kit ? :
{tabs.map((entry) => )}
} {tab === "dashboard" ?
: <>
{screen?.refreshedAt && Updated {day(screen.refreshedAt)}} {editable && screen?.ready && }
{refreshError &&

{refreshError}

} {screen?.lastError &&

{screen.lastError}

} {screen && screen.notices.length > 0 &&
    {screen.notices.map((notice) =>
  • {notice}
  • )}
} {status.phase === "loading" && } {status.phase === "error" && setAttempt((count) => count + 1)} />} {screen && !screen.ready && screen.total === 0 ?

{screen.message}

{editable && }
: screen &&
{EMPTY_PLAN}

} />
}
}
{opened && }
; }