Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(customer-analytics): aggregate account usage by interval (#99298)

Arthur Moreira de Deusd94489185862
diff --git a/docs/internal/customer-analytics-billing-tabs.md b/docs/internal/customer-analytics-billing-tabs.md
index 68e1c954a581..13ab60ce04d6 100644
--- a/docs/internal/customer-analytics-billing-tabs.md
+++ b/docs/internal/customer-analytics-billing-tabs.md
@@ -7,3 +7,14 @@ SQL variable pickers are hidden because these values are controlled by the accou
Supported SQL charts render through `AccountBillingChart`. Other visualizations, including series
breakdowns, render through an embedded `Query` in a fixed-height container. Embedded SQL charts fill
that container; standalone SQL insights retain their viewport-based height.
+
+The Usage tab offers Daily, Weekly, and Monthly aggregation. Daily is the default.
+Weekly buckets start on Monday; monthly buckets start on the first day of the month.
+Each bucket sums only the daily usage inside the selected date range, so edge buckets can be partial.
+The tab groups the existing saved query's date and value columns without changing the saved insight.
+Spend insights retain their existing monthly calculations.
+
+Usage queries request up to 10,000 buckets so year-to-date ranges are not cut off by SQL table pagination.
+Automatic usage charts use the account chart renderer, with date-axis tick spacing and wrapping series
+controls outside the fixed-height plot. The interval and date controls wrap in narrow containers.
+The selected interval survives tab switches while the account remains open.
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index d0bb02bdc5e2..6099e7a963bc 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -191,6 +191,8 @@ With the flag disabled, the body is `AccountNotebooksExpansion`: the Useful link
The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. Its "Access level" and "Last logged in" headers sort (server-side for US orgs via `ordering`, client-side for cached EU rows; sorting is not written to the URL since it's per expanded row), and the "Access level" header carries a filter menu (owner / admin / member checkboxes, count badge) built with the shared `columnValueFilter` helper in `components/columnValueFilter.tsx`, which turns any enumerated column into a header filter and leaves the actual filtering to the caller. Staff also see an "Impersonate" action that opens the user's Django admin detail page in the member's US or EU cloud. Outside PostHog Cloud, the action stays on the current origin so local and self-hosted users can test their own admin. The **Usage/Spend** tabs are different: their insight results live in `dataNodeLogic`/`dataVisualizationLogic`. After each `accountBillingLogic` loads its saved-insight metadata, it mounts those result logics immediately. Because the expanded-row root mounts both billing kinds, all Usage and Spend queries start when the account expands instead of waiting for a tab click. The result logics stay mounted until the row collapses. Changing the date range replaces each insight's preload and aborts work under the previous query key. The tab body reuses the same keyed logics and attaches them to `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this directly, and the fallback `<Query>` path uses `attachTo={accountBillingLogic-instance}` plus matching insight context. This prevents duplicate loads and keeps results across tab switches. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded query, so the root `useMountedLogic` above is enough — it needs no attachment.)
+Usage aggregation lives in `billingUsageQuery.ts`: the Usage tab wraps the saved daily query to sum its configured value columns into day/week/month buckets, preserving account/date variables and query tags. `accountBillingLogic.displayInsights` supplies the same derived query to preloads and rendered charts. The interval is part of the cache key, survives tab switches, and defaults to daily. `AccountDetailTabs` holds a usage-logic mount so the detail scene keeps that state too. Weeks start Monday; edge buckets include only dates within the selected range. Automatic usage charts render as account-owned line charts so the series controls wrap outside the plot. Spend retains its saved calculations.
+
The Usage and Spend tabs render existing saved billing insights — **point users to them, don't rebuild billing as new insights.**
**Customer analytics owns the billing chart render.** Each billing chart is multi-series on one shared axis, so a small-magnitude series (e.g. feature flag requests) is a flat sliver against large ones (events/enhanced persons) and can't be read. To offer per-series show/hide **without touching shared data-viz code**, `AccountBillingChart` renders the saved insight's SQL chart directly via `@posthog/quill-charts` instead of an embedded `<Query>`/DataVisualization. It reuses `dataVisualizationLogic` read-only for fetch + SQL-results→series parsing, and renders via `sqlLineGraphAdapter.ts`'s pure builders — the same series building, render dispatch, and line/bar/combo config building (per-column formatting, area fills, right-axis routing, goal and trend lines, percent stacks, plus the 200-series render cap applied locally) the SQL insight chart uses — while staying off that chart's React layer (`SqlChart`/`useSqlChartModel`). Chart-semantics changes belong in the adapter (covered by `sqlLineGraphAdapter.test.ts`), not here. Hidden series are injected into quill's controlled `legend.hiddenKeys` (excluded from drawing and scales; the rest rescale into the freed space). `AccountBillingSeriesToggle` is the control: a compact chip row under each chart, one chip per series colored to match its line/bar (items come from `legendItemsFromSeries` over the same `buildSeries` output the chart draws, so keys and colors can't drift), plus Select all / Clear all buttons at the end of the row that show or hide every series at once (`setAllSeriesHidden`, dispatched with the chart's own key list). The hidden-keys state lives in `accountBillingLogic` (`ephemeralHiddenSeriesKeysByShortId`, keyed per insight because the spend tab renders two) — per-view only: never written to the saved insight, reset on date change, gone on row collapse. Queries whose shape `AccountBillingChart` can't render (non-DataViz, table/number/pie displays, series breakdowns — see `canRenderBillingChart`) fall back to the embedded `<Query>` with no chips. Billing queries stay embedded in both the account list and detail scene: the account and date filter supply SQL variables, so their read-only pickers remain hidden. Embedded SQL charts use their container height instead of the standalone insight viewport height.
@@ -376,6 +378,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
| `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
| `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |
| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities` \| `summaries` \| `support_tickets` \| `email_threads` \| `meetings` \| `event_stream`) |
+| `customer analytics account usage interval changed` | `accountBillingLogic` `setUsageInterval` listener | `interval` (`day` \| `week` \| `month`) |
| `customer analytics account usage series toggled` | `accountBillingLogic` `toggleHiddenSeriesKey` listener (dispatched by the `AccountBillingSeriesToggle` chips) | `kind` (`usage` \| `spend`), `is_hidden` (the post-click state), `series_count` (no series label / no PII) |
| `customer analytics account usage series bulk toggled` | `accountBillingLogic` `setAllSeriesHidden` listener (dispatched by the Select all / Clear all buttons in `AccountBillingSeriesToggle`) | `kind` (`usage` \| `spend`), `is_hidden` (`true` when hiding all, `false` when showing all), `series_count` (no series label / no PII) |
| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx
index fb99f4a84452..39caadb0207d 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import * as burningMoneyHogPng from '@posthog/brand/hoggies/png/burning-money'
import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass-1'
-import { LemonSkeleton } from '@posthog/lemon-ui'
+import { LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
@@ -43,8 +43,16 @@ export function AccountBillingExpansion({
kind: AccountBillingKind
}): JSX.Element {
const logic = accountBillingLogic({ accountId, externalId, kind })
- const { savedInsights, savedInsightsLoading, dateRange, variableOverridesByShortId, queryKeyFor } = useValues(logic)
- const { setDateRange } = useActions(logic)
+ const {
+ displayInsights: savedInsights,
+ savedInsightsLoading,
+ dateRange,
+ variableOverridesByShortId,
+ queryKeyFor,
+ usageInterval,
+ canAggregateUsage,
+ } = useValues(logic)
+ const { setDateRange, setUsageInterval } = useActions(logic)
if (!externalId) {
return <div className="p-4 text-secondary">This account has no linked organization.</div>
@@ -62,11 +70,26 @@ export function AccountBillingExpansion({
return (
<div className="flex flex-col gap-3">
- <DateFilter
- dateFrom={dateRange.date_from}
- dateTo={dateRange.date_to}
- onChange={(from, to) => setDateRange(from, to)}
- />
+ <div className="flex flex-wrap items-center gap-2">
+ <DateFilter
+ dateFrom={dateRange.date_from}
+ dateTo={dateRange.date_to}
+ onChange={(from, to) => setDateRange(from, to)}
+ />
+ {canAggregateUsage && (
+ <LemonSelect
+ value={usageInterval}
+ onChange={setUsageInterval}
+ options={[
+ { value: 'day', label: 'Daily' },
+ { value: 'week', label: 'Weekly' },
+ { value: 'month', label: 'Monthly' },
+ ]}
+ aria-label="Usage aggregation"
+ data-attr="account-usage-interval"
+ />
+ )}
+ </div>
{savedInsights.map((insight) => {
const queryKey = queryKeyFor(insight.short_id)
const variablesOverride = variableOverridesByShortId[insight.short_id] ?? null
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
index 2b490d40a0e0..9b0e85856038 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
@@ -1,4 +1,4 @@
-import { useValues } from 'kea'
+import { useMountedLogic, useValues } from 'kea'
import type { ReactNode } from 'react'
import { LemonTabs } from '@posthog/lemon-ui'
@@ -12,6 +12,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { CustomerTasksTabContent } from '../CustomerTasks/CustomerTasksTabContent'
import { AccountEventStreamToggle } from '../EventStream/AccountEventStreamToggle'
import { AccountBillingExpansion } from './AccountBillingExpansion'
+import { accountBillingLogic } from './accountBillingLogic'
import { AccountConversationsExpansion } from './AccountConversationsExpansion'
import { AccountFeatureRequestsExpansion } from './AccountFeatureRequestsExpansion'
import { AccountMeetingsExpansion } from './AccountMeetingsExpansion'
@@ -38,6 +39,7 @@ export function AccountDetailTabs({
rightSlot,
embedded = true,
}: AccountDetailTabsProps): JSX.Element {
+ useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'usage' }))
const { featureFlags } = useValues(featureFlagLogic)
const visibleActiveTab = getVisibleAccountExpansionTab(activeTab, featureFlags)
const canCreateTasks = userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Editor)
diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
index d4489797979f..006d8c425dcc 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
@@ -7,7 +7,7 @@ import { insightsApi } from 'scenes/insights/utils/api'
import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
-import type { QueryBasedInsightModel } from '~/types'
+import { ChartDisplayType, type QueryBasedInsightModel } from '~/types'
import {
AccountBillingKind,
@@ -15,6 +15,7 @@ import {
BILLING_INSIGHT_SHORT_IDS,
getBillingDataVisualizationKey,
} from './accountBillingLogic'
+import { AccountsEvents } from './constants'
const ORG_VARIABLE_ID = 'var-org'
const START_VARIABLE_ID = 'var-start'
@@ -25,9 +26,11 @@ const buildBillingInsight = (shortId: string): QueryBasedInsightModel =>
short_id: shortId,
query: {
kind: NodeKind.DataVisualizationNode,
+ display: ChartDisplayType.Auto,
+ chartSettings: { xAxis: { column: 'day' }, yAxis: [{ column: 'Requests' }] },
source: {
kind: NodeKind.HogQLQuery,
- query: 'SELECT 1',
+ query: "SELECT toDate('2024-01-01') AS day, 7 AS Requests",
variables: {
[ORG_VARIABLE_ID]: { variableId: ORG_VARIABLE_ID, code_name: 'billing_org_id', value: null },
[START_VARIABLE_ID]: {
@@ -142,6 +145,44 @@ describe('accountBillingLogic', () => {
expect(initialPreloads.every((preload) => !preload.isMounted())).toBe(true)
})
+ it('aggregates usage without changing saved insights or spend, and replaces the cached query on interval changes', async () => {
+ mountForKind()
+ await expectLogic(logic).toFinishAllListeners()
+ const savedQuery = logic.values.savedInsights![0].query
+ const firstShortId = BILLING_INSIGHT_SHORT_IDS[kind][0]
+ const initialKey = logic.values.queryKeyFor(firstShortId)
+ if (kind === 'spend') {
+ expect(logic.values.canAggregateUsage).toBe(false)
+ expect(logic.values.displayInsights![0].query).toBe(savedQuery)
+ return
+ }
+
+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ expect(logic.values.canAggregateUsage).toBe(true)
+ for (const interval of ['week', 'month', 'day'] as const) {
+ logic.actions.setUsageInterval(interval)
+ await expectLogic(logic).toFinishAllListeners()
+ const query = logic.values.displayInsights![0].query as DataVisualizationNode
+ expect(query.source.query).toContain(
+ {
+ day: 'usage.day AS day',
+ week: 'toStartOfWeek(usage.day, 1) AS day',
+ month: 'toStartOfMonth(usage.day) AS day',
+ }[interval]
+ )
+ expect(query.source.query).toContain('sum(usage.Requests) AS Requests')
+ expect(query.source.query).toContain('LIMIT 10000')
+ expect(query.source.variables).toEqual((savedQuery as DataVisualizationNode).source.variables)
+ expect(query.display).toBe(ChartDisplayType.ActionsLineGraph)
+ expect(logic.values.savedInsights![0].query).toBe(savedQuery)
+ expect(captureSpy).toHaveBeenCalledWith(AccountsEvents.UsageIntervalChanged, { interval })
+ if (interval !== 'day') {
+ expect(logic.values.queryKeyFor(firstShortId)).not.toBe(initialKey)
+ }
+ }
+ expect(api.query).toHaveBeenCalledTimes(4)
+ })
+
it('keeps hidden series keyed per insight, so hiding on one of the two spend charts sharing this logic does not hide on the other, and resets them on date change', () => {
const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
mountForKind()
diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
index 2fc70694e148..59d7aa84c96b 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
@@ -29,6 +29,7 @@ import {
import { InsightShortId, QueryBasedInsightModel } from '~/types'
import type { Node } from '../../../../../frontend/src/queries/schema/schema-general'
+import { BillingUsageInterval, billingUsageQuery, supportsUsageAggregation } from './billingUsageQuery'
import { AccountsEvents } from './constants'
export type AccountBillingKind = 'usage' | 'spend'
@@ -117,12 +118,15 @@ function buildVariableOverrides(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountBillingLogicValues {
+ canAggregateUsage: boolean
dateRange: BillingDateRange
+ displayInsights: QueryBasedInsightModel[] | null
ephemeralHiddenSeriesKeysByShortId: Record<string, string[]>
queryKeyFor: (shortId: string) => string
resolvedDateRange: BillingDateRange
savedInsights: QueryBasedInsightModel[] | null
savedInsightsLoading: boolean
+ usageInterval: BillingUsageInterval
variableOverridesByShortId: Record<string, Record<string, HogQLVariable>>
}
@@ -159,6 +163,9 @@ export interface accountBillingLogicActions {
dateFrom: string | null
dateTo: string | null
}
+ setUsageInterval: (interval: BillingUsageInterval) => {
+ interval: BillingUsageInterval
+ }
toggleHiddenSeriesKey: (
shortId: string,
seriesKey: string,
@@ -174,13 +181,27 @@ export interface accountBillingLogicActions {
export interface accountBillingLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ canAggregateUsage: (
+ savedInsights: QueryBasedInsightModel<Node<Record<string, any>>>[] | null,
+ arg: any
+ ) => boolean
+ displayInsights: (
+ savedInsights: QueryBasedInsightModel<Node<Record<string, any>>>[] | null,
+ usageInterval: BillingUsageInterval,
+ canAggregateUsage: boolean
+ ) => QueryBasedInsightModel[] | null
resolvedDateRange: (dateRange: BillingDateRange) => BillingDateRange
variableOverridesByShortId: (
savedInsights: QueryBasedInsightModel<Node<Record<string, any>>>[] | null,
resolvedDateRange: BillingDateRange,
arg: any
) => Record<string, Record<string, HogQLVariable>>
- queryKeyFor: (resolvedDateRange: BillingDateRange, arg: any, arg2: any) => (shortId: string) => string
+ queryKeyFor: (
+ resolvedDateRange: BillingDateRange,
+ arg: any,
+ arg2: any,
+ usageInterval: BillingUsageInterval
+ ) => (shortId: string) => string
}
}
@@ -196,6 +217,7 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
props({} as AccountBillingLogicProps),
key((props) => `${props.accountId}:${props.kind}`),
actions({
+ setUsageInterval: (interval: BillingUsageInterval) => ({ interval }),
setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
toggleHiddenSeriesKey: (shortId: string, seriesKey: string, seriesCount: number) => ({
shortId,
@@ -209,6 +231,7 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
}),
}),
reducers(({ props }) => ({
+ usageInterval: ['day' as BillingUsageInterval, { setUsageInterval: (_, { interval }) => interval }],
dateRange: [
DEFAULT_DATE_RANGE[props.kind] as BillingDateRange,
{
@@ -258,11 +281,15 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
}
return {
- loadSavedInsightsSuccess: ({ savedInsights }) => {
- preloadSavedInsights(savedInsights)
+ loadSavedInsightsSuccess: () => {
+ preloadSavedInsights(values.displayInsights ?? [])
},
setDateRange: () => {
- preloadSavedInsights(values.savedInsights ?? [])
+ preloadSavedInsights(values.displayInsights ?? [])
+ },
+ setUsageInterval: ({ interval }) => {
+ preloadSavedInsights(values.displayInsights ?? [])
+ posthog.capture(AccountsEvents.UsageIntervalChanged, { interval })
},
toggleHiddenSeriesKey: ({ shortId, seriesKey, seriesCount }) => {
posthog.capture(AccountsEvents.UsageSeriesToggled, {
@@ -310,6 +337,27 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
],
})),
selectors({
+ canAggregateUsage: [
+ (s) => [s.savedInsights, (_, p) => p.kind],
+ (savedInsights: QueryBasedInsightModel[] | null, kind: AccountBillingKind): boolean =>
+ kind === 'usage' &&
+ !!savedInsights?.length &&
+ savedInsights.every(({ query }) => supportsUsageAggregation(query)),
+ ],
+ displayInsights: [
+ (s) => [s.savedInsights, s.usageInterval, s.canAggregateUsage],
+ (
+ savedInsights: QueryBasedInsightModel[] | null,
+ interval: BillingUsageInterval,
+ canAggregate: boolean
+ ): QueryBasedInsightModel[] | null =>
+ canAggregate
+ ? savedInsights!.map((insight) => ({
+ ...insight,
+ query: billingUsageQuery(insight.query as DataVisualizationNode, interval),
+ }))
+ : savedInsights,
+ ],
// The saved insights filter on a calendar date column, so the range must be resolved to absolute dates.
resolvedDateRange: [
(s) => [s.dateRange],
@@ -342,10 +390,10 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
// The embedded <Query> only refetches when its query changes, not when variablesOverride changes — so a date
// change must remount it. Keying on the resolved range gives each insight a key that changes with the range.
queryKeyFor: [
- (s) => [s.resolvedDateRange, (_, p) => p.accountId, (_, p) => p.kind],
- (resolvedDateRange: BillingDateRange, accountId, kind) =>
+ (s) => [s.resolvedDateRange, (_, p) => p.accountId, (_, p) => p.kind, s.usageInterval],
+ (resolvedDateRange: BillingDateRange, accountId, kind, interval: BillingUsageInterval) =>
(shortId: string): string =>
- `account-billing-${accountId}-${kind}-${shortId}-${resolvedDateRange.date_from}-${resolvedDateRange.date_to}`,
+ `account-billing-${accountId}-${kind}-${shortId}-${resolvedDateRange.date_from}-${resolvedDateRange.date_to}-${interval}`,
],
}),
afterMount(({ actions, props }) => {
diff --git a/products/customer_analytics/frontend/components/Accounts/billingUsageQuery.ts b/products/customer_analytics/frontend/components/Accounts/billingUsageQuery.ts
new file mode 100644
index 000000000000..77ce45d8b322
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/billingUsageQuery.ts
@@ -0,0 +1,47 @@
+import { DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
+import { escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
+import { ChartDisplayType } from '~/types'
+
+export type BillingUsageInterval = 'day' | 'week' | 'month'
+
+export function supportsUsageAggregation(query: unknown): query is DataVisualizationNode {
+ const node = query as DataVisualizationNode | null
+ return (
+ node?.kind === NodeKind.DataVisualizationNode &&
+ node.source.kind === NodeKind.HogQLQuery &&
+ !node.source.connectionId &&
+ !node.chartSettings?.seriesBreakdownColumn &&
+ !!node.chartSettings?.xAxis?.column &&
+ !!node.chartSettings?.yAxis?.length
+ )
+}
+
+export function billingUsageQuery(query: DataVisualizationNode, interval: BillingUsageInterval): DataVisualizationNode {
+ if (!supportsUsageAggregation(query)) {
+ return query
+ }
+ const dateColumn = escapeRawPropertyAsHogQLIdentifier(query.chartSettings!.xAxis!.column)
+ const valueColumns = [...new Set(query.chartSettings!.yAxis!.map(({ column }) => column))].map(
+ escapeRawPropertyAsHogQLIdentifier
+ )
+ const source = query.source.query.trim().replace(/;$/, '')
+ const bucket = {
+ day: `usage.${dateColumn}`,
+ week: `toStartOfWeek(usage.${dateColumn}, 1)`,
+ month: `toStartOfMonth(usage.${dateColumn})`,
+ }[interval]
+ const select = [
+ `${bucket} AS ${dateColumn}`,
+ ...valueColumns.map((column) => `sum(usage.${column}) AS ${column}`),
+ ].join(',\n ')
+
+ return {
+ ...query,
+ display: query.display === ChartDisplayType.Auto ? ChartDisplayType.ActionsLineGraph : query.display,
+ source: {
+ ...query.source,
+ // An explicit limit avoids the SQL table paginator truncating long daily ranges.
+ query: `SELECT\n ${select}\nFROM (\n${source}\n) AS usage\nGROUP BY ${dateColumn}\nORDER BY ${dateColumn}\nLIMIT 10000`,
+ },
+ }
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index 10f03b62f778..7afc3ae1414b 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -52,6 +52,7 @@ export const AccountsEvents = {
NotesSearched: 'customer analytics accounts notes searched',
NotesSorted: 'customer analytics accounts notes sorted',
TabViewed: 'customer analytics account tab viewed',
+ UsageIntervalChanged: 'customer analytics account usage interval changed',
UsageSeriesToggled: 'customer analytics account usage series toggled',
UsageSeriesBulkToggled: 'customer analytics account usage series bulk toggled',
RelatedUserClicked: 'customer analytics account related user clicked',