Download web/src/apps/reimbursements/AppView.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 37.2 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/reimbursements/AppView.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/apps/reimbursements/AppView.tsx
-
curl -L -o AppView.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/reimbursements/AppView.tsx
37.2 kB
| 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<string, boolean>; | |
| } | |
| 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<string, string> = { | |
| [CLAIMS]: "Nothing to claim", [PAID]: "No reimbursements paid yet", | |
| }; | |
| /** Ledger reason codes as plain words. */ | |
| const LEDGER_REASONS: Record<string, string> = { | |
| 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<string, number>; | |
| items: Claim[]; | |
| cursor: string | null; | |
| problems: string[]; | |
| statuses: string[]; | |
| held: PaidPage; | |
| } | |
| type Row = Record<string, unknown>; | |
| 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<string, PageInfo>; | |
| } | |
| type Load<T> = { 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<unknown> { | |
| 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<string, number> = {}; | |
| 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 <div className="rb-skeleton-rows" aria-busy="true" aria-label="Loading"> | |
| <div className="rb-skeleton" /><div className="rb-skeleton" /><div className="rb-skeleton" /> | |
| </div>; | |
| } | |
| function Failed({ message, onRetry }: { message: string; onRetry: () => void }) { | |
| return <p className="rb-error" role="alert">{message}{" "} | |
| <button type="button" className="rb-link" onClick={onRetry}>Retry</button></p>; | |
| } | |
| /** 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<T>(load: () => Promise<T>): { 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<SkuActionsHost>[0]) { | |
| const host = useLoaded(loadSkuActions); | |
| if (!host) return null; | |
| const Actions = host.value; | |
| return <Actions {...props} />; | |
| } | |
| function ActionList(props: Parameters<ActionListHost>[0]) { | |
| const host = useLoaded(loadActionList); | |
| if (!host) return null; | |
| const Actions = host.value; | |
| return <Actions {...props} />; | |
| } | |
| /** 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 <div className="rb-cadence"><Calendar appId={appId} appKind="reimbursements" canRead /></div>; | |
| } | |
| 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 <section className="rb-to-file" aria-label="To file" data-proof="reimbursements-to-file"> | |
| <KpiStrip label="To file"> | |
| <Kpi label="Units lost" value={totals.units} unit="units" validated={totals.validated} reason={refused} | |
| change={totals.change.units} period={CHANGE_PERIOD} {...withTrend(totals.trend.units)} /> | |
| <Kpi label="Money to claim" value={totals.value} unit={totals.currency} validated={totals.validated} | |
| reason={refused ?? (totals.valueReason || null)} change={totals.change.value} period={CHANGE_PERIOD} | |
| {...withTrend(totals.trend.value)} /> | |
| </KpiStrip> | |
| <ol className="rb-steps" aria-label="How to claim" data-proof="reimbursements-claim-steps"> | |
| {STEPS.map((item, index) => <li key={item.step}> | |
| <span className="rb-step-n" aria-hidden="true">{index + 1}</span> | |
| <span><strong>{item.step}</strong> {item.text}</span> | |
| </li>)} | |
| </ol> | |
| </section>; | |
| } | |
| /** 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 <p className="rb-empty" role="status">This list could not be loaded</p>; | |
| if (!host) return <Skeleton />; | |
| const { Grid } = host; | |
| return <div className="rb-grid" data-proof={proof}> | |
| <Grid table={table} onOpenRow={onOpenRow} empty={empty} /> | |
| </div>; | |
| } | |
| /** 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 <li className="rb-event"> | |
| <span className="rb-event-what">{what}</span> | |
| {detail && <span className="rb-event-detail">{detail}</span>} | |
| <span className="rb-event-when">{when ? dayWords(when) : "Unknown date"}</span> | |
| </li>; | |
| } | |
| 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 <nav className="rb-foot" aria-label={label}> | |
| <span className="rb-results" role="status">{busy ? "Loading" : page.total === 0 ? "0 results" | |
| : `${(page.offset + 1).toLocaleString()} to ${Math.min(page.offset + page.limit, page.total).toLocaleString()} of ${page.total.toLocaleString()}`}</span> | |
| <button type="button" className="rb-button" disabled={page.offset === 0} aria-disabled={busy || page.offset === 0} | |
| onClick={() => { if (!busy && page.offset > 0) onPage(Math.max(0, page.offset - page.limit)); }}>Previous</button> | |
| <button type="button" className="rb-button" disabled={!page.cursor} aria-disabled={busy || !page.cursor} | |
| onClick={() => { if (!busy && page.cursor) onPage(Number(page.cursor)); }}>Next</button> | |
| </nav>; | |
| } | |
| 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 <section className="rb-section" aria-label={title}> | |
| <h3 className="rb-section-title">{title}</h3> | |
| <ol className="rb-events">{lines.map((line, index) => <EventLine key={index} {...line} />)}</ol> | |
| {page && <Pager page={page} busy={busy} onPage={onPage} label={`${title} pages`} />} | |
| </section>; | |
| } | |
| 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<Load<CaseDraft>>({ phase: "loading" }); | |
| const [copied, setCopied] = useState<"" | "done" | "failed">(""); | |
| const timer = useRef<number | null>(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 <section className="rb-section" aria-label="Case text" data-proof="reimbursements-case-text" | |
| data-state={draft.phase === "ready" ? draft.value.status : draft.phase} aria-busy={draft.phase === "loading"}> | |
| <div className="rb-section-head"> | |
| <h3 className="rb-section-title">Case text</h3> | |
| <button type="button" className="rb-button rb-copy" onClick={() => void copy()}> | |
| {copied === "done" ? "Copied" : "Copy"}</button> | |
| </div> | |
| {draft.phase === "loading" && <p className="rb-muted" role="status" data-proof="reimbursements-case-drafting">Drafting</p>} | |
| <p className="rb-case-text">{displayed.split("\n").map((line, index) => | |
| <span key={index}>{index > 0 && <br />}{line}</span>)}</p> | |
| {draft.phase === "ready" && draft.value.reason && <p className="rb-problem" role="status">{draft.value.reason}</p>} | |
| {draft.phase === "error" && <p className="rb-problem" role="status">{draft.message}</p>} | |
| {copied === "failed" && <p className="rb-error" role="alert">Copy did not work. Select the text to copy it.</p>} | |
| </section>; | |
| } | |
| interface DrawerProps { | |
| appId: string; | |
| claim: Claim; | |
| url: (path: string, params?: Record<string, string>) => string; | |
| editable: boolean; | |
| statuses: string[]; | |
| onClose: () => void; | |
| onSaved: () => void; | |
| } | |
| function Drawer({ appId, claim, url, editable, statuses, onClose, onSaved }: DrawerProps) { | |
| const panel = useRef<HTMLElement | null>(null); | |
| const close = useRef<HTMLButtonElement | null>(null); | |
| const [detail, setDetail] = useState<Load<Detail>>({ phase: "loading" }); | |
| const [attempt, setAttempt] = useState(0); | |
| const [cursors, setCursors] = useState<Record<string, string>>({}); | |
| 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<string, string> = { 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 <aside ref={panel} className="rb-drawer" role="dialog" aria-label="Claim" | |
| data-proof={current.kind === "underpaid" ? "reimbursements-underpaid-detail" : undefined}> | |
| <div className="rb-drawer-head"> | |
| <h2 className="rb-drawer-title">{current.title || current.sku || "Claim"}</h2> | |
| <button ref={close} type="button" className="rb-button is-quiet" onClick={onClose}>Close</button> | |
| </div> | |
| <p className="rb-drawer-reason">{current.reason}</p> | |
| {current.sku && <div className="rb-status-actions"> | |
| <button type="button" className="rb-button" data-proof="reimbursements-sku-actions" | |
| onClick={() => setActions(true)}>Actions</button> | |
| </div>} | |
| {actions && current.sku && <ClaimActions appId={appId} appKind="reimbursements" grain="sku" entityKey={current.sku} | |
| title={current.title || current.sku} canEdit={editable} onClose={() => setActions(false)} />} | |
| {editable ? <form className="rb-status-form" onSubmit={(event) => { event.preventDefault(); void save(); }}> | |
| <label className="rb-field"> | |
| <span className="rb-field-label">Status</span> | |
| <select className="rb-select" value={status} disabled={saving} | |
| onChange={(event) => { setStatus(event.target.value); setSaved(false); }}> | |
| {statuses.map((option) => <option key={option} value={option}>{option}</option>)} | |
| </select> | |
| </label> | |
| {(status === "Filed" || caseId) && <label className="rb-field"> | |
| <span className="rb-field-label">Case ID</span> | |
| <input className="rb-input" value={caseId} disabled={saving} inputMode="numeric" placeholder="Amazon case ID" | |
| onChange={(event) => { setCaseId(event.target.value); setSaved(false); }} /> | |
| </label>} | |
| <div className="rb-status-actions"> | |
| <button type="submit" className="rb-button is-primary" disabled={saving || needsCase || !changed}> | |
| {saving ? "Saving" : "Save"}</button> | |
| {saved && <span className="rb-saved" role="status">Saved</span>} | |
| {needsCase && <span className="rb-muted">Filed needs the case ID</span>} | |
| </div> | |
| {saveError && <p className="rb-error" role="alert">{saveError}</p>} | |
| </form> : <dl className="rb-facts"> | |
| <div className="rb-fact"><dt>Status</dt><dd>{current.status}</dd></div> | |
| {current.caseId && <div className="rb-fact"><dt>Case ID</dt><dd className="is-num">{current.caseId}</dd></div>} | |
| </dl>} | |
| <dl className="rb-facts"> | |
| {facts.filter(([, fact]) => fact).map(([label, fact]) => <div key={label} className="rb-fact"> | |
| <dt>{label}</dt><dd className={["Units", "Value", "Shortfall", "Amazon per unit", "Odoo per unit"].includes(label) | |
| ? "is-num" : undefined}>{fact}</dd> | |
| </div>)} | |
| </dl> | |
| {detail.phase === "loading" && <Skeleton />} | |
| {detail.phase === "error" && <Failed message={detail.message} onRetry={() => setAttempt((count) => count + 1)} />} | |
| {value && <> | |
| {current.purchase && <section className="rb-section" aria-label="Purchase evidence" data-proof="underpaid-purchase"> | |
| <h3 className="rb-section-title">Purchase evidence</h3> | |
| <dl className="rb-facts"> | |
| {([ | |
| ["Order", text(current.purchase.order)], ["Line", text(current.purchase.line)], | |
| ["Date", dayWords(text(current.purchase.date))], ["Received", dayWords(text(current.purchase.receiptDate))], | |
| ["Unit price", money(num(current.purchase.unitPrice), text(current.purchase.currency))], | |
| ["Price per Odoo unit", money(num(current.purchase.productUnitPrice), text(current.purchase.currency))], | |
| ["Odoo product", text(current.purchase.productCode)], ["Odoo units per SKU", text(current.purchase.unitsPerSku)], | |
| ] as [string, string][]).map(([label, fact]) => <div key={label} className="rb-fact"> | |
| <dt>{label}</dt><dd>{fact}</dd> | |
| </div>)} | |
| </dl> | |
| </section>} | |
| {value.caseText && <CaseText key={`${current.id}:${attempt}`} value={value.caseText} itemId={current.id} | |
| url={url} onDenied={draftDenied} />} | |
| {pageError && <Failed message={pageError} onRetry={() => setAttempt((count) => count + 1)} />} | |
| <Events title={refund ? "Refund" : "Ledger events"} lines={value.events.map(refund ? refundLine : ledgerLine)} | |
| page={value.pages.events} busy={paging} onPage={(offset) => evidencePage("events", offset)} /> | |
| <Events title="Returns" lines={value.returns.map(returnLine)} page={value.pages.returns} | |
| busy={paging} onPage={(offset) => evidencePage("returns", offset)} /> | |
| <Events title="Paid" lines={value.reimbursements.map(paidLine)} page={value.pages.reimbursements} | |
| busy={paging} onPage={(offset) => evidencePage("reimbursements", offset)} /> | |
| <Events title="History" lines={value.history.map((event) => ({ | |
| when: event.at, what: event.status, detail: [event.caseId && `Case ${event.caseId}`, event.by && `By ${event.by}`, | |
| event.note].filter(Boolean).join(", "), | |
| }))} page={value.pages.history} busy={paging} onPage={(offset) => evidencePage("history", offset)} /> | |
| </>} | |
| </aside>; | |
| } | |
| export default function ReimbursementsView({ application, canEdit }: { | |
| application: ReimbursementsApplication; canEdit?: boolean; | |
| }) { | |
| const appId = application.id; | |
| const url = useCallback((path: string, params: Record<string, string> = {}) => { | |
| 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<Load<Screen>>({ phase: "loading" }); | |
| const [screenAttempt, setScreenAttempt] = useState(0); | |
| const [statuses, setStatuses] = useState<string[]>(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<Claim | null>(null); | |
| const [listedAction, setListedAction] = useState<SkuAction | null>(null); | |
| const opener = useRef<HTMLElement | null>(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 <div className="rb-app"> | |
| <div className="rb-scroll"> | |
| <DashboardTabs tabs={tabs} active={tab} label="Reimbursements tabs" | |
| onChange={(key) => { setTab(key); setHeldOffset(0); setShowHeld(false); setOpened(null); setListedAction(null); }} /> | |
| <div id="reimbursements-panel" role="tabpanel" aria-label={tabs.find((item) => item.id === tab)?.label ?? tab}> | |
| {tab === DASHBOARD ? <> | |
| <Dashboard key={appId} appId={appId} /> | |
| <Cadence appId={appId} /> | |
| </> : <> | |
| {tab === CLAIMS && ready?.toFile && <ToFileTiles totals={ready.toFile} />} | |
| {tab === CLAIMS && <div className="rb-claims-head"> | |
| <button type="button" className={showHeld ? "rb-tab is-active" : "rb-tab"} | |
| aria-pressed={showHeld} data-proof="reimbursements-underpaid-filter" | |
| onClick={() => { setShowHeld((open) => !open); setHeldOffset(0); }}> | |
| <span className="rb-tab-label">Underpaid</span> | |
| <span className="rb-tab-count">{counts ? (counts[UNDERPAID] ?? 0).toLocaleString() : ""}</span> | |
| </button> | |
| </div>} | |
| {ready && ready.problems.length > 0 && <div className="rb-problems"> | |
| {ready.problems.map((problem) => <p key={problem} className="rb-problem" role="status">{problem}</p>)} | |
| </div>} | |
| {tab === CLAIMS && showHeld && ready && <section className="rb-section rb-held" aria-label="Held back" | |
| data-proof="reimbursements-held"> | |
| <h3 className="rb-section-title">Held back</h3> | |
| {ready.held.total === 0 ? <p className="rb-muted" role="status">Nothing held back</p> | |
| : ready.held.rows.map((row) => <p className="rb-problem" key={`${text(row.sku)}:${text(row.reason)}`}> | |
| {text(row.sku) || "Unknown SKU"}: {text(row.reason)}</p>)} | |
| {ready.held.total > 0 && <Pager page={ready.held} busy={busy} onPage={setHeldOffset} label="Held SKU pages" />} | |
| </section>} | |
| <div className="rb-body" aria-busy={busy}> | |
| {screen.phase === "loading" && <Skeleton />} | |
| {screen.phase === "error" && <Failed message={screen.message} onRetry={retry} />} | |
| {tab === CLAIMS && ready && <ModuleGrid key={`claims:${screenAttempt}`} table={CLAIMS_TABLE} | |
| empty={EMPTY[CLAIMS]} proof="reimbursements-claims-grid" onOpenRow={openRow} />} | |
| {tab === PAID && ready && <ModuleGrid table={PAID_TABLE} empty={EMPTY[PAID]} | |
| proof="reimbursements-paid-grid" onOpenRow={ignoreRow} />} | |
| </div> | |
| {tab === CLAIMS && <ActionList appId={appId} canEdit={canEdit === true} onOpenEntity={action => { | |
| setOpened(null); setListedAction(action); | |
| }} />} | |
| </>} | |
| </div> | |
| </div> | |
| {opened && <Drawer key={opened.id} appId={appId} claim={opened} url={url} editable={editable} statuses={statuses} | |
| onClose={closeClaim} onSaved={onSaved} />} | |
| {listedAction && <ClaimActions appId={appId} appKind="reimbursements" grain={listedAction.grain} | |
| entityKey={listedAction.key} title={listedAction.key} canEdit={canEdit === true} | |
| onClose={() => setListedAction(null)} />} | |
| </div>; | |
| } | |