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): configurable persons table for account users (#121474)

Arthur Moreira de Deusc7e9c4b4c92e
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index ba12ca6e111d..4eeb0b4b72e8 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -287,6 +287,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_USERS_TABLE: 'customer-analytics-account-users-table', // owner: @arthurdedeus #team-customer-analytics, swaps the account Users tab to a configurable persons table
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
diff --git a/frontend/src/queries/nodes/DataTable/DataTableExport.tsx b/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
index 5b0c22212072..e74e2b7ccd6e 100644
--- a/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
+++ b/frontend/src/queries/nodes/DataTable/DataTableExport.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import { useState } from 'react'
import { IconDownload } from '@posthog/icons'
import { LemonButton, LemonDialog, LemonInput, LemonMenu } from '@posthog/lemon-ui'
@@ -37,6 +38,7 @@ import {
} from '~/queries/utils'
import { AccessControlLevel, AccessControlResourceType, ExportContext, ExporterFormat } from '~/types'
+import { DataTableExportColumnsModal } from './DataTableExportColumnsModal'
import { dataTableLogic } from './dataTableLogic'
// Sync with posthog/hogql/constants.py
@@ -49,7 +51,8 @@ export async function startDownload(
onlySelectedColumns: boolean,
exportCall: (exportData: TriggerExportProps) => void,
format: ExporterFormat = ExporterFormat.CSV,
- fileNameForExport?: string
+ fileNameForExport?: string,
+ columnsOverride?: string[]
): Promise<void> {
const shouldOptimize = shouldOptimizeForExport(query)
@@ -73,6 +76,7 @@ export async function startDownload(
if (onlySelectedColumns) {
let columns = (
+ columnsOverride ??
(isEventsQuery(query.source) ||
isActorsQuery(query.source) ||
isGroupsQuery(query.source) ||
@@ -129,6 +133,7 @@ export function DataTableExport({
}: DataTableExportProps): JSX.Element | null {
const { dataTableRows, columnsInResponse, columnsInQuery, queryWithDefaults } = useValues(dataTableLogic)
const { startExport, createStaticCohort } = useActions(exportsLogic)
+ const [isColumnsModalOpen, setIsColumnsModalOpen] = useState(false)
const responseColumns = columnsInResponse ?? columnsInQuery
const exportColumns = responseColumns.filter((column) => !excludedColumns.includes(column))
const exportQuery = downloadQuery ?? (excludedColumns.length ? { ...query, columns: exportColumns } : query)
@@ -153,154 +158,185 @@ export function DataTableExport({
)
return (
- <LemonMenu
- items={[
- {
- label: 'Export current columns',
- items: [
- {
- label: 'CSV',
- onClick: () => {
- void startDownload(
- exportQuery,
- true,
- startExport,
- ExporterFormat.CSV,
- fileNameForExport
- )
+ <>
+ <LemonMenu
+ items={[
+ {
+ label: 'Export selected columns…',
+ onClick: () => setIsColumnsModalOpen(true),
+ 'data-attr': 'data-table-export-selected-columns',
+ },
+ {
+ label: 'Export current columns',
+ items: [
+ {
+ label: 'CSV',
+ onClick: () => {
+ void startDownload(
+ exportQuery,
+ true,
+ startExport,
+ ExporterFormat.CSV,
+ fileNameForExport
+ )
+ },
},
- },
- {
- label: 'XLSX',
- onClick: () => {
- void startDownload(
- exportQuery,
- true,
- startExport,
- ExporterFormat.XLSX,
- fileNameForExport
- )
+ {
+ label: 'XLSX',
+ onClick: () => {
+ void startDownload(
+ exportQuery,
+ true,
+ startExport,
+ ExporterFormat.XLSX,
+ fileNameForExport
+ )
+ },
},
- },
- ],
- },
- canExportAllColumns && {
- label: 'Export all columns',
- items: [
- {
- label: 'CSV',
- onClick: () =>
- void startDownload(
- exportQuery,
- false,
- startExport,
- ExporterFormat.CSV,
- fileNameForExport
- ),
- },
- {
- label: 'XLSX',
- onClick: () =>
- void startDownload(
- exportQuery,
- false,
- startExport,
- ExporterFormat.XLSX,
- fileNameForExport
- ),
- },
- ],
- },
- showExportClipboardButtons && {
- label: 'Copy to clipboard',
- items: [
- {
- label: 'CSV',
- onClick: () => {
- if (exportRows) {
- copyTableToCsv(exportRows, exportColumns, queryWithDefaults)
- }
+ ],
+ },
+ canExportAllColumns && {
+ label: 'Export all columns',
+ items: [
+ {
+ label: 'CSV',
+ onClick: () =>
+ void startDownload(
+ exportQuery,
+ false,
+ startExport,
+ ExporterFormat.CSV,
+ fileNameForExport
+ ),
},
- 'data-attr': 'copy-csv-to-clipboard',
- },
- {
- label: 'JSON',
- onClick: () => {
- if (exportRows) {
- copyTableToJson(exportRows, exportColumns, queryWithDefaults)
- }
+ {
+ label: 'XLSX',
+ onClick: () =>
+ void startDownload(
+ exportQuery,
+ false,
+ startExport,
+ ExporterFormat.XLSX,
+ fileNameForExport
+ ),
},
- 'data-attr': 'copy-json-to-clipboard',
- },
- {
- label: 'Excel',
- onClick: () => {
- if (exportRows) {
- copyTableToExcel(exportRows, exportColumns, queryWithDefaults)
- }
+ ],
+ },
+ showExportClipboardButtons && {
+ label: 'Copy to clipboard',
+ items: [
+ {
+ label: 'CSV',
+ onClick: () => {
+ if (exportRows) {
+ copyTableToCsv(exportRows, exportColumns, queryWithDefaults)
+ }
+ },
+ 'data-attr': 'copy-csv-to-clipboard',
},
- 'data-attr': 'copy-excel-to-clipboard',
- },
- ],
- },
- canSaveAsCohort && {
- label: 'Save to cohort',
- items: [
- {
- label: 'Save as static cohort',
- onClick: () => {
- LemonDialog.openForm({
- title: 'Save as static cohort',
- description: 'This will create a cohort with the current list of people.',
- initialValues: {
- name: '',
- },
- content: (
- <LemonField name="name">
- <LemonInput
- type="text"
- data-attr="insight-name"
- placeholder="Name of the new cohort"
- autoFocus
- />
- </LemonField>
- ),
- errors: {
- name: (name) => (!name ? 'You must enter a name' : undefined),
- },
- onSubmit: async ({ name }) => createStaticCohort(name, source),
- })
+ {
+ label: 'JSON',
+ onClick: () => {
+ if (exportRows) {
+ copyTableToJson(exportRows, exportColumns, queryWithDefaults)
+ }
+ },
+ 'data-attr': 'copy-json-to-clipboard',
},
- },
- {
- label: 'Add to existing cohort',
- onClick: () => {
- LemonDialog.open({
- title: 'Add to existing cohort',
- description: 'This will add the current list of people to a static cohort.',
- content: (closeDialog) => (
- <SaveToCohortModalContent closeModal={closeDialog} query={source} />
- ),
- primaryButton: null,
- secondaryButton: {
- children: 'Cancel',
- },
- })
+ {
+ label: 'Excel',
+ onClick: () => {
+ if (exportRows) {
+ copyTableToExcel(exportRows, exportColumns, queryWithDefaults)
+ }
+ },
+ 'data-attr': 'copy-excel-to-clipboard',
+ },
+ ],
+ },
+ canSaveAsCohort && {
+ label: 'Save to cohort',
+ items: [
+ {
+ label: 'Save as static cohort',
+ onClick: () => {
+ LemonDialog.openForm({
+ title: 'Save as static cohort',
+ description: 'This will create a cohort with the current list of people.',
+ initialValues: {
+ name: '',
+ },
+ content: (
+ <LemonField name="name">
+ <LemonInput
+ type="text"
+ data-attr="insight-name"
+ placeholder="Name of the new cohort"
+ autoFocus
+ />
+ </LemonField>
+ ),
+ errors: {
+ name: (name) => (!name ? 'You must enter a name' : undefined),
+ },
+ onSubmit: async ({ name }) => createStaticCohort(name, source),
+ })
+ },
+ },
+ {
+ label: 'Add to existing cohort',
+ onClick: () => {
+ LemonDialog.open({
+ title: 'Add to existing cohort',
+ description: 'This will add the current list of people to a static cohort.',
+ content: (closeDialog) => (
+ <SaveToCohortModalContent closeModal={closeDialog} query={source} />
+ ),
+ primaryButton: null,
+ secondaryButton: {
+ children: 'Cancel',
+ },
+ })
+ },
},
- },
- ],
- },
- ].filter(Boolean)}
- >
- <LemonButton
- type="secondary"
- icon={<IconDownload />}
- data-attr="data-table-export-menu"
- size="small"
- disabledReason={accessControlDisabledReason ?? undefined}
+ ],
+ },
+ ].filter(Boolean)}
>
- Export{filterCount > 0 ? ` (${pluralize(filterCount, 'filter')})` : ''}
- </LemonButton>
- </LemonMenu>
+ <LemonButton
+ type="secondary"
+ icon={<IconDownload />}
+ data-attr="data-table-export-menu"
+ size="small"
+ disabledReason={accessControlDisabledReason ?? undefined}
+ >
+ Export{filterCount > 0 ? ` (${pluralize(filterCount, 'filter')})` : ''}
+ </LemonButton>
+ </LemonMenu>
+ <DataTableExportColumnsModal
+ isOpen={isColumnsModalOpen}
+ onClose={() => setIsColumnsModalOpen(false)}
+ columns={exportColumns.filter(
+ (column) => !columnDisallowList.includes(column) && !query.hiddenColumns?.includes(column)
+ )}
+ canCopy={showExportClipboardButtons || isActorsQuery(source)}
+ // A separate download query can name its columns differently, so the table's names do not map onto it.
+ canDownload={!downloadQuery}
+ downloadDisabledReason={accessControlDisabledReason ?? undefined}
+ onCopy={(columns, includeHeader) => {
+ if (exportRows) {
+ copyTableToCsv(
+ projectExportRows(exportRows, exportColumns, columns),
+ columns,
+ queryWithDefaults,
+ includeHeader
+ )
+ }
+ }}
+ onDownload={(columns, format) =>
+ void startDownload(exportQuery, true, startExport, format, fileNameForExport, columns)
+ }
+ />
+ </>
)
}
diff --git a/frontend/src/queries/nodes/DataTable/DataTableExportColumnsModal.tsx b/frontend/src/queries/nodes/DataTable/DataTableExportColumnsModal.tsx
new file mode 100644
index 000000000000..441e8d746511
--- /dev/null
+++ b/frontend/src/queries/nodes/DataTable/DataTableExportColumnsModal.tsx
@@ -0,0 +1,125 @@
+import { useState } from 'react'
+
+import { IconCopy, IconDownload } from '@posthog/icons'
+import { LemonButton, LemonCheckbox, LemonDivider, LemonModal } from '@posthog/lemon-ui'
+
+import { extractExpressionComment } from '~/queries/nodes/DataTable/utils'
+import { ExporterFormat } from '~/types'
+
+interface DataTableExportColumnsModalProps {
+ isOpen: boolean
+ onClose: () => void
+ columns: string[]
+ canCopy: boolean
+ canDownload: boolean
+ downloadDisabledReason?: string
+ onCopy: (columns: string[], includeHeader: boolean) => void
+ onDownload: (columns: string[], format: ExporterFormat) => void
+}
+
+export function DataTableExportColumnsModal({
+ isOpen,
+ onClose,
+ columns,
+ canCopy,
+ canDownload,
+ downloadDisabledReason,
+ onCopy,
+ onDownload,
+}: DataTableExportColumnsModalProps): JSX.Element {
+ const [selectedColumns, setSelectedColumns] = useState<string[]>([])
+ const [includeHeader, setIncludeHeader] = useState(false)
+ const orderedSelection = columns.filter((column) => selectedColumns.includes(column))
+ const noColumnsReason = orderedSelection.length === 0 ? 'Select at least one column' : undefined
+
+ // Resets after the close animation, so the content doesn't change while it fades out.
+ const resetSelection = (): void => {
+ setSelectedColumns([])
+ setIncludeHeader(false)
+ }
+
+ const toggleColumn = (column: string, checked: boolean): void =>
+ setSelectedColumns((current) => (checked ? [...current, column] : current.filter((c) => c !== column)))
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={onClose}
+ onAfterClose={resetSelection}
+ title="Export selected columns"
+ description={
+ canDownload
+ ? 'Downloads include every matching row. Copying includes only the rows loaded in the table.'
+ : 'Copying includes only the rows loaded in the table.'
+ }
+ footer={
+ <>
+ {canDownload && (
+ <>
+ <LemonButton
+ type="secondary"
+ icon={<IconDownload />}
+ disabledReason={noColumnsReason ?? downloadDisabledReason}
+ onClick={() => {
+ onDownload(orderedSelection, ExporterFormat.CSV)
+ onClose()
+ }}
+ data-attr="data-table-export-selected-columns-csv"
+ >
+ Download CSV
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ icon={<IconDownload />}
+ disabledReason={noColumnsReason ?? downloadDisabledReason}
+ onClick={() => {
+ onDownload(orderedSelection, ExporterFormat.XLSX)
+ onClose()
+ }}
+ data-attr="data-table-export-selected-columns-xlsx"
+ >
+ Download XLSX
+ </LemonButton>
+ </>
+ )}
+ {canCopy && (
+ <LemonButton
+ type="primary"
+ icon={<IconCopy />}
+ disabledReason={noColumnsReason}
+ onClick={() => {
+ onCopy(orderedSelection, includeHeader)
+ onClose()
+ }}
+ data-attr="data-table-export-selected-columns-copy"
+ >
+ Copy to clipboard
+ </LemonButton>
+ )}
+ </>
+ }
+ >
+ <div className="flex flex-col gap-1 max-h-80 overflow-y-auto">
+ {columns.map((column) => (
+ <LemonCheckbox
+ key={column}
+ checked={selectedColumns.includes(column)}
+ onChange={(checked) => toggleColumn(column, checked)}
+ label={extractExpressionComment(column)}
+ data-attr="data-table-export-selected-columns-option"
+ />
+ ))}
+ </div>
+ {canCopy && (
+ <>
+ <LemonDivider />
+ <LemonCheckbox
+ checked={includeHeader}
+ onChange={setIncludeHeader}
+ label="Include column names when copying"
+ />
+ </>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts b/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
index 9e4ad68ddd99..0c4f7028dc21 100644
--- a/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
+++ b/frontend/src/queries/nodes/DataTable/clipboardUtils.test.ts
@@ -148,6 +148,19 @@ describe('clipboardUtils', () => {
expect(result[1][1]).toBe('[email protected]') // asDisplay returns email (person display property)
})
+ it('handles ActorsQuery with a person display name column', () => {
+ const columns = ['person_display_name -- Person', 'properties.email -- Email']
+ const query = createMockQuery(NodeKind.ActorsQuery, { select: columns })
+ const rows: DataTableRow[] = [
+ { result: [{ display_name: 'Ana', id: 'uuid-1', distinct_id: 'ana' }, '[email protected]'] },
+ ]
+
+ expect(getCsvTableData(rows, columns, query)).toEqual([
+ ['Person', 'Email'],
+ ['Ana', '[email protected]'],
+ ])
+ })
+
it('handles PersonsNode with nested properties', () => {
const query = createMockQuery(NodeKind.PersonsNode)
const columns = ['email', 'properties']
@@ -293,8 +306,10 @@ describe('clipboardUtils', () => {
const rows: DataTableRow[] = [{ result: ['pageview'] }]
copyTableToCsv(rows, columns, query)
+ copyTableToCsv(rows, columns, query, false)
- expect(mockCopyToClipboard).toHaveBeenCalledWith('event\npageview', 'table')
+ expect(mockCopyToClipboard).toHaveBeenNthCalledWith(1, 'event\npageview', 'table')
+ expect(mockCopyToClipboard).toHaveBeenNthCalledWith(2, 'pageview', 'table')
})
it('shows error on copy failure', () => {
diff --git a/frontend/src/queries/nodes/DataTable/clipboardUtils.ts b/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
index f74c82c6c9ae..e21bc2350d60 100644
--- a/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
+++ b/frontend/src/queries/nodes/DataTable/clipboardUtils.ts
@@ -4,9 +4,15 @@ import { lemonToast } from '@posthog/lemon-ui'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import { extractExpressionComment } from '~/queries/nodes/DataTable/utils'
+import { extractExpressionComment, removeExpressionComment } from '~/queries/nodes/DataTable/utils'
import { DataTableNode } from '~/queries/schema/schema-general'
-import { isEventsQuery, isHogQLQuery, isMarketingAnalyticsTableQuery, isPersonsNode } from '~/queries/utils'
+import {
+ isActorsQuery,
+ isEventsQuery,
+ isHogQLQuery,
+ isMarketingAnalyticsTableQuery,
+ isPersonsNode,
+} from '~/queries/utils'
import { asDisplay } from 'products/persons/frontend/person-utils'
@@ -66,7 +72,7 @@ const processRowData = (row: DataTableRow, columns: string[], query: DataTableNo
return columns.map((col, index) =>
flattenCell(Array.isArray(data) ? data[index] : (data as Record<string, any>)[index], col)
)
- } else if (isEventsQuery(query.source)) {
+ } else if (isEventsQuery(query.source) || isActorsQuery(query.source)) {
return columns.map((col, colIndex) => {
if (columnDisallowList.includes(col)) {
return {}
@@ -80,6 +86,9 @@ const processRowData = (row: DataTableRow, columns: string[], query: DataTableNo
if (col === 'person') {
return { [colName]: asDisplay(value) }
}
+ if (removeExpressionComment(col) === 'person_display_name') {
+ return { [colName]: value?.display_name }
+ }
return flattenCell(value, colName)
})
} else if (isPersonsNode(query.source)) {
@@ -185,9 +194,14 @@ export const getJsonTableData = (
return []
}
-export function copyTableToCsv(dataTableRows: DataTableRow[], columns: string[], query: DataTableNode): void {
+export function copyTableToCsv(
+ dataTableRows: DataTableRow[],
+ columns: string[],
+ query: DataTableNode,
+ includeHeader: boolean = true
+): void {
try {
- const tableData = getCsvTableData(dataTableRows, columns, query)
+ const tableData = getCsvTableData(dataTableRows, columns, query).slice(includeHeader ? 0 : 1)
const csv = Papa.unparse(tableData)
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b5e65e99fb61..3dd9e7068c52 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -69,6 +69,36 @@
"required": ["key", "operator", "type"],
"type": "object"
},
+ "AccountUsersQuery": {
+ "additionalProperties": false,
+ "description": "The persons who use an account. Only valid as an `ActorsQuery` source.",
+ "properties": {
+ "accountId": {
+ "description": "ID of the account whose users to list.",
+ "type": "string"
+ },
+ "kind": {
+ "const": "AccountUsersQuery",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "response": {
+ "$ref": "#/definitions/ActorsQueryResponse"
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["accountId", "kind"],
+ "type": "object"
+ },
"AccountsQuery": {
"additionalProperties": false,
"properties": {
@@ -1275,6 +1305,9 @@
{
"$ref": "#/definitions/PathsV2ActorsQuery"
},
+ {
+ "$ref": "#/definitions/AccountUsersQuery"
+ },
{
"$ref": "#/definitions/HogQLQuery"
}
@@ -39708,6 +39741,7 @@
"UsageMetricsQuery",
"AccountsQuery",
"AccountsTableQuery",
+ "AccountUsersQuery",
"EndpointsUsageOverviewQuery",
"EndpointsUsageTableQuery",
"EndpointsUsageTrendsQuery",
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index d388d761421d..38c647f88570 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -192,6 +192,7 @@ export enum NodeKind {
UsageMetricsQuery = 'UsageMetricsQuery',
AccountsQuery = 'AccountsQuery',
AccountsTableQuery = 'AccountsTableQuery',
+ AccountUsersQuery = 'AccountUsersQuery',
// Endpoints usage queries
EndpointsUsageOverviewQuery = 'EndpointsUsageOverviewQuery',
@@ -3033,6 +3034,7 @@ export interface ActorsQuery extends DataNode<ActorsQueryResponse> {
| ExperimentActorsQuery
| StickinessActorsQuery
| PathsV2ActorsQuery
+ | AccountUsersQuery
| HogQLQuery
select?: HogQLExpression[]
search?: string
@@ -3404,6 +3406,13 @@ export interface AccountsTableQuery extends DataNode<AccountsTableQueryResponse>
offset?: integer
}
+/** The persons who use an account. Only valid as an `ActorsQuery` source. */
+export interface AccountUsersQuery extends DataNode<ActorsQueryResponse> {
+ kind: NodeKind.AccountUsersQuery
+ /** ID of the account whose users to list. */
+ accountId: string
+}
+
export interface TimelineEntry {
/** Session ID. None means out-of-session events */
sessionId?: string
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index 8682809042af..6d153bf73820 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -589,6 +589,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconPieChart,
inMenu: false,
},
+ [NodeKind.AccountUsersQuery]: {
+ name: 'Account users',
+ icon: IconPerson,
+ inMenu: false,
+ },
[NodeKind.EndpointsUsageOverviewQuery]: {
name: 'Endpoints usage overview',
icon: IconPieChart,
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 76263b45b7d3..e8c96044d358 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -90,6 +90,8 @@ from posthog.rate_limit import (
from posthog.schema_migrations.upgrade import upgrade
from products.access_control.backend.facade.user_access_control import UserAccessControlError
+from products.customer_analytics.backend.facade.api import validate_account_users_access
+from products.customer_analytics.backend.facade.constants import ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX
from products.managed_warehouse.backend.facade import query_labels as managed_warehouse_query_labels
from products.managed_warehouse.backend.facade.query_execution import validate_managed_trino_raw_access
from products.warehouse_sources.backend.facade.models import is_managed_warehouse_connection_ready
@@ -207,6 +209,7 @@ def _process_query_request(
# API token must hold the product scope, not just query:read, to run them through
# the generic endpoint.
_QUERY_KIND_SCOPES: dict[str, list[str]] = {
+ "AccountUsersQuery": ["query:read", "account:read", "person:read"],
"AccountsTableQuery": ["query:read", "account:read"],
"ErrorTrackingFingerprintProjectionQuery": ["query:read", "error_tracking:read"],
"ErrorTrackingReleasesQuery": ["query:read", "error_tracking:read"],
@@ -469,6 +472,21 @@ class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
show_progress or request.query_params.get("showProgress", False) == "true"
) # TODO: Remove this once we have a consistent naming convention
query_status = get_query_status(team_id=self.team.pk, query_id=pk, show_progress=show_progress)
+ account_users_account_id = next(
+ (
+ label.removeprefix(ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX)
+ for label in query_status.labels or []
+ if label.startswith(ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX)
+ ),
+ None,
+ )
+ if account_users_account_id is not None:
+ try:
+ validate_account_users_access(
+ self.team, request.user if isinstance(request.user, User) else None, account_users_account_id
+ )
+ except UserAccessControlError as error:
+ raise PermissionDenied(str(error)) from error
if managed_warehouse_query_labels.MANAGED_TRINO_RAW_QUERY_STATUS_LABEL in (query_status.labels or []):
try:
validate_managed_trino_raw_access(self.team, request.user if isinstance(request.user, User) else None)
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 63d5475d22a5..bf1432236164 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -239,7 +239,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
return {"product": Product.LOGS}
case NodeKind.METRICS_QUERY | NodeKind.METRICS_HISTOGRAM_QUERY:
return {"product": Product.METRICS}
- case NodeKind.ACCOUNTS_TABLE_QUERY:
+ case NodeKind.ACCOUNTS_TABLE_QUERY | NodeKind.ACCOUNT_USERS_QUERY:
return {"product": Product.CUSTOMER_ANALYTICS}
case NodeKind.RECORDINGS_QUERY | NodeKind.SESSION_BATCH_EVENTS_QUERY:
return {"product": Product.REPLAY}
diff --git a/posthog/hogql_queries/actors_query_runner.py b/posthog/hogql_queries/actors_query_runner.py
index a17a505bf368..7812ee8205d0 100644
--- a/posthog/hogql_queries/actors_query_runner.py
+++ b/posthog/hogql_queries/actors_query_runner.py
@@ -98,6 +98,18 @@ class ActorsQueryRunner(AnalyticsQueryRunner[ActorsQueryResponse]):
analytics_props=analytics_props,
)
+ def validate_query_runner_access(self, user: User) -> bool:
+ if self.source_query_runner is not None:
+ self.source_query_runner.validate_query_runner_access(user)
+ return super().validate_query_runner_access(user)
+
+ def get_cache_key_variant(self) -> str:
+ source_variant = self.source_query_runner.get_cache_key_variant() if self.source_query_runner else ""
+ return super().get_cache_key_variant() + source_variant
+
+ def query_status_labels(self) -> list[str] | None:
+ return self.source_query_runner.query_status_labels() if self.source_query_runner is not None else None
+
@property
def group_type_index(self) -> int | None:
if not self.source_query_runner or not isinstance(self.source_query_runner, InsightActorsQueryRunner):
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index b57681a9f285..166cfc3a44fb 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -1659,6 +1659,18 @@ def get_query_runner(
user=user,
)
+ if kind == "AccountUsersQuery":
+ from products.customer_analytics.backend.facade.queries import AccountUsersQueryRunner
+
+ return AccountUsersQueryRunner(
+ query=query,
+ team=team,
+ timings=timings,
+ modifiers=modifiers,
+ limit_context=limit_context,
+ user=user,
+ )
+
if kind == "AccountsTableQuery":
from products.customer_analytics.backend.facade.queries import AccountsTableQueryRunner
diff --git a/posthog/models/test/test_user_model.py b/posthog/models/test/test_user_model.py
index c4a9f645b64f..fee45b10fbe7 100644
--- a/posthog/models/test/test_user_model.py
+++ b/posthog/models/test/test_user_model.py
@@ -55,6 +55,7 @@ class TestUser(BaseTest):
"completed_onboarding_once": False,
"organization_id": str(organization.id),
"current_organization_membership_level": 15,
+ "current_organization_membership_level_name": "owner",
"project_id": str(team.uuid),
"project_setup_complete": False,
"has_password_set": True,
@@ -91,6 +92,7 @@ class TestUser(BaseTest):
"completed_onboarding_once": True,
"organization_id": str(self.organization.id),
"current_organization_membership_level": 1,
+ "current_organization_membership_level_name": "member",
"project_id": str(self.team.uuid),
"project_setup_complete": True,
"has_password_set": True,
diff --git a/posthog/models/user.py b/posthog/models/user.py
index d01a6d7fe011..a19aa97a13d8 100644
--- a/posthog/models/user.py
+++ b/posthog/models/user.py
@@ -602,6 +602,9 @@ class User(AbstractUser, UUIDTClassicModel, ModelActivityMixin): # type: ignore
"current_organization_membership_level": (
current_organization_membership.level if current_organization_membership else None
),
+ "current_organization_membership_level_name": (
+ current_organization_membership.get_level_display() if current_organization_membership else None
+ ),
"project_id": str(self.team.uuid) if self.team else None,
"project_setup_complete": project_setup_complete,
"joined_at": self.date_joined,
diff --git a/posthog/schema.py b/posthog/schema.py
index 1de4cd5828e6..6282abcc12f4 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -26427,6 +26427,18 @@ class WebVitalsQueryResponse(BaseModel):
)
+class AccountUsersQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ accountId: str = Field(..., description="ID of the account whose users to list.")
+ kind: Literal["AccountUsersQuery"] = "AccountUsersQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ response: ActorsQueryResponse | None = None
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class AccountsQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -33060,6 +33072,7 @@ class ActorsQuery(BaseModel):
| ExperimentActorsQuery
| StickinessActorsQuery
| PathsV2ActorsQuery
+ | AccountUsersQuery
| HogQLQuery
| None
) = None
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index ac75d813268c..b85ef25f1e97 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2442,6 +2442,7 @@ class NodeKind(StrEnum):
USAGE_METRICS_QUERY = "UsageMetricsQuery"
ACCOUNTS_QUERY = "AccountsQuery"
ACCOUNTS_TABLE_QUERY = "AccountsTableQuery"
+ ACCOUNT_USERS_QUERY = "AccountUsersQuery"
ENDPOINTS_USAGE_OVERVIEW_QUERY = "EndpointsUsageOverviewQuery"
ENDPOINTS_USAGE_TABLE_QUERY = "EndpointsUsageTableQuery"
ENDPOINTS_USAGE_TRENDS_QUERY = "EndpointsUsageTrendsQuery"
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.py
index 4a63c396cbb4..cff051615474 100644
--- a/products/customer_analytics/backend/constants.py
+++ b/products/customer_analytics/backend/constants.py
@@ -61,3 +61,6 @@ SLACK_SUMMARY_CADENCE_CHOICES = ["daily", "weekly", "monthly"]
DELIVERY_IN_FLIGHT_ERROR = "in_flight"
DELIVERY_RATE_LIMIT_DEFERRED_ERROR = "rate_limited_deferred"
DELIVERY_INTERRUPTED_ERROR = "interrupted before confirmation; the message may have been delivered"
+
+# Marks an async query status whose stored results are account users, so retrieval repeats the access check.
+ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX = "customer-analytics-account-users:"
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 7947c642ce44..8a8412ae89cf 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -129,6 +129,7 @@ from products.customer_analytics.backend.logic.account_filters import (
parse_email_search,
)
from products.customer_analytics.backend.logic.account_logo import resolve_logo_domain
+from products.customer_analytics.backend.logic.account_member_search import get_account_users_organization_id
from products.customer_analytics.backend.logic.custom_property_definitions import (
apply_option_side_effects,
coerce_is_big_number,
@@ -394,6 +395,11 @@ def _resolve_accessible_account(
return None
+def validate_account_users_access(team: Team, user: "User | None", account_id: str) -> None:
+ """Raise `UserAccessControlError` unless `user` may read the users of this account."""
+ get_account_users_organization_id(team=team, user=user, account_id=account_id)
+
+
def get_account(
team_id: int, account_id: str | None = None, external_id: str | None = None
) -> contracts.Account | None:
diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.py
index 7776e3344384..d79ffc7d2dac 100644
--- a/products/customer_analytics/backend/facade/constants.py
+++ b/products/customer_analytics/backend/facade/constants.py
@@ -6,6 +6,7 @@ stays as the source of truth.
"""
from products.customer_analytics.backend.constants import (
+ ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX,
BILLING_SPEND_INSIGHT_SHORT_IDS,
BILLING_USAGE_INSIGHT_SHORT_IDS,
CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES,
@@ -22,6 +23,7 @@ from products.customer_analytics.backend.constants import (
)
__all__ = [
+ "ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX",
"BILLING_SPEND_INSIGHT_SHORT_IDS",
"BILLING_USAGE_INSIGHT_SHORT_IDS",
"CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES",
diff --git a/products/customer_analytics/backend/facade/queries.py b/products/customer_analytics/backend/facade/queries.py
index 92d3f3070c3c..f6212c018c37 100644
--- a/products/customer_analytics/backend/facade/queries.py
+++ b/products/customer_analytics/backend/facade/queries.py
@@ -7,11 +7,13 @@ imports stay out of ``facade/api.py`` so config-only consumers don't drag them o
the ``django.setup()`` path.
"""
+from products.customer_analytics.backend.hogql_queries.account_users_query_runner import AccountUsersQueryRunner
from products.customer_analytics.backend.hogql_queries.accounts_query_runner import AccountsQueryRunner
from products.customer_analytics.backend.hogql_queries.accounts_table_query_runner import AccountsTableQueryRunner
from products.customer_analytics.backend.hogql_queries.usage_metrics_query_runner import UsageMetricsQueryRunner
__all__ = [
+ "AccountUsersQueryRunner",
"AccountsQueryRunner",
"AccountsTableQueryRunner",
"UsageMetricsQueryRunner",
diff --git a/products/customer_analytics/backend/hogql_queries/account_users_query_runner.py b/products/customer_analytics/backend/hogql_queries/account_users_query_runner.py
new file mode 100644
index 000000000000..95547d94a4bd
--- /dev/null
+++ b/products/customer_analytics/backend/hogql_queries/account_users_query_runner.py
@@ -0,0 +1,83 @@
+from posthog.schema import AccountUsersQuery, HogQLQueryResponse
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.models.user import User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControlError
+from products.customer_analytics.backend.constants import ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX
+from products.customer_analytics.backend.logic.account_member_search import (
+ get_account_users_organization_id,
+ list_organization_member_distinct_ids,
+)
+
+
+class AccountUsersQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
+ """Persons who use an account. Runs only as an `ActorsQuery` source, which hydrates the persons.
+
+ The person set comes from the PostHog Cloud organization whose ID is the account's external ID,
+ so it only works in PostHog's own project.
+ """
+
+ query: AccountUsersQuery
+
+ def validate_query_runner_access(self, user: User) -> bool:
+ get_account_users_organization_id(team=self.team, user=user, account_id=self.query.accountId)
+ return True
+
+ def get_cache_key_variant(self) -> str:
+ # Anonymous share-link viewers and cache-only reads skip `validate_query_runner_access`. A
+ # separate key for them misses staff results, and a fresh run then fails the access check.
+ try:
+ get_account_users_organization_id(team=self.team, user=self.user, account_id=self.query.accountId)
+ except UserAccessControlError:
+ return f"{super().get_cache_key_variant()}_denied"
+ return super().get_cache_key_variant()
+
+ def query_status_labels(self) -> list[str]:
+ return [f"{ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX}{self.query.accountId}"]
+
+ def _list_distinct_ids(self) -> tuple[str, ...]:
+ organization_id = get_account_users_organization_id(
+ team=self.team, user=self.user, account_id=self.query.accountId
+ )
+ if organization_id is None:
+ return ()
+ # Narrowed by the access check above, which rejects any principal that is not a User.
+ assert isinstance(self.user, User)
+ return list_organization_member_distinct_ids(team=self.team, user=self.user, organization_id=organization_id)
+
+ def to_query(self) -> ast.SelectQuery:
+ distinct_ids = self._list_distinct_ids()
+ condition: ast.Expr = (
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["distinct_id"]),
+ right=ast.Tuple(exprs=[ast.Constant(value=distinct_id) for distinct_id in distinct_ids]),
+ )
+ if distinct_ids
+ else ast.Constant(value=False)
+ )
+ query = parse_select(
+ "SELECT DISTINCT person_id FROM person_distinct_ids WHERE {condition}",
+ placeholders={"condition": condition},
+ )
+ assert isinstance(query, ast.SelectQuery)
+ return query
+
+ def to_actors_query(self) -> ast.SelectQuery:
+ return self.to_query()
+
+ def _calculate(self) -> HogQLQueryResponse:
+ return execute_hogql_query(
+ query_type="AccountUsersQuery",
+ query=self.to_query(),
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ )
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_account_users_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_account_users_query_runner.py
new file mode 100644
index 000000000000..c58bb02b66e2
--- /dev/null
+++ b/products/customer_analytics/backend/hogql_queries/test/test_account_users_query_runner.py
@@ -0,0 +1,151 @@
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, flush_persons_and_events
+from unittest.mock import patch
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.schema import CacheMissResponse, QueryStatus
+
+from posthog.constants import AvailableFeature
+from posthog.hogql_queries.query_runner import ExecutionMode, get_query_runner
+from posthog.models import Organization, OrganizationMembership, User
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.test.persons import create_person
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.customer_analytics.backend.constants import ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX
+from products.customer_analytics.backend.logic.account_member_search import list_organization_member_distinct_ids
+from products.customer_analytics.backend.test.factories import create_account
+
+FLAG_CHECK = "products.customer_analytics.backend.logic.account_member_search.posthog_feature_flag_enabled"
+
+
+class TestAccountUsersQuery(ClickhouseTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ customer_org = Organization.objects.create(name="Customer")
+ for email in ("[email protected]", "[email protected]"):
+ member = User.objects.create(email=email, distinct_id=f"distinct-{email}")
+ OrganizationMembership.objects.create(organization=customer_org, user=member)
+ create_person(team=self.team, distinct_ids=[member.distinct_id], properties={"email": email})
+ create_person(team=self.team, distinct_ids=["outsider"], properties={"email": "[email protected]"})
+ flush_persons_and_events()
+ self.account = create_account(team_id=self.team.id, external_id=str(customer_org.id))
+ self.query = {
+ "kind": "ActorsQuery",
+ "source": {"kind": "AccountUsersQuery", "accountId": str(self.account.id)},
+ "select": ["properties.email"],
+ "orderBy": ["properties.email DESC"],
+ }
+ self.user.is_staff = True
+ self.user.save()
+
+ def _run(self, headers: dict[str, str] | None = None):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/query/",
+ {"query": self.query, "refresh": "blocking"},
+ format="json",
+ headers=headers,
+ )
+
+ def _hide_account_from_user(self) -> None:
+ self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]
+ self.organization.save()
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(self.account.id),
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(user=self.user, organization=self.organization),
+ )
+
+ @patch(FLAG_CHECK, return_value=True)
+ def test_staff_get_the_organization_members_as_persons(self, _flag) -> None:
+ response = self._run()
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["results"] == [["[email protected]"], ["[email protected]"]]
+
+ @parameterized.expand(
+ [
+ ("not_staff", False, True, False),
+ ("flag_off", True, False, False),
+ ("account_hidden", True, True, True),
+ ]
+ )
+ def test_denies_access_even_when_cached(self, _name, is_staff, flag_on, account_hidden) -> None:
+ with patch(FLAG_CHECK, return_value=True):
+ assert self._run().status_code == status.HTTP_200_OK
+
+ self.user.is_staff = is_staff
+ self.user.save()
+ if account_hidden:
+ self._hide_account_from_user()
+ with patch(FLAG_CHECK, return_value=flag_on):
+ response = self._run()
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "Access control failure" in response.json()["detail"]
+
+ @patch(FLAG_CHECK, return_value=True)
+ def test_cache_only_read_without_a_user_misses_staff_results(self, _flag) -> None:
+ get_query_runner(self.query, self.team, user=self.user).run(
+ ExecutionMode.CALCULATE_BLOCKING_ALWAYS, user=self.user
+ )
+
+ response = get_query_runner(self.query, self.team).run(ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)
+
+ assert isinstance(response, CacheMissResponse)
+
+ @parameterized.expand([("staff", True, status.HTTP_200_OK), ("not_staff", False, status.HTTP_403_FORBIDDEN)])
+ @patch(FLAG_CHECK, return_value=True)
+ def test_async_result_retrieval_repeats_the_access_check(self, _name, is_staff, expected_status, _flag) -> None:
+ self.user.is_staff = is_staff
+ self.user.save()
+ stored = QueryStatus(
+ id="account-users-query",
+ team_id=self.team.id,
+ complete=True,
+ labels=[f"{ACCOUNT_USERS_QUERY_STATUS_LABEL_PREFIX}{self.account.id}"],
+ results={"results": [["[email protected]"]]},
+ )
+
+ with patch("posthog.api.query.get_query_status", return_value=stored):
+ response = self.client.get(f"/api/projects/{self.team.id}/query/account-users-query/")
+
+ assert response.status_code == expected_status, response.content
+
+ @parameterized.expand(
+ [
+ ("query_scope_only", ["query:read"], status.HTTP_403_FORBIDDEN),
+ ("all_scopes", ["query:read", "account:read", "person:read"], status.HTTP_200_OK),
+ ]
+ )
+ @patch(FLAG_CHECK, return_value=True)
+ def test_api_tokens_need_account_and_person_scopes(self, _name, scopes, expected_status, _flag) -> None:
+ token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="account users query",
+ user=self.user,
+ secure_value=hash_key_value(token),
+ scopes=scopes,
+ scoped_teams=[],
+ scoped_organizations=[],
+ )
+
+ response = self._run(headers={"authorization": f"Bearer {token}"})
+
+ assert response.status_code == expected_status, response.content
+
+ def test_eu_lookup_failure_raises_instead_of_returning_no_members(self) -> None:
+ with (
+ patch(
+ "products.customer_analytics.backend.logic.account_member_search.execute_hogql_query",
+ side_effect=TimeoutError("eu lookup timed out"),
+ ),
+ self.assertRaises(TimeoutError),
+ ):
+ list_organization_member_distinct_ids(
+ team=self.team, user=self.user, organization_id=str(Organization.objects.create(name="EU").id)
+ )
diff --git a/products/customer_analytics/backend/logic/account_member_search.py b/products/customer_analytics/backend/logic/account_member_search.py
index ad4bc9b4eff1..a612259ed45c 100644
--- a/products/customer_analytics/backend/logic/account_member_search.py
+++ b/products/customer_analytics/backend/logic/account_member_search.py
@@ -1,11 +1,15 @@
from typing import cast
+from uuid import UUID
+
+from django.core.exceptions import ValidationError
import structlog
from posthog.hogql import ast
-from posthog.hogql.errors import QueryError, ResolutionError, TableAccessDeniedError
+from posthog.hogql.errors import ResolutionError, TableAccessDeniedError
from posthog.hogql.query import execute_hogql_query
+from posthog.api.organization_member import organization_members_base_queryset
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.constants import INTERNAL_BOT_EMAIL_SUFFIX
from posthog.models import OrganizationMembership
@@ -13,11 +17,15 @@ from posthog.models.team import Team
from posthog.models.user import User
from posthog.permissions import posthog_feature_flag_enabled
+from products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlError
from products.customer_analytics.backend.constants import CUSTOMER_ANALYTICS_CSP_FLAG
+from products.customer_analytics.backend.models.account import Account
logger = structlog.get_logger(__name__)
ACCOUNT_MEMBER_SEARCH_MAX_ORGANIZATIONS = 100
+# The member list becomes a constant IN list in ClickHouse, which caps how many members one query can carry.
+ORGANIZATION_MEMBERS_MAX = 10_000
EU_ORGANIZATION_MEMBERS_VIEW = "eu_org_members"
@@ -45,48 +53,55 @@ def _list_us_organization_ids(email: str) -> tuple[str, ...]:
return tuple(str(organization_id) for organization_id in organization_ids)
-def _list_eu_organization_ids(team: Team, user: User, email: str) -> tuple[str, ...]:
+def _query_eu_organization_members(
+ team: Team,
+ user: User,
+ *,
+ query: str,
+ placeholders: dict[str, ast.Expr],
+ query_type: str,
+ log_event: str,
+ raise_query_failures: bool = False,
+) -> tuple[str, ...]:
try:
with tags_context(product=Product.CUSTOMER_ANALYTICS, feature=Feature.QUERY):
response = execute_hogql_query(
- query=f"""
- SELECT DISTINCT organization_id
- FROM {EU_ORGANIZATION_MEMBERS_VIEW}
- WHERE email = {{email}}
- ORDER BY organization_id
- LIMIT {ACCOUNT_MEMBER_SEARCH_MAX_ORGANIZATIONS}
- """,
- placeholders={"email": ast.Constant(value=email)},
+ query=query,
+ placeholders=placeholders,
team=team,
user=user,
- query_type="customer_analytics_account_member_email_lookup",
+ query_type=query_type,
)
except (ResolutionError, TableAccessDeniedError) as error:
- logger.info(
- "account_member_email_lookup_unavailable",
- team_id=team.id,
- error_type=type(error).__name__,
- )
- return ()
- except QueryError as error:
- logger.warning(
- "account_member_email_lookup_failed",
- team_id=team.id,
- error_type=type(error).__name__,
- )
+ logger.info(f"{log_event}_unavailable", team_id=team.id, error_type=type(error).__name__)
return ()
except Exception as error:
- logger.warning(
- "account_member_email_lookup_failed",
- team_id=team.id,
- error_type=type(error).__name__,
- )
+ logger.warning(f"{log_event}_failed", team_id=team.id, error_type=type(error).__name__)
+ if raise_query_failures:
+ raise
return ()
rows = cast(list[list[object]], response.results or [])
return tuple(str(row[0]) for row in rows if row and row[0] is not None)
+def _list_eu_organization_ids(team: Team, user: User, email: str) -> tuple[str, ...]:
+ return _query_eu_organization_members(
+ team,
+ user,
+ query=f"""
+ SELECT DISTINCT organization_id
+ FROM {EU_ORGANIZATION_MEMBERS_VIEW}
+ WHERE email = {{email}}
+ ORDER BY organization_id
+ LIMIT {ACCOUNT_MEMBER_SEARCH_MAX_ORGANIZATIONS}
+ """,
+ placeholders={"email": ast.Constant(value=email)},
+ query_type="customer_analytics_account_member_email_lookup",
+ log_event="account_member_email_lookup",
+ )
+
+
def list_account_external_ids_by_member_email(*, team: Team, user: User, email: str) -> tuple[str, ...]:
if not is_account_member_search_enabled(team, user):
return ()
@@ -95,3 +110,53 @@ def list_account_external_ids_by_member_email(*, team: Team, user: User, email:
if organization_ids:
return organization_ids
return _list_eu_organization_ids(team, user, email)
+
+
+def list_organization_member_distinct_ids(*, team: Team, user: User, organization_id: str) -> tuple[str, ...]:
+ """Distinct IDs of the PostHog Cloud users in an organization, from US Postgres or else the EU warehouse view."""
+ us_distinct_ids = tuple(
+ organization_members_base_queryset()
+ .filter(organization_id=organization_id, user__distinct_id__isnull=False)
+ .order_by("-joined_at")
+ .values_list("user__distinct_id", flat=True)[:ORGANIZATION_MEMBERS_MAX]
+ )
+ if us_distinct_ids:
+ return us_distinct_ids
+ return _query_eu_organization_members(
+ team,
+ user,
+ query=f"""
+ SELECT distinct_id
+ FROM {EU_ORGANIZATION_MEMBERS_VIEW}
+ WHERE organization_id = {{organization_id}} AND distinct_id IS NOT NULL
+ ORDER BY joined_at DESC
+ LIMIT {ORGANIZATION_MEMBERS_MAX}
+ """,
+ placeholders={"organization_id": ast.Constant(value=organization_id)},
+ query_type="customer_analytics_account_member_distinct_id_lookup",
+ log_event="account_member_distinct_id_lookup",
+ raise_query_failures=True,
+ )
+
+
+def get_account_users_organization_id(*, team: Team, user: User | None, account_id: str) -> str | None:
+ """The PostHog Cloud organization behind an account's users, or None when the account has none.
+
+ Raises `UserAccessControlError` unless `user` is flagged staff who can see the account: members are
+ read from any organization, not the caller's own.
+ """
+ if not isinstance(user, User) or not is_account_member_search_enabled(team, user):
+ raise UserAccessControlError("account", "viewer")
+ visible_accounts = UserAccessControl(user=user, team=team).filter_queryset_by_access_level(
+ Account.objects.for_team(team.id)
+ )
+ try:
+ account = visible_accounts.filter(id=account_id).values("external_id").first()
+ except (ValidationError, ValueError):
+ account = None
+ if account is None:
+ raise UserAccessControlError("account", "viewer", resource_id=account_id)
+ try:
+ return str(UUID(account["external_id"])) if account["external_id"] else None
+ except ValueError:
+ return None
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index e972a670a114..1ddc6d4cc219 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -50,6 +50,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |
| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |
| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). It debounces name and email searches, and owns the table's sort (`sorting`, on `level` or `last_login`) and access-level filter (`levels`); both reset to page 1 and reload. US-region orgs use the org-members endpoint, which takes `search`, `levels` and a whitelisted `ordering`. When it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only), fetched once per expansion then searched, filtered, sorted and paginated in pages of 20 client-side (mirroring the backend's ordering, "never logged in" at the far end). Once a US request has returned members the org is remembered as US-hosted and an empty filtered page is treated as "no match"; until then an empty US page falls back to the EU view, so a filter set before the first load finishes still applies. Both reads supply the member's organization access level and last-login data. EU values refresh daily. The EU view also includes the source Django user ID. Each member carries its source region so staff admin links open the correct user's detail page in the correct cloud. A missing view (local dev) degrades to the normal empty state. |
+| `accountUsersTableLogic` | The persons Users table behind `CUSTOMER_ANALYTICS_ACCOUNT_USERS_TABLE` (keyed by `accountId:instanceId`). It renders a `DataTableNode` over `ActorsQuery{ source: AccountUsersQuery{ accountId } }`, so columns, person property filters, search and sort come from the shared DataTable. The backend `AccountUsersQueryRunner` resolves the account's persons from the PostHog Cloud organization members (US Postgres, else `eu_org_members`) and is staff and `CUSTOMER_ANALYTICS_CSP` only. The tile config saves the table query without the account, so a reusable account view shows each account's own users. Members with no person in this project do not appear. |
| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint), `endRelationship` (per active row, POSTs the end endpoint), and `deleteRelationship` (admin-only, confirmation-gated hard delete). All mutations share the `relationshipSaving` guard, refresh mounted relationship views through `relationshipsUpdated`, and force-refresh the list's data nodes. `accountPropertyDataLogic` refreshes shared property data once per change. |
| `accountFeatureRequestsLogic` | Feature requests for one account (keyed by `accountId`): loads linked requests in server pages of five with debounced search, then searches a bounded server page of accessible, editable active requests for the link picker. The picker keeps a selected search result available when the select clears its input, so requests outside the default page remain linkable. Request links carry the account's Feature requests deep link as their origin, so the detail breadcrumb returns to the same account tab. The picker exposes load failures with retry guidance and refreshes stale options after optimistic-concurrency conflicts. |
| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, preloads each insight result when the account expands, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |
@@ -436,6 +437,7 @@ Account detail view events use singular `accountViewsLogic`, separate from Accou
| `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 related users table changed` | `accountUsersTableLogic` `setQuery` listener (column, filter, sort or search change in the persons Users table) | _(none; column names and filter values stay 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`) |
| `customer analytics account summary expanded` | `accountSummariesLogic` `toggleSummaryExpanded` listener (only when the toggle opens a summary, not on collapse) | _(none — summary content/period is customer data and kept out)_ |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountUsersTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountUsersTable.tsx
new file mode 100644
index 000000000000..a325652a28f6
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountUsersTable.tsx
@@ -0,0 +1,26 @@
+import { useActions, useValues } from 'kea'
+
+import { Query } from '~/queries/Query/Query'
+
+import { accountUsersTableLogic } from './accountUsersTableLogic'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
+
+interface AccountUsersTableProps extends AccountViewTileLogicProps {
+ accountId: string
+ embedded?: boolean
+}
+
+export function AccountUsersTable({ accountId, embedded = true, ...tileProps }: AccountUsersTableProps): JSX.Element {
+ const logic = accountUsersTableLogic({ accountId, ...tileProps })
+ const { query } = useValues(logic)
+ const { setQuery } = useActions(logic)
+
+ return (
+ <Query
+ uniqueKey={`account-users-${accountId}-${tileProps.instanceId ?? 'default'}`}
+ query={{ ...query, embedded }}
+ setQuery={setQuery}
+ dataAttr="customer-analytics-account-users-table"
+ />
+ )
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
index 1897e89f5f66..1ec294f2f010 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
@@ -1,3 +1,4 @@
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { userHasAccess } from 'lib/utils/accessControlUtils'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
@@ -13,6 +14,7 @@ import { AccountOpportunitiesExpansion } from './AccountOpportunitiesExpansion'
import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'
import { AccountRelationshipsExpansion } from './AccountRelationshipsExpansion'
import { AccountSessionReplays } from './AccountSessionReplays'
+import { AccountUsersTable } from './AccountUsersTable'
import type { AccountViewComponentKind } from './accountViewComponents'
import type { AccountViewTileConfig } from './accountViewTileConfig'
@@ -38,6 +40,7 @@ export function AccountViewComponent({
embedded = true,
}: AccountViewComponentProps): JSX.Element {
const tileProps = { instanceId, initialConfig, onConfigChange }
+ const isUsersTableEnabled = useFeatureFlag('CUSTOMER_ANALYTICS_ACCOUNT_USERS_TABLE')
switch (kind) {
case 'properties':
return <AccountPropertiesWidget accountId={accountId} projectId={projectId} {...tileProps} />
@@ -56,7 +59,11 @@ export function AccountViewComponent({
/>
)
case 'users':
- return <AccountRelatedUsersExpansion externalId={externalId} embedded={embedded} {...tileProps} />
+ return isUsersTableEnabled ? (
+ <AccountUsersTable accountId={accountId} embedded={embedded} {...tileProps} />
+ ) : (
+ <AccountRelatedUsersExpansion externalId={externalId} embedded={embedded} {...tileProps} />
+ )
case 'relationships':
return <AccountRelationshipsExpansion accountId={accountId} embedded={embedded} {...tileProps} />
case 'feature_requests':
diff --git a/products/customer_analytics/frontend/components/Accounts/accountUsersTableLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountUsersTableLogic.test.ts
new file mode 100644
index 000000000000..ff8a914dbb6b
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountUsersTableLogic.test.ts
@@ -0,0 +1,44 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { ActorsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { accountUsersTableLogic } from './accountUsersTableLogic'
+
+describe('accountUsersTableLogic', () => {
+ beforeEach(() => {
+ initKeaTests()
+ })
+
+ it('queries the current account and saves the table without an account', async () => {
+ const onConfigChange = jest.fn()
+ const savedOnAnotherAccount: DataTableNode = {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.ActorsQuery,
+ select: ['properties.email'],
+ source: { kind: NodeKind.AccountUsersQuery, accountId: 'other-account' },
+ },
+ }
+ const logic = accountUsersTableLogic({
+ accountId: 'current-account',
+ initialConfig: { query: savedOnAnotherAccount },
+ onConfigChange,
+ })
+ logic.mount()
+
+ expect((logic.values.query.source as ActorsQuery).source).toEqual({
+ kind: NodeKind.AccountUsersQuery,
+ accountId: 'current-account',
+ })
+
+ await expectLogic(logic, () => logic.actions.setQuery(logic.values.query)).toFinishAllListeners()
+
+ expect(onConfigChange).toHaveBeenCalledWith({
+ query: {
+ kind: NodeKind.DataTableNode,
+ source: { kind: NodeKind.ActorsQuery, select: ['properties.email'] },
+ },
+ })
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountUsersTableLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountUsersTableLogic.ts
new file mode 100644
index 000000000000..2e02024f0682
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountUsersTableLogic.ts
@@ -0,0 +1,122 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { ActorsQuery, DataTableNode, NodeKind } from '~/queries/schema/schema-general'
+import { TeamPublicType, TeamType } from '~/types'
+
+import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
+import { getTileRecord, type AccountViewTileConfig, type AccountViewTileLogicProps } from './accountViewTileConfig'
+import { AccountsEvents } from './constants'
+
+export interface AccountUsersTableLogicProps extends AccountViewTileLogicProps {
+ accountId: string
+}
+
+function createDefaultColumns(lastSeenEnabled: boolean): string[] {
+ return [
+ 'person_display_name -- Person',
+ 'properties.current_organization_membership_level_name -- Access level',
+ ...(lastSeenEnabled ? ['last_seen_at -- Last seen'] : []),
+ ]
+}
+
+function createDefaultQuery(defaultColumns: string[]): DataTableNode {
+ return {
+ kind: NodeKind.DataTableNode,
+ full: true,
+ showOpenEditorButton: false,
+ showTimings: false,
+ hiddenColumns: ['id', 'person.$delete'],
+ source: {
+ kind: NodeKind.ActorsQuery,
+ select: defaultColumns,
+ tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
+ },
+ }
+}
+
+function parseSavedQuery(config: AccountViewTileConfig | undefined): DataTableNode | null {
+ const saved = getTileRecord(config, 'query') as DataTableNode | null
+ return saved?.kind === NodeKind.DataTableNode && saved.source?.kind === NodeKind.ActorsQuery ? saved : null
+}
+
+// Account views are reusable across accounts, so the saved query never pins an account. Default
+// columns follow the team's settings at read time, so saving them would freeze stale defaults.
+function createSavedQuery(query: DataTableNode): DataTableNode {
+ const { defaultColumns: _defaultColumns, ...table } = query
+ const { source: _accountSource, ...actorsQuery } = table.source as ActorsQuery
+ return { ...table, source: actorsQuery }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountUsersTableLogicValues {
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
+ query: DataTableNode
+ savedQuery: DataTableNode | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountUsersTableLogicActions {
+ setQuery: (query: DataTableNode) => {
+ query: DataTableNode
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountUsersTableLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ query: (savedQuery: DataTableNode | null, currentTeam: TeamPublicType | TeamType | null) => DataTableNode
+ }
+}
+
+export type accountUsersTableLogicType = MakeLogicType<
+ accountUsersTableLogicValues,
+ accountUsersTableLogicActions,
+ AccountUsersTableLogicProps,
+ accountUsersTableLogicMeta
+>
+
+export const accountUsersTableLogic = kea<accountUsersTableLogicType>([
+ path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountUsersTableLogic', key]),
+ props({} as AccountUsersTableLogicProps),
+ key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
+ connect(() => ({
+ values: [teamLogic, ['currentTeam']],
+ })),
+ actions({
+ setQuery: (query: DataTableNode) => ({ query }),
+ }),
+ reducers(({ props }) => ({
+ savedQuery: [parseSavedQuery(props.initialConfig), { setQuery: (_, { query }) => createSavedQuery(query) }],
+ })),
+ selectors(({ props }) => ({
+ query: [
+ (s) => [s.savedQuery, s.currentTeam],
+ (savedQuery: DataTableNode | null, currentTeam: TeamPublicType | TeamType | null): DataTableNode => {
+ const defaultColumns = createDefaultColumns(
+ currentTeam?.extra_settings?.person_last_seen_at_enabled === true
+ )
+ const query = savedQuery ?? createDefaultQuery(defaultColumns)
+ return {
+ ...query,
+ defaultColumns,
+ source: {
+ ...(query.source as ActorsQuery),
+ source: { kind: NodeKind.AccountUsersQuery, accountId: props.accountId },
+ },
+ }
+ },
+ ],
+ })),
+ listeners(({ props, values }) => ({
+ setQuery: () => {
+ if (values.savedQuery) {
+ props.onConfigChange?.({ query: values.savedQuery })
+ }
+ posthog.capture(AccountsEvents.RelatedUsersTableChanged)
+ },
+ })),
+])
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index aa4ce81041c3..1ee7a3f7ceae 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -64,6 +64,7 @@ export const AccountsEvents = {
RelatedUsersSorted: 'customer analytics account related users sorted',
RelatedUserEmailsCopied: 'customer analytics account related user emails copied',
RelatedUserAdminOpened: 'customer analytics account related user admin opened',
+ RelatedUsersTableChanged: 'customer analytics account related users table changed',
OpportunityClicked: 'customer analytics account opportunity clicked',
SummaryCadenceChanged: 'customer analytics account summary cadence changed',
SummaryExpanded: 'customer analytics account summary expanded',
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 1c141e01cd94..0f409d3d083d 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -6676,6 +6676,18 @@ export interface PathsV2ActorsQueryApi {
version?: number | null
}
+export interface AccountUsersQueryApi {
+ /** ID of the account whose users to list. */
+ accountId: string
+ kind?: 'AccountUsersQuery'
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ response?: ActorsQueryResponseApi | null
+ tags?: QueryLogTagsApi | null
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
export type ExecutionTargetApi = (typeof ExecutionTargetApi)[keyof typeof ExecutionTargetApi]
export const ExecutionTargetApi = {
@@ -6843,6 +6855,7 @@ export interface ActorsQueryApi {
| ExperimentActorsQueryApi
| StickinessActorsQueryApi
| PathsV2ActorsQueryApi
+ | AccountUsersQueryApi
| HogQLQueryApi
| null
tags?: QueryLogTagsApi | null
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index c51613d5ad41..956af277b196 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -368,7 +368,7 @@ export namespace Schemas {
table_name: string;
type?: string | undefined;
};
- export type AccountsQueryResponse = {
+ export type ActorsQueryResponse = {
columns: Array<unknown>;
error?: (string | null) | undefined;
hasMore?: (boolean | null) | undefined;
@@ -376,9 +376,8 @@ export namespace Schemas {
* Generated HogQL query.
*/
hogql: string;
- kind?: string | undefined;
limit: number;
- metricsResults?: (Array<number | null> | null) | undefined;
+ missing_actors_count?: (number | null) | undefined;
modifiers?: (HogQLQueryModifiers | null) | undefined;
offset: number;
query_status?: (QueryStatus | null) | undefined;
@@ -388,7 +387,7 @@ export namespace Schemas {
resolved_date_range?: (ResolvedDateRangeResponse | null) | undefined;
results: Array<Array<unknown>>;
timings?: (Array<QueryTiming> | null) | undefined;
- types: Array<string>;
+ types?: (Array<string> | null) | undefined;
used_data_warehouse_sources?:
| (Array<DataWarehouseSourceUsage> | null)
| undefined;
@@ -404,6 +403,47 @@ export namespace Schemas {
productKey: string | null;
scene: string | null;
}>;
+ export type AccountUsersQuery = {
+ /**
+ * ID of the account whose users to list.
+ */
+ accountId: string;
+ kind?: string | undefined;
+ modifiers?: (HogQLQueryModifiers | null) | undefined;
+ response?: (ActorsQueryResponse | null) | undefined;
+ tags?: (QueryLogTags | null) | undefined;
+ version?: (number | null) | undefined;
+ };
+ export type AccountsQueryResponse = {
+ columns: Array<unknown>;
+ error?: (string | null) | undefined;
+ hasMore?: (boolean | null) | undefined;
+ /**
+ * Generated HogQL query.
+ */
+ hogql: string;
+ kind?: string | undefined;
+ limit: number;
+ metricsResults?: (Array<number | null> | null) | undefined;
+ modifiers?: (HogQLQueryModifiers | null) | undefined;
+ offset: number;
+ query_status?: (QueryStatus | null) | undefined;
+ resolved_compare_date_range?:
+ | (ResolvedDateRangeResponse | null)
+ | undefined;
+ resolved_date_range?: (ResolvedDateRangeResponse | null) | undefined;
+ results: Array<Array<unknown>>;
+ timings?: (Array<QueryTiming> | null) | undefined;
+ types: Array<string>;
+ used_data_warehouse_sources?:
+ | (Array<DataWarehouseSourceUsage> | null)
+ | undefined;
+ warnings?:
+ | (Array<
+ DataWarehouseSyncWarning | AccessControlFilterWarning
+ > | null)
+ | undefined;
+ };
export type AccountsQuery = Partial<{
allRolesUnassigned: boolean | null;
assignedOnly: boolean | null;
@@ -1731,35 +1771,6 @@ export namespace Schemas {
| BehavioralPropertyFilter
>;
};
- export type ActorsQueryResponse = {
- columns: Array<unknown>;
- error?: (string | null) | undefined;
- hasMore?: (boolean | null) | undefined;
- /**
- * Generated HogQL query.
- */
- hogql: string;
- limit: number;
- missing_actors_count?: (number | null) | undefined;
- modifiers?: (HogQLQueryModifiers | null) | undefined;
- offset: number;
- query_status?: (QueryStatus | null) | undefined;
- resolved_compare_date_range?:
- | (ResolvedDateRangeResponse | null)
- | undefined;
- resolved_date_range?: (ResolvedDateRangeResponse | null) | undefined;
- results: Array<Array<unknown>>;
- timings?: (Array<QueryTiming> | null) | undefined;
- types?: (Array<string> | null) | undefined;
- used_data_warehouse_sources?:
- | (Array<DataWarehouseSourceUsage> | null)
- | undefined;
- warnings?:
- | (Array<
- DataWarehouseSyncWarning | AccessControlFilterWarning
- > | null)
- | undefined;
- };
export type Compare = "current" | "previous";
export type BreakdownType =
| "cohort"
@@ -4345,6 +4356,7 @@ export namespace Schemas {
| ExperimentActorsQuery
| StickinessActorsQuery
| PathsV2ActorsQuery
+ | AccountUsersQuery
| HogQLQuery
| null;
tags: QueryLogTags | null;
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 39e40f8b75fb..1038a9caa8ad 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -5724,6 +5724,18 @@ export interface PathsV2ActorsQueryApi {
version?: number | null
}
+export interface AccountUsersQueryApi {
+ /** ID of the account whose users to list. */
+ accountId: string
+ kind?: 'AccountUsersQuery'
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ response?: ActorsQueryResponseApi | null
+ tags?: QueryLogTagsApi | null
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
export type ExecutionTargetApi = (typeof ExecutionTargetApi)[keyof typeof ExecutionTargetApi]
export const ExecutionTargetApi = {
@@ -5891,6 +5903,7 @@ export interface ActorsQueryApi {
| ExperimentActorsQueryApi
| StickinessActorsQueryApi
| PathsV2ActorsQueryApi
+ | AccountUsersQueryApi
| HogQLQueryApi
| null
tags?: QueryLogTagsApi | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4b4c68964307..b04d2dfee27e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2398,138 +2398,6 @@ export namespace Schemas {
groups: AccountTrackRuleGroup[];
}
- /**
- * * `private` - Personal
- * * `team` - Team
- */
- export type AccountViewVisibilityEnum = typeof AccountViewVisibilityEnum[keyof typeof AccountViewVisibilityEnum];
-
-
- export const AccountViewVisibilityEnum = {
- Private: 'private',
- Team: 'team',
- } as const;
-
- /**
- * * `doc` - doc
- */
- export type AccountViewContentTypeEnum = typeof AccountViewContentTypeEnum[keyof typeof AccountViewContentTypeEnum];
-
-
- export const AccountViewContentTypeEnum = {
- Doc: 'doc',
- } as const;
-
- /**
- * * `ph-markdown-notebook` - ph-markdown-notebook
- */
- export type AccountViewMarkdownNodeTypeEnum = typeof AccountViewMarkdownNodeTypeEnum[keyof typeof AccountViewMarkdownNodeTypeEnum];
-
-
- export const AccountViewMarkdownNodeTypeEnum = {
- PhMarkdownNotebook: 'ph-markdown-notebook',
- } as const;
-
- export interface AccountViewMarkdownAttributes {
- /** Stable identifier for this document. */
- nodeId: string;
- /**
- * Component-only Markdown stored by the account view editor.
- * @maxLength 262144
- */
- markdown: string;
- }
-
- export interface AccountViewMarkdownNode {
- /** Markdown notebook node type.
- *
- * * `ph-markdown-notebook` - ph-markdown-notebook */
- type: AccountViewMarkdownNodeTypeEnum;
- /** Markdown notebook attributes. */
- attrs: AccountViewMarkdownAttributes;
- }
-
- export interface AccountViewContent {
- /** Document root type.
- *
- * * `doc` - doc */
- type: AccountViewContentTypeEnum;
- /**
- * The single Markdown notebook node containing the account view components.
- * @minItems 1
- * @maxItems 1
- */
- content: AccountViewMarkdownNode[];
- }
-
- export interface AccountView {
- /** Stable account view identifier. */
- readonly id: string;
- /** Name shown in the account view. */
- readonly name: string;
- /** Whether the view is personal or available to the project.
- *
- * * `private` - Personal
- * * `team` - Team */
- readonly visibility: AccountViewVisibilityEnum;
- /** Validated Markdown notebook document. */
- readonly content: AccountViewContent;
- /** Searchable component labels extracted from content. */
- readonly text_content: string;
- /** Optimistic concurrency version. */
- readonly version: number;
- /**
- * Creator user ID.
- * @nullable
- */
- readonly created_by: number | null;
- /**
- * User ID that last changed the view.
- * @nullable
- */
- readonly last_modified_by: number | null;
- /** When the view was created. */
- readonly created_at: string;
- /** When the view was last changed. */
- readonly updated_at: string;
- /** Whether the requesting user can edit the view. */
- readonly can_edit: boolean;
- /** Whether the requesting user can delete the view. */
- readonly can_delete: boolean;
- /** Whether the requesting user can change the view visibility. */
- readonly can_change_visibility: boolean;
- }
-
- export interface AccountViewCreate {
- /**
- * View name.
- * @maxLength 400
- */
- name: string;
- /** Initial account view components. */
- content: AccountViewContent;
- }
-
- export interface AccountViewUpdate {
- /**
- * New view name. Omit to keep the current name.
- * @maxLength 400
- */
- name?: string;
- /** Replacement account view components. Omit to keep current content. */
- content?: AccountViewContent;
- /** New visibility. Only the creator or a project admin can change it.
- *
- * * `private` - Personal
- * * `team` - Team */
- visibility?: AccountViewVisibilityEnum;
- /**
- * Version returned by the last read.
- * @minimum 1
- */
- version: number;
- }
-
export type BounceRatePageViewMode = typeof BounceRatePageViewMode[keyof typeof BounceRatePageViewMode];
@@ -2948,17 +2816,15 @@ export namespace Schemas {
type?: 'warehouse_sync';
}
- export interface AccountsQueryResponse {
+ export interface ActorsQueryResponse {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
/** Generated HogQL query. */
hogql: string;
- kind?: 'AccountsQuery';
limit: number;
- /** When `metrics` is set on the query, the aggregated values in the same order. */
- metricsResults?: (number | null)[] | null;
+ missing_actors_count?: number | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
offset: number;
@@ -2971,7 +2837,7 @@ export namespace Schemas {
results: unknown[][];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
- types: string[];
+ types?: string[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
/** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
@@ -2989,6 +2855,180 @@ export namespace Schemas {
scene?: string | null;
}
+ export interface AccountUsersQuery {
+ /** ID of the account whose users to list. */
+ accountId: string;
+ kind?: 'AccountUsersQuery';
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ response?: ActorsQueryResponse | null;
+ tags?: QueryLogTags | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
+ /**
+ * * `private` - Personal
+ * * `team` - Team
+ */
+ export type AccountViewVisibilityEnum = typeof AccountViewVisibilityEnum[keyof typeof AccountViewVisibilityEnum];
+
+
+ export const AccountViewVisibilityEnum = {
+ Private: 'private',
+ Team: 'team',
+ } as const;
+
+ /**
+ * * `doc` - doc
+ */
+ export type AccountViewContentTypeEnum = typeof AccountViewContentTypeEnum[keyof typeof AccountViewContentTypeEnum];
+
+
+ export const AccountViewContentTypeEnum = {
+ Doc: 'doc',
+ } as const;
+
+ /**
+ * * `ph-markdown-notebook` - ph-markdown-notebook
+ */
+ export type AccountViewMarkdownNodeTypeEnum = typeof AccountViewMarkdownNodeTypeEnum[keyof typeof AccountViewMarkdownNodeTypeEnum];
+
+
+ export const AccountViewMarkdownNodeTypeEnum = {
+ PhMarkdownNotebook: 'ph-markdown-notebook',
+ } as const;
+
+ export interface AccountViewMarkdownAttributes {
+ /** Stable identifier for this document. */
+ nodeId: string;
+ /**
+ * Component-only Markdown stored by the account view editor.
+ * @maxLength 262144
+ */
+ markdown: string;
+ }
+
+ export interface AccountViewMarkdownNode {
+ /** Markdown notebook node type.
+ *
+ * * `ph-markdown-notebook` - ph-markdown-notebook */
+ type: AccountViewMarkdownNodeTypeEnum;
+ /** Markdown notebook attributes. */
+ attrs: AccountViewMarkdownAttributes;
+ }
+
+ export interface AccountViewContent {
+ /** Document root type.
+ *
+ * * `doc` - doc */
+ type: AccountViewContentTypeEnum;
+ /**
+ * The single Markdown notebook node containing the account view components.
+ * @minItems 1
+ * @maxItems 1
+ */
+ content: AccountViewMarkdownNode[];
+ }
+
+ export interface AccountView {
+ /** Stable account view identifier. */
+ readonly id: string;
+ /** Name shown in the account view. */
+ readonly name: string;
+ /** Whether the view is personal or available to the project.
+ *
+ * * `private` - Personal
+ * * `team` - Team */
+ readonly visibility: AccountViewVisibilityEnum;
+ /** Validated Markdown notebook document. */
+ readonly content: AccountViewContent;
+ /** Searchable component labels extracted from content. */
+ readonly text_content: string;
+ /** Optimistic concurrency version. */
+ readonly version: number;
+ /**
+ * Creator user ID.
+ * @nullable
+ */
+ readonly created_by: number | null;
+ /**
+ * User ID that last changed the view.
+ * @nullable
+ */
+ readonly last_modified_by: number | null;
+ /** When the view was created. */
+ readonly created_at: string;
+ /** When the view was last changed. */
+ readonly updated_at: string;
+ /** Whether the requesting user can edit the view. */
+ readonly can_edit: boolean;
+ /** Whether the requesting user can delete the view. */
+ readonly can_delete: boolean;
+ /** Whether the requesting user can change the view visibility. */
+ readonly can_change_visibility: boolean;
+ }
+
+ export interface AccountViewCreate {
+ /**
+ * View name.
+ * @maxLength 400
+ */
+ name: string;
+ /** Initial account view components. */
+ content: AccountViewContent;
+ }
+
+ export interface AccountViewUpdate {
+ /**
+ * New view name. Omit to keep the current name.
+ * @maxLength 400
+ */
+ name?: string;
+ /** Replacement account view components. Omit to keep current content. */
+ content?: AccountViewContent;
+ /** New visibility. Only the creator or a project admin can change it.
+ *
+ * * `private` - Personal
+ * * `team` - Team */
+ visibility?: AccountViewVisibilityEnum;
+ /**
+ * Version returned by the last read.
+ * @minimum 1
+ */
+ version: number;
+ }
+
+ export interface AccountsQueryResponse {
+ columns: unknown[];
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ hasMore?: boolean | null;
+ /** Generated HogQL query. */
+ hogql: string;
+ kind?: 'AccountsQuery';
+ limit: number;
+ /** When `metrics` is set on the query, the aggregated values in the same order. */
+ metricsResults?: (number | null)[] | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ offset: number;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: unknown[][];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ types: string[];
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
export interface AccountsQuery {
/** Match accounts with no active relationship of any definition. */
allRolesUnassigned?: boolean | null;
@@ -5162,34 +5202,6 @@ export namespace Schemas {
values: (PropertyGroupFilterValue | EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[];
}
- export interface ActorsQueryResponse {
- columns: unknown[];
- /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
- error?: string | null;
- hasMore?: boolean | null;
- /** Generated HogQL query. */
- hogql: string;
- limit: number;
- missing_actors_count?: number | null;
- /** Modifiers used when performing the query */
- modifiers?: HogQLQueryModifiers | null;
- offset: number;
- /** Query status indicates whether next to the provided data, a query is still running. */
- query_status?: QueryStatus | null;
- /** The resolved previous/comparison period date range, when comparing against another period */
- resolved_compare_date_range?: ResolvedDateRangeResponse | null;
- /** The date range used for the query */
- resolved_date_range?: ResolvedDateRangeResponse | null;
- results: unknown[][];
- /** Measured timings for different parts of the query generation process */
- timings?: QueryTiming[] | null;
- types?: string[] | null;
- /** Connector-synced data warehouse sources referenced by this query, if any. */
- used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
- /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
- warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
- }
-
export type Compare = typeof Compare[keyof typeof Compare];
@@ -7565,7 +7577,7 @@ export namespace Schemas {
response?: ActorsQueryResponse | null;
search?: string | null;
select?: string[] | null;
- source?: InsightActorsQuery | FunnelsActorsQuery | ExperimentActorsQuery | StickinessActorsQuery | PathsV2ActorsQuery | HogQLQuery | null;
+ source?: InsightActorsQuery | FunnelsActorsQuery | ExperimentActorsQuery | StickinessActorsQuery | PathsV2ActorsQuery | AccountUsersQuery | HogQLQuery | null;
tags?: QueryLogTags | null;
/** version of the node, used for schema migrations */
version?: number | null;