All files / src/apps/user/pages/spend Spend.tsx

95.23% Statements 120/126
77.2% Branches 166/215
88.09% Functions 37/42
95.72% Lines 112/117

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 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                                                                                                                            3x               3x         3x 21x   3x 42x       13x 10x   9x         13x         3x           39x                                     3x       13x 13x   13x     13x 13x                                                                                       10x 10x 10x 9x             1x 1x   1x       10x 10x 1x   1x       10x 10x 10x 1x 10x               11x 3x 2x       2x   4x     2x     3x           7x 7x 7x 7x 7x                                                                                                                                           2x                           3x     3x   3x     3x                                                                                                 3x             3x         42x 42x     15x               42x 42x     42x                                                               3x 6x         3x 5x                                             3x 4x   12x 4x 4x 4x 4x 4x 1x 1x       1x   4x         8x         1x       24x             4x                                                       3x     18x 18x   7x       18x 18x                                       3x                       3x 13x 13x 13x 13x   13x   6x     13x   5x     13x   5x     13x   5x         13x 13x     13x       13x 13x           13x   13x                               1x                                                         7x                                             26x                                                 52x   39x                                                                     1x                
import {
  BudgetBar,
  DailyCostBars,
  describeCost,
  formatUsd,
} from "@/components/cost";
import {
  BUDGET_STATUS,
  SectionCard,
  Skeleton,
  StatusBadge,
} from "@/components/detail";
import { useWorkspace } from "@/context/WorkspaceContext";
import {
  Budget,
  BudgetForecast,
  Budgets,
  PlatformAllowance,
  SpendOverview,
} from "@/objects/Budget";
import { CostPeriod, ResourceCost } from "@/objects/Cost";
import type { StatementList, StatementSummary } from "@/objects/Statement";
import {
  RuleCatalogue,
  RuleScopeTargets,
  vocabularyEntries,
} from "@/objects/Rule";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { resourceHref } from "@/routes/resourceHref";
import {
  Breakdown,
  BreakdownBucket,
} from "@/services/api/routers/StatsRouter";
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,
  Info,
  Plus,
  Wallet,
} from "lucide-react";
import moment from "moment";
import React, { useState } from "react";
import { Link } from "react-router-dom";
import AddBudgetModal from "./AddBudgetModal";
 
/**
 * Governance → Spend: what the workspace has spent, the budgets that govern
 * it and where each is heading (cost-control plan, A1.3).
 *
 * A budget is a `cost_cap` rule — the one enforcement path — read through
 * `GET /app/budgets`, which takes each figure from the cap's own reading, so
 * a budget shown "Reached" is one the next turn it governs meets. The
 * breakdowns read the ledger's measured spend (`/stats/breakdown`); budgets
 * also count a high estimate for calls no catalogue could price, so the two
 * can differ by that much. See `docs/guides/cost-monitoring.md#budgets`.
 */
 
const STATUS_LABEL: Record<string, string> = {
  ok: "On track",
  near: "Nearly used",
  projected_over: "Heading over",
  reached: "Reached",
  unavailable: "Unavailable",
};
 
const PERIODS: { key: CostPeriod; label: string }[] = [
  { key: "this_month", label: "This month" },
  { key: "last_month", label: "Last month" },
];
 
const day = (iso?: string | null) =>
  iso ? moment(parseServerDate(iso)).format("D MMM YYYY") : null;
 
const money = (value?: number | null) =>
  value === null || value === undefined ? "—" : formatUsd(value);
 
/** "Projected $64.80 (between $58.10 and $71.50) at the last 7 days' rate" */
export function forecastText(forecast?: BudgetForecast | null): string | null {
  if (!forecast) return null;
  if (!forecast.available) return forecast.note ?? null;
  const range =
    forecast.low_usd != null &&
    forecast.high_usd != null &&
    forecast.high_usd - forecast.low_usd >= 0.005
      ? ` (between ${formatUsd(forecast.low_usd)} and ${formatUsd(forecast.high_usd)})`
      : "";
  return `Projected ${money(forecast.projected_usd)}${range} at the last ${forecast.days_used} days' rate`;
}
 
// ─── The month ────────────────────────────────────────────────────────────────
 
const Figure: React.FC<{
  label: string;
  value: React.ReactNode;
  detail?: React.ReactNode;
  loading?: boolean;
}> = ({ label, value, detail, loading }) => (
  <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4">
    <div className="text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-500 font-medium">
      {label}
    </div>
    {loading ? (
      <Skeleton className="h-6 w-24 mt-1" />
    ) : (
      <div className="text-xl font-semibold tabular-nums text-gray-900 dark:text-gray-100 mt-0.5">
        {value}
      </div>
    )}
    {detail && !loading && (
      <div className="text-[11px] text-gray-500 dark:text-gray-400 mt-1">
        {detail}
      </div>
    )}
  </div>
);
 
const MonthFigures: React.FC<{
  overview: SpendOverview | null | undefined;
  loading: boolean;
}> = ({ overview, loading }) => {
  const spent = overview?.spent_usd ?? null;
  const last = overview?.last_month_usd ?? null;
  const change =
    spent !== null && last !== null && last > 0
      ? Math.round(((spent - last) / last) * 100)
      : null;
  const forecast = overview?.forecast;
  return (
    <div className="grid gap-3 sm:grid-cols-3">
      <Figure
        label="This month"
        value={money(spent)}
        detail={overview?.resets_at ? `Resets ${day(overview.resets_at)}` : undefined}
        loading={loading}
      />
      <Figure
        label="Last month"
        value={money(last)}
        detail={
          change !== null
            ? `This month so far is ${Math.abs(change)}% ${change >= 0 ? "above" : "below"} it`
            : undefined
        }
        loading={loading}
      />
      <Figure
        label="Forecast for the month"
        value={
          forecast?.available ? money(forecast.projected_usd) : "Not yet"
        }
        detail={
          forecast
            ? forecast.available
              ? `A projection, not a bill. ${forecastText(forecast)}.`
              : forecast.note
            : undefined
        }
        loading={loading}
      />
    </div>
  );
};
 
// ─── Budgets ──────────────────────────────────────────────────────────────────
 
/** What a budget covers, in words. */
export function budgetReach(
  budget: Budget,
  targets: RuleScopeTargets | null | undefined,
  typeLabels: Record<string, string>,
): string[] {
  const parts: string[] = [];
  const scope = budget.scope_type ?? "global";
  if (scope === "global") {
    parts.push(
      budget.required_for_projects
        ? "The whole workspace, every project included"
        : "The whole workspace",
    );
  } else {
    const named =
      targets?.targets?.[scope as keyof RuleScopeTargets["targets"]]?.find(
        (t) => t.id === budget.scope_id,
      )?.label ?? "one resource";
    parts.push(
      scope === "project" ? `Allocated to ${named}` : `Only ${scope}: ${named}`,
    );
  }
  if (budget.share === "per_member") parts.push("each member's own allowance");
  if (budget.execution_types?.length)
    parts.push(
      `only ${budget.execution_types
        .map((t) => typeLabels[t] ?? t)
        .join(", ")
        .toLowerCase()}`,
    );
  if (budget.conditions) parts.push("only the work its conditions match");
  if (budget.on_reach === "warn") parts.push("warns rather than stops");
  if (budget.origin === "inherited" || budget.origin === "required")
    parts.push("set by the parent workspace");
  return parts;
}
 
/** "Alerts at 80% used, used up, heading over" — or that it sends none. */
export function alertText(
  alertAt: string[] | undefined,
  labels: Record<string, string>,
): string | null {
  if (alertAt === undefined) return null;
  if (alertAt.length === 0) return "No alerts";
  const SHORT: Record<string, string> = {
    "100": "used up",
    projected: "heading over",
  };
  const named = alertAt.map(
    (key) =>
      SHORT[key] ??
      (/^\d+$/.test(key) ? `${key}% used` : (labels[key] ?? key).toLowerCase()),
  );
  return `Alerts at ${named.join(", ")}`;
}
 
const BudgetCard: React.FC<{
  budget: Budget;
  targets: RuleScopeTargets | null | undefined;
  typeLabels: Record<string, string>;
  alertLabels?: Record<string, string>;
}> = ({ budget, targets, typeLabels, alertLabels = {} }) => {
  const alerts = alertText(budget.alert_at, alertLabels);
  const href = resourceHref("rule", budget.rule_id);
  const forecast = forecastText(budget.forecast);
  const periodWord = (budget.period_label ?? "").toLowerCase();
  return (
    <li className="py-3 first:pt-0 last:pb-0">
      <div className="flex flex-wrap items-center justify-between gap-2 mb-1">
        <div className="min-w-0">
          {href ? (
            <Link
              to={href}
              className="text-sm font-medium text-gray-900 dark:text-gray-100 hover:underline"
            >
              {budget.rule_name}
            </Link>
          ) : (
            <span className="text-sm font-medium">{budget.rule_name}</span>
          )}
          <div className="text-[11px] text-gray-500 dark:text-gray-400">
            {[budget.period_label, ...budgetReach(budget, targets, typeLabels)]
              .filter(Boolean)
              .join(" · ")}
          </div>
        </div>
        <StatusBadge
          status={budget.status}
          scale={BUDGET_STATUS}
          label={STATUS_LABEL[budget.status] ?? budget.status}
        />
      </div>
      {budget.status === "unavailable" && budget.spent_usd == null ? (
        <p className="text-xs text-gray-500 dark:text-gray-400 italic">
          {budget.note ?? "Its figures could not be read just now."}
        </p>
      ) : (
        <>
          <BudgetBar budget={budget} />
          <ul className="mt-1.5 flex flex-wrap gap-x-4 gap-y-0.5 text-[11px] text-gray-500 dark:text-gray-400">
            {budget.counts === "yours" && <li>Your own spend</li>}
            {alerts && <li>{alerts}</li>}
            {budget.resets_at && <li>Resets {day(budget.resets_at)}</li>}
            {budget.previous_spent_usd != null && (
              <li>
                Previous {periodWord.replace(/^each /, "") || "period"}:{" "}
                {money(budget.previous_spent_usd)}
              </li>
            )}
            {forecast && <li>{forecast}</li>}
            {budget.forecast?.reaches_cap_at && (
              <li className="text-amber-700 dark:text-amber-300">
                At that rate it is used up on{" "}
                {day(budget.forecast.reaches_cap_at)}
              </li>
            )}
            {budget.blocks && (
              <li className="text-red-700 dark:text-red-300">
                Work it covers is refused until it resets
              </li>
            )}
          </ul>
          {budget.note && (
            <p className="mt-1 text-[11px] text-gray-500 dark:text-gray-400">
              {budget.note}
            </p>
          )}
        </>
      )}
      {budget.members && budget.members.length > 0 && (
        <details className="mt-2 text-xs">
          <summary className="cursor-pointer text-gray-500 dark:text-gray-400">
            By member ({budget.members.length})
          </summary>
          <ul className="mt-1 space-y-0.5" aria-label="Spend by member">
            {budget.members.map((m) => (
              <li key={m.user_id} className="flex justify-between gap-3">
                <span className="truncate">{m.name}</span>
                <span className="tabular-nums">{formatUsd(m.spent_usd)}</span>
              </li>
            ))}
          </ul>
        </details>
      )}
    </li>
  );
};
 
/** CHAIN-R's own monthly cap on the workspace: shown like a budget, with
 *  nothing to edit and no rule to open. */
export const AllowanceCard: React.FC<{ allowance: PlatformAllowance }> = ({
  allowance,
}) => {
  const forecast = forecastText(allowance.forecast);
  const covers =
    allowance.holder === "organisation"
      ? "The organisation and every project in it"
      : "Your Personal workspace and its projects";
  return (
    <li className="py-3 first:pt-0 last:pb-0">
      <div className="flex flex-wrap items-center justify-between gap-2 mb-1">
        <div className="min-w-0">
          <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
            {allowance.name}
          </span>
          <div className="text-[11px] text-gray-500 dark:text-gray-400">
            {[allowance.period_label, covers, "set by CHAIN-R"]
              .filter(Boolean)
              .join(" · ")}
          </div>
        </div>
        <StatusBadge
          status={allowance.status}
          scale={BUDGET_STATUS}
          label={STATUS_LABEL[allowance.status] ?? allowance.status}
        />
      </div>
      {allowance.spent_usd == null ? (
        <p className="text-xs text-gray-500 dark:text-gray-400 italic">
          {allowance.note ?? "Its figures could not be read just now."}
        </p>
      ) : (
        <>
          <BudgetBar budget={{ ...allowance, rule_name: allowance.name }} />
          <ul className="mt-1.5 flex flex-wrap gap-x-4 gap-y-0.5 text-[11px] text-gray-500 dark:text-gray-400">
            {allowance.resets_at && <li>Resets {day(allowance.resets_at)}</li>}
            {forecast && <li>{forecast}</li>}
            {allowance.blocks && (
              <li className="text-red-700 dark:text-red-300">
                Work here is refused until it resets
              </li>
            )}
          </ul>
          {allowance.note && (
            <p className="mt-1 text-[11px] text-gray-500 dark:text-gray-400">
              {allowance.note}
            </p>
          )}
        </>
      )}
    </li>
  );
};
 
// ─── Where it went ────────────────────────────────────────────────────────────
 
const BREAKDOWNS: { dimension: string; title: string; organisation?: boolean }[] =
  [
    { dimension: "source", title: "By what it was spent on" },
    { dimension: "agent", title: "By agent" },
    { dimension: "execution_type", title: "By kind of work" },
    { dimension: "project", title: "By project", organisation: true },
  ];
 
const BreakdownList: React.FC<{
  dimension: string;
  title: string;
  period: CostPeriod;
}> = ({ dimension, title, period }) => {
  const { getApiHandler } = useApiHandler();
  const { data, isLoading } = useQuery<Breakdown | null>({
    queryKey: [QUERY_KEYS.GET.STATS_BREAKDOWN, "spend", dimension, period],
    queryFn: () =>
      getApiHandler().stats_router.getBreakdown({
        metric: "estimated_cost_usd",
        dimension,
        period,
        limit: 6,
      }),
  });
  // Bound explicitly: TS 5.0.2 cannot infer react-query v5's generic here.
  const breakdown: Breakdown | null = (data as Breakdown | null) ?? null;
  const buckets: BreakdownBucket[] = (breakdown?.buckets ?? []).filter(
    (b: BreakdownBucket) => (b.value ?? 0) > 0,
  );
  return (
    <div>
      <h3 className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-1.5">
        {title}
      </h3>
      {isLoading ? (
        <Skeleton className="h-16 w-full" />
      ) : buckets.length === 0 ? (
        <p className="text-xs text-gray-400 italic">Nothing spent.</p>
      ) : (
        <ul className="space-y-1" aria-label={title}>
          {buckets.map((b) => (
            <li key={b.key} className="text-xs">
              <div className="flex justify-between gap-3">
                <span className="truncate text-gray-700 dark:text-gray-200">
                  {b.label}
                </span>
                <span className="tabular-nums text-gray-600 dark:text-gray-300">
                  {formatUsd(b.value ?? 0)}
                </span>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};
 
// ─── Statements ───────────────────────────────────────────────────────────────
 
/** Where one month's statement opens. */
export const statementHref = (month: string) =>
  APP_ROUTES.USER.GOVERNANCE.STATEMENTS.month.replace(
    ROUTE_PARAMS.STATEMENT.month,
    month,
  );
 
const StatementLine: React.FC<{ summary: StatementSummary }> = ({ summary }) => (
  <li className="py-2 first:pt-0 last:pb-0 flex flex-wrap items-center justify-between gap-2 text-sm">
    <Link
      to={statementHref(summary.period.key)}
      className="font-medium text-gray-900 dark:text-gray-100 hover:underline"
    >
      {summary.period.label}
    </Link>
    <span className="flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
      <span className="tabular-nums">
        {describeCost({ cost_usd: summary.spend_usd ?? null }).text}
      </span>
      <span>
        {summary.closed
          ? `Closed ${day(summary.closed_at)}`
          : "So far — a draft"}
      </span>
    </span>
  </li>
);
 
/** Download a run of months as one CSV for finance (svc-core
 *  `GET /app/statements/export`): every figure a row, with its month and the
 *  cost centre it is filed under. */
const FinanceExport: React.FC<{ months: StatementSummary[] }> = ({ months }) => {
  const { getApiHandler } = useApiHandler();
  // Oldest first, as a range is read.
  const keys = [...months].map((m) => m.period).reverse();
  const [from, setFrom] = useState(keys[0]?.key ?? "");
  const [to, setTo] = useState(keys[keys.length - 1]?.key ?? "");
  const [state, setState] = useState<"idle" | "working" | "failed">("idle");
  Iif (keys.length === 0) return null;
  const download = async () => {
    setState("working");
    const done = await getApiHandler().statement_router.downloadExport(
      from <= to ? from : to,
      from <= to ? to : from,
    );
    setState(done ? "idle" : "failed");
  };
  const select = (
    label: string,
    value: string,
    onChange: (v: string) => void,
  ) => (
    <label className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
      {label}
      <select
        aria-label={`${label} month`}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="rounded-md border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 px-2 py-1 text-xs text-gray-700 dark:text-gray-200"
      >
        {keys.map((p) => (
          <option key={p.key} value={p.key}>
            {p.label}
          </option>
        ))}
      </select>
    </label>
  );
  return (
    <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-gray-100 dark:border-gray-700 pt-3">
      <span className="text-xs font-medium text-gray-600 dark:text-gray-300">
        Export for finance
      </span>
      {select("From", from, setFrom)}
      {select("To", to, setTo)}
      <button
        type="button"
        onClick={download}
        disabled={state === "working"}
        className="inline-flex items-center gap-1 rounded-md border border-gray-200 dark:border-gray-600 px-2.5 py-1 text-xs font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700/50 disabled:opacity-50"
      >
        <Download className="size-3.5" />
        {state === "working" ? "Preparing…" : "Download CSV"}
      </button>
      {state === "failed" && (
        <span role="alert" className="text-xs text-red-600 dark:text-red-400">
          The export could not be downloaded.
        </span>
      )}
    </div>
  );
};
 
/** The month so far and every month the workspace has closed, each
 *  opening its statement (`pages/spend/Statement.tsx`) — and, for those who
 *  govern the workspace, a run of them as one CSV for finance. */
export const StatementsCard: React.FC<{ governs?: boolean }> = ({
  governs = false,
}) => {
  const { getApiHandler } = useApiHandler();
  const { data, isLoading, isError } = useQuery<StatementList | null>({
    queryKey: [QUERY_KEYS.GET.STATEMENTS],
    queryFn: () => getApiHandler().statement_router.list(),
    staleTime: 60_000,
  });
  // Bound explicitly: TS 5.0.2 cannot infer react-query v5's generic here.
  const list: StatementList | null = data && data.current ? data : null;
  return (
    <SectionCard
      icon={FileSpreadsheet}
      title="Statements"
      description="Each month's spend and what governed it, kept unchanged once the month closes. Download as CSV or print."
    >
      {isLoading ? (
        <Skeleton className="h-12 w-full" />
      ) : isError || !list ? (
        <p className="text-sm text-gray-400 italic">
          Statements are unavailable right now.
        </p>
      ) : (
        <>
          <ul
            className="divide-y divide-gray-100 dark:divide-gray-700"
            aria-label="Statements"
          >
            <StatementLine summary={list.current} />
            {list.closed.map((s) => (
              <StatementLine key={s.period.key} summary={s} />
            ))}
          </ul>
          {governs && <FinanceExport months={[list.current, ...list.closed]} />}
        </>
      )}
    </SectionCard>
  );
};
 
// ─── The section ──────────────────────────────────────────────────────────────
 
export const SpendContent: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const workspace = useWorkspace();
  const [period, setPeriod] = useState<CostPeriod>("this_month");
  const [adding, setAdding] = useState(false);
 
  const { data, isLoading, isError } = useQuery<Budgets | null>({
    queryKey: [QUERY_KEYS.GET.BUDGETS],
    queryFn: () => getApiHandler().budget_router.list(),
    staleTime: 30_000,
  });
  const { data: targets } = useQuery<RuleScopeTargets | null>({
    queryKey: [QUERY_KEYS.GET.RULE_SCOPE_TARGETS],
    queryFn: () => getApiHandler().rule_router.targets(),
    staleTime: 60_000,
  });
  const { data: catalogue } = useQuery<RuleCatalogue | null>({
    queryKey: [QUERY_KEYS.GET.RULE_CATALOGUE],
    queryFn: () => getApiHandler().rule_router.catalogue(),
    staleTime: 300_000,
  });
  const { data: cost, isLoading: costLoading } = useQuery<ResourceCost | null>({
    queryKey: [QUERY_KEYS.GET.RESOURCE_COST, "spend", period],
    queryFn: () => getApiHandler().stats_router.getCost({ period }),
  });
 
  // Bound explicitly: TS 5.0.2 cannot infer react-query v5's generic here.
  const budgets: Budgets | null =
    data && Array.isArray(data.budgets) ? data : null;
  const typeLabels: Record<string, string> = Object.fromEntries(
    vocabularyEntries(catalogue, "execution_types").map((e) => [e.key, e.label]),
  );
  const alertLabels: Record<string, string> = Object.fromEntries(
    vocabularyEntries(catalogue, "quota_alerts").map((e) => [e.key, e.label]),
  );
  const measured: ResourceCost | null =
    cost && typeof cost.invocations === "number" ? cost : null;
  const figure = measured
    ? describeCost({
        cost_usd: measured.cost_usd,
        unpriced: measured.unpriced_calls + measured.unpriced_invocations,
      })
    : null;
  const organisation = workspace.kind === "organisation";
 
  return (
    <div className="space-y-4">
      <MonthFigures overview={budgets?.overview} loading={isLoading} />
 
      <SectionCard
        icon={Wallet}
        title="Budgets"
        subtitle={
          budgets?.budgets.length
            ? `${budgets.budgets.length} governing this workspace`
            : undefined
        }
        action={
          budgets?.governs ? (
            <button
              type="button"
              onClick={() => setAdding(true)}
              className="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"
            >
              <Plus className="size-3.5" />
              Add budget
            </button>
          ) : undefined
        }
      >
        {isLoading ? (
          <Skeleton className="h-20 w-full" />
        ) : isError || !budgets ? (
          <p className="text-sm text-gray-400 italic">
            Budgets are unavailable right now.
          </p>
        ) : budgets.budgets.length === 0 && !budgets.allowance ? (
          <p className="text-sm text-gray-500 dark:text-gray-400">
            No budget governs this workspace. Spend is recorded, but nothing
            stops it.
            {budgets.governs
              ? " Add one to cap a month, a week or a day."
              : " Someone who governs this workspace can add one."}
          </p>
        ) : (
          <ul className="divide-y divide-gray-100 dark:divide-gray-700">
            {budgets.allowance && (
              <AllowanceCard allowance={budgets.allowance} />
            )}
            {budgets.budgets.map((b) => (
              <BudgetCard
                key={`${b.rule_id}:${b.action_index}`}
                budget={b}
                targets={targets}
                typeLabels={typeLabels}
                alertLabels={alertLabels}
              />
            ))}
          </ul>
        )}
      </SectionCard>
 
      <SectionCard
        icon={BarChart3}
        title="Where it went"
        subtitle={figure ? `${figure.text} measured` : undefined}
        action={
          <div
            role="tablist"
            aria-label="Spend period"
            className="flex rounded-lg border border-gray-200 dark:border-gray-600 p-0.5"
          >
            {PERIODS.map((p) => (
              <button
                key={p.key}
                type="button"
                role="tab"
                aria-selected={period === p.key}
                onClick={() => setPeriod(p.key)}
                className={`px-2 py-0.5 rounded-md text-[11px] font-medium transition-colors ${
                  period === p.key
                    ? "bg-gray-900 dark:bg-white text-white dark:text-gray-900"
                    : "text-gray-500 dark:text-gray-400 hover:text-gray-700"
                }`}
              >
                {p.label}
              </button>
            ))}
          </div>
        }
      >
        <div className="space-y-4">
          {costLoading ? (
            <Skeleton className="h-14 w-full" />
          ) : measured ? (
            <DailyCostBars days={measured.daily} />
          ) : null}
          <div className="grid gap-4 sm:grid-cols-2">
            {BREAKDOWNS.filter((b) => !b.organisation || organisation).map(
              (b) => (
                <BreakdownList
                  key={b.dimension}
                  dimension={b.dimension}
                  title={b.title}
                  period={period}
                />
              ),
            )}
          </div>
        </div>
      </SectionCard>
 
      <StatementsCard governs={Boolean(budgets?.governs)} />
 
      <p className="flex items-start gap-1.5 text-[11px] text-gray-500 dark:text-gray-400">
        <Info className="size-3.5 shrink-0 mt-px" />
        Budgets count everything the workspace spends, and a budget that is
        used up stops all of it: chats, skill runs, evaluations and dashboard
        tiles, and generating resources, searching and indexing knowledge and
        crawling websites too. A document or a crawl a budget holds runs when
        it starts again. A turn starts only if a budget has what a turn
        usually costs left
        {budgets?.typical_turn_usd != null
          ? ` (about ${formatUsd(budgets.typical_turn_usd)} here)`
          : ""}
        , and stops where the budget does. Budgets also count calls to a model
        with no price at its dearest catalogue rate, so they can read above
        the measured spend.
      </p>
 
      {adding && budgets && (
        <AddBudgetModal
          workspaceKind={workspace.kind}
          targets={targets}
          catalogue={catalogue}
          onClose={() => setAdding(false)}
        />
      )}
    </div>
  );
};
 
export default SpendContent;