: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): preload account billing tabs (#85840)
Arthur Moreira de Deus7424ea21731a
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex dbe770cb6874..770a961f41b9 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -51,7 +51,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). || `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. || `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |-| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |+| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, preloads each insight result when the account expands, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. || `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. || `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / loaded-empty / load-failed; captures unexpected failures. || `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |@@ -114,7 +114,7 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountSupportTicketsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`, `AccountSummariesExpansion`, `AccountSupportTicketsExpansion`, `AccountEmailThreadsExpansion`, `AccountMeetingsExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.-The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. The **Usage/Spend** tabs are different: `accountBillingLogic` only holds the saved-insight _metadata_ — the actual insight **results** live in the `dataNodeLogic`/`dataVisualizationLogic` mounted inside the tab body, which the root mount does **not** keep alive. So the tab body attaches those data logics to the (root-mounted) `accountBillingLogic` via `useAttachedLogic` — `AccountBillingChart` does this for the chart it renders, and the fallback `<Query>` path does it via `attachTo={accountBillingLogic-instance}` — so they outlive the tab body unmounting on tab switch and only detach when the row collapses. Without that attachment, usage/spend refetch on every return to the tab even with the metadata logic mounted. (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.)+The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. 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.)The Usage and Spend tabs render existing saved billing insights — **point users to them, don't rebuild billing as new insights.**diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsxindex 5a48d0575f4d..27f2a43ac6e6 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx@@ -38,7 +38,7 @@ import {} from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'-import { AccountBillingLogicProps, accountBillingLogic } from './accountBillingLogic'+import { AccountBillingLogicProps, accountBillingLogic, getBillingDataVisualizationKey } from './accountBillingLogic'import { AccountBillingSeriesToggle } from './AccountBillingSeriesToggle'const RENDERABLE_DISPLAY_TYPES = new Set<ChartDisplayType>([@@ -223,7 +223,7 @@ export function AccountBillingChart({const { toggleHiddenSeriesKey, setAllSeriesHidden } = useActions(billingLogic)const vizLogic = dataVisualizationLogic({- key: queryKey,+ key: getBillingDataVisualizationKey(queryKey),query,dataNodeCollectionId: queryKey,variablesOverride,diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsxindex d218507234fa..b7f0515cc2ec 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx@@ -8,6 +8,7 @@ import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { BurningMoneyHog } from 'lib/components/hedgehogs'import { Query } from '~/queries/Query/Query'+import { InsightShortId } from '~/types'import { AccountBillingChart, canRenderBillingChart } from './AccountBillingChart'import { AccountBillingKind, accountBillingLogic } from './accountBillingLogic'@@ -92,6 +93,12 @@ export function AccountBillingExpansion({// Attach the insight's data logic to accountBillingLogic (mounted at the expanded-row// root) so the loaded results survive tab switches instead of refetching on return.attachTo={logic}+ context={{+ insightProps: {+ dashboardItemId: queryKey as InsightShortId,+ dataNodeCollectionId: queryKey,+ },+ }}/></div>)}diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.tsindex 74bcacabfead..d4489797979f 100644--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts@@ -1,13 +1,20 @@import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'+import api from 'lib/api'import { insightsApi } from 'scenes/insights/utils/api'-import { NodeKind } from '~/queries/schema/schema-general'+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 { AccountBillingKind, accountBillingLogic, BILLING_INSIGHT_SHORT_IDS } from './accountBillingLogic'+import {+ AccountBillingKind,+ accountBillingLogic,+ BILLING_INSIGHT_SHORT_IDS,+ getBillingDataVisualizationKey,+} from './accountBillingLogic'const ORG_VARIABLE_ID = 'var-org'const START_VARIABLE_ID = 'var-start'@@ -43,6 +50,7 @@ describe('accountBillingLogic', () => {jest.spyOn(insightsApi, 'getByShortId').mockImplementation((shortId) =>Promise.resolve(buildBillingInsight(shortId)))+ jest.spyOn(api, 'query').mockResolvedValue({ columns: [], results: [] })})afterEach(() => {@@ -71,6 +79,13 @@ describe('accountBillingLogic', () => {}})+ it('preloads every saved insight result before its tab renders', async () => {+ mountForKind()++ await expectLogic(logic).toFinishAllListeners()+ expect(api.query).toHaveBeenCalledTimes(BILLING_INSIGHT_SHORT_IDS[kind].length)+ })+it('injects the external id into each saved insight variables', async () => {mountForKind()@@ -106,6 +121,27 @@ describe('accountBillingLogic', () => {expect(nextQueryKey).toContain('2024-01-31')})+ it('replaces stale preloads when the date range changes', async () => {+ mountForKind()+ await expectLogic(logic).toFinishAllListeners()++ const initialPreloads = (logic.values.savedInsights ?? []).map((insight) => {+ const queryKey = logic.values.queryKeyFor(insight.short_id)+ return dataVisualizationLogic({+ key: getBillingDataVisualizationKey(queryKey),+ query: insight.query as DataVisualizationNode,+ dataNodeCollectionId: queryKey,+ variablesOverride: logic.values.variableOverridesByShortId[insight.short_id] ?? null,+ })+ })++ logic.actions.setDateRange('2024-01-01', '2024-01-31')+ await expectLogic(logic).toFinishAllListeners()++ expect(api.query).toHaveBeenCalledTimes(BILLING_INSIGHT_SHORT_IDS[kind].length * 2)+ expect(initialPreloads.every((preload) => !preload.isMounted())).toBe(true)+ })+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.tsindex 677491a38ceb..2fc70694e148 100644--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts@@ -18,6 +18,7 @@ import { dayjs } from 'lib/dayjs'import { dateStringToDayJs } from 'lib/utils/dateFilters'import { insightsApi } from 'scenes/insights/utils/api'+import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'import {DataVisualizationNode,HogQLVariable,@@ -78,6 +79,10 @@ export interface AccountBillingLogicProps {kind: AccountBillingKind}+export function getBillingDataVisualizationKey(queryKey: string): string {+ return `InsightViz.${queryKey}`+}+// 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).function buildVariableOverrides(@@ -230,22 +235,51 @@ export const accountBillingLogic = kea<accountBillingLogicType>([},],})),- listeners(({ props, values }) => ({- toggleHiddenSeriesKey: ({ shortId, seriesKey, seriesCount }) => {- posthog.capture(AccountsEvents.UsageSeriesToggled, {- kind: props.kind,- is_hidden: (values.ephemeralHiddenSeriesKeysByShortId[shortId] ?? []).includes(seriesKey),- series_count: seriesCount,- })- },- setAllSeriesHidden: ({ seriesKeys, hidden }) => {- posthog.capture(AccountsEvents.UsageSeriesBulkToggled, {- kind: props.kind,- is_hidden: hidden,- series_count: seriesKeys.length,- })- },- })),+ listeners(({ props, values, cache }) => {+ const preloadSavedInsights = (savedInsights: QueryBasedInsightModel[]): void => {+ for (const insight of savedInsights) {+ if (!insight.query || insight.query.kind !== NodeKind.DataVisualizationNode) {+ continue+ }+ const queryKey = values.queryKeyFor(insight.short_id)+ const dataVisualizationKey = getBillingDataVisualizationKey(queryKey)+ cache.disposables.add(+ () =>+ dataVisualizationLogic({+ key: dataVisualizationKey,+ query: insight.query as DataVisualizationNode,+ dataNodeCollectionId: queryKey,+ variablesOverride: values.variableOverridesByShortId[insight.short_id] ?? null,+ }).mount(),+ `preload-${insight.short_id}`,+ { pauseOnPageHidden: false }+ )+ }+ }++ return {+ loadSavedInsightsSuccess: ({ savedInsights }) => {+ preloadSavedInsights(savedInsights)+ },+ setDateRange: () => {+ preloadSavedInsights(values.savedInsights ?? [])+ },+ toggleHiddenSeriesKey: ({ shortId, seriesKey, seriesCount }) => {+ posthog.capture(AccountsEvents.UsageSeriesToggled, {+ kind: props.kind,+ is_hidden: (values.ephemeralHiddenSeriesKeysByShortId[shortId] ?? []).includes(seriesKey),+ series_count: seriesCount,+ })+ },+ setAllSeriesHidden: ({ seriesKeys, hidden }) => {+ posthog.capture(AccountsEvents.UsageSeriesBulkToggled, {+ kind: props.kind,+ is_hidden: hidden,+ series_count: seriesKeys.length,+ })+ },+ }+ }),loaders(({ props }) => ({savedInsights: [null as QueryBasedInsightModel[] | null,