: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): expose note creator and filters on notes endpoint (#68306)
Arthur Moreira de Deusb5c034490af1
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 87a7c49a236a..8bb5c3689cfe 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -1447,13 +1447,22 @@ def list_account_notes_for_view(offset: int,limit: int,search: str | None = None,+ account_id: UUID | str | None = None,+ created_by_ids: list[int] | 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)``."""+ and account name (substring). ``account_id`` narrows to one account, ``created_by_ids`` to+ notes authored by the given users. 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+ team_id,+ account_ids=accessible_account_ids,+ account_id=account_id,+ created_by_ids=created_by_ids,+ search=search,+ offset=offset,+ limit=limit,)return [contracts.AccountNoteView(@@ -1463,6 +1472,7 @@ def list_account_notes_for_view(last_modified_at=note.last_modified_at,account_id=note.account_id,account_name=note.account_name,+ created_by=_notebook_user_to_basic_info(note.created_by),)for note in notes], countdiff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 515dc1142932..58fc06441168 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -329,6 +329,7 @@ class AccountNoteView:last_modified_at: datetimeaccount_id: UUIDaccount_name: str+ created_by: UserBasicInfo | None = None# --- 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.pyindex 9b5e576fc598..ba00edb65668 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -277,11 +277,12 @@ class AccountNoteSerializer(DataclassSerializer):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.")+ created_by = UserBasicSerializer(read_only=True, allow_null=True, help_text="User who created the note, if known.")class Meta:dataclass = AccountNoteViewref_name = "AccountNote"- fields = ["short_id", "title", "created_at", "last_modified_at", "account_id", "account_name"]+ fields = ["short_id", "title", "created_at", "last_modified_at", "account_id", "account_name", "created_by"]class CustomPropertyReferenceSerializer(DataclassSerializer):diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex f61501cd8fd9..7a9d61b67318 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -14,6 +14,7 @@ from __future__ import annotationsimport jsonfrom typing import cast+from uuid import UUIDfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema@@ -827,9 +828,41 @@ class AccountNotesViewSet(required=False,description="Full-text search across note title and content, plus substring match on account name.",),+ OpenApiParameter(+ name="account_id",+ type=OpenApiTypes.UUID,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Only return notes linked to this account.",+ ),+ OpenApiParameter(+ name="created_by",+ type=OpenApiTypes.INT,+ many=True,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Only return notes created by these user IDs (repeat the param per user).",+ ),],)def list(self, request: Request, *args, **kwargs) -> Response:+ # The generated client serializes the array as a single comma-joined value; accept that+ # and the repeated-param form alike.+ created_by_ids = []+ for value in request.query_params.getlist("created_by"):+ for part in value.split(","):+ part = part.strip()+ if not part:+ continue+ if not part.isdigit():+ raise ValidationError({"created_by": "Must be a comma-separated list of numeric user IDs."})+ created_by_ids.append(int(part))+ account_id: UUID | None = None+ if raw_account_id := request.query_params.get("account_id"):+ try:+ account_id = UUID(raw_account_id)+ except ValueError:+ raise ValidationError({"account_id": "Must be a valid UUID."})return self._paginate_via_facade(request,lambda offset, limit: api.list_account_notes_for_view(@@ -838,6 +871,8 @@ class AccountNotesViewSet(offset=offset,limit=limit,search=request.query_params.get("search", "").strip() or None,+ account_id=account_id,+ created_by_ids=created_by_ids or None,),AccountNoteSerializer,)diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex fadb4140fd35..826e470c1362 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -1917,7 +1917,7 @@ class TestAccountNotesViewSet(APIBaseTest):return notebookdef test_list_returns_account_notes_with_account_fields(self):- note = self._link_note(title="Renewal")+ note = self._link_note(title="Renewal", created_by=self.user)response = self.client.get(self.endpoint_base)@@ -1928,6 +1928,8 @@ class TestAccountNotesViewSet(APIBaseTest):self.assertEqual(results[0]["title"], "Renewal")self.assertEqual(results[0]["account_id"], str(self.account.id))self.assertEqual(results[0]["account_name"], "Acme Corp")+ self.assertEqual(results[0]["created_by"]["id"], self.user.id)+ self.assertEqual(results[0]["created_by"]["email"], self.user.email)def test_list_excludes_unlinked_deleted_noninternal_and_other_team_notes(self):included = self._link_note(title="Included")@@ -1964,6 +1966,46 @@ class TestAccountNotesViewSet(APIBaseTest):titles = {n["title"] for n in response.json()["results"]}self.assertEqual(titles, expected_titles)+ def test_list_filter_by_account(self):+ other_account = Account.objects.unscoped().create(team=self.team, name="Beta LLC")+ self._link_note(title="Acme note")+ self._link_note(title="Beta note", account=other_account)++ response = self.client.get(f"{self.endpoint_base}?account_id={self.account.id}")++ titles = [n["title"] for n in response.json()["results"]]+ self.assertEqual(titles, ["Acme note"])++ @parameterized.expand(+ [+ ("account_id", "not-a-uuid"),+ ("created_by", "alice"),+ ("created_by", "alice,bob"),+ ]+ )+ def test_list_rejects_malformed_filter(self, param, value):+ response = self.client.get(f"{self.endpoint_base}?{param}={value}")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ @parameterized.expand(+ [+ ("single", "{uid}"),+ ("comma_joined", "{uid},999999"), # the encoding the generated frontend client sends+ ("repeated", "{uid}&created_by=999999"),+ ]+ )+ def test_list_filter_by_created_by(self, _name, created_by_query):+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ self._link_note(title="Mine", created_by=self.user)+ self._link_note(title="Theirs", created_by=other_user)++ query = created_by_query.format(uid=self.user.id)+ response = self.client.get(f"{self.endpoint_base}?created_by={query}")++ titles = [n["title"] for n in response.json()["results"]]+ self.assertEqual(titles, ["Mine"])+def test_list_orders_by_last_modified_desc_and_paginates(self):with freeze_time("2024-01-01"):older = self._link_note(title="Older")diff --git a/products/customer_analytics/frontend/components/AccountNotes/AccountNotesTabContent.tsx b/products/customer_analytics/frontend/components/AccountNotes/AccountNotesTabContent.tsxindex 2748e48cf3b7..a2f742160536 100644--- a/products/customer_analytics/frontend/components/AccountNotes/AccountNotesTabContent.tsx+++ b/products/customer_analytics/frontend/components/AccountNotes/AccountNotesTabContent.tsx@@ -25,7 +25,7 @@ export function AccountNotesTabContent(): JSX.Element {title: 'Title',dataIndex: 'title',width: '100%',- render: function Render(title, note) {+ render: function Render(_, note) {// Plain click opens the note in the side panel (keeping the list mounted);// the href stays so cmd/ctrl-click opens the full notebook page in a new tab.return (@@ -41,7 +41,7 @@ export function AccountNotesTabContent(): JSX.Element {selectNotebook(note.short_id)}}>- {title || 'Untitled'}+ {note.title || 'Untitled'}</Link>)},@@ -49,7 +49,7 @@ export function AccountNotesTabContent(): JSX.Element {{title: 'Account',dataIndex: 'account_name',- render: function Render(accountName, note) {+ render: function Render(_, note) {return (<Linkdata-attr="account-note-account"@@ -59,7 +59,7 @@ export function AccountNotesTabContent(): JSX.Element {posthog.capture(AccountsEvents.NotesTabAccountClicked, { account_id: note.account_id })}}>- {accountName}+ {note.account_name}</Link>)},diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 94c60f2c5c61..eaf99d7a4bc8 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -7,6 +7,61 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+/**+ * * `engineering` - Engineering+ * * `data` - Data+ * * `product` - Product Management+ * * `founder` - Founder+ * * `leadership` - Leadership+ * * `marketing` - Marketing+ * * `sales` - Sales / Success+ * * `other` - Other+ */+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]++export const RoleAtOrganizationEnumApi = {+ Engineering: 'engineering',+ Data: 'data',+ Product: 'product',+ Founder: 'founder',+ Leadership: 'leadership',+ Marketing: 'marketing',+ Sales: 'sales',+ Other: 'other',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++/**+ * @nullable+ */+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null++export interface UserBasicApi {+ readonly id: number+ readonly uuid: string+ /**+ * @maxLength 200+ * @nullable+ */+ distinct_id?: string | null+ /** @maxLength 150 */+ first_name?: string+ /** @maxLength 150 */+ last_name?: string+ /** @maxLength 254 */+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ readonly hedgehog_config: UserBasicApiHedgehogConfig+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null+}+/*** A team-wide account note — an internal notebook linked to a Customer analytics account.*/@@ -26,6 +81,8 @@ export interface AccountNoteApi {readonly account_id: string/** Name of the account this note is linked to. */readonly account_name: string+ /** User who created the note, if known. */+ readonly created_by: UserBasicApi | null}export interface PaginatedAccountNoteListApi {@@ -142,61 +199,6 @@ export interface CustomPropertyValueWriteApi {value: string | number | boolean}-/**- * * `engineering` - Engineering- * * `data` - Data- * * `product` - Product Management- * * `founder` - Founder- * * `leadership` - Leadership- * * `marketing` - Marketing- * * `sales` - Sales / Success- * * `other` - Other- */-export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]--export const RoleAtOrganizationEnumApi = {- Engineering: 'engineering',- Data: 'data',- Product: 'product',- Founder: 'founder',- Leadership: 'leadership',- Marketing: 'marketing',- Sales: 'sales',- Other: 'other',-} as const--export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]--export const BlankEnumApi = {- '': '',-} as const--/**- * @nullable- */-export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null--export interface UserBasicApi {- readonly id: number- readonly uuid: string- /**- * @maxLength 200- * @nullable- */- distinct_id?: string | null- /** @maxLength 150 */- first_name?: string- /** @maxLength 150 */- last_name?: string- /** @maxLength 254 */- email: string- /** @nullable */- is_email_verified?: boolean | null- /** @nullable */- readonly hedgehog_config: UserBasicApiHedgehogConfig- role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null-}-export interface AccountNotebookApi {readonly id: stringreadonly short_id: string@@ -736,6 +738,14 @@ export interface PatchedGroupUsageMetricApi {}export type AccountNotesListParams = {+ /**+ * Only return notes linked to this account.+ */+ account_id?: string+ /**+ * Only return notes created by these user IDs (repeat the param per user).+ */+ created_by?: number[]/*** Number of results to return per page.*/diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.pyindex be9b280ecfb2..742cec39d5e0 100644--- a/products/notebooks/backend/facade/api.py+++ b/products/notebooks/backend/facade/api.py@@ -282,6 +282,7 @@ def _to_team_account_note(link: ResourceNotebook) -> contracts.TeamAccountNote:last_modified_at=link.notebook.last_modified_at,account_id=link.account.id,account_name=link.account.name,+ created_by=_to_notebook_user(link.notebook.created_by),)@@ -289,11 +290,19 @@ def list_team_account_notes(team_id: int,*,account_ids: Iterable[UUID | str] | None = None,+ account_id: UUID | str | None = None,+ created_by_ids: Iterable[int] | 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+ team_id,+ account_ids=account_ids,+ account_id=account_id,+ created_by_ids=created_by_ids,+ search=search,+ offset=offset,+ limit=limit,)return [_to_team_account_note(link) for link in links], countdiff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.pyindex 85d95bf06f74..fc0c068dc24a 100644--- a/products/notebooks/backend/facade/contracts.py+++ b/products/notebooks/backend/facade/contracts.py@@ -56,6 +56,21 @@ class NotebookActivitySummary:recent: list[NotebookRecent] = field(default_factory=list)+@dataclass(frozen=True)+class NotebookUserInfo:+ """The creator/modifier of a notebook — raw user values, mirroring UserBasicSerializer's input."""++ id: int+ uuid: UUID+ distinct_id: str | None+ first_name: str+ last_name: str+ email: str+ is_email_verified: bool | None+ hedgehog_config: Any+ role_at_organization: str | None++@dataclass(frozen=True)class TeamAccountNote:"""A row of a team-wide account-notes list: an internal notebook plus the account it's linked to."""@@ -66,6 +81,7 @@ class TeamAccountNote:last_modified_at: datetimeaccount_id: UUIDaccount_name: str+ created_by: NotebookUserInfo | None = None@dataclass(frozen=True)@@ -114,21 +130,6 @@ class AccountNote:short_id: str-@dataclass(frozen=True)-class NotebookUserInfo:- """The creator/modifier of a notebook — raw user values, mirroring UserBasicSerializer's input."""-- id: int- uuid: UUID- distinct_id: str | None- first_name: str- last_name: str- email: str- is_email_verified: bool | None- hedgehog_config: Any- role_at_organization: str | None--@dataclass(frozen=True)class AccountNotebook:"""A full internal notebook linked to an account, with creator/modifier info.diff --git a/products/notebooks/backend/logic.py b/products/notebooks/backend/logic.pyindex c269b92e68c5..cdaa16a2050c 100644--- a/products/notebooks/backend/logic.py+++ b/products/notebooks/backend/logic.py@@ -244,6 +244,8 @@ def list_team_account_notes(team_id: int,*,account_ids: Iterable[UUID | str] | None = None,+ account_id: UUID | str | None = None,+ created_by_ids: Iterable[int] | None = None,search: str | None = None,offset: int = 0,limit: int = 100,@@ -251,18 +253,23 @@ def list_team_account_notes("""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)``.+ a lazy ``values_list`` queryset compiles to a SQL subquery). ``account_id`` narrows to a+ single account, ``created_by_ids`` to notes authored by the given users. ``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")+ ).select_related("notebook", "notebook__created_by", "account")if account_ids is not None:queryset = queryset.filter(account_id__in=account_ids)+ if account_id is not None:+ queryset = queryset.filter(account_id=account_id)+ if created_by_ids is not None:+ queryset = queryset.filter(notebook__created_by_id__in=created_by_ids)if search:queryset = queryset.filter(Q(notebook__title__search=search)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 970dcdd6b4c1..82baee899271 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -137,27 +137,6 @@ 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@@ -215,6 +194,29 @@ export namespace Schemas {role_at_organization?: RoleAtOrganizationEnum | BlankEnum | 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;+ /** User who created the note, if known. */+ readonly created_by: UserBasic | null;+ }+export interface AccountNotebook {readonly id: string;readonly short_id: string;@@ -60572,6 +60574,14 @@ export namespace Schemas {};export type AccountNotesListParams = {+ /**+ * Only return notes linked to this account.+ */+ account_id?: string;+ /**+ * Only return notes created by these user IDs (repeat the param per user).+ */+ created_by?: number[];/*** Number of results to return per page.*/