Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 41,730 Bytes
816fa8a 2e7e617 816fa8a 2e7e617 07a68d0 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 816fa8a 2e7e617 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 | 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>
);
}
|