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): Account notes list endpoint (#67991)

Arthur Moreira de Deusdb3a5585f3b8
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index dcb2200b3fe2..87a7c49a236a 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -1440,6 +1440,34 @@ def list_account_notebooks(
]
+def list_account_notes_for_view(
+ *,
+ team_id: int,
+ user_access_control: "UserAccessControl",
+ offset: int,
+ limit: int,
+ search: str | None = None,
+) -> tuple[list[contracts.AccountNoteView], int]:
+ """Team-wide account notes (internal notebooks linked to accounts), newest-modified first,
+ restricted to accounts the caller can read. ``search`` matches note title/content (full-text)
+ and account name (substring). Returns ``(page, total_count)``."""
+ accessible_account_ids = _accounts_queryset(team_id, user_access_control).values_list("id", flat=True)
+ notes, count = notebooks.list_team_account_notes(
+ team_id, account_ids=accessible_account_ids, search=search, offset=offset, limit=limit
+ )
+ return [
+ contracts.AccountNoteView(
+ short_id=note.short_id,
+ title=note.title,
+ created_at=note.created_at,
+ last_modified_at=note.last_modified_at,
+ account_id=note.account_id,
+ account_name=note.account_name,
+ )
+ for note in notes
+ ], count
+
+
def get_account_notebook(
team_id: int, account_id: str, short_id: str, user_access_control: "UserAccessControl"
) -> contracts.AccountNotebookView | None:
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 96748eba1c49..515dc1142932 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -317,6 +317,20 @@ class AccountNotebookView:
last_modified_by: UserBasicInfo | None = None
+@dataclass(frozen=True)
+class AccountNoteView:
+ """A row of the team-wide account-notes list: an internal notebook plus the account it's
+ linked to. Read-only (the wrapping serializer never parses request bodies), so fields are
+ strict — no serializer-instantiation defaults like :class:`AccountView` needs."""
+
+ short_id: str
+ title: str | None
+ created_at: datetime
+ last_modified_at: datetime
+ account_id: UUID
+ account_name: str
+
+
# --- Presentation wave: input contracts for the CRUD write paths ---
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 740a061a1e8e..9b5e576fc598 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -30,6 +30,7 @@ from posthog.models import OrganizationMembership
from products.customer_analytics.backend.facade.constants import CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES
from products.customer_analytics.backend.facade.contracts import (
AccountNotebookView,
+ AccountNoteView,
AccountView,
CustomerJourneyView,
CustomerProfileConfigView,
@@ -267,6 +268,22 @@ class AccountNotebookSerializer(DataclassSerializer):
]
+class AccountNoteSerializer(DataclassSerializer):
+ """A team-wide account note — an internal notebook linked to a Customer analytics account."""
+
+ short_id = serializers.CharField(read_only=True, help_text="URL-safe short ID of the notebook.")
+ title = serializers.CharField(read_only=True, allow_null=True, help_text="Title of the note.")
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the note was created.")
+ last_modified_at = serializers.DateTimeField(read_only=True, help_text="When the note was last modified.")
+ account_id = serializers.UUIDField(read_only=True, help_text="UUID of the account this note is linked to.")
+ account_name = serializers.CharField(read_only=True, help_text="Name of the account this note is linked to.")
+
+ class Meta:
+ dataclass = AccountNoteView
+ ref_name = "AccountNote"
+ fields = ["short_id", "title", "created_at", "last_modified_at", "account_id", "account_name"]
+
+
class CustomPropertyReferenceSerializer(DataclassSerializer):
"""A place that uses a custom property definition (read-only)."""
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 629d424d3922..f61501cd8fd9 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -33,6 +33,7 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from products.customer_analytics.backend.facade import api, contracts
from products.customer_analytics.backend.presentation.views.serializers import (
AccountNotebookSerializer,
+ AccountNoteSerializer,
AccountSerializer,
CustomerJourneySerializer,
CustomerProfileConfigSerializer,
@@ -805,6 +806,43 @@ def _synthesize_notebook_content(text_content, existing_content):
return None
+@extend_schema(tags=["customer_analytics"])
+class AccountNotesViewSet(
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ _FacadePaginationMixin,
+ mixins.ListModelMixin,
+ viewsets.GenericViewSet,
+):
+ scope_object = "account"
+ serializer_class = AccountNoteSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
+
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ name="search",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Full-text search across note title and content, plus substring match on account name.",
+ ),
+ ],
+ )
+ def list(self, request: Request, *args, **kwargs) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_account_notes_for_view(
+ team_id=self.team_id,
+ user_access_control=self.user_access_control,
+ offset=offset,
+ limit=limit,
+ search=request.query_params.get("search", "").strip() or None,
+ ),
+ AccountNoteSerializer,
+ )
+
+
@extend_schema(
tags=["customer_analytics"],
parameters=[
diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.py
index 35a73717adb5..6f0d007f5a5a 100644
--- a/products/customer_analytics/backend/routes.py
+++ b/products/customer_analytics/backend/routes.py
@@ -5,6 +5,7 @@ from products.customer_analytics.backend.presentation.views.organization_members
)
from products.customer_analytics.backend.presentation.views.views import (
AccountNotebookViewSet,
+ AccountNotesViewSet,
AccountViewSet,
CustomerJourneyViewSet,
CustomerProfileConfigViewSet,
@@ -42,6 +43,12 @@ def register_routes(routers: RouterRegistry) -> None:
"project_custom_property_sources",
["team_id"],
)
+ routers.projects.register(
+ r"account_notes",
+ AccountNotesViewSet,
+ "project_account_notes",
+ ["team_id"],
+ )
project_accounts_router, environment_accounts_router = routers.register_legacy_dual_route(
r"accounts", AccountViewSet, "project_accounts", ["team_id"]
)
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 444fad7e17b0..7415d9cb2361 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -1902,3 +1902,103 @@ class TestCustomPropertySourceViewSet(APIBaseTest):
toggled = self.client.patch(f"{self.endpoint}{source_id}/", {"is_enabled": False}, format="json")
assert toggled.status_code == status.HTTP_200_OK
assert toggled.json()["is_enabled"] is False
+
+
+class TestAccountNotesViewSet(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = Account.objects.unscoped().create(team=self.team, name="Acme Corp")
+ self.endpoint_base = f"/api/projects/{self.team.id}/account_notes/"
+
+ def _link_note(self, account: Account | None = None, **kwargs) -> Notebook:
+ kwargs.setdefault("visibility", Notebook.Visibility.INTERNAL)
+ notebook = Notebook.objects.create(team=self.team, **kwargs)
+ ResourceNotebook.objects.create(notebook=notebook, account=account or self.account)
+ return notebook
+
+ def test_list_returns_account_notes_with_account_fields(self):
+ note = self._link_note(title="Renewal")
+
+ response = self.client.get(self.endpoint_base)
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ results = response.json()["results"]
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]["short_id"], note.short_id)
+ self.assertEqual(results[0]["title"], "Renewal")
+ self.assertEqual(results[0]["account_id"], str(self.account.id))
+ self.assertEqual(results[0]["account_name"], "Acme Corp")
+
+ def test_list_excludes_unlinked_deleted_noninternal_and_other_team_notes(self):
+ included = self._link_note(title="Included")
+ Notebook.objects.create(team=self.team, title="Standalone")
+ self._link_note(title="Deleted", deleted=True)
+ self._link_note(title="Default visibility", visibility=Notebook.Visibility.DEFAULT)
+ other_team = Team.objects.create(organization=self.organization)
+ other_account = Account.objects.unscoped().create(team=other_team, name="Other")
+ other_note = Notebook.objects.create(
+ team=other_team, title="Other team", visibility=Notebook.Visibility.INTERNAL
+ )
+ ResourceNotebook.objects.create(notebook=other_note, account=other_account)
+
+ response = self.client.get(self.endpoint_base)
+
+ short_ids = [n["short_id"] for n in response.json()["results"]]
+ self.assertEqual(short_ids, [included.short_id])
+
+ @parameterized.expand(
+ [
+ ("matches_title", "renewal", {"Renewal planning"}),
+ ("matches_content", "pricing", {"Untitled"}),
+ ("matches_account_name", "acme", {"Renewal planning", "Untitled", "Kickoff"}),
+ ("no_match", "zzzz", set()),
+ ]
+ )
+ def test_list_search(self, _name, search, expected_titles):
+ self._link_note(title="Renewal planning", text_content="")
+ self._link_note(title="Untitled", text_content="pricing discussion")
+ self._link_note(title="Kickoff", text_content="agenda")
+
+ response = self.client.get(f"{self.endpoint_base}?search={search}")
+
+ titles = {n["title"] for n in response.json()["results"]}
+ self.assertEqual(titles, expected_titles)
+
+ def test_list_orders_by_last_modified_desc_and_paginates(self):
+ with freeze_time("2024-01-01"):
+ older = self._link_note(title="Older")
+ with freeze_time("2024-01-02"):
+ newer = self._link_note(title="Newer")
+
+ first_page = self.client.get(f"{self.endpoint_base}?limit=1").json()
+ self.assertEqual(first_page["count"], 2)
+ self.assertEqual([n["short_id"] for n in first_page["results"]], [newer.short_id])
+
+ second_page = self.client.get(f"{self.endpoint_base}?limit=1&offset=1").json()
+ self.assertEqual([n["short_id"] for n in second_page["results"]], [older.short_id])
+
+ def test_list_hides_notes_of_accounts_the_caller_cannot_read(self):
+ visible = self._link_note(title="Visible")
+ hidden_account = Account.objects.unscoped().create(team=self.team, name="Hidden Inc")
+ self._link_note(title="Hidden", account=hidden_account)
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ viewer = User.objects.create_and_join(self.organization, "[email protected]", None)
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(hidden_account.id),
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(user=viewer, organization=self.organization),
+ )
+ self.client.force_login(viewer)
+
+ response = self.client.get(self.endpoint_base)
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
+ short_ids = [n["short_id"] for n in response.json()["results"]]
+ self.assertEqual(short_ids, [visible.short_id])
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index d7209ecd223b..94c60f2c5c61 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -7,6 +7,36 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+/**
+ * A team-wide account note — an internal notebook linked to a Customer analytics account.
+ */
+export interface AccountNoteApi {
+ /** URL-safe short ID of the notebook. */
+ readonly short_id: string
+ /**
+ * Title of the note.
+ * @nullable
+ */
+ readonly title: string | null
+ /** When the note was created. */
+ readonly created_at: string
+ /** When the note was last modified. */
+ readonly last_modified_at: string
+ /** UUID of the account this note is linked to. */
+ readonly account_id: string
+ /** Name of the account this note is linked to. */
+ readonly account_name: string
+}
+
+export interface PaginatedAccountNoteListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AccountNoteApi[]
+}
+
/**
* Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link). Defaults to an empty object. Unknown keys are rejected.
* @nullable
@@ -705,6 +735,21 @@ export interface PatchedGroupUsageMetricApi {
math_property?: string | null
}
+export type AccountNotesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Full-text search across note title and content, plus substring match on account name.
+ */
+ search?: string
+}
+
export type AccountsListParams = {
/**
* Filter by account executive. Use 'unassigned' or an integer user id.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index ff813e70d5c7..eac479f3a5c8 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
AccountApi,
AccountNotebookApi,
+ AccountNotesListParams,
AccountsListParams,
AccountsNotebooksListParams,
CustomPropertyDefinitionApi,
@@ -27,6 +28,7 @@ import type {
GroupUsageMetricApi,
GroupsTypesMetricsListParams,
PaginatedAccountListApi,
+ PaginatedAccountNoteListApi,
PaginatedAccountNotebookListApi,
PaginatedCustomPropertyDefinitionListApi,
PaginatedCustomPropertySourceListApi,
@@ -58,6 +60,33 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getAccountNotesListUrl = (projectId: string, params?: AccountNotesListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/account_notes/?${stringifiedParams}`
+ : `/api/projects/${projectId}/account_notes/`
+}
+
+export const accountNotesList = async (
+ projectId: string,
+ params?: AccountNotesListParams,
+ options?: RequestInit
+): Promise<PaginatedAccountNoteListApi> => {
+ return apiMutator<PaginatedAccountNoteListApi>(getAccountNotesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getAccountsListUrl = (projectId: string, params?: AccountsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 4b8aeeab204a..8e7fa5cf1a3a 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -9,6 +9,9 @@ feature: customer_analytics
url_prefix: /customer-analytics
ui_apps: {}
tools:
+ account-notes-list:
+ operation: account_notes_list
+ enabled: false
accounts-create:
operation: accounts_create
enabled: true
diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.py
index 99b345d5cd9d..be9b280ecfb2 100644
--- a/products/notebooks/backend/facade/api.py
+++ b/products/notebooks/backend/facade/api.py
@@ -12,11 +12,12 @@ Content-tree helpers live in ``facade.content``; collaborative-edit publishing
lives in ``facade.collab``.
"""
+from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from uuid import UUID
from .. import logic, markdown_migration
-from ..models import Notebook
+from ..models import Notebook, ResourceNotebook
from . import contracts
if TYPE_CHECKING:
@@ -268,3 +269,31 @@ def get_account_notebook(account_id: str | UUID, short_id: str) -> contracts.Acc
def delete_account_notebook(account_id: str | UUID, short_id: str) -> bool:
return logic.delete_account_notebook(account_id, short_id)
+
+
+def _to_team_account_note(link: ResourceNotebook) -> contracts.TeamAccountNote:
+ # The account FK is nullable on the model; the team-notes queryset filters
+ # `account__isnull=False`, so narrow for the type checker.
+ assert link.account is not None
+ return contracts.TeamAccountNote(
+ short_id=link.notebook.short_id,
+ title=link.notebook.title,
+ created_at=link.notebook.created_at,
+ last_modified_at=link.notebook.last_modified_at,
+ account_id=link.account.id,
+ account_name=link.account.name,
+ )
+
+
+def list_team_account_notes(
+ team_id: int,
+ *,
+ account_ids: Iterable[UUID | str] | None = None,
+ search: str | None = None,
+ offset: int = 0,
+ limit: int = 100,
+) -> tuple[list[contracts.TeamAccountNote], int]:
+ links, count = logic.list_team_account_notes(
+ team_id, account_ids=account_ids, search=search, offset=offset, limit=limit
+ )
+ return [_to_team_account_note(link) for link in links], count
diff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.py
index 7b9e2dc468a5..85d95bf06f74 100644
--- a/products/notebooks/backend/facade/contracts.py
+++ b/products/notebooks/backend/facade/contracts.py
@@ -56,6 +56,18 @@ class NotebookActivitySummary:
recent: list[NotebookRecent] = field(default_factory=list)
+@dataclass(frozen=True)
+class TeamAccountNote:
+ """A row of a team-wide account-notes list: an internal notebook plus the account it's linked to."""
+
+ short_id: str
+ title: str | None
+ created_at: datetime
+ last_modified_at: datetime
+ account_id: UUID
+ account_name: str
+
+
@dataclass(frozen=True)
class MarkdownNotebookMigrationStats:
"""Markdown migration status for notebooks in an optional team scope."""
diff --git a/products/notebooks/backend/logic.py b/products/notebooks/backend/logic.py
index 7d4791ddf399..c269b92e68c5 100644
--- a/products/notebooks/backend/logic.py
+++ b/products/notebooks/backend/logic.py
@@ -6,6 +6,7 @@ facade, which maps them to framework-free contracts. Nothing outside the product
should import this module — cross-product callers go through ``facade.api``.
"""
+from collections.abc import Iterable
from typing import Any
from uuid import UUID
@@ -237,3 +238,36 @@ def delete_account_notebook(account_id: str | UUID, short_id: str) -> bool:
return False
notebook.delete()
return True
+
+
+def list_team_account_notes(
+ team_id: int,
+ *,
+ account_ids: Iterable[UUID | str] | None = None,
+ search: str | None = None,
+ offset: int = 0,
+ limit: int = 100,
+) -> tuple[list[ResourceNotebook], int]:
+ """Team-wide account notes: internal notebooks linked to any account, newest-modified first.
+
+ ``account_ids`` restricts to the given accounts (callers pass the caller-accessible set —
+ a lazy ``values_list`` queryset compiles to a SQL subquery). ``search`` is full-text over
+ notebook title/content plus substring over the linked account's name. Returns
+ ``(page, total_count)``.
+ """
+ queryset = ResourceNotebook.objects.filter(
+ account__isnull=False,
+ notebook__team_id=team_id,
+ notebook__deleted=False,
+ notebook__visibility=Notebook.Visibility.INTERNAL,
+ ).select_related("notebook", "account")
+ if account_ids is not None:
+ queryset = queryset.filter(account_id__in=account_ids)
+ if search:
+ queryset = queryset.filter(
+ Q(notebook__title__search=search)
+ | Q(notebook__text_content__search=search)
+ | Q(account__name__icontains=search)
+ )
+ queryset = queryset.order_by("-notebook__last_modified_at")
+ return list(queryset[offset : offset + limit]), queryset.count()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 863ee080c0e4..12ded8778251 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -137,6 +137,27 @@ export namespace Schemas {
readonly updated_at: string | null;
}
+ /**
+ * A team-wide account note — an internal notebook linked to a Customer analytics account.
+ */
+ export interface AccountNote {
+ /** URL-safe short ID of the notebook. */
+ readonly short_id: string;
+ /**
+ * Title of the note.
+ * @nullable
+ */
+ readonly title: string | null;
+ /** When the note was created. */
+ readonly created_at: string;
+ /** When the note was last modified. */
+ readonly last_modified_at: string;
+ /** UUID of the account this note is linked to. */
+ readonly account_id: string;
+ /** Name of the account this note is linked to. */
+ readonly account_name: string;
+ }
+
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -31148,6 +31169,15 @@ export namespace Schemas {
results: Account[];
}
+ export interface PaginatedAccountNoteList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: AccountNote[];
+ }
+
export interface PaginatedAccountNotebookList {
count: number;
/** @nullable */
@@ -60178,6 +60208,21 @@ export namespace Schemas {
offset?: number;
};
+ export type AccountNotesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Full-text search across note title and content, plus substring match on account name.
+ */
+ search?: string;
+ };
+
export type AccountsListParams = {
/**
* Filter by account executive. Use 'unassigned' or an integer user id.