feat(database): add get_credit_spend_digest aggregation RPC
Re-creates #28 from an in-repo branch (same commits, authored by @arpitgupta1214) so it gets a Supabase preview branch — #28 is from a fork, and Supabase Branching doesn't create preview DBs for fork PRs (security limitation), which is why #28 had no Supabase Preview check.
Original author: @arpitgupta1214 · supersedes #28.
What it does
Adds get_credit_spend_digest(p_since timestamptz, p_limit int default 10) — a single-query aggregation over usage_events returning the top-N accounts by total credits spent over a window, each with turn count, token totals, main-vs-subagent split, and a per-model cents breakdown, enriched with account name + most-recent email. Empty window returns []. Powers the credit-spend digest cron (api#634, chat#1767).
Verification (already done on #28, against the live prod DB via Supabase MCP — read-only)
- ✅ All referenced columns exist on
usage_eventswith correct types;accounts.name+account_emails.{account_id,email,updated_at}present. - ✅ Ran the function body inline on real data: correct ranked array, all 12 keys,
by_modelsums tototal_cents,unknownbucket, null/empty-string name fallback,[]on empty. - ✅ Security:
STABLE,SET search_path,REVOKE … FROM PUBLIC+GRANT … TO service_roleonly. - 🟡 Notes (not blockers):
tool_call_countis unpopulated in prod (digest "tool calls" reads 0);agent_typeonly hasmainso the subagent split stays empty until subagent attribution lands; nocreated_at-leading index (negligible at ~680 rows). Full detail on #28.
Deploy ordering
Apply this migration to prod + set CRON_SECRET in Vercel before api#634 reaches production, or the cron 500s every 10 min.
Summary by cubic
Adds public.get_credit_spend_digest(p_since timestamptz, p_limit int) to aggregate top account credit spend for the digest cron. Returns a ranked JSON array with spend totals, token/turn counts, main vs subagent split, per-model cents, and account name/email.
-
New Features
- New RPC: top-N accounts over [p_since, now]; each item includes totals, token and turn counts, main/subagent cents, per-model cents (with an
unknownbucket), and latest account email; returns[]when empty. - Limits:
p_limitdefaults to 10 and is clamped to [1, 1000].
- New RPC: top-N accounts over [p_since, now]; each item includes totals, token and turn counts, main/subagent cents, per-model cents (with an
-
Bug Fixes
- Access restricted to
service_roleonly; revoked PUBLIC, no SECURITY DEFINER, marked STABLE with explicitsearch_path.
- Access restricted to
Summary by CodeRabbit
- New Features
- Added capability to retrieve aggregated credit spend data ranked by account, including total credits deducted, token consumption metrics, tool call counts, and cost breakdown across models with configurable result size and date filtering.