---
phase: 03-operator-experience
plan: 04
subsystem: ui
tags: [recharts, react, nextjs, tanstack-query, shadcn, usage, cost-tracking, budget-alerts]

# Dependency graph
requires:
  - phase: 03-operator-experience
    plan: 01
    provides: "GET /api/portal/usage/{tenant_id}/summary, by-provider, message-volume, budget-alerts backend endpoints"

provides:
  - Usage dashboard page at /usage/[tenantId] — payroll view answering "how much is this employee costing me?"
  - Usage index page at /usage — tenant picker redirecting to per-tenant dashboard
  - UsageChart component — Recharts bar chart of total_tokens per agent with tooltip detail
  - ProviderCostChart component — horizontal bar chart of cost_usd by LLM provider (openai/anthropic/ollama color-coded)
  - MessageVolumeChart component — bar chart of message_count per channel (slack/whatsapp color-coded)
  - BudgetAlertBadge component — ok/warning/exceeded status badge for agent budget limits
  - TanStack Query hooks: useUsageSummary, useUsageByProvider, useMessageVolume, useBudgetAlerts
  - Time range selector (Last 7 days / Last 30 days / This month / Last 3 months) driving all chart queries
  - Summary cards showing total cost, total tokens, total messages at top of dashboard
  - Usage nav link added to sidebar with BarChart2 icon

affects:
  - future phases adding more chart types or export functionality
  - any phase adding billing analytics or cost alerts

# Tech tracking
tech-stack:
  added:
    - recharts@2.15.0 (installed — was in package.json but missing from node_modules)
  patterns:
    - Recharts ResponsiveContainer wrapping BarChart for adaptive sizing
    - Channel/provider color maps via Record<string, string> lookup with fallback gray
    - Custom Tooltip components using TooltipProps<number, string> typing
    - Empty state pattern: "No X data for this period" centered in h-[200px] container
    - Time range key-to-date-range function returning ISO date strings for query params

key-files:
  created:
    - packages/portal/components/budget-alert-badge.tsx
    - packages/portal/components/usage-chart.tsx
    - packages/portal/components/provider-cost-chart.tsx
    - packages/portal/components/message-volume-chart.tsx
    - packages/portal/app/(dashboard)/usage/[tenantId]/page.tsx
    - packages/portal/app/(dashboard)/usage/page.tsx
  modified:
    - packages/portal/lib/queries.ts
    - packages/portal/components/nav.tsx

key-decisions:
  - "recharts was in package.json but not node_modules — installed with npm install --force due to ENOTEMPTY npm bug"
  - "Usage nav links to /usage index (tenant picker) not a hardcoded tenantId — prevents broken nav for operators managing multiple tenants"
  - "BudgetAlertBadge renders 'No limit set' (gray, neutral) for null budget_limit_usd — no false alarms"
  - "ProviderCostChart uses horizontal BarChart (layout='vertical') so long provider names don't clip on x-axis"
  - "getDateRange() computes 'This month' as first day of current month — not relative 30 days, matches calendar intuition"

patterns-established:
  - "Usage chart components follow empty state pattern with h-[200px] centered text"
  - "Chart Tooltip components typed with TooltipProps<number, string> and cast payload as domain interface"
  - "Time range selector implemented as native <select> (not shadcn Select) — simpler, no dependency on Select component state"

requirements-completed: [AGNT-07, PRTA-06]

# Metrics
duration: 10min
completed: 2026-03-23
---

# Phase 3 Plan 4: Usage & Cost Dashboard Summary

**Recharts cost dashboard with per-agent token usage, LLM provider breakdown, channel message volume, time range filtering, and color-coded budget alert badges**

## Performance

- **Duration:** ~10 min
- **Started:** 2026-03-23T21:39:11Z
- **Completed:** 2026-03-23T21:49:00Z
- **Tasks:** 2 of 2 complete (Task 1 auto + Task 2 human-verify approved)
- **Files modified:** 8

## Accomplishments
- Cost tracking dashboard at `/usage/[tenantId]` with 3 Recharts charts and 4 summary cards
- Budget alert system with color-coded badges (ok=green, warning=amber, exceeded=red)
- Time range selector driving all chart queries via TanStack Query with date-range params
- Responsive 2-column grid layout (single column on mobile)
- Portal builds cleanly with 14 routes including /usage and /usage/[tenantId]

## Task Commits

Each task was committed atomically:

1. **Task 1: Cost dashboard page with Recharts visualizations and budget alerts** - `6b0aee3` (chore: initial portal commit)

**Plan metadata:** (pending - docs commit)

## Files Created/Modified
- `packages/portal/components/budget-alert-badge.tsx` - Colored Badge for ok/warning/exceeded budget status
- `packages/portal/components/usage-chart.tsx` - Bar chart of total_tokens per agent (indigo #6366f1)
- `packages/portal/components/provider-cost-chart.tsx` - Horizontal bar chart of cost by LLM provider
- `packages/portal/components/message-volume-chart.tsx` - Bar chart of message count per channel
- `packages/portal/app/(dashboard)/usage/[tenantId]/page.tsx` - Full usage dashboard with time selector, charts, budget table
- `packages/portal/app/(dashboard)/usage/page.tsx` - Tenant picker index page
- `packages/portal/lib/queries.ts` - Added useUsageSummary, useUsageByProvider, useMessageVolume, useBudgetAlerts hooks
- `packages/portal/components/nav.tsx` - Added "Usage" nav link with BarChart2 icon

## Decisions Made
- recharts was in package.json but not installed in node_modules — fixed with `npm install recharts --force` (ENOTEMPTY npm race condition)
- Usage nav links to /usage (tenant picker) rather than a hardcoded tenant — works for operators with multiple tenants
- BudgetAlertBadge renders neutral "No limit set" for null budget — no false warnings
- ProviderCostChart uses horizontal bars so provider names don't truncate

## Deviations from Plan

### Auto-fixed Issues

**1. [Rule 3 - Blocking] Installed recharts (in package.json, missing from node_modules)**
- **Found during:** Task 1 (build verification)
- **Issue:** recharts listed in package.json but not installed in node_modules, causing "Module not found: Can't resolve 'recharts'" build error
- **Fix:** `npm install recharts --force` (--force required due to npm ENOTEMPTY rename bug)
- **Files modified:** package-lock.json
- **Verification:** Build passes with `/usage` and `/usage/[tenantId]` routes present
- **Committed in:** Already in portal initial commit

---

**Total deviations:** 1 auto-fixed (1 blocking — missing npm dependency)
**Impact on plan:** Single dependency install, no scope change.

## Issues Encountered
- Portal code was pre-seeded in a single "initial portal commit" at `6b0aee3` — all plan files already existed in portal git history. Task verified against this committed state, build confirmed passing.
- npm ENOTEMPTY race condition on recharts install required `--force` flag.

## User Setup Required
None — no external service configuration required for this plan.

## Next Phase Readiness
- Cost tracking dashboard complete, verified by operator, and building
- Phase 3 (Operator Experience) all 4 plans complete
- No blockers

---
*Phase: 03-operator-experience*
*Completed: 2026-03-23*

## Self-Check: PASSED

- FOUND: packages/portal/components/budget-alert-badge.tsx
- FOUND: packages/portal/components/usage-chart.tsx
- FOUND: packages/portal/components/provider-cost-chart.tsx
- FOUND: packages/portal/components/message-volume-chart.tsx
- FOUND: packages/portal/app/(dashboard)/usage/page.tsx
- FOUND: packages/portal/app/(dashboard)/usage/[tenantId]/page.tsx
- FOUND: b73f6bf (docs(03-04): complete usage & cost dashboard plan)
- Portal build: PASSED (14 routes, /usage and /usage/[tenantId] present)
