import { useCallback, useEffect, useRef, useState } from "react"; import { API_V1, CREDENTIALS } from "../../apiContract"; import { useEscapeClose } from "../../ui/useEscapeClose"; import Dashboard, { DashboardTabs } from "./Dashboard"; import { Kpi, KpiStrip } from "../../viz/kit/Kpi"; import type { KpiProps } from "../../viz/kit/Kpi"; import type { SkuAction } from "../actions/actionsApi"; import "../../styles/sdlc79/reimbursements.css"; // S79-T25 (C2, C4, R51): the Reimbursements App screen. The dispatcher draws the App frame, so this view // draws only the tabs, the claims and paid Grids and the item drawer. No chat panel exists here (R18). // S82-T30 (R6, R72): every claim status is one Grid with a status pill; the server walls each reader's rows. // S82-T31: units lost and money to claim sit above the Grid as two large tiles, then the claim steps once. export interface ReimbursementsApplication { id: string; name?: string; capabilities?: Record; } const DEFAULT_STATUSES = ["To file", "Filed", "Reimbursed", "Denied"]; const DASHBOARD = "dashboard"; const CLAIMS = "claims"; const PAID = "Paid"; /** The module tables `reimbursements.refresh_tables` writes before `/screen` answers. */ const PAID_TABLE = "ut_amazon_reimbursements_paid"; const CLAIMS_TABLE = "ut_amazon_reimbursement_claims"; const UNDERPAID = "Underpaid"; const PAGE = 50; /** The one empty sentence per Grid. */ const EMPTY: Record = { [CLAIMS]: "Nothing to claim", [PAID]: "No reimbursements paid yet", }; /** Ledger reason codes as plain words. */ const LEDGER_REASONS: Record = { M: "Lost", "5": "Lost", F: "Found", E: "Damaged", "6": "Damaged", "7": "Damaged", H: "Damaged", }; interface Claim { id: string; title: string; status: string; reason: string; sku: string; fnsku: string; asin: string; kind: string; units: number | null; value: number | null; currency: string; claimBy: string; eventDate: string; expired: boolean; caseId: string; owner: string; paidPerUnit: number | null; costPerUnit: number | null; purchase: Row | null; } interface PageInfo { cursor: string | null; total: number; offset: number; limit: number } type Change = KpiProps["change"]; /** The To file tiles `/screen` answers (S82-T31): stored rows tied to the SQL sum. */ interface ToFile { units: number | null; value: number | null; currency: string; valueReason: string; validated: boolean; reason: string; change: { units?: Change; value?: Change }; trend: { units: number[] | null; value: number[] | null }; } interface Screen extends PageInfo { canEdit: boolean; toFile: ToFile | null; paidTotal: number; counts: Record; items: Claim[]; cursor: string | null; problems: string[]; statuses: string[]; held: PaidPage; } type Row = Record; interface PaidPage extends PageInfo { rows: Row[] } interface HistoryEvent { at: string; by: string; status: string; caseId: string; note: string } interface Detail { item: Claim; events: Row[]; returns: Row[]; reimbursements: Row[]; history: HistoryEvent[]; caseText: string; pages: Record; } type Load = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T }; const text = (value: unknown) => (typeof value === "string" ? value : typeof value === "number" ? String(value) : ""); const num = (value: unknown) => { if (typeof value === "number" && Number.isFinite(value)) return value; if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value); return null; }; const rows = (raw: unknown): Row[] => (Array.isArray(raw) ? raw : []) .filter((row): row is Row => !!row && typeof row === "object" && !Array.isArray(row)); async function readJson(response: Response, fallback: string): Promise { const body: unknown = await response.json().catch(() => null); if (response.ok) return body; const error = (body as { detail?: { error?: { message?: unknown } } } | null)?.detail?.error; throw new Error(text(error?.message) || fallback); } function parseClaim(raw: unknown): Claim | null { const row = (raw ?? {}) as Row; const id = text(row.id); if (!id) return null; return { id, title: text(row.title), status: text(row.status) || "To file", reason: text(row.reason), sku: text(row.sku), fnsku: text(row.fnsku), asin: text(row.asin), kind: text(row.kind), units: num(row.units), value: num(row.value), currency: text(row.currency), claimBy: text(row.claimBy) || text(row.due), eventDate: text(row.eventDate), expired: row.expired === true, caseId: text(row.caseId), owner: text(row.owner), paidPerUnit: num(row.paidPerUnit), costPerUnit: num(row.costPerUnit), purchase: row.purchase && typeof row.purchase === "object" ? row.purchase as Row : null, }; } const claims = (raw: unknown) => (Array.isArray(raw) ? raw : []) .map(parseClaim).filter((row): row is Claim => row !== null); function parseScreen(raw: unknown): Screen { const body = (raw ?? {}) as Row; const counts: Record = {}; for (const [key, value] of Object.entries((body.counts ?? {}) as Row)) counts[key] = num(value) ?? 0; const statuses = (Array.isArray(body.statuses) ? body.statuses : []).map(text).filter(Boolean); return { ...parsePage(body), canEdit: body.canEdit === true, paidTotal: num(body.paidTotal) ?? 0, counts, items: claims(body.items), problems: (Array.isArray(body.problems) ? body.problems : []).map(text).filter(Boolean), statuses: statuses.length ? statuses : DEFAULT_STATUSES, held: parsePaid(body.held), toFile: parseToFile(body.toFile), }; } function parseChange(raw: unknown): Change { if (!raw || typeof raw !== "object") return undefined; const body = raw as Row; return { previous: num(body.previous), absolute: num(body.absolute), percent: num(body.percent), reason: text(body.reason) || null }; } function series(raw: unknown): number[] | null { if (!Array.isArray(raw)) return null; const values = raw.map(num); return values.every((value): value is number => value !== null) ? values : null; } function parseToFile(raw: unknown): ToFile | null { if (!raw || typeof raw !== "object") return null; const body = raw as Row; const change = (body.change ?? {}) as Row; const trend = (body.trend ?? {}) as Row; return { units: num(body.units), value: num(body.value), currency: text(body.currency), valueReason: text(body.valueReason), validated: body.validated === true, reason: text(body.reason), change: { units: parseChange(change.units), value: parseChange(change.value) }, trend: { units: series(trend.units), value: series(trend.value) }, }; } function parsePaid(raw: unknown): PaidPage { const body = (raw ?? {}) as Row; return { ...parsePage(body), rows: rows(body.rows) }; } function parsePage(raw: unknown): PageInfo { const body = (raw ?? {}) as Row; return { cursor: text(body.cursor) || null, total: num(body.total) ?? 0, offset: num(body.offset) ?? 0, limit: num(body.limit) ?? PAGE }; } function parseDetail(raw: unknown): Detail | null { const body = (raw ?? {}) as Row; const item = parseClaim(body.item); if (!item) return null; return { item, events: rows(body.events), returns: rows(body.returns), reimbursements: rows(body.reimbursements), history: rows(body.history).map((event) => ({ at: text(event.at), by: text(event.by), status: text(event.status), caseId: text(event.caseId), note: text(event.note), })), caseText: text(body.caseText), pages: Object.fromEntries(Object.entries((body.pages ?? {}) as Row) .map(([key, value]) => [key, parsePage(value)])), }; } /** "Dec 1, 2026" from an ISO day or a day-first stamp. A calendar day is read in UTC. */ function dayWords(raw: string) { const value = raw.trim(); const dayFirst = /^(\d{2})\.(\d{2})\.(\d{4})/.exec(value); const iso = dayFirst ? `${dayFirst[3]}-${dayFirst[2]}-${dayFirst[1]}` : value; const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso); return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" }); } function money(value: number | null, currency: string) { if (value === null) return ""; if (/^[A-Z]{3}$/.test(currency)) { try { return value.toLocaleString(undefined, { style: "currency", currency, minimumFractionDigits: 2 }); } catch { /* an unknown code falls through to a plain number */ } } return value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } const unitsWords = (value: number | null) => (value === null ? "" : value.toLocaleString()); const plural = (n: number, one: string, many: string) => `${n.toLocaleString()} ${n === 1 ? one : many}`; function Skeleton() { return
; } function Failed({ message, onRetry }: { message: string; onRetry: () => void }) { return

{message}{" "}

; } /** The Grid host's export, typed without a static import (the module loads on first open). */ type AppGridHost = typeof import("../AppGrid").AppGrid; type SkuActionsHost = typeof import("../actions/SkuActions").SkuActions; type ActionListHost = typeof import("../actions/ActionList").ActionList; type ActionCadenceHost = typeof import("../actions/ActionCadence").ActionCadence; /** A component loaded on first use. A static import would pull react-dom into the C6 consumer probe. */ function useLoaded(load: () => Promise): { value: T } | null { const [loaded, setLoaded] = useState<{ value: T } | null>(null); const loader = useRef(load); useEffect(() => { let live = true; void loader.current().then((value) => { if (live) setLoaded({ value }); }).catch(() => undefined); return () => { live = false; }; }, []); return loaded; } const loadSkuActions = () => import("../actions/SkuActions").then((module): SkuActionsHost => module.SkuActions); const loadActionList = () => import("../actions/ActionList").then((module): ActionListHost => module.ActionList); const loadCadence = () => import("../actions/ActionCadence").then((module): ActionCadenceHost => module.ActionCadence); /** D-12060: the claim's SKU actions, opened from the drawer. */ function ClaimActions(props: Parameters[0]) { const host = useLoaded(loadSkuActions); if (!host) return null; const Actions = host.value; return ; } function ActionList(props: Parameters[0]) { const host = useLoaded(loadActionList); if (!host) return null; const Actions = host.value; return ; } /** D-12027: this App's action cadence, scoped to its own App record. */ function Cadence({ appId }: { appId: string }) { const host = useLoaded(loadCadence); if (!host) return null; const Calendar = host.value; return
; } const ignoreRow = () => undefined; /** C4: lane C's opt-in Kpi `trend` arrives by spread, so a Kpi without the prop shows value and change. */ const withTrend = (trend: number[] | null): { trend?: number[] } => (trend ? { trend } : {}); const STEPS = [ { step: "Find", text: "units Amazon owes you" }, { step: "File", text: "the case in Seller Central" }, { step: "Track", text: "tick Processed, add the case ID" }, ]; const CHANGE_PERIOD = "Last 30 days against the 30 before"; /** S82-T31: units lost and money to claim over the To file rows, then the claim steps once. */ function ToFileTiles({ totals }: { totals: ToFile }) { const refused = totals.validated ? null : totals.reason || "This figure could not be validated"; return
    {STEPS.map((item, index) =>
  1. {item.step} {item.text}
  2. )}
; } /** A stored claims row as the drawer's first paint; the drawer then reads the claim itself. */ function claimFromRow(row: Row): Claim | null { const id = text(row.claim_id); if (!id) return null; return { id, title: text(row.product), status: text(row.status) || "To file", reason: text(row.reason), sku: text(row.sku), fnsku: text(row.fnsku), asin: text(row.asin), kind: text(row.kind), units: num(row.units), value: num(row.estimate), currency: text(row.currency), claimBy: text(row.claim_by), eventDate: "", expired: false, caseId: text(row.case_id), owner: "", paidPerUnit: null, costPerUnit: null, purchase: null, }; } /** S82-T29, S82-T30 (C4): a Table Grid over one App module table, loaded on first open. */ function ModuleGrid({ table, empty, proof, onOpenRow }: { table: string; empty: string; proof: string; onOpenRow: (row: Row) => void; }) { const [host, setHost] = useState<{ Grid: AppGridHost } | null>(null); const [failed, setFailed] = useState(false); useEffect(() => { let live = true; void import("../AppGrid") .then((module) => { if (live) setHost({ Grid: module.AppGrid }); }) .catch(() => { if (live) setFailed(true); }); return () => { live = false; }; }, []); if (failed) return

This list could not be loaded

; if (!host) return ; const { Grid } = host; return
; } /** One ledger event, refund row, return row or paid row as a timeline line. */ function EventLine({ when, what, detail }: { when: string; what: string; detail: string }) { return
  • {what} {detail && {detail}} {when ? dayWords(when) : "Unknown date"}
  • ; } function ledgerLine(row: Row) { const code = text(row.reason); const qty = num(row.quantity); const word = LEDGER_REASONS[code] ?? "Adjusted"; const what = qty === null ? word : `${word}: ${plural(Math.abs(qty), "unit", "units")}`; const detail = [code && `Code ${code}`, text(row.fulfillment_center) && `Center ${text(row.fulfillment_center)}`, text(row.reference_id) && `Reference ${text(row.reference_id)}`].filter(Boolean).join(", "); return { when: text(row.date), what, detail }; } function refundLine(row: Row) { const amount = num(row.amount); const what = amount === null ? "Refunded" : `Refunded ${money(Math.abs(amount), "")}`; return { when: text(row.posted_date) || text(row.posted_date_time), what, detail: [text(row.order_id) && `Order ${text(row.order_id)}`, text(row.sku) && `SKU ${text(row.sku)}`] .filter(Boolean).join(", ") }; } function returnLine(row: Row) { return { when: text(row.return_date), what: "Returned", detail: [text(row.order_id) && `Order ${text(row.order_id)}`, text(row.status)].filter(Boolean).join(", ") }; } function paidLine(row: Row) { const amount = num(row.amount_total); return { when: text(row.approval_date), what: amount === null ? "Reimbursed" : `Reimbursed ${money(amount, text(row.currency_unit))}`, detail: [text(row.reimbursement_id) && `ID ${text(row.reimbursement_id)}`, num(row.quantity_reimbursed_total) !== null && plural(num(row.quantity_reimbursed_total) ?? 0, "unit", "units")] .filter(Boolean).join(", ") }; } function Pager({ page, busy, onPage, label }: { page: PageInfo; busy: boolean; onPage: (offset: number) => void; label: string; }) { return ; } function Events({ title, lines, page, busy, onPage }: { title: string; lines: { when: string; what: string; detail: string }[]; page?: PageInfo; busy: boolean; onPage: (offset: number) => void; }) { if (!lines.length && !page?.total) return null; return

    {title}

      {lines.map((line, index) => )}
    {page && }
    ; } interface CaseDraft { caseText: string; status: "draft" | "fallback"; reason: string } function CaseText({ value, itemId, url, onDenied }: { value: string; itemId: string; url: DrawerProps["url"]; onDenied: () => void; }) { const [draft, setDraft] = useState>({ phase: "loading" }); const [copied, setCopied] = useState<"" | "done" | "failed">(""); const timer = useRef(null); useEffect(() => () => { if (timer.current !== null) window.clearTimeout(timer.current); }, []); useEffect(() => { const controller = new AbortController(); setDraft({ phase: "loading" }); setCopied(""); void fetch(url(`/items/${encodeURIComponent(itemId)}/case-text`), { credentials: CREDENTIALS, signal: controller.signal }) .then(async (response) => { if ((response.status === 403 || response.status === 404) && !controller.signal.aborted) onDenied(); return readJson(response, "The draft could not be loaded. Use the template."); }) .then((raw) => { if (controller.signal.aborted) return; const body = (raw ?? {}) as Row; if ((body.status !== "draft" && body.status !== "fallback") || !text(body.caseText)) { throw new Error("The draft response could not be read. Use the template."); } setDraft({ phase: "ready", value: { caseText: text(body.caseText), status: body.status, reason: text(body.reason), } }); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setDraft({ phase: "error", message: reason instanceof Error ? reason.message : "The draft could not be loaded. Use the template." }); }); return () => controller.abort(); }, [url, itemId, value, onDenied]); const displayed = draft.phase === "ready" ? draft.value.caseText : value; const copy = async () => { try { await navigator.clipboard.writeText(displayed); setCopied("done"); } catch { setCopied("failed"); } if (timer.current !== null) window.clearTimeout(timer.current); timer.current = window.setTimeout(() => setCopied(""), 2400); }; return

    Case text

    {draft.phase === "loading" &&

    Drafting

    }

    {displayed.split("\n").map((line, index) => {index > 0 &&
    }{line}
    )}

    {draft.phase === "ready" && draft.value.reason &&

    {draft.value.reason}

    } {draft.phase === "error" &&

    {draft.message}

    } {copied === "failed" &&

    Copy did not work. Select the text to copy it.

    }
    ; } interface DrawerProps { appId: string; claim: Claim; url: (path: string, params?: Record) => string; editable: boolean; statuses: string[]; onClose: () => void; onSaved: () => void; } function Drawer({ appId, claim, url, editable, statuses, onClose, onSaved }: DrawerProps) { const panel = useRef(null); const close = useRef(null); const [detail, setDetail] = useState>({ phase: "loading" }); const [attempt, setAttempt] = useState(0); const [cursors, setCursors] = useState>({}); const [paging, setPaging] = useState(false); const [pageError, setPageError] = useState(""); const loadedAttempt = useRef(-1); const [status, setStatus] = useState(claim.status); const [caseId, setCaseId] = useState(claim.caseId); const [saving, setSaving] = useState(false); const [saveError, setSaveError] = useState(""); const [saved, setSaved] = useState(false); const [actions, setActions] = useState(false); const draftDenied = useCallback(() => { setDetail({ phase: "error", message: "This claim is no longer available to your account." }); }, []); // SkuActions owns Escape while it is open; the claim drawer stays under it. useEscapeClose(!actions, onClose, { container: () => panel.current }); useEffect(() => { close.current?.focus(); }, [claim.id]); useEffect(() => { const controller = new AbortController(); setPaging(true); setPageError(""); void fetch(url(`/items/${encodeURIComponent(claim.id)}`, { ...cursors, limit: String(PAGE) }), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "This claim could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseDetail(body); if (!value) throw new Error("This claim could not be loaded."); setDetail({ phase: "ready", value }); if (loadedAttempt.current !== attempt) { setStatus(value.item.status); setCaseId(value.item.caseId); loadedAttempt.current = attempt; } }) .catch((reason: unknown) => { if (!controller.signal.aborted) { const message = reason instanceof Error ? reason.message : "This claim could not be loaded."; setDetail({ phase: "error", message }); setPageError(message); } }).finally(() => { if (!controller.signal.aborted) setPaging(false); }); return () => controller.abort(); }, [url, claim.id, attempt, cursors]); const current = detail.phase === "ready" ? detail.value.item : claim.kind === "underpaid" ? { ...claim, reason: "", value: null, paidPerUnit: null, costPerUnit: null, purchase: null } : claim; const needsCase = status === "Filed" && !caseId.trim(); const changed = status !== current.status || caseId.trim() !== current.caseId; const save = async () => { if (needsCase || !changed) return; setSaving(true); setSaveError(""); setSaved(false); try { const body: Record = { status }; if (caseId.trim()) body.caseId = caseId.trim(); const response = await fetch(url(`/items/${encodeURIComponent(claim.id)}`), { method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); await readJson(response, "The status was not saved."); setSaved(true); setAttempt((count) => count + 1); onSaved(); } catch (reason) { setSaveError(reason instanceof Error ? reason.message : "The status was not saved."); } finally { setSaving(false); } }; const facts: [string, string][] = [ ["Units", unitsWords(current.units)], [current.kind === "underpaid" ? "Shortfall" : "Value", current.value === null ? "No history" : money(current.value, current.currency)], ["Claim by", current.claimBy ? dayWords(current.claimBy) + (current.expired ? ", expired" : "") : "Unknown"], ["Event date", current.eventDate ? dayWords(current.eventDate) : ""], ["SKU", current.sku], ["FNSKU", current.fnsku], ["ASIN", current.asin], ["Owner", current.owner], ]; if (current.kind === "underpaid") facts.unshift( ["Amazon per unit", money(current.paidPerUnit, current.currency)], ["Odoo per unit", money(current.costPerUnit, current.currency)], ); const value = detail.phase === "ready" ? detail.value : null; const evidencePage = (section: string, offset: number) => setCursors((current) => ({ ...current, [`${section}_cursor`]: String(offset), })); const refund = current.kind === "refund"; return ; } export default function ReimbursementsView({ application, canEdit }: { application: ReimbursementsApplication; canEdit?: boolean; }) { const appId = application.id; const url = useCallback((path: string, params: Record = {}) => { const query = new URLSearchParams({ app: appId, ...params }); return `${API_V1}/app-kinds/reimbursements${path}?${query.toString()}`; }, [appId]); const [tab, setTab] = useState(CLAIMS); const [screen, setScreen] = useState>({ phase: "loading" }); const [screenAttempt, setScreenAttempt] = useState(0); const [statuses, setStatuses] = useState(DEFAULT_STATUSES); const [serverEdit, setServerEdit] = useState(false); const [heldOffset, setHeldOffset] = useState(0); const [showHeld, setShowHeld] = useState(false); const [busy, setBusy] = useState(true); const [opened, setOpened] = useState(null); const [listedAction, setListedAction] = useState(null); const opener = useRef(null); useEffect(() => { if (tab === DASHBOARD) return; const controller = new AbortController(); setBusy(true); // /screen refreshes the stored tables, then the Grids mount on them. A refetch keeps the Grid mounted. void fetch(url("/screen", { limit: String(PAGE), held_cursor: String(heldOffset) }), { credentials: CREDENTIALS, signal: controller.signal }) .then((response) => readJson(response, "Claims could not be loaded.")) .then((body) => { if (controller.signal.aborted) return; const value = parseScreen(body); setScreen({ phase: "ready", value }); setStatuses(value.statuses); setServerEdit(value.canEdit); }) .catch((reason: unknown) => { if (!controller.signal.aborted) setScreen({ phase: "error", message: reason instanceof Error ? reason.message : "Claims could not be loaded." }); }).finally(() => { if (!controller.signal.aborted) setBusy(false); }); return () => controller.abort(); }, [url, tab, heldOffset, screenAttempt]); const editable = canEdit === true && serverEdit; const openRow = useCallback((row: Row) => { const claim = claimFromRow(row); if (!claim) return; opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; setListedAction(null); setOpened(claim); }, []); const closeClaim = useCallback(() => { setOpened(null); opener.current?.focus(); }, []); const onSaved = useCallback(() => { setScreenAttempt((count) => count + 1); }, []); const ready = screen.phase === "ready" ? screen.value : null; const counts = ready?.counts ?? null; const tabs = [{ id: CLAIMS, label: "Claims", count: counts ? statuses.reduce((sum, status) => sum + (counts[status] ?? 0), 0) : null }, { id: DASHBOARD, label: "Dashboard" }, { id: PAID, label: PAID, count: ready ? ready.paidTotal : null }]; const retry = () => setScreenAttempt((count) => count + 1); return
    { setTab(key); setHeldOffset(0); setShowHeld(false); setOpened(null); setListedAction(null); }} />
    item.id === tab)?.label ?? tab}> {tab === DASHBOARD ? <> : <> {tab === CLAIMS && ready?.toFile && } {tab === CLAIMS &&
    } {ready && ready.problems.length > 0 &&
    {ready.problems.map((problem) =>

    {problem}

    )}
    } {tab === CLAIMS && showHeld && ready &&

    Held back

    {ready.held.total === 0 ?

    Nothing held back

    : ready.held.rows.map((row) =>

    {text(row.sku) || "Unknown SKU"}: {text(row.reason)}

    )} {ready.held.total > 0 && }
    }
    {screen.phase === "loading" && } {screen.phase === "error" && } {tab === CLAIMS && ready && } {tab === PAID && ready && }
    {tab === CLAIMS && { setOpened(null); setListedAction(action); }} />} }
    {opened && } {listedAction && setListedAction(null)} />}
    ; }