All files / src/components/cost useSpend.ts

100% Statements 5/5
100% Branches 18/18
100% Functions 2/2
100% Lines 5/5

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                                            411x 411x                 80x             411x 411x                          
import { CostPeriod, ResourceCost } from "@/objects/Cost";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import { describeCost, spendLabel } from "./format";
 
/**
 * The viewer's own spend in the current workspace, from the usage ledger
 * (`GET /app/stats/cost?mine=true`) — the one figure Overview, Stats and
 * the `stat` tile show, so they agree with each other and with every cost
 * card to the cent. svc-ai's traces count the same calls without the
 * ledger's estimates for unpriced ones, and the Stats page only ever had
 * its newest 500 of them.
 */
export function useSpend(
  query: {
    period?: CostPeriod;
    since?: string;
    until?: string;
  },
  { enabled = true }: { enabled?: boolean } = {},
) {
  const { getApiHandler } = useApiHandler();
  const { data, isLoading } = useQuery<ResourceCost | null>({
    queryKey: [
      QUERY_KEYS.GET.RESOURCE_COST,
      "mine",
      query.period ?? null,
      query.since ?? null,
      query.until ?? null,
    ],
    queryFn: () =>
      getApiHandler().stats_router.getCost({ ...query, mine: true }),
    staleTime: 60_000,
    enabled,
  });
  // Anything not shaped like a cost answer is "unavailable", never a
  // figure read off missing fields.
  const cost: ResourceCost | null =
    data && typeof data.invocations === "number" ? data : null;
  return {
    cost,
    isLoading: enabled && isLoading,
    /** "$1.23", "≥ $1.23" or "Unknown"; null while unavailable. */
    figure: cost
      ? describeCost({
          cost_usd: cost.cost_usd,
          unpriced: cost.unpriced_calls + cost.unpriced_invocations,
        })
      : null,
    label: spendLabel(cost ?? { mine: true }),
  };
}