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[]; row_count?: number | null; total_count?: number | null; aggregates?: Record; }; 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; }; 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 `` 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(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(); 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 (

{fact.label}

{stateLabel(fact.state)}
{displayValue(fact)} {fact.message ?

{fact.message}

: null}
As of
{fact.freshness.asOf || stateLabel(fact.freshness.state)}
Lineage
{fact.lineage.sourceEntities.join(", ")}
Reconciliation
{stateLabel(fact.reconciliation.state)}
); } function SourceFact({ fact, onDrill, onReconcile }: { fact: FinanceFact; onDrill: (fact: FinanceFact) => void; onReconcile: (fact: FinanceFact) => void; }) { return (
  • {fact.label} {fact.requiredGrain === "product_code" && fact.state === "requires_sku" ? "Available at SKU grain" : stateLabel(fact.state)}
    {fact.lineage.sourceEntities.join(", ")}
  • ); } function DashboardUnavailableValue({ label, reason }: { label: string; reason: string }) { return (
    {label ? `${label}: Unavailable` : "Unavailable"} {reason}
    ); } 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.title}

    {section.basisLabel}

      {metrics.map(metric => (
    • {metric.basisLabel}
      {metric.drillDimension ? `Required drill: ${stateLabel(metric.drillDimension)}` : "Validation seam"} {metric.validationMethod} {metric.sourceFact && factByKey.get(metric.sourceFact) ? ( ) : null}
    • ))}
    ); } 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 ; } const fact = factByKey.get(value.factKey); if (!fact) return ; return (
    {displayValue(fact)} {fact.freshness.asOf ? `As of ${fact.freshness.asOf}` : stateLabel(fact.state)}
    ); }; return (

    {section.title}

    {section.notice}

    {(section.rows || []).map(row => ( ))}
    MeasureActualBudgetPriorBasis
    {row.label} {cell(row.actual)} {cell(row.budget)} {cell(row.prior)} {row.basisLabel}
    {row.validationMethod}
    ); } 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 ; return (
    {displayValue(fact)} {fact.freshness.asOf ? `As of ${fact.freshness.asOf}` : stateLabel(fact.state)}
    ); }; return (

    {section.title}

    {section.basisLabel}

    {(section.planningRows || []).map(row => ( ))}
    MeasureActualPlanVarianceDriverBasis
    {row.label} {actualCell(row.actual)} {row.basisLabel}
    {row.validationMethod}
    ); } function DashboardSections({ contract, facts, onDrill }: { contract: DashboardContract; facts: FinanceFact[]; onDrill: (fact: FinanceFact) => void; }) { return ( <>

    Analysis basis

    {contract.basisNotice}

    {contract.sections.map(section => section.kind === "comparison" ? : section.kind === "planning" ? : )} ); } function UnavailableWorkSignals({ contract }: { contract: RequirementsWorklistContract }) { return ( <>

    {contract.basisNotice}

    Unavailable requirements

      {contract.signals.map(signal => (
    • {signal.label}{stateLabel(signal.state)}
      {signal.missingSource}
      Owner
      {signal.ownerRole}
      Status
      {stateLabel(signal.status)}
      Next action
      {signal.nextAction}
      Scope
      {stateLabel(signal.scope)}
      Basis
      {signal.basisLabel}
      Source seam
      {signal.sourceModule}
      Validation
      {signal.validationMethod}
    • ))}
    ); } 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 (

    {contract.title}

    {contract.cadence}

    {!isMirrorWorklist(contract) ? : null} {isMirrorWorklist(contract) && state.kind === "loading" ?
    : null} {isMirrorWorklist(contract) && state.kind === "error" ?

    {state.message}

    : null} {isMirrorWorklist(contract) && state.kind === "ready" && state.payload.state === "warming" ?

    The tenant mirror is warming.

    : null} {isMirrorWorklist(contract) && state.kind === "ready" && state.payload.state !== "warming" ? ( <>

    {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." : ""}

    {items.length ? (
    {items.map(item => ( ))}
    {contract.concentration ? "Vendor" : "Customer"} Document Aging / due Outstanding Owner Status {contract.concentration ? "Concentration" : "Promise"} Exception Priority Next action
    {item.entity} {item.document} {item.aging} · {item.dueDate} {money(item.amount)} {item.owner} {stateLabel(item.status)} {contract.concentration ? item.concentrationAvailable && item.concentration != null ? `${(item.concentration * 100).toFixed(1)}%` : "Unavailable" : item.promise} {item.exception} {item.priority}
    ) :

    No open work matches this scope.

    } ) : null}
    ); } 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 ( ); } 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 ( ); } 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 ; } function FinanceApplication({ appKey, apiBase = "/api/v1", businessUnit, dateFrom, dateTo, }: FinanceWorkspaceProps) { const resolvedKey = appKey || pathApplicationKey(); const [page, setPage] = useState({ kind: "loading" }); const [drillFact, setDrillFact] = useState(null); const [drill, setDrill] = useState(null); const [drillBusy, setDrillBusy] = useState(false); const [drillError, setDrillError] = useState(""); const [worklist, setWorklist] = useState({ kind: "idle" }); const [workItem, setWorkItem] = useState(null); const workspaceRef = useRef(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
    ; if (page.kind === "restricted") return

    Access restricted

    Your account does not have access to this Finance application.

    ; if (page.kind === "missing") return

    Application not found

    Open a Finance application from the navigation rail.

    ; if (page.kind === "error") return

    Finance unavailable

    {page.message}

    ; 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 (
    {application.mode}

    {application.label}

    {application.question}

    {stateLabel(page.data.state)}
    {kpis.length ?
    {kpis.map(fact => )}
    : null} {application.worklist ? ( ) : null} {application.dashboard ? ( ) : null} {supportingFacts.length ?

    Source facts

    Validated records at their honest reporting grain.

      {supportingFacts.map(fact => )}
    : null} {workItem && activeMirrorContract ? ( setWorkItem(null)} onSource={() => { setWorkItem(null); if (worklistFact) void openDrill(worklistFact); }} /> ) : null} {drillFact ? setDrillFact(null)} /> : null}
    ); }