OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): billing page breaks event usage down per project and event name (#588)
Carl-Gerhard Lindesvärde8f6fae821c3
diff --git a/apps/start/e2e/org-billing.spec.ts b/apps/start/e2e/org-billing.spec.tsindex 926598ab1..06c049f45 100644--- a/apps/start/e2e/org-billing.spec.ts+++ b/apps/start/e2e/org-billing.spec.ts@@ -14,7 +14,7 @@ const SLOW_DEV_SERVER_TIMEOUT_MS = 150_000;test.setTimeout(SLOW_DEV_SERVER_TIMEOUT_MS);// Plan rows start a real checkout when there is no current plan, so none is clicked.-test('billing renders plans, usage and the FAQ without errors', async ({+test('billing renders plans, the usage breakdown and the FAQ without errors', async ({page,seed,}) => {@@ -40,8 +40,27 @@ test('billing renders plans, usage and the FAQ without errors', async ({await page.getByRole('button', { name: 'Yearly' }).click();await expect(yearlyPlan).toBeVisible();- await expect(page.getByText('Usage', { exact: true })).toBeVisible();- await expect(page.getByText('Limit', { exact: true })).toBeVisible();+ // The usage breakdown: one stacked bar per day split by project, and the+ // event-name donut, each with a share table listing the seeded projects+ // and the most frequent names.+ await expect(page.getByText('Events per project')).toBeVisible();+ await expect(page.getByText('Events by name')).toBeVisible();+ // No plan yet, so both widgets fall back to a trailing window.+ await expect(page.getByText(/Last 30 days ·/)).toHaveCount(2);+ for (const project of seed.projects) {+ await expect(page.getByText(project.name, { exact: true })).toBeVisible();+ }+ await expect(page.getByText('screen_view', { exact: true })).toBeVisible();+ await expect(page.getByText('Other', { exact: true })).toBeVisible();++ // Selecting a project narrows the donut to that project's names.+ const firstProject = seed.projects[0]!;+ await page.getByRole('button', { name: firstProject.name }).click();+ await expect(+ page.getByText(new RegExp(`^${firstProject.name} · Last 30 days`))+ ).toBeVisible();+ await page.getByRole('button', { name: 'All projects' }).click();+ await expect(page.getByText(/^All projects · Last 30 days/)).toBeVisible();await expect(page.locator('body')).not.toContainText(/NaN|undefined/);const question = page.getByRole('button', {@@ -57,8 +76,12 @@ test('billing renders plans, usage and the FAQ without errors', async ({expect(apiFailures(problems)).toEqual([]);await page.setViewportSize({ width: 390, height: 844 });- const overflow = await page.evaluate(- () => document.documentElement.scrollWidth - window.innerWidth- );- expect(overflow).toBeLessThanOrEqual(0);+ // The charts re-measure asynchronously after a resize.+ await expect+ .poll(() =>+ page.evaluate(+ () => document.documentElement.scrollWidth - window.innerWidth+ )+ )+ .toBeLessThanOrEqual(0);});diff --git a/apps/start/src/components/organization/billing-projection.test.ts b/apps/start/src/components/organization/billing-projection.test.tsnew file mode 100644index 000000000..ab8da570a--- /dev/null+++ b/apps/start/src/components/organization/billing-projection.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from 'vitest';+import { projectUsage } from './billing-projection';++const periodStart = new Date('2026-10-01T00:00:00');+const periodEnd = new Date('2026-11-01T00:00:00');++describe('projectUsage', () => {+ it('extrapolates the average daily rate over the remaining days', () => {+ // 22 days in, 22k used → 1k/day, 9 days left.+ const projection = projectUsage({+ used: 22_000,+ limit: 100_000,+ periodStart,+ periodEnd,+ now: new Date('2026-10-22T15:00:00'),+ });+ expect(projection).toEqual({+ perDay: 1000,+ projectedTotal: 31_000,+ limitReachedAt: null,+ });+ });++ it('names the day the limit is reached when the pace overshoots it', () => {+ // 80k in 22 days ≈ 3,636/day → 20k left takes 6 more days.+ const projection = projectUsage({+ used: 80_000,+ limit: 100_000,+ periodStart,+ periodEnd,+ now: new Date('2026-10-22T15:00:00'),+ });+ expect(projection?.projectedTotal).toBe(112_727);+ expect(projection?.limitReachedAt).toEqual(new Date('2026-10-28T15:00:00'));+ });++ it('does not name a day once the limit is already exceeded', () => {+ const projection = projectUsage({+ used: 120_000,+ limit: 100_000,+ periodStart,+ periodEnd,+ now: new Date('2026-10-22T15:00:00'),+ });+ expect(projection?.limitReachedAt).toBeNull();+ });++ it('treats the first day as one elapsed day instead of dividing by zero', () => {+ const projection = projectUsage({+ used: 500,+ limit: 100_000,+ periodStart,+ periodEnd,+ now: new Date('2026-10-01T09:00:00'),+ });+ expect(projection?.perDay).toBe(500);+ expect(projection?.projectedTotal).toBe(15_500);+ });++ it('returns null without usage or a sane period', () => {+ const now = new Date('2026-10-22T15:00:00');+ expect(+ projectUsage({ used: 0, limit: 100_000, periodStart, periodEnd, now })+ ).toBeNull();+ expect(+ projectUsage({+ used: 10,+ limit: 100_000,+ periodStart: periodEnd,+ periodEnd: periodStart,+ now,+ })+ ).toBeNull();+ });+});diff --git a/apps/start/src/components/organization/billing-projection.ts b/apps/start/src/components/organization/billing-projection.tsnew file mode 100644index 000000000..4cfeecc93--- /dev/null+++ b/apps/start/src/components/organization/billing-projection.ts@@ -0,0 +1,48 @@+import { addDays, differenceInCalendarDays } from 'date-fns';++export interface UsageProjectionInput {+ /** Billable events counted so far this period. */+ used: number;+ limit: number;+ periodStart: Date;+ periodEnd: Date;+ now: Date;+}++export interface UsageProjection {+ perDay: number;+ /** Events expected by the end of the period at the current pace. */+ projectedTotal: number;+ /** The day the limit is reached at the current pace, or null if the period ends first. */+ limitReachedAt: Date | null;+}++/**+ * Straight-line projection from the average daily rate so far. The current+ * day counts as elapsed even when partially through, which biases the rate+ * low early in the day; the alternative overshoots badly on day one.+ */+export function projectUsage({+ used,+ limit,+ periodStart,+ periodEnd,+ now,+}: UsageProjectionInput): UsageProjection | null {+ const daysElapsed = differenceInCalendarDays(now, periodStart) + 1;+ const daysInPeriod = differenceInCalendarDays(periodEnd, periodStart);+ if (used <= 0 || daysElapsed <= 0 || daysInPeriod <= 0) {+ return null;+ }++ const perDay = used / daysElapsed;+ const daysRemaining = Math.max(0, daysInPeriod - daysElapsed);+ const projectedTotal = Math.round(used + perDay * daysRemaining);++ const reachesLimit = limit > 0 && used < limit && projectedTotal >= limit;+ const limitReachedAt = reachesLimit+ ? addDays(now, Math.ceil((limit - used) / perDay))+ : null;++ return { perDay, projectedTotal, limitReachedAt };+}diff --git a/apps/start/src/components/organization/billing-usage.tsx b/apps/start/src/components/organization/billing-usage.tsxindex 51e2f7a91..982712041 100644--- a/apps/start/src/components/organization/billing-usage.tsx+++ b/apps/start/src/components/organization/billing-usage.tsx@@ -1,28 +1,37 @@import type { IServiceOrganization } from '@openpanel/core';-import { sum } from '@openpanel/shared';+import { round } from '@openpanel/shared';import { useQuery } from '@tanstack/react-query';-import { Loader2Icon } from 'lucide-react';-import { useCallback } from 'react';+import { Loader2Icon, XIcon } from 'lucide-react';+import { useMemo, useState } from 'react';import { ComposedChart } from '@/components/charts/composed-chart';import { Grid } from '@/components/charts/grid';import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { PieCenter } from '@/components/charts/pie-center';+import { DEFAULT_HOVER_OFFSET, PieChart } from '@/components/charts/pie-chart';+import { PieSlice } from '@/components/charts/pie-slice';import { SeriesBar } from '@/components/charts/series-bar';import { XAxis } from '@/components/charts/x-axis';import { YAxis } from '@/components/charts/y-axis';+import { Button } from '@/components/ui/button';import { Widget, WidgetBody, WidgetHead } from '@/components/widget';import { formatDateInterval } from '@/hooks/use-format-date-interval';import { useNumber } from '@/hooks/use-numer-formatter';import { useTRPC } from '@/integrations/trpc/react';+import { cn } from '@/utils/cn';import { formatDate } from '@/utils/date';import { getChartColor } from '@/utils/theme';const MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };-const BAR_RADIUS = 4;-const DAILY_BAR_SIZE = 8;-const WEEKLY_BAR_SIZE = 20;-// Past this many days daily bars get too thin to read, so usage is summed per week.-const WEEKLY_THRESHOLD_DAYS = 30;-const BAR_COLOR = getChartColor(0);+const BAR_RADIUS = 3;+const MAX_BAR_SIZE = 14;+// Room between stacked segments so each project reads as its own block.+const STACK_GAP = 1;+const DONUT_HOLE = 0.62;+const PAD_ANGLE = 0.02;+const CORNER_RADIUS = 3;+const PIE_SIZE = 200;+const OTHER_LABEL = 'Other';+const OTHER_COLOR = 'var(--chart-foreground-muted)';interface Props {organization: IServiceOrganization;@@ -31,235 +40,383 @@ interface Props {interface UsagePoint {[key: string]: unknown;date: number;- count: number;- weekRange?: string;+ total: number;}-function Card({ title, value }: { title: string; value: string }) {+interface Slice {+ id?: string;+ label: string;+ value: number;+ share: number;+ color: string;+}++function formatDayLabel(date: Date) {+ return formatDateInterval({ interval: 'day', date, short: true });+}++function toSlices(+ rows: { id?: string; label: string; value: number; color: string }[],+ total: number+): Slice[] {+ return rows+ .filter((row) => row.value > 0)+ .map((row) => ({+ ...row,+ share: total ? round((row.value / total) * 100, 1) : 0,+ }));+}++function SliceRow({ slice }: { slice: Slice }) {+ const number = useNumber();return (- <div className="col min-w-0 flex-1 gap-2 p-4" title={`${title}: ${value}`}>- <div className="truncate text-muted-foreground">{title}</div>- <div className="truncate font-bold text-xl tabular-nums">{value}</div>- </div>+ <>+ <span+ className="size-2.5 shrink-0 rounded-full"+ style={{ background: slice.color }}+ />+ <span className="min-w-0 flex-1 truncate">{slice.label}</span>+ <span className="font-semibold tabular-nums">+ {number.short(slice.value)}+ </span>+ <span className="w-12 text-right text-muted-foreground tabular-nums">+ {slice.share}%+ </span>+ </>+ );+}++const SLICE_ROW_CLASS =+ 'flex w-full items-center gap-2 rounded px-1.5 py-1 text-left';++// The donut's legend highlights slices on hover; the project legend selects+// a project to filter the donut by.+function SliceLegend({+ slices,+ hoveredIndex = null,+ onHover,+ selectedIndex = null,+ onSelect,+}: {+ slices: Slice[];+ hoveredIndex?: number | null;+ onHover?: (index: number | null) => void;+ selectedIndex?: number | null;+ onSelect?: (index: number | null) => void;+}) {+ return (+ <ul className="col gap-0.5">+ {slices.map((slice, index) => {+ const isSelected = selectedIndex === index;+ const isFaded = hoveredIndex !== null && hoveredIndex !== index;+ return (+ <li key={slice.id ?? `${index}-${slice.label}`}>+ <button+ aria-pressed={onSelect ? isSelected : undefined}+ className={cn(+ SLICE_ROW_CLASS,+ 'transition-opacity hover:bg-def-100',+ isFaded && 'opacity-50',+ isSelected && 'bg-def-100 font-medium'+ )}+ onBlur={() => onHover?.(null)}+ onClick={() => onSelect?.(isSelected ? null : index)}+ onFocus={() => onHover?.(index)}+ onMouseEnter={() => onHover?.(index)}+ onMouseLeave={() => onHover?.(null)}+ type="button"+ >+ <SliceRow slice={slice} />+ </button>+ </li>+ );+ })}+ </ul>+ );+}++function UsageWidget({+ title,+ subtitle,+ aside,+ className,+ children,+}: {+ title: string;+ subtitle?: string;+ aside?: React.ReactNode;+ className?: string;+ children: React.ReactNode;+}) {+ return (+ <Widget className={cn('w-full', className)}>+ <WidgetHead className="row items-start justify-between gap-4">+ <div className="col min-w-0 gap-0.5">+ <span className="title">{title}</span>+ {subtitle && (+ <span className="text-muted-foreground text-sm">{subtitle}</span>+ )}+ </div>+ {aside}+ </WidgetHead>+ <WidgetBody>{children}</WidgetBody>+ </Widget>);}+function Message({ children }: { children: React.ReactNode }) {+ return <div className="center-center p-8 font-medium">{children}</div>;+}+export default function BillingUsage({ organization }: Props) {const number = useNumber();const trpc = useTRPC();const usageQuery = useQuery(- trpc.subscription.usage.queryOptions({- organizationId: organization.id,- })+ trpc.subscription.usage.queryOptions({ organizationId: organization.id }));+ const usage = usageQuery.data;- const getDataInterval = () => {- if (!usageQuery.data || usageQuery.data.length === 0) {- return 'day';- }-- const dates = usageQuery.data.map((item) => new Date(item.day));- const minDate = new Date(Math.min(...dates.map((d) => d.getTime())));- const maxDate = new Date(Math.max(...dates.map((d) => d.getTime())));- const daysDiff = Math.ceil(- (maxDate.getTime() - minDate.getTime()) / (1000 * 60 * 60 * 24)- );-- return daysDiff > WEEKLY_THRESHOLD_DAYS ? 'week' : 'day';+ const [hoveredName, setHoveredName] = useState<number | null>(null);+ const [selectedProjectId, setSelectedProjectId] = useState<string | null>(+ null+ );+ const selectProject = (projectId: string | null) => {+ setSelectedProjectId(projectId);+ setHoveredName(null);};- const interval = getDataInterval();- const useWeeklyIntervals = interval === 'week';- const formatDateLabel = useCallback(- (date: Date) => formatDateInterval({ interval, date, short: true }),- [interval]+ const projects = useMemo(+ () =>+ (usage?.projects ?? []).map((project, index) => ({+ ...project,+ color: getChartColor(index),+ total: usage?.projectTotals[project.id] ?? 0,+ })),+ [usage]);+ const total = projects.reduce((sum, project) => sum + project.total, 0);- const wrapper = (node: React.ReactNode) => (- <Widget className="w-full">- <WidgetHead className="flex items-center justify-between">- <span className="title">Usage</span>- </WidgetHead>- <WidgetBody>{node}</WidgetBody>- </Widget>+ const chartData = useMemo<UsagePoint[]>(+ () =>+ (usage?.days ?? []).map((row) => ({+ date: new Date(`${row.day}T00:00:00`).getTime(),+ total: Object.values(row.counts).reduce((sum, n) => sum + n, 0),+ ...row.counts,+ })),+ [usage]);- if (usageQuery.isLoading) {- return wrapper(- <div className="center-center p-8">- <Loader2Icon className="animate-spin" />- </div>- );- }-- if (usageQuery.isError) {- return wrapper(- <div className="center-center p-8 font-medium">- Issues loading usage data- </div>- );- }+ const projectSlices = useMemo(+ () =>+ toSlices(+ projects.map((project) => ({+ id: project.id,+ label: project.name,+ value: project.total,+ color: project.color,+ })),+ total+ ),+ [projects, total]+ );- if (- usageQuery.data?.length === 0 ||- !usageQuery.data?.some((item) => item.count !== 0)- ) {- return wrapper(- <div className="center-center p-8 font-medium">No usage data yet</div>+ const selectedProject =+ projects.find((project) => project.id === selectedProjectId) ?? null;+ const namesTotal = selectedProject ? selectedProject.total : total;+ const nameSlices = useMemo(() => {+ const rows = selectedProject+ ? (usage?.eventNamesByProject[selectedProject.id] ?? [])+ : (usage?.eventNames ?? []);+ const named = rows.map((row, index) => ({+ label: row.name,+ value: row.count,+ color: getChartColor(index),+ }));+ const namedTotal = named.reduce((sum, row) => sum + row.value, 0);+ return toSlices(+ [+ ...named,+ {+ label: OTHER_LABEL,+ value: namesTotal - namedTotal,+ color: OTHER_COLOR,+ },+ ],+ namesTotal);- }+ }, [usage, selectedProject, namesTotal]);- const subscriptionPeriodEventsLimit = organization.hasSubscription- ? organization.subscriptionPeriodEventsLimit- : 0;- const subscriptionPeriodEventsCount = organization.hasSubscription- ? organization.subscriptionPeriodEventsCount- : 0;-- const processChartData = (): UsagePoint[] => {- if (!usageQuery.data) {- return [];+ const windowLabel = (() => {+ if (!usage) {+ return undefined;}+ const range = `${formatDate(new Date(`${usage.from}T00:00:00`))} – ${formatDate(new Date(`${usage.to}T00:00:00`))}`;+ const kind =+ usage.window === 'billing_period'+ ? 'Current billing period'+ : 'Last 30 days';+ return `${kind} · ${range}`;+ })();- if (useWeeklyIntervals) {- const weeklyData: {- [key: string]: { count: number; startDate: Date; endDate: Date };- } = {};-- for (const item of usageQuery.data) {- const date = new Date(item.day);- const startOfWeek = new Date(date);- const dayOfWeek = date.getDay();- // Weeks start on Monday; getDay() puts Sunday first.- const diff = date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);- startOfWeek.setDate(diff);- startOfWeek.setHours(0, 0, 0, 0);-- const weekKey = startOfWeek.toISOString().split('T')[0];-- if (!weeklyData[weekKey]) {- weeklyData[weekKey] = {- count: 0,- startDate: new Date(startOfWeek),- endDate: new Date(startOfWeek),- };- }-- weeklyData[weekKey].count += item.count;- weeklyData[weekKey].endDate = new Date(date);- }-- return Object.values(weeklyData).map((week) => ({- date: week.startDate.getTime(),- count: week.count,- weekRange: `${formatDate(week.startDate)} - ${formatDate(week.endDate)}`,- }));+ const renderState = () => {+ if (usageQuery.isLoading) {+ return (+ <div className="center-center p-8">+ <Loader2Icon className="animate-spin" />+ </div>+ );}-- return usageQuery.data.map((item) => ({- date: new Date(item.day).getTime(),- count: item.count,- }));+ if (usageQuery.isError) {+ return <Message>Issues loading usage data</Message>;+ }+ if (total === 0) {+ return <Message>No events in this period</Message>;+ }+ return null;};+ const state = renderState();- const chartData = processChartData();- const eventsLabel = useWeeklyIntervals- ? 'Events this week'- : 'Events this day';+ if (state) {+ return <UsageWidget title="Usage">{state}</UsageWidget>;+ }- return wrapper(- <>- <div className="-m-4 mb-4 grid grid-cols-2 border-b [&>div]:shadow-[0_0_0_0.5px] [&_div]:shadow-border">- {organization.hasSubscription ? (- <>- <Card- title="Period"- value={- organization.subscriptionCurrentPeriodStart &&- organization.subscriptionCurrentPeriodEnd- ? `${formatDate(organization.subscriptionCurrentPeriodStart)}-${formatDate(organization.subscriptionCurrentPeriodEnd)}`- : '🤷♂️'- }- />- <Card- title="Left to use"- value={- subscriptionPeriodEventsLimit === 0- ? '👀'- : number.formatWithUnit(- 1 -- subscriptionPeriodEventsCount /- subscriptionPeriodEventsLimit,- '%'- )- }- />- <Card- title="Events count"- value={number.format(subscriptionPeriodEventsCount)}- />- <Card- title="Limit"- value={number.format(subscriptionPeriodEventsLimit)}- />- </>- ) : (- <>- <div className="col-span-2">- <Card title="Subscription" value={'No active subscription'} />- </div>- <div className="col-span-2">- <Card- title="Events from last 30 days"- value={number.format(- sum(usageQuery.data?.map((item) => item.count) ?? [])- )}- />- </div>- </>- )}- </div>- <div className="space-y-2">- <h3 className="font-medium text-muted-foreground text-sm">- {useWeeklyIntervals ? 'Weekly Events' : 'Daily Events'}- </h3>+ const innerRadius = (PIE_SIZE / 2 - DEFAULT_HOVER_OFFSET) * DONUT_HOLE;++ return (+ <div className="grid grid-cols-1 gap-8 lg:grid-cols-3">+ <UsageWidget+ className="lg:col-span-2"+ subtitle={windowLabel}+ title="Events per project"+ ><ComposedChartanimationDuration={0}aspectRatio="auto"- className="h-[250px]"+ className="h-[260px]"data={chartData}- formatDateLabel={formatDateLabel}+ formatDateLabel={formatDayLabel}margin={MARGIN}- maxBarSize={useWeeklyIntervals ? WEEKLY_BAR_SIZE : DAILY_BAR_SIZE}+ maxBarSize={MAX_BAR_SIZE}+ stacked+ stackGap={STACK_GAP}xDataKey="date"><Grid horizontal /><YAxis formatValue={number.short} /><XAxis />- <SeriesBar- animate={false}- dataKey="count"- fill={BAR_COLOR}- radius={BAR_RADIUS}- />+ {projects.map((project) => (+ <SeriesBar+ animate={false}+ dataKey={project.id}+ fill={project.color}+ key={project.id}+ radius={BAR_RADIUS}+ />+ ))}<OPChartTooltip<UsagePoint>- interval={interval}+ interval="day"rows={(point) => [+ ...projects+ .map((project) => ({+ color: project.color,+ label: project.name,+ value: Number(point[project.id] ?? 0),+ format: number.format,+ }))+ .filter((row) => row.value > 0),{- color: BAR_COLOR,- label: eventsLabel,- value: point.count,+ color: 'transparent',+ label: 'Total',+ value: point.total,format: number.format,},]}showCrosshair={false}showDots={false}- title={(point) =>- point.weekRange ?? formatDate(new Date(point.date))- }+ title={(point) => formatDate(new Date(point.date))}/></ComposedChart>- </div>- </>+ <div className="mt-4 border-t pt-4">+ <SliceLegend+ onSelect={(index) =>+ selectProject(+ index === null ? null : (projectSlices[index]?.id ?? null)+ )+ }+ selectedIndex={+ selectedProject+ ? projectSlices.findIndex(+ (slice) => slice.id === selectedProject.id+ )+ : null+ }+ slices={projectSlices}+ />+ </div>+ </UsageWidget>++ <UsageWidget+ aside={+ selectedProject && (+ <Button+ onClick={() => selectProject(null)}+ size="sm"+ variant="outline"+ >+ All projects+ <XIcon className="ml-1 size-3.5" />+ </Button>+ )+ }+ subtitle={+ windowLabel &&+ `${selectedProject?.name ?? 'All projects'} · ${windowLabel}`+ }+ title="Events by name"+ >+ <div className="col items-center gap-4">+ <PieChart+ cornerRadius={CORNER_RADIUS}+ data={nameSlices}+ hoveredIndex={hoveredName}+ innerRadius={innerRadius}+ onHoverChange={setHoveredName}+ padAngle={PAD_ANGLE}+ size={PIE_SIZE}+ >+ {nameSlices.map((slice, index) => (+ <PieSlice+ animate={false}+ index={index}+ key={`${index}-${slice.label}`}+ />+ ))}+ <PieCenter>+ {({ value, isHovered }) => {+ const slice =+ hoveredName === null ? null : nameSlices[hoveredName];+ return (+ <div className="col max-w-[80%] items-center text-center">+ <div className="font-semibold text-lg tabular-nums">+ {number.short(value)}+ </div>+ <div className="w-full truncate text-muted-foreground text-xs">+ {isHovered && slice ? `${slice.share}%` : 'Total'}+ </div>+ </div>+ );+ }}+ </PieCenter>+ </PieChart>+ <div className="w-full">+ <SliceLegend+ hoveredIndex={hoveredName}+ onHover={setHoveredName}+ slices={nameSlices}+ />+ </div>+ </div>+ </UsageWidget>+ </div>);}diff --git a/apps/start/src/components/organization/billing.tsx b/apps/start/src/components/organization/billing.tsxindex 2f45d7dd3..ec6689532 100644--- a/apps/start/src/components/organization/billing.tsx+++ b/apps/start/src/components/organization/billing.tsx@@ -3,12 +3,13 @@ import { getSubscriptionStateMeta } from '@openpanel/payments/subscription-stateimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { differenceInDays } from 'date-fns';import { useQueryState } from 'nuqs';-import { useEffect, useMemo, useState } from 'react';+import { useEffect } from 'react';import { toast } from 'sonner';import { Progress } from '../ui/progress';import { Widget, WidgetBody, WidgetHead } from '../widget';import { BillingFaq } from './billing-faq';import BillingPlanPicker from './billing-plan-picker';+import { projectUsage } from './billing-projection';import BillingUsage from './billing-usage';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';@@ -18,9 +19,9 @@ import { useTRPC } from '@/integrations/trpc/react';import { pushModal, useOnPushModal } from '@/modals';import { formatDate } from '@/utils/date';-type Props = {+interface Props {organization: IServiceOrganization;-};+}export default function Billing({ organization }: Props) {const [success, setSuccess] = useQueryState('customer_session_token');@@ -28,12 +29,6 @@ export default function Billing({ organization }: Props) {const trpc = useTRPC();const number = useNumber();- const productsQuery = useQuery(- trpc.subscription.products.queryOptions({- organizationId: organization.id,- })- );-const currentProductQuery = useQuery(trpc.subscription.getCurrent.queryOptions({organizationId: organization.id,@@ -77,19 +72,7 @@ export default function Billing({ organization }: Props) {queryClient.invalidateQueries(trpc.subscription.pathFilter());});- const [recurringInterval, setRecurringInterval] = useState<'year' | 'month'>(- (organization.subscriptionInterval as 'year' | 'month') || 'month'- );-- const products = useMemo(() => {- return (productsQuery.data || [])- .filter((product) => product.recurringInterval === recurringInterval)- .filter((product) =>- // `free` no longer exists in the SDK's amountType union, but retired- // free-plan products can still come back from Polar's API.- product.prices.some((p) => (p.amountType as string) !== 'free')- );- }, [productsQuery.data, recurringInterval]);+ const recurringInterval = organization.subscriptionInterval ?? 'month';const currentProduct = currentProductQuery.data ?? null;const currentPrice = currentProduct?.prices.flatMap((p) =>@@ -183,12 +166,66 @@ export default function Billing({ organization }: Props) {}});- // Active subscribers manage an existing plan: current-plan card + usage on the- // left, FAQ on the right. Plan changes go through the modal.+ // Active subscribers manage an existing plan: current-plan card beside the+ // FAQ, then the usage breakdown across the full width so both charts fit.+ // Plan changes go through the modal.if (currentProduct && currentPrice) {+ const eventsLimit = Number(currentProduct.metadata.eventsLimit);+ const eventsLeft = Math.max(+ 0,+ eventsLimit - organization.subscriptionPeriodEventsCount+ );+ const periodStart = organization.subscriptionCurrentPeriodStart;+ const periodEnd = organization.subscriptionCurrentPeriodEnd;+ const periodLabel =+ periodStart && periodEnd+ ? `${formatDate(periodStart)} – ${formatDate(periodEnd)}`+ : null;+ const projection =+ periodStart && periodEnd+ ? projectUsage({+ used: organization.subscriptionPeriodEventsCount,+ limit: eventsLimit,+ periodStart,+ periodEnd,+ now: new Date(),+ })+ : null;+ const isOverLimit =+ eventsLimit > 0 &&+ organization.subscriptionPeriodEventsCount >= eventsLimit;+ const renderProjection = () => {+ if (isOverLimit) {+ return (+ <p className="text-destructive">+ Limit reached for this period. New events are not shown until the+ next period starts.+ </p>+ );+ }+ if (!projection) {+ return null;+ }+ const pace = `${number.format(Math.round(projection.perDay))} events a day`;+ if (projection.limitReachedAt) {+ return (+ <p className="text-destructive">+ At {pace} the limit is reached around{' '}+ {formatDate(projection.limitReachedAt)}, with about{' '}+ {number.format(projection.projectedTotal)} events by period end.+ </p>+ );+ }+ return (+ <p className="text-muted-foreground">+ At {pace} this period ends at about{' '}+ {number.format(projection.projectedTotal)} events.+ </p>+ );+ };return (- <div className="grid grid-cols-1 gap-8 md:grid-cols-2">- <div className="col gap-8">+ <div className="col gap-8">+ <div className="grid grid-cols-1 gap-8 md:grid-cols-2"><Widget className="w-full"><WidgetHead className="flex items-center justify-between gap-4"><div className="title flex-1 truncate">{currentProduct.name}</div>@@ -213,18 +250,33 @@ export default function Billing({ organization }: Props) {{renderStatus()}{renderDiscount()}<div className="col mt-4">- <div className="mb-2 font-semibold">- {number.format(organization.subscriptionPeriodEventsCount)} /{' '}- {number.format(Number(currentProduct.metadata.eventsLimit))}+ <div className="row mb-2 items-baseline justify-between gap-4">+ <div className="font-semibold">+ {number.format(organization.subscriptionPeriodEventsCount)}{' '}+ / {number.format(eventsLimit)} events+ </div>+ <div className="text-muted-foreground">+ {number.format(eventsLeft)} left+ </div></div><Progresssize="sm"value={- (organization.subscriptionPeriodEventsCount /- Number(currentProduct.metadata.eventsLimit)) *- 100+ eventsLimit+ ? (organization.subscriptionPeriodEventsCount /+ eventsLimit) *+ 100+ : 0}/>+ <div className="col mt-2 gap-1">+ {periodLabel && (+ <p className="text-muted-foreground">+ Current period {periodLabel}+ </p>+ )}+ {renderProjection()}+ </div><div className="row mt-4 justify-between"><Buttonloading={portalMutation.isPending}@@ -294,10 +346,10 @@ export default function Billing({ organization }: Props) {</WidgetBody></Widget>- <BillingUsage organization={organization} />+ <BillingFaq /></div>- <BillingFaq />+ <BillingUsage organization={organization} /></div>);}@@ -346,11 +398,10 @@ export default function Billing({ organization }: Props) {</WidgetBody></Widget>- <div className="col gap-8">- <BillingUsage organization={organization} />- <BillingFaq />- </div>+ <BillingFaq /></div>++ <BillingUsage organization={organization} /></div>);}diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex 9ec13cc26..5ade52a63 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -54,10 +54,6 @@ export type IServiceMember = Omit<// Session bookkeeping rows are worker-generated (the reaper can emit// session_end long after tracking stopped), so they are not billable activity.const NON_BILLABLE_EVENT_NAMES = ['session_start', 'session_end'];-/** A module function's parameters with its leading `ServiceDeps` dropped. */-type Tail<T extends unknown[]> = T extends [unknown, ...infer Rest]- ? Rest- : never;const DELETE_GRACE_PERIOD_MS = 24 * 60 * 60 * 1000;const INVITE_EXPIRY_MS = 3 * 24 * 60 * 60 * 1000;@@ -456,45 +452,129 @@ export async function getOrganizationEventsCountSince(return res[0]?.count ?? 0;}-export async function getOrganizationBillingEventsCountSerie(+export interface IOrganizationBillingUsageInput {+ projectIds: string[];+ /** Inclusive UTC day, `YYYY-MM-DD`. */+ from: string;+ /** Inclusive UTC day, `YYYY-MM-DD`. */+ to: string;+ /** Exact lower bound within `from`, `YYYY-MM-DD HH:mm:ss` UTC, when the window starts mid-day. */+ since?: string;+}++export interface IOrganizationBillingUsage {+ from: string;+ to: string;+ /** One row per UTC day in the window, zero-filled; `counts` is keyed by project id. */+ days: { day: string; counts: Record<string, number> }[];+ /** Billable events per project over the window. */+ projectTotals: Record<string, number>;+ /** The most frequent billable event names over the window, descending. */+ eventNames: { name: string; count: number }[];+ /** The same per project, keyed by project id. */+ eventNamesByProject: Record<string, { name: string; count: number }[]>;+}++// Enough slices for a legible pie; the dashboard folds the rest into "Other".+export const BILLING_USAGE_EVENT_NAMES_LIMIT = 9;+const MS_PER_DAY = 24 * 60 * 60 * 1000;++function listUtcDays(from: string, to: string): string[] {+ const days: string[] = [];+ const end = new Date(`${to}T00:00:00.000Z`).getTime();+ for (+ let cursor = new Date(`${from}T00:00:00.000Z`).getTime();+ cursor <= end;+ cursor += MS_PER_DAY+ ) {+ days.push(new Date(cursor).toISOString().slice(0, 10));+ }+ return days;+}++export async function getOrganizationBillingUsage(deps: ServiceDeps,- organization: IServiceOrganization & { projects: { id: string }[] },- {- startDate,- endDate,- }: {- startDate: Date;- endDate: Date;+ { projectIds, from, to, since }: IOrganizationBillingUsageInput+): Promise<IOrganizationBillingUsage> {+ const empty: IOrganizationBillingUsage = {+ from,+ to,+ days: listUtcDays(from, to).map((day) => ({ day, counts: {} })),+ projectTotals: {},+ eventNames: [],+ eventNamesByProject: {},+ };+ if (projectIds.length === 0) {+ return empty;}-): Promise<{ count: number; day: string }[]> {- // `day` is the SELECT alias, referenced by both the WHERE clause and the- // WITH FILL below.- const from = formatClickhouseDate(startDate, true);- const to = formatClickhouseDate(endDate, true);- const statement = sql`- SELECT COUNT(*) AS count, toDate(toStartOfDay(created_at)) AS day- FROM ${sql.id(TABLE_NAMES.events)} e- WHERE project_id IN ${sql.array(- 'String',- organization.projects.map((project) => project.id)- )}- AND day BETWEEN ${sql.string(from)} AND ${sql.string(to)}++ // Both statements share the billable-event filter so the pie's "Other"+ // slice (total minus the named slices) adds up against the bars.+ const billable = sql`+ project_id IN ${sql.array('String', projectIds)}+ AND toDate(created_at) BETWEEN toDate(${sql.string(from)}) AND toDate(${sql.string(to)})+ ${since ? sql`AND created_at >= ${sql.string(since)}` : sql.empty}AND name NOT IN ${sql.array('String', NON_BILLABLE_EVENT_NAMES)}- GROUP BY day- ORDER BY day WITH FILL FROM toDate(${sql.string(from)}) TO toDate(${sql.string(to)}) STEP INTERVAL 1 DAY`;+ const [perProjectDay, perName, perProjectName] = await Promise.all([+ chQuery<{ project_id: string; day: string; count: number }>(+ deps,+ sql`+ SELECT project_id, toDate(created_at) AS day, COUNT(*) AS count+ FROM ${sql.id(TABLE_NAMES.events)}+ WHERE ${billable}+ GROUP BY project_id, day+ `+ ),+ chQuery<{ name: string; count: number }>(+ deps,+ sql`+ SELECT name, COUNT(*) AS count+ FROM ${sql.id(TABLE_NAMES.events)}+ WHERE ${billable}+ GROUP BY name+ ORDER BY count DESC+ LIMIT ${sql.uint64(BILLING_USAGE_EVENT_NAMES_LIMIT)}+ `+ ),+ chQuery<{ project_id: string; name: string; count: number }>(+ deps,+ sql`+ SELECT project_id, name, COUNT(*) AS count+ FROM ${sql.id(TABLE_NAMES.events)}+ WHERE ${billable}+ GROUP BY project_id, name+ ORDER BY project_id, count DESC+ LIMIT ${sql.uint64(BILLING_USAGE_EVENT_NAMES_LIMIT)} BY project_id+ `+ ),+ ]);- return chQuery<{ count: number; day: string }>(deps, statement);+ const countsByDay = new Map(empty.days.map((row) => [row.day, row.counts]));+ for (const row of perProjectDay) {+ const count = Number(row.count);+ countsByDay.get(row.day)![row.project_id] = count;+ empty.projectTotals[row.project_id] =+ (empty.projectTotals[row.project_id] ?? 0) + count;+ }+ empty.eventNames = perName.map((row) => ({+ name: row.name,+ count: Number(row.count),+ }));+ for (const row of perProjectName) {+ const names = empty.eventNamesByProject[row.project_id] ?? [];+ names.push({ name: row.name, count: Number(row.count) });+ empty.eventNamesByProject[row.project_id] = names;+ }+ return empty;}-const BILLING_EVENTS_SERIE_CACHE_TTL_SEC = 60 * 10;-export const getOrganizationBillingEventsCountSerieCached = cacheablePerDeps(- 'getOrganizationBillingEventsCountSerie',- (- deps: ServiceDeps,- ...args: Tail<Parameters<typeof getOrganizationBillingEventsCountSerie>>- ) => getOrganizationBillingEventsCountSerie(deps, ...args),- BILLING_EVENTS_SERIE_CACHE_TTL_SEC+const BILLING_USAGE_CACHE_TTL_SEC = 60 * 10;+export const getOrganizationBillingUsageCached = cacheablePerDeps(+ 'getOrganizationBillingUsage',+ (deps: ServiceDeps, input: IOrganizationBillingUsageInput) =>+ getOrganizationBillingUsage(deps, input),+ BILLING_USAGE_CACHE_TTL_SEC);export async function getOrganizationSubscriptionChartEndDate(diff --git a/packages/core/src/modules/organization/organization.usage.test.ts b/packages/core/src/modules/organization/organization.usage.test.tsnew file mode 100644index 000000000..ff1f22c27--- /dev/null+++ b/packages/core/src/modules/organization/organization.usage.test.ts@@ -0,0 +1,174 @@+// `deps.ch.query` is what ch-query.ts calls; the stub dispatches on the+// statement text so both of the usage query's statements can answer in one+// `Promise.all`.++import { beforeEach, expect, mock, test } from 'bun:test';+import {+ BILLING_USAGE_EVENT_NAMES_LIMIT,+ getOrganizationBillingUsage,+} from './organization.service';++interface ChCall {+ query: string;+ query_params: Record<string, unknown>;+}++let perProjectDayRows: { project_id: string; day: string; count: string }[] =+ [];+let perNameRows: { name: string; count: string }[] = [];+let perProjectNameRows: { project_id: string; name: string; count: string }[] =+ [];+const calls: ChCall[] = [];++function rowsFor(query: string) {+ if (query.includes('GROUP BY project_id, name')) {+ return perProjectNameRows;+ }+ if (query.includes('GROUP BY name')) {+ return perNameRows;+ }+ return perProjectDayRows;+}++const chQuery = mock(async (args: ChCall) => {+ calls.push(args);+ const rows = rowsFor(args.query);+ return {+ json: async () => ({ data: rows, meta: [], rows: rows.length }),+ };+});++const noop = () => undefined;+const deps = {+ ch: { query: chQuery },+ logger: {+ fatal: noop,+ error: noop,+ warn: noop,+ info: noop,+ debug: noop,+ trace: noop,+ child: () => deps.logger,+ },+} as unknown as import('../../services').ServiceDeps;++beforeEach(() => {+ chQuery.mockClear();+ calls.length = 0;+ perProjectDayRows = [];+ perNameRows = [];+ perProjectNameRows = [];+});++test('pivots per-project counts onto a zero-filled day axis and totals them', async () => {+ // ClickHouse returns COUNT(*) as a string in JSON output.+ perProjectDayRows = [+ { project_id: 'web', day: '2026-10-01', count: '5' },+ { project_id: 'app', day: '2026-10-01', count: '2' },+ { project_id: 'web', day: '2026-10-03', count: '1' },+ ];+ perNameRows = [+ { name: 'screen_view', count: '6' },+ { name: 'purchase', count: '2' },+ ];+ perProjectNameRows = [+ { project_id: 'web', name: 'screen_view', count: '4' },+ { project_id: 'web', name: 'purchase', count: '2' },+ { project_id: 'app', name: 'screen_view', count: '2' },+ ];++ const usage = await getOrganizationBillingUsage(deps, {+ projectIds: ['web', 'app'],+ from: '2026-10-01',+ to: '2026-10-03',+ });++ expect(chQuery).toHaveBeenCalledTimes(3);+ expect(usage.days).toEqual([+ { day: '2026-10-01', counts: { web: 5, app: 2 } },+ { day: '2026-10-02', counts: {} },+ { day: '2026-10-03', counts: { web: 1 } },+ ]);+ expect(usage.projectTotals).toEqual({ web: 6, app: 2 });+ expect(usage.eventNames).toEqual([+ { name: 'screen_view', count: 6 },+ { name: 'purchase', count: 2 },+ ]);+ expect(usage.eventNamesByProject).toEqual({+ web: [+ { name: 'screen_view', count: 4 },+ { name: 'purchase', count: 2 },+ ],+ app: [{ name: 'screen_view', count: 2 }],+ });+});++test('every statement excludes session bookkeeping and the names are capped', async () => {+ await getOrganizationBillingUsage(deps, {+ projectIds: ['web'],+ from: '2026-10-01',+ to: '2026-10-01',+ });++ expect(calls).toHaveLength(3);+ for (const call of calls) {+ expect(call.query).toContain('name NOT IN');+ expect(Object.values(call.query_params)).toContainEqual([+ 'session_start',+ 'session_end',+ ]);+ }+ const nameCalls = calls.filter((call) =>+ /GROUP BY (project_id, )?name/.test(call.query)+ );+ expect(nameCalls).toHaveLength(2);+ for (const call of nameCalls) {+ expect(call.query).toContain('LIMIT');+ expect(Object.values(call.query_params)).toContainEqual(+ BILLING_USAGE_EVENT_NAMES_LIMIT+ );+ }+ expect(+ nameCalls.find((call) => call.query.includes('BY project_id'))?.query+ ).toContain('GROUP BY project_id, name');+});++test('an exact period start narrows the first day, and is absent otherwise', async () => {+ await getOrganizationBillingUsage(deps, {+ projectIds: ['web'],+ from: '2026-10-01',+ to: '2026-10-02',+ since: '2026-10-01 19:46:17',+ });+ for (const call of calls) {+ expect(call.query).toContain('created_at >=');+ expect(Object.values(call.query_params)).toContain('2026-10-01 19:46:17');+ }++ calls.length = 0;+ await getOrganizationBillingUsage(deps, {+ projectIds: ['web'],+ from: '2026-10-01',+ to: '2026-10-02',+ });+ for (const call of calls) {+ expect(call.query).not.toContain('created_at >=');+ }+});++test('an organization without projects gets the empty window without a query', async () => {+ const usage = await getOrganizationBillingUsage(deps, {+ projectIds: [],+ from: '2026-10-01',+ to: '2026-10-02',+ });++ expect(chQuery).not.toHaveBeenCalled();+ expect(usage.days.map((row) => row.day)).toEqual([+ '2026-10-01',+ '2026-10-02',+ ]);+ expect(usage.projectTotals).toEqual({});+ expect(usage.eventNames).toEqual([]);+ expect(usage.eventNamesByProject).toEqual({});+});diff --git a/packages/core/src/modules/subscription/subscription.service.ts b/packages/core/src/modules/subscription/subscription.service.tsindex 20a1823ec..dd867d0ac 100644--- a/packages/core/src/modules/subscription/subscription.service.ts+++ b/packages/core/src/modules/subscription/subscription.service.ts@@ -18,11 +18,13 @@ import { z } from 'zod';import type { Logger } from '../../logger';import { TRPCBadRequestError } from '../../rpc/errors';import type { ServiceDeps, Services } from '../../services';+import { formatClickhouseDate } from '../../shared/ch-dates';import { getAccessChecks } from '../auth/auth.service';import {- getOrganizationBillingEventsCountSerieCached,+ getOrganizationBillingUsageCached,getOrganizationById,getOrganizationByProjectIdCached,+ type IOrganizationBillingUsage,} from '../organization/organization.service';import {type ICancellationReason,@@ -34,7 +36,13 @@ import {const POLAR_PRODUCTS_CACHE_KEY = 'polar:products';const POLAR_PRODUCTS_CACHE_TTL_SECONDS = 60 * 60 * 24;-const DEFAULT_USAGE_WINDOW_DAYS = 30;+const TRAILING_USAGE_WINDOW_DAYS = 30;++export type IOrganizationUsage = IOrganizationBillingUsage & {+ projects: { id: string; name: string }[];+ /** `billing_period` runs from the current period's start to today. */+ window: 'billing_period' | 'trailing';+};async function requireOrgAdmin(userId: string,@@ -143,40 +151,46 @@ export async function listProducts(deps: ServiceDeps, organizationId: string) {});}-export async function getUsage(deps: ServiceDeps, organizationId: string) {+export async function getUsage(+ deps: ServiceDeps,+ organizationId: string+): Promise<IOrganizationUsage> {const organization = await deps.db.organization.findUniqueOrThrow({where: { id: organizationId },- include: { projects: { select: { id: true } } },+ include: {+ projects: {+ select: { id: true, name: true },+ orderBy: { createdAt: 'asc' },+ },+ },});-- if (- organization.hasSubscription &&- organization.subscriptionStartsAt &&- organization.subscriptionEndsAt- ) {- // The CURRENT billing period, not the whole subscription term. The usage- // counter this chart sits beside resets each period, and- // `subscriptionStartsAt` is overwritten with each period start on renewal,- // so one interval from it is the period the counter belongs to. A term- // running years out — a seeded org, or a long commitment — would otherwise- // bucket thousands of days and repeat week numbers along the axis.- const periodEnd = addMonths(- organization.subscriptionStartsAt,- organization.subscriptionInterval === 'year' ? 12 : 1- );- return getOrganizationBillingEventsCountSerieCached(deps, organization, {- startDate: organization.subscriptionStartsAt,- endDate:- periodEnd < organization.subscriptionEndsAt- ? periodEnd- : organization.subscriptionEndsAt,- });- }-- return getOrganizationBillingEventsCountSerieCached(deps, organization, {- startDate: subDays(new Date(), DEFAULT_USAGE_WINDOW_DAYS),- endDate: new Date(),+ // The period the usage counter belongs to, so the breakdown adds up to the+ // number on the plan card. `subscriptionCurrentPeriodStart` is already the+ // monthly cycle for yearly plans, since limits are per month. Gated on the+ // product too, as the plan card is: without one there is no counter to match.+ const today = new Date();+ const hasPlan =+ organization.hasSubscription && organization.subscriptionProductId !== null;+ const periodStart = hasPlan+ ? organization.subscriptionCurrentPeriodStart+ : null;+ const isBillingPeriod = periodStart !== null && periodStart <= today;+ const from = isBillingPeriod+ ? periodStart+ : subDays(today, TRAILING_USAGE_WINDOW_DAYS - 1);+ // The counter starts at the exact period start, so the first day only+ // counts from that moment.+ const usage = await getOrganizationBillingUsageCached(deps, {+ projectIds: organization.projects.map((project) => project.id),+ from: formatClickhouseDate(from, true),+ to: formatClickhouseDate(today, true),+ since: isBillingPeriod ? formatClickhouseDate(from) : undefined,});+ return {+ ...usage,+ projects: organization.projects,+ window: isBillingPeriod ? 'billing_period' : 'trailing',+ };}export async function cancelSubscription(