: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 account detail scene (#91015)
Arthur Moreira de Deus664d6ddbd289
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex eb15c0254ed6..4e979d4fefa8 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -285,6 +285,7 @@ export const FEATURE_FLAGS = {CRM_ITERATION_ONE: 'crm-iteration-one', // owner: @arthurdedeus #team-customer-analyticsCUSTOM_FACET_PINNING: 'custom-facet-pinning', // owner: #team-logs — gates pinning custom facets to the logs/tracing facet railsCUSTOMER_ANALYTICS: 'customer-analytics-roadmap', // owner: @arthurdedeus #team-customer-analytics+ CUSTOMER_ANALYTICS_ACCOUNT_SCENE: 'customer-analytics-account-scene', // owner: @arthurdedeus #team-customer-analyticsCUSTOMER_ANALYTICS_CSP: 'customer-analytics-csp', // owner: @arthurdedeus #team-customer-analytics, gates the Customer analytics > Accounts settings tab (account_group_type_index dropdown)CUSTOMER_ANALYTICS_FEATURE_REQUESTS: 'customer-analytics-feature-requests',CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analyticsdiff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 576bfd31680d..e472a81f8204 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -46,6 +46,8 @@ export const productScenes: Record<string, () => Promise<any>> = {SupportSettings: () => import('../../products/conversations/frontend/scenes/settings/SupportSettingsScene'),MyTickets: () => import('../../products/conversations/frontend/scenes/myTickets/MyTicketsScene'),CustomerAnalytics: () => import('../../products/customer_analytics/frontend/CustomerAnalyticsScene'),+ CustomerAnalyticsAccount: () =>+ import('../../products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene'),CustomerAnalyticsConfiguration: () =>import('../../products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/CustomerAnalyticsConfigurationScene'),CustomerJourneyBuilder: () =>diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 531ac70e52c0..e75336d9ace9 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -104,8 +104,8 @@ export const productRoutes: Record<string, [string, string]> = {'/my-tickets': ['MyTickets', 'myTickets'],'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],'/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],- '/customer_analytics/accounts/:accountId': ['CustomerAnalytics', 'customerAnalyticsAccounts'],- '/customer_analytics/accounts/:accountId/:tab': ['CustomerAnalytics', 'customerAnalyticsAccounts'],+ '/customer_analytics/accounts/:accountId': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],+ '/customer_analytics/accounts/:accountId/:tab': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],'/customer_analytics/notes': ['CustomerAnalytics', 'customerAnalyticsNotes'],'/customer_analytics/announcements': ['CustomerAnalytics', 'customerAnalyticsAnnouncements'],'/customer_analytics/feed': ['CustomerAnalytics', 'customerAnalyticsFeed'],@@ -598,6 +598,7 @@ export const productConfiguration: Record<string, any> = {iconType: 'cohort',docsHref: 'https://posthog.com/docs/customer-analytics',},+ CustomerAnalyticsAccount: { projectBased: true, name: 'Account details', iconType: 'cohort' },CustomerAnalyticsConfiguration: { projectBased: true, name: 'Customer analytics configuration' },CustomerJourneyBuilder: { projectBased: true, name: 'New journey' },CustomerJourneyTemplates: { projectBased: true, name: 'New journey' },@@ -2043,7 +2044,12 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [tags: ['beta'],flag: FEATURE_FLAGS.CUSTOMER_ANALYTICS,sceneKey: 'CustomerAnalytics',- sceneKeys: ['CustomerAnalytics', 'CustomerJourneyTemplates', 'CustomerJourneyBuilder'],+ sceneKeys: [+ 'CustomerAnalytics',+ 'CustomerAnalyticsAccount',+ 'CustomerJourneyTemplates',+ 'CustomerJourneyBuilder',+ ],},{path: 'Dashboards',diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsxindex 456d9d48f75e..da103800f323 100644--- a/frontend/src/scenes/max/max-constants.tsx+++ b/frontend/src/scenes/max/max-constants.tsx@@ -1613,7 +1613,7 @@ export const MODE_DEFINITIONS: Record<description:'Works with your customer accounts — assign owners, review notes and usage, and dig into account data.',icon: iconForType('cohort'),- scenes: new Set([Scene.CustomerAnalytics]),+ scenes: new Set([Scene.CustomerAnalytics, Scene.CustomerAnalyticsAccount]),flag: 'CUSTOMER_ANALYTICS_CSP',},}diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 8b0f085a7522..1dd292835701 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -33,6 +33,7 @@ export enum Scene {Comments = 'Comments',CustomCss = 'CustomCss',CustomerAnalytics = 'CustomerAnalytics',+ CustomerAnalyticsAccount = 'CustomerAnalyticsAccount',CustomerAnalyticsConfiguration = 'CustomerAnalyticsConfiguration',CustomerJourneyBuilder = 'CustomerJourneyBuilder',Dashboard = 'Dashboard',diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex c06a9279d759..2aa09cc5096a 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -68,7 +68,7 @@ Ignored accounts (`ignored_at IS NOT NULL`) are excluded from list rows and overOverview tiles run as a separate metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`; `null` when there are no tiles or while definitions are loading). Count, sum, average, minimum, maximum, median, scaling, and threshold counts execute in Postgres. The "My accounts" checkbox resolves to the current user's explicit ID before either query is built, so shared URLs remain viewer-independent. Two cell shapes matter:-- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — read directly from the keyed row's `id`, `name`, `externalId`, and `logoDomain`. This is the row's identity: `id` (the account PK) drives expansion, scroll, and role updates; `externalId` is the copyable group key. `getNameCell()` in `AccountsTable.tsx` is the canonical accessor. `AccountNameCell.tsx` owns the shared name, deep link, and copyable external ID presentation. The Accounts list passes `logoDomain`, which adds `AccountLogo`, and wraps the name with inline expansion behavior. Other account tables omit the logo and use normal deep-link navigation.+- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — read directly from the keyed row's `id`, `name`, `externalId`, and `logoDomain`. This is the row's identity: `id` (the account PK) drives expansion, scroll, and role updates; `externalId` is the copyable group key. `getNameCell()` in `AccountsTable.tsx` is the canonical accessor. `AccountNameCell.tsx` owns the shared name, deep link, and copyable external ID presentation. `AccountsTableNameCell.tsx` owns list selection behavior. The Accounts list passes `logoDomain`, which adds `AccountLogo`. Other account tables omit the logo and use normal deep-link navigation.- **relationship columns** — returned in `AccountsTableRow.relationships` as arrays of active assignee user ids keyed by definition id (`[]` when unassigned). The legacy names `csm`/`account_executive`/`account_owner` remain stored in defaults, saved views, and URL state, then translate into typed relationship columns matched by seeded definition name (`LEGACY_ROLE_COLUMNS`); a legacy column with no matching definition is dropped from the query. Other definitions are pickable from the "Relationships" column group with opaque `rel_<id>` aliases, resolved back via `aliasToRelationshipDefinition`. Cells render `RelationshipCell`: single-holder definitions get an editable `MemberSelect` (writes via the relationships assign/end endpoints — assign auto-ends the previous holder server-side); multi-holder definitions render read-only. User ids resolve to members via `membersLogic` (loaded up front in `accountsLogic.afterMount`). Sorting uses the alias directly (arrays of ids — deterministic but not email order).### Account logos@@ -125,6 +125,17 @@ Resetting on fresh load lets a filtered-down set (now ≤ one page) return to inSort safety: removing the sorted column drops the sort (`clearSortIfColumnRemoved`); otherwise a server-side sort would reference a missing SELECT alias.+## Account detail scene++`CUSTOMER_ANALYTICS_ACCOUNT_SCENE` changes account links from inline row expansion to `CustomerAnalyticsAccountScene` at `/customer_analytics/accounts/:accountId`.+The detail scene loads the account through `accountsRetrieve` and currently renders only its name and external ID.++When the flag is off, the detail scene renders `CustomerAnalyticsScene` and preserves the legacy filtered, expanded-row behavior.+The optional `/:tab` route remains valid for existing links in both states. The detail scene ignores its tab value.++`AccountsTableNameCell` records `AccountOpened` when a person opens an account in either experience.+`AccountsTable` disables row expansion while the flag is on.+## The expanded row`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `feature_requests` / `usage` / `spend` / `opportunities` / `conversations` / `meetings` / `event_stream` (`AccountExpansionTab`; the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`). Pagination inside these tabs keeps its page state out of the URL so changing pages does not rerun deep-link restoration and replace the active tab.@@ -180,8 +191,8 @@ The Notes tab is server-paginated, searchable, and sortable (all via `accountNot### Deep-link to one account (path route)-`/customer_analytics/accounts/:accountId/:tab` opens a single account directly (separate from the persistent `#view=` filter state).-`accountsLogic.urlToAction` reads the route params, validates the id (UUID) and tab (against `ACCOUNT_EXPANSION_TABS`, default `DEFAULT_ACCOUNT_TAB`), sets `accountIdFilter`, and opens the tab via `openAccountTab`.+`/customer_analytics/accounts/:accountId/:tab` opens the account detail scene when `CUSTOMER_ANALYTICS_ACCOUNT_SCENE` is enabled.+When the flag is off, `accountsLogic.urlToAction` reads the route params, validates the id (UUID) and tab (against `ACCOUNT_EXPANSION_TABS`, default `DEFAULT_ACCOUNT_TAB`), sets `accountIdFilter`, and opens the tab via `openAccountTab`.Returning to the bare `/customer_analytics/accounts` clears `accountIdFilter`.Because it filters by the PK, the id alone is enough; no name/external_id is needed in the link.@@ -295,7 +306,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` || `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` || `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics accounts account opened` | `AccountsTable.tsx` `NameCell` account-name `<Link>` `onClick` (only when the row expands, not when it collapses) | _(none — the row's `id` is customer PII-adjacent and kept out)_ |+| `customer analytics accounts account opened` | `AccountsTableNameCell.tsx` account-name `<Link>` `onClick` (only when the row expands in the legacy experience) | _(none — the row's `id` is customer PII-adjacent and kept out)_ || ~~`customer analytics accounts columns saved`~~ | _Deprecated — no longer emitted. Column changes are now saved as part of a view (see view events below)._ | _n/a_ || `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` || `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsxindex cae361a9c232..22bc00911143 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx@@ -1,5 +1,4 @@import { useActions, useValues } from 'kea'-import posthog from 'posthog-js'import { useMemo } from 'react'import { IconCheck, IconX } from '@posthog/icons'@@ -10,11 +9,13 @@ import { MemberSelect } from 'lib/components/MemberSelect'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { Sparkline } from 'lib/components/Sparkline'import { TZLabel } from 'lib/components/TZLabel'+import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'import { Link } from 'lib/lemon-ui/Link'import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { percentage } from 'lib/utils/numbers'import { membersLogic } from 'scenes/organization/membersLogic'import { urls } from 'scenes/urls'@@ -32,13 +33,12 @@ import type {import { ACCOUNTS_TABLE_DATA_NODE_KEY } from '../../constants'import { formatCustomPropertyValue } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'-import { AccountNameCell } from './AccountNameCell'import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'import { AccountColumnDisplayConfig, LEGACY_ROLE_COLUMNS, accountsColumnConfigLogic } from './accountsColumnConfigLogic'import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'import { accountsLogic, savingRoleKey } from './accountsLogic'+import { AccountsTableNameCell } from './AccountsTableNameCell'import { accountsTableCell, isAccountsTableRow } from './accountsTableQuery'-import { AccountsEvents } from './constants'// Shape the name renderer uses from the keyed AccountsTableRow identity fields.type AccountNameCellData = { name: string; external_id: string | null; id: string; logo_domain: string | null }@@ -77,27 +77,13 @@ function parseAssignedUserIds(value: unknown): number[] {}function NameCell({ record }: { record: unknown }): JSX.Element {- const { isAccountExpanded } = useValues(accountsExpansionLogic)- const { toggleAccountExpanded } = useActions(accountsExpansionLogic)const cell = getNameCell(record)- const accountId = cell?.idreturn (- <AccountNameCell- accountId={accountId}+ <AccountsTableNameCell+ accountId={cell?.id}name={cell?.name ?? ''}externalId={cell?.external_id}logoDomain={cell?.logo_domain}- onClick={(event) => {- if (!accountId || event.metaKey || event.ctrlKey || event.shiftKey) {- return- }- event.preventDefault()- event.stopPropagation()- if (!isAccountExpanded(accountId)) {- posthog.capture(AccountsEvents.AccountOpened)- }- toggleAccountExpanded(accountId)- }}/>)}@@ -326,6 +312,7 @@ function CanonicalTimestampCell({value: stringtab: AccountExpansionTab}): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)const { openAccountTab } = useActions(accountsExpansionLogic)const accountId = getNameCell(record)?.idconst label = <TZLabel time={value} showSeconds={definition.display_type === 'datetime'} />@@ -337,8 +324,12 @@ function CanonicalTimestampCell({<Linkto={urls.customerAnalyticsAccount(accountId, tab)}onClick={(event) => {- // Modifier-click keeps the href's new-tab behavior, matching the account name cell.- if (event.metaKey || event.ctrlKey || event.shiftKey) {+ if (+ featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE] ||+ event.metaKey ||+ event.ctrlKey ||+ event.shiftKey+ ) {return}event.preventDefault()@@ -503,10 +494,15 @@ function useContextColumns(): Record<string, QueryContextColumn> {}function useExpandable(): QueryContext<DataTableNode>['expandable'] {+ const { featureFlags } = useValues(featureFlagLogic)const { expandedAccountIds } = useValues(accountsExpansionLogic)const { toggleAccountExpanded } = useActions(accountsExpansionLogic)- return useMemo(- () => ({+ const accountSceneEnabled = !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]+ return useMemo(() => {+ if (accountSceneEnabled) {+ return undefined+ }+ return {noIndent: true,expandedRowClassName: '[&>td]:overflow-visible!',isRowExpanded: ({ result }) => {@@ -531,9 +527,8 @@ function useExpandable(): QueryContext<DataTableNode>['expandable'] {<AccountNotebooksExpansion accountId={cell.id} externalId={cell.external_id ?? ''} />) : null},- }),- [expandedAccountIds, toggleAccountExpanded]- )+ }+ }, [accountSceneEnabled, expandedAccountIds, toggleAccountExpanded])}const SKELETON_ROW_COUNT = 5@@ -576,18 +571,22 @@ const SKELETON_COLUMNS: LemonTableColumns<{ key: number }> = [})),]-function AccountsTableSkeleton(): JSX.Element {+function AccountsTableSkeleton({ expandable }: { expandable: boolean }): JSX.Element {return (<LemonTableclassName="DataTable"columns={SKELETON_COLUMNS}dataSource={Array.from({ length: SKELETON_ROW_COUNT }, (_, key) => ({ key }))}rowKey="key"- expandable={{- noIndent: true,- expandedRowRender: () => null,- rowExpandable: () => true,- }}+ expandable={+ expandable+ ? {+ noIndent: true,+ expandedRowRender: () => null,+ rowExpandable: () => true,+ }+ : undefined+ }/>)}@@ -600,12 +599,14 @@ export function AccountsTable(): JSX.Element {query: accountsQuerySource ?? accountsDataTableQuery.source,} as DataNodeLogicProps))+ const { featureFlags } = useValues(featureFlagLogic)const contextColumns = useContextColumns()const expandable = useExpandable()+ const accountSceneEnabled = !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]// A null source means the query is still waiting on the relationship// definitions — same skeleton as the initial fetch, not an empty table.if ((responseLoading || !accountsQuerySource) && !response) {- return <AccountsTableSkeleton />+ return <AccountsTableSkeleton expandable={!accountSceneEnabled} />}return (<div className="@container">diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.test.tsxnew file mode 100644index 000000000000..cec39eadaaff--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.test.tsx@@ -0,0 +1,83 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { Provider } from 'kea'+import { router } from 'kea-router'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { accountsExpansionLogic } from './accountsExpansionLogic'+import { AccountsTableNameCell } from './AccountsTableNameCell'+import { AccountsEvents } from './constants'++const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'++describe('AccountsTableNameCell', () => {+ beforeEach(() => {+ initKeaTests()+ featureFlagLogic.mount()+ accountsExpansionLogic.mount()+ jest.spyOn(posthog, 'capture').mockImplementation()+ })++ afterEach(() => {+ cleanup()+ featureFlagLogic.unmount()+ accountsExpansionLogic.unmount()+ })++ it('expands the row instead of navigating when the account scene flag is off', () => {+ featureFlagLogic.actions.setFeatureFlags([], {})++ render(+ <Provider>+ <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" />+ </Provider>+ )++ const link = screen.getByText('Test account')+ expect(fireEvent.click(link)).toBe(false)++ expect(accountsExpansionLogic.values.isAccountExpanded(ACCOUNT_ID)).toBe(true)+ expect(posthog.capture).toHaveBeenCalledWith(AccountsEvents.AccountOpened)+ })++ it('keeps modifier-click behavior for the account link', () => {+ featureFlagLogic.actions.setFeatureFlags([], {})++ render(+ <Provider>+ <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" />+ </Provider>+ )++ fireEvent.click(screen.getByText('Test account'), { metaKey: true })++ expect(accountsExpansionLogic.values.isAccountExpanded(ACCOUNT_ID)).toBe(false)+ expect(posthog.capture).not.toHaveBeenCalled()+ })++ it('navigates to the account scene without expanding when the flag is on', () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]: true })++ render(+ <Provider>+ <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" />+ </Provider>+ )++ const link = screen.getByText('Test account')+ expect(link.closest('a')?.getAttribute('href')).toMatch(+ new RegExp(`/customer_analytics/accounts/${ACCOUNT_ID}$`)+ )+ fireEvent.click(link)++ expect(router.values.location.pathname).toMatch(new RegExp(`/customer_analytics/accounts/${ACCOUNT_ID}$`))+ expect(accountsExpansionLogic.values.isAccountExpanded(ACCOUNT_ID)).toBe(false)+ expect(posthog.capture).toHaveBeenCalledWith(AccountsEvents.AccountOpened)+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsxnew file mode 100644index 000000000000..6b6920f93be9--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsx@@ -0,0 +1,57 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'+import type { MouseEventHandler } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { AccountNameCell } from './AccountNameCell'+import { accountsExpansionLogic } from './accountsExpansionLogic'+import { AccountsEvents } from './constants'++export interface AccountsTableNameCellProps {+ accountId?: string+ externalId?: string | null+ logoDomain?: string | null+ name: string+}++export function AccountsTableNameCell({+ accountId,+ externalId,+ logoDomain,+ name,+}: AccountsTableNameCellProps): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const { isAccountExpanded } = useValues(accountsExpansionLogic)+ const { toggleAccountExpanded } = useActions(accountsExpansionLogic)+ const accountSceneEnabled = !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]++ const handleClick: MouseEventHandler<HTMLElement> = (event) => {+ if (!accountId || event.metaKey || event.ctrlKey || event.shiftKey) {+ return+ }++ if (accountSceneEnabled) {+ posthog.capture(AccountsEvents.AccountOpened)+ return+ }++ event.preventDefault()+ event.stopPropagation()+ if (!isAccountExpanded(accountId)) {+ posthog.capture(AccountsEvents.AccountOpened)+ }+ toggleAccountExpanded(accountId)+ }++ return (+ <AccountNameCell+ accountId={accountId}+ name={name}+ externalId={externalId}+ logoDomain={logoDomain}+ onClick={handleClick}+ />+ )+}diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.tsindex 4df14a9e7888..31ec26609478 100644--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.test.ts@@ -60,6 +60,12 @@ describe('customerAnalyticsSceneLogic', () => {expectLogic(logic).toMatchValues({ activeTab: 'feature_requests' })})+ it('activates the Accounts tab for the account detail scene key', () => {+ sceneLogic.actions.setScene(Scene.CustomerAnalyticsAccount, 'customerAnalyticsAccount', emptySceneParams)++ expectLogic(logic).toMatchValues({ activeTab: 'accounts' })+ })+it('reads filter_test_accounts from URL', () => {expectLogic(logic).toMatchValues({filterTestAccounts: true,diff --git a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.tsindex 258b60694c78..2153d5fb9c1d 100644--- a/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts+++ b/products/customer_analytics/frontend/customerAnalyticsSceneLogic.ts@@ -48,6 +48,7 @@ type ActiveTab = 'dashboard' | 'journeys' | 'accounts' | 'notes' | 'announcementconst SCENE_KEY_TO_TAB: Record<string, ActiveTab> = {customerAnalyticsJourneys: 'journeys',customerAnalyticsAccounts: 'accounts',+ customerAnalyticsAccount: 'accounts',customerAnalyticsNotes: 'notes',customerAnalyticsAnnouncements: 'announcements',customerAnalyticsFeed: 'feed',diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsxnew file mode 100644index 000000000000..f75aeb9fd181--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx@@ -0,0 +1,100 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonCard, LemonSkeleton } from '@posthog/lemon-ui'++import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { NotFound } from 'lib/components/NotFound'+import { FEATURE_FLAGS } from 'lib/constants'+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { SceneExport } from 'scenes/sceneTypes'++import { FeaturePreviewSceneGate } from '~/layout/scenes/components/FeaturePreviewSceneGate'+import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ProductKey } from '~/queries/schema/schema-general'++import { CustomerAnalyticsScene } from '../../CustomerAnalyticsScene'+import { customerAnalyticsFeaturePreviewGate } from '../../featurePreviewGate'+import {+ CustomerAnalyticsAccountSceneLogicProps,+ customerAnalyticsAccountSceneLogic,+} from './customerAnalyticsAccountSceneLogic'++export const scene: SceneExport<CustomerAnalyticsAccountSceneLogicProps> = {+ component: CustomerAnalyticsAccountScene,+ logic: customerAnalyticsAccountSceneLogic,+ productKey: ProductKey.CUSTOMER_ANALYTICS,+ paramsToProps: ({ params: { accountId } }) => ({ accountId: accountId ?? '' }),+}++export function CustomerAnalyticsAccountScene(): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)++ if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE]) {+ return <CustomerAnalyticsScene />+ }++ if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {+ return <NotFound object="page" />+ }++ return (+ <FeaturePreviewSceneGate config={customerAnalyticsFeaturePreviewGate}>+ <CustomerAnalyticsAccountSceneContent />+ </FeaturePreviewSceneGate>+ )+}++function CustomerAnalyticsAccountSceneContent(): JSX.Element {+ const { account, accountLoadError, accountLoading, isAccountMissing } = useValues(+ customerAnalyticsAccountSceneLogic+ )+ const { loadAccount } = useActions(customerAnalyticsAccountSceneLogic)++ useOnMountEffect(loadAccount)++ if (isAccountMissing) {+ return <NotFound object="account" />+ }++ if (!account && accountLoadError) {+ return (+ <SceneContent>+ <LemonBanner+ type="error"+ action={{ children: 'Try again', onClick: loadAccount, loading: accountLoading }}+ >+ Couldn't load this account. Try again.+ </LemonBanner>+ </SceneContent>+ )+ }++ if (!account) {+ return (+ <SceneContent>+ <div className="flex flex-col gap-3 max-w-xl">+ <LemonSkeleton className="h-6 w-56" />+ <LemonSkeleton className="h-24 w-full" />+ </div>+ </SceneContent>+ )+ }++ return (+ <SceneContent>+ <SceneTitleSection name={account.name} resourceType={{ type: 'cohort' }} />+ <LemonCard hoverEffect={false} className="flex flex-col gap-1 max-w-xl">+ <span className="text-xs text-secondary">External ID</span>+ {account.external_id ? (+ <CopyToClipboardInline explicitValue={account.external_id} description="external ID">+ {account.external_id}+ </CopyToClipboardInline>+ ) : (+ <span className="text-secondary">Not set</span>+ )}+ </LemonCard>+ </SceneContent>+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.tsnew file mode 100644index 000000000000..951c6cb938f0--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts@@ -0,0 +1,105 @@+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api'++import { initKeaTests } from '~/test/init'++import { accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'+import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'++jest.mock('products/customer_analytics/frontend/generated/api', () => ({+ ...jest.requireActual('products/customer_analytics/frontend/generated/api'),+ accountsRetrieve: jest.fn(),+}))++const mockAccountsRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>++const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'+const account: AccountApi = {+ id: ACCOUNT_ID,+ name: 'Test account',+ external_id: 'test-account-external-id',+ tags: [],+ notebooks: [],+ ignored_at: null,+ created_at: '2026-01-01T00:00:00Z',+ created_by: null,+ updated_at: null,+}++describe('customerAnalyticsAccountSceneLogic', () => {+ let logic: ReturnType<typeof customerAnalyticsAccountSceneLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.resetAllMocks()+ logic = customerAnalyticsAccountSceneLogic({ accountId: ACCOUNT_ID })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('loads the account and uses its name in the breadcrumb', async () => {+ mockAccountsRetrieve.mockResolvedValue(account)++ logic.actions.loadAccount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.account).toEqual(account)+ expect(logic.values.accountLoadError).toBeNull()+ expect(logic.values.breadcrumbs.at(-1)?.name).toBe(account.name)+ })++ it('classifies a missing account without reporting an exception', async () => {+ const captureException = jest.spyOn(posthog, 'captureException')+ mockAccountsRetrieve.mockRejectedValue(new ApiError('Not found', 404))++ logic.actions.loadAccount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.isAccountMissing).toBe(true)+ expect(captureException).not.toHaveBeenCalled()+ })++ it('reports unexpected load failures', async () => {+ const failure = new ApiError('Server error', 500)+ const captureException = jest.spyOn(posthog, 'captureException')+ mockAccountsRetrieve.mockRejectedValue(failure)++ logic.actions.loadAccount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.isAccountMissing).toBe(false)+ expect(logic.values.accountLoadError).toBe(failure)+ expect(captureException).toHaveBeenCalledWith(failure, {+ scope: 'customerAnalyticsAccountSceneLogic.loadAccount',+ })+ })++ it('clears a previous error when retrying', async () => {+ mockAccountsRetrieve.mockRejectedValueOnce(new ApiError('Server error', 500))++ logic.actions.loadAccount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.accountLoadError).toBeInstanceOf(ApiError)++ let resolveAccount: (value: AccountApi) => void+ mockAccountsRetrieve.mockReturnValueOnce(+ new Promise<AccountApi>((resolve) => {+ resolveAccount = resolve+ })+ )++ logic.actions.loadAccount()+ expect(logic.values.accountLoadError).toBeNull()++ resolveAccount!(account)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.account).toEqual(account)+ })+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.tsnew file mode 100644index 000000000000..e29d7be10853--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts@@ -0,0 +1,145 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { ApiError } from 'lib/api'+import { Scene } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { Breadcrumb } from '~/types'++import { accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'+import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'++export interface CustomerAnalyticsAccountSceneLogicProps {+ accountId: string+}++function isAccountNotFound(error: unknown): boolean {+ return error instanceof ApiError && error.status === 404+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface customerAnalyticsAccountSceneLogicValues {+ currentTeamId: number | null // teamLogic+ account: AccountApi | null+ accountLoadError: unknown+ accountLoading: boolean+ breadcrumbs: Breadcrumb[]+ isAccountMissing: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface customerAnalyticsAccountSceneLogicActions {+ loadAccount: () => {+ value: true+ }+ loadAccountFailure: (error: unknown) => {+ error: unknown+ }+ loadAccountSuccess: (account: AccountApi) => {+ account: AccountApi+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface customerAnalyticsAccountSceneLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ isAccountMissing: (account: AccountApi | null, accountLoading: boolean, accountLoadError: unknown) => boolean+ breadcrumbs: (account: AccountApi | null) => Breadcrumb[]+ }+}++export type customerAnalyticsAccountSceneLogicType = MakeLogicType<+ customerAnalyticsAccountSceneLogicValues,+ customerAnalyticsAccountSceneLogicActions,+ CustomerAnalyticsAccountSceneLogicProps,+ customerAnalyticsAccountSceneLogicMeta+>++export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSceneLogicType>([+ path((key) => [+ 'products',+ 'customer_analytics',+ 'frontend',+ 'scenes',+ 'CustomerAnalyticsAccountScene',+ 'customerAnalyticsAccountSceneLogic',+ key,+ ]),+ props({} as CustomerAnalyticsAccountSceneLogicProps),+ key((props) => props.accountId),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),+ actions({+ loadAccount: true,+ loadAccountSuccess: (account: AccountApi) => ({ account }),+ loadAccountFailure: (error: unknown) => ({ error }),+ }),+ reducers({+ account: [+ null as AccountApi | null,+ {+ loadAccountSuccess: (_, { account }) => account,+ },+ ],+ accountLoading: [+ false,+ {+ loadAccount: () => true,+ loadAccountSuccess: () => false,+ loadAccountFailure: () => false,+ },+ ],+ accountLoadError: [+ null as unknown,+ {+ loadAccount: () => null,+ loadAccountSuccess: () => null,+ loadAccountFailure: (_, { error }) => error,+ },+ ],+ }),+ selectors({+ isAccountMissing: [+ (s) => [s.account, s.accountLoading, s.accountLoadError],+ (account: AccountApi | null, accountLoading: boolean, accountLoadError: unknown): boolean =>+ !account && !accountLoading && isAccountNotFound(accountLoadError),+ ],+ breadcrumbs: [+ (s) => [s.account],+ (account: AccountApi | null): Breadcrumb[] => [+ {+ key: Scene.CustomerAnalytics,+ name: 'Accounts',+ path: urls.customerAnalyticsAccounts(),+ iconType: 'cohort',+ },+ {+ key: Scene.CustomerAnalyticsAccount,+ name: account?.name ?? 'Account',+ iconType: 'cohort',+ },+ ],+ ],+ }),+ listeners(({ actions, props, values }) => ({+ loadAccount: async () => {+ try {+ actions.loadAccountSuccess(await accountsRetrieve(String(values.currentTeamId), props.accountId))+ } catch (error) {+ actions.loadAccountFailure(error)+ }+ },+ loadAccountFailure: ({ error }) => {+ if (isAccountNotFound(error)) {+ return+ }+ posthog.captureException(error instanceof Error ? error : new Error('Could not load account'), {+ scope: 'customerAnalyticsAccountSceneLogic.loadAccount',+ })+ },+ })),+])diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsxindex fdce24db58cd..cadb63b1a075 100644--- a/products/customer_analytics/manifest.tsx+++ b/products/customer_analytics/manifest.tsx@@ -20,6 +20,12 @@ export const manifest: ProductManifest = {iconType: 'cohort',docsHref: 'https://posthog.com/docs/customer-analytics',},+ CustomerAnalyticsAccount: {+ import: () => import('./frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene'),+ projectBased: true,+ name: 'Account details',+ iconType: 'cohort',+ },CustomerAnalyticsConfiguration: {import: () =>import('./frontend/scenes/CustomerAnalyticsConfigurationScene/CustomerAnalyticsConfigurationScene'),@@ -47,10 +53,9 @@ export const manifest: ProductManifest = {routes: {'/customer_analytics/dashboard': ['CustomerAnalytics', 'customerAnalyticsDashboard'],'/customer_analytics/accounts': ['CustomerAnalytics', 'customerAnalyticsAccounts'],- // Deep-link to a single account (filtered + expanded), optionally on a given tab. Same scene key- // as the list so the accounts tab activates; accountsLogic reads the params.- '/customer_analytics/accounts/:accountId': ['CustomerAnalytics', 'customerAnalyticsAccounts'],- '/customer_analytics/accounts/:accountId/:tab': ['CustomerAnalytics', 'customerAnalyticsAccounts'],+ // The detail scene serves these paths behind its flag and falls back to the list for legacy deep links.+ '/customer_analytics/accounts/:accountId': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],+ '/customer_analytics/accounts/:accountId/:tab': ['CustomerAnalyticsAccount', 'customerAnalyticsAccount'],'/customer_analytics/notes': ['CustomerAnalytics', 'customerAnalyticsNotes'],'/customer_analytics/announcements': ['CustomerAnalytics', 'customerAnalyticsAnnouncements'],'/customer_analytics/feed': ['CustomerAnalytics', 'customerAnalyticsFeed'],@@ -76,7 +81,7 @@ export const manifest: ProductManifest = {customerAnalytics: (): string => '/customer_analytics',customerAnalyticsDashboard: (): string => '/customer_analytics/dashboard',customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',- // Path-based deep link to one account: filters the list to it, expands it, opens `tab`.+ // Account detail path. The flag-off scene falls back to the filtered, expanded Accounts list.customerAnalyticsAccount: (accountId: string, tab?: string): string =>`/customer_analytics/accounts/${accountId}${tab ? `/${tab}` : ''}`,customerAnalyticsNotes: (): string => '/customer_analytics/notes',@@ -103,7 +108,12 @@ export const manifest: ProductManifest = {tags: ['beta'],flag: FEATURE_FLAGS.CUSTOMER_ANALYTICS,sceneKey: 'CustomerAnalytics',- sceneKeys: ['CustomerAnalytics', 'CustomerJourneyTemplates', 'CustomerJourneyBuilder'],+ sceneKeys: [+ 'CustomerAnalytics',+ 'CustomerAnalyticsAccount',+ 'CustomerJourneyTemplates',+ 'CustomerJourneyBuilder',+ ],},],// Deliberately not behind the Customer analytics flag: warehouse-backed person and group