Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/apps/payouts/AppView.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 42 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/payouts/AppView.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/apps/payouts/AppView.tsx
-
curl -L -o AppView.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/payouts/AppView.tsx
42 kB
| import { useCallback, useEffect, useRef, useState } from "react"; | |
| import { API_V1, CREDENTIALS } from "../../apiContract"; | |
| import type { Row } from "../../customer-grid/seam"; | |
| import { useEscapeClose } from "../../ui/useEscapeClose"; | |
| import { AppGrid } from "../AppGrid"; | |
| import CashForecast from "./CashForecast"; | |
| import CaseText from "./CaseText"; | |
| import Dashboard, { DashboardTabs } from "./Dashboard"; | |
| import { Kpi, KpiStrip } from "../../viz/kit/Kpi"; | |
| import type { KpiProps } from "../../viz/kit/Kpi"; | |
| import { ComboChart } from "../../viz/kit/charts"; | |
| import "../../styles/sdlc79/payouts.css"; | |
| import "../../styles/sdlc81/payouts-bank.css"; | |
| // S79-T27 (C2): the Payouts App body. The dispatcher draws the App frame; this view never does. | |
| // Every read and write names the App, so the server applies may_read and may_edit to this App record. | |
| export interface PayoutsApplication { | |
| id: string; | |
| name?: string; | |
| capabilities?: Record<string, boolean>; | |
| } | |
| interface BankMatch { | |
| status: string; | |
| missing: boolean; | |
| difference: number | null; | |
| line: { id: string; date: string; amount: number | null; currency: string; reference: string } | null; | |
| } | |
| interface NextDeposit { expected: boolean; date: string | null; amount: number | null; currency: string; overdue: boolean } | |
| interface OpenSettlement { start: string | null; expectedClose: string | null; currency: string } | |
| interface LastDeposit { date: string | null; amount: number | null; currency: string; change: number | null } | |
| interface Tile { | |
| id: string; label: string; currency: string; period: string; validated: boolean; reason: string; cost: boolean; | |
| value: number | null; change: KpiProps["change"]; series: { week: string; value: number }[]; | |
| } | |
| /** S82-T23's opt-in Kpi prop. Today's Kpi ignores it; lane C's Kpi draws it. */ | |
| interface KpiTrend { trend?: number[] } | |
| interface Screen { | |
| empty: boolean; | |
| currencies: string[]; | |
| counts: { all: number; unreconciled: number; unmatched: number }; | |
| bankMessage: string; | |
| bankAvailable: boolean; | |
| bankMatchDays: number; | |
| canEdit: boolean; | |
| next: NextDeposit | null; | |
| open: OpenSettlement | null; | |
| last: LastDeposit | null; | |
| unreconciled: number; | |
| total: number; | |
| tiles: Tile[]; | |
| } | |
| interface Part { transactionType: string; amountType: string; description: string; amount: number; lines: number } | |
| interface Bucket { key: string; label: string; amount: number | null; parts: Part[]; cursor: string | null; offset: number; total: number } | |
| interface Exclusion { key: string; label: string; monthAmount: number | null } | |
| interface Reference { message: string } | |
| interface Tie { | |
| available: boolean; | |
| final: boolean; | |
| month: string; | |
| monthLabel: string; | |
| currency: string; | |
| basis: string; | |
| settlements: number | null; | |
| economics: number | null; | |
| gap: number | null; | |
| gapPct: number | null; | |
| matched: boolean | null; | |
| exclusions: Exclusion[]; | |
| reference: Reference | null; | |
| message: string; | |
| } | |
| interface Item { id: string; status: string; owner: string; due: string } | |
| interface FeeItem extends Item { | |
| title: string; kind: string; sku: string; shipmentId: string; settlementId: string; currency: string; | |
| chargedAmount: number | null; expectedAmount: number | null; chargedPerUnit: number | null; | |
| expectedPerUnit: number | null; estimateDate: string; disputeBy: string; chargedOn: string; | |
| deadlineBasis: string; expectedBasis: string; policyUrl: string; | |
| } | |
| interface Detail { | |
| canEdit: boolean; | |
| statuses: string[]; | |
| id: string; | |
| title: string; | |
| currency: string; | |
| reconciled: boolean; | |
| bankMatch: BankMatch; | |
| gap: number | null; | |
| reason: string; | |
| waterfall: Bucket[]; | |
| tie: Tie; | |
| item: Item | null; | |
| } | |
| type Load<T> = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T }; | |
| const text = (value: unknown) => (typeof value === "string" ? value : ""); | |
| const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : null); | |
| const rec = (value: unknown) => (value && typeof value === "object" ? value as Record<string, unknown> : {}); | |
| const list = (value: unknown) => (Array.isArray(value) ? value : []); | |
| /** The server's own cause: `error` at the top on the real server, `detail.error` on a bare router. */ | |
| export function refusalMessage(body: unknown): string { | |
| const top = rec(rec(body).error); | |
| const nested = rec(rec(rec(body).detail).error); | |
| return text(top.message) || text(nested.message); | |
| } | |
| async function readJson(response: Response, fallback: string): Promise<unknown> { | |
| const body: unknown = await response.json().catch(() => null); | |
| if (response.ok) return body; | |
| throw new Error(refusalMessage(body) || fallback); | |
| } | |
| function parseScreen(raw: unknown): Screen { | |
| const body = rec(raw); | |
| const kpis = rec(body.kpis); | |
| const counts = rec(body.counts); | |
| const next = kpis.nextDeposit ? rec(kpis.nextDeposit) : null; | |
| const open = kpis.openSettlement ? rec(kpis.openSettlement) : null; | |
| const last = kpis.lastDeposit ? rec(kpis.lastDeposit) : null; | |
| return { | |
| empty: body.empty === true, | |
| currencies: list(body.currencies).map(text).filter(Boolean), | |
| counts: { all: num(counts.all) ?? 0, unreconciled: num(counts.unreconciled) ?? 0, | |
| unmatched: num(counts.unmatched) ?? 0 }, | |
| bankMessage: text(rec(body.bankFeed).message), bankAvailable: rec(body.bankFeed).available === true, | |
| bankMatchDays: num(body.bankMatchDays) ?? 7, canEdit: body.canEdit === true, | |
| next: next && { expected: next.expected === true, date: text(next.date) || null, amount: num(next.amount), | |
| currency: text(next.currency), overdue: next.overdue === true }, | |
| open: open && { start: text(open.start) || null, expectedClose: text(open.expectedClose) || null, | |
| currency: text(open.currency) }, | |
| last: last && { date: text(last.date) || null, amount: num(last.amount), currency: text(last.currency), | |
| change: num(last.change) }, | |
| unreconciled: num(kpis.unreconciled) ?? 0, | |
| total: num(kpis.settlements) ?? 0, | |
| tiles: list(kpis.tiles).map(parseTile).filter((tile) => tile.id), | |
| }; | |
| } | |
| function parseTile(raw: unknown): Tile { | |
| const tile = rec(raw); | |
| const change = tile.change ? rec(tile.change) : null; | |
| return { id: text(tile.id), label: text(tile.label), currency: text(tile.currency), period: text(tile.period), | |
| validated: tile.validated === true, reason: text(tile.reason), cost: tile.cost === true, value: num(tile.value), | |
| change: change ? { previous: num(change.previous), absolute: num(change.absolute), percent: num(change.percent), | |
| reason: text(change.reason) || null } : undefined, | |
| series: list(tile.series).flatMap((point) => { | |
| const p = rec(point); | |
| const value = num(p.value); | |
| return text(p.week) && value !== null ? [{ week: text(p.week), value }] : []; | |
| }) }; | |
| } | |
| /** Deposits, sales, fees and other costs as a 2x2 block beside deposits by settlement week. Costs read positive. */ | |
| function SettlementTiles({ tiles }: { tiles: Tile[] }) { | |
| if (!tiles.length) return null; | |
| const deposits = tiles.find((tile) => tile.id === "deposits"); | |
| const currency = tiles[0].currency; | |
| return <div className="po-tiles" data-proof="payouts-tiles"> | |
| <KpiStrip label={`Payouts, ${currency}`}> | |
| {tiles.map((tile) => { | |
| const trend: KpiTrend = tile.validated ? { trend: tile.series.map((point) => point.value) } : {}; | |
| return <div key={tile.id} data-tile={tile.id} data-cost={tile.cost}> | |
| <Kpi label={tile.label} value={tile.value} unit={tile.currency} validated={tile.validated} | |
| reason={tile.validated ? null : tile.reason} change={tile.change} period={tile.period} {...trend} /> | |
| </div>; | |
| })} | |
| </KpiStrip> | |
| {deposits?.validated && deposits.series.length > 0 && <div data-proof="payouts-deposits-chart"> | |
| <ComboChart title="Deposits by week" currency={currency} size={{ width: 520, height: 200 }} | |
| bars={[{ key: "deposits", label: "Deposits", tone: "navy" }]} | |
| data={deposits.series.map((point) => ({ label: day(point.week, false), deposits: point.value }))} /> | |
| </div>} | |
| </div>; | |
| } | |
| function parseBankMatch(raw: unknown): BankMatch { | |
| const match = rec(raw); | |
| const line = match.bankLine ? rec(match.bankLine) : null; | |
| return { status: text(match.status) || "unavailable", missing: match.missing === true, | |
| difference: num(match.difference), line: line ? { id: text(line.id), date: text(line.date), | |
| amount: num(line.amount), currency: text(line.currency), reference: text(line.paymentRef) } : null }; | |
| } | |
| function bankLabel(status: string): string { | |
| return ({ matched: "Matched", unmatched: "Unmatched", pending: "Pending", | |
| restricted: "Bank access needed", unavailable: "Bank lines unavailable" } as Record<string, string>)[status] | |
| || "Bank lines unavailable"; | |
| } | |
| function parseItem(raw: unknown): Item | null { | |
| const row = rec(raw); | |
| return text(row.id) ? { id: text(row.id), status: text(row.status), owner: text(row.owner), due: text(row.due) } : null; | |
| } | |
| function parseFee(raw: unknown): FeeItem { | |
| const row = rec(raw); | |
| return { id: text(row.id), title: text(row.title), kind: text(row.kind), status: text(row.status), | |
| owner: text(row.owner), due: text(row.due), sku: text(row.sku), shipmentId: text(row.shipmentId), | |
| settlementId: text(row.settlementId), currency: text(row.currency), chargedAmount: num(row.chargedAmount), | |
| expectedAmount: num(row.expectedAmount), chargedPerUnit: num(row.chargedPerUnit), | |
| expectedPerUnit: num(row.expectedPerUnit), estimateDate: text(row.estimateDate), | |
| disputeBy: text(row.disputeBy), chargedOn: text(row.chargedOn), deadlineBasis: text(row.deadlineBasis), | |
| expectedBasis: text(row.expectedBasis), policyUrl: text(row.policyUrl) }; | |
| } | |
| function parseDetail(raw: unknown): Detail { | |
| const body = rec(raw); | |
| const s = rec(body.settlement); | |
| const t = rec(s.tie); | |
| const ref = t.reference ? rec(t.reference) : null; | |
| return { | |
| canEdit: body.canEdit === true, | |
| statuses: list(body.statuses).map(text).filter(Boolean), | |
| id: text(s.id), title: text(s.title), currency: text(s.currency), reconciled: s.reconciled === true, | |
| bankMatch: parseBankMatch(s.bankMatch), | |
| gap: num(s.gap), reason: text(s.reason), | |
| waterfall: list(s.waterfall).map((item) => { | |
| const row = rec(item); | |
| return { | |
| key: text(row.key), label: text(row.label), amount: num(row.amount), | |
| cursor: text(row.cursor) || null, offset: num(row.offset) ?? 0, total: num(row.total) ?? 0, | |
| parts: list(row.parts).map((part) => { | |
| const p = rec(part); | |
| return { transactionType: text(p.transactionType), amountType: text(p.amountType), | |
| description: text(p.description), amount: num(p.amount) ?? 0, lines: num(p.lines) ?? 0 }; | |
| }), | |
| }; | |
| }).filter((row) => row.key), | |
| tie: { | |
| available: t.available === true, final: t.final === true, month: text(t.month), monthLabel: text(t.monthLabel), | |
| currency: text(t.currency), basis: text(t.basis), settlements: num(t.settlements), economics: num(t.economics), | |
| gap: num(t.gap), gapPct: num(t.gapPct), matched: typeof t.matched === "boolean" ? t.matched : null, | |
| exclusions: list(t.exclusions).map((item) => { | |
| const row = rec(item); | |
| return { key: text(row.key), label: text(row.label), monthAmount: num(row.monthAmount) }; | |
| }), | |
| reference: ref && text(ref.message) ? { message: text(ref.message) } : null, | |
| message: text(t.message), | |
| }, | |
| item: parseItem(body.item), | |
| }; | |
| } | |
| /** Money with its currency, for example "$1,234.50" or "CA$255.00"; a bare number when the code is unknown. */ | |
| export function money(amount: number | null, currency: string): string { | |
| if (amount === null) return "Not stated"; | |
| try { | |
| return new Intl.NumberFormat("en-US", { style: "currency", currency: currency || "USD", | |
| currencyDisplay: "symbol" }).format(amount); | |
| } catch { | |
| return amount.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); | |
| } | |
| } | |
| const tone = (amount: number | null) => (amount === null || Math.abs(amount) < 0.005 ? "" : amount < 0 ? " is-neg" : " is-pos"); | |
| const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; | |
| /** "24 Sep 2026" in UTC, the module's own date words; "24 Sep" without the year. */ | |
| function day(iso: string | null, withYear = true): string { | |
| if (!iso) return "Not known"; | |
| const date = new Date(iso.length === 10 ? iso + "T00:00:00Z" : iso); | |
| if (Number.isNaN(date.getTime())) return iso; | |
| const short = `${date.getUTCDate()} ${MONTHS[date.getUTCMonth()]}`; | |
| return withYear ? `${short} ${date.getUTCFullYear()}` : short; | |
| } | |
| function Skeleton({ rows = 4 }: { rows?: number }) { | |
| return <div className="po-skeleton-rows" aria-busy="true" aria-label="Loading"> | |
| {Array.from({ length: rows }, (_, index) => <div key={index} className="po-skeleton" />)} | |
| </div>; | |
| } | |
| function Chevron({ open }: { open: boolean }) { | |
| return <svg className={open ? "po-chevron is-open" : "po-chevron"} width="12" height="12" viewBox="0 0 12 12" | |
| aria-hidden="true"><path d="M4 2.5 7.5 6 4 9.5" fill="none" stroke="currentColor" strokeWidth="1.5" | |
| strokeLinecap="round" strokeLinejoin="round" /></svg>; | |
| } | |
| function Waterfall({ rows, currency, url, settlementId }: { | |
| rows: Bucket[]; currency: string; url: ReturnType<typeof useAppUrl>; settlementId: string; | |
| }) { | |
| const [openKey, setOpenKey] = useState<string | null>(null); | |
| const [pages, setPages] = useState<Record<string, Bucket>>({}); | |
| const [search, setSearch] = useState(""); | |
| const [query, setQuery] = useState(""); | |
| const [offset, setOffset] = useState(0); | |
| const [busy, setBusy] = useState(false); | |
| const [error, setError] = useState(""); | |
| useEffect(() => { | |
| if (!openKey) return; | |
| const controller = new AbortController(); | |
| setBusy(true); | |
| setError(""); | |
| void fetch(url(`/screen/settlements/${encodeURIComponent(settlementId)}`, { | |
| bucket: openKey, cursor: String(offset), limit: "50", q: query, | |
| }), { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((r) => readJson(r, "The parts could not be loaded.")) | |
| .then((raw) => { | |
| const part = parseDetail(raw).waterfall.find((r) => r.key === openKey); | |
| if (!controller.signal.aborted && part) setPages((current) => ({ ...current, [openKey]: part })); | |
| }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : "The parts could not be loaded."); | |
| }).finally(() => { if (!controller.signal.aborted) setBusy(false); }); | |
| return () => controller.abort(); | |
| }, [url, settlementId, openKey, offset, query]); | |
| return <ul className="po-waterfall" aria-label="Waterfall"> | |
| {rows.map((original) => { | |
| const row = pages[original.key] ?? original; | |
| const deposit = row.key === "deposit"; | |
| const expandable = original.total > 0; | |
| const expanded = openKey === row.key; | |
| const amount = <span className={`po-amount${deposit ? "" : tone(row.amount)}`}>{money(row.amount, currency)}</span>; | |
| return <li key={row.key} className={deposit ? "po-step is-deposit" : "po-step"}> | |
| {expandable | |
| ? <button type="button" className="po-step-head" aria-expanded={expanded} | |
| onClick={() => { setOpenKey(expanded ? null : row.key); setOffset(0); setSearch(""); setQuery(""); }}> | |
| <Chevron open={expanded} /><span className="po-step-label">{row.label}</span>{amount} | |
| </button> | |
| : <div className="po-step-head is-static"><span className="po-chevron-gap" aria-hidden="true" /> | |
| <span className="po-step-label">{row.label}</span>{amount}</div>} | |
| {expandable && expanded && <div aria-busy={busy}> | |
| <form onSubmit={(event) => { event.preventDefault(); if (search !== query) { setQuery(search); setOffset(0); } }}> | |
| <input className="po-select" aria-label="Search parts" value={search} onChange={(event) => setSearch(event.target.value)} /> | |
| <button type="submit" className="po-link">Search</button> | |
| </form> | |
| <ul className="po-parts"> | |
| {row.parts.map((part, index) => <li key={`${part.transactionType}:${part.amountType}:${part.description}:${index}`} | |
| className="po-part"> | |
| <span className="po-part-label">{part.description || part.amountType || part.transactionType} | |
| <span className="po-part-kind">{[part.transactionType, part.amountType].filter(Boolean).join(", ")}</span> | |
| </span> | |
| <span className={`po-amount${tone(part.amount)}`}>{money(part.amount, currency)}</span> | |
| </li>)} | |
| </ul> | |
| <nav aria-label="Waterfall pages"> | |
| <button type="button" className="po-link" aria-disabled={busy || offset === 0} | |
| style={busy || offset === 0 ? { opacity: "var(--lp-home-disabled-opacity)", cursor: "not-allowed" } : undefined} | |
| onClick={() => { if (!busy && offset > 0) setOffset(Math.max(0, offset - 50)); }}>Previous</button> | |
| <span> {row.offset + (row.parts.length ? 1 : 0)} to {row.offset + row.parts.length} of {row.total} </span> | |
| <button type="button" className="po-link" aria-disabled={busy || !row.cursor} | |
| style={busy || !row.cursor ? { opacity: "var(--lp-home-disabled-opacity)", cursor: "not-allowed" } : undefined} | |
| onClick={() => { if (!busy && row.cursor) setOffset(Number(row.cursor)); }}>Next</button> | |
| </nav> | |
| {error && <p className="po-error" role="alert">{error}</p>} | |
| </div>} | |
| </li>; | |
| })} | |
| </ul>; | |
| } | |
| function TieLine({ tie, currency }: { tie: Tie; currency: string }) { | |
| const cur = tie.currency || currency; | |
| if (!tie.available) { | |
| return <div className="po-tie"> | |
| <p className="po-note" role="status">{tie.message}</p> | |
| {tie.reference && <p className="po-note">{tie.reference.message}</p>} | |
| </div>; | |
| } | |
| const pct = tie.gapPct === null ? "" : ` (${Math.abs(tie.gapPct).toFixed(1)} percent)`; | |
| return <div className="po-tie"> | |
| <dl className="po-tie-rows"> | |
| <div className="po-tie-row"><dt>Month</dt><dd>{tie.monthLabel}</dd></div> | |
| <div className="po-tie-row"><dt>Settlements without loan repayment and withheld tax</dt> | |
| <dd className="po-num">{money(tie.settlements, cur)}</dd></div> | |
| <div className="po-tie-row"><dt>{tie.basis ? `Economics ${tie.basis}` : "Economics"}</dt> | |
| <dd className="po-num">{money(tie.economics, cur)}</dd></div> | |
| {tie.final && <div className="po-tie-row"><dt>Gap</dt> | |
| <dd className="po-num">{money(tie.gap, cur)}{pct}</dd></div>} | |
| {tie.exclusions.map((ex) => <div key={ex.key} className="po-tie-row is-excluded"> | |
| <dt>Excluded {ex.label.toLowerCase()}</dt><dd className="po-num">{money(ex.monthAmount, cur)}</dd></div>)} | |
| </dl> | |
| {tie.final | |
| ? <p className={tie.matched ? "po-verdict is-matched" : "po-verdict is-unmatched"} role="status"> | |
| {tie.matched ? "Matched" : "Not matched"}</p> | |
| : <> | |
| <p className="po-note" role="status">{tie.message}</p> | |
| {tie.reference && <p className="po-verdict">{tie.reference.message}</p>} | |
| </>} | |
| </div>; | |
| } | |
| function BankLine({ match, currency }: { match: BankMatch; currency: string }) { | |
| return <section className="po-section po-bank-match" aria-label="Bank match" data-bank-match={match.status}> | |
| <h3 className="po-heading">Bank match</h3> | |
| <p className={`po-verdict${match.status === "matched" ? " is-matched" : ""}`} role="status"> | |
| {bankLabel(match.status)}</p> | |
| {match.line && <dl className="po-tie-rows"> | |
| <div className="po-tie-row"><dt>Bank line</dt><dd>{match.line.reference || `Line ${match.line.id}`}</dd></div> | |
| <div className="po-tie-row"><dt>Line</dt><dd className="po-num">{match.line.id}</dd></div> | |
| <div className="po-tie-row"><dt>Date</dt><dd>{day(match.line.date)}</dd></div> | |
| <div className="po-tie-row"><dt>Amount</dt><dd className="po-num">{money(match.line.amount, match.line.currency)}</dd></div> | |
| <div className="po-tie-row"><dt>Difference</dt><dd className="po-num">{money(match.difference, currency)}</dd></div> | |
| </dl>} | |
| </section>; | |
| } | |
| function BankSettings({ days, url, onSaved }: { | |
| days: number; url: ReturnType<typeof useAppUrl>; onSaved: () => void; | |
| }) { | |
| const [value, setValue] = useState(String(days)); | |
| const [saving, setSaving] = useState(false); | |
| const [error, setError] = useState(""); | |
| const [saved, setSaved] = useState(false); | |
| useEffect(() => { setValue(String(days)); }, [days]); | |
| const save = async () => { | |
| setSaving(true); setError(""); setSaved(false); | |
| try { | |
| await readJson(await fetch(url("/settings"), { method: "PATCH", credentials: CREDENTIALS, | |
| headers: { "Content-Type": "application/json" }, body: JSON.stringify({ bankMatchDays: Number(value) }) }), | |
| "The bank window was not saved."); | |
| setSaved(true); onSaved(); | |
| } catch (reason) { | |
| setError(reason instanceof Error ? reason.message : "The bank window was not saved."); | |
| } finally { setSaving(false); } | |
| }; | |
| return <form className="po-bank-settings" onSubmit={(event) => { event.preventDefault(); void save(); }}> | |
| <label className="po-field"><span className="po-field-label">Bank match days</span> | |
| <input className="po-select" type="number" min="0" step="1" required value={value} disabled={saving} | |
| onChange={(event) => { setValue(event.target.value); setSaved(false); }} /></label> | |
| <button type="submit" className="po-more" disabled={saving || value === "" || !Number.isInteger(Number(value)) | |
| || Number(value) < 0 || Number(value) === days}>{saving ? "Saving" : "Save"}</button> | |
| {saved && <span className="po-note" role="status">Saved</span>} | |
| {error && <p className="po-error" role="alert">{error}</p>} | |
| </form>; | |
| } | |
| function useAppUrl(appId: string) { | |
| return useCallback((path: string, params: Record<string, string> = {}) => { | |
| const query = new URLSearchParams({ app: appId, ...params }); | |
| return `${API_V1}/app-kinds/payouts${path}?${query.toString()}`; | |
| }, [appId]); | |
| } | |
| function FeeDrawer({ item, url, canEdit, saving, error, onStatus, onClose, onDenied }: { | |
| item: FeeItem; canEdit: boolean; saving: boolean; error: string; | |
| url: ReturnType<typeof useAppUrl>; | |
| onStatus: (item: FeeItem, status: string) => void; onClose: () => void; onDenied: () => void; | |
| }) { | |
| const panel = useRef<HTMLElement | null>(null); | |
| useEscapeClose(true, onClose, { container: () => panel.current }); | |
| useEffect(() => { panel.current?.focus(); }, [item.id]); | |
| return <aside className="po-drawer" role="dialog" aria-modal="false" aria-labelledby="po-fee-title" | |
| tabIndex={-1} ref={panel} data-fee-drawer={item.kind}> | |
| <div className="po-drawer-head"> | |
| <h2 className="po-drawer-title" id="po-fee-title">{item.title}</h2> | |
| <button type="button" className="po-icon-button" onClick={onClose} aria-label="Close"> | |
| <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M3 3l8 8M11 3l-8 8" | |
| stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg> | |
| </button> | |
| </div> | |
| <div className="po-drawer-body"> | |
| <div className="po-item"> | |
| <label className="po-field"><span className="po-field-label">Status</span> | |
| {canEdit ? <select className="po-select" value={item.status} disabled={saving} | |
| onChange={(event) => onStatus(item, event.target.value)}> | |
| <option value="Open">Open</option><option value="Disputed">Disputed</option> | |
| </select> : <span className="po-field-value">{item.status}</span>} | |
| </label> | |
| <div className="po-field"><span className="po-field-label">Owner</span> | |
| <span className="po-field-value">{item.owner || "Not set"}</span></div> | |
| </div> | |
| {error && <p className="po-error" role="alert">{error}</p>} | |
| <dl className="po-tie-rows"> | |
| <div className="po-tie-row"><dt>Settlement</dt><dd>{item.settlementId}</dd></div> | |
| {item.sku && <div className="po-tie-row"><dt>SKU</dt><dd>{item.sku}</dd></div>} | |
| {item.shipmentId && <div className="po-tie-row"><dt>Shipment</dt><dd>{item.shipmentId}</dd></div>} | |
| <div className="po-tie-row"><dt>Charged</dt><dd className="po-num">{money(item.chargedAmount, item.currency)}</dd></div> | |
| <div className="po-tie-row"><dt>Expected</dt><dd className="po-num">{money(item.expectedAmount, item.currency)}</dd></div> | |
| {item.kind === "fulfillment" && <> | |
| <div className="po-tie-row"><dt>Charged per unit</dt><dd className="po-num">{money(item.chargedPerUnit, item.currency)}</dd></div> | |
| <div className="po-tie-row"><dt>Expected per unit</dt><dd className="po-num">{money(item.expectedPerUnit, item.currency)}</dd></div> | |
| <div className="po-tie-row"><dt>Estimate date</dt><dd>{day(item.estimateDate)}</dd></div> | |
| </>} | |
| <div className="po-tie-row"><dt>Charge date</dt><dd>{day(item.chargedOn)}</dd></div> | |
| <div className="po-tie-row"><dt>Dispute by</dt><dd>{item.disputeBy ? day(item.disputeBy) : "Unknown"}</dd></div> | |
| </dl> | |
| <p className="po-note">{item.deadlineBasis}</p> | |
| <p className="po-note">{item.expectedBasis}</p> | |
| <a className="po-link" href={item.policyUrl} target="_blank" rel="noreferrer">Amazon policy</a> | |
| {item.status === "Open" && <CaseText key={item.id} itemId={item.id} url={url} onDenied={onDenied} />} | |
| </div> | |
| </aside>; | |
| } | |
| type FeeLoad = { phase: "loading" } | { phase: "error"; message: string } | |
| | { phase: "ready"; canEdit: boolean; message: string }; | |
| function FeeChecks({ url, canEdit }: { url: ReturnType<typeof useAppUrl>; canEdit: boolean }) { | |
| const [load, setLoad] = useState<FeeLoad>({ phase: "loading" }); | |
| const [attempt, setAttempt] = useState(0); | |
| const [gridKey, setGridKey] = useState(0); | |
| const [selected, setSelected] = useState<string | null>(null); | |
| const [item, setItem] = useState<FeeItem | null>(null); | |
| const [itemError, setItemError] = useState(""); | |
| const [saving, setSaving] = useState(false); | |
| const [saveError, setSaveError] = useState(""); | |
| const close = useCallback(() => { setSelected(null); setItem(null); setSaveError(""); }, []); | |
| const denied = useCallback(() => { | |
| setSelected(null); setItem(null); setLoad({ phase: "error", message: "Fee checks are unavailable. Check your access." }); | |
| }, []); | |
| // The table is written by POST only, so no GET writes it and the Grid never reads a stale copy. | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setLoad({ phase: "loading" }); setSelected(null); setItem(null); | |
| void fetch(url("/fee-checks", { limit: "1" }), { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "Fee checks could not be loaded.")) | |
| .then(async (raw) => { | |
| const body = rec(raw); | |
| await readJson(await fetch(url("/fee-table"), { method: "POST", credentials: CREDENTIALS, signal: controller.signal }), | |
| "The fee checks table could not be built."); | |
| if (!controller.signal.aborted) setLoad({ phase: "ready", canEdit: body.canEdit === true, message: text(body.message) }); | |
| }).catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setLoad({ phase: "error", | |
| message: reason instanceof Error ? reason.message : "Fee checks could not be loaded." }); | |
| }); | |
| return () => controller.abort(); | |
| }, [url, attempt]); | |
| // The drawer reads the one fee check the clicked row names. | |
| useEffect(() => { | |
| if (!selected) return; | |
| const controller = new AbortController(); | |
| setItem(null); setItemError(""); | |
| void fetch(url("/fee-checks", { item: selected, limit: "1" }), { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "That fee check could not be loaded.")) | |
| .then((raw) => { | |
| if (controller.signal.aborted) return; | |
| const first = list(rec(raw).items)[0]; | |
| if (first) setItem(parseFee(first)); else setItemError("That fee check does not exist."); | |
| }).catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setItemError(reason instanceof Error ? reason.message : "That fee check could not be loaded."); | |
| }); | |
| return () => controller.abort(); | |
| }, [url, selected]); | |
| const openRow = useCallback((row: Row) => { | |
| const id = row.fee_id; | |
| if (typeof id === "string" && id) { setSelected(id); setSaveError(""); } | |
| }, []); | |
| const setStatus = async (current: FeeItem, status: string) => { | |
| setSaving(true); setSaveError(""); | |
| try { | |
| const raw = await readJson(await fetch(url(`/fee-checks/${encodeURIComponent(current.id)}`), { | |
| method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ status }), | |
| }), "The status was not saved."); | |
| setItem((shown) => shown?.id === current.id ? parseFee(raw) : shown); | |
| setGridKey((count) => count + 1); | |
| } catch (reason) { setSaveError(reason instanceof Error ? reason.message : "The status was not saved."); } | |
| finally { setSaving(false); } | |
| }; | |
| const ready = load.phase === "ready" ? load : null; | |
| return <section className="po-section" role="tabpanel" aria-label="Fee checks" data-proof="payouts-fee-checks" | |
| aria-busy={load.phase === "loading"}> | |
| {load.phase === "loading" && <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading fee checks" />} | |
| {load.phase === "error" && <p className="po-error" role="alert">{load.message}{" "} | |
| <button type="button" className="po-link" onClick={() => setAttempt((count) => count + 1)}>Retry</button></p>} | |
| {ready?.message && <p className="po-note" role="status">{ready.message}</p>} | |
| {ready && <div className="po-grid" data-proof="payouts-fee-grid"> | |
| <AppGrid key={gridKey} table="ut_amazon_fee_checks" onOpenRow={openRow} | |
| empty={<p className="po-empty" role="status">No fee differences</p>} /> | |
| </div>} | |
| {selected && itemError && <p className="po-error" role="alert">{itemError}</p>} | |
| {item && <FeeDrawer item={item} url={url} canEdit={canEdit && ready?.canEdit === true} saving={saving} error={saveError} | |
| onStatus={(row, status) => { void setStatus(row, status); }} onClose={close} onDenied={denied} />} | |
| </section>; | |
| } | |
| function SettlementDrawer({ appId, settlementId, canEditApp, bankMatchDays, onClose }: { | |
| appId: string; settlementId: string; canEditApp: boolean; bankMatchDays: number; onClose: () => void; | |
| }) { | |
| const url = useAppUrl(appId); | |
| const [state, setState] = useState<Load<Detail>>({ phase: "loading" }); | |
| const [attempt, setAttempt] = useState(0); | |
| const [saving, setSaving] = useState(false); | |
| const [saveError, setSaveError] = useState(""); | |
| const panel = useRef<HTMLElement | null>(null); | |
| const alive = useRef(true); | |
| useEffect(() => () => { alive.current = false; }, []); | |
| useEscapeClose(true, onClose, { container: () => panel.current }); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setState({ phase: "loading" }); | |
| setSaveError(""); | |
| void fetch(url(`/screen/settlements/${encodeURIComponent(settlementId)}`), | |
| { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "The settlement could not be loaded.")) | |
| .then((body) => { if (!controller.signal.aborted) setState({ phase: "ready", value: parseDetail(body) }); }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setState({ phase: "error", | |
| message: reason instanceof Error ? reason.message : "The settlement could not be loaded." }); | |
| }); | |
| return () => controller.abort(); | |
| }, [url, settlementId, attempt, bankMatchDays]); | |
| useEffect(() => { panel.current?.focus(); }, [settlementId]); | |
| const setStatus = async (item: Item, status: string) => { | |
| setSaving(true); | |
| setSaveError(""); | |
| try { | |
| const response = await fetch(url(`/items/${encodeURIComponent(item.id)}`), { | |
| method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ status }), | |
| }); | |
| const saved = parseItem(await readJson(response, "The status was not saved.")); | |
| if (!alive.current) return; | |
| setState((current) => current.phase !== "ready" ? current | |
| : { phase: "ready", value: { ...current.value, item: saved ?? { ...item, status } } }); | |
| } catch (reason) { | |
| if (alive.current) setSaveError(reason instanceof Error ? reason.message : "The status was not saved."); | |
| } finally { | |
| if (alive.current) setSaving(false); | |
| } | |
| }; | |
| const detail = state.phase === "ready" ? state.value : null; | |
| const canEdit = canEditApp && detail?.canEdit === true; | |
| return <aside className="po-drawer" role="dialog" aria-modal="false" aria-labelledby="po-drawer-title" | |
| tabIndex={-1} ref={panel}> | |
| <div className="po-drawer-head"> | |
| <h2 className="po-drawer-title" id="po-drawer-title">{detail?.title || "Settlement"}</h2> | |
| <button type="button" className="po-icon-button" aria-label="Close" onClick={onClose}> | |
| <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="M3 3l8 8M11 3l-8 8" | |
| stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg> | |
| </button> | |
| </div> | |
| {state.phase === "loading" && <Skeleton rows={6} />} | |
| {state.phase === "error" && <p className="po-error" role="alert">{state.message}{" "} | |
| <button type="button" className="po-link" onClick={() => setAttempt((count) => count + 1)}>Retry</button></p>} | |
| {detail && <div className="po-drawer-body"> | |
| <BankLine match={detail.bankMatch} currency={detail.currency} /> | |
| {(!detail.reconciled || detail.item) && <section className="po-section" aria-label="Owned item"> | |
| {!detail.reconciled && <p className="po-flag"><span className="po-chip">Unreconciled</span> | |
| <span className="po-amount is-neg">Gap {money(detail.gap, detail.currency)}</span></p> | |
| } | |
| {detail.reconciled && detail.bankMatch.missing && <p className="po-note">No matching bank line</p>} | |
| {detail.reason && <p className="po-note">{detail.reason}</p>} | |
| {detail.item && <div className="po-item"> | |
| <label className="po-field"> | |
| <span className="po-field-label">Status</span> | |
| {canEdit | |
| ? <select className="po-select" value={detail.item.status} disabled={saving} | |
| onChange={(event) => { if (detail.item) void setStatus(detail.item, event.target.value); }}> | |
| {detail.statuses.map((status) => <option key={status} value={status}>{status}</option>)} | |
| </select> | |
| : <span className="po-field-value">{detail.item.status}</span>} | |
| </label> | |
| <div className="po-field"><span className="po-field-label">Owner</span> | |
| <span className="po-field-value">{detail.item.owner || "Not set"}</span></div> | |
| <div className="po-field"><span className="po-field-label">Due</span> | |
| <span className="po-field-value po-num">{detail.item.due ? day(detail.item.due) : "Not set"}</span></div> | |
| </div>} | |
| {saveError && <p className="po-error" role="alert">{saveError}</p>} | |
| </section>} | |
| <section className="po-section" aria-label="Waterfall"> | |
| <h3 className="po-heading">Waterfall</h3> | |
| <Waterfall rows={detail.waterfall} currency={detail.currency} url={url} settlementId={settlementId} /> | |
| </section> | |
| <section className="po-section" aria-label="Tie to economics"> | |
| <h3 className="po-heading">Tie to economics</h3> | |
| <TieLine tie={detail.tie} currency={detail.currency} /> | |
| </section> | |
| </div>} | |
| </aside>; | |
| } | |
| type TableLoad = { phase: "idle" } | { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready" }; | |
| function PayoutsBody({ application, canEdit = false }: { | |
| application: PayoutsApplication; canEdit?: boolean; | |
| }) { | |
| const appId = application.id; | |
| const url = useAppUrl(appId); | |
| const [fees, setFees] = useState(false); | |
| const [forecast, setForecast] = useState(false); | |
| const [dashboard, setDashboard] = useState(false); | |
| const [attempt, setAttempt] = useState(0); | |
| const [state, setState] = useState<Load<Screen>>({ phase: "loading" }); | |
| const [busy, setBusy] = useState(false); | |
| const [pageError, setPageError] = useState(""); | |
| const [table, setTable] = useState<TableLoad>({ phase: "idle" }); | |
| const [selected, setSelected] = useState<string | null>(null); | |
| useEffect(() => { | |
| if (dashboard) return; | |
| const controller = new AbortController(); | |
| setBusy(true); | |
| setPageError(""); | |
| void fetch(url("/screen", { limit: "1" }), { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "Payouts could not be loaded.")) | |
| .then((body) => { if (!controller.signal.aborted) setState({ phase: "ready", value: parseScreen(body) }); }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setPageError(reason instanceof Error ? reason.message : "Payouts could not be loaded."); | |
| }).finally(() => { if (!controller.signal.aborted) setBusy(false); }); | |
| return () => controller.abort(); | |
| }, [url, attempt, dashboard]); | |
| const screen = state.phase === "ready" ? state.value : null; | |
| const settlementsTab = !dashboard && !fees && !forecast; | |
| const hasRows = screen !== null && !screen.empty; | |
| // The table is written by POST only, so no GET writes it and the Grid never reads a stale copy. | |
| useEffect(() => { | |
| if (!settlementsTab || !hasRows) return; | |
| const controller = new AbortController(); | |
| setTable({ phase: "loading" }); | |
| void fetch(url("/table"), { method: "POST", credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "The settlements table could not be built.")) | |
| .then(() => { if (!controller.signal.aborted) setTable({ phase: "ready" }); }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setTable({ phase: "error", | |
| message: reason instanceof Error ? reason.message : "The settlements table could not be built." }); | |
| }); | |
| return () => controller.abort(); | |
| }, [url, settlementsTab, hasRows, attempt]); | |
| const close = useCallback(() => setSelected(null), []); | |
| const openRow = useCallback((row: Row) => { | |
| const id = row.settlement_id; | |
| if (typeof id === "string" && id) setSelected(id); | |
| else if (typeof id === "number") setSelected(String(id)); | |
| }, []); | |
| const tabs = [{ id: "all", label: "Settlements", count: screen?.counts.all }, | |
| { id: "dashboard", label: "Dashboard" }, | |
| { id: "forecast", label: "Cash forecast" }, { id: "fees", label: "Fee checks" }]; | |
| const active = dashboard ? "dashboard" : fees ? "fees" : forecast ? "forecast" : "all"; | |
| const unmatched = screen?.counts.unmatched ?? 0; | |
| return <div className={selected ? "po-app has-drawer" : "po-app"} data-proof="payouts-bank-match"> | |
| <div className="po-main" aria-busy={settlementsTab && (busy || table.phase === "loading")}> | |
| <DashboardTabs tabs={tabs} active={active} label="Payouts tabs" onChange={(key) => { | |
| setDashboard(key === "dashboard"); setFees(key === "fees"); setForecast(key === "forecast"); setSelected(null); | |
| }} /> | |
| <div id="payouts-panel" role="tabpanel" aria-label={tabs.find((tab) => tab.id === active)?.label}> | |
| {dashboard ? <Dashboard key={appId} appId={appId} /> : <> | |
| {!forecast && !screen && busy && <> | |
| <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading payouts" /> | |
| <Skeleton /> | |
| </>} | |
| {!forecast && pageError && <p className="po-error" role="alert">{pageError}{" "} | |
| <button type="button" className="po-link" onClick={() => setAttempt((count) => count + 1)}>Retry</button></p>} | |
| {screen && screen.empty && !fees && !forecast && <p className="po-empty" role="status">No settlements yet</p>} | |
| {!forecast && screen?.bankMessage && <p className="po-note po-bank-feed" role="status" data-bank-feed="stale">{screen.bankMessage}</p>} | |
| {fees && <FeeChecks url={url} canEdit={canEdit} />} | |
| {forecast && <CashForecast appId={appId} />} | |
| {settlementsTab && hasRows && <section className="po-settlements" aria-label="Settlements" | |
| data-proof="payouts-settlement-grid"> | |
| {screen && <SettlementTiles tiles={screen.tiles} />} | |
| {screen?.bankAvailable && <p className="po-note po-unmatched" role="status" data-unmatched={unmatched}> | |
| {unmatched === 0 ? "Every deposit has a bank line" | |
| : `${unmatched} ${unmatched === 1 ? "deposit has" : "deposits have"} no bank line`}</p>} | |
| {table.phase === "loading" && <span className="lp-spin lp-spin--lg" role="status" aria-label="Loading settlements" />} | |
| {table.phase === "error" && <p className="po-error" role="alert">{table.message}{" "} | |
| <button type="button" className="po-link" onClick={() => setAttempt((count) => count + 1)}>Retry</button></p>} | |
| {table.phase === "ready" && <div className="po-grid"> | |
| <AppGrid table="ut_amazon_payouts" onOpenRow={openRow} | |
| empty={<p className="po-empty" role="status">No settlements yet</p>} /> | |
| </div>} | |
| </section>} | |
| {settlementsTab && screen && canEdit && screen.canEdit && <BankSettings days={screen.bankMatchDays} url={url} | |
| onSaved={() => setAttempt((count) => count + 1)} />} | |
| </>} | |
| </div> | |
| </div> | |
| {selected && <SettlementDrawer key={selected} appId={appId} settlementId={selected} canEditApp={canEdit} | |
| bankMatchDays={screen?.bankMatchDays ?? 7} onClose={close} />} | |
| </div>; | |
| } | |
| export default function PayoutsAppView({ application, canEdit = false }: { | |
| application: PayoutsApplication; canEdit?: boolean; | |
| }) { | |
| return <PayoutsBody key={application.id} application={application} canEdit={canEdit} />; | |
| } | |