Skip to content

: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.

feat(customer-analytics): add personal account view editor (#107160)

Arthur Moreira de Deus87b845ad8377
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1ac066ff87d9..fb6df0cef359 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7979,25 +7979,25 @@ snapshots:
scenes-app-businessknowledge-knowledgesourcenamecell--user-text--light:
hash: v1.k794b7964.fba04716b8f344e21fa3bb2ec69e627bd9836ff2161986538ac2b562973b0edc.Xl-YJ8Poqz1nofU4nIyAfnM4GbZZ1YYtbM37mIzZ4w4
scenes-app-customer-analytics-account-detail--default--dark:
- hash: v1.k794b7964.32d5329bf4ce6055010743914ec226973cc4d455a70581692f97d8cae13c04f1.4Zd5MpCXYXWDIegWaghLkfmgRx11JTVSpbyCab_3_YU
+ hash: v1.k794b7964.b722c6c92866329d952050c1b454d323b3cc753cf2da0966309dedc9ce1277ae.t2xO0wIJkkKdoiJrSN79BB9HEDAk_ibLhBDWI6lammU
scenes-app-customer-analytics-account-detail--default--light:
- hash: v1.k794b7964.3a6ffd58e88bdd30817bc9c6b1c2c9f9bae8825975c121157efb3bd6fbba9f39.81lpbCyMf0S_9mRYZFcT97ecch6YY1--yoxMK2hI-xU
+ hash: v1.k794b7964.d4a4366994ca6bc7a66a61717a30d03be4d912efa40ed71031a100c38d99fc91.90Kqh9qtggxPpuTU6hTnVnIOxQfm8xJvVPx5glfp6xk
scenes-app-customer-analytics-account-detail--external-id--dark:
- hash: v1.k794b7964.3b9ede70a7ed63499ad3d0af05d3ef48768a4b3f739188c18ea92359c4e79ca5.891Bbj7hbUzalM62rLwAJPVPqnQjC1IqugNpYLjfS8E
+ hash: v1.k794b7964.f8ae0455e63cce9ec11e141a98d495fc721386d77ff809ba170c83eef841a528.B4RO1BEXmx8eB3Jpkdm_TccVpfGovN-lvZBa8OxxTY4
scenes-app-customer-analytics-account-detail--external-id--light:
- hash: v1.k794b7964.f33b988a1b58fed2225acb0bdaf75a28c0ef8b094d8a874e4ecfea1704710f95.I_nTZzangmXWh1QhKFugn7GJYhnsMLcMwolRQ9fO7Yg
+ hash: v1.k794b7964.09a01fcd9830239f684e589179ecd6fe4265196d60554307df84dbe86d6f2f1d.bFV4kcj3vJfQqSVmMbAVLXyw5xV4PzafDhtpKO1tHUo
scenes-app-customer-analytics-account-detail--narrow--dark:
- hash: v1.k794b7964.31ffca7eb6c59cf545dd8f16e7a532149448b95c65444aa14d5e776a0875dafd.lULK4-DoenY3SeZK1Sfr50doCkqdIbyl9U35M4ah00g
+ hash: v1.k794b7964.168b51fc7bb530e2f0cf319c2f40bec95c13ce0ef5b7a1e64d9e161e178ad541.N2Hoo63uX3J2ppmOTs_ZAzcX_JaKpu8646UHPvMsaa8
scenes-app-customer-analytics-account-detail--narrow--light:
- hash: v1.k794b7964.5a6763d49a273274f686f1517da9d2ba4af64b5be6897a9886addc04f429c209.JZ6O0iGKO-5AKZyg0XnVZ8JoOZ2-Jg4i9E746aSUm2I
+ hash: v1.k794b7964.d268860af68579ee5a269b8b20f22d1643a6791bf677851ae760569635b22d27.6D3Xn7IFqBI9s8rz5SeHqMQNJieJm07ToJRX8yvpa64
scenes-app-customer-analytics-account-detail--pinned-properties--dark:
- hash: v1.k794b7964.c9bf124e1b6ac61c97cc341788244e25f32b5288b5cf45664b8759d0d0c384d9.5IUvjb3RB5_uobh_9zOjsFbiPbaCNeMwKTof3CDb2FI
+ hash: v1.k794b7964.e8c6dfd9b14aaebdef6509e0b1c9cb79104edcb601540b3281389f970994a42f.ZCIo29eW7hUVoJSQM5domMOzZJxQ7xTLHbyglkVTwZQ
scenes-app-customer-analytics-account-detail--pinned-properties--light:
- hash: v1.k794b7964.60d428d3b31111585e14a43eda01fa1bc1c598c04fb0ba12e895204ccf0421d2.Y2AJGXAEGUlItnKmh9gv5j2I_Epcl4ehUF_fCKC1ewc
+ hash: v1.k794b7964.26baa4906be5a0a6e80ee162f3caada163d5606ed6fbd0d322c1b63495f208e9.1vU97twfzIg__VzQeKQxh1b7Qmks9-7ugaL8Zf2bXJY
scenes-app-customer-analytics-account-detail--pinned-properties-narrow--dark:
- hash: v1.k794b7964.ff9da4647c64580046ded4d93bfd5d1f5b9ddeb91afa106e89b290b1294caba3.v7FVsOduvBV8A7I35N0H0rNRbTs70559gvkezl-TZJs
+ hash: v1.k794b7964.de33855f1c17a82c55e0faec33846783e220077115f4b517f8d020ae9a3db08c.dw3swEPrHa8inmBHh5AfcyVobSGqctlmpctsHlqkWpg
scenes-app-customer-analytics-account-detail--pinned-properties-narrow--light:
- hash: v1.k794b7964.2abb48fdc076ac41b8fc614e2917b8eb5075b0f88d3d0fc904eaab2c97a2eca0.UrfORDRAfYTngPUcDgRb8nS6pT4ExcEp0HmF9kD7zf0
+ hash: v1.k794b7964.c6566c518481be0dc38e0199184d0dfc5704e1b630f08a490bc7c97a7af1d2c7.VLxVjB9T-b8DvQRA28t9c1C1douss-KH4MnkbuuhqaQ
scenes-app-customer-analytics-account-detail-property-sidebar--custom-property-editors--dark:
hash: v1.k794b7964.caefec23d66985f72f6eb40a23370ec4bf1701b9b6cfccd2a4b2b09cc9c1606f.lJ1UWZ6LkZI-k4XJw5UtuIJx1m5tWlMyvgoPlQH2L-g
scenes-app-customer-analytics-account-detail-property-sidebar--custom-property-editors--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 80615cb1339f..6a86cfcde373 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -286,6 +286,7 @@ export const FEATURE_FLAGS = {
CUSTOM_FACET_PINNING: 'custom-facet-pinning', // owner: #team-logs — gates pinning custom facets to the logs/tracing facet rails
CUSTOMER_ANALYTICS: 'customer-analytics-roadmap', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_ACCOUNT_SCENE: 'customer-analytics-account-scene', // owner: @arthurdedeus #team-customer-analytics
+ CUSTOMER_ANALYTICS_ACCOUNT_VIEWS: 'customer-analytics-account-views', // owner: @arthurdedeus #team-customer-analytics
CUSTOMER_ANALYTICS_CSP: 'customer-analytics-csp', // owner: @arthurdedeus #team-customer-analytics, gates the Customer analytics > Accounts settings tab (account_group_type_index dropdown)
CUSTOMER_ANALYTICS_CUSTOMER_TASKS: 'customer-analytics-customer-tasks', // owner: @arthurdedeus #team-web-analytics
CUSTOMER_ANALYTICS_FEATURE_REQUESTS: 'customer-analytics-feature-requests',
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 901e00f1db16..362c0f669b55 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1267,9 +1267,9 @@ export const productUrls = {
customerAnalyticsDashboard: (): string => '/customer_analytics/dashboard',
customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',
customerAnalyticsAccount: (accountId: string, tab?: string): string =>
- `/customer_analytics/accounts/${accountId}${tab ? `/${tab}` : ''}`,
+ `/customer_analytics/accounts/${accountId}${tab ? `/${encodeURIComponent(tab)}` : ''}`,
customerAnalyticsAccountByExternalId: (externalId: string, tab?: string): string =>
- `/customer_analytics/accounts/by-external-id/${encodeURIComponent(externalId)}${tab ? `/${tab}` : ''}`,
+ `/customer_analytics/accounts/by-external-id/${encodeURIComponent(externalId)}${tab ? `/${encodeURIComponent(tab)}` : ''}`,
customerAnalyticsNotes: (): string => '/customer_analytics/notes',
customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',
customerAnalyticsFeed: (): string => '/customer_analytics/feed',
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index d600262b86ee..e84e82bfd617 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -196,6 +196,9 @@ Loading, failed requests, refresh failures, and missing definitions remain disti
`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. With `CUSTOMER_ANALYTICS_ACCOUNT_SCENE` enabled, the body is `AccountPinnedPropertiesExpansion`.
With the flag disabled, the body is `AccountNotebooksExpansion`: the Useful links and active-relationships sidebar plus the shared `AccountDetailTabs` over `notes` / `tasks` / `users` / `relationships` / `feature_requests` / `usage` / `spend` / `opportunities` / `conversations` / `meetings` / `event_stream` (`AccountExpansionTab`; the `tasks` tab is gated by the `CUSTOMER_ANALYTICS_CUSTOMER_TASKS` flag and 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.
+`AccountDetailTabs` builds its tabs from the `ACCOUNT_VIEW_COMPONENTS` registry in `accountViewComponents.ts` (`listAvailableAccountViewComponents` drops flag-gated entries) and renders each body through `AccountViewComponent`, the same switch that renders personal account-view tiles. Add a new tab to the registry and to `AccountViewComponent`, not to `AccountDetailTabs`.
+Each per-tab logic key ends in an `instanceId` segment (`accountId:instanceId`, `externalId:instanceId`, or `accountId:kind:instanceId` for billing). Tabs omit `instanceId`, so they share the `default` instance with the mounts below. Account-view tiles pass their own `instanceId`, so two tiles of one kind keep separate state.
+
**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. `CustomerTasksMount` keeps the account task logic mounted only when `CUSTOMER_ANALYTICS_CUSTOMER_TASKS` is enabled. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live. Flag-gated tabs load only when their flag is enabled.
The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. Its "Access level" and "Last logged in" headers sort (server-side for US orgs via `ordering`, client-side for cached EU rows; sorting is not written to the URL since it's per expanded row), and the "Access level" header carries a filter menu (owner / admin / member checkboxes, count badge) built with the shared `columnValueFilter` helper in `components/columnValueFilter.tsx`, which turns any enumerated column into a header filter and leaves the actual filtering to the caller. Row checkboxes keep selected email addresses across pages. The search field and bulk controls share one wrapping toolbar row, so selection does not add a row above the table. The bulk action copies each selected address on a separate line. A user without an email address cannot be selected. 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.tsx
index 02df0217b5f2..40aa5648d067 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountBillingExpansion.tsx
@@ -12,6 +12,7 @@ import { InsightShortId } from '~/types'
import { AccountBillingChart, canRenderBillingChart } from './AccountBillingChart'
import { AccountBillingKind, accountBillingLogic } from './accountBillingLogic'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
const HedgehogBurningMoney = pngHoggie(burningMoneyHogPng)
const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
@@ -33,16 +34,20 @@ function BillingInsightNotFound({ kind }: { kind: AccountBillingKind }): JSX.Ele
)
}
+interface AccountBillingExpansionProps extends AccountViewTileLogicProps {
+ accountId: string
+ externalId: string
+ kind: AccountBillingKind
+}
+
export function AccountBillingExpansion({
accountId,
externalId,
kind,
-}: {
- accountId: string
- externalId: string
- kind: AccountBillingKind
-}): JSX.Element {
- const logic = accountBillingLogic({ accountId, externalId, kind })
+ ...tileProps
+}: AccountBillingExpansionProps): JSX.Element {
+ const logicProps = { accountId, externalId, kind, ...tileProps }
+ const logic = accountBillingLogic(logicProps)
const {
displayInsights: savedInsights,
savedInsightsLoading,
@@ -69,7 +74,7 @@ export function AccountBillingExpansion({
const showTitles = savedInsights.length > 1
return (
- <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-3 mb-2">
<div className="flex flex-wrap items-center gap-2">
<DateFilter
dateFrom={dateRange.date_from}
@@ -99,7 +104,7 @@ export function AccountBillingExpansion({
{canRenderBillingChart(insight.query) ? (
<AccountBillingChart
key={queryKey}
- logicProps={{ accountId, externalId, kind }}
+ logicProps={logicProps}
shortId={insight.short_id}
query={insight.query}
queryKey={queryKey}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx
index 84ae6003f6d4..5bdfb777d15c 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountConversationsExpansion.tsx
@@ -43,6 +43,7 @@ import {
import { accountEmailThreadsLogic, MESSAGE_PAGE_SIZE } from './accountEmailThreadsLogic'
import { periodLabel } from './AccountSummariesExpansion'
import { AccountSummaryCadencePicker } from './AccountSummaryCadencePicker'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
const HedgehogBusiness = pngHoggie(businessEvolutionPng)
@@ -297,20 +298,23 @@ function SupportMessage({ message }: { message: AccountSupportTicketMessageApi }
function ConversationDetail({
accountId,
+ tileProps,
conversation,
}: {
accountId: string
+ tileProps: AccountViewTileLogicProps
conversation: AccountConversation
}): JSX.Element {
- const emailLogic = accountEmailThreadsLogic({ accountId })
+ const emailLogic = accountEmailThreadsLogic({ accountId, instanceId: tileProps.instanceId })
+ const conversationLogic = accountConversationsLogic({ accountId, ...tileProps })
const { threadDetails, threadDetailsLoading, threadDetailErrors, threadDetailPages } = useValues(emailLogic)
const {
expandedSummaryMessageIds,
supportTicketMessages,
supportTicketMessagesLoading,
supportTicketMessageErrors,
- } = useValues(accountConversationsLogic({ accountId }))
- const { toggleSummaryMessages } = useActions(accountConversationsLogic({ accountId }))
+ } = useValues(conversationLogic)
+ const { toggleSummaryMessages } = useActions(conversationLogic)
const { setThreadDetailPage } = useActions(emailLogic)
if (conversation.source === 'slack') {
@@ -443,15 +447,18 @@ function conversationPreview(conversation: AccountConversation): string {
.trim()
}
+interface AccountConversationsExpansionProps extends AccountViewTileLogicProps {
+ accountId: string
+ embedded?: boolean
+}
+
export function AccountConversationsExpansion({
accountId,
embedded = true,
-}: {
- accountId: string
- embedded?: boolean
-}): JSX.Element {
- const logic = accountConversationsLogic({ accountId })
- const emailLogic = accountEmailThreadsLogic({ accountId })
+ ...tileProps
+}: AccountConversationsExpansionProps): JSX.Element {
+ const logic = accountConversationsLogic({ accountId, ...tileProps })
+ const emailLogic = accountEmailThreadsLogic({ accountId, instanceId: tileProps.instanceId })
const {
conversationsResult,
conversationsResultLoading,
@@ -472,7 +479,7 @@ export function AccountConversationsExpansion({
return <LemonSkeleton className="h-64 w-full" />
}
const toolbar = (
- <div className="hide-scrollbar flex items-center gap-4 overflow-x-auto pb-1">
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 pb-1">
<LemonInput
type="search"
value={searchTerm}
@@ -639,7 +646,7 @@ export function AccountConversationsExpansion({
pagination={{ pageSize: 10, useUrl: false }}
expandable={{
expandedRowRender: (conversation) => (
- <ConversationDetail accountId={accountId} conversation={conversation} />
+ <ConversationDetail accountId={accountId} tileProps={tileProps} conversation={conversation} />
),
isRowExpanded: (conversation) => conversation.id === expandedConversationId,
rowExpandable: () => true,
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
index 9b0e85856038..99dcdcaa78ce 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
@@ -3,24 +3,12 @@ import type { ReactNode } from 'react'
import { LemonTabs } from '@posthog/lemon-ui'
-import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { userHasAccess } from 'lib/utils/accessControlUtils'
-import { AccessControlLevel, AccessControlResourceType } from '~/types'
-
-import { CustomerTasksTabContent } from '../CustomerTasks/CustomerTasksTabContent'
-import { AccountEventStreamToggle } from '../EventStream/AccountEventStreamToggle'
-import { AccountBillingExpansion } from './AccountBillingExpansion'
import { accountBillingLogic } from './accountBillingLogic'
-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'
+import { AccountViewComponent } from './AccountViewComponent'
+import { listAvailableAccountViewComponents } from './accountViewComponents'
interface AccountDetailTabsProps {
accountId: string
@@ -42,8 +30,7 @@ export function AccountDetailTabs({
useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'usage' }))
const { featureFlags } = useValues(featureFlagLogic)
const visibleActiveTab = getVisibleAccountExpansionTab(activeTab, featureFlags)
- const canCreateTasks = userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Editor)
- const canViewAllTasks = userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Viewer)
+ const components = listAvailableAccountViewComponents(featureFlags)
return (
<LemonTabs
@@ -51,71 +38,18 @@ export function AccountDetailTabs({
onChange={onChange}
size="small"
rightSlot={rightSlot}
- tabs={[
- {
- key: 'notes',
- label: 'Notes',
- content: <AccountNotesExpansion accountId={accountId} embedded={embedded} />,
- },
- !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS] && {
- key: 'tasks' as const,
- label: 'Tasks',
- content: (
- <CustomerTasksTabContent
- accountId={accountId}
- canCreate={canCreateTasks}
- canViewAll={canViewAllTasks}
- 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" />,
- },
- {
- key: 'spend',
- label: 'Spend',
- content: <AccountBillingExpansion accountId={accountId} externalId={externalId} kind="spend" />,
- },
- {
- 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} />,
- },
- ]}
+ tabs={components.map((component) => ({
+ key: component.kind,
+ label: component.label,
+ content: (
+ <AccountViewComponent
+ kind={component.kind}
+ accountId={accountId}
+ externalId={externalId}
+ embedded={embedded}
+ />
+ ),
+ }))}
/>
)
}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx
index 221956d5243b..4c8caa8d07aa 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountFeatureRequestsExpansion.tsx
@@ -20,15 +20,19 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import type { FeatureRequestApi } from '../../generated/api.schemas'
import { getFeatureRequestDetailUrl } from '../FeatureRequests/featureRequestNavigation'
import { ACCOUNT_FEATURE_REQUESTS_PAGE_SIZE, accountFeatureRequestsLogic } from './accountFeatureRequestsLogic'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
+
+interface AccountFeatureRequestsExpansionProps extends AccountViewTileLogicProps {
+ accountId: string
+ embedded?: boolean
+}
export function AccountFeatureRequestsExpansion({
accountId,
embedded = true,
-}: {
- accountId: string
- embedded?: boolean
-}): JSX.Element {
- const logic = accountFeatureRequestsLogic({ accountId })
+ ...tileProps
+}: AccountFeatureRequestsExpansionProps): JSX.Element {
+ const logic = accountFeatureRequestsLogic({ accountId, ...tileProps })
const {
accountRequests,
accountRequestsPage,
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx
index b1f90af06527..44b5ee6b373b 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountMeetingsExpansion.tsx
@@ -24,14 +24,21 @@ import gongIcon from 'public/services/gong.png'
import { MeetingApi, MeetingParticipantApi } from 'products/customer_analytics/frontend/generated/api.schemas'
import { accountMeetingsLogic, NOT_LOADED, PAGE_SIZE } from './accountMeetingsLogic'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
import { AccountsEvents } from './constants'
const HedgehogBusiness = pngHoggie(businessEvolutionPng)
const COLLAPSED_ATTENDEE_COUNT = 3
-function MatchingEditor({ accountId }: { accountId: string }): JSX.Element {
- const logic = accountMeetingsLogic({ accountId })
+function MatchingEditor({
+ accountId,
+ tileProps,
+}: {
+ accountId: string
+ tileProps: AccountViewTileLogicProps
+}): JSX.Element {
+ const logic = accountMeetingsLogic({ accountId, ...tileProps })
const { domainsDraft, emailsDraft, savingMatching } = useValues(logic)
const { closeMatchingEditor, setDomainsDraft, setEmailsDraft, saveMatching } = useActions(logic)
@@ -111,8 +118,16 @@ function AttendeeLink({ participant }: { participant: MeetingParticipantApi }):
)
}
-function AttendeeList({ accountId, meeting }: { accountId: string; meeting: MeetingApi }): JSX.Element {
- const logic = accountMeetingsLogic({ accountId })
+function AttendeeList({
+ accountId,
+ tileProps,
+ meeting,
+}: {
+ accountId: string
+ tileProps: AccountViewTileLogicProps
+ meeting: MeetingApi
+}): JSX.Element {
+ const logic = accountMeetingsLogic({ accountId, ...tileProps })
const { expandedAttendeeMeetingIds } = useValues(logic)
const { toggleAttendeesExpanded } = useActions(logic)
@@ -160,14 +175,17 @@ const STATUS_TAG_TYPE = {
cancelled: 'danger',
} as const
+interface AccountMeetingsExpansionProps extends AccountViewTileLogicProps {
+ accountId: string
+ embedded?: boolean
+}
+
export function AccountMeetingsExpansion({
accountId,
embedded = true,
-}: {
- accountId: string
- embedded?: boolean
-}): JSX.Element {
- const logic = accountMeetingsLogic({ accountId })
+ ...tileProps
+}: AccountMeetingsExpansionProps): JSX.Element {
+ const logic = accountMeetingsLogic({ accountId, ...tileProps })
const { canEditMeetingMatching, meetingsResult, meetingsResultLoading, searchTerm, page, matchingEditorOpen } =
useValues(logic)
const { setSearchTerm, setPage, openMatchingEditor } = useActions(logic)
@@ -217,7 +235,7 @@ export function AccountMeetingsExpansion({
{
title: 'Attendees',
key: 'participants',
- render: (_, meeting) => <AttendeeList accountId={accountId} meeting={meeting} />,
+ render: (_, meeting) => <AttendeeList accountId={accountId} tileProps={tileProps} meeting={meeting} />,
},
{
title: 'Status',
@@ -294,7 +312,7 @@ export function AccountMeetingsExpansion({
Edit matching
</LemonButton>
</div>
- {matchingEditorOpen && <MatchingEditor accountId={accountId} />}
+ {matchingEditorOpen && <MatchingEditor accountId={accountId} tileProps={tileProps} />}
{content}
</div>
)
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotesExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotesExpansion.tsx
index 3b6c041d168e..90eb2c78dffb 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountNotesExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotesExpansion.tsx
@@ -12,6 +12,7 @@ import { urls } from 'scenes/urls'
import type { AccountNotebookApi } from 'products/customer_analytics/frontend/generated/api.schemas'
import { accountNotebooksLogic } from './accountNotebooksLogic'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
import { AccountsEvents } from './constants'
const PREVIEW_MAX_CHARS = 200
@@ -25,14 +26,17 @@ function getPreview(notebook: AccountNotebookApi): string {
return collapsed.length > PREVIEW_MAX_CHARS ? `${collapsed.slice(0, PREVIEW_MAX_CHARS).trimEnd()}…` : collapsed
}
+interface AccountNotesExpansionProps extends AccountViewTileLogicProps {
+ accountId: string
+ embedded?: boolean
+}
+
export function AccountNotesExpansion({
accountId,
embedded = true,
-}: {
- accountId: string
- embedded?: boolean
-}): JSX.Element {
- const logic = accountNotebooksLogic({ accountId })
+ ...tileProps
+}: AccountNotesExpansionProps): JSX.Element {
+ const logic = accountNotebooksLogic({ accountId, ...tileProps })
const { notebooks, notebooksResponseLoading, createdNoteLoading, searchTerm, sorting, pagination } =
useValues(logic)
const { setSearchTerm, setSorting, createNote } = useActions(logic)
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx
index 9a0b577b4762..2fe5923e1e60 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountOpportunitiesExpansion.tsx
@@ -75,12 +75,16 @@ const columns: LemonTableColumns<AccountOpportunity> = [
export function AccountOpportunitiesExpansion({
accountId,
+ instanceId,
embedded = true,
}: {
accountId: string
+ instanceId?: string
embedded?: boolean
}): JSX.Element {
- const { opportunitiesResult, opportunitiesResultLoading } = useValues(accountOpportunitiesLogic({ accountId }))
+ const { opportunitiesResult, opportunitiesResultLoading } = useValues(
+ accountOpportunitiesLogic({ accountId, instanceId })
+ )
if (opportunitiesResultLoading || opportunitiesResult === NOT_LOADED) {
return <LemonSkeleton className="h-64 w-full" />
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
index 1e8e704befc9..8cdaa088ec6e 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
@@ -16,6 +16,7 @@ import { userLogic } from 'scenes/userLogic'
import { columnValueFilter } from '../columnValueFilter'
import { getAccountRelatedUserAdminUrl } from './accountRelatedUserAdminUrl'
import { accountRelatedUsersLogic, AccountOrganizationMember, PAGE_SIZE } from './accountRelatedUsersLogic'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
import { AccountsEvents } from './constants'
const LEVEL_FILTER_OPTIONS = [
@@ -27,14 +28,17 @@ const LEVEL_FILTER_OPTIONS = [
label: capitalizeFirstLetter(membershipLevelToName.get(level) ?? 'Unknown'),
}))
+interface AccountRelatedUsersExpansionProps extends AccountViewTileLogicProps {
+ externalId: string
+ embedded?: boolean
+}
+
export function AccountRelatedUsersExpansion({
externalId,
embedded = true,
-}: {
- externalId: string
- embedded?: boolean
-}): JSX.Element {
- const logic = accountRelatedUsersLogic({ externalId })
+ ...tileProps
+}: AccountRelatedUsersExpansionProps): JSX.Element {
+ const logic = accountRelatedUsersLogic({ externalId, ...tileProps })
const { membersResponse, membersResponseLoading, page, searchTerm, levels, sorting } = useValues(logic)
const { user } = useValues(userLogic)
const { setPage, setSearchTerm, setLevels, setSorting } = useActions(logic)
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
index 0d4b22c7c8cd..dc4618bac293 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx
@@ -20,6 +20,7 @@ import type {
} from 'products/customer_analytics/frontend/generated/api.schemas'
import { accountRelationshipsLogic } from './accountRelationshipsLogic'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
const PAGE_SIZE = 10
@@ -31,13 +32,17 @@ const SOURCE_LABELS: Record<AccountRelationshipSourceEnumApi, string> = {
migration: 'Migration',
}
+interface AccountRelationshipsExpansionProps extends AccountViewTileLogicProps {
+ accountId: string
+ embedded?: boolean
+}
+
export function AccountRelationshipsExpansion({
accountId,
embedded = true,
-}: {
- accountId: string
- embedded?: boolean
-}): JSX.Element {
+ ...tileProps
+}: AccountRelationshipsExpansionProps): JSX.Element {
+ const logic = accountRelationshipsLogic({ accountId, ...tileProps })
const {
relationships,
relationshipsLoading,
@@ -50,7 +55,7 @@ export function AccountRelationshipsExpansion({
canDeleteRelationships,
relationshipSaving,
relationshipToDelete,
- } = useValues(accountRelationshipsLogic({ accountId }))
+ } = useValues(logic)
const {
setDefinitionFilter,
setAssignDefinitionId,
@@ -59,7 +64,7 @@ export function AccountRelationshipsExpansion({
openDeleteConfirmation,
closeDeleteConfirmation,
deleteRelationship,
- } = useActions(accountRelationshipsLogic({ accountId }))
+ } = useActions(logic)
const columns: LemonTableColumns<AccountRelationshipApi> = [
{
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
new file mode 100644
index 000000000000..295ca99a9230
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
@@ -0,0 +1,70 @@
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import { CustomerTasksTabContent } from '../CustomerTasks/CustomerTasksTabContent'
+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 type { AccountViewComponentKind } from './accountViewComponents'
+import type { AccountViewTileConfig } from './accountViewTileConfig'
+
+interface AccountViewComponentProps {
+ kind: AccountViewComponentKind
+ accountId: string
+ externalId: string
+ instanceId?: string
+ initialConfig?: AccountViewTileConfig
+ onConfigChange?: (config: AccountViewTileConfig) => void
+ embedded?: boolean
+}
+
+export function AccountViewComponent({
+ kind,
+ accountId,
+ externalId,
+ instanceId,
+ initialConfig,
+ onConfigChange,
+ embedded = true,
+}: AccountViewComponentProps): JSX.Element {
+ const tileProps = { instanceId, initialConfig, onConfigChange }
+ switch (kind) {
+ case 'notes':
+ return <AccountNotesExpansion accountId={accountId} embedded={embedded} {...tileProps} />
+ case 'tasks':
+ return (
+ <CustomerTasksTabContent
+ accountId={accountId}
+ canCreate={userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Editor)}
+ canViewAll={userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Viewer)}
+ embedded={embedded}
+ {...tileProps}
+ />
+ )
+ case 'users':
+ return <AccountRelatedUsersExpansion externalId={externalId} embedded={embedded} {...tileProps} />
+ case 'relationships':
+ return <AccountRelationshipsExpansion accountId={accountId} embedded={embedded} {...tileProps} />
+ case 'feature_requests':
+ return <AccountFeatureRequestsExpansion accountId={accountId} embedded={embedded} {...tileProps} />
+ case 'usage':
+ return <AccountBillingExpansion accountId={accountId} externalId={externalId} kind="usage" {...tileProps} />
+ case 'spend':
+ return <AccountBillingExpansion accountId={accountId} externalId={externalId} kind="spend" {...tileProps} />
+ case 'opportunities':
+ return <AccountOpportunitiesExpansion accountId={accountId} embedded={embedded} instanceId={instanceId} />
+ case 'conversations':
+ return <AccountConversationsExpansion accountId={accountId} embedded={embedded} {...tileProps} />
+ case 'meetings':
+ return <AccountMeetingsExpansion accountId={accountId} embedded={embedded} {...tileProps} />
+ case 'event_stream':
+ return <AccountEventStreamToggle accountId={accountId} externalId={externalId} />
+ }
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
index 1382226110e2..83be2f1656e0 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.test.ts
@@ -60,6 +60,59 @@ describe('accountBillingLogic', () => {
logic?.unmount()
})
+ it('keeps duplicate tile configuration independent', async () => {
+ const firstConfigChanged = jest.fn()
+ const secondConfigChanged = jest.fn()
+ const first = accountBillingLogic({
+ accountId: 'acc-1',
+ externalId: 'org-uuid',
+ kind: 'usage',
+ instanceId: 'tile-a',
+ initialConfig: {
+ dateRange: { date_from: '-7d', date_to: null },
+ usageInterval: 'week',
+ },
+ onConfigChange: firstConfigChanged,
+ })
+ const second = accountBillingLogic({
+ accountId: 'acc-1',
+ externalId: 'org-uuid',
+ kind: 'usage',
+ instanceId: 'tile-b',
+ initialConfig: {
+ dateRange: { date_from: '-90d', date_to: null },
+ usageInterval: 'month',
+ },
+ onConfigChange: secondConfigChanged,
+ })
+ first.mount()
+ second.mount()
+
+ try {
+ await expectLogic(first).toFinishAllListeners()
+ await expectLogic(second).toFinishAllListeners()
+
+ expect(first.values.dateRange).toEqual({ date_from: '-7d', date_to: null })
+ expect(first.values.usageInterval).toBe('week')
+ expect(second.values.dateRange).toEqual({ date_from: '-90d', date_to: null })
+ expect(second.values.usageInterval).toBe('month')
+
+ first.actions.setDateRange('2024-01-01', '2024-01-31')
+
+ expect(first.values.dateRange).toEqual({ date_from: '2024-01-01', date_to: '2024-01-31' })
+ expect(second.values.dateRange).toEqual({ date_from: '-90d', date_to: null })
+ expect(firstConfigChanged).toHaveBeenLastCalledWith({
+ dateRange: { date_from: '2024-01-01', date_to: '2024-01-31' },
+ usageInterval: 'week',
+ hiddenSeriesKeysByShortId: {},
+ })
+ expect(secondConfigChanged).not.toHaveBeenCalled()
+ } finally {
+ first.unmount()
+ second.unmount()
+ }
+ })
+
describe.each<AccountBillingKind>(['usage', 'spend'])('kind: %s', (kind) => {
const mountForKind = (): void => {
logic = accountBillingLogic({ accountId: 'acc-1', externalId: 'org-uuid', kind })
diff --git a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
index 39a58f0c5e60..63ef19ac9229 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountBillingLogic.ts
@@ -29,6 +29,12 @@ import {
import { InsightShortId, InsightModel } from '~/types'
import type { Node } from '../../../../../frontend/src/queries/schema/schema-general'
+import {
+ getTileRecord,
+ getTileString,
+ type AccountViewTileConfig,
+ type AccountViewTileLogicProps,
+} from './accountViewTileConfig'
import { BillingUsageInterval, billingUsageQuery, supportsUsageAggregation } from './billingUsageQuery'
import { AccountsEvents } from './constants'
@@ -74,12 +80,40 @@ const DEFAULT_DATE_RANGE: Record<AccountBillingKind, BillingDateRange> = {
spend: { date_from: '-1y', date_to: null },
}
-export interface AccountBillingLogicProps {
+export interface AccountBillingLogicProps extends AccountViewTileLogicProps {
accountId: string
externalId: string
kind: AccountBillingKind
}
+function getInitialDateRange(config: AccountViewTileConfig | undefined, kind: AccountBillingKind): BillingDateRange {
+ const dateRange = getTileRecord(config, 'dateRange')
+ const dateFrom = dateRange?.date_from
+ const dateTo = dateRange?.date_to
+ return {
+ date_from: typeof dateFrom === 'string' || dateFrom === null ? dateFrom : DEFAULT_DATE_RANGE[kind].date_from,
+ date_to: typeof dateTo === 'string' || dateTo === null ? dateTo : DEFAULT_DATE_RANGE[kind].date_to,
+ }
+}
+
+function getInitialUsageInterval(config: AccountViewTileConfig | undefined): BillingUsageInterval {
+ const interval = getTileString(config, 'usageInterval')
+ return interval === 'week' || interval === 'month' ? interval : 'day'
+}
+
+function getInitialHiddenSeries(config: AccountViewTileConfig | undefined): Record<string, string[]> {
+ const hiddenSeries = getTileRecord(config, 'hiddenSeriesKeysByShortId')
+ if (!hiddenSeries) {
+ return {}
+ }
+ return Object.fromEntries(
+ Object.entries(hiddenSeries).filter(
+ (entry): entry is [string, string[]] =>
+ Array.isArray(entry[1]) && entry[1].every((value) => typeof value === 'string')
+ )
+ )
+}
+
export function getBillingDataVisualizationKey(queryKey: string): string {
return `InsightViz.${queryKey}`
}
@@ -197,6 +231,7 @@ export interface accountBillingLogicMeta {
resolvedDateRange: BillingDateRange,
arg: any,
arg2: any,
+ arg3: any,
usageInterval: BillingUsageInterval
) => (shortId: string) => string
}
@@ -212,7 +247,7 @@ export type accountBillingLogicType = MakeLogicType<
export const accountBillingLogic = kea<accountBillingLogicType>([
path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountBillingLogic', key]),
props({} as AccountBillingLogicProps),
- key((props) => `${props.accountId}:${props.kind}`),
+ key((props) => `${props.accountId}:${props.kind}:${props.instanceId ?? 'default'}`),
actions({
setUsageInterval: (interval: BillingUsageInterval) => ({ interval }),
setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
@@ -228,15 +263,18 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
}),
}),
reducers(({ props }) => ({
- usageInterval: ['day' as BillingUsageInterval, { setUsageInterval: (_, { interval }) => interval }],
+ usageInterval: [
+ getInitialUsageInterval(props.initialConfig),
+ { setUsageInterval: (_, { interval }) => interval },
+ ],
dateRange: [
- DEFAULT_DATE_RANGE[props.kind] as BillingDateRange,
+ getInitialDateRange(props.initialConfig, props.kind),
{
setDateRange: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom, date_to: dateTo }),
},
],
ephemeralHiddenSeriesKeysByShortId: [
- {} as Record<string, string[]>,
+ getInitialHiddenSeries(props.initialConfig),
{
toggleHiddenSeriesKey: (state, { shortId, seriesKey }) => {
const current = state[shortId] ?? []
@@ -256,6 +294,13 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
],
})),
listeners(({ props, values, cache }) => {
+ const saveConfig = (): void => {
+ props.onConfigChange?.({
+ dateRange: values.dateRange,
+ usageInterval: values.usageInterval,
+ hiddenSeriesKeysByShortId: values.ephemeralHiddenSeriesKeysByShortId,
+ })
+ }
const preloadSavedInsights = (savedInsights: InsightModel[]): void => {
for (const insight of savedInsights) {
if (!insight.query || insight.query.kind !== NodeKind.DataVisualizationNode) {
@@ -282,13 +327,16 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
preloadSavedInsights(values.displayInsights ?? [])
},
setDateRange: () => {
+ saveConfig()
preloadSavedInsights(values.displayInsights ?? [])
},
setUsageInterval: ({ interval }) => {
+ saveConfig()
preloadSavedInsights(values.displayInsights ?? [])
posthog.capture(AccountsEvents.UsageIntervalChanged, { interval })
},
toggleHiddenSeriesKey: ({ shortId, seriesKey, seriesCount }) => {
+ saveConfig()
posthog.capture(AccountsEvents.UsageSeriesToggled, {
kind: props.kind,
is_hidden: (values.ephemeralHiddenSeriesKeysByShortId[shortId] ?? []).includes(seriesKey),
@@ -296,6 +344,7 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
})
},
setAllSeriesHidden: ({ seriesKeys, hidden }) => {
+ saveConfig()
posthog.capture(AccountsEvents.UsageSeriesBulkToggled, {
kind: props.kind,
is_hidden: hidden,
@@ -387,10 +436,16 @@ export const accountBillingLogic = kea<accountBillingLogicType>([
// The embedded <Query> only refetches when its query changes, not when variablesOverride changes — so a date
// change must remount it. Keying on the resolved range gives each insight a key that changes with the range.
queryKeyFor: [
- (s) => [s.resolvedDateRange, (_, p) => p.accountId, (_, p) => p.kind, s.usageInterval],
- (resolvedDateRange: BillingDateRange, accountId, kind, interval: BillingUsageInterval) =>
+ (s) => [
+ s.resolvedDateRange,
+ (_, p) => p.accountId,
+ (_, p) => p.kind,
+ (_, p) => p.instanceId,
+ s.usageInterval,
+ ],
+ (resolvedDateRange: BillingDateRange, accountId, kind, instanceId, interval: BillingUsageInterval) =>
(shortId: string): string =>
- `account-billing-${accountId}-${kind}-${shortId}-${resolvedDateRange.date_from}-${resolvedDateRange.date_to}-${interval}`,
+ `account-billing-${accountId}-${kind}-${instanceId ?? 'default'}-${shortId}-${resolvedDateRange.date_from}-${resolvedDateRange.date_to}-${interval}`,
],
}),
afterMount(({ actions, props }) => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.ts
index 9829e2ccad27..0636fa134be9 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountConversationsLogic.ts
@@ -18,6 +18,8 @@ import type {
SupportTicketApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import { getTileString, type AccountViewTileConfig, type AccountViewTileLogicProps } from './accountViewTileConfig'
+
export type ConversationSource = 'email' | 'support' | 'slack'
export type AccountConversation =
@@ -41,10 +43,18 @@ export const NOT_LOADED: AccountConversationsResult = {
}
const LIST_LIMIT = 50
-export interface AccountConversationsLogicProps {
+export interface AccountConversationsLogicProps extends AccountViewTileLogicProps {
accountId: string
}
+function getInitialSources(config: AccountViewTileConfig | undefined): ConversationSource[] {
+ const sources = config?.sources
+ return Array.isArray(sources) &&
+ sources.every((source) => source === 'email' || source === 'support' || source === 'slack')
+ ? sources
+ : ['email', 'support', 'slack']
+}
+
interface accountConversationsLogicValues {
conversationsResult: AccountConversationsResult
conversationsResultLoading: boolean
@@ -159,7 +169,7 @@ function searchableText(conversation: AccountConversation): string {
export const accountConversationsLogic = kea<accountConversationsLogicType>([
path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountConversationsLogic', key]),
props({} as AccountConversationsLogicProps),
- key((props) => props.accountId),
+ key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
connect(() => ({ values: [teamLogic, ['currentTeamId']] })),
actions({
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
@@ -287,9 +297,12 @@ export const accountConversationsLogic = kea<accountConversationsLogicType>([
},
],
})),
- reducers({
- searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],
- sources: [['email', 'support', 'slack'] as ConversationSource[], { setSources: (_, { sources }) => sources }],
+ reducers(({ props }) => ({
+ searchTerm: [
+ getTileString(props.initialConfig, 'searchTerm'),
+ { setSearchTerm: (_, { searchTerm }) => searchTerm },
+ ],
+ sources: [getInitialSources(props.initialConfig), { setSources: (_, { sources }) => sources }],
expandedConversationId: [
null as string | null,
{
@@ -331,7 +344,7 @@ export const accountConversationsLogic = kea<accountConversationsLogicType>([
loadSupportTicketMessagesFailure: (state, { ticketId }) => ({ ...state, [ticketId]: true }),
},
],
- }),
+ })),
selectors({
filteredConversations: [
(selectors) => [selectors.conversationsResult, selectors.searchTerm, selectors.sources],
@@ -358,6 +371,13 @@ export const accountConversationsLogic = kea<accountConversationsLogicType>([
],
}),
listeners(({ actions, props, values }) => ({
+ setSearchTerm: async (_, breakpoint) => {
+ await breakpoint(300)
+ props.onConfigChange?.({ searchTerm: values.searchTerm, sources: values.sources })
+ },
+ setSources: () => {
+ props.onConfigChange?.({ searchTerm: values.searchTerm, sources: values.sources })
+ },
openConversation: ({ conversationId }) => {
if (!conversationId.startsWith('support:')) {
return
diff --git a/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.ts
index 6780ca8dc740..b4396575d6dc 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountEmailThreadsLogic.ts
@@ -18,6 +18,7 @@ export const MESSAGE_PAGE_SIZE = 50
export interface AccountEmailThreadsLogicProps {
accountId: string
+ instanceId?: string
}
export interface AccountEmailThreadsResult {
@@ -104,7 +105,7 @@ export type accountEmailThreadsLogicType = MakeLogicType<
export const accountEmailThreadsLogic = kea<accountEmailThreadsLogicType>([
path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountEmailThreadsLogic', key]),
props({} as AccountEmailThreadsLogicProps),
- key((props) => props.accountId),
+ key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
connect(() => ({
values: [teamLogic, ['currentTeamId']],
})),
diff --git a/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.ts
index aa29ab892b8e..eb54da5f99c4 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountFeatureRequestsLogic.ts
@@ -8,6 +8,7 @@ import { teamLogic } from 'scenes/teamLogic'
import type { TeamPublicType, TeamType } from '../../../../../frontend/src/types'
import { featureRequestsList, featureRequestsUpdate } from '../../generated/api'
import type { FeatureRequestApi, PaginatedFeatureRequestListApi } from '../../generated/api.schemas'
+import { getTileString, type AccountViewTileLogicProps } from './accountViewTileConfig'
export const ACCOUNT_FEATURE_REQUESTS_PAGE_SIZE = 5
const AVAILABLE_REQUESTS_LIMIT = 50
@@ -18,7 +19,7 @@ const EMPTY_REQUESTS_RESPONSE: PaginatedFeatureRequestListApi = {
results: [],
}
-export interface AccountFeatureRequestsLogicProps {
+export interface AccountFeatureRequestsLogicProps extends AccountViewTileLogicProps {
accountId: string
}
@@ -121,7 +122,7 @@ export type accountFeatureRequestsLogicType = MakeLogicType<
export const accountFeatureRequestsLogic = kea<accountFeatureRequestsLogicType>([
props({} as AccountFeatureRequestsLogicProps),
- key((props) => props.accountId),
+ key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
path((key) => ['products', 'customerAnalytics', 'accountFeatureRequestsLogic', key]),
connect(() => ({ values: [teamLogic, ['currentTeam']] })),
actions({
@@ -170,7 +171,7 @@ export const accountFeatureRequestsLogic = kea<accountFeatureRequestsLogicType>(
},
],
})),
- reducers({
+ reducers(({ props }) => ({
requestPickerOpen: [false, { openRequestPicker: () => true, closeRequestPicker: () => false }],
selectedRequestId: [
null as string | null,
@@ -188,7 +189,10 @@ export const accountFeatureRequestsLogic = kea<accountFeatureRequestsLogicType>(
setAccountRequestsSearch: () => 1,
},
],
- accountRequestsSearch: ['', { setAccountRequestsSearch: (_, { search }) => search }],
+ accountRequestsSearch: [
+ getTileString(props.initialConfig, 'searchTerm'),
+ { setAccountRequestsSearch: (_, { search }) => search },
+ ],
requestSearch: [
'',
{
@@ -215,7 +219,7 @@ export const accountFeatureRequestsLogic = kea<accountFeatureRequestsLogicType>(
closeRequestPicker: () => null,
},
],
- }),
+ })),
selectors({
candidateOptions: [
(selectors) => [selectors.availableRequests],
@@ -228,6 +232,7 @@ export const accountFeatureRequestsLogic = kea<accountFeatureRequestsLogicType>(
setAccountRequestsPage: () => actions.loadAccountRequests(),
setAccountRequestsSearch: async (_, breakpoint) => {
await breakpoint(300)
+ props.onConfigChange?.({ searchTerm: values.accountRequestsSearch })
actions.loadAccountRequests()
},
setRequestSearch: async (_, breakpoint) => {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
index b5866501eb70..c96196b8ead6 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
@@ -20,12 +20,13 @@ import type {
import { canEditEmailMatching, cleanDomains, cleanEmails } from './accountEmailMatching'
import { accountLinksLogic } from './accountLinksLogic'
+import { getTileString, type AccountViewTileLogicProps } from './accountViewTileConfig'
import { AccountsEvents } from './constants'
// Matches the Users tab, the other server-side-paginated account tab.
export const PAGE_SIZE = 10
-export interface AccountMeetingsLogicProps {
+export interface AccountMeetingsLogicProps extends AccountViewTileLogicProps {
accountId: string
}
@@ -129,7 +130,7 @@ export type accountMeetingsLogicType = MakeLogicType<
export const accountMeetingsLogic = kea<accountMeetingsLogicType>([
path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountMeetingsLogic', key]),
props({} as AccountMeetingsLogicProps),
- key((props) => props.accountId),
+ key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
connect((props: AccountMeetingsLogicProps) => ({
values: [
teamLogic,
@@ -173,7 +174,7 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([
},
],
})),
- reducers({
+ reducers(({ props }) => ({
matchingEditorOpen: [
false,
{
@@ -201,7 +202,7 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([
},
],
searchTerm: [
- '',
+ getTileString(props.initialConfig, 'searchTerm'),
{
setSearchTerm: (_, { searchTerm }) => searchTerm,
},
@@ -220,7 +221,7 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([
state.includes(meetingId) ? state.filter((id) => id !== meetingId) : [...state, meetingId],
},
],
- }),
+ })),
selectors({
canEditMeetingMatching: [
(selectors) => [selectors.currentTeam],
@@ -231,6 +232,7 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([
setPage: () => actions.loadMeetings(),
setSearchTerm: async ({ searchTerm }, breakpoint) => {
await breakpoint(300)
+ props.onConfigChange?.({ searchTerm: values.searchTerm })
actions.loadMeetings()
posthog.capture(AccountsEvents.MeetingsSearched, {
has_query: searchTerm.trim().length > 0,
diff --git a/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts
index 6f398369d159..19d3ef5e743a 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts
@@ -28,16 +28,29 @@ import type {
PaginatedAccountNotebookListApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import {
+ getTileRecord,
+ getTileString,
+ type AccountViewTileConfig,
+ type AccountViewTileLogicProps,
+} from './accountViewTileConfig'
import { AccountsEvents } from './constants'
export const NOTES_PER_PAGE = 5
export const DEFAULT_NOTES_SORTING: Sorting = { columnKey: 'created_at', order: -1 }
-export interface AccountNotebooksLogicProps {
+export interface AccountNotebooksLogicProps extends AccountViewTileLogicProps {
accountId: string
}
+function getInitialSorting(config: AccountViewTileConfig | undefined): Sorting | null {
+ const sorting = getTileRecord(config, 'sorting')
+ return typeof sorting?.columnKey === 'string' && (sorting.order === 1 || sorting.order === -1)
+ ? (sorting as unknown as Sorting)
+ : DEFAULT_NOTES_SORTING
+}
+
// Maps the table's sorting state onto the backend's whitelisted `ordering` param.
function sortingToOrdering(sorting: Sorting | null): string | undefined {
if (!sorting) {
@@ -141,7 +154,7 @@ export type accountNotebooksLogicType = MakeLogicType<
export const accountNotebooksLogic = kea<accountNotebooksLogicType>([
path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountNotebooksLogic', key]),
props({} as AccountNotebooksLogicProps),
- key((props) => props.accountId),
+ key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
connect(() => ({
values: [teamLogic, ['currentTeamId']],
actions: [notebookPanelLogic, ['selectNotebook']],
@@ -199,11 +212,14 @@ export const accountNotebooksLogic = kea<accountNotebooksLogicType>([
},
],
})),
- reducers({
- searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],
- sorting: [DEFAULT_NOTES_SORTING as Sorting | null, { setSorting: (_, { sorting }) => sorting }],
+ reducers(({ props }) => ({
+ searchTerm: [
+ getTileString(props.initialConfig, 'searchTerm'),
+ { setSearchTerm: (_, { searchTerm }) => searchTerm },
+ ],
+ sorting: [getInitialSorting(props.initialConfig), { setSorting: (_, { sorting }) => sorting }],
page: [1, { setPage: (_, { page }) => page }],
- }),
+ })),
selectors(({ actions }) => ({
notebooks: [
(s) => [s.notebooksResponse],
@@ -227,9 +243,10 @@ export const accountNotebooksLogic = kea<accountNotebooksLogicType>([
}),
],
})),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, props, values }) => ({
setSearchTerm: async (_, breakpoint) => {
await breakpoint(300)
+ props.onConfigChange?.({ searchTerm: values.searchTerm, sorting: values.sorting })
posthog.capture(AccountsEvents.NotesSearched, {
has_query: values.searchTerm.trim().length > 0,
query_length: values.searchTerm.trim().length,
@@ -237,6 +254,7 @@ export const accountNotebooksLogic = kea<accountNotebooksLogicType>([
actions.setPage(1)
},
setSorting: ({ sorting }) => {
+ props.onConfigChange?.({ searchTerm: values.searchTerm, sorting: values.sorting })
posthog.capture(AccountsEvents.NotesSorted, {
column: sorting?.columnKey ?? null,
direction: sorting ? (sorting.order === -1 ? 'desc' : 'asc') : 'cleared',
diff --git a/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.ts
index 2b6e9b8bbc57..63caf90e2e9e 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountOpportunitiesLogic.ts
@@ -14,6 +14,7 @@ import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
export interface AccountOpportunitiesLogicProps {
accountId: string
+ instanceId?: string
}
export interface AccountOpportunity {
@@ -88,7 +89,7 @@ export type accountOpportunitiesLogicType = MakeLogicType<
export const accountOpportunitiesLogic = kea<accountOpportunitiesLogicType>([
path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountOpportunitiesLogic', key]),
props({} as AccountOpportunitiesLogicProps),
- key((props) => props.accountId),
+ key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
connect(() => ({
values: [teamLogic, ['currentTeamId']],
})),
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts
index 93c0a5f84c21..fe54635c870b 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts
@@ -25,6 +25,12 @@ import { hogql } from '~/queries/utils'
import { OrganizationMemberType, Region } from '~/types'
import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
+import {
+ getTileRecord,
+ getTileString,
+ type AccountViewTileConfig,
+ type AccountViewTileLogicProps,
+} from './accountViewTileConfig'
import { AccountsEvents } from './constants'
export type AccountOrganizationMember = Pick<OrganizationMemberType, 'id' | 'user' | 'level' | 'last_login'> & {
@@ -137,10 +143,24 @@ const fetchEuMembers = async (externalId: string): Promise<AccountOrganizationMe
}
}
-export interface AccountRelatedUsersLogicProps {
+export interface AccountRelatedUsersLogicProps extends AccountViewTileLogicProps {
externalId: string
}
+function getInitialLevels(config: AccountViewTileConfig | undefined): OrganizationMembershipLevel[] {
+ const levels = config?.levels
+ return Array.isArray(levels) && levels.every((level) => typeof level === 'number')
+ ? (levels as OrganizationMembershipLevel[])
+ : []
+}
+
+function getInitialSorting(config: AccountViewTileConfig | undefined): Sorting | null {
+ const sorting = getTileRecord(config, 'sorting')
+ return typeof sorting?.columnKey === 'string' && (sorting.order === 1 || sorting.order === -1)
+ ? (sorting as unknown as Sorting)
+ : null
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountRelatedUsersLogicValues {
levels: OrganizationMembershipLevel[]
@@ -202,14 +222,14 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([
path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountRelatedUsersLogic', key]),
props({} as AccountRelatedUsersLogicProps),
// Accounts with no external_id all share the empty-string key, which is benign: afterMount skips loading when externalId is falsy.
- key((props) => props.externalId),
+ key((props) => `${props.externalId}:${props.instanceId ?? 'default'}`),
actions({
setPage: (page: number) => ({ page }),
setSearchTerm: (searchTerm: string) => ({ searchTerm }),
setLevels: (levels: OrganizationMembershipLevel[]) => ({ levels }),
setSorting: (sorting: Sorting | null) => ({ sorting }),
}),
- reducers({
+ reducers(({ props }) => ({
page: [
1,
{
@@ -219,10 +239,13 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([
setSorting: () => 1,
},
],
- searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],
- levels: [[] as OrganizationMembershipLevel[], { setLevels: (_, { levels }) => levels }],
- sorting: [null as Sorting | null, { setSorting: (_, { sorting }) => sorting }],
- }),
+ searchTerm: [
+ getTileString(props.initialConfig, 'searchTerm'),
+ { setSearchTerm: (_, { searchTerm }) => searchTerm },
+ ],
+ levels: [getInitialLevels(props.initialConfig), { setLevels: (_, { levels }) => levels }],
+ sorting: [getInitialSorting(props.initialConfig), { setSorting: (_, { sorting }) => sorting }],
+ })),
selectors({
query: [
(s) => [s.searchTerm, s.levels, s.sorting],
@@ -281,10 +304,11 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([
},
],
})),
- listeners(({ actions }) => ({
+ listeners(({ actions, props, values }) => ({
setPage: () => actions.loadMembers(),
setSearchTerm: async ({ searchTerm }, breakpoint) => {
await breakpoint(300)
+ props.onConfigChange?.({ searchTerm: values.searchTerm, levels: values.levels, sorting: values.sorting })
actions.loadMembers()
posthog.capture(AccountsEvents.RelatedUsersSearched, {
has_query: searchTerm.trim().length > 0,
@@ -292,10 +316,12 @@ export const accountRelatedUsersLogic = kea<accountRelatedUsersLogicType>([
})
},
setLevels: ({ levels }) => {
+ props.onConfigChange?.({ searchTerm: values.searchTerm, levels: values.levels, sorting: values.sorting })
actions.loadMembers()
posthog.capture(AccountsEvents.RelatedUsersFiltered, { levels })
},
setSorting: ({ sorting }) => {
+ props.onConfigChange?.({ searchTerm: values.searchTerm, levels: values.levels, sorting: values.sorting })
actions.loadMembers()
posthog.capture(AccountsEvents.RelatedUsersSorted, {
column: (sorting?.columnKey as RelatedUsersSortKey | undefined) ?? null,
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
index 253d07156dce..9b446f1e3175 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
@@ -23,9 +23,10 @@ import type {
import { ACCOUNTS_TABLE_DATA_NODE_KEY, ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'
import { accountSidebarPropertiesLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic'
import { accountsColumnConfigLogic, ROLE_KEY_BY_NAME } from './accountsColumnConfigLogic'
+import { getTileString, type AccountViewTileLogicProps } from './accountViewTileConfig'
import { AccountsEvents } from './constants'
-export interface AccountRelationshipsLogicProps {
+export interface AccountRelationshipsLogicProps extends AccountViewTileLogicProps {
accountId: string
}
@@ -131,7 +132,7 @@ export type accountRelationshipsLogicType = MakeLogicType<
export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountRelationshipsLogic', key]),
props({} as AccountRelationshipsLogicProps),
- key((props) => props.accountId),
+ key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
connect(() => ({
values: [teamLogic, ['currentTeam', 'currentTeamId'], accountsColumnConfigLogic, ['relationshipDefinitions']],
})),
@@ -162,9 +163,9 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
},
],
})),
- reducers({
+ reducers(({ props }) => ({
definitionFilter: [
- null as string | null,
+ getTileString(props.initialConfig, 'definitionFilter') || null,
{
setDefinitionFilter: (_, { definitionId }) => definitionId,
},
@@ -189,7 +190,7 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
closeDeleteConfirmation: () => null,
},
],
- }),
+ })),
selectors({
canDeleteRelationships: [
(s) => [s.currentTeam],
@@ -237,6 +238,9 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
],
}),
listeners(({ actions, props, values }) => ({
+ setDefinitionFilter: () => {
+ props.onConfigChange?.({ definitionFilter: values.definitionFilter })
+ },
loadRelationshipsSuccess: () => {
if (values.currentTeamId) {
accountSidebarPropertiesLogic
diff --git a/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts b/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts
new file mode 100644
index 000000000000..4e4867063c89
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts
@@ -0,0 +1,87 @@
+import { FEATURE_FLAGS, type FeatureFlagKey } from 'lib/constants'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+import type { AccountExpansionTab } from './accountsExpansionLogic'
+
+export type AccountViewComponentKind = AccountExpansionTab
+
+export interface AccountViewComponentDefinition {
+ kind: AccountViewComponentKind
+ tagName: string
+ label: string
+ systemTabId: `system:${AccountViewComponentKind}`
+ featureFlag?: FeatureFlagKey
+}
+
+export const ACCOUNT_VIEW_COMPONENTS: AccountViewComponentDefinition[] = [
+ { kind: 'notes', tagName: 'Notes', label: 'Notes', systemTabId: 'system:notes' },
+ {
+ kind: 'tasks',
+ tagName: 'Tasks',
+ label: 'Tasks',
+ systemTabId: 'system:tasks',
+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS,
+ },
+ { kind: 'users', tagName: 'Users', label: 'Users', systemTabId: 'system:users' },
+ {
+ kind: 'relationships',
+ tagName: 'Relationships',
+ label: 'Relationships',
+ systemTabId: 'system:relationships',
+ },
+ {
+ kind: 'feature_requests',
+ tagName: 'FeatureRequests',
+ label: 'Feature requests',
+ systemTabId: 'system:feature_requests',
+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_FEATURE_REQUESTS,
+ },
+ { kind: 'usage', tagName: 'Usage', label: 'Usage', systemTabId: 'system:usage' },
+ { kind: 'spend', tagName: 'Spend', label: 'Spend', systemTabId: 'system:spend' },
+ {
+ kind: 'opportunities',
+ tagName: 'Opportunities',
+ label: 'Opportunities',
+ systemTabId: 'system:opportunities',
+ },
+ {
+ kind: 'conversations',
+ tagName: 'Conversations',
+ label: 'Conversations',
+ systemTabId: 'system:conversations',
+ },
+ {
+ kind: 'meetings',
+ tagName: 'Meetings',
+ label: 'Meetings',
+ systemTabId: 'system:meetings',
+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,
+ },
+ {
+ kind: 'event_stream',
+ tagName: 'EventStream',
+ label: 'Event stream',
+ systemTabId: 'system:event_stream',
+ featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,
+ },
+]
+
+export function listAvailableAccountViewComponents(featureFlags: FeatureFlagsSet): AccountViewComponentDefinition[] {
+ return ACCOUNT_VIEW_COMPONENTS.filter(
+ (component) => !component.featureFlag || !!featureFlags[component.featureFlag]
+ )
+}
+
+export function getAccountViewComponentByKind(
+ kind: AccountViewComponentKind
+): AccountViewComponentDefinition | undefined {
+ return ACCOUNT_VIEW_COMPONENTS.find((component) => component.kind === kind)
+}
+
+export function getAccountViewComponentByTag(tagName: string): AccountViewComponentDefinition | undefined {
+ return ACCOUNT_VIEW_COMPONENTS.find((component) => component.tagName === tagName)
+}
+
+export function getAccountViewComponentBySystemTabId(tabId: string): AccountViewComponentDefinition | undefined {
+ return ACCOUNT_VIEW_COMPONENTS.find((component) => component.systemTabId === tabId)
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountViewTileConfig.ts b/products/customer_analytics/frontend/components/Accounts/accountViewTileConfig.ts
new file mode 100644
index 000000000000..b2ce5f57e44d
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountViewTileConfig.ts
@@ -0,0 +1,22 @@
+export type AccountViewTileConfig = Record<string, unknown>
+
+export interface AccountViewTileLogicProps {
+ instanceId?: string
+ initialConfig?: AccountViewTileConfig
+ onConfigChange?: (config: AccountViewTileConfig) => void
+}
+
+export function getTileString(config: AccountViewTileConfig | undefined, key: string, fallback = ''): string {
+ const value = config?.[key]
+ return typeof value === 'string' ? value : fallback
+}
+
+export function getTileStringArray(config: AccountViewTileConfig | undefined, key: string): string[] {
+ const value = config?.[key]
+ return Array.isArray(value) && value.every((item) => typeof item === 'string') ? value : []
+}
+
+export function getTileRecord(config: AccountViewTileConfig | undefined, key: string): Record<string, unknown> | null {
+ const value = config?.[key]
+ return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index e2ae88171a5e..5702d28c1564 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -2068,7 +2068,14 @@ export const accountsLogic = kea<accountsLogicType>([
actions.restoreViewStateFromRoute(method)
openAccountByPath(accountId)
},
- [urls.customerAnalyticsAccount(':accountId', ':tab')]: ({ accountId, tab }, __, ___, { method }): void => {
+ // This is a route template, not a navigable URL. `customerAnalyticsAccount` encodes
+ // tab values for real links, so append the literal matcher segment here.
+ [`${urls.customerAnalyticsAccount(':accountId')}/:tab`]: (
+ { accountId, tab },
+ __,
+ ___,
+ { method }
+ ): void => {
actions.restoreViewStateFromRoute(method)
openAccountByPath(accountId, tab)
},
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTabContent.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTabContent.tsx
index b52d53813f72..c7a2e1916db6 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTabContent.tsx
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTabContent.tsx
@@ -1,8 +1,9 @@
import { useMountedLogic } from 'kea'
+import type { AccountViewTileLogicProps } from '../Accounts/accountViewTileConfig'
import { customerTasksLogic } from './customerTasksLogic'
import { CustomerTasksTable } from './CustomerTasksTable'
-export interface CustomerTasksTabContentProps {
+export interface CustomerTasksTabContentProps extends AccountViewTileLogicProps {
accountId: string
canCreate?: boolean
canViewAll?: boolean
@@ -13,8 +14,9 @@ export function CustomerTasksTabContent({
canCreate = false,
canViewAll = false,
embedded = true,
+ ...tileProps
}: CustomerTasksTabContentProps): JSX.Element {
- const logic = customerTasksLogic({ context: 'account', accountId })
+ const logic = customerTasksLogic({ context: 'account', accountId, ...tileProps })
useMountedLogic(logic)
return (
<CustomerTasksTable
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss
index 9ed2f869c9b2..2e80883eb356 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.scss
@@ -7,6 +7,10 @@
display: none;
}
+.CustomerTasksTable__narrow-controls {
+ display: none;
+}
+
@container (max-width: 720px) {
.CustomerTasksTable__updated,
.CustomerTasksTable__assignee {
@@ -16,4 +20,33 @@
.CustomerTasksTable__narrow-assignee {
display: block;
}
+
+ // LemonTable renders one <col> per column, so these must follow the column order in CustomerTasksTable.tsx.
+ // Account: Assignee (3) and Updated (5). Inbox adds Account at 3: Assignee (4) and Updated (6).
+ .CustomerTasksTable--account .LemonTable colgroup col:nth-child(3),
+ .CustomerTasksTable--account .LemonTable colgroup col:nth-child(5),
+ .CustomerTasksTable--inbox .LemonTable colgroup col:nth-child(4),
+ .CustomerTasksTable--inbox .LemonTable colgroup col:nth-child(6) {
+ display: none;
+ }
+}
+
+@container (max-width: 560px) {
+ .CustomerTasksTable--account {
+ // Also hides the Status (2) and Due (4) <col> elements.
+ .CustomerTasksTable__status,
+ .CustomerTasksTable__due,
+ .LemonTable colgroup col:nth-child(2),
+ .LemonTable colgroup col:nth-child(4) {
+ display: none;
+ }
+
+ .CustomerTasksTable__narrow-controls {
+ display: flex;
+ }
+
+ .LemonTable colgroup col:first-child {
+ width: auto !important;
+ }
+ }
}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx
index e3f5342d83a4..53399e194ac0 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.tsx
@@ -69,12 +69,19 @@ export function CustomerTasksTable({
<div className="CustomerTasksTable__narrow-assignee">
<CustomerTaskAssigneeSelect task={task} logic={logic} />
</div>
+ {context === 'account' && (
+ <div className="CustomerTasksTable__narrow-controls flex-wrap items-center gap-1">
+ <CustomerTaskStatusSelect task={task} logic={logic} />
+ <CustomerTaskDueAtInput task={task} logic={logic} timezone={timezone} />
+ </div>
+ )}
</div>
),
},
{
title: 'Status',
key: 'status',
+ className: 'CustomerTasksTable__status',
width: 130,
sorter: true,
render: (_, task) => <CustomerTaskStatusSelect task={task} logic={logic} />,
@@ -106,6 +113,7 @@ export function CustomerTasksTable({
{
title: 'Due',
key: 'due_at',
+ className: 'CustomerTasksTable__due',
width: 170,
sorter: true,
render: (_, task) => <CustomerTaskDueAtInput task={task} logic={logic} timezone={timezone} />,
@@ -141,7 +149,7 @@ export function CustomerTasksTable({
</div>
)
return (
- <div className="CustomerTasksTable" data-attr="customer-tasks-table">
+ <div className={`CustomerTasksTable CustomerTasksTable--${context}`} data-attr="customer-tasks-table">
<div className="mb-4 flex items-center justify-between gap-2">
<CustomerTasksFilters logic={logic} context={context} canViewAll={canViewAll} />
{canCreate && (
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
index 6ae49f560bab..ae8d4cfe2f45 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
@@ -17,7 +17,7 @@ export type CustomerTaskDueFilter = 'any' | 'overdue' | 'today' | 'upcoming' | '
export type CustomerTaskAccountFilter = { id: string; name: string }
const MAX_CUSTOMER_TASK_ASSIGNEE_ID = 2_147_483_647
-const CUSTOMER_TASK_ORDERINGS = [
+export const CUSTOMER_TASK_ORDERINGS = [
'name',
'-name',
'status',
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
index b8027ecfa7c8..19fc7b094bb5 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
@@ -47,8 +47,10 @@ import type {
PatchedCustomerTaskUpdateApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import { getTileRecord, getTileString, type AccountViewTileLogicProps } from '../Accounts/accountViewTileConfig'
import {
CUSTOMER_TASK_FILTER_URL_KEYS,
+ CUSTOMER_TASK_ORDERINGS,
CUSTOMER_TASK_URL_KEYS,
customerTaskSearchParams,
CustomerTaskEvents,
@@ -70,7 +72,7 @@ const ACCOUNT_PAGE_SIZE = 20
const INBOX_PAGE_SIZE = 50
const ACCOUNT_OPTIONS_LIMIT = 50
-export interface CustomerTasksLogicProps {
+export interface CustomerTasksLogicProps extends AccountViewTileLogicProps {
context: CustomerTasksContext
accountId?: string
canViewAll?: boolean
@@ -143,6 +145,21 @@ export type customerTasksLogicType = MakeLogicType<
CustomerTasksLogicProps
>
+function getInitialFilters(props: CustomerTasksLogicProps): CustomerTaskFilters {
+ const defaults = defaultCustomerTaskFilters(props.context)
+ const saved = props.context === 'account' ? getTileRecord(props.initialConfig, 'filters') : null
+ return saved ? ({ ...defaults, ...saved, account: null } as CustomerTaskFilters) : defaults
+}
+
+function getInitialOrdering(props: CustomerTasksLogicProps): CustomerTaskOrdering {
+ const ordering = getTileString(props.initialConfig, 'ordering')
+ return CUSTOMER_TASK_ORDERINGS.find((candidate) => candidate === ordering) ?? DEFAULT_CUSTOMER_TASK_ORDERING
+}
+
+function taskConfig(values: customerTasksLogicValues): Record<string, unknown> {
+ return { filters: { ...values.filters, account: null }, ordering: values.ordering }
+}
+
function taskUrlState(values: customerTasksLogicValues): CustomerTaskUrlState {
return { filters: values.filters, ordering: values.ordering, page: values.page }
}
@@ -163,7 +180,15 @@ function taskWriteFailureMessage(error: unknown, fallback: string): string {
export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<customerTasksLogicType>([
props({} as CustomerTasksLogicProps),
- key((p) => 'customer-tasks-' + p.context + '-' + (p.accountId ?? p.persistPrefix ?? 'all')),
+ key(
+ (p) =>
+ 'customer-tasks-' +
+ p.context +
+ '-' +
+ (p.accountId ?? p.persistPrefix ?? 'all') +
+ '-' +
+ (p.instanceId ?? 'default')
+ ),
path(['products', 'customer_analytics', 'frontend', 'components', 'CustomerTasks', 'customerTasksLogic']),
connect(() => ({ values: [teamLogic, ['currentTeamId', 'timezone'], userLogic, ['user']] })),
actions({
@@ -246,7 +271,7 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
props.context === 'inbox' && props.persistPrefix ? { persist: true, prefix: props.persistPrefix } : {}
return {
filters: [
- defaultCustomerTaskFilters(props.context),
+ getInitialFilters(props),
persist,
{
setFilters: (s: CustomerTaskFilters, a: { filters: Partial<CustomerTaskFilters> }) => ({
@@ -265,7 +290,7 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
},
],
ordering: [
- DEFAULT_CUSTOMER_TASK_ORDERING,
+ getInitialOrdering(props),
{
setTaskOrdering: (_, { ordering }) => ordering,
setFiltersFromUrl: (_: CustomerTaskOrdering, a: { state: CustomerTaskUrlState }) =>
@@ -409,7 +434,10 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
)
}
},
- setFilters: () => actions.loadTaskPage(),
+ setFilters: () => {
+ props.onConfigChange?.(taskConfig(values))
+ actions.loadTaskPage()
+ },
setFiltersFromUrl: async () => {
actions.loadTaskPage()
const account = values.filters.account
@@ -425,17 +453,27 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
// The account filter still applies; the control falls back to its generic label.
}
},
- setSearch: () => actions.loadTaskPage(),
+ setSearch: async (_, breakpoint) => {
+ await breakpoint(300)
+ props.onConfigChange?.(taskConfig(values))
+ actions.loadTaskPage()
+ },
setAccountFilter: () => actions.loadTaskPage(),
setPage: () => actions.loadTaskPage(),
- setTaskOrdering: () => actions.loadTaskPage(),
+ setTaskOrdering: () => {
+ props.onConfigChange?.(taskConfig(values))
+ actions.loadTaskPage()
+ },
setTaskSorting: ({ sorting }) => {
const ordering = customerTaskSortingToOrdering(sorting)
if (ordering) {
actions.setTaskOrdering(ordering)
}
},
- resetFilters: () => actions.loadTaskPage(),
+ resetFilters: () => {
+ props.onConfigChange?.(taskConfig(values))
+ actions.loadTaskPage()
+ },
openCreateModal: () => {
if (props.context === 'inbox' && values.filters.assignee === 'me' && values.user) {
actions.setDraftAssignedTo({
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx
index 52fcd9557c09..c016de8b13fb 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx
@@ -1,25 +1,38 @@
import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { resetContext } from 'kea'
-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { AccountDetailActions } from './AccountDetailActions'
+import { accountViewsLogic } from './accountViewsLogic'
-jest.mock('lib/lemon-ui/LemonDialog', () => ({ LemonDialog: { open: jest.fn() } }))
+jest.mock('../../generated/api', () => ({ accountViewsList: jest.fn().mockResolvedValue([]) }))
describe('AccountDetailActions', () => {
- beforeEach(jest.clearAllMocks)
- afterEach(cleanup)
+ beforeEach(() => {
+ resetContext()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]: true,
+ })
+ })
- it.each(['Configure tabs', 'Add view'])('opens a work-in-progress dialog for %s', (title) => {
- render(<AccountDetailActions />)
+ afterEach(() => {
+ cleanup()
+ featureFlagLogic.unmount()
+ })
- fireEvent.click(screen.getByText(title))
+ it('opens the personal account view editor', () => {
+ const logic = accountViewsLogic({ projectId: 1 })
+ logic.mount()
+ render(<AccountDetailActions projectId={1} />)
- expect(LemonDialog.open).toHaveBeenCalledWith({
- title,
- content: 'This feature is a work in progress.',
- })
+ fireEvent.click(screen.getByText('New view'))
+
+ expect(logic.values.editorOpen).toBe(true)
+ logic.unmount()
})
})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx
index c6012d1ba618..495d7b474b62 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx
@@ -1,29 +1,34 @@
-import { IconGear, IconPlus } from '@posthog/icons'
+import { useActions, useValues } from 'kea'
+
+import { IconPlus } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
-import { openAccountDetailWorkInProgress } from './accountDetailWorkInProgress'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { accountViewsLogic } from './accountViewsLogic'
+
+interface AccountDetailActionsProps {
+ projectId: number
+}
+
+export function AccountDetailActions({ projectId }: AccountDetailActionsProps): JSX.Element | null {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { openCreateEditor } = useActions(accountViewsLogic({ projectId }))
+
+ if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]) {
+ return null
+ }
-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>
- </>
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconPlus />}
+ data-attr="account-detail-add-view"
+ onClick={openCreateEditor}
+ >
+ New view
+ </LemonButton>
)
}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailNavigation.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailNavigation.tsx
new file mode 100644
index 000000000000..5f71b8156ca2
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailNavigation.tsx
@@ -0,0 +1,101 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+
+import { IconPencil } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonSkeleton, LemonTabs } from '@posthog/lemon-ui'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { accountBillingLogic } from '../../components/Accounts/accountBillingLogic'
+import { AccountViewComponent } from '../../components/Accounts/AccountViewComponent'
+import { listAvailableAccountViewComponents } from '../../components/Accounts/accountViewComponents'
+import { AccountViewRenderer } from './AccountViewRenderer'
+import { accountViewsLogic } from './accountViewsLogic'
+
+interface AccountDetailNavigationProps {
+ projectId: number
+ accountId: string
+ externalId: string
+ requestedTab: string
+ onChange: (tab: string) => void
+}
+
+export function AccountDetailNavigation({
+ projectId,
+ accountId,
+ externalId,
+ requestedTab,
+ onChange,
+}: AccountDetailNavigationProps): JSX.Element {
+ useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'usage' }))
+ const { featureFlags } = useValues(featureFlagLogic)
+ const logic = accountViewsLogic({ projectId })
+ const { views, viewsError, viewsLoading } = useValues(logic)
+ const { openEditEditor, loadViews } = useActions(logic)
+ const accountViewsEnabled = !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]
+ const systemTabs = listAvailableAccountViewComponents(featureFlags)
+ const selectedViewId =
+ accountViewsEnabled && requestedTab.startsWith('view:') ? requestedTab.slice('view:'.length) : null
+ const selectedView = selectedViewId ? views.find((view) => view.id === selectedViewId) : undefined
+ const selectedSystemTab = systemTabs.find((tab) => tab.kind === requestedTab) ?? systemTabs[0]
+ const activeKey = selectedViewId ? `view:${selectedViewId}` : selectedSystemTab?.kind
+ const loadingView = !!selectedViewId && !selectedView && viewsLoading
+
+ return (
+ <div className="min-w-0">
+ {viewsError && accountViewsEnabled ? (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadViews }} className="mb-2">
+ Couldn't load account views. System tabs are still available.
+ </LemonBanner>
+ ) : null}
+ <div className="sticky top-0 z-10 bg-primary">
+ <LemonTabs
+ activeKey={activeKey}
+ onChange={onChange}
+ rightSlotClassName="pr-0"
+ size="small"
+ rightSlot={
+ selectedView ? (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconPencil />}
+ onClick={() => openEditEditor(selectedView)}
+ data-attr="account-view-edit"
+ >
+ Edit view
+ </LemonButton>
+ ) : undefined
+ }
+ tabs={[
+ ...systemTabs.map((tab) => ({ key: tab.kind, label: tab.label })),
+ ...(accountViewsEnabled
+ ? views.map((view) => ({ key: `view:${view.id}`, label: view.name }))
+ : []),
+ ]}
+ />
+ </div>
+ {loadingView ? (
+ <LemonSkeleton className="my-3 h-40" />
+ ) : selectedView ? (
+ <AccountViewRenderer
+ view={selectedView}
+ projectId={projectId}
+ accountId={accountId}
+ externalId={externalId}
+ />
+ ) : selectedViewId && !viewsError ? (
+ <LemonBanner type="warning" className="my-3">
+ This view was deleted or you no longer have access to it. Choose another tab.
+ </LemonBanner>
+ ) : selectedSystemTab ? (
+ <AccountViewComponent
+ kind={selectedSystemTab.kind}
+ accountId={accountId}
+ externalId={externalId}
+ embedded={false}
+ />
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorComponentItem.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorComponentItem.tsx
new file mode 100644
index 000000000000..667af1f9fb77
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorComponentItem.tsx
@@ -0,0 +1,73 @@
+import { useSortable } from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
+
+import { IconCopy, IconTrash } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { SortableDragIcon } from 'lib/lemon-ui/icons'
+
+import type { AccountViewComponentInstance } from './accountViewDocument'
+
+interface AccountViewEditorComponentItemProps {
+ component: AccountViewComponentInstance
+ label: string
+ disabled: boolean
+ onDuplicate: () => void
+ onRemove: () => void
+}
+
+export function AccountViewEditorComponentItem({
+ component,
+ label,
+ disabled,
+ onDuplicate,
+ onRemove,
+}: AccountViewEditorComponentItemProps): JSX.Element {
+ const { setNodeRef, attributes, listeners, transform, transition, isDragging } = useSortable({
+ id: component.nodeId,
+ disabled,
+ })
+
+ return (
+ <div
+ ref={setNodeRef}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ transform: CSS.Transform.toString(transform), transition }}
+ className={`flex flex-wrap items-center gap-2 rounded border bg-surface-primary p-2 ${
+ isDragging ? 'opacity-50' : ''
+ }`}
+ data-attr="account-view-editor-component"
+ >
+ <button
+ type="button"
+ className={`flex items-center text-secondary ${
+ disabled ? 'cursor-not-allowed' : 'cursor-grab active:cursor-grabbing'
+ }`}
+ aria-label={`Reorder ${label}`}
+ disabled={disabled}
+ {...attributes}
+ {...listeners}
+ >
+ <SortableDragIcon />
+ </button>
+ <span className="min-w-32 flex-1 font-medium">{label}</span>
+ <div className="flex items-center gap-1">
+ <LemonButton
+ size="xsmall"
+ icon={<IconCopy />}
+ aria-label={`Duplicate ${label}`}
+ onClick={onDuplicate}
+ disabledReason={disabled ? 'Saving changes' : undefined}
+ />
+ <LemonButton
+ size="xsmall"
+ status="danger"
+ icon={<IconTrash />}
+ aria-label={`Remove ${label}`}
+ onClick={onRemove}
+ disabledReason={disabled ? 'Saving changes' : undefined}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.tsx
new file mode 100644
index 000000000000..fc17d2f18d98
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.tsx
@@ -0,0 +1,180 @@
+import { DndContext } from '@dnd-kit/core'
+import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'
+import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
+import { useActions, useValues } from 'kea'
+
+import { IconTrash } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonDialog,
+ LemonInput,
+ LemonLabel,
+ LemonModal,
+ LemonSelect,
+ LemonTag,
+} from '@posthog/lemon-ui'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import {
+ getAccountViewComponentByKind,
+ listAvailableAccountViewComponents,
+ type AccountViewComponentKind,
+} from '../../components/Accounts/accountViewComponents'
+import { AccountViewEditorComponentItem } from './AccountViewEditorComponentItem'
+import { accountViewsLogic } from './accountViewsLogic'
+
+interface AccountViewEditorModalProps {
+ projectId: number
+}
+
+export function AccountViewEditorModal({ projectId }: AccountViewEditorModalProps): JSX.Element {
+ const logic = accountViewsLogic({ projectId })
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { editorOpen, editorDraft, editorSaving, editorConflict, editingView } = useValues(logic)
+ const {
+ setEditorOpen,
+ setEditorName,
+ addEditorComponent,
+ duplicateEditorComponent,
+ removeEditorComponent,
+ reorderEditorComponent,
+ saveEditor,
+ reloadEditor,
+ deleteView,
+ } = useActions(logic)
+ const availableComponents = listAvailableAccountViewComponents(featureFlags)
+ const saveDisabledReason = !editorDraft.name.trim()
+ ? 'Enter a view name'
+ : editorDraft.components.length === 0
+ ? 'Add at least one component'
+ : undefined
+
+ const confirmDelete = (): void => {
+ if (!editingView) {
+ return
+ }
+ LemonDialog.open({
+ title: `Delete "${editingView.name}"?`,
+ description: 'This removes the view from your account tabs.',
+ primaryButton: {
+ children: 'Delete view',
+ status: 'danger',
+ onClick: () => deleteView(editingView.id, editingView.version),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+
+ return (
+ <LemonModal
+ isOpen={editorOpen}
+ onClose={() => setEditorOpen(false)}
+ title={editingView ? 'Edit view' : 'Add view'}
+ width={640}
+ footer={
+ <>
+ {editingView ? (
+ <LemonButton
+ status="danger"
+ type="secondary"
+ icon={<IconTrash />}
+ onClick={confirmDelete}
+ loading={editorSaving}
+ disabledReason={editorSaving ? 'Saving changes' : undefined}
+ className="mr-auto"
+ data-attr="account-view-delete"
+ >
+ Delete view
+ </LemonButton>
+ ) : null}
+ <LemonButton type="secondary" onClick={() => setEditorOpen(false)}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={saveEditor}
+ loading={editorSaving}
+ disabledReason={saveDisabledReason}
+ data-attr="account-view-save"
+ >
+ {editingView ? 'Save changes' : 'Create view'}
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-4">
+ {editorConflict ? (
+ <LemonBanner type="warning" action={{ children: 'Reload view', onClick: reloadEditor }}>
+ This view changed since you opened it. Reload the latest version before saving.
+ </LemonBanner>
+ ) : null}
+ <div className="flex flex-col gap-1">
+ <LemonLabel htmlFor="account-view-name">View name</LemonLabel>
+ <LemonInput
+ id="account-view-name"
+ value={editorDraft.name}
+ onChange={setEditorName}
+ placeholder="Account overview"
+ autoFocus
+ data-attr="account-view-name"
+ />
+ </div>
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="flex min-w-56 flex-1 flex-col gap-1">
+ <LemonLabel>Components</LemonLabel>
+ <LemonSelect<AccountViewComponentKind>
+ value={null}
+ allowClear
+ onChange={(kind) => kind && addEditorComponent(kind)}
+ options={availableComponents.map((component) => ({
+ value: component.kind,
+ label: component.label,
+ }))}
+ placeholder="Choose a component"
+ />
+ </div>
+ <LemonTag type="muted">{editorDraft.components.length} added</LemonTag>
+ </div>
+ <div className="flex flex-col gap-2">
+ {editorDraft.components.length === 0 ? (
+ <div className="rounded border border-dashed p-4 text-center text-secondary">
+ Add the account sections you want to show in this view.
+ </div>
+ ) : (
+ <DndContext
+ onDragEnd={({ active, over }) => {
+ if (over) {
+ reorderEditorComponent(String(active.id), String(over.id))
+ }
+ }}
+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}
+ >
+ <SortableContext
+ items={editorDraft.components.map((component) => component.nodeId)}
+ strategy={verticalListSortingStrategy}
+ >
+ <div className="flex flex-col gap-2">
+ {editorDraft.components.map((component) => {
+ const definition = getAccountViewComponentByKind(component.kind)
+ return (
+ <AccountViewEditorComponentItem
+ key={component.nodeId}
+ component={component}
+ label={component.title ?? definition?.label ?? component.kind}
+ disabled={editorSaving}
+ onDuplicate={() => duplicateEditorComponent(component.nodeId)}
+ onRemove={() => removeEditorComponent(component.nodeId)}
+ />
+ )
+ })}
+ </div>
+ </SortableContext>
+ </DndContext>
+ )}
+ </div>
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.test.tsx
new file mode 100644
index 000000000000..b3948ccf9a8a
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.test.tsx
@@ -0,0 +1,84 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { resetContext } from 'kea'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import type { AccountViewApi } from '../../generated/api.schemas'
+import { createAccountViewContent } from './accountViewDocument'
+import { AccountViewRenderer } from './AccountViewRenderer'
+import { accountViewsLogic } from './accountViewsLogic'
+
+jest.mock('./AccountViewTile', () => {
+ const React = jest.requireActual<typeof import('react')>('react')
+
+ return {
+ AccountViewTile: ({ component }: { component: { config?: { searchTerm?: string } } }) => {
+ const [mountedSearchTerm] = React.useState(component.config?.searchTerm)
+ return React.createElement('span', { 'data-attr': 'mounted-search-term' }, mountedSearchTerm)
+ },
+ }
+})
+
+function createView(searchTerm: string): AccountViewApi {
+ return {
+ id: '11111111-2222-4333-8444-555555555555',
+ name: 'Account view',
+ visibility: 'private',
+ content: createAccountViewContent([
+ {
+ nodeId: 'tile-1',
+ kind: 'notes',
+ config: { searchTerm },
+ },
+ ]),
+ text_content: '',
+ version: 1,
+ created_by: 1,
+ last_modified_by: 1,
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ }
+}
+
+describe('AccountViewRenderer', () => {
+ beforeEach(() => {
+ resetContext()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ })
+
+ afterEach(() => {
+ cleanup()
+ featureFlagLogic.unmount()
+ })
+
+ it('remounts a tile only after a failed save reloads persisted config at the same version', () => {
+ const { rerender } = render(
+ <AccountViewRenderer
+ view={createView('optimistic')}
+ projectId={1}
+ accountId="account-1"
+ externalId="external-account-1"
+ />
+ )
+
+ expect(screen.getByTestId('mounted-search-term')).toHaveTextContent('optimistic')
+
+ rerender(
+ <AccountViewRenderer
+ view={createView('persisted')}
+ projectId={1}
+ accountId="account-1"
+ externalId="external-account-1"
+ />
+ )
+
+ expect(screen.getByTestId('mounted-search-term')).toHaveTextContent('optimistic')
+ act(() =>
+ accountViewsLogic({ projectId: 1 }).actions.resetViewComponentConfig('11111111-2222-4333-8444-555555555555')
+ )
+ expect(screen.getByTestId('mounted-search-term')).toHaveTextContent('persisted')
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.tsx
new file mode 100644
index 000000000000..317eb38c3ef6
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.tsx
@@ -0,0 +1,39 @@
+import { useValues } from 'kea'
+
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { listAvailableAccountViewComponents } from '../../components/Accounts/accountViewComponents'
+import type { AccountViewApi } from '../../generated/api.schemas'
+import { parseAccountViewContent } from './accountViewDocument'
+import { accountViewsLogic } from './accountViewsLogic'
+import { AccountViewTile } from './AccountViewTile'
+
+interface AccountViewRendererProps {
+ view: AccountViewApi
+ accountId: string
+ externalId: string
+ projectId: number
+}
+
+export function AccountViewRenderer({ view, accountId, externalId, projectId }: AccountViewRendererProps): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const { tileConfigReloads } = useValues(accountViewsLogic({ projectId }))
+ const availableKinds = new Set(listAvailableAccountViewComponents(featureFlags).map((component) => component.kind))
+ const components = parseAccountViewContent(view.content).filter((component) => availableKinds.has(component.kind))
+
+ return (
+ <div className="flex flex-col gap-3 py-3" data-attr="account-view-content">
+ {components.map((component) => (
+ <AccountViewTile
+ key={`${component.nodeId}:${tileConfigReloads[view.id] ?? 0}`}
+ view={view}
+ component={component}
+ componentCount={components.length}
+ projectId={projectId}
+ accountId={accountId}
+ externalId={externalId}
+ />
+ ))}
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx
new file mode 100644
index 000000000000..9ff44477839c
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx
@@ -0,0 +1,98 @@
+import { useActions, useValues } from 'kea'
+
+import { IconEllipsis, IconPencil, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonCard, LemonDialog, LemonMenu, type LemonMenuItems } from '@posthog/lemon-ui'
+
+import { AccountViewComponent } from '../../components/Accounts/AccountViewComponent'
+import { getAccountViewComponentByKind } from '../../components/Accounts/accountViewComponents'
+import type { AccountViewApi } from '../../generated/api.schemas'
+import type { AccountViewComponentInstance } from './accountViewDocument'
+import { accountViewsLogic } from './accountViewsLogic'
+
+interface AccountViewTileProps {
+ view: AccountViewApi
+ component: AccountViewComponentInstance
+ componentCount: number
+ projectId: number
+ accountId: string
+ externalId: string
+}
+
+export function AccountViewTile({
+ view,
+ component,
+ componentCount,
+ projectId,
+ accountId,
+ externalId,
+}: AccountViewTileProps): JSX.Element {
+ const logic = accountViewsLogic({ projectId })
+ const { tileSaving, tileConfigReloads } = useValues(logic)
+ const { openTileEditor, removeViewComponent, updateViewComponentConfig } = useActions(logic)
+ const title = component.title ?? getAccountViewComponentByKind(component.kind)?.label ?? component.kind
+ const menuDisabledReason = tileSaving ? 'Saving changes' : undefined
+
+ const confirmRemove = (): void => {
+ LemonDialog.open({
+ title: `Remove "${title}" from view?`,
+ description: 'This removes the tile from this view.',
+ primaryButton: {
+ children: 'Remove from view',
+ status: 'danger',
+ onClick: () => removeViewComponent(view.id, component.nodeId),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+
+ const items: LemonMenuItems = [
+ {
+ items: [
+ {
+ label: 'Edit',
+ icon: <IconPencil />,
+ onClick: () => openTileEditor(view.id, component.nodeId, title),
+ disabledReason: menuDisabledReason,
+ },
+ {
+ label: 'Remove from view',
+ icon: <IconTrash />,
+ status: 'danger',
+ onClick: confirmRemove,
+ disabledReason:
+ menuDisabledReason ?? (componentCount === 1 ? 'A view needs at least one tile' : undefined),
+ },
+ ],
+ },
+ ]
+
+ return (
+ <LemonCard hoverEffect={false} className="min-w-0 overflow-hidden p-0">
+ <div className="flex items-center gap-2 border-b px-2 py-1">
+ <span className="min-w-0 flex-1 truncate text-xs font-medium text-secondary">{title}</span>
+ <LemonMenu items={items}>
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ icon={<IconEllipsis />}
+ loading={tileSaving}
+ disabledReason={menuDisabledReason}
+ aria-label="Tile actions"
+ data-attr="account-view-tile-actions"
+ />
+ </LemonMenu>
+ </div>
+ <div className="min-w-0 px-2 pt-2 pb-0 [&_.LemonTable]:-mx-2 [&_.LemonTable]:!w-[calc(100%+1rem)]">
+ <AccountViewComponent
+ kind={component.kind}
+ accountId={accountId}
+ externalId={externalId}
+ instanceId={`${component.nodeId}:${tileConfigReloads[view.id] ?? 0}`}
+ initialConfig={component.config}
+ onConfigChange={(config) => updateViewComponentConfig(view.id, component.nodeId, config)}
+ embedded
+ />
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTileEditorModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTileEditorModal.tsx
new file mode 100644
index 000000000000..846e71b468b4
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTileEditorModal.tsx
@@ -0,0 +1,65 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonInput, LemonLabel, LemonModal } from '@posthog/lemon-ui'
+
+import { accountViewsLogic } from './accountViewsLogic'
+
+interface AccountViewTileEditorModalProps {
+ projectId: number
+}
+
+export function AccountViewTileEditorModal({ projectId }: AccountViewTileEditorModalProps): JSX.Element {
+ const logic = accountViewsLogic({ projectId })
+ const { tileEditor, tileSaving } = useValues(logic)
+ const { closeTileEditor, saveTileEditor, setTileEditorName } = useActions(logic)
+ const saveDisabledReason = tileSaving
+ ? 'Saving changes'
+ : !tileEditor?.name.trim()
+ ? 'Enter a tile name'
+ : undefined
+
+ return (
+ <LemonModal
+ isOpen={tileEditor !== null}
+ onClose={() => {
+ if (!tileSaving) {
+ closeTileEditor()
+ }
+ }}
+ title="Edit tile"
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={closeTileEditor}
+ disabledReason={tileSaving ? 'Saving changes' : undefined}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ onClick={saveTileEditor}
+ loading={tileSaving}
+ disabledReason={saveDisabledReason}
+ data-attr="account-view-tile-save"
+ >
+ Save changes
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="flex flex-col gap-1">
+ <LemonLabel htmlFor="account-view-tile-name">Tile name</LemonLabel>
+ <LemonInput
+ id="account-view-tile-name"
+ value={tileEditor?.name ?? ''}
+ onChange={setTileEditorName}
+ onPressEnter={tileSaving ? undefined : saveTileEditor}
+ autoFocus
+ maxLength={400}
+ data-attr="account-view-tile-name"
+ />
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
index 1dae724fa6ec..4991a94054a6 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
@@ -18,9 +18,35 @@ const ACCOUNT_ICON_ENDPOINT = 'api/projects/:team_id/accounts/icon/'
const VALUES_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/custom_property_values/'
const ASSIGNMENTS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/relationships/'
const ACCOUNT_SIDEBAR_CONFIG_ENDPOINT = 'api/projects/:team_id/user_customer_analytics_config/@me/'
+const ACCOUNT_VIEWS_ENDPOINT = 'api/projects/:team_id/account_views/'
+const ACCOUNT_VIEW_ID = '77777777-8888-4999-8aaa-bbbbbbbbbbbb'
const CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/custom_property_definitions/'
const RELATIONSHIP_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/account_relationship_definitions/'
+const accountView = {
+ id: ACCOUNT_VIEW_ID,
+ name: 'Account workspace',
+ visibility: 'private',
+ content: {
+ type: 'doc',
+ content: [
+ {
+ type: 'ph-markdown-notebook',
+ attrs: {
+ nodeId: 'markdown-notebook-v2',
+ markdown: '<Notes nodeId="notes" />\n\n<Relationships nodeId="relationships" />',
+ },
+ },
+ ],
+ },
+ text_content: 'Notes\nRelationships',
+ version: 1,
+ created_by: 1,
+ last_modified_by: 1,
+ created_at: '2026-05-10T10:00:00Z',
+ updated_at: '2026-05-20T14:30:00Z',
+}
+
const account = {
id: ACCOUNT_ID,
name: 'Example Labs',
@@ -77,8 +103,9 @@ const meta: Meta = {
FEATURE_FLAGS.CUSTOMER_ANALYTICS,
FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,
FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_SCENE,
+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS,
],
- pageUrl: urls.customerAnalyticsAccount(ACCOUNT_ID),
+ pageUrl: urls.customerAnalyticsAccount(ACCOUNT_ID, `view:${ACCOUNT_VIEW_ID}`),
testOptions: {
waitForSelector: [
'[data-attr="customer-analytics-account-scene"]',
@@ -103,6 +130,7 @@ const meta: Meta = {
{ headers: { 'Content-Type': 'image/svg+xml' } }
),
[ACCOUNT_SIDEBAR_CONFIG_ENDPOINT]: { pinned_properties: [] },
+ [ACCOUNT_VIEWS_ENDPOINT]: [accountView],
[VALUES_ENDPOINT]: [],
[ASSIGNMENTS_ENDPOINT]: [],
[CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT]: {
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
index 9995c77f23d8..0aa15fd8351b 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
@@ -15,14 +15,16 @@ 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 { AccountDetailNavigation } from './AccountDetailNavigation'
import { AccountPresence } from './AccountPresence'
import { AccountSidebar } from './AccountSidebar'
+import { AccountViewEditorModal } from './AccountViewEditorModal'
+import { AccountViewTileEditorModal } from './AccountViewTileEditorModal'
import {
CustomerAnalyticsAccountSceneLogicProps,
customerAnalyticsAccountSceneLogic,
@@ -86,10 +88,11 @@ export function CustomerAnalyticsAccountScene(): JSX.Element {
}
function CustomerAnalyticsAccountSceneContent(): JSX.Element {
- const { account, accountLoadError, accountLoading, activeTab, isAccountMissing } = useValues(
+ const { account, accountLoadError, accountLoading, requestedTab, isAccountMissing } = useValues(
customerAnalyticsAccountSceneLogic
)
const { loadAccount, setActiveTab } = useActions(customerAnalyticsAccountSceneLogic)
+ const projectId = getCurrentTeamIdOrNone()
if (isAccountMissing) {
return <NotFound object="account" />
@@ -130,28 +133,36 @@ function CustomerAnalyticsAccountSceneContent(): JSX.Element {
actions={
<>
<AccountPresence />
- <AccountDetailActions />
+ {projectId ? <AccountDetailActions projectId={projectId} /> : null}
</>
}
/>
<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="@container/account-detail flex flex-1 min-h-0 overflow-y-auto -mt-4 -mr-4 [scrollbar-gutter:stable] @min-[60rem]:-ml-4 @min-[60rem]:[scrollbar-gutter:auto]">
<div className="flex min-h-full w-full flex-col gap-4 @min-[60rem]/account-detail:h-full @min-[60rem]/account-detail:min-h-0 @min-[60rem]/account-detail:flex-row">
<AccountSidebar account={account} />
<main
- className="flex-1 min-w-0 @min-[60rem]/account-detail:h-full @min-[60rem]/account-detail:min-h-0 @min-[60rem]/account-detail:overflow-y-auto"
+ className="flex-1 min-w-0 @min-[60rem]/account-detail:h-full @min-[60rem]/account-detail:min-h-0 @min-[60rem]/account-detail:overflow-y-auto @min-[60rem]/account-detail:[scrollbar-gutter:stable]"
data-attr="account-detail-tabs"
>
- <AccountDetailTabs
- accountId={account.id}
- externalId={account.external_id ?? ''}
- activeTab={activeTab}
- onChange={setActiveTab}
- embedded={false}
- />
+ {projectId ? (
+ <AccountDetailNavigation
+ projectId={projectId}
+ accountId={account.id}
+ externalId={account.external_id ?? ''}
+ requestedTab={requestedTab}
+ onChange={setActiveTab}
+ />
+ ) : null}
</main>
</div>
</div>
+ {projectId ? (
+ <>
+ <AccountViewEditorModal projectId={projectId} />
+ <AccountViewTileEditorModal projectId={projectId} />
+ </>
+ ) : null}
</SceneContent>
)
}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewDocument.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewDocument.ts
new file mode 100644
index 000000000000..83066b1318a3
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewDocument.ts
@@ -0,0 +1,94 @@
+import { v4 as uuidv4 } from 'uuid'
+
+import { parseMarkdownNotebook, serializeMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'
+import type {
+ NotebookComponentBlockNode,
+ NotebookDocument,
+ NotebookPropValue,
+} from 'lib/components/MarkdownNotebook/types'
+
+import {
+ getAccountViewComponentByKind,
+ getAccountViewComponentByTag,
+ type AccountViewComponentKind,
+} from '../../components/Accounts/accountViewComponents'
+import type { AccountViewTileConfig } from '../../components/Accounts/accountViewTileConfig'
+import type { AccountViewContentApi } from '../../generated/api.schemas'
+import { AccountViewContentTypeEnumApi, AccountViewMarkdownNodeTypeEnumApi } from '../../generated/api.schemas'
+
+export interface AccountViewComponentInstance {
+ nodeId: string
+ kind: AccountViewComponentKind
+ title?: string
+ config?: AccountViewTileConfig
+}
+
+export function createAccountViewComponentInstance(kind: AccountViewComponentKind): AccountViewComponentInstance {
+ return { nodeId: uuidv4(), kind }
+}
+
+export function parseAccountViewContent(content: AccountViewContentApi): AccountViewComponentInstance[] {
+ const markdown = content.content[0]?.attrs.markdown ?? ''
+ return parseMarkdownNotebook(markdown).nodes.flatMap((node) => {
+ if (node.type !== 'component') {
+ return []
+ }
+ const definition = getAccountViewComponentByTag(node.tagName)
+ const nodeId = node.props.nodeId
+ const title = node.props.title
+ const config = node.props.config
+ if (!definition || typeof nodeId !== 'string') {
+ return []
+ }
+ return [
+ {
+ nodeId,
+ kind: definition.kind,
+ title: typeof title === 'string' && title.trim() ? title : undefined,
+ config:
+ config && typeof config === 'object' && !Array.isArray(config)
+ ? (config as AccountViewTileConfig)
+ : undefined,
+ },
+ ]
+ })
+}
+
+export function createAccountViewContent(components: AccountViewComponentInstance[]): AccountViewContentApi {
+ const document: NotebookDocument = {
+ type: 'doc',
+ errors: [],
+ nodes: components.map(
+ (component): NotebookComponentBlockNode => ({
+ id: component.nodeId,
+ type: 'component',
+ tagName: getTagName(component.kind),
+ props: {
+ nodeId: component.nodeId,
+ ...(component.title ? { title: component.title } : {}),
+ ...(component.config ? { config: component.config as NotebookPropValue } : {}),
+ },
+ })
+ ),
+ }
+ return {
+ type: AccountViewContentTypeEnumApi.Doc,
+ content: [
+ {
+ type: AccountViewMarkdownNodeTypeEnumApi.PhMarkdownNotebook,
+ attrs: {
+ nodeId: 'markdown-notebook-v2',
+ markdown: serializeMarkdownNotebook(document),
+ },
+ },
+ ],
+ }
+}
+
+function getTagName(kind: AccountViewComponentKind): string {
+ const definition = getAccountViewComponentByKind(kind)
+ if (!definition) {
+ throw new Error(`Unknown account view component: ${kind}`)
+ }
+ return definition.tagName
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts
new file mode 100644
index 000000000000..abe9eb947bdc
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts
@@ -0,0 +1,607 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import { ApiError } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+
+import type { AccountExpansionTab } from '../../components/Accounts/accountsExpansionLogic'
+import type { AccountViewComponentKind } from '../../components/Accounts/accountViewComponents'
+import type { AccountViewTileConfig } from '../../components/Accounts/accountViewTileConfig'
+import {
+ accountViewsCreate,
+ accountViewsDestroy,
+ accountViewsList,
+ accountViewsPartialUpdate,
+ accountViewsRetrieve,
+} from '../../generated/api'
+import type { AccountViewApi, AccountViewContentApi } from '../../generated/api.schemas'
+import {
+ createAccountViewContent,
+ createAccountViewComponentInstance,
+ parseAccountViewContent,
+ type AccountViewComponentInstance,
+} from './accountViewDocument'
+
+export interface AccountViewsLogicProps {
+ projectId: number
+}
+
+export interface AccountViewEditorDraft {
+ name: string
+ components: AccountViewComponentInstance[]
+}
+
+export interface AccountViewTileEditor {
+ viewId: string
+ nodeId: string
+ name: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountViewsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ editingView: AccountViewApi | null
+ editingViewId: string | null
+ editorConflict: boolean
+ editorDraft: AccountViewEditorDraft
+ editorOpen: boolean
+ editorSaving: boolean
+ tileConfigReloads: Record<string, number>
+ tileEditor: AccountViewTileEditor | null
+ tileSaving: boolean
+ views: AccountViewApi[]
+ viewsError: unknown
+ viewsLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountViewsLogicActions {
+ setFeatureFlags: (
+ flags: string[],
+ variants: Record<string, boolean | string>
+ ) => {
+ flags: string[]
+ variants: Record<string, boolean | string>
+ } // featureFlagLogic
+ addEditorComponent: (kind: AccountViewComponentKind) => {
+ kind: AccountExpansionTab
+ }
+ closeTileEditor: () => {
+ value: true
+ }
+ deleteView: (
+ viewId: string,
+ version: number
+ ) => {
+ version: number
+ viewId: string
+ }
+ deleteViewFailure: () => {
+ value: true
+ }
+ deleteViewSuccess: (viewId: string) => {
+ viewId: string
+ }
+ duplicateEditorComponent: (nodeId: string) => {
+ nodeId: string
+ }
+ loadViews: () => {
+ value: true
+ }
+ loadViewsFailure: (error: unknown) => {
+ error: unknown
+ }
+ loadViewsSuccess: (views: AccountViewApi[]) => {
+ views: AccountViewApi[]
+ }
+ openCreateEditor: () => {
+ value: true
+ }
+ openEditEditor: (view: AccountViewApi) => {
+ view: AccountViewApi
+ }
+ openTileEditor: (
+ viewId: string,
+ nodeId: string,
+ name: string
+ ) => {
+ name: string
+ nodeId: string
+ viewId: string
+ }
+ reloadEditor: () => {
+ value: true
+ }
+ removeEditorComponent: (nodeId: string) => {
+ nodeId: string
+ }
+ removeViewComponent: (
+ viewId: string,
+ nodeId: string
+ ) => {
+ nodeId: string
+ viewId: string
+ }
+ reorderEditorComponent: (
+ activeNodeId: string,
+ overNodeId: string
+ ) => {
+ activeNodeId: string
+ overNodeId: string
+ }
+ resetViewComponentConfig: (viewId: string) => {
+ viewId: string
+ }
+ saveEditor: () => {
+ value: true
+ }
+ saveEditorFailure: () => {
+ value: true
+ }
+ saveEditorSuccess: (view: AccountViewApi) => {
+ view: AccountViewApi
+ }
+ saveTileEditor: () => {
+ value: true
+ }
+ saveViewComponentConfigFailure: () => {
+ value: true
+ }
+ saveViewComponentConfigSuccess: (
+ view: AccountViewApi,
+ savedContent: AccountViewContentApi
+ ) => {
+ savedContent: AccountViewContentApi
+ view: AccountViewApi
+ }
+ saveViewComponentFailure: () => {
+ value: true
+ }
+ setEditorConflict: (conflict: boolean) => {
+ conflict: boolean
+ }
+ setEditorName: (name: string) => {
+ name: string
+ }
+ setEditorOpen: (open: boolean) => {
+ open: boolean
+ }
+ setTileEditorName: (name: string) => {
+ name: string
+ }
+ updateViewComponentConfig: (
+ viewId: string,
+ nodeId: string,
+ config: AccountViewTileConfig
+ ) => {
+ config: AccountViewTileConfig
+ nodeId: string
+ viewId: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountViewsLogicMeta {
+ key: number
+ __keaTypeGenInternalSelectorTypes: {
+ editingView: (views: AccountViewApi[], editingViewId: string | null) => AccountViewApi | null
+ }
+}
+
+export type accountViewsLogicType = MakeLogicType<
+ accountViewsLogicValues,
+ accountViewsLogicActions,
+ AccountViewsLogicProps,
+ accountViewsLogicMeta
+>
+
+function updateAccountViewComponents(
+ projectId: number,
+ view: AccountViewApi,
+ components: AccountViewComponentInstance[]
+): Promise<AccountViewApi> {
+ return accountViewsPartialUpdate(String(projectId), view.id, {
+ content: createAccountViewContent(components),
+ version: view.version,
+ })
+}
+
+// Every write sends the view's version, so concurrent writes to one view would conflict with each other.
+function queueViewWrite(cache: Record<string, any>, viewId: string, write: () => Promise<void>): Promise<void> {
+ const writes = (cache.viewWrites ??= new Map<string, Promise<void>>()) as Map<string, Promise<void>>
+ const next = (writes.get(viewId) ?? Promise.resolve()).catch(() => undefined).then(write)
+ writes.set(viewId, next)
+ return next
+}
+
+function loadViewsOnceEnabled(logic: Pick<accountViewsLogicType, 'actions' | 'cache' | 'values'>): void {
+ if (!logic.cache.viewsRequested && logic.values.featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]) {
+ logic.cache.viewsRequested = true
+ logic.actions.loadViews()
+ }
+}
+
+function createAccountViewWithComponentConfig(
+ view: AccountViewApi,
+ nodeId: string,
+ config: AccountViewTileConfig
+): AccountViewApi {
+ return {
+ ...view,
+ content: createAccountViewContent(
+ parseAccountViewContent(view.content).map((component) =>
+ component.nodeId === nodeId ? { ...component, config } : component
+ )
+ ),
+ }
+}
+
+export const accountViewsLogic = kea<accountViewsLogicType>([
+ props({} as AccountViewsLogicProps),
+ key((props) => props.projectId),
+ path((key) => [
+ 'products',
+ 'customer_analytics',
+ 'frontend',
+ 'scenes',
+ 'CustomerAnalyticsAccountScene',
+ 'accountViewsLogic',
+ key,
+ ]),
+ connect(() => ({
+ values: [featureFlagLogic, ['featureFlags']],
+ actions: [featureFlagLogic, ['setFeatureFlags']],
+ })),
+ actions({
+ loadViews: true,
+ loadViewsSuccess: (views: AccountViewApi[]) => ({ views }),
+ loadViewsFailure: (error: unknown) => ({ error }),
+ setEditorOpen: (open: boolean) => ({ open }),
+ openCreateEditor: true,
+ openEditEditor: (view: AccountViewApi) => ({ view }),
+ setEditorName: (name: string) => ({ name }),
+ addEditorComponent: (kind: AccountViewComponentKind) => ({ kind }),
+ duplicateEditorComponent: (nodeId: string) => ({ nodeId }),
+ removeEditorComponent: (nodeId: string) => ({ nodeId }),
+ reorderEditorComponent: (activeNodeId: string, overNodeId: string) => ({ activeNodeId, overNodeId }),
+ openTileEditor: (viewId: string, nodeId: string, name: string) => ({ viewId, nodeId, name }),
+ closeTileEditor: true,
+ setTileEditorName: (name: string) => ({ name }),
+ saveTileEditor: true,
+ removeViewComponent: (viewId: string, nodeId: string) => ({ viewId, nodeId }),
+ updateViewComponentConfig: (viewId: string, nodeId: string, config: AccountViewTileConfig) => ({
+ viewId,
+ nodeId,
+ config,
+ }),
+ saveViewComponentConfigSuccess: (view: AccountViewApi, savedContent: AccountViewContentApi) => ({
+ view,
+ savedContent,
+ }),
+ saveViewComponentConfigFailure: true,
+ resetViewComponentConfig: (viewId: string) => ({ viewId }),
+ saveViewComponentFailure: true,
+ saveEditor: true,
+ saveEditorSuccess: (view: AccountViewApi) => ({ view }),
+ saveEditorFailure: true,
+ setEditorConflict: (conflict: boolean) => ({ conflict }),
+ reloadEditor: true,
+ deleteView: (viewId: string, version: number) => ({ viewId, version }),
+ deleteViewFailure: true,
+ deleteViewSuccess: (viewId: string) => ({ viewId }),
+ }),
+ reducers({
+ views: [
+ [] as AccountViewApi[],
+ {
+ loadViewsSuccess: (_, { views }: { views: AccountViewApi[] }) => views,
+ saveEditorSuccess: (state, { view }: { view: AccountViewApi }) => {
+ const existingIndex = state.findIndex((candidate) => candidate.id === view.id)
+ return existingIndex === -1
+ ? [...state, view]
+ : state.map((candidate, index) => (index === existingIndex ? view : candidate))
+ },
+ updateViewComponentConfig: (
+ state,
+ { viewId, nodeId, config }: { viewId: string; nodeId: string; config: AccountViewTileConfig }
+ ) =>
+ state.map((view) =>
+ view.id === viewId ? createAccountViewWithComponentConfig(view, nodeId, config) : view
+ ),
+ saveViewComponentConfigSuccess: (
+ state,
+ { view, savedContent }: { view: AccountViewApi; savedContent: AccountViewApi['content'] }
+ ) =>
+ state.map((candidate) =>
+ candidate.id !== view.id
+ ? candidate
+ : candidate.content === savedContent
+ ? view
+ : { ...view, content: candidate.content }
+ ),
+ deleteViewSuccess: (state, { viewId }: { viewId: string }) =>
+ state.filter((view) => view.id !== viewId),
+ },
+ ],
+ tileConfigReloads: [
+ {} as Record<string, number>,
+ {
+ resetViewComponentConfig: (state, { viewId }: { viewId: string }) => ({
+ ...state,
+ [viewId]: (state[viewId] ?? 0) + 1,
+ }),
+ },
+ ],
+ viewsLoading: [false, { loadViews: () => true, loadViewsSuccess: () => false, loadViewsFailure: () => false }],
+ viewsError: [
+ null as unknown,
+ {
+ loadViews: () => null,
+ loadViewsSuccess: () => null,
+ loadViewsFailure: (_, { error }: { error: unknown }) => error,
+ },
+ ],
+ editorOpen: [false, { setEditorOpen: (_, { open }: { open: boolean }) => open }],
+ editingViewId: [
+ null as string | null,
+ { openCreateEditor: () => null, openEditEditor: (_, { view }: { view: AccountViewApi }) => view.id },
+ ],
+ editorDraft: [
+ { name: '', components: [] } as AccountViewEditorDraft,
+ {
+ openCreateEditor: () => ({ name: '', components: [] }),
+ openEditEditor: (_, { view }: { view: AccountViewApi }) => ({
+ name: view.name,
+ components: parseAccountViewContent(view.content),
+ }),
+ setEditorName: (state, { name }: { name: string }) => ({ ...state, name }),
+ addEditorComponent: (state, { kind }: { kind: AccountViewComponentKind }) => ({
+ ...state,
+ components: [...state.components, createAccountViewComponentInstance(kind)],
+ }),
+ duplicateEditorComponent: (state, { nodeId }: { nodeId: string }) => {
+ const index = state.components.findIndex((component) => component.nodeId === nodeId)
+ if (index === -1) {
+ return state
+ }
+ const source = state.components[index]
+ const duplicate = { ...source, nodeId: createAccountViewComponentInstance(source.kind).nodeId }
+ return {
+ ...state,
+ components: [
+ ...state.components.slice(0, index + 1),
+ duplicate,
+ ...state.components.slice(index + 1),
+ ],
+ }
+ },
+ removeEditorComponent: (state, { nodeId }: { nodeId: string }) => ({
+ ...state,
+ components: state.components.filter((component) => component.nodeId !== nodeId),
+ }),
+ reorderEditorComponent: (
+ state,
+ { activeNodeId, overNodeId }: { activeNodeId: string; overNodeId: string }
+ ) => {
+ const fromIndex = state.components.findIndex((component) => component.nodeId === activeNodeId)
+ const toIndex = state.components.findIndex((component) => component.nodeId === overNodeId)
+ if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) {
+ return state
+ }
+ const components = [...state.components]
+ const [moved] = components.splice(fromIndex, 1)
+ components.splice(toIndex, 0, moved)
+ return { ...state, components }
+ },
+ },
+ ],
+ editorSaving: [
+ false,
+ {
+ saveEditor: () => true,
+ deleteView: () => true,
+ saveEditorSuccess: () => false,
+ saveEditorFailure: () => false,
+ deleteViewSuccess: () => false,
+ deleteViewFailure: () => false,
+ },
+ ],
+ editorConflict: [
+ false,
+ {
+ openCreateEditor: () => false,
+ openEditEditor: () => false,
+ saveEditorSuccess: () => false,
+ setEditorConflict: (_, { conflict }: { conflict: boolean }) => conflict,
+ },
+ ],
+ tileEditor: [
+ null as AccountViewTileEditor | null,
+ {
+ openTileEditor: (_, { viewId, nodeId, name }: AccountViewTileEditor) => ({ viewId, nodeId, name }),
+ closeTileEditor: () => null,
+ setTileEditorName: (state, { name }: { name: string }) => (state ? { ...state, name } : state),
+ },
+ ],
+ tileSaving: [
+ false,
+ {
+ saveTileEditor: () => true,
+ removeViewComponent: () => true,
+ saveEditorSuccess: () => false,
+ saveViewComponentFailure: () => false,
+ },
+ ],
+ }),
+ selectors({
+ editingView: [
+ (selectors) => [selectors.views, selectors.editingViewId],
+ (views: AccountViewApi[], editingViewId: string | null): AccountViewApi | null =>
+ views.find((view) => view.id === editingViewId) ?? null,
+ ],
+ }),
+ listeners(({ actions, cache, props, values }) => ({
+ setFeatureFlags: () => loadViewsOnceEnabled({ actions, cache, values }),
+ loadViews: async () => {
+ try {
+ actions.loadViewsSuccess(await accountViewsList(String(props.projectId)))
+ const failedViewIds = cache.failedTileConfigViewIds as Set<string> | undefined
+ if (failedViewIds) {
+ for (const viewId of failedViewIds) {
+ actions.resetViewComponentConfig(viewId)
+ }
+ failedViewIds.clear()
+ }
+ } catch (error) {
+ actions.loadViewsFailure(error)
+ }
+ },
+ openCreateEditor: () => actions.setEditorOpen(true),
+ openEditEditor: () => actions.setEditorOpen(true),
+ saveEditor: async () => {
+ if (!values.editorDraft.name.trim() || values.editorDraft.components.length === 0) {
+ actions.saveEditorFailure()
+ return
+ }
+ try {
+ const content = createAccountViewContent(values.editorDraft.components)
+ const view = values.editingView
+ ? await accountViewsPartialUpdate(String(props.projectId), values.editingView.id, {
+ name: values.editorDraft.name.trim(),
+ content,
+ version: values.editingView.version,
+ })
+ : await accountViewsCreate(String(props.projectId), {
+ name: values.editorDraft.name.trim(),
+ content,
+ })
+ actions.saveEditorSuccess(view)
+ actions.setEditorOpen(false)
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 409) {
+ actions.setEditorConflict(true)
+ } else {
+ lemonToast.error("Couldn't save the view. Try again.")
+ }
+ actions.saveEditorFailure()
+ }
+ },
+ reloadEditor: async () => {
+ if (!values.editingViewId) {
+ return
+ }
+ try {
+ const view = await accountViewsRetrieve(String(props.projectId), values.editingViewId)
+ actions.saveEditorSuccess(view)
+ actions.openEditEditor(view)
+ } catch {
+ lemonToast.error("Couldn't reload the view. Close the editor and try again.")
+ }
+ },
+ deleteView: async ({ viewId, version }) => {
+ try {
+ await accountViewsDestroy(String(props.projectId), viewId, { version })
+ actions.deleteViewSuccess(viewId)
+ actions.setEditorOpen(false)
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 409) {
+ actions.setEditorConflict(true)
+ } else {
+ lemonToast.error("Couldn't delete the view. Try again.")
+ }
+ actions.deleteViewFailure()
+ }
+ },
+ saveTileEditor: async () => {
+ const tileEditor = values.tileEditor
+ if (!tileEditor) {
+ actions.saveViewComponentFailure()
+ return
+ }
+ await queueViewWrite(cache, tileEditor.viewId, async () => {
+ const view = values.views.find((candidate) => candidate.id === tileEditor.viewId)
+ const name = tileEditor.name.trim()
+ if (!view || !name) {
+ actions.saveViewComponentFailure()
+ return
+ }
+ const components = parseAccountViewContent(view.content).map((component) =>
+ component.nodeId === tileEditor.nodeId ? { ...component, title: name } : component
+ )
+ try {
+ actions.saveEditorSuccess(await updateAccountViewComponents(props.projectId, view, components))
+ actions.closeTileEditor()
+ } catch (error) {
+ lemonToast.error(
+ error instanceof ApiError && error.status === 409
+ ? 'This view changed. Refresh and try again.'
+ : "Couldn't rename the tile. Try again."
+ )
+ actions.saveViewComponentFailure()
+ actions.loadViews()
+ }
+ })
+ },
+ updateViewComponentConfig: async ({ viewId }) => {
+ const pendingViewIds = (cache.pendingConfigViewIds ??= new Set<string>()) as Set<string>
+ if (pendingViewIds.has(viewId)) {
+ return
+ }
+ pendingViewIds.add(viewId)
+ await queueViewWrite(cache, viewId, async () => {
+ pendingViewIds.delete(viewId)
+ const failedViewIds = cache.failedTileConfigViewIds as Set<string> | undefined
+ const view = values.views.find((candidate) => candidate.id === viewId)
+ if (!view || failedViewIds?.has(viewId)) {
+ return
+ }
+ const savedContent = view.content
+ try {
+ const updatedView = await accountViewsPartialUpdate(String(props.projectId), view.id, {
+ content: savedContent,
+ version: view.version,
+ })
+ actions.saveViewComponentConfigSuccess(updatedView, savedContent)
+ } catch (error) {
+ lemonToast.error(
+ error instanceof ApiError && error.status === 409
+ ? 'This view changed. Refresh and try again.'
+ : "Couldn't save the tile settings. Try again."
+ )
+ ;(cache.failedTileConfigViewIds ??= new Set<string>()).add(viewId)
+ actions.saveViewComponentConfigFailure()
+ actions.loadViews()
+ }
+ })
+ },
+ removeViewComponent: async ({ viewId, nodeId }) => {
+ await queueViewWrite(cache, viewId, async () => {
+ const view = values.views.find((candidate) => candidate.id === viewId)
+ if (!view) {
+ actions.saveViewComponentFailure()
+ return
+ }
+ const components = parseAccountViewContent(view.content).filter(
+ (component) => component.nodeId !== nodeId
+ )
+ if (components.length === 0) {
+ actions.saveViewComponentFailure()
+ return
+ }
+ try {
+ actions.saveEditorSuccess(await updateAccountViewComponents(props.projectId, view, components))
+ } catch (error) {
+ lemonToast.error(
+ error instanceof ApiError && error.status === 409
+ ? 'This view changed. Refresh and try again.'
+ : "Couldn't remove the tile. Try again."
+ )
+ actions.saveViewComponentFailure()
+ actions.loadViews()
+ }
+ })
+ },
+ })),
+ afterMount((logic) => loadViewsOnceEnabled(logic)),
+])
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
index a1064c23e9a0..ed03c2c97740 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
@@ -41,6 +41,7 @@ const mockAccountsPresenceCreate = accountsPresenceCreate as jest.MockedFunction
const mockAccountsRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>
const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'
+const ACCOUNT_VIEW_TAB = 'view:11111111-2222-4333-8444-555555555555'
const PROJECT_ID = 999
const account: AccountApi = {
id: ACCOUNT_ID,
@@ -698,9 +699,18 @@ describe('customerAnalyticsAccountSceneLogic', () => {
expect(router.values.currentLocation.hashParams).toEqual(hashParams)
expect(capture).toHaveBeenCalledWith(AccountsEvents.TabViewed, { tab: 'usage' })
+ logic.actions.setActiveTab(ACCOUNT_VIEW_TAB)
+
+ expect(router.values.location.pathname).toBe(
+ urls.currentProject(urls.customerAnalyticsAccount(ACCOUNT_ID, ACCOUNT_VIEW_TAB))
+ )
+ expect(logic.values.requestedTab).toBe(ACCOUNT_VIEW_TAB)
+
logic.actions.setActiveTab('notes')
- expect(router.values.location.pathname).toBe(urls.currentProject(urls.customerAnalyticsAccount(ACCOUNT_ID)))
+ expect(router.values.location.pathname).toBe(
+ urls.currentProject(urls.customerAnalyticsAccount(ACCOUNT_ID, 'notes'))
+ )
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.ts
index 40dea2b45468..23fa48586e65 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
@@ -34,7 +34,6 @@ import {
} from 'products/customer_analytics/frontend/components/Accounts/accountEmailMatching'
import {
AccountExpansionTab,
- DEFAULT_ACCOUNT_TAB,
getVisibleAccountExpansionTab,
} from 'products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic'
import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'
@@ -98,6 +97,17 @@ function accountDetailUrl(props: CustomerAnalyticsAccountSceneLogicProps, tab?:
: urls.customerAnalyticsAccount(props.accountId ?? '', tab)
}
+function parseAccountTabRoute(tab: string | undefined): string | undefined {
+ if (!tab) {
+ return undefined
+ }
+ try {
+ return decodeURIComponent(tab)
+ } catch {
+ return tab
+ }
+}
+
function isAccountNotFound(error: unknown): boolean {
return error instanceof ApiError && error.status === 404
}
@@ -191,8 +201,8 @@ export interface customerAnalyticsAccountSceneLogicActions {
setAccountFormValues: (values: DeepPartial<AccountEditFormValues>) => {
values: DeepPartial<AccountEditFormValues>
}
- setActiveTab: (tab: AccountExpansionTab) => {
- tab: AccountExpansionTab
+ setActiveTab: (tab: string) => {
+ tab: string
}
startAccountPresencePolling: (accountId: string) => {
accountId: string
@@ -273,8 +283,8 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
loadAccountPresenceSuccess: (viewers: AccountPresenceViewerApi[]) => ({ viewers }),
startAccountPresencePolling: (accountId: string) => ({ accountId }),
loadAccountPresenceFailure: (error: unknown) => ({ error }),
- setActiveTab: (tab: AccountExpansionTab) => ({ tab }),
- restoreActiveTab: (tab: string | undefined) => ({ tab: tab ?? DEFAULT_ACCOUNT_TAB }),
+ setActiveTab: (tab: string) => ({ tab }),
+ restoreActiveTab: (tab: string | undefined) => ({ tab: tab ?? '' }),
updateTags: (tags: string[]) => ({ tags }),
updateTagsDone: (account: AccountApi | null) => ({ account }),
openAccountEditor: true,
@@ -375,7 +385,7 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
},
],
requestedTab: [
- DEFAULT_ACCOUNT_TAB as string,
+ '',
{
setActiveTab: (_, { tab }) => tab,
restoreActiveTab: (_, { tab }) => tab,
@@ -565,7 +575,7 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
})),
actionToUrl(({ props }) => ({
setActiveTab: ({ tab }) => [
- accountDetailUrl(props, tab === DEFAULT_ACCOUNT_TAB ? undefined : tab),
+ accountDetailUrl(props, tab),
router.values.currentLocation.searchParams,
router.values.currentLocation.hashParams,
],
@@ -580,10 +590,10 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
}
return {
[`${accountDetailUrl(props)}/:tab`]: ({ tab }) => {
- actions.restoreActiveTab(tab)
+ actions.restoreActiveTab(parseAccountTabRoute(tab))
},
[accountDetailUrl(props)]: () => {
- actions.restoreActiveTab(DEFAULT_ACCOUNT_TAB)
+ actions.restoreActiveTab(undefined)
},
}
}),
diff --git a/products/customer_analytics/manifest.tsx b/products/customer_analytics/manifest.tsx
index f20aadc7592d..9e7ad5296977 100644
--- a/products/customer_analytics/manifest.tsx
+++ b/products/customer_analytics/manifest.tsx
@@ -103,9 +103,9 @@ export const manifest: ProductManifest = {
customerAnalyticsAccounts: (): string => '/customer_analytics/accounts',
// 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}` : ''}`,
+ `/customer_analytics/accounts/${accountId}${tab ? `/${encodeURIComponent(tab)}` : ''}`,
customerAnalyticsAccountByExternalId: (externalId: string, tab?: string): string =>
- `/customer_analytics/accounts/by-external-id/${encodeURIComponent(externalId)}${tab ? `/${tab}` : ''}`,
+ `/customer_analytics/accounts/by-external-id/${encodeURIComponent(externalId)}${tab ? `/${encodeURIComponent(tab)}` : ''}`,
customerAnalyticsNotes: (): string => '/customer_analytics/notes',
customerAnalyticsAnnouncements: (): string => '/customer_analytics/announcements',
customerAnalyticsFeed: (): string => '/customer_analytics/feed',