All files / src/components/cost format.ts

100% Statements 15/15
100% Branches 23/23
100% Functions 5/5
100% Lines 13/13

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                      403x 403x 403x                 8x                                   134x 7x 127x 6x 121x         202x 61x 10x             415x    
/**
 * How spend is written. One place, because a cost read three different ways
 * on three pages is a cost nobody trusts.
 *
 * Two rules the backend's contract needs honouring on screen:
 * - `null` is **unknown**, never `$0`: a model neither price table knows.
 * - a figure with unpriced calls in it is a **lower bound**, and says so.
 */
 
/** "$0.0042", "$1.23", "$1,204" — enough precision to see a cheap call. */
export function formatUsd(value: number): string {
  const abs = Math.abs(value);
  const digits = abs === 0 ? 2 : abs < 0.01 ? 4 : abs < 1 ? 3 : abs < 1000 ? 2 : 0;
  return `$${value.toLocaleString("en-US", {
    minimumFractionDigits: digits,
    maximumFractionDigits: digits,
  })}`;
}
 
/** An amount to bill (a statement's charges): always to the cent, however
 *  large — `formatUsd` drops the cents past $1,000, as a spend figure may. */
export function formatUsdCents(value: number): string {
  return `$${value.toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
}
 
export interface CostFigure {
  cost_usd: number | null;
  /** Calls or invocations that could not be priced. */
  unpriced?: number;
}
 
/** The figure as a reader should see it: exact, a floor, or unknown. */
export function describeCost({ cost_usd, unpriced = 0 }: CostFigure): {
  text: string;
  lowerBound: boolean;
  unknown: boolean;
} {
  if (cost_usd === null || cost_usd === undefined)
    return { text: "Unknown", lowerBound: false, unknown: true };
  if (unpriced > 0)
    return { text: `≥ ${formatUsd(cost_usd)}`, lowerBound: true, unknown: false };
  return { text: formatUsd(cost_usd), lowerBound: false, unknown: false };
}
 
/** "12.3k" — token and call counts in a strip. */
export function formatCount(value: number): string {
  if (value < 1000) return String(value);
  if (value < 1_000_000) return `${(value / 1000).toFixed(value < 10_000 ? 1 : 0)}k`;
  return `${(value / 1_000_000).toFixed(1)}M`;
}
 
/** Whose spend a figure counts, as its caption says it: the viewer's own,
 *  or everyone's in the workspace. A figure that does not say is read as
 *  the workspace's — the wider claim is the safe one. */
export function spendLabel(cost: { mine?: boolean } | null | undefined): string {
  return cost?.mine ? "Your spend" : "Workspace spend";
}