Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 2x 26x 2x 73x 2x 9x 2x 2x 8x 2x 45x 10x 10x 2x 1x 2x 9x 18x 2x 18x 63x 2x 9x 9x 9x 9x 9x 2x 20x 20x 20x 20x 20x 7x 20x 20x 1x 1x 1x 1x 1x 20x 20x 9x | import {
DailyCostBars,
describeCost,
formatCount,
formatUsd,
formatUsdCents,
} from "@/components/cost";
import {
CopyButton,
DetailPage,
MetaGrid,
MetaItem,
SectionCard,
} from "@/components/detail";
import type {
Statement,
StatementBudget,
StatementCharges,
StatementTable,
} from "@/objects/Statement";
import { RULE_LAYERS, ruleLayerMeta } from "@/apps/user/pages/rules/ruleLayer";
import { APP_ROUTES } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { parseServerDate } from "@/util/time";
import { useQuery } from "@tanstack/react-query";
import {
BarChart3,
Download,
FileSpreadsheet,
Gavel,
Printer,
Receipt,
ShieldCheck,
Wallet,
} from "lucide-react";
import moment from "moment";
import React, { useState } from "react";
import { useParams } from "react-router-dom";
/**
* One month's statement (Governance → Spend → Statements; cost-control plan
* A4.1): what the workspace spent and what governed it, as figures — the
* monthly organisation statement a design partner's success criteria are
* measured on. A closed month is the statement written when it ended, kept
* unchanged with its SHA-256; the month under way is a draft computed now.
* Downloadable as CSV, and laid out to print.
*/
/** A month key in the address — `2026-10` — or null. */
export const parseMonth = (raw: string | undefined): string | null =>
raw && /^\d{4}-(0[1-9]|1[0-2])$/.test(raw) ? raw : null;
const money = (value?: number | null, unpriced = 0) =>
describeCost({ cost_usd: value ?? null, unpriced }).text;
const day = (iso?: string | null) =>
iso ? moment(parseServerDate(iso)).format("D MMM YYYY") : "";
const OUTCOME_LABELS: Record<string, string> = {
blocked: "Blocked",
applied: "Changed something",
no_change: "Ran, nothing to do",
not_matched: "Stood aside",
};
/** What a statement counts rules in force by: their layer, or for one
* closed before layers (schema 2 and earlier, frozen as it was kept) their
* type — routing included, from before routing rules were removed. */
const RULES_IN_FORCE_LABELS: Record<string, string> = {
...Object.fromEntries(
RULE_LAYERS.map((layer) => [layer, ruleLayerMeta(layer).label]),
),
policy: "Policy",
routing: "Routing",
audit: "Audit",
};
const Breakdown: React.FC<{ table?: StatementTable | null }> = ({ table }) => {
if (!table) return null;
return (
<div className="break-inside-avoid">
<h3 className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-1.5">
{table.title}
</h3>
{table.rows.length === 0 ? (
<p className="text-xs text-gray-400 italic">Nothing spent.</p>
) : (
<table className="w-full text-xs" aria-label={table.title}>
<thead>
<tr className="text-left text-[10px] uppercase tracking-wide text-gray-400">
<th className="font-medium py-1">Name</th>
<th className="font-medium py-1 text-right">Spend</th>
<th className="font-medium py-1 text-right">Decisions</th>
</tr>
</thead>
<tbody>
{table.rows.map((row) => (
<tr
key={row.key}
className="border-t border-gray-100 dark:border-gray-700"
>
<td className="py-1 pr-3 truncate max-w-[16rem] text-gray-700 dark:text-gray-200">
{row.label}
{row.cost_centre && (
<span
className="ml-1.5 font-mono text-[10px] text-gray-400"
title="Cost centre"
>
{row.cost_centre}
</span>
)}
</td>
<td className="py-1 text-right tabular-nums">
{money(row.spend_usd, row.unpriced_calls)}
</td>
<td className="py-1 text-right tabular-nums text-gray-500">
{formatCount(row.decisions ?? 0)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
};
/** What the month comes to under the workspace's plan (svc-core
* `services/plans.py`): an estimate to invoice by hand, not an invoice. */
const ChargesCard: React.FC<{ charges: StatementCharges }> = ({ charges: c }) => (
<SectionCard
icon={Receipt}
title="Charges"
description={c.note ?? "An estimate to invoice by hand, not an invoice."}
>
<MetaGrid columns={4}>
<MetaItem label="Platform fee" value={formatUsdCents(c.fee_usd)} />
<MetaItem label="Model usage at cost" value={formatUsdCents(c.usage_usd)} />
<MetaItem label="Included in the fee" value={formatUsdCents(c.included_usd)} />
<MetaItem
label={`Usage past it, plus ${c.markup_percent}%`}
value={formatUsdCents(c.usage_charge_usd)}
/>
<MetaItem label="Total" value={formatUsdCents(c.total_usd)} />
</MetaGrid>
{c.unpriced_calls > 0 && (
<p className="mt-3 text-[11px] text-gray-500 dark:text-gray-400">
{formatCount(c.unpriced_calls)} call
{c.unpriced_calls === 1 ? "" : "s"} went to a model with no price on
record and {c.unpriced_calls === 1 ? "is" : "are"} not charged.
</p>
)}
</SectionCard>
);
const BudgetRows: React.FC<{ budgets: StatementBudget[] }> = ({ budgets }) =>
budgets.length === 0 ? (
<p className="text-sm text-gray-500 dark:text-gray-400">
No budget or platform allowance governed this workspace.
</p>
) : (
<table className="w-full text-xs" aria-label="Budgets">
<thead>
<tr className="text-left text-[10px] uppercase tracking-wide text-gray-400">
<th className="font-medium py-1">Budget</th>
<th className="font-medium py-1 text-right">Cap</th>
<th className="font-medium py-1 text-right">Spent this month</th>
<th className="font-medium py-1 text-right">Refused</th>
<th className="font-medium py-1 text-right">Stopped</th>
<th className="font-medium py-1 text-right">Let through</th>
</tr>
</thead>
<tbody>
{budgets.map((b) => (
<tr key={b.key} className="border-t border-gray-100 dark:border-gray-700">
<td className="py-1 pr-3">
<div className="text-gray-700 dark:text-gray-200">{b.label}</div>
<div className="text-[10px] text-gray-400">
{[
b.period_label,
b.kind === "platform" ? "set by CHAIN-R" : null,
]
.filter(Boolean)
.join(" · ")}
</div>
</td>
<td className="py-1 text-right tabular-nums">{money(b.cap_usd)}</td>
<td className="py-1 text-right tabular-nums">{money(b.spent_usd)}</td>
<td className="py-1 text-right tabular-nums">{b.refused}</td>
<td className="py-1 text-right tabular-nums">{b.stopped}</td>
<td className="py-1 text-right tabular-nums">{b.let_through}</td>
</tr>
))}
</tbody>
</table>
);
const CountList: React.FC<{
label: string;
counts?: Record<string, number>;
names: Record<string, string>;
}> = ({ label, counts, names }) => (
<div>
<h3 className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-1.5">
{label}
</h3>
<ul className="space-y-0.5 text-xs" aria-label={label}>
{Object.entries(counts ?? {}).map(([key, count]) => (
<li key={key} className="flex justify-between gap-3">
<span className="text-gray-600 dark:text-gray-300">
{names[key] ?? key.replace(/_/g, " ")}
</span>
<span className="tabular-nums">{formatCount(count)}</span>
</li>
))}
</ul>
</div>
);
export const StatementBody: React.FC<{ statement: Statement }> = ({
statement: s,
}) => {
const spend = s.spend;
const previous = spend.previous_month;
const verdicts = s.decisions.verdicts ?? {};
return (
<div className="space-y-4">
<div
className={`rounded-lg border px-4 py-2.5 text-xs ${
s.closed
? "border-emerald-200 dark:border-emerald-800 bg-emerald-50 dark:bg-emerald-900/20 text-emerald-800 dark:text-emerald-200"
: "border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900/20 text-amber-800 dark:text-amber-200"
}`}
>
{s.closed ? (
<span className="flex flex-wrap items-center gap-x-2 gap-y-1">
Closed {day(s.generated_at)} and kept unchanged.
{s.content_sha256 && (
<>
<span className="font-mono">
SHA-256 {s.content_sha256.slice(0, 16)}…
</span>
<span className="print:hidden">
<CopyButton value={s.content_sha256} label="Copy digest" />
</span>
</>
)}
</span>
) : (
<>
A draft: the month so far, computed {day(s.generated_at)}. It is
kept unchanged once the month closes.
</>
)}
</div>
<SectionCard icon={Wallet} title="Spend">
<MetaGrid columns={4}>
<MetaItem
label="Measured spend"
value={money(spend.spend_usd, spend.unpriced_calls)}
/>
<MetaItem
label="Counted by budgets"
value={money(spend.counted_usd)}
/>
<MetaItem
label={previous ? `Previous month (${previous.key})` : "Previous month"}
value={money(previous?.spend_usd)}
/>
<MetaItem
label="Governed decisions"
value={formatCount(spend.decisions ?? 0)}
/>
<MetaItem label="Model calls" value={formatCount(spend.calls ?? 0)} />
<MetaItem
label="Tokens in / out"
value={`${formatCount(spend.input_tokens ?? 0)} / ${formatCount(spend.output_tokens ?? 0)}`}
/>
<MetaItem
label="Spent on failed or stopped turns"
value={formatUsd(spend.failed_spend_usd ?? 0)}
/>
<MetaItem
label="Calls with no price"
value={formatCount(spend.unpriced_calls ?? 0)}
/>
{s.workspace.cost_centre && (
<MetaItem label="Cost centre" value={s.workspace.cost_centre} />
)}
</MetaGrid>
{(spend.unpriced_calls ?? 0) > 0 && (
<p className="mt-3 text-[11px] text-gray-500 dark:text-gray-400">
Measured spend is a floor: some calls went to a model with no price
on record. Budgets count those at the dearest catalogue rate.
</p>
)}
{s.daily.length > 0 && (
<div className="mt-4">
<DailyCostBars
days={s.daily.map((d) => ({
date: d.date,
cost_usd: d.spend_usd ?? null,
invocations: d.decisions ?? 0,
}))}
/>
</div>
)}
</SectionCard>
{s.charges && <ChargesCard charges={s.charges} />}
<SectionCard icon={BarChart3} title="Where it went">
<div className="grid gap-5 sm:grid-cols-2">
<Breakdown table={s.by_source} />
<Breakdown table={s.by_agent} />
<Breakdown table={s.by_model} />
<Breakdown table={s.by_kind} />
<Breakdown table={s.by_project} />
</div>
</SectionCard>
<SectionCard icon={ShieldCheck} title="Budgets">
<BudgetRows budgets={s.budgets} />
</SectionCard>
<SectionCard icon={Gavel} title="Governance and decisions">
<div className="grid gap-5 sm:grid-cols-2">
<CountList
label="Rules in force"
counts={s.governance.rules_in_force}
names={RULES_IN_FORCE_LABELS}
/>
<CountList
label="What the rules did"
counts={s.governance.rule_outcomes}
names={OUTCOME_LABELS}
/>
</div>
<MetaGrid columns={4} className="mt-5">
<MetaItem label="Flags raised" value={formatCount(s.reviews.raised ?? 0)} />
<MetaItem
label="Flags decided"
value={formatCount(s.reviews.decided ?? 0)}
/>
<MetaItem
label="Open at month end"
value={formatCount(s.reviews.open_at_end ?? 0)}
/>
<MetaItem
label="Median time to a decision"
value={
s.reviews.median_hours_to_decision != null
? `${s.reviews.median_hours_to_decision} h`
: "—"
}
/>
<MetaItem
label="Evaluation runs"
value={formatCount(s.evaluations.runs_completed ?? 0)}
/>
<MetaItem
label="Regressions caught"
value={formatCount(s.evaluations.regressions_caught ?? 0)}
/>
<MetaItem
label="Decisions verified"
value={`${formatCount(s.decisions.verified ?? 0)} of ${formatCount(s.decisions.governed ?? 0)}`}
/>
<MetaItem
label="Accepted · edited · rejected"
value={`${verdicts.accepted ?? 0} · ${verdicts.edited ?? 0} · ${verdicts.rejected ?? 0}`}
/>
<MetaItem
label="Corrections captured"
value={formatCount(s.decisions.corrections_captured ?? 0)}
/>
</MetaGrid>
</SectionCard>
<p className="text-[11px] text-gray-500 dark:text-gray-400">
Aggregate figures only: no question, answer or person is named.
{s.workspace.counts_projects
? " The workspace's projects are counted in it."
: ""}{" "}
Months are UTC.
</p>
</div>
);
};
const StatementViewer: React.FC = () => {
const { month: raw } = useParams<{ month: string }>();
const month = parseMonth(raw);
const { getApiHandler } = useApiHandler();
const [downloading, setDownloading] = useState(false);
const { data, isLoading, error } = useQuery<Statement | null>({
queryKey: [QUERY_KEYS.GET.STATEMENT, month],
queryFn: () => getApiHandler().statement_router.get(month!),
enabled: !!month,
});
// Bound explicitly: TS 5.0.2 cannot infer react-query v5's generic here.
const statement: Statement | null = data ?? null;
const download = async () => {
Iif (!month) return;
setDownloading(true);
try {
await getApiHandler().statement_router.downloadCsv(month);
} finally {
setDownloading(false);
}
};
const button =
"flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700 print:hidden";
return (
<DetailPage<Statement>
resource={month ? statement : null}
loading={!!month && isLoading}
error={error}
label="statement"
title={statement ? `Statement — ${statement.period.label}` : undefined}
description="What this workspace spent in the month, and what governed it: budgets, rules, reviews, evaluations and verified decisions. Aggregate figures only."
icon={<FileSpreadsheet className="size-5" />}
back={APP_ROUTES.USER.GOVERNANCE.spend}
actions={[
<button
key="csv"
type="button"
onClick={download}
disabled={downloading}
className={button}
>
<Download className="size-3.5" />
{downloading ? "Downloading…" : "Download CSV"}
</button>,
<button
key="print"
type="button"
onClick={() => window.print()}
className={button}
>
<Printer className="size-3.5" />
Print
</button>,
]}
// A record of a month, written once: nobody edits it.
history={false}
resourceId={month}
>
{(s) => <StatementBody statement={s} />}
</DetailPage>
);
};
export default StatementViewer;
|