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): copy selected user emails (#101178)

Arthur Moreira de Deusb375d31315c0
diff --git a/frontend/src/lib/lemon-ui/LemonCheckbox/LemonCheckbox.tsx b/frontend/src/lib/lemon-ui/LemonCheckbox/LemonCheckbox.tsx
index 5e6995b84037..41ace7225156 100644
--- a/frontend/src/lib/lemon-ui/LemonCheckbox/LemonCheckbox.tsx
+++ b/frontend/src/lib/lemon-ui/LemonCheckbox/LemonCheckbox.tsx
@@ -27,6 +27,7 @@ export interface LemonCheckboxProps {
/** @deprecated See https://github.com/PostHog/posthog/pull/9357#pullrequestreview-933783868. */
color?: string
'data-attr'?: string
+ 'aria-label'?: string
/** Whether to stop propagation of events from the input */
stopPropagation?: boolean
/** Removes input semantics when an ancestor owns the interaction. */
@@ -60,6 +61,7 @@ export function LemonCheckbox({
color,
size,
'data-attr': dataAttr,
+ 'aria-label': ariaLabel,
stopPropagation,
decorative,
}: LemonCheckboxProps): JSX.Element {
@@ -122,6 +124,7 @@ export function LemonCheckbox({
}}
id={id}
disabled={disabled}
+ aria-label={ariaLabel}
tabIndex={decorative ? -1 : undefined}
aria-hidden={decorative || undefined}
/>
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 58b10d5c7d0d..3d77bf5e5c84 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -28,7 +28,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
└── passes a memoized DataTable context, so unrelated state updates keep memoized table rows intact
└── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Feature requests/Usage/Spend/Opportunities/Conversations/Meetings/Event stream)
├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)
- ├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId; staff get a compact, region-aware admin link)
+ ├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId; supports bulk email copy; staff get a compact, region-aware admin link)
├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated; assign/unassign controls + definition filter, admin-only hard-delete controls with confirmation, current assignments sorted on top)
├── (feature requests) AccountFeatureRequestsExpansion (accountFeatureRequestsLogic, keyed by accountId — linked requests and link-existing flow)
├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)
@@ -189,7 +189,7 @@ With the flag disabled, the body is `AccountNotebooksExpansion`: the Useful link
**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. 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.)
+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.)
Usage aggregation lives in `billingUsageQuery.ts`: the Usage tab wraps the saved daily query to sum its configured value columns into day/week/month buckets, preserving account/date variables and query tags. `accountBillingLogic.displayInsights` supplies the same derived query to preloads and rendered charts. The interval is part of the cache key, survives tab switches, and defaults to daily. `AccountDetailTabs` holds a usage-logic mount so the detail scene keeps that state too. Weeks start Monday; edge buckets include only dates within the selected range. Automatic usage charts render as account-owned line charts so the series controls wrap outside the plot. Spend retains its saved calculations.
@@ -402,6 +402,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |
| `customer analytics account related users filtered` | `accountRelatedUsersLogic` `setLevels` listener | `levels` (selected `OrganizationMembershipLevel[]`) |
| `customer analytics account related users sorted` | `accountRelatedUsersLogic` `setSorting` listener | `column` (`level` \| `last_login` \| `null`), `direction` (`asc` \| `desc` \| `cleared`) |
+| `customer analytics account related user emails copied` | `AccountRelatedUsersExpansion.tsx` "Copy email addresses" bulk action after a successful clipboard write | `user_count` (email addresses stay out) |
| `customer analytics account related user admin opened` | `AccountRelatedUsersExpansion.tsx` staff-only "Impersonate" button | `region` (`US` \| `EU`; user ID kept out) |
| `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |
| `customer analytics account summary cadence changed` | `accountSummariesLogic` `setCadence` listener (after the PATCH succeeds) | `cadence` (`daily` \| `weekly` \| `monthly` \| `off`) |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx
index 6e7af07bad68..389fd40643de 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx
@@ -1,10 +1,11 @@
import '@testing-library/jest-dom'
-import { cleanup, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { Provider } from 'kea'
import api from 'lib/api'
import { OrganizationMembershipLevel } from 'lib/constants'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { userLogic } from 'scenes/userLogic'
import type { HogQLQueryResponse } from '~/queries/schema/schema-general'
@@ -16,50 +17,62 @@ import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'
jest.mock('lib/components/TZLabel', () => ({
TZLabel: ({ time }: { time: string }) => <span>{time}</span>,
}))
+jest.mock('lib/utils/copyToClipboard', () => ({
+ copyToClipboard: jest.fn().mockResolvedValue(true),
+}))
+
+const buildEuRow = (
+ userId: number,
+ membershipId: string,
+ level: OrganizationMembershipLevel,
+ firstName: string,
+ lastName: string,
+ email: string | null,
+ distinctId: string,
+ lastLogin: string | null
+): unknown[] => [userId, membershipId, level, firstName, lastName, email, distinctId, lastLogin]
+
+const ALEX_ROW = buildEuRow(
+ 42,
+ 'membership-1',
+ OrganizationMembershipLevel.Owner,
+ 'Alex',
+ 'Mercer',
+ 'distinct-1',
+ '2026-01-02T03:04:05Z'
+)
+const JORDAN_ROW = buildEuRow(
+ 43,
+ 'membership-2',
+ OrganizationMembershipLevel.Member,
+ 'Jordan',
+ 'Bell',
+ 'distinct-2',
+ null
+)
describe('AccountRelatedUsersExpansion', () => {
beforeEach(() => {
initKeaTests()
jest.restoreAllMocks()
+ jest.mocked(copyToClipboard).mockClear()
userLogic.actions.loadUserSuccess({ is_staff: true } as UserType)
- })
-
- afterEach(() => {
- cleanup()
- })
-
- it('shows the EU member access level and opens them in the current admin', async () => {
jest.spyOn(api.organizationMembers, 'listForOrg').mockResolvedValue({
count: 0,
next: null,
previous: null,
results: [],
})
- jest.spyOn(api, 'query').mockResolvedValue({
- results: [
- [
- 42,
- 'membership-1',
- OrganizationMembershipLevel.Owner,
- 'Alex',
- 'Mercer',
- 'distinct-1',
- '2026-01-02T03:04:05Z',
- ],
- [
- 43,
- 'membership-2',
- OrganizationMembershipLevel.Member,
- 'Jordan',
- 'Bell',
- 'distinct-2',
- null,
- ],
- ],
- } as HogQLQueryResponse)
+ jest.spyOn(api, 'query').mockResolvedValue({ results: [ALEX_ROW, JORDAN_ROW] } as HogQLQueryResponse)
+ })
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('shows the EU member access level and opens them in the current admin', async () => {
render(
<Provider>
<AccountRelatedUsersExpansion externalId="organization-1" />
@@ -79,4 +92,59 @@ describe('AccountRelatedUsersExpansion', () => {
const [impersonateButton] = await screen.findAllByText('Impersonate')
expect(impersonateButton.closest('a')).toHaveAttribute('href', 'http://localhost/admin/posthog/user/42/change/')
})
+
+ it('copies selected emails across pages and excludes users without an email address', async () => {
+ const fillerRows = Array.from({ length: 19 }, (_, index) =>
+ buildEuRow(
+ 100 + index,
+ `membership-${index + 3}`,
+ OrganizationMembershipLevel.Member,
+ `Member${index + 1}`,
+ 'Example',
+ `member${index + 1}@example.com`,
+ `distinct-${index + 3}`,
+ null
+ )
+ )
+ jest.mocked(api.query).mockResolvedValue({
+ results: [
+ ALEX_ROW,
+ ...fillerRows,
+ JORDAN_ROW,
+ buildEuRow(
+ 44,
+ 'membership-without-email',
+ OrganizationMembershipLevel.Member,
+ 'Taylor',
+ 'Stone',
+ null,
+ 'distinct-without-email',
+ null
+ ),
+ ],
+ } as HogQLQueryResponse)
+
+ render(
+ <Provider>
+ <AccountRelatedUsersExpansion externalId="organization-1" />
+ </Provider>
+ )
+
+ expect(await screen.findByText('Owner')).toBeInTheDocument()
+ fireEvent.click(screen.getByLabelText('Select user Alex Mercer'))
+ fireEvent.click(screen.getByLabelText('Next page'))
+
+ expect(await screen.findByText('Jordan Bell')).toBeInTheDocument()
+ expect(screen.getByText('1 user selected')).toBeInTheDocument()
+ expect(screen.getByLabelText('Select user Taylor Stone')).toBeDisabled()
+ fireEvent.click(screen.getByLabelText('Select user Jordan Bell'))
+
+ const copyButton = screen.getByText('Copy email addresses')
+ expect(document.querySelector('[data-attr="customer-analytics-account-users-toolbar"]')).toContainElement(
+ copyButton
+ )
+ fireEvent.click(copyButton)
+
+ expect(copyToClipboard).toHaveBeenCalledWith('[email protected]\[email protected]', 'email addresses')
+ })
})
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
index f555793bdf2a..1e8e704befc9 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
@@ -1,10 +1,13 @@
import { useActions, useValues } from 'kea'
import posthog from 'posthog-js'
+import { useState } from 'react'
+import { IconCopy } from '@posthog/icons'
import { LemonButton, LemonInput, LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { OrganizationMembershipLevel } from 'lib/constants'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { membershipLevelToName } from 'lib/utils/permissioning'
import { capitalizeFirstLetter, fullName } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
@@ -35,6 +38,7 @@ export function AccountRelatedUsersExpansion({
const { membersResponse, membersResponseLoading, page, searchTerm, levels, sorting } = useValues(logic)
const { user } = useValues(userLogic)
const { setPage, setSearchTerm, setLevels, setSorting } = useActions(logic)
+ const [bulkBarTarget, setBulkBarTarget] = useState<HTMLDivElement | null>(null)
const columns: LemonTableColumns<AccountOrganizationMember> = [
{
@@ -111,17 +115,24 @@ export function AccountRelatedUsersExpansion({
return (
<div className="flex flex-col gap-2">
- <LemonInput
- type="search"
- value={searchTerm}
- onChange={setSearchTerm}
- placeholder="Search users by name or email..."
- maxLength={200}
- size="small"
- className="min-w-64"
- data-attr="customer-analytics-account-users-search"
- />
+ <div
+ className="flex flex-wrap items-center justify-between gap-2"
+ data-attr="customer-analytics-account-users-toolbar"
+ >
+ <LemonInput
+ type="search"
+ value={searchTerm}
+ onChange={setSearchTerm}
+ placeholder="Search users by name or email..."
+ maxLength={200}
+ size="small"
+ className="min-w-64 max-w-80 grow"
+ data-attr="customer-analytics-account-users-search"
+ />
+ <div ref={setBulkBarTarget} className="flex items-center empty:hidden" />
+ </div>
<LemonTable<AccountOrganizationMember>
+ key={externalId}
size="small"
embedded={embedded}
dataSource={membersResponse?.results ?? []}
@@ -140,6 +151,38 @@ export function AccountRelatedUsersExpansion({
onForward: () => setPage(page + 1),
onBackward: () => setPage(page - 1),
}}
+ bulkSelection={{
+ getKey: (member) => member.user.email,
+ isRowSelectable: (member) =>
+ member.user.email ? true : { disabledReason: 'This user has no email address' },
+ noun: ['user', 'users'],
+ rowAriaLabel: (member) =>
+ `Select user ${fullName(member.user) || member.user.email || 'without an email address'}`,
+ headerAriaLabel: 'Select all users on this page',
+ barPortalTarget: bulkBarTarget,
+ renderActions: (context) => (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconCopy />}
+ data-attr="customer-analytics-account-users-copy-emails"
+ onClick={() => {
+ void copyToClipboard(
+ context.selectedKeys.join('\n'),
+ context.selectedCount === 1 ? 'email address' : 'email addresses'
+ ).then((copied) => {
+ if (copied) {
+ posthog.capture(AccountsEvents.RelatedUserEmailsCopied, {
+ user_count: context.selectedCount,
+ })
+ }
+ })
+ }}
+ >
+ Copy email addresses
+ </LemonButton>
+ ),
+ }}
emptyState={
!externalId
? 'This account has no linked organization.'
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index 7afc3ae1414b..d0cebb071754 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -59,6 +59,7 @@ export const AccountsEvents = {
RelatedUsersSearched: 'customer analytics account related users searched',
RelatedUsersFiltered: 'customer analytics account related users filtered',
RelatedUsersSorted: 'customer analytics account related users sorted',
+ RelatedUserEmailsCopied: 'customer analytics account related user emails copied',
RelatedUserAdminOpened: 'customer analytics account related user admin opened',
OpportunityClicked: 'customer analytics account opportunity clicked',
SummaryCadenceChanged: 'customer analytics account summary cadence changed',