runloopable / web /src /app /FinanceWorkspace.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
07a68d0 verified
Raw History Blame Contribute Delete
41.7 kB
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useEscapeClose } from "../ui/useEscapeClose"; import "./finance.css"; import "../styles/sdlc72/app-fullscreen.css"; type FactState = "ready" | "warming" | "missing" | "unavailable" | "restricted" | "requires_sku"; type FinanceFact = { key: string; label: string; format: "usd" | "int" | "pct"; scope: "business_unit" | "hq_consolidated" | "all_channel_inventory"; state: FactState; value: number | null; message?: string; requiredGrain?: string; freshness: { state: string; asOf?: string | null }; lineage: { topic: string; metric: string; sourceEntities: string[] }; drillThrough: { kind: "source_records"; href: string }; reconciliation: { state: string; method: string; href: string }; }; type MirrorWorklistContract = { title: string; cadence: string; kind?: undefined; sourceFact: string; pageSize: number; maxRows: number; displayLimit: number; entityField: string; documentField: string; amountField: string; // C10: agingLabel prints "Overdue" from this field, so it binds the Odoo-matching `ar_overdue`, never the grace number. overdueAmountField?: string; dueDateField: string; ownerField: string; statusField: string; promiseDateField?: string; promiseAmountField?: string; nextAction: string; previewOnly: boolean; concentration?: boolean; }; type UnavailableWorkSignal = { key: string; label: string; state: "unavailable"; scope: FinanceFact["scope"]; basisLabel: string; missingSource: string; sourceModule: string; validationMethod: string; ownerRole: string; status: "unavailable"; nextAction: string; }; type RequirementsWorklistContract = { kind: "unavailable_requirements"; title: string; cadence: string; basisNotice: string; signals: UnavailableWorkSignal[]; sourceFact?: undefined; }; type WorklistContract = MirrorWorklistContract | RequirementsWorklistContract; type DashboardUnavailable = { state: "unavailable"; missingSource: string; }; type DashboardFactCell = { state: "fact"; factKey: string; }; type DashboardMetric = { key: string; label: string; format: "usd" | "int" | "pct" | "days"; state: "unavailable"; scope: FinanceFact["scope"]; basisLabel: string; missingSource: string; validationMethod: string; drillDimension?: string; sourceFact?: string; }; type DashboardComparisonRow = { key: string; label: string; basisLabel: string; actual: DashboardFactCell | DashboardUnavailable; budget: DashboardFactCell | DashboardUnavailable; prior: DashboardFactCell | DashboardUnavailable; validationMethod: string; }; type DashboardPlanningRow = { key: string; label: string; scope: FinanceFact["scope"]; basisLabel: string; actual: DashboardFactCell; plan: DashboardUnavailable; variance: DashboardUnavailable; driver: DashboardUnavailable; validationMethod: string; }; type DashboardSection = { key: string; title: string; kind: "metric_strip" | "drill_matrix" | "comparison" | "planning"; basisLabel?: string; metrics?: DashboardMetric[]; columns?: string[]; rows?: DashboardComparisonRow[]; planningRows?: DashboardPlanningRow[]; notice?: string; }; type DashboardContract = { basisNotice: string; sections: DashboardSection[]; }; type FinanceApplication = { key: string; label: string; navLabel: string; mode: "workflow" | "dashboard"; question: string; deepLink: string; factKeys: string[]; kpiKeys: string[]; worklist?: WorklistContract; dashboard?: DashboardContract; }; type ApplicationPayload = { state: string; application: FinanceApplication; businessUnit: number | null; facts: FinanceFact[]; kpis: FinanceFact[]; }; type DrillPayload = { fact?: FinanceFact; state?: string; rows?: Record<string, unknown>[]; row_count?: number | null; total_count?: number | null; aggregates?: Record<string, number | null>; }; type WorklistPayload = DrillPayload & { total_count?: number | null; }; type WorklistState = | { kind: "idle" } | { kind: "loading" } | { kind: "ready"; payload: WorklistPayload; complete: boolean } | { kind: "error"; message: string }; type WorkItem = { key: string; entity: string; document: string; amount: number | null; overdueAmount: number | null; dueDate: string; aging: string; owner: string; status: string; promise: string; concentration: number | null; concentrationAvailable: boolean; exception: string; priority: string; nextAction: string; source: Record<string, unknown>; }; type PageState = | { kind: "loading" } | { kind: "ready"; data: ApplicationPayload } | { kind: "restricted" } | { kind: "missing" } | { kind: "error"; message: string }; const CREDENTIALS: RequestCredentials = "include"; /** S72-T62 (R108 k): the class on `<html>` that hides the shell rail and top bar. It matches * `CustomerGrid.tsx::APP_FULLSCREEN_CLASS`, so grid and Finance Apps share one rule. */ const APP_FULLSCREEN_CLASS = "is-app-fullscreen"; /** The App root wears this while full screen. The root class leaves when no root wears it. */ const APP_FULLSCREEN_MARK = "data-app-fullscreen"; const APP_FULLSCREEN_TABBABLE = "button:not([disabled]),input:not([disabled])," + "select:not([disabled]),textarea:not([disabled]),[href],[tabindex]:not([tabindex=\"-1\"])"; /** * Full screen for one App root. Component state only, so a reload never restores it. Escape * leaves through the shared arbiter, and Tab wraps inside the root while the chrome is hidden. */ function useAppFullscreen(rootRef: { current: HTMLElement | null }) { const [fullscreen, setFullscreen] = useState(false); const toggleFullscreen = useCallback(() => setFullscreen(on => !on), []); const exitFullscreen = useCallback(() => setFullscreen(false), []); const fullscreenContainer = useCallback(() => rootRef.current, [rootRef]); useEscapeClose(fullscreen, exitFullscreen, { cancelEditFirst: true, container: fullscreenContainer }); useEffect(() => { if (!fullscreen) return; const html = document.documentElement; html.classList.add(APP_FULLSCREEN_CLASS); const onTab = (event: KeyboardEvent) => { const root = rootRef.current; if (event.key !== "Tab" || !root) return; const active = document.activeElement; const outside = !active || active === document.body || active === html; if (!outside && !root.contains(active)) return; const stops = Array.from(root.querySelectorAll<HTMLElement>(APP_FULLSCREEN_TABBABLE)) .filter(element => element.getClientRects().length > 0); if (!stops.length) return; const first = stops[0]; const last = stops[stops.length - 1]; if (outside) { event.preventDefault(); (event.shiftKey ? last : first).focus(); } else if (event.shiftKey && active === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && active === last) { event.preventDefault(); first.focus(); } }; document.addEventListener("keydown", onTab, true); return () => { document.removeEventListener("keydown", onTab, true); // Runs after React removed this root's mark, on exit and on unmount alike. if (!document.querySelector(`[${APP_FULLSCREEN_MARK}]`)) html.classList.remove(APP_FULLSCREEN_CLASS); }; }, [fullscreen, rootRef]); return { fullscreen, toggleFullscreen }; } function pathApplicationKey() { if (typeof window === "undefined") return ""; const match = `${window.location.pathname}${window.location.hash}`.match(/\/finance\/([^/?#]+)/); return match ? decodeURIComponent(match[1]) : ""; } function displayValue(fact: FinanceFact) { if (fact.state !== "ready" || fact.value == null) return "Not available"; if (fact.format === "usd") { return new Intl.NumberFormat(undefined, { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(fact.value); } if (fact.format === "pct") return `${(fact.value * 100).toFixed(1)}%`; return new Intl.NumberFormat().format(fact.value); } function stateLabel(state: string) { return state.replaceAll("_", " "); } function isMirrorWorklist(contract: WorklistContract): contract is MirrorWorklistContract { return contract.kind !== "unavailable_requirements"; } function numberValue(value: unknown) { if (value == null || value === "" || typeof value === "boolean") return null; const parsed = typeof value === "number" ? value : Number(value); return Number.isFinite(parsed) ? parsed : null; } function textValue(value: unknown) { const text = typeof value === "string" || typeof value === "number" ? String(value).trim() : ""; return text || "Unavailable"; } function money(value: number | null) { return value == null ? "Unavailable" : new Intl.NumberFormat(undefined, { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(value); } function dueAge(value: unknown) { const text = typeof value === "string" ? value.slice(0, 10) : ""; if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) return { date: "Unavailable", days: null }; const due = new Date(`${text}T00:00:00Z`).getTime(); const now = new Date(); const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()); return { date: text, days: Math.max(0, Math.floor((today - due) / 86_400_000)) }; } function agingLabel(days: number | null, overdueAmount: number | null) { if (days != null && days > 90) return "90+ days"; if (days != null && days > 60) return "61-90 days"; if (days != null && days > 30) return "31-60 days"; if (days != null && days > 0) return "1-30 days"; if (days === 0) return "Current"; if (overdueAmount != null) return overdueAmount > 0 ? "Overdue" : "Current"; return "Unavailable"; } function workItems(contract: MirrorWorklistContract, payload: WorklistPayload, complete: boolean) { const rows = payload.rows || []; const entityTotals = new Map<string, number>(); for (const row of rows) { const entity = textValue(row[contract.entityField]); const amount = numberValue(row[contract.amountField]); if (amount != null) entityTotals.set(entity, (entityTotals.get(entity) || 0) + amount); } const payloadTotal = numberValue(payload.aggregates?.[contract.amountField]); const computedTotal = rows.reduce((sum, row) => sum + (numberValue(row[contract.amountField]) || 0), 0); const total = payloadTotal ?? (complete ? computedTotal : null); const concentrationAvailable = Boolean(contract.concentration && complete && total != null && total > 0); const items = rows.map((row, index): WorkItem => { const entity = textValue(row[contract.entityField]); const document = textValue(row[contract.documentField]); const amount = numberValue(row[contract.amountField]); const overdueAmount = contract.overdueAmountField ? numberValue(row[contract.overdueAmountField]) : null; const due = dueAge(row[contract.dueDateField]); const aging = agingLabel(due.days, overdueAmount); const concentration = concentrationAvailable ? Math.max(0, entityTotals.get(entity) || 0) / (total as number) : null; const promiseDate = contract.promiseDateField ? textValue(row[contract.promiseDateField]) : "Unavailable"; const promiseAmount = contract.promiseAmountField ? numberValue(row[contract.promiseAmountField]) : null; const promise = promiseDate !== "Unavailable" || promiseAmount != null ? [promiseDate !== "Unavailable" ? promiseDate : null, promiseAmount != null ? money(promiseAmount) : null].filter(Boolean).join(" · ") : "Unavailable"; const overdue = (due.days != null && due.days > 0) || (overdueAmount != null && overdueAmount > 0); const credit = amount != null && amount < 0; const concentrated = concentration != null && concentration >= 0.25; const exception = credit ? "Vendor credit" : overdue ? "Past due" : concentrated ? "High concentration" : "No exception"; const nextAction = contract.previewOnly ? contract.nextAction : credit ? "Apply vendor credit" : overdue ? "Resolve overdue bill" : contract.nextAction; return { key: String(row._rid ?? `${entity}-${document}-${index}`), entity, document, amount, overdueAmount, dueDate: due.date, aging, owner: textValue(row[contract.ownerField]), status: textValue(row[contract.statusField]), promise, concentration, concentrationAvailable, exception, priority: amount == null ? "Amount unavailable" : `${overdue ? "Overdue" : "Open"} · ${money(Math.abs(amount))}`, nextAction, source: row, }; }); const actionable = items.filter(item => item.amount == null || Math.abs(item.amount) >= 0.005); actionable.sort((left, right) => { const leftOverdue = left.aging !== "Current" && left.aging !== "Unavailable"; const rightOverdue = right.aging !== "Current" && right.aging !== "Unavailable"; if (leftOverdue !== rightOverdue) return leftOverdue ? -1 : 1; if (left.amount == null) return right.amount == null ? left.document.localeCompare(right.document) : 1; if (right.amount == null) return -1; return Math.abs(right.amount) - Math.abs(left.amount) || left.document.localeCompare(right.document); }); return actionable.slice(0, contract.displayLimit); } function appendScope(url: string, businessUnit?: string, dateFrom?: string, dateTo?: string) { const target = new URL(url, window.location.origin); if (businessUnit) target.searchParams.set("bu", businessUnit); if (dateFrom) target.searchParams.set("date_from", dateFrom); if (dateTo) target.searchParams.set("date_to", dateTo); return `${target.pathname}${target.search}`; } async function responseMessage(response: Response) { try { const body = await response.json() as { detail?: { error?: { message?: string } } }; return body.detail?.error?.message || "Finance is temporarily unavailable."; } catch { return "Finance is temporarily unavailable."; } } function FactCard({ fact, onDrill, onReconcile }: { fact: FinanceFact; onDrill: (fact: FinanceFact) => void; onReconcile: (fact: FinanceFact) => void; }) { return ( <article className="finance-kpi"> <div className="finance-kpi-topline"> <h2>{fact.label}</h2> <span className={`finance-state finance-state--${fact.state}`}>{stateLabel(fact.state)}</span> </div> <strong className="finance-kpi-value">{displayValue(fact)}</strong> {fact.message ? <p className="finance-kpi-message">{fact.message}</p> : null} <dl className="finance-proof"> <div><dt>As of</dt><dd>{fact.freshness.asOf || stateLabel(fact.freshness.state)}</dd></div> <div><dt>Lineage</dt><dd>{fact.lineage.sourceEntities.join(", ")}</dd></div> <div><dt>Reconciliation</dt><dd>{stateLabel(fact.reconciliation.state)}</dd></div> </dl> <div className="finance-kpi-actions"> <button type="button" onClick={() => onDrill(fact)}>Source records</button> <button type="button" className="finance-secondary" onClick={() => onReconcile(fact)}> Check reconciliation </button> </div> </article> ); } function SourceFact({ fact, onDrill, onReconcile }: { fact: FinanceFact; onDrill: (fact: FinanceFact) => void; onReconcile: (fact: FinanceFact) => void; }) { return ( <li className="finance-source-fact"> <div> <strong>{fact.label}</strong> <span>{fact.requiredGrain === "product_code" && fact.state === "requires_sku" ? "Available at SKU grain" : stateLabel(fact.state)}</span> </div> <span className="finance-source-lineage">{fact.lineage.sourceEntities.join(", ")}</span> <div className="finance-source-actions"> <button type="button" onClick={() => onDrill(fact)}>Source records</button> <button type="button" className="finance-secondary" onClick={() => onReconcile(fact)}>Check reconciliation</button> </div> </li> ); } function DashboardUnavailableValue({ label, reason }: { label: string; reason: string }) { return ( <div> <strong>{label ? `${label}: Unavailable` : "Unavailable"}</strong> <span>{reason}</span> </div> ); } function DashboardMetricSection({ section, facts, onDrill }: { section: DashboardSection; facts: FinanceFact[]; onDrill: (fact: FinanceFact) => void; }) { const metrics = section.metrics || []; const factByKey = new Map(facts.map(fact => [fact.key, fact])); return ( <section className="finance-source-section" aria-label={section.title}> <header><h2>{section.title}</h2><p>{section.basisLabel}</p></header> <ul>{metrics.map(metric => ( <li className="finance-source-fact" key={metric.key}> <DashboardUnavailableValue label={metric.label} reason={metric.missingSource} /> <span className="finance-source-lineage">{metric.basisLabel}</span> <div> <strong>{metric.drillDimension ? `Required drill: ${stateLabel(metric.drillDimension)}` : "Validation seam"}</strong> <span>{metric.validationMethod}</span> {metric.sourceFact && factByKey.get(metric.sourceFact) ? ( <button type="button" className="finance-secondary" onClick={() => { const fact = metric.sourceFact ? factByKey.get(metric.sourceFact) : undefined; if (fact) onDrill(fact); }} >Source line records</button> ) : null} </div> </li> ))}</ul> </section> ); } function DashboardComparisonSection({ section, facts, onDrill }: { section: DashboardSection; facts: FinanceFact[]; onDrill: (fact: FinanceFact) => void; }) { const factByKey = new Map(facts.map(fact => [fact.key, fact])); const cell = (value: DashboardFactCell | DashboardUnavailable) => { if (value.state === "unavailable") { return <DashboardUnavailableValue label="" reason={value.missingSource} />; } const fact = factByKey.get(value.factKey); if (!fact) return <DashboardUnavailableValue label="" reason="The governed fact is not part of this application." />; return ( <div> <strong>{displayValue(fact)}</strong> <span>{fact.freshness.asOf ? `As of ${fact.freshness.asOf}` : stateLabel(fact.state)}</span> <button type="button" className="finance-secondary" onClick={() => onDrill(fact)}>Source records</button> </div> ); }; return ( <section className="finance-source-section" aria-label={section.title}> <header><h2>{section.title}</h2><p>{section.notice}</p></header> <div className="finance-table-wrap"> <table className="finance-table"> <thead><tr><th>Measure</th><th>Actual</th><th>Budget</th><th>Prior</th><th>Basis</th></tr></thead> <tbody>{(section.rows || []).map(row => ( <tr key={row.key}> <td>{row.label}</td> <td>{cell(row.actual)}</td> <td>{cell(row.budget)}</td> <td>{cell(row.prior)}</td> <td><strong>{row.basisLabel}</strong><br /><span>{row.validationMethod}</span></td> </tr> ))}</tbody> </table> </div> </section> ); } function DashboardPlanningSection({ section, facts, onDrill }: { section: DashboardSection; facts: FinanceFact[]; onDrill: (fact: FinanceFact) => void; }) { const factByKey = new Map(facts.map(fact => [fact.key, fact])); const actualCell = (value: DashboardFactCell) => { const fact = factByKey.get(value.factKey); if (!fact) return <DashboardUnavailableValue label="" reason="The governed fact is not part of this application." />; return ( <div> <strong>{displayValue(fact)}</strong> <span>{fact.freshness.asOf ? `As of ${fact.freshness.asOf}` : stateLabel(fact.state)}</span> <button type="button" className="finance-secondary" onClick={() => onDrill(fact)}>Source records</button> </div> ); }; return ( <section className="finance-source-section" aria-label={section.title}> <header><h2>{section.title}</h2><p>{section.basisLabel}</p></header> <div className="finance-table-wrap"> <table className="finance-table"> <thead><tr><th>Measure</th><th>Actual</th><th>Plan</th><th>Variance</th><th>Driver</th><th>Basis</th></tr></thead> <tbody>{(section.planningRows || []).map(row => ( <tr key={row.key}> <td>{row.label}</td> <td>{actualCell(row.actual)}</td> <td><DashboardUnavailableValue label="" reason={row.plan.missingSource} /></td> <td><DashboardUnavailableValue label="" reason={row.variance.missingSource} /></td> <td><DashboardUnavailableValue label="" reason={row.driver.missingSource} /></td> <td><strong>{row.basisLabel}</strong><br /><span>{row.validationMethod}</span></td> </tr> ))}</tbody> </table> </div> </section> ); } function DashboardSections({ contract, facts, onDrill }: { contract: DashboardContract; facts: FinanceFact[]; onDrill: (fact: FinanceFact) => void; }) { return ( <> <section className="finance-source-section" aria-label="Analysis basis"> <header><h2>Analysis basis</h2><p>{contract.basisNotice}</p></header> </section> {contract.sections.map(section => section.kind === "comparison" ? <DashboardComparisonSection key={section.key} section={section} facts={facts} onDrill={onDrill} /> : section.kind === "planning" ? <DashboardPlanningSection key={section.key} section={section} facts={facts} onDrill={onDrill} /> : <DashboardMetricSection key={section.key} section={section} facts={facts} onDrill={onDrill} />)} </> ); } function UnavailableWorkSignals({ contract }: { contract: RequirementsWorklistContract }) { return ( <> <p>{contract.basisNotice}</p> <p className="finance-row-count">Unavailable requirements</p> <ul>{contract.signals.map(signal => ( <li className="finance-source-fact" key={signal.key}> <div><strong>{signal.label}</strong><span>{stateLabel(signal.state)}</span></div> <span className="finance-source-lineage">{signal.missingSource}</span> <dl className="finance-proof"> <div><dt>Owner</dt><dd>{signal.ownerRole}</dd></div> <div><dt>Status</dt><dd>{stateLabel(signal.status)}</dd></div> <div><dt>Next action</dt><dd>{signal.nextAction}</dd></div> <div><dt>Scope</dt><dd>{stateLabel(signal.scope)}</dd></div> <div><dt>Basis</dt><dd>{signal.basisLabel}</dd></div> <div><dt>Source seam</dt><dd>{signal.sourceModule}</dd></div> <div><dt>Validation</dt><dd>{signal.validationMethod}</dd></div> </dl> </li> ))}</ul> </> ); } function WorklistSection({ contract, state, onSelect }: { contract: WorklistContract; state: WorklistState; onSelect: (item: WorkItem) => void; }) { const items = useMemo( () => isMirrorWorklist(contract) && state.kind === "ready" ? workItems(contract, state.payload, state.complete) : [], [contract, state], ); const population = state.kind === "ready" ? state.payload.total_count : null; return ( <section className="finance-source-section" aria-label={contract.title}> <header> <h2>{contract.title}</h2> <p>{contract.cadence}</p> </header> {!isMirrorWorklist(contract) ? <UnavailableWorkSignals contract={contract} /> : null} {isMirrorWorklist(contract) && state.kind === "loading" ? <div className="finance-table-skeleton" aria-label="Loading worklist" /> : null} {isMirrorWorklist(contract) && state.kind === "error" ? <p role="alert" className="finance-error">{state.message}</p> : null} {isMirrorWorklist(contract) && state.kind === "ready" && state.payload.state === "warming" ? <p>The tenant mirror is warming.</p> : null} {isMirrorWorklist(contract) && state.kind === "ready" && state.payload.state !== "warming" ? ( <> <p className="finance-row-count"> {population == null ? "Record count unavailable" : `${population.toLocaleString()} source records`} {!state.complete ? contract.concentration ? ". Ranking uses the loaded mirror window; concentration is unavailable." : ". Priority reflects only the loaded mirror window." : ""} </p> {items.length ? ( <div className="finance-table-wrap"> <table className="finance-table"> <thead><tr> <th>{contract.concentration ? "Vendor" : "Customer"}</th> <th>Document</th> <th>Aging / due</th> <th>Outstanding</th> <th>Owner</th> <th>Status</th> <th>{contract.concentration ? "Concentration" : "Promise"}</th> <th>Exception</th> <th>Priority</th> <th>Next action</th> </tr></thead> <tbody>{items.map(item => ( <tr key={item.key}> <td>{item.entity}</td> <td>{item.document}</td> <td>{item.aging} · {item.dueDate}</td> <td>{money(item.amount)}</td> <td>{item.owner}</td> <td>{stateLabel(item.status)}</td> <td>{contract.concentration ? item.concentrationAvailable && item.concentration != null ? `${(item.concentration * 100).toFixed(1)}%` : "Unavailable" : item.promise}</td> <td>{item.exception}</td> <td>{item.priority}</td> <td><button type="button" onClick={() => onSelect(item)}>{item.nextAction}</button></td> </tr> ))}</tbody> </table> </div> ) : <p>No open work matches this scope.</p>} </> ) : null} </section> ); } function WorkItemDrawer({ application, contract, item, onSource, onClose }: { application: FinanceApplication; contract: MirrorWorklistContract; item: WorkItem; onSource: () => void; onClose: () => void; }) { useEscapeClose(true, onClose); const previewSubject = `Account follow-up for ${item.document}`; const previewBody = `${item.entity}: please review ${item.document}, which currently shows ${money(item.amount)} outstanding. Confirm the source record before any follow-up.`; return ( <aside className="finance-drawer" role="dialog" aria-modal="true" aria-label={`${application.label} work item`}> <header> <div><span>{contract.previewOnly ? "Outreach preview" : "Payable review"}</span><h2>{item.entity}</h2></div> <button type="button" className="finance-secondary" onClick={onClose}>Close</button> </header> <div className="finance-drawer-body"> <dl className="finance-proof"> <div><dt>Document</dt><dd>{item.document}</dd></div> <div><dt>Outstanding</dt><dd>{money(item.amount)}</dd></div> <div><dt>Aging</dt><dd>{item.aging}</dd></div> <div><dt>Due date</dt><dd>{item.dueDate}</dd></div> <div><dt>Owner</dt><dd>{item.owner}</dd></div> <div><dt>Status</dt><dd>{stateLabel(item.status)}</dd></div> <div><dt>Exception</dt><dd>{item.exception}</dd></div> </dl> {contract.previewOnly ? ( <section> <h2>Outreach preview</h2> <p>Preview only. Nothing is sent from this application.</p> <dl className="finance-proof"> <div><dt>Recipient</dt><dd>Unavailable</dd></div> <div><dt>Subject</dt><dd>{previewSubject}</dd></div> <div><dt>Message</dt><dd>{previewBody}</dd></div> <div><dt>Promise</dt><dd>{item.promise}</dd></div> </dl> </section> ) : ( <section> <h2>Next action</h2> <p>{item.nextAction}. Confirm the source document before scheduling or recording payment.</p> </section> )} <div className="finance-kpi-actions"> <button type="button" className="finance-secondary" onClick={onSource}>Source records</button> </div> </div> </aside> ); } function DrillDrawer({ fact, payload, busy, error, onClose }: { fact: FinanceFact; payload: DrillPayload | null; busy: boolean; error: string; onClose: () => void; }) { useEscapeClose(true, onClose); const rows = payload?.rows || []; const columns = useMemo(() => { if (!rows.length) return []; const available = Object.keys(rows[0]); const preferred = fact.key === "revenue" ? ["date", "order", "order_partner", "category", "product_code", "revenue", "margin", "team"] : ["date", "move", "partner", "vendor", fact.lineage.metric]; return [...preferred, ...available].filter((column, index, all) => available.includes(column) && all.indexOf(column) === index).slice(0, 8); }, [fact.key, fact.lineage.metric, rows]); return ( <aside className="finance-drawer" role="dialog" aria-modal="true" aria-label={`${fact.label} source records`}> <header> <div><span>Source records</span><h2>{fact.label}</h2></div> <button type="button" className="finance-secondary" onClick={onClose}>Close</button> </header> <div className="finance-drawer-body"> {busy ? <div className="finance-table-skeleton" aria-label="Loading source records" /> : null} {error ? <p role="alert" className="finance-error">{error}</p> : null} {!busy && !error && payload?.state === "warming" ? <p>The tenant mirror is warming.</p> : null} {!busy && !error && payload && payload.state !== "warming" ? ( <> <p className="finance-row-count"> {payload.row_count == null ? "Count unavailable" : `${payload.row_count.toLocaleString()} matching records`} </p> {rows.length ? ( <div className="finance-table-wrap"> <table><thead><tr>{columns.map(column => <th key={column}>{stateLabel(column)}</th>)}</tr></thead> <tbody>{rows.map((row, index) => <tr key={String(row._rid ?? index)}>{columns.map(column => <td key={column}>{String(row[column] ?? "Not available")}</td>)}</tr>)}</tbody> </table> </div> ) : <p>No source records match this scope.</p>} </> ) : null} </div> </aside> ); } type FinanceWorkspaceProps = { appKey?: string; apiBase?: string; businessUnit?: string; dateFrom?: string; dateTo?: string; }; // S65-T18: Collection is its own surface now; every other Finance app keeps this workspace. // The branch is its own component so no hook below it is ever skipped by an early return. export default function FinanceWorkspace(props: FinanceWorkspaceProps) { return <FinanceApplication {...props} />; } function FinanceApplication({ appKey, apiBase = "/api/v1", businessUnit, dateFrom, dateTo, }: FinanceWorkspaceProps) { const resolvedKey = appKey || pathApplicationKey(); const [page, setPage] = useState<PageState>({ kind: "loading" }); const [drillFact, setDrillFact] = useState<FinanceFact | null>(null); const [drill, setDrill] = useState<DrillPayload | null>(null); const [drillBusy, setDrillBusy] = useState(false); const [drillError, setDrillError] = useState(""); const [worklist, setWorklist] = useState<WorklistState>({ kind: "idle" }); const [workItem, setWorkItem] = useState<WorkItem | null>(null); const workspaceRef = useRef<HTMLElement>(null); const { fullscreen, toggleFullscreen } = useAppFullscreen(workspaceRef); const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen"; useEffect(() => { if (!resolvedKey) { setPage({ kind: "missing" }); return; } const controller = new AbortController(); setPage({ kind: "loading" }); const url = appendScope(`${apiBase}/finance/applications/${encodeURIComponent(resolvedKey)}`, businessUnit, dateFrom, dateTo); void fetch(url, { credentials: CREDENTIALS, signal: controller.signal }).then(async response => { if (response.status === 403) { setPage({ kind: "restricted" }); return; } if (response.status === 404) { setPage({ kind: "missing" }); return; } if (!response.ok) throw new Error(await responseMessage(response)); setPage({ kind: "ready", data: await response.json() as ApplicationPayload }); }).catch((error: unknown) => { if (!controller.signal.aborted) setPage({ kind: "error", message: error instanceof Error ? error.message : "Finance is temporarily unavailable." }); }); return () => controller.abort(); }, [apiBase, businessUnit, dateFrom, dateTo, resolvedKey]); const activeContract = page.kind === "ready" ? page.data.application.worklist : undefined; const activeMirrorContract = activeContract && isMirrorWorklist(activeContract) ? activeContract : undefined; const activeSourceFact = activeMirrorContract?.sourceFact || ""; useEffect(() => { if (page.kind !== "ready" || !activeMirrorContract) { setWorklist({ kind: "idle" }); setWorkItem(null); return; } const fact = page.data.facts.find(item => item.key === activeMirrorContract.sourceFact); if (!fact) { setWorklist({ kind: "error", message: "The governed worklist source is unavailable." }); return; } if (fact.state === "restricted") { setWorklist({ kind: "error", message: "This consolidated worklist is restricted for the selected Business Unit." }); return; } if (fact.state !== "ready") { setWorklist({ kind: "error", message: fact.message || `The governed worklist source is ${stateLabel(fact.state)}.`, }); return; } const controller = new AbortController(); setWorklist({ kind: "loading" }); setWorkItem(null); const fetchPage = async (offset: number) => { const scoped = appendScope(fact.drillThrough.href, businessUnit, dateFrom, dateTo); const target = new URL(scoped, window.location.origin); target.searchParams.set("limit", String(activeMirrorContract.pageSize)); target.searchParams.set("offset", String(offset)); const response = await fetch(`${target.pathname}${target.search}`, { credentials: CREDENTIALS, signal: controller.signal, }); if (!response.ok) throw new Error(await responseMessage(response)); return await response.json() as WorklistPayload; }; void (async () => { try { const first = await fetchPage(0); if (first.state === "warming") { setWorklist({ kind: "ready", payload: first, complete: false }); return; } const population = first.total_count ?? first.row_count; if (population == null || population > activeMirrorContract.maxRows) { setWorklist({ kind: "ready", payload: first, complete: false }); return; } const offsets: number[] = []; for (let offset = activeMirrorContract.pageSize; offset < population; offset += activeMirrorContract.pageSize) { offsets.push(offset); } const rest = await Promise.all(offsets.map(fetchPage)); const rows = [...(first.rows || []), ...rest.flatMap(payload => payload.rows || [])]; setWorklist({ kind: "ready", payload: { ...first, rows }, complete: rows.length >= population, }); } catch (error) { if (!controller.signal.aborted) { setWorklist({ kind: "error", message: error instanceof Error ? error.message : "The worklist is temporarily unavailable.", }); } } })(); return () => controller.abort(); }, [activeSourceFact, businessUnit, dateFrom, dateTo, resolvedKey]); async function openDrill(fact: FinanceFact) { setDrillFact(fact); setDrill(null); setDrillError(""); setDrillBusy(true); try { const response = await fetch(appendScope(fact.drillThrough.href, businessUnit, dateFrom, dateTo), { credentials: CREDENTIALS }); if (!response.ok) throw new Error(await responseMessage(response)); setDrill(await response.json() as DrillPayload); } catch (error) { setDrillError(error instanceof Error ? error.message : "Source records are temporarily unavailable."); } finally { setDrillBusy(false); } } async function checkReconciliation(fact: FinanceFact) { try { const response = await fetch(appendScope(fact.reconciliation.href, businessUnit, dateFrom, dateTo), { credentials: CREDENTIALS }); if (!response.ok) throw new Error(await responseMessage(response)); const result = await response.json() as { state?: string }; setPage(current => current.kind !== "ready" ? current : { kind: "ready", data: { ...current.data, facts: current.data.facts.map(item => item.key === fact.key ? { ...item, reconciliation: { ...item.reconciliation, state: result.state || "unavailable" } } : item), kpis: current.data.kpis.map(item => item.key === fact.key ? { ...item, reconciliation: { ...item.reconciliation, state: result.state || "unavailable" } } : item), }, }); } catch { setPage(current => current.kind !== "ready" ? current : { kind: "ready", data: { ...current.data, facts: current.data.facts.map(item => item.key === fact.key ? { ...item, reconciliation: { ...item.reconciliation, state: "unavailable" } } : item), kpis: current.data.kpis.map(item => item.key === fact.key ? { ...item, reconciliation: { ...item.reconciliation, state: "unavailable" } } : item), }, }); } } if (page.kind === "loading") return <main className="finance-workspace"><div className="finance-page-skeleton" aria-label="Loading Finance application" /></main>; if (page.kind === "restricted") return <main className="finance-workspace finance-centered"><h1>Access restricted</h1><p>Your account does not have access to this Finance application.</p></main>; if (page.kind === "missing") return <main className="finance-workspace finance-centered"><h1>Application not found</h1><p>Open a Finance application from the navigation rail.</p></main>; if (page.kind === "error") return <main className="finance-workspace finance-centered"><h1>Finance unavailable</h1><p>{page.message}</p></main>; const { application, facts, kpis } = page.data; const supportingFacts = facts.filter(fact => !application.kpiKeys.includes(fact.key)); const worklistFact = application.worklist ? facts.find(fact => fact.key === application.worklist?.sourceFact) : undefined; return ( <main ref={workspaceRef} className="finance-workspace" data-finance-app={application.key} data-app-fullscreen={fullscreen ? "" : undefined} > <header className="finance-header"> <div><span className="finance-mode">{application.mode}</span><h1>{application.label}</h1><p>{application.question}</p></div> <div className="finance-header-actions"> <span className={`finance-state finance-state--${page.data.state}`}>{stateLabel(page.data.state)}</span> <button type="button" className={"finance-secondary finance-fullscreen-toggle" + (fullscreen ? " is-active" : "")} aria-pressed={fullscreen} aria-label={fullscreenLabel} title={fullscreenLabel} onClick={toggleFullscreen} > {fullscreenLabel} </button> </div> </header> {kpis.length ? <section className="finance-kpi-grid" aria-label="Finance key performance indicators"> {kpis.map(fact => <FactCard key={fact.key} fact={fact} onDrill={openDrill} onReconcile={checkReconciliation} />)} </section> : null} {application.worklist ? ( <WorklistSection contract={application.worklist} state={worklist} onSelect={setWorkItem} /> ) : null} {application.dashboard ? ( <DashboardSections contract={application.dashboard} facts={facts} onDrill={openDrill} /> ) : null} {supportingFacts.length ? <section className="finance-source-section"><header><h2>Source facts</h2><p>Validated records at their honest reporting grain.</p></header> <ul>{supportingFacts.map(fact => <SourceFact key={fact.key} fact={fact} onDrill={openDrill} onReconcile={checkReconciliation} />)}</ul> </section> : null} {workItem && activeMirrorContract ? ( <WorkItemDrawer application={application} contract={activeMirrorContract} item={workItem} onClose={() => setWorkItem(null)} onSource={() => { setWorkItem(null); if (worklistFact) void openDrill(worklistFact); }} /> ) : null} {drillFact ? <DrillDrawer fact={drillFact} payload={drill} busy={drillBusy} error={drillError} onClose={() => setDrillFact(null)} /> : null} </main> ); }
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useEscapeClose } from "../ui/useEscapeClose";
import "./finance.css";
import "../styles/sdlc72/app-fullscreen.css";
type FactState = "ready" | "warming" | "missing" | "unavailable" | "restricted" | "requires_sku";
type FinanceFact = {
key: string;
label: string;
format: "usd" | "int" | "pct";
scope: "business_unit" | "hq_consolidated" | "all_channel_inventory";
state: FactState;
value: number | null;
message?: string;
requiredGrain?: string;
freshness: { state: string; asOf?: string | null };
lineage: { topic: string; metric: string; sourceEntities: string[] };
drillThrough: { kind: "source_records"; href: string };
reconciliation: { state: string; method: string; href: string };
};
type MirrorWorklistContract = {
title: string;
cadence: string;
kind?: undefined;
sourceFact: string;
pageSize: number;
maxRows: number;
displayLimit: number;
entityField: string;
documentField: string;
amountField: string;
// C10: agingLabel prints "Overdue" from this field, so it binds the Odoo-matching `ar_overdue`, never the grace number.
overdueAmountField?: string;
dueDateField: string;
ownerField: string;
statusField: string;
promiseDateField?: string;
promiseAmountField?: string;
nextAction: string;
previewOnly: boolean;
concentration?: boolean;
};
type UnavailableWorkSignal = {
key: string;
label: string;
state: "unavailable";
scope: FinanceFact["scope"];
basisLabel: string;
missingSource: string;
sourceModule: string;
validationMethod: string;
ownerRole: string;
status: "unavailable";
nextAction: string;
};
type RequirementsWorklistContract = {
kind: "unavailable_requirements";
title: string;
cadence: string;
basisNotice: string;
signals: UnavailableWorkSignal[];
sourceFact?: undefined;
};
type WorklistContract = MirrorWorklistContract | RequirementsWorklistContract;
type DashboardUnavailable = {
state: "unavailable";
missingSource: string;
};
type DashboardFactCell = {
state: "fact";
factKey: string;
};
type DashboardMetric = {
key: string;
label: string;
format: "usd" | "int" | "pct" | "days";
state: "unavailable";
scope: FinanceFact["scope"];
basisLabel: string;
missingSource: string;
validationMethod: string;
drillDimension?: string;
sourceFact?: string;
};
type DashboardComparisonRow = {
key: string;
label: string;
basisLabel: string;
actual: DashboardFactCell | DashboardUnavailable;
budget: DashboardFactCell | DashboardUnavailable;
prior: DashboardFactCell | DashboardUnavailable;