Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 13,440 Bytes
f462120 8729c1d f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 8133df9 f462120 | 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 | import { useEffect, useState } from "react";
import type { ReactNode } from "react";
import { LogoLoader } from "../ui/LogoLoader";
import { DashboardPeriodPicker } from "../customer-grid/seam";
import { API_V1, CREDENTIALS, checkTenant, currentTenant, UNAUTHORIZED_EVENT, signal } from "../apiContract";
import { fetchWithDeadline } from "../net/deadline";
import { Kpi, KpiStrip, TrendChart, validSeries, finite, formatMeasure } from "../viz/kit";
import type { TrendChartProps, ChartKind, KpiProps, ChartPoint, ChartSeries } from "../viz/kit";
import "../styles/sdlc81/dashboard-kit.css";
export interface DashboardFigure {
id: string; label: string; value: number | string | null; unit: string;
series: TrendChartProps["series"]; source_table: string; validated: boolean; reason: string | null;
change?: KpiProps["change"]; noPrior?: boolean;
comparisonStatus?: "available" | "partial_data" | "unavailable" | "no_prior_data";
/** Set by the server's per-kind headline list: the figure draws in the first row. */
headline?: boolean;
}
export interface DashboardPeriod { start: string; end: string }
/** Supplied figures select controlled mode. The default kind/appId mode owns one bounded GET. */
export interface AppDashboardProps<F extends DashboardFigure = DashboardFigure> {
application?: { id: string; templateKind?: string };
appKind?: string; kind?: string; appId?: string;
width?: number;
figures?: F[];
notShown?: FoldedFigure[];
start?: string; end?: string; period?: DashboardPeriod;
onPeriodChange?: (period: DashboardPeriod) => void;
loading?: boolean; error?: string | null; onRetry?: () => void;
charts?: { id: string; kind: ChartKind }[];
/** Opt-in: a figure id named here draws as a tile with its trend line instead of a chart. */
tileTrends?: string[];
onFigureClick?: (figure: F) => void;
formatValue?: (figure: F) => string;
formatChange?: (figure: F) => string;
children?: ReactNode;
compare?: "prior" | "yoy";
}
export function initialPeriod(): DashboardPeriod {
const stop = new Date(), begin = new Date(stop);
begin.setUTCDate(begin.getUTCDate() - 29);
return { start: begin.toISOString().slice(0, 10), end: stop.toISOString().slice(0, 10) };
}
export function usableFigure(figure: DashboardFigure): boolean {
return figure.validated === true && formatMeasure(figure.value, figure.unit) !== "Unavailable"
&& validSeries(figure.series) && (!figure.change || [figure.change.previous, figure.change.absolute, figure.change.percent]
.every(value => value == null || finite(value)));
}
/** A refused Dashboard names the missing access in the server's plain line. */
function refusalLine(body: unknown): string {
const message = (body as { detail?: { error?: { message?: unknown } } } | null)?.detail?.error?.message;
return typeof message === "string" && message.trim() ? message.trim() : "Dashboard access needed";
}
/** One number per period for a tile trend: flat points or a single series, else none. */
function tileTrend(series: DashboardFigure["series"]): (number | null)[] | undefined {
const points = series.length && "points" in series[0] ? series.length === 1 ? (series as ChartSeries[])[0].points : null
: series as ChartPoint[];
return points?.map(p => ("y" in p ? p.y : p.value) ?? null);
}
/** A figure the Dashboard does not draw, named with the reason it is missing. */
export interface FoldedFigure { id?: string; label: string; reason?: string | null }
/** One line, "N figures not shown", that opens each folded figure's label and reason. */
export function FiguresNotShown({ figures }: { figures: FoldedFigure[] }) {
const seen = new Set<string>();
const folded = figures.filter(figure => {
if (!figure.id) return true;
if (seen.has(figure.id)) return false;
seen.add(figure.id);
return true;
});
if (!folded.length) return null;
return <details className="lp-figure-fold" data-proof="figure-fold">
<summary>{folded.length} figures not shown</summary>
<ul>{folded.map((figure, index) => <li key={figure.id ?? index} data-folded={figure.id}>
<span className="lp-figure-fold-label">{figure.label}</span>{": "}
<span className="lp-figure-fold-reason">{figure.reason || "No checked value for this period"}</span>
</li>)}</ul>
</details>;
}
/** Only an explicit comparison series identity supersedes the caller's missing-comparison state. */
function chartComparison(figure: DashboardFigure, formattedChange?: string) {
const hasPriorSeries = figure.series.some(part => "points" in part && (part.key ?? part.id) === "comparison"
&& part.points.some(point => finite("y" in point ? point.y : point.value)));
const percent = finite(figure.change?.percent);
if (figure.comparisonStatus && formattedChange?.trim() && formattedChange.trim() !== "No comparison data")
return { change: { ...figure.change, reason: percent ? figure.change?.reason : formattedChange }, noPrior: figure.noPrior };
if (!figure.change && !figure.noPrior) return undefined;
if (hasPriorSeries && (!percent || figure.noPrior)) return undefined;
return { change: figure.change, noPrior: figure.noPrior };
}
export function AppDashboard<F extends DashboardFigure = DashboardFigure>(props: AppDashboardProps<F>) {
const controlled = props.figures !== undefined;
const kind = props.kind ?? props.appKind ?? props.application?.templateKind ?? "";
const id = props.appId ?? props.application?.id ?? "";
const tenant = currentTenant();
const [localPeriod, setLocalPeriod] = useState(initialPeriod);
const period = props.period ?? { start: props.start ?? localPeriod.start, end: props.end ?? localPeriod.end };
const [attempt, setAttempt] = useState(0);
const key = JSON.stringify([tenant, id, kind, period.start, period.end, props.compare ?? "prior", attempt]);
const [load, setLoad] = useState<{ key: string; figures: DashboardFigure[]; error: string; busy: boolean } | null>(null);
useEffect(() => {
if (controlled) return;
if (!id || !kind) { setLoad({ key, figures: [], error: "Open a saved App to see its dashboard", busy: false }); return; }
const controller = new AbortController();
let active = true;
const settle = (figures: DashboardFigure[], error: string) => {
if (active && !controller.signal.aborted) setLoad({ key, figures, error, busy: false });
};
const scopeChanged = () => { active = false; controller.abort(); setLoad(null); };
window.addEventListener("aios:tenant-changed", scopeChanged);
window.addEventListener("aios:signed-out", scopeChanged);
window.addEventListener(UNAUTHORIZED_EVENT, scopeChanged);
setLoad({ key, figures: [], error: "", busy: true });
const query = new URLSearchParams({ app: id, start: period.start, end: period.end, compare: props.compare ?? "prior" });
void fetchWithDeadline(`${API_V1}/app-kinds/${encodeURIComponent(kind)}/dashboard?${query}`,
{ method: "GET", credentials: CREDENTIALS, cache: "no-store", signal: controller.signal },
response => active && !controller.signal.aborted && currentTenant() === tenant && (response.ok || response.status === 403)
? response.json().catch(() => null) as Promise<unknown> : Promise.resolve(null), 25000).then(({ res: response, body }) => {
if (!active || controller.signal.aborted || currentTenant() !== tenant) return;
if (checkTenant(response)) { settle([], "Dashboard access needed"); return; }
if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
if (!response.ok) { settle([], response.status === 403 ? refusalLine(body)
: response.status === 404 ? "Dashboard access needed" : "Dashboard could not be loaded"); return; }
const data = body as { kind?: string; start?: string; end?: string; compare?: string; figures?: unknown[] };
if (!data || data.kind !== kind || data.start !== period.start || data.end !== period.end
|| data.compare !== (props.compare ?? "prior") || !Array.isArray(data.figures)) throw Error("Unavailable");
const figures = data.figures.filter((raw): raw is DashboardFigure => !!raw && typeof raw === "object"
&& ["id", "label", "unit", "source_table"].every(k => typeof (raw as Record<string, unknown>)[k] === "string"));
settle(figures, "");
}).catch(() => settle([], "Dashboard could not be loaded"));
return () => {
active = false; controller.abort();
window.removeEventListener("aios:tenant-changed", scopeChanged);
window.removeEventListener("aios:signed-out", scopeChanged);
window.removeEventListener(UNAUTHORIZED_EVENT, scopeChanged);
};
}, [controlled, key, tenant, kind, id, period.start, period.end, props.compare]);
const fresh = load?.key === key ? load : null;
const figures = controlled ? props.figures! : fresh?.figures ?? [];
const busy = props.loading ?? (!controlled && (!fresh || fresh.busy));
const error = props.error ?? (!controlled ? fresh?.error : "");
const trendIds = new Set(props.tileTrends ?? []);
const charts = (props.charts ?? figures.filter(f => Array.isArray(f.series) && f.series.length).map(f => ({ id: f.id,
kind: f.series.every(p => "label" in p && !("x" in p) && !("date" in p) && !("points" in p)) ? "bar" as const : "line" as const }))).filter(c => !trendIds.has(c.id));
// A tile draws only for a usable figure, a charted one too; every other figure folds into one line.
const tiles = figures.filter(usableFigure);
const folded = figures.filter(f => !usableFigure(f));
const rows = [tiles.filter(f => f.headline === true), tiles.filter(f => f.headline !== true)].filter(row => row.length);
const changePeriod = (next: DashboardPeriod) => { setLocalPeriod(next); props.onPeriodChange?.(next); };
const retry = () => { setAttempt(n => n + 1); props.onRetry?.(); };
// Read calendar parts directly so the reader's time zone cannot move a day.
const formatPeriod = ({ start, end }: DashboardPeriod) => {
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const parts = [start, end].map(value => /^(\d{4})-(\d{2})-(\d{2})$/.exec(value));
if (parts.some(part => !part || !months[Number(part[2]) - 1])) return undefined;
const withYear = start.slice(0, 4) !== end.slice(0, 4);
return parts.map(part => `${months[Number(part![2]) - 1]} ${Number(part![3])}${withYear ? `, ${part![1]}` : ""}`).join(" to ");
};
const periodText = !controlled || props.period || props.start || props.end ? formatPeriod(period) : undefined;
const comparisonLabel = props.compare === "yoy" ? "Year over year"
: props.compare === "prior" || !controlled ? "Previous period" : undefined;
return <section className="lp-dashboard" aria-label="Dashboard" data-proof="app-dashboard-kit" aria-busy={busy}
style={finite(props.width) && props.width > 0 ? { width: `min(100%, ${props.width}px)` } : undefined}>
{(props.onPeriodChange || !controlled) && <DashboardPeriodPicker period={period} onChange={changePeriod} />}
{busy ? <div className="lp-dashboard-loading"><LogoLoader /></div>
: error ? <p className="lp-figure-reason" role="alert">{error} <button type="button" className="cg-select" onClick={retry}>Retry</button></p>
: <>
{rows.map((row, index) => <div key={index} className="lp-kpi-row" data-row={row[0].headline === true ? "headline" : "rest"}
role="group" aria-label={row[0].headline === true ? "Headline figures" : "Key figures"}>
<KpiStrip>{row.map(figure =>
<div key={figure.id} data-figure={figure.id} data-validated="true" data-headline={figure.headline === true || undefined}>
<Kpi label={figure.label} value={figure.value} unit={figure.unit} validated
reason={figure.reason} change={figure.change} noPrior={figure.noPrior} period={periodText}
onClick={props.onFigureClick ? () => props.onFigureClick!(figure as F) : undefined}
formattedValue={props.formatValue?.(figure as F)}
formattedChange={props.formatChange?.(figure as F)}
trend={trendIds.has(figure.id) ? tileTrend(figure.series) : undefined} />
</div>)}</KpiStrip></div>)}
<FiguresNotShown figures={[...folded, ...(props.notShown ?? [])]} />
{charts.map(chart => {
const figure = tiles.find(f => f.id === chart.id);
if (!figure || !figure.series.length) return null;
const comparison = chartComparison(figure, props.formatChange?.(figure as F));
return <div className="lp-dashboard-chart" key={chart.id} data-figure={chart.id} data-validated="true">
<TrendChart label={figure.label} unit={figure.unit} series={figure.series} kind={chart.kind}
comparison={comparison && { ...comparison, formattedChange: props.formatChange?.(figure as F) }}
period={periodText} comparisonLabel={comparisonLabel} />
{figure.reason && <p className="lp-figure-reason" role="status">{figure.reason}</p>}
{props.onFigureClick && <button type="button" className="lp-chart-source" onClick={() => props.onFigureClick!(figure as F)}>Source rows</button>}
</div>;
})}
{!figures.length && !props.notShown?.length && <p className="lp-figure-reason" role="status">No figures for this period</p>}
{props.children}
</>}
</section>;
}
export default AppDashboard;
|