: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): add usage tab to account rows (#61635)
Arthur Moreira de Deusefa105104734
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a4cb3b425418..9e3639317559 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4298,6 +4298,14 @@ snapshots:hash: v1.k794b7964.db477f267006ea1a7c62dcc6650babdb05173670d274cb6e2c13eb7d507efdee.u0g7FlaBy1aMwj2qdxZtZwbP5SbJrJAQ_8yzC13I6Psscenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:hash: v1.k794b7964.b351959bb62bd40e5bcf62b774dc9d22484ae233784b67b7b64c29fc22c5e90a.pkRs8TqG9UAOhgvNduTlGYGfkoG9UGg35yf77xuRh6A+ scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:+ hash: v1.k794b7964.9d3e9c149633e6f1677c52086eab4923d9154084843bc072f09c1ea49191c81e.lN_ygX8-IRvnUCJMJxSorgYUrIBxplHmxr0zRhbH7Dw+ scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:+ hash: v1.k794b7964.dbed81a9f646d861c5fea01fbb66409ca2134d052126c83910f0d48cc7c229b9.NTmSJa7n10fuCNA-jmRnxjcAV6Na8sJSdTOwg0LZb7M+ scenes-app-customer-analytics-accounts--row-expanded-usage-populated--dark:+ hash: v1.k794b7964.51df31b2f26139195bd36ff3a49dc9ef508ece5a82b27531c67a079b8ba0c3d5.G6zXVyDobNnlIPNswkE8aailxmojSt2QNJ5ov3tGwKs+ scenes-app-customer-analytics-accounts--row-expanded-usage-populated--light:+ hash: v1.k794b7964.9f2f530882c939501fe180e1cf3ff3bf2af41ec6a37648b0db528aaa3d1532b9.kQ4UI7ylaSo9OoZGNrq3eIOTcrmezd00e3LSUCGpZ30scenes-app-customer-analytics-accounts--row-expanded-with-note--dark:hash: v1.k794b7964.3c9ce002ecb9931c56ef82618cc1625ee847a7f8df2a35c490006e4b356e6fb5.bK3yVZfb-U4TUMJHKvLemkMdqx6YNKdkFC2lnrWBgYgscenes-app-customer-analytics-accounts--row-expanded-with-note--light:diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsxnew file mode 100644index 000000000000..75302bfe92bf--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx@@ -0,0 +1,80 @@+import { useActions, useValues } from 'kea'++import { LemonSkeleton } from '@posthog/lemon-ui'++import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { BurningMoneyHog, DetectiveHog } from 'lib/components/hedgehogs'++import { Query } from '~/queries/Query/Query'++import { AccountBillingKind, accountBillingLogic } from './accountBillingLogic'++const KIND_NOTE: Record<AccountBillingKind, string | null> = {+ usage: null,+ spend: 'Daily billed units (not dollars).',+}++function BillingInsightNotFound({ kind }: { kind: AccountBillingKind }): JSX.Element {+ const Hog = kind === 'spend' ? BurningMoneyHog : DetectiveHog+ return (+ <div className="flex flex-col items-center justify-center gap-2 p-8 text-center">+ <Hog className="w-24 h-24" />+ <h4 className="mb-0">No billing {kind} insight here</h4>+ <p className="text-secondary max-w-sm mb-0">+ We couldn't find the saved billing {kind} insight in this environment.+ </p>+ </div>+ )+}++export function AccountBillingExpansion({+ accountId,+ externalId,+ kind,+}: {+ accountId: string+ externalId: string+ kind: AccountBillingKind+}): JSX.Element {+ const logic = accountBillingLogic({ accountId, externalId, kind })+ const { savedInsight, savedInsightLoading, dateRange, variableOverrides } = useValues(logic)+ const { setDateRange } = useActions(logic)++ if (!externalId) {+ return <div className="p-4 text-secondary">This account has no linked organization.</div>+ }++ if (savedInsightLoading) {+ return <LemonSkeleton className="h-64 w-full" />+ }++ const query = savedInsight?.query+ if (!query) {+ return <BillingInsightNotFound kind={kind} />+ }++ const note = KIND_NOTE[kind]++ return (+ <div className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ <DateFilter+ dateFrom={dateRange.date_from}+ dateTo={dateRange.date_to}+ onChange={(from, to) => setDateRange(from, to)}+ />+ {note ? <span className="text-xs text-secondary">{note}</span> : null}+ </div>+ {/* Embedded DataVisualization collapses to a sliver without a fixed-height parent (InsightCard__viz is flex:1, min-height:0). */}+ <div className="h-80 flex flex-col overflow-hidden">+ <Query+ uniqueKey={`account-billing-${accountId}-${kind}`}+ query={query}+ variablesOverride={variableOverrides ?? null}+ readOnly+ embedded+ />+ </div>+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex 06a658927709..9bd7be4d6233 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -20,6 +20,7 @@ import { urls } from 'scenes/urls'import type { AccountNotebookApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import { AccountBillingExpansion } from './AccountBillingExpansion'import { accountLinksLogic } from './accountLinksLogic'import { accountNotebooksLogic } from './accountNotebooksLogic'import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'@@ -94,7 +95,7 @@ export function AccountNotebooksExpansion({}): JSX.Element {const logic = accountNotebooksLogic({ accountId })const { notebooks, notebooksLoading } = useValues(logic)- const [activeTab, setActiveTab] = useState<'notes' | 'users'>('notes')+ const [activeTab, setActiveTab] = useState<'notes' | 'users' | 'usage'>('notes')const columns: LemonTableColumns<AccountNotebookApi> = [{@@ -192,6 +193,17 @@ export function AccountNotebooksExpansion({label: 'Users',content: <AccountRelatedUsersExpansion externalId={externalId} />,},+ {+ key: 'usage',+ label: 'Usage',+ content: (+ <AccountBillingExpansion+ accountId={accountId}+ externalId={externalId}+ kind="usage"+ />+ ),+ },]}/></div>diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex 1d122f04e4d0..dd59607bd0a7 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -12,6 +12,7 @@ const QUERY_ENDPOINT = '/api/environments/:team_id/query/:kind/'const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'const WAREHOUSE_VIEW_LINK_ENDPOINT = 'api/environments/:team_id/warehouse_view_link/'+const INSIGHTS_ENDPOINT = 'api/environments/:team_id/insights/'type AccountNameCell = { name: string; external_id: string | null; id: string }type AccountRoleCell = [number, string] | null@@ -91,6 +92,91 @@ const ACCOUNT_WITHOUT_LINKS = {updated_at: '2026-05-15T10:30:00Z',}+const EMPTY_INSIGHTS = { count: 0, next: null, previous: null, results: [] }++function insightsResponse(insight: Record<string, unknown>): Record<string, unknown> {+ return { count: 1, next: null, previous: null, results: [insight] }+}++const BILLING_VARIABLES = {+ 'var-org': { variableId: 'var-org', code_name: 'billing_org_id', value: '' },+ 'var-start': { variableId: 'var-start', code_name: 'billing_start_date', value: '2026-04-21' },+ 'var-end': { variableId: 'var-end', code_name: 'billing_end_date', value: '2026-05-21' },+}++const USAGE_INSIGHT = {+ id: 9050931,+ short_id: 'fiJDsKLp',+ name: 'Billing usage by type (warehouse)',+ filters: {},+ saved: true,+ deleted: false,+ query: {+ kind: 'DataVisualizationNode',+ display: 'ActionsLineGraph',+ source: {+ kind: 'HogQLQuery',+ query: 'SELECT date, ... FROM postgres.prod.billing_usagereport',+ variables: BILLING_VARIABLES,+ },+ },+}++const USAGE_QUERY_RESPONSE = {+ error: '',+ hasMore: false,+ is_cached: true,+ query_status: null,+ columns: ['date', 'Events', 'Recordings'],+ types: [+ ['date', 'Date'],+ ['Events', 'Nullable(Float64)'],+ ['Recordings', 'Nullable(Float64)'],+ ],+ results: [+ ['2026-05-01', 1200, 30],+ ['2026-05-08', 1800, 45],+ ['2026-05-15', 1500, 38],+ ['2026-05-21', 2100, 52],+ ],+}++// Dispatches the shared query endpoint: account rows for the list, billing chart data for the embedded insight.+function mockAccountsAndBillingQuery(+ rows: AccountRow[],+ billingResponse: Record<string, unknown>+): (req: { body: unknown }) => [number, unknown] | undefined {+ return (req) => {+ const kind = (req.body as { query?: { kind?: string } })?.query?.kind+ if (kind === 'AccountsQuery') {+ return [200, buildAccountsQueryResponse(rows)]+ }+ if (kind === 'HogQLQuery') {+ return [200, billingResponse]+ }+ return undefined+ }+}++// Billing tab stories share the same account + notebooks mocks; they differ only in the insight and query responses.+function billingTabDecorators(+ insightsGet: Record<string, unknown>,+ queryPost: (req: { body: unknown }) => [number, unknown] | undefined+): ReturnType<typeof mswDecorator>[] {+ return [+ mswDecorator({+ get: {+ [ACCOUNT_RETRIEVE_ENDPOINT]: ACCOUNT_WITH_LINKS,+ [ACCOUNT_NOTEBOOKS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },+ [INSIGHTS_ENDPOINT]: insightsGet,+ },+ post: {+ [QUERY_ENDPOINT]: queryPost,+ },+ }),+ ]+}+// Expanding a row mounts UsefulLinks (loads the account async) and the notes table// (loads notebooks async). Both start as skeletons and resolve later, which changes// the expansion's width and height. Awaiting the settled content here keeps the@@ -104,6 +190,15 @@ async function expandFirstRow(canvasElement: HTMLElement, notesLoadedText: strinawait canvas.findByText(notesLoadedText)}+// Expands the first row and switches to a billing tab. Awaits the settled sidebar first to avoid layout races.+async function expandAndOpenTab(canvasElement: HTMLElement, tab: 'Usage' | 'Spend'): Promise<void> {+ const canvas = within(canvasElement)+ await userEvent.click(await canvas.findByTitle('Show more'))+ await canvas.findByText('Useful links')+ await canvas.findByText('Organization')+ await userEvent.click(await canvas.findByRole('tab', { name: tab }))+}+function mockAccountsQuery(rows: AccountRow[]): (req: { body: unknown }) => [number, unknown] | undefined {return (req) => {const kind = (req.body as { query?: { kind?: string } })?.query?.kind@@ -254,3 +349,28 @@ export const RowExpandedLinksDisabled: Story = {await expandFirstRow(canvasElement, 'No notes linked to this account yet.')},}++export const RowExpandedUsageNotFound: Story = {+ render: () => <App />,+ decorators: billingTabDecorators(EMPTY_INSIGHTS, mockAccountsQuery(SINGLE_ROW)),+ play: async ({ canvasElement }) => {+ await expandAndOpenTab(canvasElement, 'Usage')+ await within(canvasElement).findByText('No billing usage insight here')+ },+}++export const RowExpandedUsagePopulated: Story = {+ render: () => <App />,+ parameters: {+ testOptions: {+ waitForSelector: ['[data-attr="accounts-refresh"]', '.DataVisualization canvas'],+ },+ },+ decorators: billingTabDecorators(+ insightsResponse(USAGE_INSIGHT),+ mockAccountsAndBillingQuery(SINGLE_ROW, USAGE_QUERY_RESPONSE)+ ),+ play: async ({ canvasElement }) => {+ await expandAndOpenTab(canvasElement, 'Usage')+ },+}diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.tsnew file mode 100644index 000000000000..1fe0847bf058--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts@@ -0,0 +1,122 @@+import { actions, afterMount, isBreakpoint, kea, key, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { dayjs } from 'lib/dayjs'+import { dateStringToDayJs } from 'lib/utils'+import { insightsApi } from 'scenes/insights/utils/api'++import { DataVisualizationNode, HogQLVariable, NodeKind } from '~/queries/schema/schema-general'+import { InsightShortId, QueryBasedInsightModel } from '~/types'++import type { accountBillingLogicType } from './accountBillingLogicType'++export type AccountBillingKind = 'usage' | 'spend'++// Short IDs of the saved billing insights. Absent in environments without them — the tab then shows a not-found state.+export const BILLING_INSIGHT_SHORT_IDS: Record<AccountBillingKind, InsightShortId> = {+ usage: 'fiJDsKLp' as InsightShortId,+ spend: '9cZ54LsW' as InsightShortId,+}++// code_names of the SQL variables defined on the saved billing insights.+const ORG_VARIABLE = 'billing_org_id'+const START_VARIABLE = 'billing_start_date'+const END_VARIABLE = 'billing_end_date'++export interface BillingDateRange {+ date_from: string | null+ date_to: string | null+}++export interface AccountBillingLogicProps {+ accountId: string+ externalId: string+ kind: AccountBillingKind+}++export const accountBillingLogic = kea<accountBillingLogicType>([+ path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountBillingLogic', key]),+ props({} as AccountBillingLogicProps),+ key((props) => `${props.accountId}:${props.kind}`),+ actions({+ setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ }),+ reducers({+ dateRange: [+ { date_from: '-30d', date_to: null } as BillingDateRange,+ {+ setDateRange: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom, date_to: dateTo }),+ },+ ],+ }),+ loaders(({ props }) => ({+ savedInsight: [+ null as QueryBasedInsightModel | null,+ {+ loadSavedInsight: async (_ = null, breakpoint) => {+ try {+ const insight = await insightsApi.getByShortId(BILLING_INSIGHT_SHORT_IDS[props.kind])+ breakpoint()+ return insight+ } catch (error) {+ if (isBreakpoint(error as Error)) {+ throw error+ }+ posthog.captureException(error as Error, { scope: 'accountBillingLogic.loadSavedInsight' })+ return null+ }+ },+ },+ ],+ })),+ selectors({+ // The saved insight filters on the calendar `date` column, so the range must be resolved to absolute dates.+ resolvedDateRange: [+ (s) => [s.dateRange],+ (dateRange): BillingDateRange => {+ const from = dateStringToDayJs(dateRange.date_from)+ const to = dateRange.date_to ? dateStringToDayJs(dateRange.date_to) : dayjs()+ return {+ date_from: from ? from.format('YYYY-MM-DD') : null,+ date_to: to ? to.format('YYYY-MM-DD') : null,+ }+ },+ ],+ // Inject the account's org and the chosen date range into the saved insight's SQL variables, keyed by their+ // variableId as read from the fetched insight (so this works regardless of the variable UUIDs in each env).+ variableOverrides: [+ (s) => [s.savedInsight, s.resolvedDateRange, (_, p) => p.externalId],+ (savedInsight, resolvedDateRange, externalId): Record<string, HogQLVariable> | undefined => {+ const query = savedInsight?.query+ if (!query || query.kind !== NodeKind.DataVisualizationNode) {+ return undefined+ }+ const variables = (query as DataVisualizationNode).source.variables+ if (!variables) {+ return undefined+ }+ const valueByCodeName: Record<string, string | null> = {+ [ORG_VARIABLE]: externalId,+ [START_VARIABLE]: resolvedDateRange.date_from,+ [END_VARIABLE]: resolvedDateRange.date_to,+ }+ const overrides: Record<string, HogQLVariable> = {}+ for (const variable of Object.values(variables)) {+ if (variable.code_name in valueByCodeName) {+ overrides[variable.variableId] = {+ ...variable,+ value: valueByCodeName[variable.code_name],+ }+ }+ }+ return overrides+ },+ ],+ }),+ afterMount(({ actions, props }) => {+ if (props.externalId) {+ actions.loadSavedInsight()+ }+ }),+])