: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): reuse account tabs in detail scene (#94393)
Arthur Moreira de Deusa2899851ce4a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 747552377adf..ee44a792a211 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6236,6 +6236,14 @@ snapshots:hash: v1.k794b7964.c4b1a6986db44af6a8e496ec80f9d177d131a2db6e5fa09cc87a79ec6c53a6f4.09YBKQpa28bk-h-ntRltPIPEGy_XRWA3Ner82vwyHRcscenes-app-batchexports--runs-with-data--light:hash: v1.k794b7964.4c1646577dc53efffd814b1a2e723f9da6b10d3641e979f48c5d0447859e2348.fkHuUw1l_9c3rJKSi467jx-6Nv81nNp-PjeRmsgU7l0+ scenes-app-customer-analytics-account-detail--default--dark:+ hash: v1.k794b7964.32d5329bf4ce6055010743914ec226973cc4d455a70581692f97d8cae13c04f1.4Zd5MpCXYXWDIegWaghLkfmgRx11JTVSpbyCab_3_YU+ scenes-app-customer-analytics-account-detail--default--light:+ hash: v1.k794b7964.3a6ffd58e88bdd30817bc9c6b1c2c9f9bae8825975c121157efb3bd6fbba9f39.81lpbCyMf0S_9mRYZFcT97ecch6YY1--yoxMK2hI-xU+ scenes-app-customer-analytics-account-detail--narrow--dark:+ hash: v1.k794b7964.31ffca7eb6c59cf545dd8f16e7a532149448b95c65444aa14d5e776a0875dafd.lULK4-DoenY3SeZK1Sfr50doCkqdIbyl9U35M4ah00g+ scenes-app-customer-analytics-account-detail--narrow--light:+ hash: v1.k794b7964.5a6763d49a273274f686f1517da9d2ba4af64b5be6897a9886addc04f429c209.JZ6O0iGKO-5AKZyg0XnVZ8JoOZ2-Jg4i9E746aSUm2Iscenes-app-customer-analytics-accounts--default--dark:hash: v1.k794b7964.dbaff4c177f276bb47e0587c5f66195cec454a062fa87a2c506ad1cbc5d04a40.3YhGb7YnUDZDgX333J4grk5qzIg-8A1qMdTDxUiTLecscenes-app-customer-analytics-accounts--default--light:diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 39859b652125..31ad73160013 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -595,7 +595,12 @@ export const productConfiguration: Record<string, any> = {iconType: 'cohort',docsHref: 'https://posthog.com/docs/customer-analytics',},- CustomerAnalyticsAccount: { projectBased: true, name: 'Account details', iconType: 'cohort' },+ CustomerAnalyticsAccount: {+ projectBased: true,+ name: 'Account details',+ iconType: 'cohort',+ layout: 'app-full-scene-height',+ },CustomerAnalyticsConfiguration: { projectBased: true, name: 'Customer analytics configuration' },CustomerJourneyBuilder: { projectBased: true, name: 'New journey' },CustomerJourneyTemplates: { projectBased: true, name: 'New journey' },diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 7e7a9966cafd..6033bb8488dd 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -139,19 +139,28 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove## 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.-+The keyed scene logic loads the account through `accountsRetrieve` when it mounts, including direct navigation between account routes.+The scene renders the account logo in `SceneTitleSection`.+`AccountSidebar` holds editable tags and a Properties section. It sits flush with the scene's left edge and uses only a right border.+Tag edits save through `accountsPartialUpdate` and update optimistically. Only the latest save can replace or reload the account.+It reuses `AccountDetailTabs` and `AccountNotesExpansion` with the expanded row, but mounts only the active tab so inactive detail tabs do not load data.+Tables use borders in the detail scene and remain embedded in expanded rows.+Configure tabs and Add view sit in the scene header. They open work-in-progress dialogs.+The Properties section stays visible when empty, and its gear opens the same work-in-progress dialog.++The active tab is path-backed at `/customer_analytics/accounts/:accountId/:tab`.+The bare path, unknown tabs, and tabs hidden by feature flags render Notes.+User tab changes preserve URL search and hash state and capture `TabViewed`; URL restoration does not capture that event.++When `CUSTOMER_ANALYTICS_ACCOUNT_SCENE` is off, the scene renders `CustomerAnalyticsScene` and preserves the filtered, expanded-row fallback.`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.+`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`: the Useful links and active-relationships sidebar plus the shared `AccountDetailTabs` 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). `AccountNotesExpansion` owns the shared Notes body. 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.-**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 })`, `accountConversationsLogic({ 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 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 flag-gated Feature requests tab loads when opened instead of mounting its logic while the flag is off.+**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `AccountDetailTabs` 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` — `accountNotebooksLogic({ accountId })`, `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountConversationsLogic({ 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 so both resolve to the same keyed instance. `accountLinksLogic` mounts through the always-rendered sidebar. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live. The flag-gated Feature requests tab loads when opened instead of mounting its logic while the flag is off.The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. Staff also see an "Impersonate" action that opens the user's Django admin detail page in the member's US or EU cloud. Outside PostHog Cloud, the action stays on the current origin so local and self-hosted users can test their own admin. 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.)diff --git a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsxindex fb99f4a84452..3ae36cc7de1b 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx@@ -37,10 +37,12 @@ export function AccountBillingExpansion({accountId,externalId,kind,+ embedded = true,}: {accountId: stringexternalId: stringkind: AccountBillingKind+ embedded?: boolean}): JSX.Element {const logic = accountBillingLogic({ accountId, externalId, kind })const { savedInsights, savedInsightsLoading, dateRange, variableOverridesByShortId, queryKeyFor } = useValues(logic)@@ -91,7 +93,7 @@ export function AccountBillingExpansion({query={insight.query}variablesOverride={variablesOverride}readOnly- embedded+ embedded={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}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsxindex adf75cddbf2e..84ae6003f6d4 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx@@ -443,7 +443,13 @@ function conversationPreview(conversation: AccountConversation): string {.trim()}-export function AccountConversationsExpansion({ accountId }: { accountId: string }): JSX.Element {+export function AccountConversationsExpansion({+ accountId,+ embedded = true,+}: {+ accountId: string+ embedded?: boolean+}): JSX.Element {const logic = accountConversationsLogic({ accountId })const emailLogic = accountEmailThreadsLogic({ accountId })const {@@ -625,7 +631,7 @@ export function AccountConversationsExpansion({ accountId }: { accountId: string<LemonTable<AccountConversation>data-attr="account-conversations-table"size="small"- embedded+ embedded={embedded}dataSource={filteredConversations}columns={columns}rowKey="id"diff --git a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsxnew file mode 100644index 000000000000..2b8bc475ad66--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx@@ -0,0 +1,115 @@+import { useValues } from 'kea'+import type { ReactNode } from 'react'++import { LemonTabs } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { AccountEventStreamToggle } from '../EventStream/AccountEventStreamToggle'+import { AccountBillingExpansion } from './AccountBillingExpansion'+import { AccountConversationsExpansion } from './AccountConversationsExpansion'+import { AccountFeatureRequestsExpansion } from './AccountFeatureRequestsExpansion'+import { AccountMeetingsExpansion } from './AccountMeetingsExpansion'+import { AccountNotesExpansion } from './AccountNotesExpansion'+import { AccountOpportunitiesExpansion } from './AccountOpportunitiesExpansion'+import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'+import { AccountRelationshipsExpansion } from './AccountRelationshipsExpansion'+import { AccountExpansionTab, getVisibleAccountExpansionTab } from './accountsExpansionLogic'++interface AccountDetailTabsProps {+ accountId: string+ externalId: string+ activeTab: AccountExpansionTab+ onChange: (tab: AccountExpansionTab) => void+ rightSlot?: ReactNode+ embedded?: boolean+}++export function AccountDetailTabs({+ accountId,+ externalId,+ activeTab,+ onChange,+ rightSlot,+ embedded = true,+}: AccountDetailTabsProps): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const visibleActiveTab = getVisibleAccountExpansionTab(activeTab, featureFlags)++ return (+ <LemonTabs+ activeKey={visibleActiveTab}+ onChange={onChange}+ size="small"+ rightSlot={rightSlot}+ tabs={[+ {+ key: 'notes',+ label: 'Notes',+ content: <AccountNotesExpansion accountId={accountId} embedded={embedded} />,+ },+ {+ key: 'users',+ label: 'Users',+ content: <AccountRelatedUsersExpansion externalId={externalId} embedded={embedded} />,+ },+ {+ key: 'relationships',+ label: 'Relationships',+ content: <AccountRelationshipsExpansion accountId={accountId} embedded={embedded} />,+ },+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS] && {+ key: 'feature_requests' as const,+ label: 'Feature requests',+ content: <AccountFeatureRequestsExpansion accountId={accountId} embedded={embedded} />,+ },+ {+ key: 'usage',+ label: 'Usage',+ content: (+ <AccountBillingExpansion+ accountId={accountId}+ externalId={externalId}+ kind="usage"+ embedded={embedded}+ />+ ),+ },+ {+ key: 'spend',+ label: 'Spend',+ content: (+ <AccountBillingExpansion+ accountId={accountId}+ externalId={externalId}+ kind="spend"+ embedded={embedded}+ />+ ),+ },+ {+ key: 'opportunities',+ label: 'Opportunities',+ content: <AccountOpportunitiesExpansion accountId={accountId} embedded={embedded} />,+ },+ {+ key: 'conversations',+ label: 'Conversations',+ content: <AccountConversationsExpansion accountId={accountId} embedded={embedded} />,+ },+ // Flag-gated here (not just inside the component) so the tab label hides too.+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {+ key: 'meetings' as const,+ label: 'Meetings',+ content: <AccountMeetingsExpansion accountId={accountId} embedded={embedded} />,+ },+ !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {+ key: 'event_stream' as const,+ label: 'Event stream',+ content: <AccountEventStreamToggle accountId={accountId} externalId={externalId} />,+ },+ ]}+ />+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsxindex ee8b6d859017..221956d5243b 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx@@ -21,7 +21,13 @@ import type { FeatureRequestApi } from '../../generated/api.schemas'import { getFeatureRequestDetailUrl } from '../FeatureRequests/featureRequestNavigation'import { ACCOUNT_FEATURE_REQUESTS_PAGE_SIZE, accountFeatureRequestsLogic } from './accountFeatureRequestsLogic'-export function AccountFeatureRequestsExpansion({ accountId }: { accountId: string }): JSX.Element {+export function AccountFeatureRequestsExpansion({+ accountId,+ embedded = true,+}: {+ accountId: string+ embedded?: boolean+}): JSX.Element {const logic = accountFeatureRequestsLogic({ accountId })const {accountRequests,@@ -124,7 +130,7 @@ export function AccountFeatureRequestsExpansion({ accountId }: { accountId: stri)}<LemonTablesize="small"- embedded+ embedded={embedded}dataSource={accountRequests.results}columns={columns}rowKey="id"diff --git a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsxindex 01fb4abbd067..b1f90af06527 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx@@ -160,7 +160,13 @@ const STATUS_TAG_TYPE = {cancelled: 'danger',} as const-export function AccountMeetingsExpansion({ accountId }: { accountId: string }): JSX.Element {+export function AccountMeetingsExpansion({+ accountId,+ embedded = true,+}: {+ accountId: string+ embedded?: boolean+}): JSX.Element {const logic = accountMeetingsLogic({ accountId })const { canEditMeetingMatching, meetingsResult, meetingsResultLoading, searchTerm, page, matchingEditorOpen } =useValues(logic)@@ -244,7 +250,7 @@ export function AccountMeetingsExpansion({ accountId }: { accountId: string }):content = (<LemonTable<MeetingApi>size="small"- embedded+ embedded={embedded}dataSource={meetings ?? []}columns={columns}rowKey="id"diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex 849f00e847a7..b88b9dd92064 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -8,67 +8,31 @@ import {IconDatabase,IconGlobe,IconGraph,- IconPencil,IconPeople,IconPiggyBank,IconReceipt,} from '@posthog/icons'-import {- LemonButton,- LemonInput,- LemonLabel,- LemonSkeleton,- LemonTable,- LemonTableColumns,- LemonTabs,- Link,- ProfilePicture,-} from '@posthog/lemon-ui'+import { LemonButton, LemonLabel, LemonSkeleton, ProfilePicture } from '@posthog/lemon-ui'-import { TZLabel } from 'lib/components/TZLabel'-import { FEATURE_FLAGS } from 'lib/constants'import { IconSlack } from 'lib/lemon-ui/icons'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'-import { fullName } from 'lib/utils/strings'-import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'import { urls } from 'scenes/urls'-import type { AccountNotebookApi } from 'products/customer_analytics/frontend/generated/api.schemas'--import { AccountEventStreamToggle } from '../EventStream/AccountEventStreamToggle'-import { AccountBillingExpansion } from './AccountBillingExpansion'import { accountBillingLogic } from './accountBillingLogic'-import { AccountConversationsExpansion } from './AccountConversationsExpansion'import { accountConversationsLogic } from './accountConversationsLogic'+import { AccountDetailTabs } from './AccountDetailTabs'import { accountEmailThreadsLogic } from './accountEmailThreadsLogic'-import { AccountFeatureRequestsExpansion } from './AccountFeatureRequestsExpansion'import { accountLinksLogic } from './accountLinksLogic'-import { AccountMeetingsExpansion } from './AccountMeetingsExpansion'import { accountMeetingsLogic } from './accountMeetingsLogic'import { accountNotebooksLogic } from './accountNotebooksLogic'-import { AccountOpportunitiesExpansion } from './AccountOpportunitiesExpansion'import { accountOpportunitiesLogic } from './accountOpportunitiesLogic'-import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'import { accountRelatedUsersLogic } from './accountRelatedUsersLogic'-import { AccountRelationshipsExpansion } from './AccountRelationshipsExpansion'import { accountRelationshipsLogic } from './accountRelationshipsLogic'import { accountsExpansionLogic } from './accountsExpansionLogic'import { accountSummariesLogic } from './accountSummariesLogic'import { AccountsEvents } from './constants'import { EditAccountLinksButton } from './EditAccountLinksButton'-const PREVIEW_MAX_CHARS = 200--function getPreview(notebook: AccountNotebookApi): string {- const text = (notebook.text_content ?? '').trim()- if (!text) {- return ''- }- const collapsed = text.replace(/\s+/g, ' ')- return collapsed.length > PREVIEW_MAX_CHARS ? `${collapsed.slice(0, PREVIEW_MAX_CHARS).trimEnd()}…` : collapsed-}-const LINK_ICONS: Record<string, JSX.Element> = {website: <IconGlobe />,organization: <IconPeople />,@@ -173,11 +137,8 @@ export function AccountNotebooksExpansion({accountId: stringexternalId: string}): JSX.Element {- const logic = accountNotebooksLogic({ accountId })- const { notebooks, notebooksResponseLoading, createdNoteLoading, searchTerm, sorting, pagination } =- useValues(logic)-- // LemonTabs only renders the active tab, so without this the data refetches on every tab switch.+ // AccountDetailTabs only renders the active tab, so these mounts keep expanded-row data cached between tab switches.+ useMountedLogic(accountNotebooksLogic({ accountId }))useMountedLogic(accountRelatedUsersLogic({ externalId }))useMountedLogic(accountRelationshipsLogic({ accountId }))useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'usage' }))@@ -187,74 +148,10 @@ export function AccountNotebooksExpansion({useMountedLogic(accountConversationsLogic({ accountId }))useMountedLogic(accountEmailThreadsLogic({ accountId }))useMountedLogic(accountMeetingsLogic({ accountId }))- const { setSearchTerm, setSorting, createNote } = useActions(logic)- const { featureFlags } = useValues(featureFlagLogic)const { activeTabFor } = useValues(accountsExpansionLogic)const { setActiveTab } = useActions(accountsExpansionLogic)- const { selectNotebook } = useActions(notebookPanelLogic)const activeTab = activeTabFor(accountId)- const columns: LemonTableColumns<AccountNotebookApi> = [- {- title: 'Note',- key: 'title',- render: (_, notebook) => {- const preview = getPreview(notebook)- return (- <div className="flex flex-col gap-1 py-1 max-w-2xl">- <Link- to={urls.notebook(notebook.short_id)}- className="font-medium"- onClick={(event) => {- posthog.capture(AccountsEvents.NoteClicked, {- notebook_short_id: notebook.short_id,- })- event.preventDefault()- selectNotebook(notebook.short_id)- }}- >- {notebook.title || 'Untitled note'}- </Link>- {preview ? (- <span className="text-xs text-muted line-clamp-2">{preview}</span>- ) : (- <span className="text-xs text-muted italic">No content yet</span>- )}- </div>- )- },- },- {- title: 'Created by',- key: 'created_by',- width: 160,- sorter: true,- render: (_, notebook) => {- const user = notebook.created_by- if (!user) {- return <span className="text-muted italic">Unknown</span>- }- const name = fullName(user) || user.email- return (- <div className="flex items-center gap-2">- <ProfilePicture- user={{ email: user.email, first_name: user.first_name, last_name: user.last_name }}- size="sm"- />- <span className="text-sm">{name}</span>- </div>- )- },- },- {- title: 'Created at',- key: 'created_at',- width: 140,- sorter: true,- render: (_, notebook) => <TZLabel time={notebook.created_at} />,- },- ]-return (<divclassName="sticky left-0 w-[100cqw] max-w-full overflow-x-hidden p-3 bg-bg-light"@@ -266,115 +163,11 @@ export function AccountNotebooksExpansion({<ActiveRelationships accountId={accountId} /></div><div className="flex-1 min-w-0">- <LemonTabs- activeKey={activeTab}+ <AccountDetailTabs+ accountId={accountId}+ externalId={externalId}+ activeTab={activeTab}onChange={(tab) => setActiveTab(accountId, tab)}- size="small"- tabs={[- {- key: 'notes',- label: 'Notes',- content: (- <div className="flex flex-col gap-2">- <div className="flex flex-wrap items-center justify-between gap-2">- <LemonInput- type="search"- placeholder="Search notes by title or content..."- value={searchTerm}- onChange={setSearchTerm}- size="small"- className="min-w-64"- />- <LemonButton- type="primary"- size="small"- icon={<IconPencil />}- onClick={createNote}- loading={createdNoteLoading}- >- New note- </LemonButton>- </div>- <LemonTable<AccountNotebookApi>- size="small"- embedded- dataSource={notebooks ?? []}- rowKey="short_id"- loading={notebooksResponseLoading}- columns={columns}- sorting={sorting}- onSort={setSorting}- pagination={pagination}- emptyState={- notebooks === null- ? 'Failed to load account notes.'- : searchTerm- ? 'No notes match your search.'- : 'No notes linked to this account yet.'- }- />- </div>- ),- },- {- key: 'users',- label: 'Users',- content: <AccountRelatedUsersExpansion externalId={externalId} />,- },- {- key: 'relationships',- label: 'Relationships',- content: <AccountRelationshipsExpansion accountId={accountId} />,- },- !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS] && {- key: 'feature_requests' as const,- label: 'Feature requests',- content: <AccountFeatureRequestsExpansion accountId={accountId} />,- },- {- key: 'usage',- label: 'Usage',- content: (- <AccountBillingExpansion- accountId={accountId}- externalId={externalId}- kind="usage"- />- ),- },- {- key: 'spend',- label: 'Spend',- content: (- <AccountBillingExpansion- accountId={accountId}- externalId={externalId}- kind="spend"- />- ),- },- {- key: 'opportunities',- label: 'Opportunities',- content: <AccountOpportunitiesExpansion accountId={accountId} />,- },- {- key: 'conversations',- label: 'Conversations',- content: <AccountConversationsExpansion accountId={accountId} />,- },- // Flag-gated here (not just inside the component) so the tab label hides too.- !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {- key: 'meetings' as const,- label: 'Meetings',- content: <AccountMeetingsExpansion accountId={accountId} />,- },- !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP] && {- key: 'event_stream' as const,- label: 'Event stream',- content: <AccountEventStreamToggle accountId={accountId} externalId={externalId} />,- },- ]}/></div></div>diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotesExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotesExpansion.tsxnew file mode 100644index 000000000000..3b6c041d168e--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotesExpansion.tsx@@ -0,0 +1,143 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'++import { IconPencil } from '@posthog/icons'+import { LemonButton, LemonInput, LemonTable, LemonTableColumns, Link, ProfilePicture } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { fullName } from 'lib/utils/strings'+import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'+import { urls } from 'scenes/urls'++import type { AccountNotebookApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountNotebooksLogic } from './accountNotebooksLogic'+import { AccountsEvents } from './constants'++const PREVIEW_MAX_CHARS = 200++function getPreview(notebook: AccountNotebookApi): string {+ const text = (notebook.text_content ?? '').trim()+ if (!text) {+ return ''+ }+ const collapsed = text.replace(/\s+/g, ' ')+ return collapsed.length > PREVIEW_MAX_CHARS ? `${collapsed.slice(0, PREVIEW_MAX_CHARS).trimEnd()}…` : collapsed+}++export function AccountNotesExpansion({+ accountId,+ embedded = true,+}: {+ accountId: string+ embedded?: boolean+}): JSX.Element {+ const logic = accountNotebooksLogic({ accountId })+ const { notebooks, notebooksResponseLoading, createdNoteLoading, searchTerm, sorting, pagination } =+ useValues(logic)+ const { setSearchTerm, setSorting, createNote } = useActions(logic)+ const { selectNotebook } = useActions(notebookPanelLogic)++ const columns: LemonTableColumns<AccountNotebookApi> = [+ {+ title: 'Note',+ key: 'title',+ render: (_, notebook) => {+ const preview = getPreview(notebook)+ return (+ <div className="flex flex-col gap-1 py-1 max-w-2xl">+ <Link+ to={urls.notebook(notebook.short_id)}+ className="font-medium"+ onClick={(event) => {+ posthog.capture(AccountsEvents.NoteClicked, {+ notebook_short_id: notebook.short_id,+ })+ event.preventDefault()+ selectNotebook(notebook.short_id)+ }}+ >+ {notebook.title || 'Untitled note'}+ </Link>+ {preview ? (+ <span className="text-xs text-muted line-clamp-2">{preview}</span>+ ) : (+ <span className="text-xs text-muted italic">No content yet</span>+ )}+ </div>+ )+ },+ },+ {+ title: 'Created by',+ key: 'created_by',+ width: 160,+ sorter: true,+ render: (_, notebook) => {+ const user = notebook.created_by+ if (!user) {+ return <span className="text-muted italic">Unknown</span>+ }+ const name = fullName(user) || user.email+ return (+ <div className="flex items-center gap-2">+ <ProfilePicture+ user={{ email: user.email, first_name: user.first_name, last_name: user.last_name }}+ size="sm"+ />+ <span className="text-sm">{name}</span>+ </div>+ )+ },+ },+ {+ title: 'Created at',+ key: 'created_at',+ width: 140,+ sorter: true,+ render: (_, notebook) => <TZLabel time={notebook.created_at} />,+ },+ ]++ return (+ <div className="flex flex-col gap-2" data-attr="account-notes">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <LemonInput+ type="search"+ placeholder="Search notes by title or content..."+ value={searchTerm}+ onChange={setSearchTerm}+ size="small"+ className="min-w-64"+ />+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPencil />}+ onClick={createNote}+ loading={createdNoteLoading}+ >+ New note+ </LemonButton>+ </div>+ <LemonTable<AccountNotebookApi>+ size="small"+ embedded={embedded}+ dataSource={notebooks ?? []}+ rowKey="short_id"+ loading={notebooksResponseLoading}+ columns={columns}+ sorting={sorting}+ onSort={setSorting}+ pagination={pagination}+ emptyState={+ notebooks === null+ ? 'Failed to load account notes.'+ : searchTerm+ ? 'No notes match your search.'+ : 'No notes linked to this account yet.'+ }+ />+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsxindex feebf695f02b..9a0b577b4762 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx@@ -73,7 +73,13 @@ const columns: LemonTableColumns<AccountOpportunity> = [},]-export function AccountOpportunitiesExpansion({ accountId }: { accountId: string }): JSX.Element {+export function AccountOpportunitiesExpansion({+ accountId,+ embedded = true,+}: {+ accountId: string+ embedded?: boolean+}): JSX.Element {const { opportunitiesResult, opportunitiesResultLoading } = useValues(accountOpportunitiesLogic({ accountId }))if (opportunitiesResultLoading || opportunitiesResult === NOT_LOADED) {@@ -112,7 +118,7 @@ export function AccountOpportunitiesExpansion({ accountId }: { accountId: stringreturn (<LemonTable<AccountOpportunity>size="small"- embedded+ embedded={embedded}dataSource={opportunities}columns={columns}rowKey="id"diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsxindex cc413181c245..61500ea1a7a0 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx@@ -13,7 +13,13 @@ import { getAccountRelatedUserAdminUrl } from './accountRelatedUserAdminUrl'import { accountRelatedUsersLogic, AccountOrganizationMember, PAGE_SIZE } from './accountRelatedUsersLogic'import { AccountsEvents } from './constants'-export function AccountRelatedUsersExpansion({ externalId }: { externalId: string }): JSX.Element {+export function AccountRelatedUsersExpansion({+ externalId,+ embedded = true,+}: {+ externalId: string+ embedded?: boolean+}): JSX.Element {const logic = accountRelatedUsersLogic({ externalId })const { membersResponse, membersResponseLoading, page, searchTerm } = useValues(logic)const { user } = useValues(userLogic)@@ -96,7 +102,7 @@ export function AccountRelatedUsersExpansion({ externalId }: { externalId: strin/><LemonTable<AccountOrganizationMember>size="small"- embedded+ embedded={embedded}dataSource={membersResponse?.results ?? []}rowKey="id"loading={membersResponseLoading}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsxindex 04c664c542a8..83d0a77420c3 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx@@ -20,7 +20,13 @@ import { accountRelationshipsLogic } from './accountRelationshipsLogic'const PAGE_SIZE = 10-export function AccountRelationshipsExpansion({ accountId }: { accountId: string }): JSX.Element {+export function AccountRelationshipsExpansion({+ accountId,+ embedded = true,+}: {+ accountId: string+ embedded?: boolean+}): JSX.Element {const {relationships,relationshipsLoading,@@ -169,7 +175,7 @@ export function AccountRelationshipsExpansion({ accountId }: { accountId: string</div><LemonTable<AccountRelationshipApi>size="small"- embedded+ embedded={embedded}dataSource={displayedRelationships}rowKey="id"loading={relationshipsLoading}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex dfcfb0456a5e..fbcf179aff47 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -1,6 +1,9 @@import { MakeLogicType, actions, kea, listeners, path, reducers, selectors } from 'kea'import posthog from 'posthog-js'+import { FEATURE_FLAGS } from 'lib/constants'+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { AccountsEvents } from './constants'export type AccountExpansionTab =@@ -30,6 +33,22 @@ export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = [export const DEFAULT_ACCOUNT_TAB: AccountExpansionTab = 'notes'+export function getVisibleAccountExpansionTab(+ tab: string | undefined,+ featureFlags: FeatureFlagsSet+): AccountExpansionTab {+ if (!ACCOUNT_EXPANSION_TABS.includes(tab as AccountExpansionTab)) {+ return DEFAULT_ACCOUNT_TAB+ }+ if (tab === 'feature_requests' && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS]) {+ return DEFAULT_ACCOUNT_TAB+ }+ if ((tab === 'meetings' || tab === 'event_stream') && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {+ return DEFAULT_ACCOUNT_TAB+ }+ return tab as AccountExpansionTab+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountsExpansionLogicValues {activeTabByAccount: Record<string, AccountExpansionTab>diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsxnew file mode 100644index 000000000000..52fcd9557c09--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx@@ -0,0 +1,25 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { LemonDialog } from 'lib/lemon-ui/LemonDialog'++import { AccountDetailActions } from './AccountDetailActions'++jest.mock('lib/lemon-ui/LemonDialog', () => ({ LemonDialog: { open: jest.fn() } }))++describe('AccountDetailActions', () => {+ beforeEach(jest.clearAllMocks)+ afterEach(cleanup)++ it.each(['Configure tabs', 'Add view'])('opens a work-in-progress dialog for %s', (title) => {+ render(<AccountDetailActions />)++ fireEvent.click(screen.getByText(title))++ expect(LemonDialog.open).toHaveBeenCalledWith({+ title,+ content: 'This feature is a work in progress.',+ })+ })+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsxnew file mode 100644index 000000000000..c6012d1ba618--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx@@ -0,0 +1,29 @@+import { IconGear, IconPlus } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { openAccountDetailWorkInProgress } from './accountDetailWorkInProgress'++export function AccountDetailActions(): JSX.Element {+ return (+ <>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconGear />}+ data-attr="account-detail-configure-tabs"+ onClick={() => openAccountDetailWorkInProgress('Configure tabs')}+ >+ Configure tabs+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlus />}+ data-attr="account-detail-add-view"+ onClick={() => openAccountDetailWorkInProgress('Add view')}+ >+ Add view+ </LemonButton>+ </>+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsxnew file mode 100644index 000000000000..e47b901c0165--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx@@ -0,0 +1,52 @@+import { useActions, useValues } from 'kea'++import { IconGear } from '@posthog/icons'+import { LemonButton, LemonDivider } from '@posthog/lemon-ui'++import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'++import { tagsModel } from '~/models/tagsModel'++import type { AccountApi } from '../../generated/api.schemas'+import { openAccountDetailWorkInProgress } from './accountDetailWorkInProgress'+import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'++export function AccountSidebar({ account }: { account: AccountApi }): JSX.Element {+ const { tagsSaving } = useValues(customerAnalyticsAccountSceneLogic)+ const { updateTags } = useActions(customerAnalyticsAccountSceneLogic)+ const { tags: tagsAvailable } = useValues(tagsModel)++ return (+ <aside+ className="w-full shrink-0 @max-[60rem]:border @max-[60rem]:rounded border-r rounded-r bg-surface-primary flex flex-col @min-[60rem]/account-detail:w-60"+ data-attr="account-sidebar"+ >+ <div className="flex flex-col gap-1 p-4" data-attr="account-rail-tags">+ <span className="secondary text-secondary">Tags</span>+ <ObjectTags+ tags={account.tags ?? []}+ onChange={updateTags}+ saving={tagsSaving}+ tagsAvailable={tagsAvailable}+ wrap+ />+ </div>+ <LemonDivider className="my-0" />+ <div className="flex flex-col gap-3 p-4" data-attr="account-rail-properties">+ <div className="flex items-center gap-2">+ <span className="secondary text-secondary">Properties</span>+ <LemonButton+ size="xsmall"+ icon={<IconGear />}+ className="ml-auto"+ tooltip="Configure properties"+ aria-label="Configure properties"+ onClick={() => openAccountDetailWorkInProgress('Configure properties')}+ data-attr="account-detail-configure-properties"+ />+ </div>+ <span className="text-xs text-muted">No properties pinned.</span>+ </div>+ </aside>+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsxnew file mode 100644index 000000000000..a7b932375ce2--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx@@ -0,0 +1,107 @@+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++const ACCOUNT_ID = '11111111-2222-4333-8444-555555555555'+const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'+const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'+const ACCOUNT_ICON_ENDPOINT = 'api/projects/:team_id/accounts/icon/'++const account = {+ id: ACCOUNT_ID,+ name: 'Example Labs',+ external_id: 'example_labs_42',+ properties: {+ website_domain: 'example.com',+ email_domains: ['example.com'],+ known_emails: [],+ },+ tags: ['enterprise', 'onboarding'],+ notebooks: ['note1234'],+ slack_summary_cadence: null,+ churned_at: null,+ ignored_at: null,+ created_at: '2026-05-10T10:00:00Z',+ created_by: null,+ updated_at: '2026-05-20T14:30:00Z',+}++const notebooks = {+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee',+ short_id: 'note1234',+ title: 'Implementation planning',+ content: null,+ text_content: 'The team plans to finish its data import and review the first dashboard next week.',+ created_at: '2026-05-18T09:15:00Z',+ created_by: {+ id: 7,+ uuid: '99999999-8888-4777-8666-555555555555',+ email: '[email protected]',+ first_name: 'Alex',+ last_name: 'River',+ is_email_verified: true,+ },+ last_modified_at: '2026-05-18T09:15:00Z',+ last_modified_by: null,+ },+ ],+}++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Customer Analytics/Account detail',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-05-21',+ featureFlags: [+ FEATURE_FLAGS.CUSTOMER_ANALYTICS,+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE,+ ],+ pageUrl: urls.customerAnalyticsAccount(ACCOUNT_ID),+ testOptions: {+ waitForSelector: ['[data-attr="customer-analytics-account-scene"]', '[data-attr="account-notes"]'],+ viewport: { width: 1280, height: 900 },+ },+ },+ decorators: [+ mswDecorator({+ get: {+ [ACCOUNT_RETRIEVE_ENDPOINT]: account,+ [ACCOUNT_NOTEBOOKS_ENDPOINT]: notebooks,+ [ACCOUNT_ICON_ENDPOINT]: () =>+ new Response(+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#8f68d4"/></svg>',+ { headers: { 'Content-Type': 'image/svg+xml' } }+ ),+ },+ }),+ ],+}+export default meta++type Story = StoryObj<{}>++export const Default: Story = {+ render: () => <App />,+}++export const Narrow: Story = {+ render: () => <App />,+ parameters: {+ testOptions: {+ waitForSelector: '[data-attr="customer-analytics-account-scene"]',+ viewport: { width: 800, height: 900 },+ },+ },+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsxindex f75aeb9fd181..35d8208521fe 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx@@ -1,21 +1,25 @@import { useActions, useValues } from 'kea'-import { LemonBanner, LemonCard, LemonSkeleton } from '@posthog/lemon-ui'+import { LemonBanner, 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 { SceneDivider } from '~/layout/scenes/components/SceneDivider'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'+import { AccountDetailTabs } from '../../components/Accounts/AccountDetailTabs'+import { AccountLogo } from '../../components/Accounts/AccountLogo'import { CustomerAnalyticsScene } from '../../CustomerAnalyticsScene'import { customerAnalyticsFeaturePreviewGate } from '../../featurePreviewGate'+import type { AccountApi } from '../../generated/api.schemas'+import { AccountDetailActions } from './AccountDetailActions'+import { AccountSidebar } from './AccountSidebar'import {CustomerAnalyticsAccountSceneLogicProps,customerAnalyticsAccountSceneLogic,@@ -28,6 +32,10 @@ export const scene: SceneExport<CustomerAnalyticsAccountSceneLogicProps> = {paramsToProps: ({ params: { accountId } }) => ({ accountId: accountId ?? '' }),}+function getAccountLogoDomain(account: AccountApi): string | null {+ return account.properties?.website_domain ?? account.properties?.email_domains?.[0] ?? null+}+export function CustomerAnalyticsAccountScene(): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)@@ -47,12 +55,10 @@ export function CustomerAnalyticsAccountScene(): JSX.Element {}function CustomerAnalyticsAccountSceneContent(): JSX.Element {- const { account, accountLoadError, accountLoading, isAccountMissing } = useValues(+ const { account, accountLoadError, accountLoading, activeTab, isAccountMissing } = useValues(customerAnalyticsAccountSceneLogic)- const { loadAccount } = useActions(customerAnalyticsAccountSceneLogic)-- useOnMountEffect(loadAccount)+ const { loadAccount, setActiveTab } = useActions(customerAnalyticsAccountSceneLogic)if (isAccountMissing) {return <NotFound object="account" />@@ -60,7 +66,7 @@ function CustomerAnalyticsAccountSceneContent(): JSX.Element {if (!account && accountLoadError) {return (- <SceneContent>+ <SceneContent className="h-full"><LemonBannertype="error"action={{ children: 'Try again', onClick: loadAccount, loading: accountLoading }}@@ -73,28 +79,40 @@ function CustomerAnalyticsAccountSceneContent(): JSX.Element {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" />+ <SceneContent className="h-full">+ <div className="flex flex-1 min-h-0 gap-4">+ <LemonSkeleton className="h-full w-56" />+ <LemonSkeleton className="h-32 flex-1" /></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 className="h-full min-h-0" data-attr="customer-analytics-account-scene">+ <SceneTitleSection+ name={account.name}+ resourceType={{+ type: 'cohort',+ forceIcon: <AccountLogo domain={getAccountLogoDomain(account)} name={account.name} />,+ }}+ actions={<AccountDetailActions />}+ />+ <SceneDivider />+ <div className="@container/account-detail flex flex-1 min-h-0 overflow-y-auto @min-[60rem]:-mt-4 @min-[60rem]:-ml-4">+ <div className="flex min-h-full w-full flex-col gap-4 @min-[60rem]/account-detail:flex-row">+ <AccountSidebar account={account} />+ <main className="flex-1 min-w-0" data-attr="account-detail-tabs">+ <AccountDetailTabs+ accountId={account.id}+ externalId={account.external_id ?? ''}+ activeTab={activeTab}+ onChange={setActiveTab}+ embedded={false}+ />+ </main>+ </div>+ </div></SceneContent>)}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountDetailWorkInProgress.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountDetailWorkInProgress.tsnew file mode 100644index 000000000000..8767895dfd4d--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountDetailWorkInProgress.ts@@ -0,0 +1,8 @@+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'++export function openAccountDetailWorkInProgress(title: string): void {+ LemonDialog.open({+ title,+ content: 'This feature is a work in progress.',+ })+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.tsindex 951c6cb938f0..7838be37b75a 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts@@ -1,20 +1,27 @@+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import { ApiError } from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'-import { accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'+import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'+import { accountsPartialUpdate, 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'),+ accountsPartialUpdate: jest.fn(),accountsRetrieve: jest.fn(),}))+const mockAccountsPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>const mockAccountsRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'@@ -30,24 +37,50 @@ const account: AccountApi = {updated_at: null,}+interface Deferred<T> {+ promise: Promise<T>+ resolve: (value: T) => void+ reject: (reason: unknown) => void+}++function createDeferred<T>(): Deferred<T> {+ let resolve!: (value: T) => void+ let reject!: (reason: unknown) => void+ const promise = new Promise<T>((promiseResolve, promiseReject) => {+ resolve = promiseResolve+ reject = promiseReject+ })+ return { promise, resolve, reject }+}+describe('customerAnalyticsAccountSceneLogic', () => {let logic: ReturnType<typeof customerAnalyticsAccountSceneLogic.build>beforeEach(() => {initKeaTests()jest.resetAllMocks()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS]: true,+ })+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))+ })++ function mountLogic(): void {logic = customerAnalyticsAccountSceneLogic({ accountId: ACCOUNT_ID })logic.mount()- })+ }afterEach(() => {logic.unmount()+ featureFlagLogic.unmount()})- it('loads the account and uses its name in the breadcrumb', async () => {+ it('loads the account on mount and uses its name in the breadcrumb', async () => {mockAccountsRetrieve.mockResolvedValue(account)- logic.actions.loadAccount()+ mountLogic()await expectLogic(logic).toFinishAllListeners()expect(logic.values.account).toEqual(account)@@ -59,7 +92,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {const captureException = jest.spyOn(posthog, 'captureException')mockAccountsRetrieve.mockRejectedValue(new ApiError('Not found', 404))- logic.actions.loadAccount()+ mountLogic()await expectLogic(logic).toFinishAllListeners()expect(logic.values.isAccountMissing).toBe(true)@@ -71,7 +104,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {const captureException = jest.spyOn(posthog, 'captureException')mockAccountsRetrieve.mockRejectedValue(failure)- logic.actions.loadAccount()+ mountLogic()await expectLogic(logic).toFinishAllListeners()expect(logic.values.isAccountMissing).toBe(false)@@ -84,7 +117,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {it('clears a previous error when retrying', async () => {mockAccountsRetrieve.mockRejectedValueOnce(new ApiError('Server error', 500))- logic.actions.loadAccount()+ mountLogic()await expectLogic(logic).toFinishAllListeners()expect(logic.values.accountLoadError).toBeInstanceOf(ApiError)@@ -102,4 +135,142 @@ describe('customerAnalyticsAccountSceneLogic', () => {await expectLogic(logic).toFinishAllListeners()expect(logic.values.account).toEqual(account)})++ describe('tag updates', () => {+ beforeEach(async () => {+ mockAccountsRetrieve.mockResolvedValue(account)+ mountLogic()+ await expectLogic(logic).toFinishAllListeners()+ mockAccountsRetrieve.mockClear()+ })++ it('saves tags and keeps the optimistic value', async () => {+ const updatedAccount = { ...account, tags: ['priority'] }+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()+ mockAccountsPartialUpdate.mockResolvedValue(updatedAccount)++ logic.actions.updateTags(['priority'])++ expect(logic.values.account?.tags).toEqual(['priority'])+ expect(logic.values.tagsSaving).toBe(true)+ await expectLogic(logic).toFinishAllListeners()+ expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(logic.values.currentTeamId), ACCOUNT_ID, {+ tags: ['priority'],+ })+ expect(logic.values.account).toEqual(updatedAccount)+ expect(logic.values.tagsSaving).toBe(false)+ expect(capture).toHaveBeenCalledWith(AccountsEvents.TagsUpdated, { tag_count: 1 })+ })++ it('restores the account when saving tags fails', async () => {+ const failure = new ApiError('Server error', 500)+ mockAccountsPartialUpdate.mockRejectedValue(failure)+ mockAccountsRetrieve.mockResolvedValue(account)++ logic.actions.updateTags(['priority'])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.account).toEqual(account)+ expect(logic.values.tagsSaving).toBe(false)+ expect(mockAccountsRetrieve).toHaveBeenCalled()+ })++ it.each(['success', 'failure'] as const)(+ 'keeps the latest tags when an earlier save ends with %s',+ async (staleResult) => {+ const staleRequest = createDeferred<AccountApi>()+ const latestRequest = createDeferred<AccountApi>()+ const staleRequestStarted = createDeferred<void>()+ const latestRequestStarted = createDeferred<void>()+ const latestAccount = { ...account, tags: ['latest'] }+ mockAccountsPartialUpdate+ .mockImplementationOnce(() => {+ staleRequestStarted.resolve()+ return staleRequest.promise+ })+ .mockImplementationOnce(() => {+ latestRequestStarted.resolve()+ return latestRequest.promise+ })++ logic.actions.updateTags(['stale'])+ await staleRequestStarted.promise+ logic.actions.updateTags(['latest'])+ await latestRequestStarted.promise++ latestRequest.resolve(latestAccount)+ if (staleResult === 'success') {+ staleRequest.resolve({ ...account, tags: ['stale'] })+ } else {+ staleRequest.reject(new ApiError('Server error', 500))+ }+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.account).toEqual(latestAccount)+ expect(logic.values.tagsSaving).toBe(false)+ expect(mockAccountsRetrieve).not.toHaveBeenCalled()+ }+ )+ })++ describe('tab routing', () => {+ beforeEach(async () => {+ mockAccountsRetrieve.mockResolvedValue(account)+ mountLogic()+ await expectLogic(logic).toFinishAllListeners()+ })++ it('selects Notes for the bare account URL', () => {+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID))++ expect(logic.values.activeTab).toBe('notes')+ })++ it.each(['users', 'usage', 'feature_requests'] as const)('selects the %s tab from the URL', (tab) => {+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, tab))++ expect(logic.values.activeTab).toBe(tab)+ })++ it('selects Notes for an unknown tab', () => {+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'unknown'))++ expect(logic.values.activeTab).toBe('notes')+ })++ it('selects Notes for a feature-flag-hidden tab', () => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,+ })+ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'feature_requests'))++ expect(logic.values.activeTab).toBe('notes')+ })++ it('preserves URL state and captures only user tab changes', () => {+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()+ const searchParams = { source: 'accounts' }+ const hashParams = { view: { search: 'example' } }++ router.actions.push(urls.customerAnalyticsAccount(ACCOUNT_ID, 'users'), searchParams, hashParams)++ expect(logic.values.activeTab).toBe('users')+ expect(capture).not.toHaveBeenCalledWith(AccountsEvents.TabViewed, expect.anything())++ logic.actions.setActiveTab('usage')++ expect(router.values.location.pathname).toBe(+ urls.currentProject(urls.customerAnalyticsAccount(ACCOUNT_ID, 'usage'))+ )+ expect(router.values.currentLocation.searchParams).toEqual(searchParams)+ expect(router.values.currentLocation.hashParams).toEqual(hashParams)+ expect(capture).toHaveBeenCalledWith(AccountsEvents.TabViewed, { tab: 'usage' })++ logic.actions.setActiveTab('notes')++ expect(router.values.location.pathname).toBe(urls.currentProject(urls.customerAnalyticsAccount(ACCOUNT_ID)))+ expect(router.values.currentLocation.searchParams).toEqual(searchParams)+ expect(router.values.currentLocation.hashParams).toEqual(hashParams)+ })+ })})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.tsindex e29d7be10853..f0f13fca8bb1 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts@@ -1,14 +1,37 @@-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import {+ MakeLogicType,+ actions,+ afterMount,+ connect,+ isBreakpoint,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import { actionToUrl, router, urlToAction } from 'kea-router'import posthog from 'posthog-js'import { ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { featureFlagLogic, FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { Scene } from 'scenes/sceneTypes'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { tagsModel } from '~/models/tagsModel'import { Breadcrumb } from '~/types'-import { accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'+import {+ AccountExpansionTab,+ DEFAULT_ACCOUNT_TAB,+ getVisibleAccountExpansionTab,+} from 'products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic'+import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'+import { accountsPartialUpdate, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'export interface CustomerAnalyticsAccountSceneLogicProps {@@ -21,12 +44,16 @@ function isAccountNotFound(error: unknown): boolean {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface customerAnalyticsAccountSceneLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogiccurrentTeamId: number | null // teamLogicaccount: AccountApi | nullaccountLoadError: unknownaccountLoading: boolean+ activeTab: AccountExpansionTabbreadcrumbs: Breadcrumb[]isAccountMissing: boolean+ requestedTab: string+ tagsSaving: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -40,12 +67,25 @@ export interface customerAnalyticsAccountSceneLogicActions {loadAccountSuccess: (account: AccountApi) => {account: AccountApi}+ restoreActiveTab: (tab: string | undefined) => {+ tab: string+ }+ setActiveTab: (tab: AccountExpansionTab) => {+ tab: AccountExpansionTab+ }+ updateTags: (tags: string[]) => {+ tags: string[]+ }+ updateTagsDone: (account: AccountApi | null) => {+ account: AccountApi | null+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface customerAnalyticsAccountSceneLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {+ activeTab: (requestedTab: string, featureFlags: FeatureFlagsSet) => AccountExpansionTabisAccountMissing: (account: AccountApi | null, accountLoading: boolean, accountLoadError: unknown) => booleanbreadcrumbs: (account: AccountApi | null) => Breadcrumb[]}@@ -71,18 +111,24 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountScprops({} as CustomerAnalyticsAccountSceneLogicProps),key((props) => props.accountId),connect(() => ({- values: [teamLogic, ['currentTeamId']],+ values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],})),actions({loadAccount: true,loadAccountSuccess: (account: AccountApi) => ({ account }),loadAccountFailure: (error: unknown) => ({ error }),+ setActiveTab: (tab: AccountExpansionTab) => ({ tab }),+ restoreActiveTab: (tab: string | undefined) => ({ tab: tab ?? DEFAULT_ACCOUNT_TAB }),+ updateTags: (tags: string[]) => ({ tags }),+ updateTagsDone: (account: AccountApi | null) => ({ account }),}),reducers({account: [null as AccountApi | null,{loadAccountSuccess: (_, { account }) => account,+ updateTags: (state, { tags }) => (state ? { ...state, tags } : state),+ updateTagsDone: (state, { account }) => account ?? state,},],accountLoading: [@@ -101,8 +147,27 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountScloadAccountFailure: (_, { error }) => error,},],+ requestedTab: [+ DEFAULT_ACCOUNT_TAB as string,+ {+ setActiveTab: (_, { tab }) => tab,+ restoreActiveTab: (_, { tab }) => tab,+ },+ ],+ tagsSaving: [+ false,+ {+ updateTags: () => true,+ updateTagsDone: () => false,+ },+ ],}),selectors({+ activeTab: [+ (s) => [s.requestedTab, s.featureFlags],+ (requestedTab: string, featureFlags: FeatureFlagsSet): AccountExpansionTab =>+ getVisibleAccountExpansionTab(requestedTab, featureFlags),+ ],isAccountMissing: [(s) => [s.account, s.accountLoading, s.accountLoadError],(account: AccountApi | null, accountLoading: boolean, accountLoadError: unknown): boolean =>@@ -141,5 +206,47 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountScscope: 'customerAnalyticsAccountSceneLogic.loadAccount',})},+ setActiveTab: ({ tab }) => {+ posthog.capture(AccountsEvents.TabViewed, { tab })+ },+ updateTags: async ({ tags }, breakpoint) => {+ try {+ await breakpoint(300)+ const account = await accountsPartialUpdate(String(values.currentTeamId), props.accountId, { tags })+ await breakpoint()+ actions.updateTagsDone(account)+ tagsModel.findMounted()?.actions.loadTags()+ posthog.capture(AccountsEvents.TagsUpdated, { tag_count: tags.length })+ } catch (error) {+ if (error instanceof Error && isBreakpoint(error)) {+ throw error+ }+ await breakpoint()+ actions.updateTagsDone(null)+ lemonToast.error("Couldn't save tags. Try again.")+ posthog.captureException(error instanceof Error ? error : new Error('Could not update tags'), {+ scope: 'customerAnalyticsAccountSceneLogic.updateTags',+ })+ actions.loadAccount()+ }+ },})),+ actionToUrl(({ props }) => ({+ setActiveTab: ({ tab }) => [+ urls.customerAnalyticsAccount(props.accountId, tab === DEFAULT_ACCOUNT_TAB ? undefined : tab),+ router.values.currentLocation.searchParams,+ router.values.currentLocation.hashParams,+ ],+ })),+ urlToAction(({ actions, props }) => ({+ [`${urls.customerAnalyticsAccount(props.accountId)}/:tab`]: ({ tab }) => {+ actions.restoreActiveTab(tab)+ },+ [urls.customerAnalyticsAccount(props.accountId)]: () => {+ actions.restoreActiveTab(DEFAULT_ACCOUNT_TAB)+ },+ })),+ afterMount(({ actions }) => {+ actions.loadAccount()+ }),])diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsxindex 4568b78ac069..39b2d2a90ae2 100644--- a/products/customer_analytics/manifest.tsx+++ b/products/customer_analytics/manifest.tsx@@ -25,6 +25,7 @@ export const manifest: ProductManifest = {projectBased: true,name: 'Account details',iconType: 'cohort',+ layout: 'app-full-scene-height',},CustomerAnalyticsConfiguration: {import: () =>