: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 spend tab to accounts (#62761)
Arthur Moreira de Deus02073ff7fa96
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex aa418587d61e..b80b58b8c5f9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4363,9 +4363,9 @@ snapshots:scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:hash: v1.k794b7964.dbed81a9f646d861c5fea01fbb66409ca2134d052126c83910f0d48cc7c229b9.NTmSJa7n10fuCNA-jmRnxjcAV6Na8sJSdTOwg0LZb7Mscenes-app-customer-analytics-accounts--row-expanded-usage-populated--dark:- hash: v1.k794b7964.51df31b2f26139195bd36ff3a49dc9ef508ece5a82b27531c67a079b8ba0c3d5.G6zXVyDobNnlIPNswkE8aailxmojSt2QNJ5ov3tGwKs+ hash: v1.k794b7964.d04d40247868d79a631943192b59d6770129069130c7c01c218174297ea8e211.RdxB2mQsJYtXUNAhwCxybVGkPS9s-Y4rIV5-_PiJsbkscenes-app-customer-analytics-accounts--row-expanded-usage-populated--light:- hash: v1.k794b7964.9f2f530882c939501fe180e1cf3ff3bf2af41ec6a37648b0db528aaa3d1532b9.kQ4UI7ylaSo9OoZGNrq3eIOTcrmezd00e3LSUCGpZ30+ hash: v1.k794b7964.6ba35c84f16d06a3a8e664519ac1d4cbe045069e459be8cd8752cdcb9e1f51fc.-7O2_Vcw9A-mDb_FWHgDylXVMLolYP3xzcf0X_oNUQIscenes-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.tsxindex 75302bfe92bf..862890bc7681 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx@@ -9,11 +9,6 @@ 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 : DetectiveHogreturn (@@ -37,44 +32,49 @@ export function AccountBillingExpansion({kind: AccountBillingKind}): JSX.Element {const logic = accountBillingLogic({ accountId, externalId, kind })- const { savedInsight, savedInsightLoading, dateRange, variableOverrides } = useValues(logic)+ const { savedInsights, savedInsightsLoading, dateRange, variableOverridesByShortId, queryKeyFor } = useValues(logic)const { setDateRange } = useActions(logic)if (!externalId) {return <div className="p-4 text-secondary">This account has no linked organization.</div>}- if (savedInsightLoading) {+ if (savedInsightsLoading) {return <LemonSkeleton className="h-64 w-full" />}- const query = savedInsight?.query- if (!query) {+ if (!savedInsights || savedInsights.length === 0) {return <BillingInsightNotFound kind={kind} />}- const note = KIND_NOTE[kind]+ const showTitles = savedInsights.length > 1return (- <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 className="flex flex-col gap-3">+ <DateFilter+ dateFrom={dateRange.date_from}+ dateTo={dateRange.date_to}+ onChange={(from, to) => setDateRange(from, to)}+ />+ {savedInsights.map((insight) => {+ const queryKey = queryKeyFor(insight.short_id)+ return (+ <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+ key={queryKey}+ uniqueKey={queryKey}+ query={insight.query}+ variablesOverride={variableOverridesByShortId[insight.short_id] ?? null}+ readOnly+ embedded+ />+ </div>+ </div>+ )+ })}</div>)}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex 957006f5f843..d2c21985556e 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -203,6 +203,17 @@ export function AccountNotebooksExpansion({/>),},+ {+ key: 'spend',+ label: 'Spend',+ content: (+ <AccountBillingExpansion+ accountId={accountId}+ externalId={externalId}+ kind="spend"+ />+ ),+ },]}/></div>diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.tsnew file mode 100644index 000000000000..5f4a960b63e5--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts@@ -0,0 +1,101 @@+import { expectLogic } from 'kea-test-utils'++import { insightsApi } from 'scenes/insights/utils/api'++import { 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'++const ORG_VARIABLE_ID = 'var-org'+const START_VARIABLE_ID = 'var-start'+const END_VARIABLE_ID = 'var-end'++const buildBillingInsight = (shortId: string): QueryBasedInsightModel =>+ ({+ short_id: shortId,+ query: {+ kind: NodeKind.DataVisualizationNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: 'SELECT 1',+ variables: {+ [ORG_VARIABLE_ID]: { variableId: ORG_VARIABLE_ID, code_name: 'billing_org_id', value: null },+ [START_VARIABLE_ID]: {+ variableId: START_VARIABLE_ID,+ code_name: 'billing_start_date',+ value: null,+ },+ [END_VARIABLE_ID]: { variableId: END_VARIABLE_ID, code_name: 'billing_end_date', value: null },+ },+ },+ },+ }) as unknown as QueryBasedInsightModel++describe('accountBillingLogic', () => {+ let logic: ReturnType<typeof accountBillingLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.restoreAllMocks()+ jest.spyOn(insightsApi, 'getByShortId').mockImplementation((shortId) =>+ Promise.resolve(buildBillingInsight(shortId))+ )+ })++ afterEach(() => {+ logic?.unmount()+ })++ describe.each<AccountBillingKind>(['usage', 'spend'])('kind: %s', (kind) => {+ const mountForKind = (): void => {+ logic = accountBillingLogic({ accountId: 'acc-1', externalId: 'org-uuid', kind })+ logic.mount()+ }++ it('loads every saved insight configured for the kind', async () => {+ mountForKind()++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.savedInsights?.map((insight) => insight.short_id)).toEqual(+ BILLING_INSIGHT_SHORT_IDS[kind]+ )+ })++ it('injects the external id into each saved insight variables', async () => {+ mountForKind()++ await expectLogic(logic).toFinishAllListeners()+ for (const shortId of BILLING_INSIGHT_SHORT_IDS[kind]) {+ expect(logic.values.variableOverridesByShortId[shortId]?.[ORG_VARIABLE_ID]?.value).toBe('org-uuid')+ }+ })++ it('updates the date variable overrides when the date range changes', async () => {+ mountForKind()+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setDateRange('2024-01-01', '2024-01-31')++ const [firstShortId] = BILLING_INSIGHT_SHORT_IDS[kind]+ expect(logic.values.variableOverridesByShortId[firstShortId]?.[START_VARIABLE_ID]?.value).toBe('2024-01-01')+ expect(logic.values.variableOverridesByShortId[firstShortId]?.[END_VARIABLE_ID]?.value).toBe('2024-01-31')+ })++ it('changes the query key when the date range changes so the insight refetches', async () => {+ mountForKind()+ await expectLogic(logic).toFinishAllListeners()++ const [firstShortId] = BILLING_INSIGHT_SHORT_IDS[kind]+ const initialQueryKey = logic.values.queryKeyFor(firstShortId)++ logic.actions.setDateRange('2024-01-01', '2024-01-31')++ const nextQueryKey = logic.values.queryKeyFor(firstShortId)+ expect(nextQueryKey).not.toEqual(initialQueryKey)+ expect(nextQueryKey).toContain('2024-01-01')+ expect(nextQueryKey).toContain('2024-01-31')+ })+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.tsindex 1fe0847bf058..d21654d1b772 100644--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts@@ -13,10 +13,10 @@ 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,+// Short IDs of the saved billing insights per tab. 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: ['o4I9sdFE' as InsightShortId, 'Tjo4bsux' as InsightShortId],}// code_names of the SQL variables defined on the saved billing insights.@@ -29,12 +29,50 @@ export interface BillingDateRange {date_to: string | null}+// Usage insights are daily, spend insights are monthly — so they want different default windows.+const DEFAULT_DATE_RANGE: Record<AccountBillingKind, BillingDateRange> = {+ usage: { date_from: '-30d', date_to: null },+ spend: { date_from: '-1y', date_to: null },+}+export interface AccountBillingLogicProps {accountId: stringexternalId: stringkind: AccountBillingKind}+// 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(+ insight: QueryBasedInsightModel,+ resolvedDateRange: BillingDateRange,+ externalId: string+): Record<string, HogQLVariable> | undefined {+ const query = insight.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+}+export const accountBillingLogic = kea<accountBillingLogicType>([path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountBillingLogic', key]),props({} as AccountBillingLogicProps),@@ -42,36 +80,43 @@ export const accountBillingLogic = kea<accountBillingLogicType>([actions({setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),}),- reducers({+ reducers(({ props }) => ({dateRange: [- { date_from: '-30d', date_to: null } as BillingDateRange,+ DEFAULT_DATE_RANGE[props.kind] as BillingDateRange,{setDateRange: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom, date_to: dateTo }),},],- }),+ })),loaders(({ props }) => ({- savedInsight: [- null as QueryBasedInsightModel | null,+ savedInsights: [+ 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- }+ loadSavedInsights: async (_ = null, breakpoint) => {+ const insights = await Promise.all(+ BILLING_INSIGHT_SHORT_IDS[props.kind].map(async (shortId) => {+ try {+ return await insightsApi.getByShortId(shortId)+ } catch (error) {+ if (isBreakpoint(error as Error)) {+ throw error+ }+ posthog.captureException(error as Error, {+ scope: 'accountBillingLogic.loadSavedInsights',+ shortId,+ })+ return null+ }+ })+ )+ breakpoint()+ return insights.filter((insight): insight is QueryBasedInsightModel => insight !== null)},},],})),selectors({- // The saved insight filters on the calendar `date` column, so the range must be resolved to absolute dates.+ // The saved insights filter on a calendar date column, so the range must be resolved to absolute dates.resolvedDateRange: [(s) => [s.dateRange],(dateRange): BillingDateRange => {@@ -83,40 +128,31 @@ export const accountBillingLogic = kea<accountBillingLogicType>([}},],- // 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],- }+ variableOverridesByShortId: [+ (s) => [s.savedInsights, s.resolvedDateRange, (_, p) => p.externalId],+ (savedInsights, resolvedDateRange, externalId): Record<string, Record<string, HogQLVariable>> => {+ const overridesByShortId: Record<string, Record<string, HogQLVariable>> = {}+ for (const insight of savedInsights ?? []) {+ const overrides = buildVariableOverrides(insight, resolvedDateRange, externalId)+ if (overrides) {+ overridesByShortId[insight.short_id] = overrides}}- return overrides+ return overridesByShortId},],+ // 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, accountId, kind) =>+ (shortId: string): string =>+ `account-billing-${accountId}-${kind}-${shortId}-${resolvedDateRange.date_from}-${resolvedDateRange.date_to}`,+ ],}),afterMount(({ actions, props }) => {if (props.externalId) {- actions.loadSavedInsight()+ actions.loadSavedInsights()}}),])diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex 2e1cd7bbe5bf..35c8c7ca7215 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -4,7 +4,7 @@ import posthog from 'posthog-js'import type { accountsExpansionLogicType } from './accountsExpansionLogicType'import { AccountsEvents } from './constants'-export type AccountExpansionTab = 'notes' | 'users' | 'usage'+export type AccountExpansionTab = 'notes' | 'users' | 'usage' | 'spend'export const DEFAULT_ACCOUNT_TAB: AccountExpansionTab = 'notes'