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): Instrument accounts list with product analytics events (#61606)

Arthur Moreira de Deus1cf0a8c5dba8
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
new file mode 100644
index 000000000000..6fbbcbaf729b
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -0,0 +1,43 @@
+# Accounts — agent guide
+
+Guidance for agents working on the Accounts area of Customer analytics (`products/customer_analytics/frontend/components/Accounts/`). Scope is the **Accounts list** only, not the rest of Customer analytics.
+
+## Analytics events
+
+We track user actions on the Accounts list with `posthog.capture()`. Conventions:
+
+- Event names: `customer analytics accounts <verb> <object>` — lowercase, spaces. Property keys are `snake_case`.
+- **Reference event names via the `AccountsEvents` const in `constants.ts`** — never pass a raw string to `posthog.capture`. A typo'd literal silently forks a new event in PostHog and breaks reporting with no error. When adding an event, add it to `AccountsEvents` and to the table below.
+- Fire events in the **kea logic listeners** (where the action and its values live), not in components. Only fire from a component when no action exists for the interaction (the expanded-row links/notes).
+- **Filters use a dedicated `reportFilterChange` action.** The raw filter setters (`setTagsFilter`, `setCsmFilter`, …) are also dispatched by URL sync (shared view links) and by cross-filter cascades (checking "unassigned only" clears the role filters), so capturing in their listeners would log phantom events. The filter controls dispatch `reportFilterChange(filterType)` on genuine interaction only; its listener reads the post-change state and captures. Add new filters the same way.
+- Use the **effective/debounced** action where one exists (e.g. capture in the `setSearchInput` listener after its debounce) so events don't fire per keystroke.
+- PII: log internal team members by `user_id` only (never email); never log raw search text, link URLs, or notebook titles.
+
+### Tracked events
+
+| Event | Fires from | Properties |
+| --------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |
+| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `csm` \| `account_executive` \| `account_owner` \| `unassigned_only`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count` |
+| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |
+| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |
+| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |
+| `customer analytics accounts columns saved` | `accountsColumnConfigLogic` `saveColumns` (success, only when changed) | `column_count`, `columns`, `added_count`, `removed_count`, `reordered` |
+| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |
+| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) |
+| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` |
+| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |
+| `customer analytics account tab viewed` | `AccountNotebooksExpansion.tsx` `LemonTabs` `onChange` | `tab` (`notes` \| `users`) |
+| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |
+
+> **Keep this table up to date.** Whenever you add, rename, or remove a `posthog.capture()` event in the Accounts area — or change its properties — update this table in the same change. An agent reading this file should be able to trust it as the source of truth for what the Accounts list reports.
+
+### Adding features and events
+
+- **Instrument every new feature as you build it.** Any new user action on the accounts list should emit a `posthog.capture`, following this product's pattern and the wider PostHog pattern:
+ - Add the event name to the `AccountsEvents` const in `constants.ts` and capture through it — never a raw string (a typo silently forks a new event in PostHog).
+ - Keep the naming convention (`customer analytics accounts <verb> <object>`) and `snake_case` property keys.
+ - Type discriminator property _values_ with a union (e.g. `AccountFilterType`, `AccountRoleKey`) rather than bare strings, so the value set is typo-proof and self-documenting — these are what dashboard breakdowns key off.
+ - Fire from the kea logic listener where the values live; only fire from a component when no action exists. If the trigger is also dispatched by URL sync or cross-filter cascades, add a dedicated report action (see `reportFilterChange`).
+ - Add a row to the table above.
+- **Update the monitoring dashboard whenever events change.** New or changed events must be reflected in the "Customer analytics: Accounts list usage" dashboard in PostHog — add a new insight or extend an existing one so the metric is actually visible, don't just emit the event. For example, if you add a new tab to the expanded account row, its click event should feed the engagement-funnel insight (the "opened a link or note" step) and the feature-adoption insight — not just be captured.
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
index dd143b13cdd4..06a658927709 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx
@@ -1,4 +1,5 @@
import { useValues } from 'kea'
+import posthog from 'posthog-js'
import { useState } from 'react'
import { IconGraph, IconPeople, IconPiggyBank, IconReceipt } from '@posthog/icons'
@@ -22,6 +23,7 @@ import type { AccountNotebookApi } from 'products/customer_analytics/frontend/ge
import { accountLinksLogic } from './accountLinksLogic'
import { accountNotebooksLogic } from './accountNotebooksLogic'
import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'
+import { AccountsEvents } from './constants'
import { EditAccountLinksButton } from './EditAccountLinksButton'
const PREVIEW_MAX_CHARS = 200
@@ -68,6 +70,12 @@ function UsefulLinks({ accountId }: { accountId: string }): JSX.Element {
to={link.to ?? undefined}
targetBlank={link.targetBlank}
disabledReason={link.disabledReason ?? undefined}
+ onClick={() =>
+ posthog.capture(AccountsEvents.LinkClicked, {
+ link_key: link.key,
+ has_destination: !!link.to,
+ })
+ }
>
{link.label}
</LemonButton>
@@ -96,7 +104,15 @@ export function AccountNotebooksExpansion({
const preview = getPreview(notebook)
return (
<div className="flex flex-col gap-1 py-1 max-w-2xl">
- <Link to={urls.notebook(notebook.short_id)} className="font-medium">
+ <Link
+ to={urls.notebook(notebook.short_id)}
+ className="font-medium"
+ onClick={() =>
+ posthog.capture(AccountsEvents.NoteClicked, {
+ notebook_short_id: notebook.short_id,
+ })
+ }
+ >
{notebook.title || 'Untitled note'}
</Link>
{preview ? (
@@ -146,7 +162,10 @@ export function AccountNotebooksExpansion({
<div className="flex-1 min-w-0">
<LemonTabs
activeKey={activeTab}
- onChange={setActiveTab}
+ onChange={(tab) => {
+ setActiveTab(tab)
+ posthog.capture(AccountsEvents.TabViewed, { tab })
+ }}
size="small"
tabs={[
{
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
index b86fee0a1574..e97ca4e56e51 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
import { LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'
@@ -6,6 +7,7 @@ import { fullName } from 'lib/utils'
import { urls } from 'scenes/urls'
import { accountRelatedUsersLogic, AccountOrganizationMember, PAGE_SIZE } from './accountRelatedUsersLogic'
+import { AccountsEvents } from './constants'
export function AccountRelatedUsersExpansion({ externalId }: { externalId: string }): JSX.Element {
const logic = accountRelatedUsersLogic({ externalId })
@@ -19,7 +21,11 @@ export function AccountRelatedUsersExpansion({ externalId }: { externalId: strin
render: (_, member) => {
const name = fullName(member.user) || member.user.email
return member.user.distinct_id ? (
- <Link to={urls.personByDistinctId(member.user.distinct_id)} className="font-medium">
+ <Link
+ to={urls.personByDistinctId(member.user.distinct_id)}
+ className="font-medium"
+ onClick={() => posthog.capture(AccountsEvents.RelatedUserClicked)}
+ >
{name}
</Link>
) : (
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx
index 1add3ae97ddc..1a1ebf87d88e 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTabFilters.tsx
@@ -22,6 +22,7 @@ export function AccountsTabFilters(): JSX.Element {
setAccountExecutiveFilter,
setAccountOwnerFilter,
refresh,
+ reportFilterChange,
} = useActions(accountsLogic)
const { tags: tagsAvailable } = useValues(tagsModel)
@@ -48,7 +49,10 @@ export function AccountsTabFilters(): JSX.Element {
allowCustomValues
value={tagsFilter}
options={(tagsAvailable || []).map((t: string) => ({ key: t, label: t }))}
- onChange={setTagsFilter}
+ onChange={(tags) => {
+ setTagsFilter(tags)
+ reportFilterChange('tag')
+ }}
placeholder="Select or type tags..."
data-attr="accounts-tags-filter"
/>
@@ -64,27 +68,47 @@ export function AccountsTabFilters(): JSX.Element {
type="secondary"
size="small"
icon={<IconX />}
- onClick={() => setTagsFilter([])}
+ onClick={() => {
+ setTagsFilter([])
+ reportFilterChange('tag')
+ }}
tooltip="Clear tag filter"
/>
)}
- <RolePicker label="CSM" value={csmFilter} onChange={setCsmFilter} dataAttr="accounts-csm-filter" />
+ <RolePicker
+ label="CSM"
+ value={csmFilter}
+ onChange={(value) => {
+ setCsmFilter(value)
+ reportFilterChange('csm')
+ }}
+ dataAttr="accounts-csm-filter"
+ />
<RolePicker
label="AE"
value={accountExecutiveFilter}
- onChange={setAccountExecutiveFilter}
+ onChange={(value) => {
+ setAccountExecutiveFilter(value)
+ reportFilterChange('account_executive')
+ }}
dataAttr="accounts-ae-filter"
/>
<RolePicker
label="Owner"
value={accountOwnerFilter}
- onChange={setAccountOwnerFilter}
+ onChange={(value) => {
+ setAccountOwnerFilter(value)
+ reportFilterChange('account_owner')
+ }}
dataAttr="accounts-owner-filter"
/>
<LemonCheckbox
checked={allRolesUnassigned}
- onChange={setAllRolesUnassigned}
+ onChange={(value) => {
+ setAllRolesUnassigned(value)
+ reportFilterChange('unassigned_only')
+ }}
label="Unassigned only"
disabledReason={accountsLoading ? 'Loading…' : undefined}
data-attr="accounts-unassigned-filter"
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
index 299eb706971d..bd489c1281a6 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.ts
@@ -5,6 +5,7 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { objectsEqual } from 'lib/utils'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { teamLogic } from 'scenes/teamLogic'
@@ -15,6 +16,7 @@ import type { DataWarehouseViewLink } from '~/types'
import { joinsLogic } from 'products/data_warehouse/frontend/shared/logics/joinsLogic'
import type { accountsColumnConfigLogicType } from './accountsColumnConfigLogicType'
+import { AccountsEvents } from './constants'
// Mandatory — the backend emits it as `tuple(name, external_id, id)` so the
// row identity (id) and copy-able external_id ride along with the display name.
@@ -33,6 +35,21 @@ function ensureNameColumn(columns: string[]): string[] {
return columns.includes(ACCOUNTS_NAME_COLUMN) ? columns : [ACCOUNTS_NAME_COLUMN, ...columns]
}
+export function diffColumnConfiguration(
+ previous: string[],
+ next: string[]
+): { changed: boolean; added: number; removed: number; reordered: boolean } {
+ const previousSet = new Set(previous)
+ const nextSet = new Set(next)
+ const added = next.filter((column) => !previousSet.has(column)).length
+ const removed = previous.filter((column) => !nextSet.has(column)).length
+ const reordered = !objectsEqual(
+ previous.filter((column) => nextSet.has(column)),
+ next.filter((column) => previousSet.has(column))
+ )
+ return { changed: added > 0 || removed > 0 || reordered, added, removed, reordered }
+}
+
export const ACCOUNTS_COLUMN_CONFIG_KEY = 'customer_analytics_accounts_columns'
// `allTablesMap` keys system tables by their fully qualified name (e.g.
@@ -271,6 +288,7 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
saveColumns: async () => {
const teamId = values.currentTeamId || undefined
const columns = values.selectColumns
+ const previousColumns = values.savedColumnConfiguration?.columns ?? ACCOUNTS_HOGQL_DEFAULT_SELECT
try {
if (values.savedColumnConfiguration?.id) {
await api.columnConfigurations.update({
@@ -286,6 +304,16 @@ export const accountsColumnConfigLogic = kea<accountsColumnConfigLogicType>([
actions.loadSavedColumnConfigurationSuccess({ id: response.id, columns: response.columns || [] })
}
lemonToast.success('Columns saved')
+ const diff = diffColumnConfiguration(previousColumns, columns)
+ if (diff.changed) {
+ posthog.capture(AccountsEvents.ColumnsSaved, {
+ column_count: columns.length,
+ columns,
+ added_count: diff.added,
+ removed_count: diff.removed,
+ reordered: diff.reordered,
+ })
+ }
} catch (error) {
posthog.captureException(error as Error, { scope: 'accountsColumnConfigLogic.saveColumns' })
lemonToast.error('Failed to save columns')
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index 35feae50c971..2d63d87ae4b5 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -1,4 +1,4 @@
-import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
@@ -21,6 +21,7 @@ import { ACCOUNTS_HOGQL_DATA_NODE_KEY, CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } f
import { ACCOUNTS_HOGQL_DEFAULT_SELECT, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import type { accountsLogicType } from './accountsLogicType'
import { accountsOverviewTilesLogic, TileFilter } from './accountsOverviewTilesLogic'
+import { AccountsEvents } from './constants'
export const SEARCH_DEBOUNCE_MS = 300
@@ -50,6 +51,8 @@ export type RoleFilterValue = number | null
export type AccountRoleKey = 'csm' | 'account_executive' | 'account_owner'
+export type AccountFilterType = 'tag' | 'csm' | 'account_executive' | 'account_owner' | 'unassigned_only'
+
// `column` matches the visible column name (alias-stripped) so any selected
// column can drive the sort.
export type AccountSortableColumn = string
@@ -126,6 +129,10 @@ export const accountsLogic = kea<accountsLogicType>([
setSortOrder: (sortOrder: AccountSortOrder) => ({ sortOrder }),
toggleSort: (column: AccountSortableColumn) => ({ column }),
refresh: true,
+ // Dispatched by the filter controls on genuine user interaction only.
+ // The raw filter setters are also fired by URL sync and cross-filter
+ // cascades, so capturing analytics here keeps phantom events out.
+ reportFilterChange: (filterType: AccountFilterType) => ({ filterType }),
updateAccountRole: (accountId: string, role: AccountRoleKey, user: UserBasicType | null) => ({
accountId,
role,
@@ -213,6 +220,32 @@ export const accountsLogic = kea<accountsLogicType>([
(accountId: string, role: AccountRoleKey): boolean =>
!!savingRoles[savingRoleKey(accountId, role)],
],
+ activeFilterCount: [
+ (s) => [
+ s.searchQuery,
+ s.tagsFilter,
+ s.csmFilter,
+ s.accountExecutiveFilter,
+ s.accountOwnerFilter,
+ s.allRolesUnassigned,
+ ],
+ (
+ searchQuery: string,
+ tagsFilter: string[],
+ csmFilter: RoleFilterValue,
+ accountExecutiveFilter: RoleFilterValue,
+ accountOwnerFilter: RoleFilterValue,
+ allRolesUnassigned: boolean
+ ): number =>
+ [
+ !!searchQuery.trim(),
+ tagsFilter.length > 0,
+ csmFilter !== null,
+ accountExecutiveFilter !== null,
+ accountOwnerFilter !== null,
+ allRolesUnassigned,
+ ].filter(Boolean).length,
+ ],
viewUrlState: [
(s) => [
s.searchQuery,
@@ -344,6 +377,42 @@ export const accountsLogic = kea<accountsLogicType>([
setSearchInput: async ({ query }, breakpoint) => {
await breakpoint(SEARCH_DEBOUNCE_MS)
actions.setSearchQuery(query)
+ const trimmed = query.trim()
+ posthog.capture(AccountsEvents.Searched, {
+ query_length: trimmed.length,
+ has_query: !!trimmed,
+ active_filter_count: values.activeFilterCount,
+ })
+ },
+ reportFilterChange: ({ filterType }) => {
+ const properties: Record<string, unknown> = {
+ filter_type: filterType,
+ active_filter_count: values.activeFilterCount,
+ }
+ switch (filterType) {
+ case 'tag':
+ properties.value = values.tagsFilter
+ properties.tag_count = values.tagsFilter.length
+ properties.is_cleared = values.tagsFilter.length === 0
+ break
+ case 'csm':
+ properties.value = values.csmFilter
+ properties.is_cleared = values.csmFilter === null
+ break
+ case 'account_executive':
+ properties.value = values.accountExecutiveFilter
+ properties.is_cleared = values.accountExecutiveFilter === null
+ break
+ case 'account_owner':
+ properties.value = values.accountOwnerFilter
+ properties.is_cleared = values.accountOwnerFilter === null
+ break
+ case 'unassigned_only':
+ properties.value = values.allRolesUnassigned
+ properties.is_cleared = !values.allRolesUnassigned
+ break
+ }
+ posthog.capture(AccountsEvents.FilterChanged, properties)
},
setAllRolesUnassigned: ({ value }) => {
if (value) {
@@ -384,6 +453,10 @@ export const accountsLogic = kea<accountsLogicType>([
next = null
}
actions.setSortOrder(next)
+ posthog.capture(AccountsEvents.Sorted, {
+ column,
+ direction: next ? next.direction : 'cleared',
+ })
},
setSelectColumns: () => {
clearSortIfColumnRemoved(values, actions)
@@ -395,6 +468,11 @@ export const accountsLogic = kea<accountsLogicType>([
clearSortIfColumnRemoved(values, actions)
},
refresh: () => {
+ posthog.capture(AccountsEvents.Refreshed, {
+ has_search: !!values.searchQuery.trim(),
+ active_filter_count: values.activeFilterCount,
+ sort_column: values.sortOrder?.column ?? null,
+ })
dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })?.actions.loadData('force_async')
},
updateAccountRole: async ({ accountId, role, user }) => {
@@ -411,6 +489,12 @@ export const accountsLogic = kea<accountsLogicType>([
}
const updated = await accountsPartialUpdate(projectId, accountId, { properties: nextProperties })
actions.replaceAccount(updated)
+ posthog.capture(AccountsEvents.RoleAssigned, {
+ role,
+ is_assigned: user !== null,
+ assigned_user_id: user?.id ?? null,
+ source: 'list_row',
+ })
dataNodeLogic.findMounted({ key: ACCOUNTS_HOGQL_DATA_NODE_KEY })?.actions.loadData('force_async')
} catch (error) {
posthog.captureException(error as Error, { scope: 'accountsLogic.updateAccountRole' })
@@ -420,6 +504,9 @@ export const accountsLogic = kea<accountsLogicType>([
}
},
})),
+ afterMount(() => {
+ posthog.capture(AccountsEvents.ListViewed)
+ }),
actionToUrl(({ values }) => {
// Mirror the full view into the URL hash so the link is shareable.
// Search params are preserved untouched — the parent scene owns those.
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
index f9b983957405..5dae26baae06 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsOverviewTilesLogic.ts
@@ -1,6 +1,9 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
import { v4 as uuidv4 } from 'uuid'
+import { objectsEqual } from 'lib/utils'
+
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { AccountsQueryResponse, DataNode } from '~/queries/schema/schema-general'
@@ -9,6 +12,7 @@ import { AccountColumnGroup, AccountColumnOption, accountsColumnConfigLogic } fr
import type { accountsOverviewTilesLogicType } from './accountsOverviewTilesLogicType'
import {
ACCOUNTS_OVERVIEW_PERSIST_CONFIG,
+ AccountsEvents,
AccountsOverviewThresholdOperator,
DEFAULT_TILES,
MAX_ACCOUNTS_OVERVIEW_TILES,
@@ -132,6 +136,25 @@ function reconcileTilesAgainstSchema(
})
}
+export function diffOverviewTiles(
+ before: AccountsOverviewTile[],
+ after: AccountsOverviewTile[]
+): { changed: boolean; added: number; removed: number; updated: number; reordered: boolean } {
+ const beforeById = new Map(before.map((tile) => [tile.id, tile]))
+ const afterById = new Map(after.map((tile) => [tile.id, tile]))
+ const added = after.filter((tile) => !beforeById.has(tile.id)).length
+ const removed = before.filter((tile) => !afterById.has(tile.id)).length
+ const updated = after.filter((tile) => {
+ const previous = beforeById.get(tile.id)
+ return !!previous && !objectsEqual(previous, tile)
+ }).length
+ const reordered = !objectsEqual(
+ before.filter((tile) => afterById.has(tile.id)).map((tile) => tile.id),
+ after.filter((tile) => beforeById.has(tile.id)).map((tile) => tile.id)
+ )
+ return { changed: added > 0 || removed > 0 || updated > 0 || reordered, added, removed, updated, reordered }
+}
+
export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([
path(['scenes', 'customerAnalytics', 'accounts', 'accountsOverviewTilesLogic']),
connect(() => ({
@@ -225,7 +248,28 @@ export const accountsOverviewTilesLogic = kea<accountsOverviewTilesLogicType>([
tilesLoading: [(s) => [s.accountsResponseLoading], (loading: boolean): boolean => loading],
selectedTileId: [(s) => [s.tileFilter], (filter: TileFilter | null): string | null => filter?.tileId ?? null],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, values, cache }) => ({
+ showEditor: () => {
+ cache.tilesSnapshot = values.tiles
+ },
+ hideEditor: () => {
+ const before: AccountsOverviewTile[] | undefined = cache.tilesSnapshot
+ cache.tilesSnapshot = undefined
+ if (!before) {
+ return
+ }
+ const diff = diffOverviewTiles(before, values.tiles)
+ if (diff.changed) {
+ posthog.capture(AccountsEvents.OverviewTilesEdited, {
+ tiles_added: diff.added,
+ tiles_removed: diff.removed,
+ tiles_updated: diff.updated,
+ reordered: diff.reordered,
+ tile_count_before: before.length,
+ tile_count_after: values.tiles.length,
+ })
+ }
+ },
removeTile: ({ id }) => {
if (values.tileFilter?.tileId === id) {
actions.setTileFilter(null)
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index 99702d8bd3f0..b236e4eaeee0 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -16,3 +16,22 @@ export const ACCOUNTS_OVERVIEW_PERSIST_CONFIG = {
persist: true,
prefix: `${teamIdForPersistence}_customer_analytics_accounts_overview__`,
}
+
+// Canonical analytics event names for the accounts list. Every `posthog.capture`
+// in this directory must reference these — a mistyped string silently forks a new
+// event in PostHog and breaks reporting without any error. Keep in sync with the
+// analytics table in AGENTS.md.
+export const AccountsEvents = {
+ ListViewed: 'customer analytics accounts list viewed',
+ FilterChanged: 'customer analytics accounts filter changed',
+ Searched: 'customer analytics accounts searched',
+ Refreshed: 'customer analytics accounts refreshed',
+ Sorted: 'customer analytics accounts sorted',
+ ColumnsSaved: 'customer analytics accounts columns saved',
+ OverviewTilesEdited: 'customer analytics accounts overview tiles edited',
+ RoleAssigned: 'customer analytics account role assigned',
+ LinkClicked: 'customer analytics account link clicked',
+ NoteClicked: 'customer analytics account note clicked',
+ TabViewed: 'customer analytics account tab viewed',
+ RelatedUserClicked: 'customer analytics account related user clicked',
+} as const