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): show account user access levels (#88831)

Arthur Moreira de Deus37e7ce9a2729
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index 105b7218daac..6c9cc1d27aaf 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -415,6 +415,9 @@ jobs:
toolchain: 1.91.1
components: cargo
+ - name: Install protoc
+ uses: ./.github/actions/setup-protoc
+
- name: Cache Rust dependencies
uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1
with:
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 87d48c230eec..9770b04b16ba 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -3642,7 +3642,7 @@ const api = {
async listForOrg(
organizationId: OrganizationType['id'],
params: { limit?: number; offset?: number } = {}
- ): Promise<CountedPaginatedResponse<Pick<OrganizationMemberType, 'id' | 'user'>>> {
+ ): Promise<CountedPaginatedResponse<Pick<OrganizationMemberType, 'id' | 'user' | 'level'>>> {
return await new ApiRequest()
.organizationMembersForAccount()
.withQueryString({ organization_id: organizationId, ...params })
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index e41d7304e72a..1fc2b13e9b8a 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -992,9 +992,12 @@ class AccountOrganizationMemberSerializer(serializers.ModelSerializer):
class Meta:
model = OrganizationMembership
- fields = ["id", "user"]
- read_only_fields = ["id", "user"]
- extra_kwargs = {"id": {"help_text": "Organization membership ID."}}
+ fields = ["id", "user", "level"]
+ read_only_fields = ["id", "user", "level"]
+ extra_kwargs = {
+ "id": {"help_text": "Organization membership ID."},
+ "level": {"help_text": "Organization access level: member, admin, or owner."},
+ }
class AccountNotebookSerializer(DataclassSerializer):
diff --git a/products/customer_analytics/backend/test/test_organization_members.py b/products/customer_analytics/backend/test/test_organization_members.py
index dcee8f8c4ab7..2ad49ac5f269 100644
--- a/products/customer_analytics/backend/test/test_organization_members.py
+++ b/products/customer_analytics/backend/test/test_organization_members.py
@@ -5,7 +5,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.constants import INTERNAL_BOT_EMAIL_SUFFIX
-from posthog.models.organization import Organization
+from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.user import User
@@ -19,14 +19,21 @@ class TestOrganizationMembersForAccountAPI(APIBaseTest):
def _url(self, organization_id: object) -> str:
return f"/api/projects/{self.team.id}/organization_members/?organization_id={organization_id}"
- def _join(self, email: str, **kwargs) -> User:
+ def _join(
+ self, email: str, level: OrganizationMembership.Level = OrganizationMembership.Level.MEMBER, **kwargs
+ ) -> User:
user = User.objects.create(email=email, **kwargs)
- user.join(organization=self.target_org)
+ user.join(organization=self.target_org, level=level)
return user
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_returns_slim_members_of_target_org_when_staff_and_flag_enabled(self, _mock_flag):
- self._join("[email protected]", first_name="Ada", distinct_id="distinct-1")
+ self._join(
+ first_name="Ada",
+ distinct_id="distinct-1",
+ level=OrganizationMembership.Level.ADMIN,
+ )
self._join("[email protected]", first_name="Grace", distinct_id="distinct-2")
response = self.client.get(self._url(self.target_org.id))
@@ -38,7 +45,10 @@ class TestOrganizationMembersForAccountAPI(APIBaseTest):
results = body["results"]
self.assertEqual({r["user"]["email"] for r in results}, {"[email protected]", "[email protected]"})
self.assertEqual({r["user"]["distinct_id"] for r in results}, {"distinct-1", "distinct-2"})
- self.assertEqual(set(results[0].keys()), {"id", "user"})
+ self.assertEqual(set(results[0].keys()), {"id", "user", "level"})
+ self.assertEqual(
+ {r["user"]["email"]: r["level"] for r in results}, {"[email protected]": 8, "[email protected]": 1}
+ )
@patch("posthoganalytics.feature_enabled", return_value=False)
def test_forbidden_when_flag_disabled(self, _mock_flag):
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index d440007684ce..24e7799f06d6 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -48,7 +48,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |
| `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`). US-region orgs come from the org-members endpoint; 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, refreshed daily), fetched once per expansion and paginated client-side. The EU view 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. |
+| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; 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, refreshed daily), fetched once per expansion and paginated in pages of 20 client-side. Both sources include the member's organization access level. 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. |
| `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) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |
| `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. 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. |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx
index d420e951850f..155c4fe3308a 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.test.tsx
@@ -4,6 +4,7 @@ import { cleanup, render, screen } from '@testing-library/react'
import { Provider } from 'kea'
import api from 'lib/api'
+import { OrganizationMembershipLevel } from 'lib/constants'
import { userLogic } from 'scenes/userLogic'
import type { HogQLQueryResponse } from '~/queries/schema/schema-general'
@@ -23,7 +24,7 @@ describe('AccountRelatedUsersExpansion', () => {
cleanup()
})
- it('opens a dev EU member in the current admin', async () => {
+ 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,
@@ -31,7 +32,17 @@ describe('AccountRelatedUsersExpansion', () => {
results: [],
})
jest.spyOn(api, 'query').mockResolvedValue({
- results: [[42, 'membership-1', 'Alex', 'Mercer', '[email protected]', 'distinct-1']],
+ results: [
+ [
+ 42,
+ 'membership-1',
+ OrganizationMembershipLevel.Owner,
+ 'Alex',
+ 'Mercer',
+ 'distinct-1',
+ ],
+ ],
} as HogQLQueryResponse)
render(
@@ -40,6 +51,7 @@ describe('AccountRelatedUsersExpansion', () => {
</Provider>
)
+ expect(await screen.findByText('Owner')).toBeInTheDocument()
const impersonateButton = await screen.findByText('Impersonate')
expect(impersonateButton.closest('a')).toHaveAttribute('href', 'http://localhost/admin/posthog/user/42/change/')
})
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
index 0fce03fcb1be..3bc53fd98133 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelatedUsersExpansion.tsx
@@ -3,7 +3,8 @@ import posthog from 'posthog-js'
import { LemonButton, LemonTable, LemonTableColumns, Link } from '@posthog/lemon-ui'
-import { fullName } from 'lib/utils/strings'
+import { membershipLevelToName } from 'lib/utils/permissioning'
+import { capitalizeFirstLetter, fullName } from 'lib/utils/strings'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
@@ -41,6 +42,11 @@ export function AccountRelatedUsersExpansion({ externalId }: { externalId: strin
key: 'email',
render: (_, member) => <span className="text-sm text-muted">{member.user.email}</span>,
},
+ {
+ title: 'Access level',
+ key: 'level',
+ render: (_, member) => capitalizeFirstLetter(membershipLevelToName.get(member.level) ?? 'Unknown'),
+ },
]
if (user?.is_staff) {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts
index db0f5c968539..fdd93ef1e498 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.test.ts
@@ -2,6 +2,7 @@ import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import api, { CountedPaginatedResponse } from 'lib/api'
+import { OrganizationMembershipLevel } from 'lib/constants'
import { initKeaTests } from '~/test/init'
import { OrganizationMemberType, Region } from '~/types'
@@ -56,7 +57,7 @@ describe('accountRelatedUsersLogic', () => {
await expectLogic(logic)
.toFinishAllListeners()
.toMatchValues({ membersResponse: { ...response, results: [{ ...member, region: Region.US }] } })
- expect(listForOrg).toHaveBeenCalledWith('org-uuid', { limit: PAGE_SIZE, offset: 0 })
+ expect(listForOrg).toHaveBeenCalledWith('org-uuid', { limit: 20, offset: 0 })
})
it('does not load when the account has no external id', async () => {
@@ -81,21 +82,19 @@ describe('accountRelatedUsersLogic', () => {
logic.actions.setPage(2)
await expectLogic(logic).toFinishAllListeners()
- expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', { limit: PAGE_SIZE, offset: PAGE_SIZE })
+ expect(listForOrg).toHaveBeenLastCalledWith('org-uuid', { limit: 20, offset: 20 })
})
- const buildEuRow = (n: number): unknown[] => [
- 100 + n,
- `eu-m-${n}`,
- `First${n}`,
- `Last${n}`,
- `eu${n}@example.com`,
- `did-${n}`,
- ]
+ const buildEuRow = (
+ n: number,
+ level: OrganizationMembershipLevel = OrganizationMembershipLevel.Member
+ ): unknown[] => [100 + n, `eu-m-${n}`, level, `First${n}`, `Last${n}`, `eu${n}@example.com`, `did-${n}`]
it('falls back to the EU warehouse view when the org has no local members', async () => {
jest.spyOn(api.organizationMembers, 'listForOrg').mockResolvedValue(buildResponse([], 0))
- const query = jest.spyOn(api, 'query').mockResolvedValue({ results: [buildEuRow(1), buildEuRow(2)] } as any)
+ const query = jest
+ .spyOn(api, 'query')
+ .mockResolvedValue({ results: [buildEuRow(1, OrganizationMembershipLevel.Admin), buildEuRow(2)] } as any)
logic = accountRelatedUsersLogic({ externalId: 'org-uuid' })
logic.mount()
@@ -107,11 +106,13 @@ describe('accountRelatedUsersLogic', () => {
results: [
{
id: 'eu-m-1',
+ level: OrganizationMembershipLevel.Admin,
user: { id: 101, first_name: 'First1', email: '[email protected]', distinct_id: 'did-1' },
region: Region.EU,
},
{
id: 'eu-m-2',
+ level: OrganizationMembershipLevel.Member,
user: { id: 102, first_name: 'First2', email: '[email protected]', distinct_id: 'did-2' },
region: Region.EU,
},
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts
index f3c9e56f0887..291bc22abbbc 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelatedUsersLogic.ts
@@ -11,12 +11,11 @@ import { OrganizationMemberType, Region } from '~/types'
import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'
-// The account org-members endpoint returns a slim member shape — only id + user are serialized.
-export type AccountOrganizationMember = Pick<OrganizationMemberType, 'id' | 'user'> & {
+export type AccountOrganizationMember = Pick<OrganizationMemberType, 'id' | 'user' | 'level'> & {
region: Region.US | Region.EU
}
-export const PAGE_SIZE = 5
+export const PAGE_SIZE = 20
// EU-region orgs have no rows in this region's posthog_user tables; eu_org_members is a
// materialized DWH pre-join of the EU postgres sync (prod-only, refreshed daily).
@@ -45,7 +44,7 @@ const fetchEuMembers = async (externalId: string): Promise<AccountOrganizationMe
kind: NodeKind.HogQLQuery,
tags: CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
query: hogql`
- select user_id, membership_id, first_name, last_name, email, distinct_id
+ select user_id, membership_id, level, first_name, last_name, email, distinct_id
from eu_org_members
where organization_id = ${externalId}
order by joined_at desc
@@ -55,12 +54,13 @@ const fetchEuMembers = async (externalId: string): Promise<AccountOrganizationMe
const rows = (response.results ?? []) as unknown[][]
return rows.map((row) => ({
id: String(row[1]),
+ level: Number(row[2]) as AccountOrganizationMember['level'],
user: {
id: Number(row[0]),
- first_name: (row[2] as string | null) ?? '',
- last_name: (row[3] as string | null) ?? '',
- email: (row[4] as string | null) ?? '',
- distinct_id: (row[5] as string | null) ?? '',
+ first_name: (row[3] as string | null) ?? '',
+ last_name: (row[4] as string | null) ?? '',
+ email: (row[5] as string | null) ?? '',
+ distinct_id: (row[6] as string | null) ?? '',
} as AccountOrganizationMember['user'],
region: Region.EU,
}))