: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): search, sort, paginate & create account notes (#65880)
Arthur Moreira de Deus6525b7bf444f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5f0abb897b47..89717c9a2e33 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4773,17 +4773,17 @@ snapshots:scenes-app-customer-analytics-accounts--row-expanded-empty--light:hash: v1.k794b7964.904bd5b939f99d43408ae3a8a814a3c299bd57bf13a0fd1d98ff6033fd66e343.K1Z16ICEF6-O9kIej8kGnYyarloq2oZH5rdtmx-8Hu0scenes-app-customer-analytics-accounts--row-expanded-links-disabled--dark:- hash: v1.k794b7964.0d01e116e4a6c7f48c2463d03e458a537de5b7ed170bcd6eaa53132e5401b003.SXbtak_1nqvrKhJF0zbIF4qEW9NFrjrd6VcoQphZ2Z0+ hash: v1.k794b7964.f2d43867c031f539641e4c8f6fcf30bfe6140cc9e3aa596b65d767dd10fa4921.F1vyV__TE7gcuA85X8fUmey9KXhssurg6Rk65ETYcIMscenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:- hash: v1.k794b7964.2719242d07a4035afb1207ecc9f5bc17023128269e105416dbef7fa89532b0df.PS57UkTp6HZQve4AaLvscsJRv6Do48TkGsQC3YDtFqc+ hash: v1.k794b7964.7895f3c3ea4bd144f0fab73b065ed655f19e1726976d0fef0abfeb68d10743f6.1yXgRyhrdluQY4gaksbmnL5KmsTfBC51mFDrwuH-a8kscenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:- hash: v1.k794b7964.db2b85da4ffdfb9b336ce25618d52fa2b83e385d794ac7e15ee208ee5180cbe5.OUqstg6jUmYhZrvHuH5p4__83sjVTVpWFFA6HA0_ODc+ hash: v1.k794b7964.53af994a2a4dfb2f883e27ed73be8d55e1177b97f5c8b622708dfcdbe5f33d2a.A7AJRK9hY-yytJMNPghuLYtOJIoj0VBJidseMubwZWsscenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:- hash: v1.k794b7964.a764885f8e150d90b1e5377d48cd3b27c0662375b868efa15e7151eb9cc65c96.K1zizRw3mEP8dLm7dR2Exm6BBSx4y2rcbiVvu1roBcs+ hash: v1.k794b7964.f09bed960de45bc9ff5f420947a71bc6df84adbad2bf9ad49567b6ad9682fac1.MODXCsvl4HKThtTT0q9ixAlK-obyYstQN3BmZgVR3tgscenes-app-customer-analytics-accounts--row-expanded-usage-populated--dark:- hash: v1.k794b7964.f6e3297d03ce70c9f476a3f4a439023e9165f0b807da04cbaea31bdd4e7131fc.5UhghJQ945WUBU_G21NKnnFtNXpl02vNHgHGKUmuF3w+ hash: v1.k794b7964.292e28475dccfaa5774086c075e30ec13b687a2cdd31940d91db2867f6eebb59.rmdLj-KuNUYG9EaP14dC0lNITfedqDA6ZowjtaypwqEscenes-app-customer-analytics-accounts--row-expanded-usage-populated--light:- hash: v1.k794b7964.3c9bf682041aaec51eee49033716cc5b02bd868faaf1a4212610fcbc7de774be.__A7U7lquAbOTTIY-zgPd7uYibm3hEug52PnXcet8H0+ hash: v1.k794b7964.8480cd33c476381878cbf88f6b91ae617c71d2093d19983a83b082e39b2c60e2.q-ykZx3-XGsMNDO60MI74cTBmrklBZ1zqtMyk0U9CU8scenes-app-customer-analytics-accounts--row-expanded-with-note--dark:hash: v1.k794b7964.3c9ce002ecb9931c56ef82618cc1625ee847a7f8df2a35c490006e4b356e6fb5.bK3yVZfb-U4TUMJHKvLemkMdqx6YNKdkFC2lnrWBgYgscenes-app-customer-analytics-accounts--row-expanded-with-note--light:diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 34dba640ea9f..efbb6d23cd10 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -1161,13 +1161,21 @@ def get_accessible_account_id(team_id: int, account_id: str, user_access_controldef list_account_notebooks(- team_id: int, account_id: str, user_access_control: "UserAccessControl"+ team_id: int,+ account_id: str,+ user_access_control: "UserAccessControl",+ *,+ search: str | None = None,+ order: str | None = None,) -> list[contracts.AccountNotebookView] | None:- """Internal notebooks linked to an accessible account, newest first. None when the- parent account isn't accessible (→ 404)."""+ """Internal notebooks linked to an accessible account. Optionally full-text filtered by+ ``search`` (title + content) and sorted by ``order`` (creation date or author); defaults to+ newest first. None when the parent account isn't accessible (→ 404)."""if get_accessible_account_id(team_id, account_id, user_access_control) is None:return None- return [_to_account_notebook_view(n) for n in notebooks.list_account_notebooks(account_id)]+ return [+ _to_account_notebook_view(n) for n in notebooks.list_account_notebooks(account_id, search=search, order=order)+ ]def get_account_notebook(diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 7c8c8e0a962e..5159de4351a5 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -634,9 +634,36 @@ class AccountNotebookViewSet(queryset = Nonelookup_field = "short_id"+ ALLOWED_ORDERING = frozenset({"created_at", "-created_at", "created_by", "-created_by"})++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="search",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Full-text search across notebook title and content.",+ ),+ OpenApiParameter(+ name="ordering",+ type=OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ enum=["created_at", "-created_at", "created_by", "-created_by"],+ description="Sort by creation date or author. Defaults to '-created_at'.",+ ),+ ],+ )def list(self, request: Request, *args, **kwargs) -> Response:+ ordering = request.query_params.get("ordering")+ ordering = ordering if ordering in self.ALLOWED_ORDERING else Nonenotebooks = api.list_account_notebooks(- self.team_id, self.parents_query_dict["account_id"], user_access_control=self.user_access_control+ self.team_id,+ self.parents_query_dict["account_id"],+ user_access_control=self.user_access_control,+ search=request.query_params.get("search", "").strip() or None,+ order=ordering,)if notebooks is None:return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex 4c023eae445a..0be30b2539e5 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -1,4 +1,5 @@import pytest+from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom parameterized import parameterized@@ -1031,6 +1032,36 @@ class TestAccountNotebookViewSet(APIBaseTest):short_ids = [n["short_id"] for n in response.json()["results"]]self.assertEqual(short_ids, [account_notebook.short_id])+ def _link_internal_notebook(self, **kwargs) -> Notebook:+ notebook = Notebook.objects.create(team=self.team, visibility=Notebook.Visibility.INTERNAL, **kwargs)+ ResourceNotebook.objects.create(notebook=notebook, account=self.account)+ return notebook++ def test_list_search_matches_title_and_content(self):+ by_title = self._link_internal_notebook(title="Renewal planning", text_content="")+ by_content = self._link_internal_notebook(title="Untitled", text_content="discuss renewal terms")+ self._link_internal_notebook(title="Onboarding", text_content="kickoff call")++ response = self.client.get(f"{self.endpoint_base}?search=renewal")++ self.assertEqual(status.HTTP_200_OK, response.status_code)+ short_ids = {n["short_id"] for n in response.json()["results"]}+ self.assertEqual(short_ids, {by_title.short_id, by_content.short_id})++ def test_list_orders_by_created_at(self):+ with freeze_time("2024-01-01"):+ older = self._link_internal_notebook(title="Older", content={})+ with freeze_time("2024-01-02"):+ newer = self._link_internal_notebook(title="Newer", content={})++ default_order = [n["short_id"] for n in self.client.get(self.endpoint_base).json()["results"]]+ self.assertEqual(default_order, [newer.short_id, older.short_id])++ ascending = [+ n["short_id"] for n in self.client.get(f"{self.endpoint_base}?ordering=created_at").json()["results"]+ ]+ self.assertEqual(ascending, [older.short_id, newer.short_id])+def test_retrieve_returns_notebook_for_account(self):notebook = Notebook.objects.create(team=self.team, title="Note", content={"foo": "bar"}, visibility=Notebook.Visibility.INTERNALdiff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex a53ef499ca93..0931ccb89158 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -24,24 +24,24 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc├── AccountsOverviewTiles metric tiles across the filtered set└── AccountsHogQLTable the DataTable; per-column renderers; controlled row expansion└── AccountNotebooksExpansion expanded row: Useful links + LemonTabs(Notes/Users/Usage)- ├── (notes) in-place LemonTable of linked notebooks (accountNotebooksLogic, keyed by accountId)+ ├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)└── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)```### Logics and what each owns-| Logic | Owns |-| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `accountsLogic` | The hub. Search (debounced), tag and assigned-to/unassigned filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |-| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |-| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API). |-| `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`); feeds `metrics` into the query. 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`). |-| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). |-| `accountBillingLogic` | Billing/usage data behind the Usage tab. |-| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |+| Logic | Owns |+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `accountsLogic` | The hub. Search (debounced), tag and assigned-to/unassigned filters, sort, inline role assignment, the `hogqlQuery` selector, shareable URL-hash view state, and `openAccount` (the Max entry point). `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |+| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API). |+| `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`); feeds `metrics` into the query. 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`). |+| `accountBillingLogic` | Billing/usage data behind the Usage tab. |+| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |## Data & query model@@ -62,6 +62,8 @@ The Usage tab renders an existing saved billing-usage insight — **point usersClicking a note in the Notes tab opens it in the global notebook **side panel** (`notebookPanelLogic.selectNotebook`), keeping the Accounts list mounted — not the full `NotebookScene`. The note `<Link>` still points at `urls.notebook(shortId)` so cmd/ctrl-click opens the full page in a new tab; a plain click `preventDefault()`s the router push and opens the panel instead.+The Notes tab is server-paginated, searchable, and sortable (all via `accountNotebooksLogic`, which sends `limit`/`offset`/`search`/`ordering` to `accountsNotebooksList`). Search is full-text over title **and** content (mirrors the main Notebooks page); the **Created by** and **Created at** columns sort server-side (whitelisted `ordering`, default `-created_at`). The **New note** button creates an internal notebook linked to the account (via `accountsNotebooksCreate`) and opens it in the side panel — it persists immediately like normal notebook creation (no empty-cleanup). The backend chain threading `search`/`order` is: `AccountNotebookViewSet.list` (whitelists `ordering`) → customer-analytics facade `api.list_account_notebooks` → notebooks facade → `notebooks/backend/logic.list_account_notebooks`.+## Shareable view state`accountsLogic` mirrors the full view (search, tags, unassigned, assigned-to, sort, columns, tile filter) into the URL hash `#view=...` via `actionToUrl`/`urlToAction`, so a copied URL reproduces the exact list. Only non-default values are serialized. The "assigned to" filter persists as concrete `assignedTo` ids (not a `mine` flag), so a link shared with a colleague resolves to the **same** accounts for them as for the sharer; the legacy `mine: true` hash is still read and resolved to the current user's id for backward compatibility. A shared link's `columns` win over the per-user saved column config (`accountsColumnConfigLogic` enforces this when its async saved-config load resolves by checking the live URL).@@ -162,6 +164,9 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner`), `is_assigned`, `assigned_user_id`, `source` (always `list_row` today) || `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` | `link_key`, `has_destination` || `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |+| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` |+| `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |+| `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) || `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `usage`) || `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex 57e9ef406633..06194ca540c5 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -1,9 +1,10 @@import { useActions, useValues } from 'kea'import posthog from 'posthog-js'-import { IconGraph, IconPeople, IconPiggyBank, IconReceipt } from '@posthog/icons'+import { IconGraph, IconPencil, IconPeople, IconPiggyBank, IconReceipt } from '@posthog/icons'import {LemonButton,+ LemonInput,LemonSkeleton,LemonTable,LemonTableColumns,@@ -95,7 +96,9 @@ export function AccountNotebooksExpansion({externalId: string}): JSX.Element {const logic = accountNotebooksLogic({ accountId })- const { notebooks, notebooksLoading } = useValues(logic)+ const { notebooks, notebooksResponseLoading, createdNoteLoading, searchTerm, sorting, pagination } =+ useValues(logic)+ const { setSearchTerm, setSorting, createNote } = useActions(logic)const { activeTabFor } = useValues(accountsExpansionLogic)const { setActiveTab } = useActions(accountsExpansionLogic)const { selectNotebook } = useActions(notebookPanelLogic)@@ -134,7 +137,8 @@ export function AccountNotebooksExpansion({{title: 'Created by',key: 'created_by',- width: 220,+ width: 160,+ sorter: true,render: (_, notebook) => {const user = notebook.created_byif (!user) {@@ -155,14 +159,15 @@ export function AccountNotebooksExpansion({{title: 'Created at',key: 'created_at',- width: 180,+ width: 140,+ sorter: true,render: (_, notebook) => <TZLabel time={notebook.created_at} />,},]return (- <div className="sticky left-0 w-[100cqw] p-3 bg-bg-light">- <div className="flex gap-8">+ <div className="sticky left-0 w-[100cqw] max-w-full overflow-x-hidden p-3 bg-bg-light">+ <div className="flex gap-4"><div className="w-fit shrink-0"><UsefulLinks accountId={accountId} /></div>@@ -176,19 +181,45 @@ export function AccountNotebooksExpansion({key: 'notes',label: 'Notes',content: (- <LemonTable<AccountNotebookApi>- size="small"- embedded- dataSource={notebooks ?? []}- rowKey="short_id"- loading={notebooksLoading}- columns={columns}- emptyState={- notebooks === null- ? 'Failed to load account notes.'- : 'No notes linked to this account yet.'- }- />+ <div className="flex flex-col gap-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <LemonInput+ type="search"+ placeholder="Search notes by title or content..."+ value={searchTerm}+ onChange={setSearchTerm}+ size="small"+ className="min-w-64"+ />+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPencil />}+ onClick={createNote}+ loading={createdNoteLoading}+ >+ New note+ </LemonButton>+ </div>+ <LemonTable<AccountNotebookApi>+ size="small"+ embedded+ dataSource={notebooks ?? []}+ rowKey="short_id"+ loading={notebooksResponseLoading}+ columns={columns}+ sorting={sorting}+ onSort={setSorting}+ pagination={pagination}+ emptyState={+ notebooks === null+ ? 'Failed to load account notes.'+ : searchTerm+ ? 'No notes match your search.'+ : 'No notes linked to this account yet.'+ }+ />+ </div>),},{diff --git a/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.test.tsnew file mode 100644index 000000000000..1842838d260e--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.test.ts@@ -0,0 +1,117 @@+import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'++import { initKeaTests } from '~/test/init'++import { accountsNotebooksCreate, accountsNotebooksList } from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountNotebookApi,+ PaginatedAccountNotebookListApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountNotebooksLogic, NOTES_PER_PAGE } from './accountNotebooksLogic'++jest.mock('products/customer_analytics/frontend/generated/api', () => ({+ accountsNotebooksList: jest.fn(),+ accountsNotebooksCreate: jest.fn(),+}))++const mockList = accountsNotebooksList as jest.MockedFunction<typeof accountsNotebooksList>+const mockCreate = accountsNotebooksCreate as jest.MockedFunction<typeof accountsNotebooksCreate>++const TEAM = String(MOCK_DEFAULT_TEAM.id)++const buildResponse = (+ results: AccountNotebookApi[] = [],+ count: number = results.length+): PaginatedAccountNotebookListApi => ({ results, count, next: null, previous: null })++describe('accountNotebooksLogic', () => {+ let logic: ReturnType<typeof accountNotebooksLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.resetAllMocks()+ mockList.mockResolvedValue(buildResponse())+ })++ afterEach(() => {+ logic?.unmount()+ })++ const mount = async (): Promise<void> => {+ logic = accountNotebooksLogic({ accountId: 'acc-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ }++ it('loads the first page with the default ordering', async () => {+ await mount()++ expect(mockList).toHaveBeenLastCalledWith(TEAM, 'acc-1', {+ limit: NOTES_PER_PAGE,+ offset: 0,+ search: undefined,+ ordering: '-created_at',+ })+ })++ it('search resets to the first page and reloads with the search term', async () => {+ await mount()+ logic.actions.setPage(3)+ await expectLogic(logic).toFinishAllListeners()++ logic.actions.setSearchTerm('renewal')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.page).toBe(1)+ expect(mockList).toHaveBeenLastCalledWith(TEAM, 'acc-1', {+ limit: NOTES_PER_PAGE,+ offset: 0,+ search: 'renewal',+ ordering: '-created_at',+ })+ })++ it('sorting maps the column and direction onto the ordering param', async () => {+ await mount()++ logic.actions.setSorting({ columnKey: 'created_by', order: 1 })+ await expectLogic(logic).toFinishAllListeners()++ expect(mockList).toHaveBeenLastCalledWith(+ TEAM,+ 'acc-1',+ expect.objectContaining({ ordering: 'created_by', offset: 0 })+ )+ })++ it('createNote opens the new note in the side panel and reloads the list', async () => {+ await mount()+ mockCreate.mockResolvedValue({ short_id: 'note-1' } as AccountNotebookApi)+ mockList.mockResolvedValue(buildResponse([{ short_id: 'note-1' } as AccountNotebookApi], 1))++ logic.actions.createNote()+ await expectLogic(logic).toFinishAllListeners()++ expect(mockCreate).toHaveBeenCalledTimes(1)+ expect(notebookPanelLogic.values.selectedNotebook).toBe('note-1')+ expect(logic.values.notebooks).toEqual([{ short_id: 'note-1' }])+ })++ it('createNote resets to the first page so the new note is visible', async () => {+ await mount()+ logic.actions.setPage(2)+ await expectLogic(logic).toFinishAllListeners()+ mockCreate.mockResolvedValue({ short_id: 'note-1' } as AccountNotebookApi)++ logic.actions.createNote()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.page).toBe(1)+ expect(mockList).toHaveBeenLastCalledWith(TEAM, 'acc-1', expect.objectContaining({ offset: 0 }))+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.tsindex 7dc24da87f63..3a2c5c922078 100644--- a/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountNotebooksLogic.ts@@ -1,36 +1,68 @@-import { afterMount, connect, isBreakpoint, kea, key, path, props } from 'kea'+import { actions, afterMount, connect, isBreakpoint, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import posthog from 'posthog-js'+import { PaginationManual, Sorting } from '@posthog/lemon-ui'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { notebookPanelLogic } from 'scenes/notebooks/NotebookPanel/notebookPanelLogic'+import { defaultNotebookContent } from 'scenes/notebooks/utils'import { teamLogic } from 'scenes/teamLogic'-import { accountsNotebooksList } from 'products/customer_analytics/frontend/generated/api'-import type { AccountNotebookApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import { accountsNotebooksCreate, accountsNotebooksList } from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountNotebookApi,+ PaginatedAccountNotebookListApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'import type { accountNotebooksLogicType } from './accountNotebooksLogicType'+import { AccountsEvents } from './constants'++export const NOTES_PER_PAGE = 5++export const DEFAULT_NOTES_SORTING: Sorting = { columnKey: 'created_at', order: -1 }export interface AccountNotebooksLogicProps {accountId: string}+// Maps the table's sorting state onto the backend's whitelisted `ordering` param.+function sortingToOrdering(sorting: Sorting | null): string | undefined {+ if (!sorting) {+ return undefined+ }+ return sorting.order === -1 ? `-${sorting.columnKey}` : sorting.columnKey+}+export const accountNotebooksLogic = kea<accountNotebooksLogicType>([path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountNotebooksLogic', key]),props({} as AccountNotebooksLogicProps),key((props) => props.accountId),connect(() => ({values: [teamLogic, ['currentTeamId']],+ actions: [notebookPanelLogic, ['selectNotebook']],})),+ actions({+ setSearchTerm: (searchTerm: string) => ({ searchTerm }),+ setSorting: (sorting: Sorting | null) => ({ sorting }),+ setPage: (page: number) => ({ page }),+ createNote: true,+ }),loaders(({ props, values }) => ({- notebooks: [- null as AccountNotebookApi[] | null,+ notebooksResponse: [+ null as PaginatedAccountNotebookListApi | null,{loadNotebooks: async (_ = null, breakpoint) => {const projectId = String(values.currentTeamId)try {- const response = await accountsNotebooksList(projectId, props.accountId)+ const response = await accountsNotebooksList(projectId, props.accountId, {+ limit: NOTES_PER_PAGE,+ offset: (values.page - 1) * NOTES_PER_PAGE,+ search: values.searchTerm.trim() || undefined,+ ordering: sortingToOrdering(values.sorting),+ })breakpoint()- return response.results+ return response} catch (error) {if (!isBreakpoint(error as Error)) {posthog.captureException(error as Error, {@@ -43,6 +75,74 @@ export const accountNotebooksLogic = kea<accountNotebooksLogicType>([},},],+ createdNote: [+ null as AccountNotebookApi | null,+ {+ createNote: async () => {+ const projectId = String(values.currentTeamId)+ try {+ return await accountsNotebooksCreate(projectId, props.accountId, {+ content: defaultNotebookContent(),+ })+ } catch (error) {+ posthog.captureException(error as Error, {+ scope: 'accountNotebooksLogic.createNote',+ })+ lemonToast.error('Failed to create note')+ throw error+ }+ },+ },+ ],+ })),+ reducers({+ searchTerm: ['', { setSearchTerm: (_, { searchTerm }) => searchTerm }],+ sorting: [DEFAULT_NOTES_SORTING as Sorting | null, { setSorting: (_, { sorting }) => sorting }],+ page: [1, { setPage: (_, { page }) => page }],+ }),+ selectors(({ actions }) => ({+ notebooks: [(s) => [s.notebooksResponse], (response): AccountNotebookApi[] | null => response?.results ?? null],+ notebooksCount: [(s) => [s.notebooksResponse], (response): number => response?.count ?? 0],+ pagination: [+ (s) => [s.page, s.notebooksCount],+ (page, count): PaginationManual => ({+ controlled: true,+ pageSize: NOTES_PER_PAGE,+ currentPage: page,+ entryCount: count,+ onBackward: () => actions.setPage(page - 1),+ onForward: () => actions.setPage(page + 1),+ }),+ ],+ })),+ listeners(({ actions, values }) => ({+ setSearchTerm: async (_, breakpoint) => {+ await breakpoint(300)+ posthog.capture(AccountsEvents.NotesSearched, {+ has_query: values.searchTerm.trim().length > 0,+ query_length: values.searchTerm.trim().length,+ })+ actions.setPage(1)+ },+ setSorting: ({ sorting }) => {+ posthog.capture(AccountsEvents.NotesSorted, {+ column: sorting?.columnKey ?? null,+ direction: sorting ? (sorting.order === -1 ? 'desc' : 'asc') : 'cleared',+ })+ actions.setPage(1)+ },+ setPage: () => {+ actions.loadNotebooks()+ },+ createNoteSuccess: ({ createdNote }) => {+ if (!createdNote) {+ return+ }+ posthog.capture(AccountsEvents.NoteCreated, { notebook_short_id: createdNote.short_id })+ actions.selectNotebook(createdNote.short_id, { autofocus: 'end' })+ // A new note sorts to page 1 (default -created_at); reset there so it's visible in the table.+ actions.setPage(1)+ },})),afterMount(({ actions }) => {actions.loadNotebooks()diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex a770d47fdde6..eb722f9bc7b9 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -39,6 +39,9 @@ export const AccountsEvents = {RoleAssigned: 'customer analytics account role assigned',LinkClicked: 'customer analytics account link clicked',NoteClicked: 'customer analytics account note clicked',+ NoteCreated: 'customer analytics accounts note created',+ NotesSearched: 'customer analytics accounts notes searched',+ NotesSorted: 'customer analytics accounts notes sorted',TabViewed: 'customer analytics account tab viewed',RelatedUserClicked: 'customer analytics account related user clicked',} as constdiff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 61a9280e2d5f..89f749f8ece4 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -617,6 +617,14 @@ export type AccountsNotebooksListParams = {* The initial index from which to return the results.*/offset?: number+ /**+ * Sort by creation date or author. Defaults to '-created_at'.+ */+ ordering?: string+ /**+ * Full-text search across notebook title and content.+ */+ search?: string}export type CustomPropertyDefinitionsListParams = {diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.pyindex fad32b87607d..d6ae34afcf33 100644--- a/products/notebooks/backend/facade/api.py+++ b/products/notebooks/backend/facade/api.py@@ -226,8 +226,13 @@ def _to_account_notebook(notebook: Notebook) -> contracts.AccountNotebook:)-def list_account_notebooks(account_id: str | UUID) -> list[contracts.AccountNotebook]:- return [_to_account_notebook(notebook) for notebook in logic.list_account_notebooks(account_id)]+def list_account_notebooks(+ account_id: str | UUID, *, search: str | None = None, order: str | None = None+) -> list[contracts.AccountNotebook]:+ return [+ _to_account_notebook(notebook)+ for notebook in logic.list_account_notebooks(account_id, search=search, order=order)+ ]def get_account_notebook(account_id: str | UUID, short_id: str) -> contracts.AccountNotebook | None:diff --git a/products/notebooks/backend/logic.py b/products/notebooks/backend/logic.pyindex 27feab0f0926..7d4791ddf399 100644--- a/products/notebooks/backend/logic.py+++ b/products/notebooks/backend/logic.py@@ -10,7 +10,7 @@ from typing import Anyfrom uuid import UUIDfrom django.db import transaction-from django.db.models import F+from django.db.models import F, Qfrom django.utils import timezonefrom asgiref.sync import sync_to_async@@ -205,8 +205,26 @@ def _account_notebook_queryset(account_id: str | UUID) -> Any:).select_related("created_by", "last_modified_by")-def list_account_notebooks(account_id: str | UUID) -> list[Notebook]:- return list(_account_notebook_queryset(account_id).order_by("-last_modified_at"))+# Author sorting fans out to the user's name columns so the order matches what the UI shows.+_ACCOUNT_NOTEBOOK_ORDERING: dict[str, tuple[str, ...]] = {+ "created_at": ("created_at",),+ "-created_at": ("-created_at",),+ "created_by": ("created_by__first_name", "created_by__last_name"),+ "-created_by": ("-created_by__first_name", "-created_by__last_name"),+}+_DEFAULT_ACCOUNT_NOTEBOOK_ORDERING = ("-created_at",)+++def list_account_notebooks(+ account_id: str | UUID, *, search: str | None = None, order: str | None = None+) -> list[Notebook]:+ queryset = _account_notebook_queryset(account_id)+ if search:+ # Mirror the main notebooks list: full-text over title and content (some notebooks+ # have no text_content until their next save, so title is matched too).+ queryset = queryset.filter(Q(title__search=search) | Q(text_content__search=search))+ ordering = _ACCOUNT_NOTEBOOK_ORDERING.get(order or "", _DEFAULT_ACCOUNT_NOTEBOOK_ORDERING)+ return list(queryset.order_by(*ordering))def get_account_notebook(account_id: str | UUID, short_id: str) -> Notebook | None:diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c15d03157758..43391e547690 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -52389,6 +52389,14 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Sort by creation date or author. Defaults to '-created_at'.+ */+ ordering?: string;+ /**+ * Full-text search across notebook title and content.+ */+ search?: string;};export type EnvironmentsAlertsListParams = {@@ -57182,6 +57190,14 @@ export namespace Schemas {* The initial index from which to return the results.*/offset?: number;+ /**+ * Sort by creation date or author. Defaults to '-created_at'.+ */+ ordering?: string;+ /**+ * Full-text search across notebook title and content.+ */+ search?: string;};export type ActionsListParams = {diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex faae57f321b3..a6b0e5ec0d93 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -115,6 +115,8 @@ export const AccountsNotebooksListParams = /* @__PURE__ */ zod.object({export const AccountsNotebooksListQueryParams = /* @__PURE__ */ zod.object({limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),+ ordering: zod.string().optional().describe("Sort by creation date or author. Defaults to '-created_at'."),+ search: zod.string().optional().describe('Full-text search across notebook title and content.'),})export const AccountsNotebooksCreateParams = /* @__PURE__ */ zod.object({diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.tsindex 8306ed3f42c8..4c5439e1468f 100644--- a/services/mcp/src/tools/generated/customer_analytics.ts+++ b/services/mcp/src/tools/generated/customer_analytics.ts@@ -170,6 +170,8 @@ const accountsNotebooksList = (): ToolBase<query: {limit: params.limit,offset: params.offset,+ ordering: params.ordering,+ search: params.search,},})return await withPostHogUrl(context, result, '/customer-analytics')