import { useMemo } from "react"; import { useQuery } from "@tanstack/react-query"; import { Coins, DollarSign, PlayCircle, ReceiptText } from "lucide-react"; import type { CostByAgent, CostByAgentModel } from "@paperclipai/shared"; import { costsApi } from "../api/costs"; import { CostAmount } from "../components/CostAmount"; import { EmptyState } from "../components/EmptyState"; import { MetricCard } from "../components/MetricCard"; import { PageSkeleton } from "../components/PageSkeleton"; import { Button } from "@/components/ui/button"; import { useDateRange, PRESET_KEYS, PRESET_LABELS } from "../hooks/useDateRange"; import { queryKeys } from "../lib/queryKeys"; import { billingTypeDisplayName, formatCents, formatTokens, providerDisplayName } from "../lib/utils"; export function agentCostRow(rows: readonly CostByAgent[] | undefined, agentId: string): CostByAgent | null { return rows?.find((row) => row.agentId === agentId) ?? null; } export function agentModelCostRows(rows: readonly CostByAgentModel[] | undefined, agentId: string): CostByAgentModel[] { return (rows ?? []) .filter((row) => row.agentId === agentId) .sort((a, b) => b.costCents - a.costCents); } export function AgentCostsPanel({ agentId, agentName, companyId }: { agentId: string; agentName: string; companyId: string }) { const { preset, setPreset, customFrom, setCustomFrom, customTo, setCustomTo, from, to, customReady } = useDateRange(); const reportFrom = ["custom", "mtd", "ytd"].includes(preset) ? from || undefined : undefined; const reportTo = preset === "custom" ? to || undefined : preset; const spend = useQuery({ queryKey: [...queryKeys.costs(companyId, reportFrom, reportTo), "agent", agentId], queryFn: async () => { const [byAgent, byAgentModel] = await Promise.all([ costsApi.byAgent(companyId, from || undefined, to || undefined), costsApi.byAgentModel(companyId, from || undefined, to || undefined), ]); return { row: agentCostRow(byAgent, agentId), models: agentModelCostRows(byAgentModel, agentId) }; }, enabled: customReady, refetchInterval: 30_000, }); const row = spend.data?.row ?? null; const models = spend.data?.models ?? []; const totalTokens = useMemo( () => (row ? row.inputTokens + row.cachedInputTokens + row.outputTokens : 0), [row], ); return (
Select a start and end date to load data.
) : spend.isLoading ? ({agentName}'s costs could not be loaded. Please try again shortly.
) : !row ? (No model breakdown for this period.
) : (