diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 3e7f76a..8d7e912 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -8,7 +8,7 @@ - Search by name/email - Filter by billing group -- Time range: 24h / 3d / 7d / 14d / 30d +- Time range: 24h / 3d / 7d / 14d / 30d / Cycle (default, from the billing cycle start). Spend, ranks, $/req and the charts all follow the selected range, over as many billing cycles as it spans. ### Stat Cards @@ -21,10 +21,10 @@ ### Charts -- **Daily Spend Trend** — area chart with avg line, provisional zone (last 2d), spike detection +- **Daily Spend Trend** — area chart with avg line, provisional zone (last 2d), cycle change marker, spike detection - **Model Cost Comparison** — table with $/request, relative multiplier (1x–8x+), color-coded - **Top Spenders** — horizontal bar chart, top 8 -- **Daily Spend by User** — stacked bar, top 6 + Others, clickable legend +- **Daily Spend by User** — stacked bar, top 6 + Others, clickable legend, cycle change marker ### Members Table @@ -57,10 +57,11 @@ - Name, email, role, billing group link - Profile badges (same as dashboard) +- Time range: 24h / 3d / 7d / 14d / 30d / Cycle (default) ### KPI Cards -- **Cycle Spend** — total $ in billing cycle, $/day +- **Spend** — total $ in time range, $/day - **$/Req** — cost per agent request - **Agent Reqs** — total requests in time range - **Diffs Accepted** — % of agent diffs accepted (accepts/applies), raw counts @@ -86,6 +87,10 @@ **Team analytics — adoption, efficiency, trends.** +### Controls + +- Time range: 24h / 3d / 7d / 14d / 30d / Cycle (default), all sections except Plan Exhaustion and Client Versions + ### Stat Cards - Avg DAU, Commands total, Agent lines accepted, Tab lines accepted, MCP tools count diff --git a/src/app/api/analytics/route.ts b/src/app/api/analytics/route.ts index 34b923e..c8929a0 100644 --- a/src/app/api/analytics/route.ts +++ b/src/app/api/analytics/route.ts @@ -12,6 +12,7 @@ import { getUsersByClientVersion, getPlanExhaustionStats, getModelEfficiency, + getCycleWindowDays, getGroupsWithMembers, getRepoAIAttribution, } from "@/lib/data"; @@ -39,7 +40,8 @@ function resolveGroupEmails(group: string): string[] | undefined { export function GET(request: Request) { const { searchParams } = new URL(request.url); - const days = parseInt(searchParams.get("days") ?? "30", 10); + const param = searchParams.get("days") ?? "30"; + const days = param === "cycle" ? getCycleWindowDays() : parseInt(param, 10) || 30; const group = searchParams.get("group") ?? "all"; const emails = resolveGroupEmails(group); @@ -56,7 +58,7 @@ export function GET(request: Request) { clientVersions: getAnalyticsClientVersionsSummary(), versionUsers: getUsersByClientVersion(), planExhaustion: getPlanExhaustionStats(emails), - modelEfficiency: getModelEfficiency(emails), + modelEfficiency: getModelEfficiency(emails, days), repoAttribution: getRepoAIAttribution(days, emails), }); } catch { diff --git a/src/app/api/stats/route.ts b/src/app/api/stats/route.ts index 5096a2d..911373c 100644 --- a/src/app/api/stats/route.ts +++ b/src/app/api/stats/route.ts @@ -5,8 +5,9 @@ export const dynamic = "force-dynamic"; export function GET(request: Request) { const url = new URL(request.url); - const days = parseInt(url.searchParams.get("days") ?? "30", 10); + const param = url.searchParams.get("days") ?? "30"; + const range = param === "cycle" ? "cycle" : parseInt(param, 10) || 30; - const dashboard = getFullDashboard(days); + const dashboard = getFullDashboard(range); return NextResponse.json(dashboard); } diff --git a/src/app/api/users/[email]/route.ts b/src/app/api/users/[email]/route.ts index a94aaff..da02f03 100644 --- a/src/app/api/users/[email]/route.ts +++ b/src/app/api/users/[email]/route.ts @@ -7,9 +7,10 @@ export function GET(request: Request, { params }: { params: Promise<{ email: str return params.then((p) => { const email = decodeURIComponent(p.email); const url = new URL(request.url); - const days = parseInt(url.searchParams.get("days") ?? "30", 10); + const param = url.searchParams.get("days") ?? "30"; + const range = param === "cycle" ? "cycle" : parseInt(param, 10) || 30; - const stats = getUserStats(email, days); + const stats = getUserStats(email, range); return NextResponse.json(stats); }); } diff --git a/src/app/dashboard-client.tsx b/src/app/dashboard-client.tsx index 59518fc..b6b853b 100644 --- a/src/app/dashboard-client.tsx +++ b/src/app/dashboard-client.tsx @@ -10,6 +10,13 @@ import { MembersTable } from "@/components/dashboard/members-table"; import Link from "next/link"; import { shortModel } from "@/lib/format-utils"; import { ExpandableCard } from "@/components/expandable-card"; +import { DEFAULT_RANGE } from "@/lib/time-range"; +import { isHourKey } from "@/lib/date-utils"; +import { + TimeRangeSelector, + formatTimeLabel, + type TimeRange, +} from "@/components/time-range-selector"; interface BillingGroupWithMembers { id: string; @@ -28,19 +35,6 @@ interface ModelCost { emails: string[]; } -const TIME_RANGES = [ - { label: "24h", days: 1 }, - { label: "3d", days: 3 }, - { label: "7d", days: 7 }, - { label: "14d", days: 14 }, - { label: "30d", days: 30 }, -] as const; - -function formatTimeLabel(days: number): string { - if (days === 1) return "24h"; - return `${days}d`; -} - function fmt(n: number): string { if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`; @@ -58,14 +52,12 @@ interface SpendBreakdownRow { interface DashboardClientProps { initialData: FullDashboard; + initialRange: TimeRange; } -export function DashboardClient({ initialData }: DashboardClientProps) { +export function DashboardClient({ initialData: data, initialRange: range }: DashboardClientProps) { const searchParams = useSearchParams(); - const [data, setData] = useState(initialData); - const [days, setDays] = useState(30); const [search, setSearch] = useState(""); - const [loading, setLoading] = useState(false); const [sortCol, setSortCol] = useState("spend"); const [sortAsc, setSortAsc] = useState(false); const [badgeFilter, setBadgeFilter] = useState(null); @@ -114,11 +106,6 @@ export function DashboardClient({ initialData }: DashboardClientProps) { ) .catch(() => {}); } - const saved = localStorage.getItem("dashboard-days"); - if (saved) { - const parsed = parseInt(saved, 10); - if (parsed !== 30) changeTimeRange(parsed); - } }, []); const groupEmailSet = useMemo(() => { @@ -269,20 +256,8 @@ export function DashboardClient({ initialData }: DashboardClientProps) { ); }, [stats.rankedUsers, search]); - async function changeTimeRange(newDays: number) { - setDays(newDays); - localStorage.setItem("dashboard-days", String(newDays)); - setLoading(true); - try { - const res = await fetch(`/api/stats?days=${newDays}`); - const newData: FullDashboard = await res.json(); - setData(newData); - } finally { - setLoading(false); - } - } - - const timeLabel = formatTimeLabel(days); + const days = data.days; + const timeLabel = formatTimeLabel(range); const isSearching = search.trim().length > 0 || selectedGroup !== "all" || @@ -290,7 +265,6 @@ export function DashboardClient({ initialData }: DashboardClientProps) { exhaustionFilter !== null || modelFilter !== null; const totalLines = stats.dailyTeamActivity.reduce((s, d) => s + d.total_lines_added, 0); - const effectiveDays = Math.min(days, stats.cycleDays); const cycleStartDate = new Date(stats.cycleStart); const cycleEndDate = stats.cycleEnd ? new Date(stats.cycleEnd) @@ -328,20 +302,28 @@ export function DashboardClient({ initialData }: DashboardClientProps) { return data.dailySpendBreakdown.filter((r) => filteredEmails.has(r.email)); }, [isSearching, data.dailySpendBreakdown, filteredEmails]); + // the 24h range comes back hour by hour: keep every hour, empty ones included + const hourKeys = useMemo( + () => + isHourKey(data.teamDailySpend[0]?.date ?? "") ? data.teamDailySpend.map((r) => r.date) : null, + [data.teamDailySpend], + ); + const filteredTeamDailySpend = useMemo(() => { if (!isSearching) return data.teamDailySpend; const byDate = new Map(); for (const r of filteredBreakdown) { byDate.set(r.date, (byDate.get(r.date) ?? 0) + r.spend_cents); } + if (hourKeys) return hourKeys.map((date) => ({ date, spend_cents: byDate.get(date) ?? 0 })); return [...byDate.entries()] .sort(([a], [b]) => a.localeCompare(b)) .map(([date, spend_cents]) => ({ date, spend_cents })); - }, [isSearching, data.teamDailySpend, filteredBreakdown]); + }, [isSearching, data.teamDailySpend, filteredBreakdown, hourKeys]); const dailySpendData = useMemo(() => { - return buildDailySpendData(filteredBreakdown); - }, [filteredBreakdown]); + return buildDailySpendData(filteredBreakdown, hourKeys); + }, [filteredBreakdown, hourKeys]); return (
@@ -365,6 +347,19 @@ export function DashboardClient({ initialData }: DashboardClientProps) { )}
+
+ {isSearching ? `${filteredUsers.length} / ` : ""} + {stats.totalMembers} members + {selectedGroup !== "all" && ( + + )} +
{groups.length > 1 && ( )} -
- {TIME_RANGES.map((r) => ( - - ))} -
+ @@ -338,7 +331,7 @@ export function InsightsClient({ value={dauSummary.avgDau.toString()} sub={`Peak: ${dauSummary.peakDau}`} /> - + @@ -364,7 +357,7 @@ export function InsightsClient({ @@ -591,7 +584,7 @@ export function InsightsClient({ {/* Tables Row: Repo Attribution + File Extensions */}
- + {data.repoAttribution?.length > 0 ? ( (() => { const grandTotal = data.repoAttribution.reduce((s, r) => s + r.total_lines, 0) || 1; @@ -968,11 +961,11 @@ function PlanExhaustionSection({ function ModelEfficiencySection({ data, - days, + windowLabel, groupName, }: { data: ModelEfficiencyEntry[]; - days: number; + windowLabel: string; groupName?: string; }) { const [showDetail, setShowDetail] = useState(false); @@ -1006,8 +999,8 @@ function ModelEfficiencySection({ const maxSpend = bySpend[0]?.total_spend_usd ?? 1; const subtitle = groupName - ? `${groupName} · Last ${days} days` - : `Models with $30+ spend · Last ${days} days`; + ? `${groupName} · ${windowLabel}` + : `Models with $30+ spend · ${windowLabel}`; return (
diff --git a/src/app/insights/page.tsx b/src/app/insights/page.tsx index 518e5b7..dc0188a 100644 --- a/src/app/insights/page.tsx +++ b/src/app/insights/page.tsx @@ -13,32 +13,40 @@ import { getPlanExhaustionStats, getGroupsWithMembers, getRepoAIAttribution, + getCycleWindowDays, } from "@/lib/data"; +import { parseRange } from "@/lib/time-range"; import { InsightsClient } from "./insights-client"; export const dynamic = "force-dynamic"; -export default function InsightsPage() { +export default async function InsightsPage({ + searchParams, +}: { + searchParams: Promise<{ range?: string }>; +}) { + const range = parseRange((await searchParams).range); try { + const days = range === "cycle" ? getCycleWindowDays() : range; const data = { - dau: getAnalyticsDAU(30), - modelSummary: getAnalyticsModelUsageSummary(30), - modelTrend: getAnalyticsModelUsageTrend(30), - agentEdits: getAnalyticsAgentEditsTrend(30), - tabs: getAnalyticsTabsTrend(30), - mcp: getAnalyticsMCPSummary(30), - commands: getAnalyticsCommandsSummary(30), - fileExtensions: getAnalyticsFileExtensionsSummary(30), + dau: getAnalyticsDAU(days), + modelSummary: getAnalyticsModelUsageSummary(days), + modelTrend: getAnalyticsModelUsageTrend(days), + agentEdits: getAnalyticsAgentEditsTrend(days), + tabs: getAnalyticsTabsTrend(days), + mcp: getAnalyticsMCPSummary(days), + commands: getAnalyticsCommandsSummary(days), + fileExtensions: getAnalyticsFileExtensionsSummary(days), clientVersions: getAnalyticsClientVersionsSummary(), versionUsers: getUsersByClientVersion(), - modelEfficiency: getModelEfficiency(), + modelEfficiency: getModelEfficiency(undefined, days), planExhaustion: getPlanExhaustionStats(), - repoAttribution: getRepoAIAttribution(30), + repoAttribution: getRepoAIAttribution(days), }; const groups = getGroupsWithMembers(); - return ; + return ; } catch { return (
diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 192028b..e561b5e 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,3 +1,4 @@ +import { Suspense } from "react"; import type { Metadata } from "next"; import Image from "next/image"; import Link from "next/link"; @@ -27,7 +28,9 @@ export default async function RootLayout({ children }: { children: React.ReactNo Cursor Tracker - + + +
diff --git a/src/app/page.tsx b/src/app/page.tsx index 95bf64e..e4e15cc 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,15 +1,21 @@ import { Suspense } from "react"; import { getFullDashboard } from "@/lib/data"; +import { parseRange } from "@/lib/time-range"; import { DashboardClient } from "./dashboard-client"; export const dynamic = "force-dynamic"; -export default function HomePage() { +export default async function HomePage({ + searchParams, +}: { + searchParams: Promise<{ range?: string }>; +}) { + const range = parseRange((await searchParams).range); try { - const data = getFullDashboard(30); + const data = getFullDashboard(range); return ( - + ); } catch { diff --git a/src/app/users/[email]/page.tsx b/src/app/users/[email]/page.tsx index fdf53a3..847d871 100644 --- a/src/app/users/[email]/page.tsx +++ b/src/app/users/[email]/page.tsx @@ -1,31 +1,37 @@ import Link from "next/link"; import { getUserStats } from "@/lib/data"; +import { overviewHref, parseRange } from "@/lib/time-range"; import { UserDetailClient } from "./user-detail-client"; export const dynamic = "force-dynamic"; interface PageProps { params: Promise<{ email: string }>; + searchParams: Promise<{ range?: string }>; } -export default async function UserPage({ params }: PageProps) { +export default async function UserPage({ params, searchParams }: PageProps) { const { email } = await params; const decodedEmail = decodeURIComponent(email); + const range = parseRange((await searchParams).range); let stats; try { - stats = getUserStats(decodedEmail, 30); + stats = getUserStats(decodedEmail, range); } catch { return (

User Not Found

No data found for {decodedEmail}

- + ← Back to overview
); } - return ; + return ; } diff --git a/src/app/users/[email]/user-detail-client.tsx b/src/app/users/[email]/user-detail-client.tsx index 09722e4..684c427 100644 --- a/src/app/users/[email]/user-detail-client.tsx +++ b/src/app/users/[email]/user-detail-client.tsx @@ -2,13 +2,21 @@ import Link from "next/link"; import { SpendTrendChart } from "@/components/charts/spend-trend-chart"; -import { formatDateShort } from "@/lib/date-utils"; +import { formatDateShort, isHourKey } from "@/lib/date-utils"; import { shortModel } from "@/lib/format-utils"; import { ExpandableCard } from "@/components/expandable-card"; +import { + TimeRangeSelector, + formatTimeLabel, + type TimeRange, +} from "@/components/time-range-selector"; import type { Anomaly } from "@/lib/types"; +import { overviewHref } from "@/lib/time-range"; import type { UsageBadge, SpendBadge, ContextBadge, AdoptionBadge } from "@/lib/data"; interface UserStats { + windowSpendCents: number; + cycleStarts: string[]; member: | { name: string; email: string; role: string; first_seen: string; last_seen: string } | undefined; @@ -32,7 +40,7 @@ interface UserStats { }>; modelBreakdown: Array<{ model: string; days_used: number; total_requests: number }>; anomalies: Anomaly[]; - dailySpend: Array<{ date: string; spend_cents: number }>; + dailySpend: Array<{ date: string; spend_cents: number; requests?: number }>; usageEventsSummary: Array<{ model: string; requests: number; @@ -107,6 +115,7 @@ interface UserStats { interface UserDetailClientProps { email: string; stats: UserStats; + initialRange: TimeRange; } function fmt(n: number): string { @@ -189,29 +198,37 @@ const BADGE_STYLES: Record sum + d.agent_requests, 0); + const timeLabel = formatTimeLabel(range); + // the 24h range counts the usage events of each hour, daily activity cannot start at an exact hour + const totalAgentRequests = + range === 1 + ? stats.dailySpend.reduce((sum, d) => sum + (d.requests ?? 0), 0) + : stats.dailyActivity.reduce((sum, d) => sum + d.agent_requests, 0); const cycleStart = currentSpend?.cycle_start; - const cycleAgentRequests = cycleStart - ? stats.dailyActivity - .filter((d) => d.date >= cycleStart) - .reduce((sum, d) => sum + d.agent_requests, 0) - : totalAgentRequests; - const billedCycleCents = currentSpend?.spend_cents ?? 0; - const cycleSpendDollars = billedCycleCents / 100; + const windowSpendDollars = stats.windowSpendCents / 100; const dollarsPerReq = - cycleAgentRequests > 0 ? (billedCycleCents / cycleAgentRequests / 100).toFixed(2) : null; + totalAgentRequests > 0 ? (stats.windowSpendCents / totalAgentRequests / 100).toFixed(2) : null; const cycleDaysElapsed = cycleStart ? Math.max( 1, Math.ceil((Date.now() - new Date(`${cycleStart}T12:00:00Z`).getTime()) / 86_400_000), ) : Math.max(1, stats.dailySpend.length); - const dailyAvgSpend = cycleSpendDollars / cycleDaysElapsed; + const windowDays = range === "cycle" ? cycleDaysElapsed : range; + const dailyAvgSpend = windowSpendDollars / windowDays; - const mergedDailyData = buildMergedDailyData(stats.dailySpend, stats.dailyActivity); + // the 24h range charts hours; the table below stays per day + const spendByDay = new Map(); + for (const d of stats.dailySpend) { + const day = d.date.slice(0, 10); + spendByDay.set(day, (spendByDay.get(day) ?? 0) + d.spend_cents); + } + const dailySpendRows = isHourKey(stats.dailySpend[0]?.date ?? "") + ? [...spendByDay].map(([date, spend_cents]) => ({ date, spend_cents })) + : stats.dailySpend; + const mergedDailyData = buildMergedDailyData(dailySpendRows, stats.dailyActivity); const hasUsageEvents = stats.usageEventsSummary.length > 0; const userBadges: string[] = []; @@ -223,7 +240,7 @@ export function UserDetailClient({ email, stats }: UserDetailClientProps) { return (
- + ← Back
@@ -258,12 +275,15 @@ export function UserDetailClient({ email, stats }: UserDetailClientProps) { )}

+
+ +
- + { const activity = stats.dailyActivity.find((a) => a.date === d.date); return { ...d, - agent_requests: activity?.agent_requests, + agent_requests: activity?.agent_requests ?? d.requests, lines_added: activity?.lines_added, lines_deleted: activity?.lines_deleted, }; diff --git a/src/components/charts/cycle-marker.tsx b/src/components/charts/cycle-marker.tsx new file mode 100644 index 0000000..d884e20 --- /dev/null +++ b/src/components/charts/cycle-marker.tsx @@ -0,0 +1,44 @@ +import { usePlotArea } from "recharts"; + +export const AXIS_STROKE = "#71717a"; +// the cycle change line sits between the widget border (zinc-800) and the "previous cycle" label (zinc-600) +export const CYCLE_STROKE = "#3f3f46"; +export const CYCLE_STROKE_WIDTH = 2; +// the "previous cycle" label is dimmer (zinc-600) than the new one +const CYCLE_TEXT = "#52525b"; + +// approximate widths of the labels, to leave out one that would run past the plot (over the axis) +const PREVIOUS_WIDTH = 84; +const NEW_WIDTH = 56; + +// labels of a billing cycle change, drawn above the plot on each side of the line: +// the old cycle in the dimmer colour, the new one in the axis text colour +export function CycleLabels({ viewBox }: { viewBox?: { x?: number; y?: number } }) { + const x = viewBox?.x ?? 0; + const y = viewBox?.y ?? 0; + const plot = usePlotArea(); + const left = plot?.x ?? 0; + const right = plot ? plot.x + plot.width : Infinity; + return ( + + + {x - 8 - PREVIOUS_WIDTH >= left && ( + + previous cycle + + )} + {x + 8 + NEW_WIDTH <= right && ( + + new cycle + + )} + + ); +} diff --git a/src/components/charts/daily-spend-chart.tsx b/src/components/charts/daily-spend-chart.tsx index a422167..a04b032 100644 --- a/src/components/charts/daily-spend-chart.tsx +++ b/src/components/charts/daily-spend-chart.tsx @@ -1,8 +1,20 @@ "use client"; -import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from "recharts"; +import { + BarChart, + Bar, + XAxis, + YAxis, + Tooltip, + ResponsiveContainer, + CartesianGrid, + DefaultZIndexes, + ZIndexLayer, + usePlotArea, +} from "recharts"; import type { DailySpendDataPoint } from "@/app/dashboard-client"; -import { formatDateTick, formatDateLabel } from "@/lib/date-utils"; +import { formatDateTick, formatDateLabel, isHourKey, isTickHour } from "@/lib/date-utils"; +import { CYCLE_STROKE, CYCLE_STROKE_WIDTH, CycleLabels } from "./cycle-marker"; const COLORS = ["#3b82f6", "#8b5cf6", "#f59e0b", "#10b981", "#ef4444", "#ec4899"]; const OTHERS_COLOR = "#52525b"; @@ -10,9 +22,36 @@ const OTHERS_COLOR = "#52525b"; interface DailySpendChartProps { data: { points: DailySpendDataPoint[]; topNames: string[] }; onNameClick?: (name: string) => void; + cycleStarts?: string[]; } -export function DailySpendChart({ data, onNameClick }: DailySpendChartProps) { +// bars sit in equal bands, so a cycle change is the edge between two bands +function CycleBoundaries({ boundaries, count }: { boundaries: number[]; count: number }) { + const plot = usePlotArea(); + if (!plot) return null; + return ( + + {boundaries.map((i, k) => { + const x = plot.x + (i * plot.width) / count; + return ( + + + + + ); + })} + + ); +} + +export function DailySpendChart({ data, onNameClick, cycleStarts = [] }: DailySpendChartProps) { const { points, topNames } = data; if (!points.length) { @@ -29,13 +68,26 @@ export function DailySpendChart({ data, onNameClick }: DailySpendChartProps) { colorMap.set(key, key === "Others" ? OTHERS_COLOR : (COLORS[i % COLORS.length] ?? "#71717a")); }); + const hourly = isHourKey(points[0]?.date ?? ""); + const boundaries = hourly + ? [] + : cycleStarts.map((start) => points.findIndex((p) => p.date >= start)).filter((i) => i > 0); + return (
-

Daily Spend by Top Users

+

+ {hourly ? "Hourly" : "Daily"} Spend by Top Users +

- + - + p.date).filter(isTickHour), interval: 0 })} + /> ))} +
diff --git a/src/components/charts/spend-bar-chart.tsx b/src/components/charts/spend-bar-chart.tsx index 45c64d7..1969f6c 100644 --- a/src/components/charts/spend-bar-chart.tsx +++ b/src/components/charts/spend-bar-chart.tsx @@ -2,6 +2,7 @@ import { useCallback, useState } from "react"; import { useRouter } from "next/navigation"; +import { userHref, type TimeRange } from "@/lib/time-range"; import { BarChart, Bar, @@ -18,6 +19,8 @@ interface SpendBarChartProps { data: Array<{ email: string; name: string; spend_cents: number; spend_rank: number }>; highlightEmail?: string; expanded?: boolean; + timeLabel: string; + range: TimeRange; } const TOOLTIP_STYLE = { @@ -35,7 +38,13 @@ const BAR_HOVER_COLOR = "#60a5fa"; const HIGHLIGHT_COLOR = "#f59e0b"; const HIGHLIGHT_HOVER_COLOR = "#fbbf24"; -export function SpendBarChart({ data, highlightEmail, expanded }: SpendBarChartProps) { +export function SpendBarChart({ + data, + highlightEmail, + expanded, + timeLabel, + range, +}: SpendBarChartProps) { const router = useRouter(); const [hoveredIndex, setHoveredIndex] = useState(null); @@ -50,7 +59,7 @@ export function SpendBarChart({ data, highlightEmail, expanded }: SpendBarChartP const handleBarClick = useCallback( (entry: (typeof chartData)[number]) => { - router.push(`/users/${encodeURIComponent(entry.email)}`); + router.push(userHref(entry.email, range)); }, [router], ); @@ -67,7 +76,7 @@ export function SpendBarChart({ data, highlightEmail, expanded }: SpendBarChartP className={`bg-zinc-900 rounded-lg border border-zinc-800 p-4 ${expanded ? "h-full flex flex-col" : ""}`} >

- Top Spenders (Current Cycle) + Top Spenders ({timeLabel})

diff --git a/src/components/charts/spend-trend-chart.tsx b/src/components/charts/spend-trend-chart.tsx index 40bbdb6..ce25554 100644 --- a/src/components/charts/spend-trend-chart.tsx +++ b/src/components/charts/spend-trend-chart.tsx @@ -10,9 +10,10 @@ import { ResponsiveContainer, CartesianGrid, ReferenceLine, - ReferenceArea, + DefaultZIndexes, } from "recharts"; -import { formatDateTick, formatDateLabel } from "@/lib/date-utils"; +import { formatDateTick, formatDateLabel, isHourKey, isTickHour } from "@/lib/date-utils"; +import { AXIS_STROKE, CYCLE_STROKE, CYCLE_STROKE_WIDTH, CycleLabels } from "./cycle-marker"; interface SpendDataPoint { date: string; @@ -24,8 +25,8 @@ interface SpendDataPoint { interface SpendTrendChartProps { data: Array; - selectedDays?: number; avgPerDay?: number; + cycleStarts?: string[]; } function fmtDollars(v: number): string { @@ -41,7 +42,7 @@ const TOOLTIP_STYLE = { color: "#fafafa", } as const; -export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendChartProps) { +export function SpendTrendChart({ data, avgPerDay, cycleStarts = [] }: SpendTrendChartProps) { if (!data.length) { return (
@@ -58,6 +59,7 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha const costPerReq = d.agent_requests && d.agent_requests > 0 ? spend / d.agent_requests : undefined; return { + idx: i, date: d.date, spend, change, @@ -71,27 +73,33 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha const hasCostPerReq = chartData.some((d) => d.costPerReq != null); - const provisionalDays = 2; + const hourly = isHourKey(data[0]?.date ?? ""); + const provisionalDays = hourly ? 1 : 2; const provisionalStart = chartData.length > provisionalDays ? chartData[chartData.length - provisionalDays]?.date : undefined; - const cutoffDate = - selectedDays && selectedDays < data.length ? data[data.length - selectedDays]?.date : undefined; + // a new cycle starts between two days: the line sits halfway between them + const cycleLines = hourly + ? [] + : cycleStarts + .map((start) => chartData.findIndex((d) => d.date >= start)) + .filter((i) => i > 0) + .map((i) => i - 0.5); - const avg = avgPerDay ?? chartData.reduce((s, d) => s + d.spend, 0) / (chartData.length || 1); + const step = chartData.length <= 14 ? 1 : Math.floor(chartData.length / 10) + 1; + const tickIdx = chartData + .filter((d) => (hourly ? isTickHour(d.date) : d.idx % step === 0)) + .map((d) => d.idx); - const dimEndDate = - cutoffDate && data.length > 0 - ? data[Math.max(0, data.length - (selectedDays ?? 0) - 1)]?.date - : undefined; + const total = chartData.reduce((s, d) => s + d.spend, 0); + const avg = hourly ? total / 24 : (avgPerDay ?? total / (chartData.length || 1)); return (
-

Daily Spend

- {data.length} days of data +

{hourly ? "Hourly" : "Daily"} Spend

spend @@ -104,21 +112,28 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha )} {provisionalStart && ( - Last {provisionalDays}d may be partial · daily shape from events, totals match billing + {hourly + ? "Current hour may be partial · hourly shape from events, totals match billing" + : `Last ${provisionalDays}d may be partial · daily shape from events, totals match billing`} )}
- + formatDateTick(chartData[i]?.date ?? "")} /> - + {hasCostPerReq && ( { + content={({ active, payload }) => { if (!active || !payload?.length) return null; const pt = payload[0]?.payload as (typeof chartData)[0] | undefined; if (!pt) return null; - const isInRange = !cutoffDate || pt.date >= cutoffDate; const isProvisional = provisionalStart != null && pt.date >= provisionalStart; const changeColor = pt.change > 0 ? "#ef4444" : pt.change < 0 ? "#22c55e" : "#a1a1aa"; const changeSign = pt.change > 0 ? "+" : ""; return (
- {formatDateLabel(String(label))} - {!isInRange && (context)} + {formatDateLabel(pt.date)} {isProvisional && (partial)}
@@ -154,11 +167,11 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha {pt.change !== 0 && (
{changeSign} - {pt.changePct.toFixed(0)}% vs prev day + {pt.changePct.toFixed(0)}% vs prev {hourly ? "hour" : "day"}
)}
- avg ${Math.round(avg).toLocaleString()}{" "} + avg {fmtDollars(avg)}{" "} avg ? "#ef4444" : "#22c55e" }}> ({pt.spend > avg ? "+" : ""} {(((pt.spend - avg) / avg) * 100).toFixed(0)}%) @@ -205,28 +218,17 @@ export function SpendTrendChart({ data, selectedDays, avgPerDay }: SpendTrendCha ); }} /> - {dimEndDate && cutoffDate && ( - ( + } /> - )} - {provisionalStart && ( - - )} + ))} void; highlightEmail?: string; timeLabel: string; + range: TimeRange; badgeFilter: string | null; onBadgeFilter: (badge: string | null) => void; } @@ -293,9 +296,11 @@ export function MembersTable({ onSort, highlightEmail, timeLabel, + range, badgeFilter, onBadgeFilter, }: MembersTableProps) { + const router = useRouter(); const sortLabel = sortCol === "spend" ? "Spend" @@ -375,14 +380,14 @@ export function MembersTable({ className="text-right px-4 py-3 font-medium cursor-pointer hover:text-zinc-300 select-none" onClick={() => onSort("spend")} > - Spend (cycle) + Spend onSort("reqs")} > - Reqs ({timeLabel}) + Reqs - Lines ({timeLabel}) + Lines @@ -400,7 +405,9 @@ export function MembersTable({ className="text-right px-4 py-3 font-medium cursor-pointer hover:text-zinc-300 select-none" onClick={() => onSort("cpr")} > - $/req + + $/req + Model @@ -414,7 +421,7 @@ export function MembersTable({ Ranks @@ -429,7 +436,11 @@ export function MembersTable({ return ( { + if ((e.target as HTMLElement).closest("a, button")) return; + router.push(userHref(row.email, range)); + }} + className={`border-b border-zinc-800/50 transition-colors cursor-pointer group ${ isHighlighted ? "bg-blue-500/10 ring-1 ring-blue-500/30" : "hover:bg-zinc-800/30" @@ -442,7 +453,7 @@ export function MembersTable({ {row.name} @@ -557,7 +568,7 @@ export function MembersTable({
${row.spend_rank} @@ -571,8 +582,8 @@ export function MembersTable({ → diff --git a/src/components/nav-links.tsx b/src/components/nav-links.tsx index 5bccc6a..829c091 100644 --- a/src/components/nav-links.tsx +++ b/src/components/nav-links.tsx @@ -1,26 +1,27 @@ "use client"; import Link from "next/link"; -import { usePathname } from "next/navigation"; +import { usePathname, useSearchParams } from "next/navigation"; const LINKS = [ - { href: "/", label: "Overview" }, - { href: "/insights", label: "Insights" }, + { href: "/", label: "Overview", ranged: true }, + { href: "/insights", label: "Insights", ranged: true }, { href: "/anomalies", label: "Anomalies" }, { href: "/settings", label: "Settings" }, ]; export function NavLinks() { const pathname = usePathname(); + const range = useSearchParams().get("range"); return ( <> - {LINKS.map(({ href, label }) => { + {LINKS.map(({ href, label, ranged }) => { const active = href === "/" ? pathname === "/" : pathname.startsWith(href); return ( = [ + { label: "24h", days: 1 }, + { label: "3d", days: 3 }, + { label: "7d", days: 7 }, + { label: "14d", days: 14 }, + { label: "30d", days: 30 }, + { label: "Cycle", days: "cycle" }, +]; + +export function formatTimeLabel(range: TimeRange): string { + if (range === "cycle") return "cycle"; + return range === 1 ? "24h" : `${range}d`; +} + +export function TimeRangeSelector({ value }: { value: TimeRange }) { + const router = useRouter(); + const pathname = usePathname(); + const searchParams = useSearchParams(); + const [pending, startTransition] = useTransition(); + + function select(range: TimeRange) { + const params = new URLSearchParams(searchParams); + if (range === DEFAULT_RANGE) params.delete("range"); + else params.set("range", String(range)); + const query = params.toString(); + startTransition(() => router.replace(query ? `${pathname}?${query}` : pathname)); + } + + return ( +
+ {TIME_RANGES.map((r) => ( + + ))} +
+ ); +} diff --git a/src/lib/data/sqlite.ts b/src/lib/data/sqlite.ts index 3aa0c52..bcb5553 100644 --- a/src/lib/data/sqlite.ts +++ b/src/lib/data/sqlite.ts @@ -959,22 +959,127 @@ export type { CycleSummaryData, }; -export function getFullDashboard(days: number = 7): FullDashboard { - const db = getDb(); - const dateFilter = `-${days} days`; +export type TimeRange = number | "cycle"; - const totalMembers = - (db.prepare("SELECT COUNT(*) as c FROM members WHERE is_removed = 0").get() as { c: number }) - ?.c ?? 0; +const DAY_MS = 86_400_000; +const HOUR_MS = 3_600_000; - const activeMembers = - ( - db - .prepare( - "SELECT COUNT(DISTINCT email) as c FROM daily_usage WHERE is_active = 1 AND date >= date('now', ?)", - ) - .get(dateFilter) as { c: number } - )?.c ?? 0; +function dayStart(daysAgo: number): string { + return new Date(Date.now() - daysAgo * DAY_MS).toISOString().slice(0, 10); +} + +// the 24h range measures exactly the last 24 hours... +const last24HoursStart = () => Date.now() - 24 * HOUR_MS; + +// ...and charts it one point per hour, keyed "YYYY-MM-DDTHH" (UTC), from the hour of the cutoff +// to the current hour (25 points, both ends partial) +const chartHourKeys = (sinceMs: number) => + Array.from({ length: 25 }, (_, i) => new Date(sinceMs + i * HOUR_MS).toISOString().slice(0, 13)); + +// Number of days back from today that lands on the start of the current billing cycle. +export function getCycleWindowDays(): number { + const row = getDb().prepare("SELECT MAX(cycle_start) as cs FROM spending").get() as { + cs: string | null; + }; + const start = (row?.cs ?? getMetadata("cycle_start"))?.slice(0, 10); + if (!start) return 30; + const elapsed = Date.parse(`${dayStart(0)}T00:00:00.000Z`) - Date.parse(`${start}T00:00:00.000Z`); + return Math.max(1, Math.round(elapsed / DAY_MS)); +} + +function getCycleStarts(db: Database.Database): string[] { + return ( + db.prepare("SELECT DISTINCT cycle_start FROM spending ORDER BY cycle_start").all() as Array<{ + cycle_start: string; + }> + ).map((r) => r.cycle_start); +} + +// Spend per user is billed per cycle, so a window is estimated by sharing each cycle's billed +// total across the usage events that fall inside the window. +function spendSince(db: Database.Database, sinceMs: number, hourly = false) { + const bucket = hourly + ? "strftime('%Y-%m-%dT%H', CAST(timestamp AS INTEGER) / 1000, 'unixepoch')" + : "date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch')"; + const names = new Map( + (db.prepare("SELECT email, name FROM members").all() as Array<{ email: string; name: string }>).map( + (m) => [m.email, m.name], + ), + ); + const totals = new Map(); + const daily: Array<{ date: string; email: string; name: string; spend_cents: number }> = []; + const starts = getCycleStarts(db); + const now = Date.now(); + + starts.forEach((start, i) => { + const startMs = Date.parse(`${start}T12:00:00.000Z`); + const next = starts[i + 1]; + const endMs = next ? Date.parse(`${next}T12:00:00.000Z`) : Number.MAX_SAFE_INTEGER; + if (endMs <= sinceMs) return; + + const billed = db + .prepare("SELECT email, spend_cents FROM spending WHERE cycle_start = ?") + .all(start) as Array<{ email: string; spend_cents: number }>; + const rawByUser = new Map( + ( + db + .prepare( + `SELECT user_email as email, SUM(total_cents) as t FROM usage_events + WHERE CAST(timestamp AS INTEGER) >= ? AND CAST(timestamp AS INTEGER) < ? + GROUP BY user_email`, + ) + .all(startMs, endMs) as Array<{ email: string; t: number }> + ).map((r) => [r.email, r.t]), + ); + const from = Math.max(startMs, sinceMs); + const rawDays = db + .prepare( + `SELECT user_email as email, ${bucket} as date, + SUM(total_cents) as t + FROM usage_events + WHERE CAST(timestamp AS INTEGER) >= ? AND CAST(timestamp AS INTEGER) < ? + GROUP BY user_email, date`, + ) + .all(from, endMs) as Array<{ email: string; date: string; t: number }>; + + const billedBy = new Map(billed.map((b) => [b.email, b.spend_cents])); + const windowRaw = new Map(); + for (const r of rawDays) { + windowRaw.set(r.email, (windowRaw.get(r.email) ?? 0) + r.t); + const spend = billedBy.get(r.email) ?? 0; + const rawTotal = rawByUser.get(r.email) ?? 0; + if (spend > 0 && rawTotal > 0) { + daily.push({ + date: r.date, + email: r.email, + name: names.get(r.email) ?? r.email, + spend_cents: Math.round((r.t * spend) / rawTotal), + }); + } + } + + const coveredEnd = Math.min(now, endMs); + const share = Math.min(1, Math.max(0, (coveredEnd - from) / Math.max(1, coveredEnd - startMs))); + for (const { email, spend_cents } of billed) { + if (spend_cents <= 0) continue; + const rawTotal = rawByUser.get(email) ?? 0; + const part = + sinceMs <= startMs + ? spend_cents + : rawTotal > 0 + ? ((windowRaw.get(email) ?? 0) * spend_cents) / rawTotal + : spend_cents * share; + totals.set(email, (totals.get(email) ?? 0) + part); + } + }); + + for (const [email, v] of totals) totals.set(email, Math.round(v)); + daily.sort((x, y) => x.date.localeCompare(y.date) || y.spend_cents - x.spend_cents); + return { totals, daily }; +} + +export function getFullDashboard(range: TimeRange = 7): FullDashboard { + const db = getDb(); const cycleRow = db.prepare("SELECT MAX(cycle_start) as cycle_start FROM spending").get() as { cycle_start: string | null; @@ -982,59 +1087,78 @@ export function getFullDashboard(days: number = 7): FullDashboard { const cycleStart = getMetadata("cycle_start") ?? cycleRow?.cycle_start ?? new Date().toISOString().slice(0, 10); const cycleEnd = getMetadata("cycle_end") ?? ""; - const cycleDays = Math.max( - 1, - Math.ceil((Date.now() - new Date(cycleStart).getTime()) / 86_400_000), - ); + const cycleDays = Math.max(1, Math.ceil((Date.now() - new Date(cycleStart).getTime()) / DAY_MS)); const billing = cycleBillingAnchor(db); + const days = range === "cycle" ? cycleDays : range; + const since = range === "cycle" ? (billing?.cycleStart ?? cycleStart).slice(0, 10) : dayStart(days); + // the 24h range spends over the last 24 hours, not since yesterday's midnight + const hourly = range === 1; + const sinceMs = hourly + ? last24HoursStart() + : range === "cycle" && billing + ? billing.cycleStartMs + : Date.parse(`${since}T00:00:00.000Z`); + + // daily activity cannot start at an exact hour: the 24h range counts usage events instead, + // so requests and active members cover the same window as the spend + const eventRequests = hourly + ? new Map( + ( + db + .prepare( + `SELECT user_email as email, COUNT(*) as n FROM usage_events + WHERE is_chargeable = 1 AND CAST(timestamp AS INTEGER) >= ? GROUP BY user_email`, + ) + .all(sinceMs) as Array<{ email: string; n: number }> + ).map((r) => [r.email, r.n]), + ) + : null; + + const totalMembers = + (db.prepare("SELECT COUNT(*) as c FROM members WHERE is_removed = 0").get() as { c: number }) + ?.c ?? 0; + + const activeMembers = eventRequests + ? eventRequests.size + : (( + db + .prepare( + "SELECT COUNT(DISTINCT email) as c FROM daily_usage WHERE is_active = 1 AND date >= ?", + ) + .get(since) as { c: number } + )?.c ?? 0); + + const windowSpend = spendSince(db, sinceMs); + const chartSpend = hourly ? spendSince(db, sinceMs, true) : windowSpend; + const dailySpendWindowFromGroups = () => ( db .prepare( `SELECT COALESCE(SUM(spend), 0) as total FROM ( SELECT date, email, MAX(spend_cents) as spend FROM daily_spend - WHERE date >= date('now', ?) GROUP BY date, email + WHERE date >= ? GROUP BY date, email )`, ) - .get(dateFilter) as { total: number } + .get(since) as { total: number } ).total; - let totalSpendCentsForWindow: number; - if (billing && billing.teamBilledCents > 0) { - const fullRaw = ( - db - .prepare( - `SELECT COALESCE(SUM(total_cents), 0) as t FROM usage_events WHERE CAST(timestamp AS INTEGER) >= ?`, - ) - .get(billing.cycleStartMs) as { t: number } - ).t; - if (fullRaw > 0) { - const windowRaw = ( - db - .prepare( - `SELECT COALESCE(SUM(total_cents), 0) as t FROM usage_events - WHERE CAST(timestamp AS INTEGER) >= ? - AND date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') >= date('now', ?)`, - ) - .get(billing.cycleStartMs, dateFilter) as { t: number } - ).t; - totalSpendCentsForWindow = Math.round((billing.teamBilledCents * windowRaw) / fullRaw); - } else { - totalSpendCentsForWindow = dailySpendWindowFromGroups(); - } - } else { - totalSpendCentsForWindow = dailySpendWindowFromGroups(); - } + const totalSpendCentsForWindow = + billing && billing.teamBilledCents > 0 + ? [...windowSpend.totals.values()].reduce((sum, v) => sum + v, 0) + : dailySpendWindowFromGroups(); const spendRow = { total: totalSpendCentsForWindow }; - const agentRow = db - .prepare( - "SELECT COALESCE(SUM(agent_requests), 0) as total FROM daily_usage WHERE date >= date('now', ?)", - ) - .get(dateFilter) as { total: number }; + const agentRow = eventRequests + ? { total: [...eventRequests.values()].reduce((sum, n) => sum + n, 0) } + : (db + .prepare( + "SELECT COALESCE(SUM(agent_requests), 0) as total FROM daily_usage WHERE date >= ?", + ) + .get(since) as { total: number }); const activeAnomalies = ( @@ -1050,29 +1174,24 @@ export function getFullDashboard(days: number = 7): FullDashboard { SUM(lines_added) as total_lines_added, COUNT(DISTINCT CASE WHEN is_active = 1 THEN email END) as active_users FROM daily_usage - WHERE date >= date('now', ?) + WHERE date >= ? GROUP BY date ORDER BY date`, ) - .all(dateFilter) as Array<{ + .all(since) as Array<{ date: string; total_agent_requests: number; total_lines_added: number; active_users: number; }>; - const rankedUsers = db + const rankedRows = db .prepare( - `WITH user_spend AS ( - SELECT email, spend_cents - FROM spending - WHERE cycle_start = (SELECT MAX(cycle_start) FROM spending) - ), - user_cache AS ( + `WITH user_cache AS ( SELECT user_email as email, ROUND(AVG(CASE WHEN cache_read_tokens > 0 THEN cache_read_tokens END)) as avg_cache_read, ROUND(100.0 * SUM(CASE WHEN max_mode = 1 THEN 1 ELSE 0 END) / COUNT(*)) as max_mode_pct FROM usage_events - WHERE date(timestamp/1000, 'unixepoch') >= date('now', ?) + WHERE date(timestamp/1000, 'unixepoch') >= ? GROUP BY user_email ), activity AS ( @@ -1086,12 +1205,12 @@ export function getFullDashboard(days: number = 7): FullDashboard { COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_days, MAX(most_used_model) as most_used_model FROM daily_usage - WHERE date >= date('now', ?) AND is_active = 1 + WHERE date >= ? AND is_active = 1 GROUP BY email ) SELECT m.email, m.name, - COALESCE(us.spend_cents, 0) as spend_cents, + 0 as spend_cents, 0 as included_spend_cents, 0 as fast_premium_requests, COALESCE(a.agent_requests, 0) as agent_requests, COALESCE(a.lines_added, 0) as lines_added, @@ -1103,16 +1222,14 @@ export function getFullDashboard(days: number = 7): FullDashboard { COALESCE(a.total_accepts, 0) as total_accepts, COALESCE(uc.avg_cache_read, 0) as avg_cache_read, COALESCE(uc.max_mode_pct, 0) as max_mode_pct, - RANK() OVER (ORDER BY COALESCE(us.spend_cents, 0) DESC) as spend_rank, + 0 as spend_rank, RANK() OVER (ORDER BY COALESCE(a.agent_requests, 0) DESC) as activity_rank FROM members m - LEFT JOIN user_spend us ON m.email = us.email LEFT JOIN user_cache uc ON m.email = uc.email LEFT JOIN activity a ON m.email = a.email - WHERE m.is_removed = 0 - ORDER BY COALESCE(us.spend_cents, 0) DESC`, + WHERE m.is_removed = 0`, ) - .all(dateFilter, dateFilter) as Array<{ + .all(since, since) as Array<{ email: string; name: string; spend_cents: number; @@ -1132,34 +1249,32 @@ export function getFullDashboard(days: number = 7): FullDashboard { activity_rank: number; }>; - const chartDays = Math.max(days, 7); - const chartDateFilter = `-${chartDays} days`; + const rankedUsers = rankedRows + .map((u) => ({ + ...u, + spend_cents: windowSpend.totals.get(u.email) ?? 0, + // lines are only kept per day + ...(eventRequests && { agent_requests: eventRequests.get(u.email) ?? 0, lines_added: 0 }), + })) + .sort((x, y) => y.spend_cents - x.spend_cents); + for (const u of rankedUsers) { + u.spend_rank = 1 + rankedUsers.filter((o) => o.spend_cents > u.spend_cents).length; + if (eventRequests) { + u.activity_rank = 1 + rankedUsers.filter((o) => o.agent_requests > u.agent_requests).length; + } + } let teamDailySpend: Array<{ date: string; spend_cents: number }> = []; if (billing && billing.teamBilledCents > 0) { - const fullRaw = ( - db - .prepare( - `SELECT COALESCE(SUM(total_cents), 0) as t FROM usage_events WHERE CAST(timestamp AS INTEGER) >= ?`, - ) - .get(billing.cycleStartMs) as { t: number } - ).t; - const rawByDay = db - .prepare( - `SELECT date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') as date, - SUM(total_cents) as raw_cents - FROM usage_events - WHERE CAST(timestamp AS INTEGER) >= ? - AND date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') >= date('now', ?) - GROUP BY date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') - ORDER BY date`, - ) - .all(billing.cycleStartMs, chartDateFilter) as Array<{ date: string; raw_cents: number }>; - if (fullRaw > 0) { - const f = billing.teamBilledCents / fullRaw; - teamDailySpend = rawByDay.map((r) => ({ - date: r.date, - spend_cents: Math.round(r.raw_cents * f), + const byDate = new Map(); + for (const r of chartSpend.daily) { + byDate.set(r.date, (byDate.get(r.date) ?? 0) + r.spend_cents); + } + teamDailySpend = [...byDate].map(([date, spend_cents]) => ({ date, spend_cents })); + if (hourly && teamDailySpend.length > 0) { + teamDailySpend = chartHourKeys(sinceMs).map((date) => ({ + date, + spend_cents: byDate.get(date) ?? 0, })); } } @@ -1169,62 +1284,14 @@ export function getFullDashboard(days: number = 7): FullDashboard { ` SELECT date, SUM(spend) as spend_cents FROM ( SELECT date, email, MAX(spend_cents) as spend FROM daily_spend - WHERE date >= date('now', ?) GROUP BY date, email + WHERE date >= ? GROUP BY date, email ) GROUP BY date ORDER BY date `, ) - .all(chartDateFilter) as Array<{ date: string; spend_cents: number }>; + .all(since) as Array<{ date: string; spend_cents: number }>; } - let dailySpendBreakdown: Array<{ - date: string; - email: string; - name: string; - spend_cents: number; - }> = []; - if (billing && billing.teamBilledCents > 0) { - dailySpendBreakdown = db - .prepare( - ` - WITH cb AS ( - SELECT email, spend_cents FROM spending - WHERE cycle_start = (SELECT MAX(cycle_start) FROM spending) - ), - ur AS ( - SELECT user_email as email, SUM(total_cents) as tr - FROM usage_events - WHERE CAST(timestamp AS INTEGER) >= ? - GROUP BY user_email - ), - dr AS ( - SELECT user_email, date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') as date, - SUM(total_cents) as rd - FROM usage_events - WHERE CAST(timestamp AS INTEGER) >= ? - AND date(CAST(timestamp AS INTEGER) / 1000, 'unixepoch') >= date('now', ?) - GROUP BY user_email, date - ) - SELECT x.date, x.email, x.name, x.spend_cents FROM ( - SELECT dr.date, dr.user_email as email, COALESCE(m.name, dr.user_email) as name, - CASE WHEN COALESCE(ur.tr, 0) > 0 AND COALESCE(cb.spend_cents, 0) > 0 - THEN CAST(ROUND(dr.rd * cb.spend_cents * 1.0 / ur.tr) AS INTEGER) - ELSE 0 END as spend_cents - FROM dr - LEFT JOIN ur ON ur.email = dr.user_email - LEFT JOIN cb ON cb.email = dr.user_email - LEFT JOIN members m ON m.email = dr.user_email - ) x - WHERE x.spend_cents > 0 - ORDER BY x.date, x.spend_cents DESC - `, - ) - .all(billing.cycleStartMs, billing.cycleStartMs, chartDateFilter) as Array<{ - date: string; - email: string; - name: string; - spend_cents: number; - }>; - } + let dailySpendBreakdown = billing && billing.teamBilledCents > 0 ? chartSpend.daily : []; if (dailySpendBreakdown.length === 0) { dailySpendBreakdown = db .prepare( @@ -1235,7 +1302,7 @@ export function getFullDashboard(days: number = 7): FullDashboard { FROM ( SELECT date, email, MAX(spend_cents) as spend_cents FROM daily_spend - WHERE date >= date('now', ?) + WHERE date >= ? GROUP BY date, email ) ds LEFT JOIN members m ON ds.email = m.email @@ -1243,7 +1310,7 @@ export function getFullDashboard(days: number = 7): FullDashboard { ORDER BY ds.date, ds.spend_cents DESC `, ) - .all(chartDateFilter) as Array<{ + .all(since) as Array<{ date: string; email: string; name: string; @@ -1251,43 +1318,50 @@ export function getFullDashboard(days: number = 7): FullDashboard { }>; } - const modelCosts = db + const modelRows = db .prepare( ` WITH user_model AS ( SELECT email, most_used_model, SUM(agent_requests) as reqs - FROM daily_usage WHERE is_active = 1 AND most_used_model != '' AND date >= date('now', ?) + FROM daily_usage WHERE is_active = 1 AND most_used_model != '' AND date >= ? GROUP BY email, most_used_model ), primary_model AS ( SELECT email, most_used_model FROM user_model WHERE (email, reqs) IN (SELECT email, MAX(reqs) FROM user_model GROUP BY email) - ), - user_spend AS ( - SELECT email, spend_cents FROM spending - WHERE cycle_start = (SELECT MAX(cycle_start) FROM spending) ) SELECT pm.most_used_model as model, COUNT(*) as users, - ROUND(AVG(COALESCE(us.spend_cents, 0))/100, 0) as avg_spend, - ROUND(SUM(COALESCE(us.spend_cents, 0))/100, 0) as total_spend, COALESCE(SUM(du.reqs), 0) as total_reqs, GROUP_CONCAT(pm.email) as emails FROM primary_model pm - LEFT JOIN user_spend us ON pm.email = us.email - LEFT JOIN (SELECT email, SUM(agent_requests) as reqs FROM daily_usage WHERE date >= date('now', ?) GROUP BY email) du ON pm.email = du.email + LEFT JOIN (SELECT email, SUM(agent_requests) as reqs FROM daily_usage WHERE date >= ? GROUP BY email) du ON pm.email = du.email GROUP BY pm.most_used_model - ORDER BY total_spend DESC `, ) - .all(dateFilter, dateFilter) as Array<{ + .all(since, since) as Array<{ model: string; users: number; - avg_spend: number; - total_spend: number; total_reqs: number; - emails: string; + emails: string | null; }>; + const modelCosts = modelRows + .map((mc) => { + const emails = mc.emails ? mc.emails.split(",") : []; + const spend = emails.reduce((sum, e) => sum + (windowSpend.totals.get(e) ?? 0), 0); + return { + model: mc.model, + users: mc.users, + avg_spend: Math.round(spend / 100 / Math.max(1, mc.users)), + total_spend: Math.round(spend / 100), + total_reqs: eventRequests + ? emails.reduce((sum, e) => sum + (eventRequests.get(e) ?? 0), 0) + : mc.total_reqs, + emails, + }; + }) + .sort((x, y) => y.total_spend - x.total_spend); + const stats: DashboardStats = { totalMembers, activeMembers, @@ -1303,13 +1377,12 @@ export function getFullDashboard(days: number = 7): FullDashboard { return { days, + range, stats, - modelCosts: modelCosts.map((mc) => ({ - ...mc, - emails: mc.emails ? mc.emails.split(",") : [], - })), + modelCosts, teamDailySpend, dailySpendBreakdown, + cycleStarts: getCycleStarts(db), }; } @@ -1597,8 +1670,16 @@ export function getDashboardStats(days: number = 7): DashboardStats { return getFullDashboard(days).stats; } -export function getUserStats(email: string, days: number = 7) { +export function getUserStats(email: string, range: TimeRange = 7) { const db = getDb(); + const days = range === "cycle" ? getCycleWindowDays() : range; + const sinceMs = + range === 1 + ? last24HoursStart() + : ((range === "cycle" ? cycleBillingAnchor(db)?.cycleStartMs : undefined) ?? + Date.parse(`${dayStart(days)}T00:00:00.000Z`)); + const windowSpend = spendSince(db, sinceMs); + const windowSpendCents = windowSpend.totals.get(email) ?? 0; const member = db.prepare("SELECT * FROM members WHERE email = ?").get(email) as | (TeamMember & { first_seen: string; last_seen: string }) @@ -1652,7 +1733,47 @@ export function getUserStats(email: string, days: number = 7) { .prepare(`${ANOMALY_SELECT} WHERE user_email = ? ORDER BY detected_at DESC LIMIT 20`) .all(email) as Anomaly[]; - const dailySpend = getUserDailySpend(email); + const hourly = range === 1; + const firstDate = new Date(sinceMs).toISOString().slice(0, 10); + const spendByDate = new Map( + (hourly ? spendSince(db, sinceMs, true) : windowSpend).daily + .filter((r) => r.email === email) + .map((r) => [r.date, r.spend_cents]), + ); + if (spendByDate.size === 0 && !hourly) { + for (const d of getUserDailySpend(email)) { + if (d.date >= firstDate) spendByDate.set(d.date, d.spend_cents); + } + } + const dailySpend: Array<{ date: string; spend_cents: number; requests?: number }> = []; + if (hourly) { + // activity is only kept per day, so the hourly $/req counts the usage events of each hour + const requestsByHour = new Map( + ( + db + .prepare( + `SELECT strftime('%Y-%m-%dT%H', CAST(timestamp AS INTEGER) / 1000, 'unixepoch') as hour, + COUNT(*) as n + FROM usage_events + WHERE user_email = ? AND is_chargeable = 1 AND CAST(timestamp AS INTEGER) >= ? + GROUP BY hour`, + ) + .all(email, sinceMs) as Array<{ hour: string; n: number }> + ).map((r) => [r.hour, r.n]), + ); + for (const date of chartHourKeys(sinceMs)) { + dailySpend.push({ + date, + spend_cents: spendByDate.get(date) ?? 0, + requests: requestsByHour.get(date), + }); + } + } else { + for (let t = Date.parse(`${firstDate}T00:00:00.000Z`); t <= Date.now(); t += DAY_MS) { + const date = new Date(t).toISOString().slice(0, 10); + dailySpend.push({ date, spend_cents: spendByDate.get(date) ?? 0 }); + } + } const billCycleStart = spending[0]?.cycle_start ?? null; const usageEventsSummaryRaw = getUserUsageEventsSummary(email, days, billCycleStart); const billedCents = spending[0]?.spend_cents ?? 0; @@ -1771,6 +1892,8 @@ export function getUserStats(email: string, days: number = 7) { aiAdoption, planExhaustion, repoBreakdown, + windowSpendCents, + cycleStarts: getCycleStarts(db), }; } @@ -2291,7 +2414,7 @@ export function getUsersByClientVersion(): Record "?").join(",")})` : ""; const params = emails?.length ? [...emails] : []; @@ -2326,12 +2449,13 @@ export function getModelEfficiency(emails?: string[]): ModelEfficiency[] { AND du.most_used_model != '' AND du.agent_requests > 0 AND ds.spend_cents > 0 + AND du.date >= date('now', ?) ${emailFilter} GROUP BY du.most_used_model HAVING COUNT(DISTINCT du.email) >= ${emails?.length ? "1" : "3"} AND SUM(ds.spend_cents) >= ${emails?.length ? "0" : "2000"} ORDER BY total_spend_usd DESC`, ) - .all(...params, ...params) as ModelEfficiency[]; + .all(...params, `-${days} days`, ...params) as ModelEfficiency[]; } export function getAllMembers(): Array { diff --git a/src/lib/data/types.ts b/src/lib/data/types.ts index cce620d..d9173f3 100644 --- a/src/lib/data/types.ts +++ b/src/lib/data/types.ts @@ -55,6 +55,7 @@ export interface DashboardStats { export interface FullDashboard { days: number; + range: number | "cycle"; stats: DashboardStats; modelCosts: Array<{ model: string; @@ -66,6 +67,7 @@ export interface FullDashboard { }>; teamDailySpend: Array<{ date: string; spend_cents: number }>; dailySpendBreakdown: Array<{ date: string; email: string; name: string; spend_cents: number }>; + cycleStarts: string[]; } export interface ModelEfficiency { diff --git a/src/lib/date-utils.ts b/src/lib/date-utils.ts index efcbd7c..dd77798 100644 --- a/src/lib/date-utils.ts +++ b/src/lib/date-utils.ts @@ -6,16 +6,23 @@ export function formatDateShort(dateStr: string): string { return `${day} ${dateStr.slice(5)}`; } +// the 24h range keys its points by hour ("2026-11-09T14", UTC) +export const isHourKey = (key: string) => key.length === 13; + +// the 24h charts tick every 3 hours on fixed clock hours (0h, 3h, 6h...) so the marks stay stable +export const isTickHour = (key: string) => Number(key.slice(11)) % 3 === 0; + export function formatDateTick(dateStr: string): string { + if (isHourKey(dateStr)) return `${dateStr.slice(11)}h`; const d = new Date(dateStr + "T00:00:00"); const day = DAYS[d.getDay()] ?? ""; return `${day} ${dateStr.slice(8)}`; } export function formatDateLabel(dateStr: string): string { - const d = new Date(dateStr + "T00:00:00"); - const day = DAYS[d.getDay()] ?? ""; - return `${day}, ${dateStr}`; + const date = dateStr.slice(0, 10); + const day = DAYS[new Date(`${date}T00:00:00`).getDay()] ?? ""; + return isHourKey(dateStr) ? `${day}, ${date} ${dateStr.slice(11)}:00 UTC` : `${day}, ${dateStr}`; } export function timeAgo(dateStr: string): string { diff --git a/src/lib/time-range.ts b/src/lib/time-range.ts new file mode 100644 index 0000000..86fa7c8 --- /dev/null +++ b/src/lib/time-range.ts @@ -0,0 +1,17 @@ +export type TimeRange = number | "cycle"; + +export const DEFAULT_RANGE: TimeRange = "cycle"; + +export function parseRange(value?: string): TimeRange { + if (value === "cycle") return "cycle"; + return parseInt(value ?? "", 10) || DEFAULT_RANGE; +} + +export function userHref(email: string, range: TimeRange): string { + const base = `/users/${encodeURIComponent(email)}`; + return range === DEFAULT_RANGE ? base : `${base}?range=${range}`; +} + +export function overviewHref(range: TimeRange): string { + return range === DEFAULT_RANGE ? "/" : `/?range=${range}`; +} diff --git a/tests/hourly-spend.test.ts b/tests/hourly-spend.test.ts new file mode 100644 index 0000000..82a1036 --- /dev/null +++ b/tests/hourly-spend.test.ts @@ -0,0 +1,73 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; + +const TEST_DB_PATH = path.join(process.cwd(), "data", "test-hourly-spend.db"); +const HOUR_MS = 3_600_000; +const DAY_MS = 24 * HOUR_MS; + +const hourKey = (ms: number) => new Date(ms).toISOString().slice(0, 13); +const daysAgo = (n: number) => new Date(Date.now() - n * DAY_MS).toISOString().slice(0, 10); + +describe("charts zoom on the selected range", () => { + let sqlite: typeof import("@/lib/data/sqlite"); + const now = Date.now(); + + beforeAll(async () => { + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + process.env.DATABASE_PATH = TEST_DB_PATH; + sqlite = await import("@/lib/data/sqlite"); + const db = sqlite.getDb(); + db.prepare("INSERT INTO members (email, name, role) VALUES (?, ?, ?)").run( + "a@x.com", + "A", + "member", + ); + db.prepare("INSERT INTO spending (email, cycle_start, spend_cents) VALUES (?, ?, ?)").run( + "a@x.com", + daysAgo(10), + 900, + ); + const event = db.prepare( + "INSERT INTO usage_events (user_email, timestamp, model, kind, total_cents) VALUES (?, ?, 'm', 'k', 100)", + ); + event.run("a@x.com", String(now - 30 * 60_000)); + event.run("a@x.com", String(now - 5 * HOUR_MS)); + event.run("a@x.com", String(now - 3 * DAY_MS + HOUR_MS)); + event.run("a@x.com", String(now - 6 * DAY_MS)); + }); + + afterAll(() => { + sqlite.getDb().close(); + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + delete process.env.DATABASE_PATH; + }); + + it("charts the last 24 hours hour by hour on the 24h range", () => { + const d = sqlite.getFullDashboard(1); + expect(d.teamDailySpend).toHaveLength(25); + expect(d.teamDailySpend.every((r) => r.date.length === 13)).toBe(true); + const latest = d.teamDailySpend.find((r) => r.date === hourKey(now - 30 * 60_000)); + expect(latest?.spend_cents).toBe(225); + expect(d.dailySpendBreakdown.every((r) => r.date.length === 13)).toBe(true); + }); + + it("shows only the selected days on short ranges", () => { + const dates = sqlite.getFullDashboard(3).teamDailySpend.map((r) => r.date); + expect(dates.length).toBeGreaterThan(0); + expect(dates.every((date) => date >= daysAgo(3))).toBe(true); + }); + + it("gives the user page the same hourly points on the 24h range", () => { + const stats = sqlite.getUserStats("a@x.com", 1); + expect(stats.dailySpend).toHaveLength(25); + expect(stats.dailySpend.every((r) => r.date.length === 13)).toBe(true); + }); + + it("counts the requests of each hour so the user chart can draw $/req", () => { + const stats = sqlite.getUserStats("a@x.com", 1); + const latest = stats.dailySpend.find((r) => r.date === hourKey(now - 30 * 60_000)); + expect(latest?.requests).toBe(1); + expect(stats.dailySpend.filter((r) => r.requests != null)).toHaveLength(2); + }); +}); diff --git a/tests/rolling-24h.test.ts b/tests/rolling-24h.test.ts new file mode 100644 index 0000000..02b8558 --- /dev/null +++ b/tests/rolling-24h.test.ts @@ -0,0 +1,96 @@ +import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; + +const TEST_DB_PATH = path.join(process.cwd(), "data", "test-rolling-24h.db"); +const at = (iso: string) => String(Date.parse(iso)); + +describe("24h range is a rolling window with hourly bars", () => { + let sqlite: typeof import("@/lib/data/sqlite"); + + beforeAll(async () => { + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + process.env.DATABASE_PATH = TEST_DB_PATH; + sqlite = await import("@/lib/data/sqlite"); + const db = sqlite.getDb(); + const member = db.prepare("INSERT INTO members (email, name, role) VALUES (?, ?, 'member')"); + const spending = db.prepare( + "INSERT INTO spending (email, cycle_start, spend_cents) VALUES (?, ?, ?)", + ); + const event = db.prepare( + "INSERT INTO usage_events (user_email, timestamp, model, kind, total_cents) VALUES (?, ?, 'm', 'k', 100)", + ); + // at 14:41 UTC on the 13th, "24h" starts at 14:41 on the 12th + member.run("b@x.com", "b"); + spending.run("b@x.com", "2026-11-01", 1000); + member.run("c@x.com", "c"); + spending.run("c@x.com", "2026-11-01", 900); + event.run("b@x.com", at("2026-11-12T14:51:00Z")); // 23h50 ago: inside the oldest partial hour + event.run("b@x.com", at("2026-11-13T14:30:00Z")); + event.run("c@x.com", at("2026-11-12T14:30:00Z")); // 24h11 ago: just outside + event.run("c@x.com", at("2026-11-12T14:51:00Z")); + event.run("c@x.com", at("2026-11-13T14:30:00Z")); + // the night the clocks go back in Paris (01:00 UTC on 25 October 2026) + member.run("e@x.com", "e"); + spending.run("e@x.com", "2026-10-01", 900); + event.run("e@x.com", at("2026-10-24T01:45:00Z")); // 23h45 ago + event.run("e@x.com", at("2026-10-24T01:15:00Z")); // 24h15 ago + event.run("e@x.com", at("2026-10-25T01:10:00Z")); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + afterAll(() => { + sqlite.getDb().close(); + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + delete process.env.DATABASE_PATH; + }); + + const freeze = (iso: string) => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date(iso)); + }; + + it("counts an event from the oldest partial hour and leaves out an older one", () => { + freeze("2026-11-13T14:41:00Z"); + expect(sqlite.getUserStats("b@x.com", 1).windowSpendCents).toBe(1000); + expect(sqlite.getUserStats("c@x.com", 1).windowSpendCents).toBe(600); + }); + + it("charts from the hour 24h back to the current hour, partial ends included", () => { + freeze("2026-11-13T14:41:00Z"); + const chart = sqlite.getFullDashboard(1).teamDailySpend; + expect(chart[0]?.date).toBe("2026-11-12T14"); + expect(chart.at(-1)?.date).toBe("2026-11-13T14"); + expect(chart.reduce((sum, r) => sum + r.spend_cents, 0)).toBe(1000 + 600); + }); + + it("counts requests and active members from the events of the last 24 hours", () => { + freeze("2026-11-13T14:41:00Z"); + const { stats } = sqlite.getFullDashboard(1); + expect(stats.totalAgentRequests).toBe(4); // b: 2, c: 2 (its event at 14:30 yesterday is out) + expect(stats.activeMembers).toBe(2); + expect(stats.rankedUsers.find((u) => u.email === "c@x.com")?.agent_requests).toBe(2); + // the user page counts the same events, hour by hour + const hours = sqlite.getUserStats("c@x.com", 1).dailySpend; + expect(hours.reduce((sum, r) => sum + (r.requests ?? 0), 0)).toBe(2); + }); + + it("is unaffected by a daylight saving change in the local time zone", () => { + const tz = process.env.TZ; + process.env.TZ = "Europe/Paris"; + try { + freeze("2026-10-25T01:30:00Z"); + const stats = sqlite.getUserStats("e@x.com", 1); + expect(stats.windowSpendCents).toBe(600); + expect(stats.dailySpend).toHaveLength(25); + expect(stats.dailySpend[0]?.date).toBe("2026-10-24T01"); + expect(stats.dailySpend.at(-1)?.date).toBe("2026-10-25T01"); + } finally { + if (tz === undefined) delete process.env.TZ; + else process.env.TZ = tz; + } + }); +}); diff --git a/tests/window-spend.test.ts b/tests/window-spend.test.ts new file mode 100644 index 0000000..8f21b99 --- /dev/null +++ b/tests/window-spend.test.ts @@ -0,0 +1,87 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; + +const TEST_DB_PATH = path.join(process.cwd(), "data", "test-window-spend.db"); +const DAY_MS = 86_400_000; + +const midnight = Date.UTC( + new Date().getUTCFullYear(), + new Date().getUTCMonth(), + new Date().getUTCDate(), +); +const daysAgo = (n: number) => new Date(midnight - n * DAY_MS).toISOString().slice(0, 10); +const noon = (n: number) => String(midnight - n * DAY_MS + DAY_MS / 2); + +describe("getFullDashboard spend over a window", () => { + let sqlite: typeof import("@/lib/data/sqlite"); + + beforeAll(async () => { + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + process.env.DATABASE_PATH = TEST_DB_PATH; + sqlite = await import("@/lib/data/sqlite"); + const db = sqlite.getDb(); + db.prepare("INSERT INTO members (email, name, role) VALUES (?, ?, ?)").run( + "a@x.com", + "A", + "member", + ); + const bill = db.prepare( + "INSERT INTO spending (email, cycle_start, spend_cents) VALUES (?, ?, ?)", + ); + bill.run("a@x.com", daysAgo(35), 1000); + bill.run("a@x.com", daysAgo(5), 500); + const event = db.prepare( + "INSERT INTO usage_events (user_email, timestamp, model, kind, total_cents) VALUES (?, ?, 'm', 'k', ?)", + ); + event.run("a@x.com", noon(34), 100); + event.run("a@x.com", noon(15), 100); + event.run("a@x.com", noon(4), 50); + event.run("a@x.com", noon(2), 50); + }); + + afterAll(() => { + sqlite.getDb().close(); + if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); + delete process.env.DATABASE_PATH; + }); + + const spend = (range: number | "cycle") => { + const d = sqlite.getFullDashboard(range); + return { + user: d.stats.rankedUsers[0]?.spend_cents, + team: d.stats.totalSpendCents, + chart: d.teamDailySpend.reduce((sum, r) => sum + r.spend_cents, 0), + }; + }; + + it("uses the billed total for the current cycle", () => { + expect(spend("cycle")).toEqual({ user: 500, team: 500, chart: 500 }); + expect(spend(7).user).toBe(500); + }); + + it("shares the previous cycle's bill over the events inside the window", () => { + expect(spend(30)).toEqual({ user: 1000, team: 1000, chart: 1000 }); + }); + + it("counts nothing when no event falls inside the window", () => { + expect(spend(1).user).toBe(0); + }); + + it("returns the user's spend for the selected range", () => { + const spendFor = (range: number | "cycle") => + sqlite.getUserStats("a@x.com", range).windowSpendCents; + expect(spendFor("cycle")).toBe(500); + expect(spendFor(30)).toBe(1000); + expect(spendFor(1)).toBe(0); + }); + + it("lists the cycle starts so charts can mark them", () => { + expect(sqlite.getFullDashboard(30).cycleStarts).toEqual([daysAgo(35), daysAgo(5)]); + expect(sqlite.getUserStats("a@x.com", 30).cycleStarts).toEqual([daysAgo(35), daysAgo(5)]); + }); + + it("finds how many days back the current cycle started", () => { + expect(sqlite.getCycleWindowDays()).toBe(5); + }); +});