All files / src/components/cost BudgetBar.tsx

100% Statements 8/8
82.75% Branches 24/29
100% Functions 1/1
100% Lines 8/8

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              33x                                           33x         15x 15x 15x 15x       15x 15x                                                        
import { BUDGET_STATUS, MeterBar, MeterTone } from "@/components/detail";
import { Budget } from "@/objects/Budget";
import React from "react";
import { formatUsd } from "./format";
 
/** A budget's status as the meter's fill — the same meaning as its badge
 *  (`BUDGET_STATUS`), never a colour of its own. */
const TONE: Record<string, MeterTone> = {
  success: "ok",
  warning: "warning",
  danger: "danger",
  neutral: "muted",
};
 
export interface BudgetBarProps {
  budget: Pick<
    Budget,
    "cap_usd" | "spent_usd" | "status" | "forecast" | "rule_name"
  >;
  loading?: boolean;
  className?: string;
}
 
/**
 * A budget's spend against its cap, with a tick where its forecast lands
 * when it lands inside the bar. Figures are what the cap counts — the
 * estimate for unpriced calls included — so they can read a little above
 * the measured spend elsewhere.
 */
const BudgetBar: React.FC<BudgetBarProps> = ({
  budget,
  loading = false,
  className = "",
}) => {
  const cap = budget.cap_usd ?? null;
  const spent = budget.spent_usd ?? null;
  const share = cap && spent !== null ? spent / cap : null;
  const projected = budget.forecast?.available
    ? (budget.forecast.projected_usd ?? null)
    : null;
  const marker =
    cap && projected !== null && projected <= cap ? projected / cap : null;
  return (
    <div className={className}>
      <div className="flex items-baseline justify-between gap-2 mb-1 text-xs">
        <span className="tabular-nums text-gray-700 dark:text-gray-200">
          {spent === null ? "—" : formatUsd(spent)}
          <span className="text-gray-400 dark:text-gray-500">
            {" "}
            of {cap === null ? "—" : formatUsd(cap)}
          </span>
        </span>
        {share !== null && (
          <span className="tabular-nums text-gray-500 dark:text-gray-400">
            {Math.round(share * 100)}%
          </span>
        )}
      </div>
      <MeterBar
        share={share}
        tone={TONE[BUDGET_STATUS[budget.status] ?? "neutral"] ?? "muted"}
        marker={marker}
        loading={loading}
        label={`${budget.rule_name}: spend against its cap`}
      />
    </div>
  );
};
 
export default BudgetBar;