: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): show/hide lines in account billing charts (#71615)
jake sciottof907f7c8ee8e
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a032a775317a..9ecee1e67a1e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2974,6 +2974,9 @@ importers:'@posthog/icons':specifier: 'catalog:'+ '@posthog/quill-charts':+ specifier: workspace:*+ version: link:../../packages/quill/packages/charts'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 46cf86552b3c..60bbdacc7f8e 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -150,6 +150,7 @@ class FallbackTags(TypedDict):# fallback. The `None` rows double as breadcrumbs so the absence of a common scene is loud.SCENE_TO_TAGS: dict[str, FallbackTags | None] = {"Cohort": {"product": Product.COHORTS, "feature": Feature.COHORT},+ "CustomerAnalytics": {"product": Product.CUSTOMER_ANALYTICS, "feature": Feature.QUERY},"EndpointScene": {"product": Product.ENDPOINTS, "feature": Feature.QUERY},"EndpointsScene": {"product": Product.ENDPOINTS, "feature": Feature.QUERY},"EngineeringAnalytics": {"product": Product.ENGINEERING_ANALYTICS, "feature": Feature.QUERY},diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex ce6d6008bed7..c6ae5da5f4d8 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -46,7 +46,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_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`). || `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. |+| `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. || `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. || `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |@@ -77,10 +77,12 @@ 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'`, and `accountOpportunitiesLogic({ 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`) 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` that the embedded `<Query>` mounts inside the tab body, which the root mount does **not** keep alive. So `AccountBillingExpansion` passes `attachTo={accountBillingLogic-instance}` to each `<Query>`: `useAttachedLogic` mounts the query's data logics and attaches them to the (root-mounted) `accountBillingLogic`, so they outlive the `<Query>` unmounting on tab switch and only detach when the row collapses. Without `attachTo`, 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 `attachTo`.)+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 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 the shared pipeline read-only — `dataVisualizationLogic` for fetch + SQL-results→series parsing, and the exported `useSqlChartModel`/`build*ChartConfig` builders so the chart matches what the insight renders elsewhere — and injects the hidden series 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). 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.+The Opportunities tab lists the account's Salesforce opportunities from the data-warehouse `salesforce.opportunity` table (joined by the account's `sfdc_id`). The query runs in `accountOpportunitiesLogic` rather than via a bare `<Query>` so the tab owns every state: a missing `sfdc_id` shows a "not linked to Salesforce" empty state, and because `salesforce.opportunity` is **access-gated and production-only**, a failed query degrades to a pretty hog empty state instead of a red error box. The expected denied/absent-table `QueryError` (`You don't have access to table …` / `Unknown table …`) is **not** captured to PostHog — it's the normal empty state, not a bug — while genuine, unexpected query failures are still reported (`isExpectedMissingTableError` in `accountOpportunitiesLogic`). Each opportunity name links to its Salesforce record (`SALESFORCE_ORIGIN/<id>` in `constants.ts`, the same origin the Useful links sidebar uses).Clicking a note in the Notes tab opens it in the global notebook **side panel** (`notebookPanelLogic.selectNotebook`), keeping the Accounts list mounted — not the full `NotebookScene`. The note `<Link>` still points at `urls.notebook(shortId)` so cmd/ctrl-click opens the full page in a new tab; a plain click `preventDefault()`s the router push and opens the panel instead.@@ -192,6 +194,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`) |+| `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 related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ || `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ || `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsxnew file mode 100644index 000000000000..8f1362789ff6--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingChart.tsx@@ -0,0 +1,228 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'++import { LemonSkeleton } from '@posthog/lemon-ui'+import {+ type ChartTheme,+ type LegendItem,+ TimeSeriesBarChart,+ TimeSeriesComboChart,+ TimeSeriesLineChart,+ legendItemsFromSeries,+} from '@posthog/quill-charts'++import { useChartTheme } from 'lib/charts/hooks'+import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'+import { InsightErrorState } from 'scenes/insights/EmptyStates'++import { LineGraphProps } from '~/queries/nodes/DataVisualization/Components/Charts/LineGraph'+import {+ SqlLineSeriesMeta,+ buildBarChartConfig,+ buildComboChartConfig,+ buildLineChartConfig,+ buildSeries,+ canRenderSqlBarGraph,+ canRenderSqlComboGraph,+ capYSeriesData,+} from '~/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter'+import { useSqlChartModel } from '~/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel'+import { dataVisualizationLogic } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'+import { DataVisualizationNode, HogQLVariable, NodeKind } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'++import { AccountBillingLogicProps, accountBillingLogic } from './accountBillingLogic'+import { AccountBillingSeriesToggle } from './AccountBillingSeriesToggle'++const RENDERABLE_DISPLAY_TYPES = new Set<ChartDisplayType>([+ ChartDisplayType.ActionsLineGraph,+ ChartDisplayType.ActionsAreaGraph,+ ChartDisplayType.ActionsBar,+ ChartDisplayType.ActionsStackedBar,+])++/** Series breakdowns are excluded because they need the full DataVisualization pipeline+ * (seriesBreakdownLogic); those queries fall back to the embedded <Query>. */+export function canRenderBillingChart(query: Record<string, any> | null): query is DataVisualizationNode {+ return (+ query?.kind === NodeKind.DataVisualizationNode &&+ !!query.display &&+ RENDERABLE_DISPLAY_TYPES.has(query.display) &&+ !query.chartSettings?.seriesBreakdownColumn+ )+}++const handleChartError = (error: Error): void => {+ posthog.captureException(error, { scope: 'AccountBillingChart' })+}++function chipItemsFromChartOwnSeries(+ yData: LineGraphProps['yData'],+ visualizationType: ChartDisplayType,+ theme: ChartTheme+): LegendItem[] {+ const ySeriesData = capYSeriesData(yData)+ return ySeriesData?.length ? legendItemsFromSeries(buildSeries(ySeriesData, visualizationType), theme) : []+}++function BillingChartByKind({+ chartProps,+ hiddenKeys,+}: {+ chartProps: LineGraphProps+ hiddenKeys: string[]+}): JSX.Element | null {+ if (canRenderSqlComboGraph(chartProps)) {+ return <BillingComboChart chartProps={chartProps} hiddenKeys={hiddenKeys} />+ }+ if (canRenderSqlBarGraph(chartProps)) {+ return <BillingBarChart chartProps={chartProps} hiddenKeys={hiddenKeys} />+ }+ return <BillingLineChart chartProps={chartProps} hiddenKeys={hiddenKeys} />+}++// One subcomponent per chart kind because useSqlChartModel's config type follows the builder it's given.+function BillingLineChart({+ chartProps,+ hiddenKeys,+}: {+ chartProps: LineGraphProps+ hiddenKeys: string[]+}): JSX.Element | null {+ const model = useSqlChartModel(chartProps, buildLineChartConfig)+ if (!model) {+ return null+ }+ return (+ <TimeSeriesLineChart<SqlLineSeriesMeta>+ series={model.series}+ labels={model.labels}+ theme={model.theme}+ config={{ ...model.config, legend: { ...model.config.legend, show: false, hiddenKeys } }}+ onError={handleChartError}+ />+ )+}++function BillingBarChart({+ chartProps,+ hiddenKeys,+}: {+ chartProps: LineGraphProps+ hiddenKeys: string[]+}): JSX.Element | null {+ const model = useSqlChartModel(chartProps, buildBarChartConfig)+ if (!model) {+ return null+ }+ return (+ <TimeSeriesBarChart<SqlLineSeriesMeta>+ series={model.series}+ labels={model.labels}+ theme={model.theme}+ config={{ ...model.config, legend: { ...model.config.legend, show: false, hiddenKeys } }}+ onError={handleChartError}+ />+ )+}++function BillingComboChart({+ chartProps,+ hiddenKeys,+}: {+ chartProps: LineGraphProps+ hiddenKeys: string[]+}): JSX.Element | null {+ const model = useSqlChartModel(chartProps, buildComboChartConfig)+ if (!model) {+ return null+ }+ return (+ <TimeSeriesComboChart<SqlLineSeriesMeta>+ series={model.series}+ labels={model.labels}+ theme={model.theme}+ config={{ ...model.config, legend: { ...model.config.legend, show: false, hiddenKeys } }}+ onError={handleChartError}+ />+ )+}++/**+ * Renders a saved billing insight's SQL chart directly via @posthog/quill-charts instead of the+ * embedded DataVisualization, so Customer analytics owns the per-series show/hide chips without+ * touching shared data-viz code. The shared pipeline is reused read-only — `dataVisualizationLogic`+ * for fetch + SQL-results→series parsing, the exported `useSqlChartModel`/config builders for the+ * render — so the chart matches what the insight renders elsewhere. Hidden series go into quill's+ * controlled `legend.hiddenKeys`: excluded from drawing and scales, the rest rescale into the+ * freed space.+ */+export function AccountBillingChart({+ logicProps,+ shortId,+ query,+ queryKey,+ variablesOverride,+}: {+ logicProps: AccountBillingLogicProps+ shortId: string+ query: DataVisualizationNode+ queryKey: string+ variablesOverride: Record<string, HogQLVariable> | null+}): JSX.Element {+ const billingLogic = accountBillingLogic(logicProps)+ const { ephemeralHiddenSeriesKeysByShortId } = useValues(billingLogic)+ const { toggleHiddenSeriesKey } = useActions(billingLogic)++ const vizLogic = dataVisualizationLogic({+ key: queryKey,+ query,+ dataNodeCollectionId: queryKey,+ variablesOverride,+ })+ // Keeps the query's data logics alive across tab switches — they detach only on row collapse.+ useAttachedLogic(vizLogic, billingLogic)+ const { response, responseLoading, responseError, xData, yData, chartSettings, effectiveVisualizationType } =+ useValues(vizLogic)+ const theme = useChartTheme()++ const hiddenKeys = ephemeralHiddenSeriesKeysByShortId[shortId] ?? []+ const chartProps: LineGraphProps = {+ xData,+ yData,+ visualizationType: effectiveVisualizationType,+ chartSettings,+ goalLines: chartSettings.goalLines,+ }+ const chipItems = chipItemsFromChartOwnSeries(yData, effectiveVisualizationType, theme)++ let content: JSX.Element | null+ if (responseError) {+ content = <InsightErrorState query={query} title={responseError} excludeDetail />+ } else if (!response || responseLoading) {+ content = <LemonSkeleton className="h-full w-full" />+ } else if (!xData || chipItems.length === 0) {+ content = (+ <div className="flex flex-1 items-center justify-center text-secondary">+ No data for this date range. Try widening it.+ </div>+ )+ } else {+ content = <BillingChartByKind chartProps={chartProps} hiddenKeys={hiddenKeys} />+ }++ return (+ <div className="flex flex-col gap-1">+ {/* Quill charts fill their container, so the parent must have real dimensions. */}+ <div className="h-80 flex flex-col rounded bg-surface-primary overflow-hidden p-3">{content}</div>+ {chipItems.length > 1 && (+ <AccountBillingSeriesToggle+ kind={logicProps.kind}+ series={chipItems}+ hiddenKeys={hiddenKeys}+ onToggle={(seriesKey) => toggleHiddenSeriesKey(shortId, seriesKey, chipItems.length)}+ />+ )}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsxindex cb63bc45d3e6..def4f96809e4 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx@@ -9,6 +9,7 @@ import { BurningMoneyHog } from 'lib/components/hedgehogs'import { Query } from '~/queries/Query/Query'+import { AccountBillingChart, canRenderBillingChart } from './AccountBillingChart'import { AccountBillingKind, accountBillingLogic } from './accountBillingLogic'const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)@@ -65,23 +66,35 @@ export function AccountBillingExpansion({/>{savedInsights.map((insight) => {const queryKey = queryKeyFor(insight.short_id)+ const variablesOverride = variableOverridesByShortId[insight.short_id] ?? nullreturn (<div key={insight.short_id} className="flex flex-col gap-1">{showTitles && insight.name ? <h4 className="mb-0 text-sm">{insight.name}</h4> : null}- {/* 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+ {canRenderBillingChart(insight.query) ? (+ <AccountBillingChartkey={queryKey}- uniqueKey={queryKey}+ logicProps={{ accountId, externalId, kind }}+ shortId={insight.short_id}query={insight.query}- variablesOverride={variableOverridesByShortId[insight.short_id] ?? null}- readOnly- embedded- // 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}+ queryKey={queryKey}+ variablesOverride={variablesOverride}/>- </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+ key={queryKey}+ uniqueKey={queryKey}+ query={insight.query}+ variablesOverride={variablesOverride}+ readOnly+ embedded+ // 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}+ />+ </div>+ )}</div>)})}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingSeriesToggle.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingSeriesToggle.tsxnew file mode 100644index 000000000000..261c42b54a3e--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingSeriesToggle.tsx@@ -0,0 +1,42 @@+import { LemonSnack } from '@posthog/lemon-ui'+import type { LegendItem } from '@posthog/quill-charts'++import { LemonColorGlyph } from 'lib/lemon-ui/LemonColor/LemonColorGlyph'+import { cn } from 'lib/utils/css-classes'++import { AccountBillingKind } from './accountBillingLogic'++export function AccountBillingSeriesToggle({+ series,+ hiddenKeys,+ kind,+ onToggle,+}: {+ series: LegendItem[]+ hiddenKeys: string[]+ kind: AccountBillingKind+ onToggle: (seriesKey: string) => void+}): JSX.Element {+ const hidden = new Set(hiddenKeys)++ return (+ <div className="flex flex-wrap gap-1" data-attr={`account-billing-series-toggle-${kind}`}>+ {series.map(({ key, label, color }) => {+ const isHidden = hidden.has(key)+ return (+ <LemonSnack+ key={key}+ onClick={() => onToggle(key)}+ title={isHidden ? `Show ${label}` : `Hide ${label}`}+ className={cn('cursor-pointer', isHidden && 'opacity-50')}+ >+ <span className="flex items-center gap-1">+ <LemonColorGlyph color={color} size="small" />+ <span className={cn(isHidden && 'line-through')}>{label}</span>+ </span>+ </LemonSnack>+ )+ })}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.tsindex bf98c2ddc4f7..b5f1f631be38 100644--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts@@ -1,4 +1,5 @@import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import { insightsApi } from 'scenes/insights/utils/api'@@ -54,13 +55,20 @@ describe('accountBillingLogic', () => {logic.mount()}- it('loads every saved insight configured for the kind', async () => {+ it('loads every saved insight configured for the kind, with product-attribution query tags', async () => {mountForKind()await expectLogic(logic).toFinishAllListeners()expect(logic.values.savedInsights?.map((insight) => insight.short_id)).toEqual(BILLING_INSIGHT_SHORT_IDS[kind])+ // Without these tags the ad-hoc SQL is untagged and local dev rejects it (UntaggedQueryError).+ for (const insight of logic.values.savedInsights ?? []) {+ expect((insight.query as Record<string, any>).source.tags).toEqual({+ productKey: 'customer_analytics',+ scene: 'CustomerAnalytics',+ })+ }})it('injects the external id into each saved insight variables', async () => {@@ -98,6 +106,37 @@ describe('accountBillingLogic', () => {expect(nextQueryKey).toContain('2024-01-31')})+ 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()++ logic.actions.toggleHiddenSeriesKey('insight-a', 'Events-0', 3)+ logic.actions.toggleHiddenSeriesKey('insight-b', 'Recordings-1', 2)+ expect(logic.values.ephemeralHiddenSeriesKeysByShortId).toEqual({+ 'insight-a': ['Events-0'],+ 'insight-b': ['Recordings-1'],+ })+ expect(captureSpy).toHaveBeenLastCalledWith('customer analytics account usage series toggled', {+ kind,+ is_hidden: true,+ series_count: 2,+ })++ logic.actions.toggleHiddenSeriesKey('insight-a', 'Events-0', 3)+ expect(logic.values.ephemeralHiddenSeriesKeysByShortId).toEqual({+ 'insight-a': [],+ 'insight-b': ['Recordings-1'],+ })+ expect(captureSpy).toHaveBeenLastCalledWith('customer analytics account usage series toggled', {+ kind,+ is_hidden: false,+ series_count: 3,+ })++ logic.actions.setDateRange('2024-01-01', '2024-01-31')+ expect(logic.values.ephemeralHiddenSeriesKeysByShortId).toEqual({})+ })+// Environments without the saved billing insight (or a failing fetch) must degrade to an// empty list, which is what drives the tab's not-found state instead of a crash or broken chart.it.each([diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.tsindex 0f76a5a01125..7b2e286dde96 100644--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts@@ -1,4 +1,16 @@-import { MakeLogicType, actions, afterMount, isBreakpoint, kea, key, path, props, reducers, selectors } from 'kea'+import {+ MakeLogicType,+ actions,+ afterMount,+ isBreakpoint,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'@@ -6,10 +18,17 @@ import { dayjs } from 'lib/dayjs'import { dateStringToDayJs } from 'lib/utils/dateFilters'import { insightsApi } from 'scenes/insights/utils/api'-import { DataVisualizationNode, HogQLVariable, NodeKind } from '~/queries/schema/schema-general'+import {+ DataVisualizationNode,+ HogQLVariable,+ NodeKind,+ ProductKey,+ QueryLogTags,+} from '~/queries/schema/schema-general'import { InsightShortId, QueryBasedInsightModel } from '~/types'import type { Node } from '../../../../../frontend/src/queries/schema/schema-general'+import { AccountsEvents } from './constants'export type AccountBillingKind = 'usage' | 'spend'@@ -24,6 +43,24 @@ const ORG_VARIABLE = 'billing_org_id'const START_VARIABLE = 'billing_start_date'const END_VARIABLE = 'billing_end_date'+// Attributes the saved insights' ad-hoc SQL to this product — an untagged ClickHouse query is+// rejected in local dev (UntaggedQueryError), and the insight's SQL may reference no table the+// backend could attribute it by.+const BILLING_QUERY_TAGS: QueryLogTags = { productKey: ProductKey.CUSTOMER_ANALYTICS, scene: 'CustomerAnalytics' }++function withBillingQueryTags(insight: QueryBasedInsightModel): QueryBasedInsightModel {+ const query = insight.query+ if (!query || query.kind !== NodeKind.DataVisualizationNode) {+ return insight+ }+ const dataViz = query as DataVisualizationNode+ const taggedQuery: DataVisualizationNode = {+ ...dataViz,+ source: { ...dataViz.source, tags: { ...BILLING_QUERY_TAGS, ...dataViz.source.tags } },+ }+ return { ...insight, query: taggedQuery as QueryBasedInsightModel['query'] }+}+export interface BillingDateRange {date_from: string | nulldate_to: string | null@@ -76,6 +113,7 @@ function buildVariableOverrides(// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountBillingLogicValues {dateRange: BillingDateRange+ ephemeralHiddenSeriesKeysByShortId: Record<string, string[]>queryKeyFor: (shortId: string) => stringresolvedDateRange: BillingDateRangesavedInsights: QueryBasedInsightModel[] | null@@ -107,6 +145,15 @@ export interface accountBillingLogicActions {dateFrom: string | nulldateTo: string | null}+ toggleHiddenSeriesKey: (+ shortId: string,+ seriesKey: string,+ seriesCount: number+ ) => {+ seriesCount: number+ seriesKey: string+ shortId: string+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -136,6 +183,11 @@ export const accountBillingLogic = kea<accountBillingLogicType>([key((props) => `${props.accountId}:${props.kind}`),actions({setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),+ toggleHiddenSeriesKey: (shortId: string, seriesKey: string, seriesCount: number) => ({+ shortId,+ seriesKey,+ seriesCount,+ }),}),reducers(({ props }) => ({dateRange: [@@ -144,6 +196,30 @@ export const accountBillingLogic = kea<accountBillingLogicType>([setDateRange: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom, date_to: dateTo }),},],+ ephemeralHiddenSeriesKeysByShortId: [+ {} as Record<string, string[]>,+ {+ toggleHiddenSeriesKey: (state, { shortId, seriesKey }) => {+ const current = state[shortId] ?? []+ return {+ ...state,+ [shortId]: current.includes(seriesKey)+ ? current.filter((key) => key !== seriesKey)+ : [...current, seriesKey],+ }+ },+ setDateRange: () => ({}),+ },+ ],+ })),+ listeners(({ props, values }) => ({+ toggleHiddenSeriesKey: ({ shortId, seriesKey, seriesCount }) => {+ posthog.capture(AccountsEvents.UsageSeriesToggled, {+ kind: props.kind,+ is_hidden: (values.ephemeralHiddenSeriesKeysByShortId[shortId] ?? []).includes(seriesKey),+ series_count: seriesCount,+ })+ },})),loaders(({ props }) => ({savedInsights: [@@ -167,7 +243,9 @@ export const accountBillingLogic = kea<accountBillingLogicType>([}))breakpoint()- return insights.filter((insight): insight is QueryBasedInsightModel => insight !== null)+ return insights+ .filter((insight): insight is QueryBasedInsightModel => insight !== null)+ .map(withBillingQueryTags)},},],diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex 3a0788cd7ac0..a52ce8f58c1a 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -47,6 +47,7 @@ export const AccountsEvents = {NotesSearched: 'customer analytics accounts notes searched',NotesSorted: 'customer analytics accounts notes sorted',TabViewed: 'customer analytics account tab viewed',+ UsageSeriesToggled: 'customer analytics account usage series toggled',RelatedUserClicked: 'customer analytics account related user clicked',OpportunityClicked: 'customer analytics account opportunity clicked',NotesTabViewed: 'customer analytics notes tab viewed',diff --git a/products/customer_analytics/package.json b/products/customer_analytics/package.jsonindex 220ea4fb0953..911904acb03d 100644--- a/products/customer_analytics/package.json+++ b/products/customer_analytics/package.json@@ -5,6 +5,7 @@"backend:contract-check": "echo 'Contract files unchanged'"},"dependencies": {+ "@posthog/quill-charts": "workspace:*","kea": "catalog:","kea-forms": "catalog:","kea-loaders": "catalog:",