: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): share views and configure tabs (#107161)
Arthur Moreira de Deus66192b80433d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6346779415cb..f1ac29027531 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8475,25 +8475,25 @@ snapshots:scenes-app-businessknowledge-knowledgesourcenamecell--user-text--light:hash: v1.k794b7964.fba04716b8f344e21fa3bb2ec69e627bd9836ff2161986538ac2b562973b0edc.Xl-YJ8Poqz1nofU4nIyAfnM4GbZZ1YYtbM37mIzZ4w4scenes-app-customer-analytics-account-detail--default--dark:- hash: v1.k794b7964.b722c6c92866329d952050c1b454d323b3cc753cf2da0966309dedc9ce1277ae.t2xO0wIJkkKdoiJrSN79BB9HEDAk_ibLhBDWI6lammU+ hash: v1.k794b7964.f55cbc927d83349e6016946865d60af9ebfbe3724597caf9bf682c4d885b5f55.pZQ15hvOXcX-PPQg5opIFACfL02olPu3GdjWWADiyIoscenes-app-customer-analytics-account-detail--default--light:- hash: v1.k794b7964.d4a4366994ca6bc7a66a61717a30d03be4d912efa40ed71031a100c38d99fc91.90Kqh9qtggxPpuTU6hTnVnIOxQfm8xJvVPx5glfp6xk+ hash: v1.k794b7964.17f23e44d4be6419b743063d4acb33c56cc2db90bda270441bf6846b8fa5c9dd.rDWoID_DTSWG3KvlD1692sNZ2TfFlVv-locqE4UG6yIscenes-app-customer-analytics-account-detail--external-id--dark:- hash: v1.k794b7964.f8ae0455e63cce9ec11e141a98d495fc721386d77ff809ba170c83eef841a528.B4RO1BEXmx8eB3Jpkdm_TccVpfGovN-lvZBa8OxxTY4+ hash: v1.k794b7964.7a97ff01865aa33e2e515dbcfa3271c4d09b30e178c2068cfd6c50b354dc0c88.M4v9oXKbuYzcCJpEjJxSBlFvxNVJ_ML54IzW5y0drwAscenes-app-customer-analytics-account-detail--external-id--light:- hash: v1.k794b7964.09a01fcd9830239f684e589179ecd6fe4265196d60554307df84dbe86d6f2f1d.bFV4kcj3vJfQqSVmMbAVLXyw5xV4PzafDhtpKO1tHUo+ hash: v1.k794b7964.0dd4405e4b4afc137065998960479aead50b51dd699d78fcd5ee69a7f0c341ef.6ZpL-2UskmHTXtHbB2Fym3H1GBqkpNILhX5aN5_VdKYscenes-app-customer-analytics-account-detail--narrow--dark:- hash: v1.k794b7964.168b51fc7bb530e2f0cf319c2f40bec95c13ce0ef5b7a1e64d9e161e178ad541.N2Hoo63uX3J2ppmOTs_ZAzcX_JaKpu8646UHPvMsaa8+ hash: v1.k794b7964.3afacd443ad5e52ea3928f246ec369cef0e96e9fdcaa8df42bea2f28c9ed68ea.m1gsgodQb5ZRVNX8upsuVpOsgoL7_gpJB2bScwvBXC0scenes-app-customer-analytics-account-detail--narrow--light:- hash: v1.k794b7964.d268860af68579ee5a269b8b20f22d1643a6791bf677851ae760569635b22d27.6D3Xn7IFqBI9s8rz5SeHqMQNJieJm07ToJRX8yvpa64+ hash: v1.k794b7964.2e433c51ae4e4964ff5ef866c16c329e1c8efdc7309c8e52b3c6356b5f5284fd.ygUYz_umKVeGeUQxWKccERjADuln7EmWLMwWSrPtjscscenes-app-customer-analytics-account-detail--pinned-properties--dark:- hash: v1.k794b7964.e8c6dfd9b14aaebdef6509e0b1c9cb79104edcb601540b3281389f970994a42f.ZCIo29eW7hUVoJSQM5domMOzZJxQ7xTLHbyglkVTwZQ+ hash: v1.k794b7964.54ea48d6975378be56d4e7173249f474dd8918e21edb8403c01faec6291283a4.b9-0ww9qPZpRSI6Y5zO39ZoQOJrsTL_4eJzmamPOvbsscenes-app-customer-analytics-account-detail--pinned-properties--light:- hash: v1.k794b7964.26baa4906be5a0a6e80ee162f3caada163d5606ed6fbd0d322c1b63495f208e9.1vU97twfzIg__VzQeKQxh1b7Qmks9-7ugaL8Zf2bXJY+ hash: v1.k794b7964.3c50d69127e61293fd954705cdffafcd34f29d5351b326eecfd02a3c3342fbef.eGAb5f9f9CvdrdRduMhUbmOTmdXvhA0LxPvWbrKgT-Ascenes-app-customer-analytics-account-detail--pinned-properties-narrow--dark:- hash: v1.k794b7964.de33855f1c17a82c55e0faec33846783e220077115f4b517f8d020ae9a3db08c.dw3swEPrHa8inmBHh5AfcyVobSGqctlmpctsHlqkWpg+ hash: v1.k794b7964.cd775573d45974bb438db1d97582091af93786bab2119fc3ba1fb6d1704563f5.xR1-jf_tn9a1PLQRZrEhuIlKXVmVu5LWmNc_8umPF-kscenes-app-customer-analytics-account-detail--pinned-properties-narrow--light:- hash: v1.k794b7964.c6566c518481be0dc38e0199184d0dfc5704e1b630f08a490bc7c97a7af1d2c7.VLxVjB9T-b8DvQRA28t9c1C1douss-KH4MnkbuuhqaQ+ hash: v1.k794b7964.04da5af95a08a1b9ff1dcd34e0411556930d1f337012afacbcba0ded5b05b8a6.4IPSYRPZJx4fgSouqwBJ68lzocov_SugJCTZt2ot4-sscenes-app-customer-analytics-account-detail-property-sidebar--custom-property-editors--dark:hash: v1.k794b7964.caefec23d66985f72f6eb40a23370ec4bf1701b9b6cfccd2a4b2b09cc9c1606f.lJ1UWZ6LkZI-k4XJw5UtuIJx1m5tWlMyvgoPlQH2L-gscenes-app-customer-analytics-account-detail-property-sidebar--custom-property-editors--light:diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex a2d975a8b71c..250c714dc0d1 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -100,6 +100,7 @@ from products.customer_analytics.backend.facade.email_matching import schedule_efrom products.customer_analytics.backend.facade.enums import (AccountPropertyPinKind,AccountRelationshipSource,+ AccountViewVisibility,TaskDigestCadence,)from products.customer_analytics.backend.logic import (@@ -1220,13 +1221,21 @@ def delete_customer_profile_config(InvalidAccountViewContent = _account_views_logic.InvalidAccountViewContentAccountViewVersionConflict = _account_views_logic.AccountViewVersionConflict+AccountViewPermissionDenied = _account_views_logic.AccountViewPermissionDenied-def _to_account_view(view: AccountViewModel) -> contracts.AccountView:+def _to_account_view(+ view: AccountViewModel,+ *,+ actor_user_id: int,+ can_edit_team_views: bool,+ is_project_admin: bool,+) -> contracts.AccountView:+ is_creator = view.created_by_id == actor_user_idreturn contracts.AccountView(id=view.id,name=view.name,- visibility=cast(Literal["private"], view.visibility),+ visibility=cast(Literal["private", "team"], view.visibility),content=view.content,text_content=view.text_content,version=view.version,@@ -1234,24 +1243,53 @@ def _to_account_view(view: AccountViewModel) -> contracts.AccountView:last_modified_by=view.last_modified_by_id,created_at=view.created_at,updated_at=view.updated_at,+ can_edit=(view.visibility == AccountViewVisibility.PRIVATE and is_creator)+ or (view.visibility == AccountViewVisibility.TEAM and can_edit_team_views),+ can_delete=is_creator or is_project_admin,+ can_change_visibility=is_creator or is_project_admin,)-def list_account_views(*, team_id: int, user_id: int) -> list[contracts.AccountView]:+def list_account_views(+ *, team_id: int, user_id: int, can_edit_team_views: bool, is_project_admin: bool+) -> list[contracts.AccountView]:return [- _to_account_view(view) for view in _account_views_logic.list_account_views(team_id=team_id, user_id=user_id)+ _to_account_view(+ view,+ actor_user_id=user_id,+ can_edit_team_views=can_edit_team_views,+ is_project_admin=is_project_admin,+ )+ for view in _account_views_logic.list_account_views(team_id=team_id, user_id=user_id)]-def get_account_view(*, team_id: int, user_id: int, view_id: UUID) -> contracts.AccountView | None:+def get_account_view(+ *,+ team_id: int,+ user_id: int,+ view_id: UUID,+ can_edit_team_views: bool,+ is_project_admin: bool,+) -> contracts.AccountView | None:view = _account_views_logic.get_account_view(team_id=team_id, user_id=user_id, view_id=view_id)- return _to_account_view(view) if view is not None else None+ return (+ _to_account_view(+ view,+ actor_user_id=user_id,+ can_edit_team_views=can_edit_team_views,+ is_project_admin=is_project_admin,+ )+ if view is not None+ else None+ )-def create_account_view(*, team_id: int, user_id: int, name: str, content: dict[str, Any]) -> contracts.AccountView:- return _to_account_view(- _account_views_logic.create_account_view(team_id=team_id, user_id=user_id, name=name, content=content)- )+def create_account_view(+ *, team_id: int, user_id: int, name: str, content: dict[str, Any], is_project_admin: bool+) -> contracts.AccountView:+ view = _account_views_logic.create_account_view(team_id=team_id, user_id=user_id, name=name, content=content)+ return _to_account_view(view, actor_user_id=user_id, can_edit_team_views=True, is_project_admin=is_project_admin)def update_account_view(@@ -1260,26 +1298,44 @@ def update_account_view(user_id: int,view_id: UUID,expected_version: int,+ can_edit_team_views: bool,+ is_project_admin: bool,name: str | None = None,content: dict[str, Any] | None = None,+ visibility: str | None = None,) -> contracts.AccountView | None:view = _account_views_logic.update_account_view(team_id=team_id,user_id=user_id,view_id=view_id,expected_version=expected_version,+ can_edit_team_views=can_edit_team_views,+ is_project_admin=is_project_admin,name=name,content=content,+ visibility=visibility,+ )+ return (+ _to_account_view(+ view,+ actor_user_id=user_id,+ can_edit_team_views=can_edit_team_views,+ is_project_admin=is_project_admin,+ )+ if view is not None+ else None)- return _to_account_view(view) if view is not None else None-def delete_account_view(*, team_id: int, user_id: int, view_id: UUID, expected_version: int) -> bool:+def delete_account_view(+ *, team_id: int, user_id: int, view_id: UUID, expected_version: int, is_project_admin: bool+) -> bool:return _account_views_logic.delete_account_view(team_id=team_id,user_id=user_id,view_id=view_id,expected_version=expected_version,+ is_project_admin=is_project_admin,)@@ -1302,6 +1358,7 @@ def _to_user_customer_analytics_config(for reference in raw_references],task_digest=_user_customer_analytics_config_logic.read_task_digest(config),+ account_detail_tabs=_user_customer_analytics_config_logic.read_account_detail_tabs(config),)@@ -1321,6 +1378,24 @@ def update_user_customer_analytics_config(return _to_user_customer_analytics_config(config)+def update_user_account_detail_tabs(+ *,+ team_id: int,+ user_id: int,+ ordered_tab_ids: list[str],+ hidden_tab_ids: list[str],+ default_tab_id: str | None,+) -> contracts.UserCustomerAnalyticsConfig:+ config = _user_customer_analytics_config_logic.update_account_detail_tabs(+ team_id=team_id,+ user_id=user_id,+ ordered_tab_ids=ordered_tab_ids,+ hidden_tab_ids=hidden_tab_ids,+ default_tab_id=default_tab_id,+ )+ return _to_user_customer_analytics_config(config)++def update_user_task_digest_preferences(*,team_id: int,diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex f86bce0b5955..0a0d782c393d 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -80,10 +80,18 @@ class TaskDigestPreferences:cadence: Literal["weekdays", "every_day"] = "weekdays"+@dataclass(frozen=True)+class AccountDetailTabsConfig:+ ordered_tab_ids: list[str] = field(default_factory=list)+ hidden_tab_ids: list[str] = field(default_factory=list)+ default_tab_id: str | None = None++@dataclass(frozen=True)class UserCustomerAnalyticsConfig:pinned_properties: list[PinnedAccountProperty] = field(default_factory=list)task_digest: TaskDigestPreferences = field(default_factory=TaskDigestPreferences)+ account_detail_tabs: AccountDetailTabsConfig = field(default_factory=AccountDetailTabsConfig)RelationshipSourceValue = Literal["human", "workflow", "ai", "salesforce_claim", "migration"]@@ -811,7 +819,7 @@ class AccountDetails:class AccountView:id: UUIDname: str- visibility: Literal["private"]+ visibility: Literal["private", "team"]content: dict[str, Any]text_content: strversion: int@@ -819,6 +827,9 @@ class AccountView:last_modified_by: int | Nonecreated_at: datetimeupdated_at: datetime+ can_edit: bool+ can_delete: bool+ can_change_visibility: bool@stdlib_dataclass(frozen=True)diff --git a/products/customer_analytics/backend/logic/account_views.py b/products/customer_analytics/backend/logic/account_views.pyindex d12ede347a72..7ccb3f2891fa 100644--- a/products/customer_analytics/backend/logic/account_views.py+++ b/products/customer_analytics/backend/logic/account_views.py@@ -4,6 +4,7 @@ from typing import Anyfrom uuid import UUIDfrom django.db import transaction+from django.db.models import Q, QuerySetfrom django.utils import timezonefrom products.customer_analytics.backend.facade.enums import AccountViewVisibility@@ -22,7 +23,6 @@ ACCOUNT_VIEW_COMPONENT_LABELS = {"Opportunities": "Opportunities","Conversations": "Conversations","Meetings": "Meetings",- "EventStream": "Event stream",}ACCOUNT_VIEW_ALLOWED_PROPS = {"config", "nodeId", "title"}ACCOUNT_VIEW_COMPONENT_TITLE_MAX_LENGTH = 400@@ -50,6 +50,10 @@ class AccountViewVersionConflict(Exception):pass+class AccountViewPermissionDenied(Exception):+ pass++def get_account_identity_props(value: object) -> set[str]:if isinstance(value, dict):return ACCOUNT_VIEW_IDENTITY_PROPS.intersection(value) | set().union(@@ -60,25 +64,17 @@ def get_account_identity_props(value: object) -> set[str]:return set()-def list_account_views(*, team_id: int, user_id: int) -> list[AccountView]:- return list(+def list_account_views(*, team_id: int, user_id: int) -> QuerySet[AccountView]:+ return (AccountView.objects.for_team(team_id)- .filter(created_by_id=user_id, deleted_at__isnull=True, visibility=AccountViewVisibility.PRIVATE)+ .filter(deleted_at__isnull=True)+ .filter(Q(created_by_id=user_id) | Q(visibility=AccountViewVisibility.TEAM)).order_by("name", "created_at"))def get_account_view(*, team_id: int, user_id: int, view_id: UUID) -> AccountView | None:- return (- AccountView.objects.for_team(team_id)- .filter(- id=view_id,- created_by_id=user_id,- deleted_at__isnull=True,- visibility=AccountViewVisibility.PRIVATE,- )- .first()- )+ return list_account_views(team_id=team_id, user_id=user_id).filter(id=view_id).first()def validate_account_view_content(content: dict[str, Any]) -> tuple[dict[str, Any], str]:@@ -160,25 +156,39 @@ def update_account_view(user_id: int,view_id: UUID,expected_version: int,+ can_edit_team_views: bool,+ is_project_admin: bool,name: str | None = None,content: dict[str, Any] | None = None,+ visibility: str | None = None,) -> AccountView | None:view = (AccountView.objects.for_team(team_id).select_for_update()- .filter(- id=view_id,- created_by_id=user_id,- deleted_at__isnull=True,- visibility=AccountViewVisibility.PRIVATE,- )+ .filter(id=view_id, deleted_at__isnull=True)+ .filter(Q(created_by_id=user_id) | Q(visibility=AccountViewVisibility.TEAM)).first())if view is None:return Noneif view.version != expected_version:raise AccountViewVersionConflict("This view changed since you opened it.")- if name is None and content is None:+ if view.visibility == AccountViewVisibility.PRIVATE and view.created_by_id != user_id:+ raise AccountViewPermissionDenied("Only the creator can edit this personal view.")+ if (+ view.visibility == AccountViewVisibility.TEAM+ and (name is not None or content is not None)+ and not can_edit_team_views+ ):+ raise AccountViewPermissionDenied("You need editor access to change this team view.")+ if (+ visibility is not None+ and visibility != view.visibility+ and view.created_by_id != user_id+ and not is_project_admin+ ):+ raise AccountViewPermissionDenied("Only the creator or a project admin can change visibility.")+ if name is None and content is None and (visibility is None or visibility == view.visibility):return viewupdate_fields = ["last_modified_by", "version", "updated_at"]@@ -188,6 +198,12 @@ def update_account_view(if content is not None:view.content, view.text_content = validate_account_view_content(content)update_fields.extend(["content", "text_content"])+ if visibility is not None and visibility != view.visibility:+ view.visibility = AccountViewVisibility(visibility)+ update_fields.append("visibility")+ if view.visibility == AccountViewVisibility.PRIVATE and view.created_by_id != user_id:+ view.created_by_id = user_id+ update_fields.append("created_by")view.last_modified_by_id = user_idview.version += 1@@ -196,22 +212,22 @@ def update_account_view(@transaction.atomic-def delete_account_view(*, team_id: int, user_id: int, view_id: UUID, expected_version: int) -> bool:+def delete_account_view(+ *, team_id: int, user_id: int, view_id: UUID, expected_version: int, is_project_admin: bool+) -> bool:view = (AccountView.objects.for_team(team_id).select_for_update()- .filter(- id=view_id,- created_by_id=user_id,- deleted_at__isnull=True,- visibility=AccountViewVisibility.PRIVATE,- )+ .filter(id=view_id, deleted_at__isnull=True)+ .filter(Q(created_by_id=user_id) | Q(visibility=AccountViewVisibility.TEAM)).first())if view is None:return Falseif view.version != expected_version:raise AccountViewVersionConflict("This view changed since you opened it.")+ if view.created_by_id != user_id and not is_project_admin:+ raise AccountViewPermissionDenied("Only the creator or a project admin can delete this view.")view.deleted_at = timezone.now()view.last_modified_by_id = user_iddiff --git a/products/customer_analytics/backend/logic/user_customer_analytics_config.py b/products/customer_analytics/backend/logic/user_customer_analytics_config.pyindex 9db3a6d4a52e..b1531563a1d3 100644--- a/products/customer_analytics/backend/logic/user_customer_analytics_config.py+++ b/products/customer_analytics/backend/logic/user_customer_analytics_config.py@@ -17,6 +17,21 @@ PINNED_PROPERTIES_OVERRIDE_KEY = "pinned_properties_override"TASK_DIGEST_KEY = "task_digest"DEFAULT_TASK_DIGEST = contracts.TaskDigestPreferences()+ACCOUNT_DETAIL_TABS_KEY = "account_detail_tabs"+ACCOUNT_DETAIL_SYSTEM_TAB_IDS = {+ "system:notes",+ "system:tasks",+ "system:users",+ "system:relationships",+ "system:feature_requests",+ "system:usage",+ "system:spend",+ "system:opportunities",+ "system:conversations",+ "system:meetings",+}+MAX_ACCOUNT_DETAIL_TAB_IDS = 100+@transaction.atomicdef get_or_create_config(*, team_id: int, user_id: int) -> UserCustomerAnalyticsConfig:@@ -124,6 +139,84 @@ def update_task_digest(return config+def read_account_detail_tabs(config: UserCustomerAnalyticsConfig) -> contracts.AccountDetailTabsConfig:+ stored = config.properties.get(ACCOUNT_DETAIL_TABS_KEY)+ if not isinstance(stored, dict):+ return contracts.AccountDetailTabsConfig()++ ordered_tab_ids = _read_tab_ids(stored.get("ordered_tab_ids"))+ hidden_tab_ids = _read_tab_ids(stored.get("hidden_tab_ids"))+ default_tab_id = stored.get("default_tab_id")+ return contracts.AccountDetailTabsConfig(+ ordered_tab_ids=ordered_tab_ids,+ hidden_tab_ids=hidden_tab_ids,+ default_tab_id=default_tab_id if isinstance(default_tab_id, str) and _is_tab_id(default_tab_id) else None,+ )+++def update_account_detail_tabs(+ *,+ team_id: int,+ user_id: int,+ ordered_tab_ids: list[str],+ hidden_tab_ids: list[str],+ default_tab_id: str | None,+) -> UserCustomerAnalyticsConfig:+ errors: list[str] = []+ _validate_tab_ids("ordered_tab_ids", ordered_tab_ids, errors)+ _validate_tab_ids("hidden_tab_ids", hidden_tab_ids, errors)+ if default_tab_id is not None and not _is_tab_id(default_tab_id):+ errors.append("default_tab_id must use a system: or view: identifier.")+ if errors:+ raise ValueError("; ".join(errors))++ config = get_or_create_config(team_id=team_id, user_id=user_id)+ config.properties = {+ **config.properties,+ ACCOUNT_DETAIL_TABS_KEY: {+ "ordered_tab_ids": ordered_tab_ids,+ "hidden_tab_ids": hidden_tab_ids,+ "default_tab_id": default_tab_id,+ },+ }+ config.save(update_fields=["properties", "updated_at"])+ return config+++def _is_tab_id(tab_id: str) -> bool:+ if tab_id in ACCOUNT_DETAIL_SYSTEM_TAB_IDS:+ return True+ if not tab_id.startswith("view:"):+ return False+ try:+ UUID(tab_id.removeprefix("view:"))+ except ValueError:+ return False+ return True+++def _read_tab_ids(value: Any) -> list[str]:+ if not isinstance(value, list):+ return []+ tab_ids: list[str] = []+ for tab_id in value:+ if isinstance(tab_id, str) and _is_tab_id(tab_id) and tab_id not in tab_ids:+ tab_ids.append(tab_id)+ if len(tab_ids) == MAX_ACCOUNT_DETAIL_TAB_IDS:+ break+ return tab_ids+++def _validate_tab_ids(field: str, tab_ids: list[str], errors: list[str]) -> None:+ if len(tab_ids) > MAX_ACCOUNT_DETAIL_TAB_IDS:+ errors.append(f"{field} can contain at most {MAX_ACCOUNT_DETAIL_TAB_IDS} items.")+ if len(set(tab_ids)) != len(tab_ids):+ errors.append(f"{field} cannot contain duplicates.")+ if any(not _is_tab_id(tab_id) for tab_id in tab_ids):+ errors.append(f"{field} contains an invalid tab identifier.")++def _read_send_time(stored: dict[str, Any]) -> str:value = stored.get("send_time")if isinstance(value, str):diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 789e56ff28bc..ba2df42c2355 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -990,7 +990,11 @@ class AccountViewContentSerializer(serializers.Serializer):class AccountViewSerializer(DataclassSerializer):id = serializers.UUIDField(read_only=True, help_text="Stable account view identifier.")name = serializers.CharField(read_only=True, help_text="Name shown in the account view.")- visibility = serializers.CharField(read_only=True, help_text="Account views created through this API are private.")+ visibility = serializers.ChoiceField(+ read_only=True,+ choices=AccountViewVisibility.choices,+ help_text="Whether the view is personal or available to the project.",+ )content = AccountViewContentSerializer(read_only=True, help_text="Validated Markdown notebook document.")text_content = serializers.CharField(read_only=True, help_text="Searchable component labels extracted from content."@@ -1004,6 +1008,12 @@ class AccountViewSerializer(DataclassSerializer):)created_at = serializers.DateTimeField(read_only=True, help_text="When the view was created.")updated_at = serializers.DateTimeField(read_only=True, help_text="When the view was last changed.")+ can_edit = serializers.BooleanField(read_only=True, help_text="Whether the requesting user can edit the view.")+ can_delete = serializers.BooleanField(read_only=True, help_text="Whether the requesting user can delete the view.")+ can_change_visibility = serializers.BooleanField(+ read_only=True,+ help_text="Whether the requesting user can change the view visibility.",+ )class Meta:dataclass = AccountView@@ -1019,6 +1029,9 @@ class AccountViewSerializer(DataclassSerializer):"last_modified_by","created_at","updated_at",+ "can_edit",+ "can_delete",+ "can_change_visibility",]@@ -1040,18 +1053,12 @@ class AccountViewUpdateSerializer(serializers.Serializer):help_text="Replacement account view components. Omit to keep current content.",)visibility = serializers.ChoiceField(- choices=[(AccountViewVisibility.PRIVATE, "Personal")],+ choices=AccountViewVisibility.choices,required=False,- write_only=True,- help_text="Views can only be private.",+ help_text="New visibility. Only the creator or a project admin can change it.",)version = serializers.IntegerField(min_value=1, help_text="Version returned by the last read.")- def validate_visibility(self, value: str) -> str:- if value != AccountViewVisibility.PRIVATE:- raise serializers.ValidationError("Views can only be private.")- return value-# The endpoint is a PATCH, so the schema generator marks every field optional. Every update needs# `version`, and the generated types and MCP tool must say so.@property@@ -2256,6 +2263,23 @@ class TaskDigestPreferencesUpdateSerializer(serializers.Serializer):)+class AccountDetailTabsConfigSerializer(serializers.Serializer):+ ordered_tab_ids = serializers.ListField(+ child=serializers.CharField(),+ allow_empty=True,+ help_text="Tab identifiers in the user's preferred order.",+ )+ hidden_tab_ids = serializers.ListField(+ child=serializers.CharField(),+ allow_empty=True,+ help_text="Tab identifiers hidden from the tab strip.",+ )+ default_tab_id = serializers.CharField(+ allow_null=True,+ help_text="Tab identifier opened by default. Null uses the first available system tab.",+ )++class UserCustomerAnalyticsConfigSerializer(serializers.Serializer):pinned_properties = PinnedAccountPropertySerializer(many=True,@@ -2266,6 +2290,10 @@ class UserCustomerAnalyticsConfigSerializer(serializers.Serializer):read_only=True,help_text="Task digest email preferences. Disabled until the user turns the digest on.",)+ account_detail_tabs = AccountDetailTabsConfigSerializer(+ read_only=True,+ help_text="Personal order, visibility, and default for account tabs.",+ )class UserCustomerAnalyticsConfigUpdateSerializer(serializers.Serializer):@@ -2279,6 +2307,10 @@ class UserCustomerAnalyticsConfigUpdateSerializer(serializers.Serializer):required=False,help_text="Task digest email preferences to change. Omit the object to keep them all; omit a field inside it to keep that one.",)+ account_detail_tabs = AccountDetailTabsConfigSerializer(+ required=False,+ help_text="Complete personal account tab configuration. Omit to keep it unchanged.",+ )class AccountRelationshipDefinitionSerializer(DataclassSerializer):diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 797f10f7adb0..5ff2f3ea57c6 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -16,7 +16,7 @@ import jsonimport builtinsfrom dataclasses import asdictfrom functools import cached_property-from typing import Any, cast+from typing import Any, Protocol, castfrom uuid import UUIDfrom django.core.exceptions import ValidationError as DjangoValidationError@@ -30,7 +30,7 @@ from rest_framework import mixins, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import PermissionDenied, ValidationErrorfrom rest_framework.pagination import LimitOffsetPagination-from rest_framework.permissions import BasePermission+from rest_framework.permissions import BasePermission, IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.throttling import UserRateThrottle@@ -47,6 +47,8 @@ from posthog.models import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import (+ AccessControlPermission,+ APIScopePermission,PostHogFeatureFlagPermission,TeamMemberAccessPermission,TeamMemberLightManagementPermission,@@ -56,8 +58,13 @@ from posthog.permissions import (is_service_auth,)from posthog.rate_limit import RunSavedQueryRateThrottle+from posthog.user_permissions import UserPermissions-from products.access_control.backend.facade.user_access_control import UserAccessControl, model_to_resource+from products.access_control.backend.facade.user_access_control import (+ AccessControlLevel,+ UserAccessControl,+ model_to_resource,+)from products.access_control.backend.presentation.access_control import AccessControlViewSetMixinfrom products.customer_analytics.backend.facade import api, contractsfrom products.customer_analytics.backend.facade.constants import (@@ -872,18 +879,93 @@ class FeatureRequestViewSet(return Response(FeatureRequestStatusHistorySerializer(instance=history, many=True).data)+class CanonicalTeamViewSet(Protocol):+ @property+ def canonical_team(self) -> Team: ...++ @property+ def team_id(self) -> int: ...++ @property+ def user_permissions(self) -> UserPermissions: ...+++class CanonicalTeamAccessPermission(BasePermission):+ """Data under an environment URL belongs to its parent project, so access must hold on that project too."""++ message = "You don't have access to the project."++ def has_permission(self, request: Request, view: Any) -> bool:+ if not request.user.is_authenticated:+ return True+ canonical_view = cast(CanonicalTeamViewSet, view)+ canonical_team = canonical_view.canonical_team+ if canonical_team.id == canonical_view.team_id:+ return True+ scoped_team_ids = get_authenticator_scoped_team_ids(request.successful_authenticator)+ if scoped_team_ids and canonical_team.id not in scoped_team_ids:+ return False+ return canonical_view.user_permissions.team(canonical_team).effective_membership_level is not None+++class AccountViewChangePermission(AccessControlPermission):+ """The facade applies each view's own rules: account editors change team view contents, and the+ creator or a project admin changes visibility or deletes. An account editor floor here would+ block a project admin who only views accounts before those rules run."""++ def _get_required_access_level(self, request: Request, view: Any) -> AccessControlLevel:+ return "viewer"++class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):scope_object = "account"serializer_class = AccountViewSerializerlookup_value_regex = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"queryset = Nonepagination_class = None- permission_classes = [PostHogFeatureFlagPermission]+ permission_classes = [PostHogFeatureFlagPermission, CanonicalTeamAccessPermission]posthog_feature_flag = CUSTOMER_ANALYTICS_ACCOUNT_VIEWS_FLAG+ @cached_property+ def canonical_team(self) -> Team:+ return self.team.parent_team or self.team++ @cached_property+ def user_access_control(self) -> UserAccessControl:+ return UserAccessControl(+ user=cast(User, self.request.user),+ team=self.canonical_team,+ organization_id=self.organization_id,+ )++ def dangerously_get_permissions(self) -> list[BasePermission]:+ if self.action not in ("partial_update", "destroy"):+ raise NotImplementedError()+ return [+ IsAuthenticated(),+ APIScopePermission(),+ AccountViewChangePermission(),+ TeamMemberAccessPermission(),+ PostHogFeatureFlagPermission(),+ CanonicalTeamAccessPermission(),+ ]++ def _is_project_admin(self) -> bool:+ if self.user_access_control.is_organization_admin:+ return True+ return bool(self.user_access_control.check_access_level_for_object(self.canonical_team, "admin", explicit=True))++ def _can_edit_team_views(self) -> bool:+ return self.user_access_control.check_access_level_for_resource("account", "editor")+@extend_schema(responses={200: AccountViewSerializer(many=True)}, summary="List account views")def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:- views = api.list_account_views(team_id=self.team_id, user_id=cast(User, request.user).id)+ views = api.list_account_views(+ team_id=self.team_id,+ user_id=cast(User, request.user).id,+ can_edit_team_views=self._can_edit_team_views(),+ is_project_admin=self._is_project_admin(),+ )return Response(AccountViewSerializer(instance=views, many=True).data)@extend_schema(responses={200: AccountViewSerializer}, summary="Get an account view")@@ -892,6 +974,8 @@ class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixteam_id=self.team_id,user_id=cast(User, request.user).id,view_id=UUID(self.kwargs["pk"]),+ can_edit_team_views=self._can_edit_team_views(),+ is_project_admin=self._is_project_admin(),)if view is None:return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)@@ -900,7 +984,7 @@ class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix@validated_request(request_serializer=AccountViewCreateSerializer,responses={201: AccountViewSerializer, 400: OpenApiResponse(description="The content is invalid.")},- summary="Create a private account view",+ summary="Create a personal account view",)def create(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:try:@@ -909,6 +993,7 @@ class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixuser_id=cast(User, request.user).id,name=request.validated_data["name"],content=request.validated_data["content"],+ is_project_admin=self._is_project_admin(),)except api.InvalidAccountViewContent as error:raise ValidationError({"content": error.errors})@@ -919,6 +1004,7 @@ class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixresponses={200: AccountViewSerializer,400: OpenApiResponse(description="The request is invalid."),+ 403: OpenApiResponse(description="The view cannot be changed by this user."),404: OpenApiResponse(description="The view was not found."),409: OpenApiResponse(description="The view changed since the supplied version."),},@@ -931,13 +1017,18 @@ class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixuser_id=cast(User, request.user).id,view_id=UUID(self.kwargs["pk"]),expected_version=request.validated_data["version"],+ can_edit_team_views=self._can_edit_team_views(),+ is_project_admin=self._is_project_admin(),name=request.validated_data.get("name"),content=request.validated_data.get("content"),+ visibility=request.validated_data.get("visibility"),)except api.InvalidAccountViewContent as error:raise ValidationError({"content": error.errors})except api.AccountViewVersionConflict as error:raise Conflict(str(error))+ except api.AccountViewPermissionDenied as error:+ raise PermissionDenied(str(error))if view is None:return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)return Response(AccountViewSerializer(instance=view).data)@@ -952,7 +1043,7 @@ class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixdescription="Version returned by the last read.",)],- responses={204: None, 404: OpenApiResponse(), 409: OpenApiResponse()},+ responses={204: None, 403: OpenApiResponse(), 404: OpenApiResponse(), 409: OpenApiResponse()},summary="Delete an account view",)def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:@@ -964,30 +1055,17 @@ class AccountViewTemplateViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixuser_id=cast(User, request.user).id,view_id=UUID(self.kwargs["pk"]),expected_version=query.validated_data["version"],+ is_project_admin=self._is_project_admin(),)except api.AccountViewVersionConflict as error:raise Conflict(str(error))+ except api.AccountViewPermissionDenied as error:+ raise PermissionDenied(str(error))if not deleted:return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)return Response(status=status.HTTP_204_NO_CONTENT)-class UserConfigCanonicalTeamAccessPermission(BasePermission):- message = "You don't have access to the project."-- def has_permission(self, request: Request, view: Any) -> bool:- if not request.user.is_authenticated:- return True- config_view = cast(UserCustomerAnalyticsConfigViewSet, view)- canonical_team = config_view.canonical_team- if canonical_team.id == config_view.team_id:- return True- scoped_team_ids = get_authenticator_scoped_team_ids(request.successful_authenticator)- if scoped_team_ids and canonical_team.id not in scoped_team_ids:- return False- return config_view.user_permissions.team(canonical_team).effective_membership_level is not None--class UserCustomerAnalyticsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "account"scope_object_read_actions = ["retrieve"]@@ -995,7 +1073,7 @@ class UserCustomerAnalyticsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.Generiserializer_class = UserCustomerAnalyticsConfigSerializerqueryset = Nonelookup_value_regex = "@me"- permission_classes = [UserConfigCanonicalTeamAccessPermission]+ permission_classes = [CanonicalTeamAccessPermission]@cached_propertydef canonical_team(self) -> Team:@@ -1057,29 +1135,43 @@ class UserCustomerAnalyticsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.Generiuser_id = cast(User, request.user).idconfig: contracts.UserCustomerAnalyticsConfig | None = None- if "pinned_properties" in request.validated_data:- pinned_properties = [- contracts.PinnedAccountProperty(kind=reference["kind"], id=reference["id"])- for reference in request.validated_data["pinned_properties"]- ]- try:- config = api.update_user_customer_analytics_config(+ with transaction.atomic():+ if "pinned_properties" in request.validated_data:+ pinned_properties = [+ contracts.PinnedAccountProperty(kind=reference["kind"], id=reference["id"])+ for reference in request.validated_data["pinned_properties"]+ ]+ try:+ config = api.update_user_customer_analytics_config(+ team_id=self.team_id,+ user_id=user_id,+ pinned_properties=pinned_properties,+ )+ except api.InvalidPinnedAccountProperties as error:+ raise ValidationError({"pinned_properties": error.errors})++ if "task_digest" in request.validated_data:+ task_digest = request.validated_data["task_digest"]+ config = api.update_user_task_digest_preferences(team_id=self.team_id,user_id=user_id,- pinned_properties=pinned_properties,+ enabled=task_digest.get("enabled"),+ send_time=task_digest.get("send_time"),+ cadence=task_digest.get("cadence"),)- except api.InvalidPinnedAccountProperties as error:- raise ValidationError({"pinned_properties": error.errors})- if "task_digest" in request.validated_data:- task_digest = request.validated_data["task_digest"]- config = api.update_user_task_digest_preferences(- team_id=self.team_id,- user_id=user_id,- enabled=task_digest.get("enabled"),- send_time=task_digest.get("send_time"),- cadence=task_digest.get("cadence"),- )+ if "account_detail_tabs" in request.validated_data:+ account_detail_tabs = request.validated_data["account_detail_tabs"]+ try:+ config = api.update_user_account_detail_tabs(+ team_id=self.team_id,+ user_id=user_id,+ ordered_tab_ids=account_detail_tabs["ordered_tab_ids"],+ hidden_tab_ids=account_detail_tabs["hidden_tab_ids"],+ default_tab_id=account_detail_tabs["default_tab_id"],+ )+ except ValueError as error:+ raise ValidationError({"account_detail_tabs": str(error)})if config is None:return self.retrieve(request, *args, **kwargs)diff --git a/products/customer_analytics/backend/test/test_account_views.py b/products/customer_analytics/backend/test/test_account_views.pyindex 46e54f357561..41ab2bed7b2c 100644--- a/products/customer_analytics/backend/test/test_account_views.py+++ b/products/customer_analytics/backend/test/test_account_views.py@@ -4,11 +4,11 @@ from unittest.mock import patchfrom rest_framework import statusfrom posthog.constants import AvailableFeature-from posthog.models import OrganizationMembership, User+from posthog.models import OrganizationMembership, Team, Userfrom posthog.models.activity_logging.activity_log import ActivityLogfrom products.access_control.backend.models.access_control import AccessControl-from products.customer_analytics.backend.models import AccountView+from products.customer_analytics.backend.models import Account, AccountViewdef account_view_content(*components: str) -> dict:@@ -35,19 +35,36 @@ class TestAccountViews(APIBaseTest):self.organization.save()self.endpoint = f"/api/projects/{self.team.id}/account_views/"self.viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")- membership = OrganizationMembership.objects.get(user=self.viewer, organization=self.organization)+ self.editor = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ self.project_admin = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ project_admin_membership = OrganizationMembership.objects.get(+ user=self.project_admin, organization=self.organization+ )AccessControl.objects.create(team=self.team,- resource="account",- access_level="viewer",+ resource="project",+ resource_id=str(self.team.id),+ organization_member=project_admin_membership,+ access_level="admin",+ )+ self._set_access(self.viewer, "viewer")+ self._set_access(self.editor, "editor")+ self._set_access(self.project_admin, "viewer")++ def _set_access(self, user: User, access_level: str) -> None:+ membership = OrganizationMembership.objects.get(user=user, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource="customer_analytics",+ access_level=access_level,organization_member=membership,)- def _create(self) -> dict:+ def _create(self, name: str = "Account workspace") -> dict:response = self.client.post(self.endpoint,{- "name": "Account workspace",+ "name": name,"content": account_view_content('<Usage nodeId="usage-one" title="Product usage" />'),},format="json",@@ -56,7 +73,16 @@ class TestAccountViews(APIBaseTest):self.assertEqual(response.json()["visibility"], "private")return response.json()- def test_private_view_is_not_readable_or_editable_by_another_user(self) -> None:+ def _publish(self, view: dict) -> dict:+ response = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"visibility": "team", "version": view["version"]},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ return response.json()++ def test_private_view_is_not_visible_to_other_users(self) -> None:view = self._create()self.client.force_login(self.viewer)@@ -79,19 +105,158 @@ class TestAccountViews(APIBaseTest):status.HTTP_404_NOT_FOUND,)- def test_patch_rejects_team_visibility(self) -> None:- view = self._create()+ def test_team_view_is_visible_to_viewers_and_editable_by_editors(self) -> None:+ view = self._publish(self._create())- response = self.client.patch(+ self.client.force_login(self.viewer)+ listed = self.client.get(self.endpoint)+ self.assertEqual(listed.status_code, status.HTTP_200_OK, listed.json())+ self.assertEqual([item["id"] for item in listed.json()], [view["id"]])+ self.assertFalse(listed.json()[0]["can_edit"])+ self.assertFalse(listed.json()[0]["can_delete"])++ self.client.force_login(self.editor)+ updated = self.client.patch(f"{self.endpoint}{view['id']}/",- {"visibility": "team", "version": view["version"]},+ {"name": "Renewal workspace", "version": view["version"]},+ format="json",+ )+ self.assertEqual(updated.status_code, status.HTTP_200_OK, updated.json())+ self.assertEqual(updated.json()["name"], "Renewal workspace")+ self.assertTrue(updated.json()["can_edit"])+ self.assertFalse(updated.json()["can_delete"])++ def test_only_creator_or_project_admin_can_change_team_visibility_or_delete(self) -> None:+ view = self._publish(self._create())++ self.client.force_login(self.editor)+ denied_visibility = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"visibility": "private", "version": view["version"]},format="json",)+ self.assertEqual(denied_visibility.status_code, status.HTTP_403_FORBIDDEN, denied_visibility.json())+ denied_delete = self.client.delete(f"{self.endpoint}{view['id']}/?version={view['version']}")+ self.assertEqual(denied_delete.status_code, status.HTTP_403_FORBIDDEN, denied_delete.json())- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())- self.assertEqual(AccountView.objects.for_team(self.team.id).get(id=view["id"]).visibility, "private")+ self.client.force_login(self.user)+ deleted = self.client.delete(f"{self.endpoint}{view['id']}/?version={view['version']}")+ self.assertEqual(deleted.status_code, status.HTTP_204_NO_CONTENT)++ def test_project_admin_without_account_editor_can_only_change_team_view_visibility(self) -> None:+ view = self._publish(self._create())++ self.client.force_login(self.project_admin)+ listed = self.client.get(self.endpoint)+ self.assertEqual(listed.status_code, status.HTTP_200_OK, listed.json())+ self.assertFalse(listed.json()[0]["can_edit"])+ self.assertTrue(listed.json()[0]["can_change_visibility"])++ denied_name = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"name": "Blocked edit", "version": view["version"]},+ format="json",+ )+ self.assertEqual(denied_name.status_code, status.HTTP_403_FORBIDDEN, denied_name.json())+ denied_content = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {+ "content": account_view_content('<Usage nodeId="blocked-usage" title="Blocked content" />'),+ "version": view["version"],+ },+ format="json",+ )+ self.assertEqual(denied_content.status_code, status.HTTP_403_FORBIDDEN, denied_content.json())- def test_stale_update_does_not_overwrite_newer_content(self) -> None:+ made_private = self.client.patch(+ f"{self.endpoint}{view['id']}/",+ {"visibility": "private", "version": view["version"]},+ format="json",+ )+ self.assertEqual(made_private.status_code, status.HTTP_200_OK, made_private.json())+ self.assertEqual(made_private.json()["visibility"], "private")+ self.assertTrue(made_private.json()["can_delete"])++ deleted = self.client.delete(f"{self.endpoint}{view['id']}/?version={made_private.json()['version']}")+ self.assertEqual(deleted.status_code, status.HTTP_204_NO_CONTENT)++ def test_environment_only_admin_cannot_change_parent_project_views(self) -> None:+ view = self._publish(self._create())+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")+ environment_admin = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=environment_admin, organization=self.organization)+ AccessControl.objects.create(+ team=environment,+ resource="project",+ resource_id=str(environment.id),+ organization_member=membership,+ access_level="admin",+ )+ AccessControl.objects.create(+ team=environment,+ resource="customer_analytics",+ access_level="editor",+ organization_member=membership,+ )+ self._set_access(environment_admin, "viewer")+ environment_view_endpoint = f"/api/projects/{environment.id}/account_views/{view['id']}/"++ self.client.force_login(environment_admin)+ renamed = self.client.patch(+ environment_view_endpoint, {"name": "Renamed", "version": view["version"]}, format="json"+ )+ deleted = self.client.delete(f"{environment_view_endpoint}?version={view['version']}")++ self.assertEqual(renamed.status_code, status.HTTP_403_FORBIDDEN, renamed.json())+ self.assertEqual(deleted.status_code, status.HTTP_403_FORBIDDEN, deleted.json())+ preserved = AccountView.objects.for_team(self.team.id).get(id=view["id"])+ self.assertEqual(preserved.name, view["name"])+ self.assertIsNone(preserved.deleted_at)++ def test_account_specific_editor_cannot_edit_team_views_but_can_edit_own_private_views(self) -> None:+ team_view = self._publish(self._create())+ account_editor = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=account_editor, organization=self.organization)+ account = Account.objects.for_team(self.team.id).create(team=self.team, name="Restricted account")+ AccessControl.objects.create(+ team=self.team,+ resource="customer_analytics",+ access_level="none",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=self.team,+ resource="account",+ resource_id=str(account.id),+ access_level="editor",+ organization_member=membership,+ )+ private_view = AccountView.objects.for_team(self.team.id).create(+ team=self.team,+ name="Private workspace",+ content=account_view_content('<Usage nodeId="private-usage" />'),+ created_by=account_editor,+ last_modified_by=account_editor,+ )++ self.client.force_login(account_editor)+ denied = self.client.patch(+ f"{self.endpoint}{team_view['id']}/",+ {"name": "Blocked edit", "version": team_view["version"]},+ format="json",+ )+ self.assertEqual(denied.status_code, status.HTTP_403_FORBIDDEN, denied.json())+ self.assertEqual(AccountView.objects.for_team(self.team.id).get(id=team_view["id"]).name, "Account workspace")++ updated_private = self.client.patch(+ f"{self.endpoint}{private_view.id}/",+ {"name": "Updated private workspace", "version": private_view.version},+ format="json",+ )+ self.assertEqual(updated_private.status_code, status.HTTP_200_OK, updated_private.json())+ self.assertTrue(updated_private.json()["can_edit"])++ def test_stale_update_returns_conflict_without_overwriting_newer_content(self) -> None:view = self._create()first = self.client.patch(f"{self.endpoint}{view['id']}/",@@ -112,11 +277,10 @@ class TestAccountViews(APIBaseTest):{"name": "Stale save", "version": view["version"]},format="json",)-self.assertEqual(stale.status_code, status.HTTP_409_CONFLICT)self.assertEqual(AccountView.objects.for_team(self.team.id).get(id=view["id"]).name, "First save")- def test_invalid_content_is_not_persisted(self) -> None:+ def test_invalid_content_changes_no_state(self) -> None:response = self.client.post(self.endpoint,{@@ -125,30 +289,39 @@ class TestAccountViews(APIBaseTest):},format="json",)-self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertFalse(AccountView.objects.for_team(self.team.id).exists())- def test_create_update_and_delete_are_audited_without_content(self) -> None:- view = self._create()+ def test_deleting_creator_removes_private_views_and_preserves_team_views(self) -> None:+ private_view = self._create("Private workspace")+ team_view = self._publish(self._create("Shared workspace"))++ self.user.delete()++ self.assertFalse(AccountView.objects.unscoped().filter(id=private_view["id"]).exists())+ preserved = AccountView.objects.unscoped().get(id=team_view["id"])+ self.assertIsNone(preserved.created_by_id)++ def test_activity_log_masks_title_name_and_content_for_team_views(self) -> None:+ view = self._publish(self._create("Sensitive workspace"))updated = self.client.patch(f"{self.endpoint}{view['id']}/",{- "name": "Updated private view",+ "name": "Updated workspace","content": account_view_content('<Usage nodeId="usage-one" title="Renewal details" />'),"version": view["version"],},format="json",)self.assertEqual(updated.status_code, status.HTTP_200_OK, updated.json())- deleted = self.client.delete(f"{self.endpoint}{view['id']}/?version={updated.json()['version']}")- self.assertEqual(deleted.status_code, status.HTTP_204_NO_CONTENT)activities = ActivityLog.objects.filter(scope="AccountView", item_id=view["id"]).order_by("created_at")- self.assertEqual([activity.activity for activity in activities], ["created", "updated", "deleted"])+ self.assertEqual([activity.activity for activity in activities], ["created", "updated", "updated"])for activity in activities:- self.assertNotIn("Account workspace", str(activity.detail))- self.assertNotIn("Updated private view", str(activity.detail))+ assert isinstance(activity.detail, dict)+ self.assertIsNone(activity.detail.get("name"))+ self.assertNotIn("Sensitive workspace", str(activity.detail))+ self.assertNotIn("Updated workspace", str(activity.detail))self.assertNotIn("Product usage", str(activity.detail))self.assertNotIn("Renewal details", str(activity.detail))diff --git a/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.py b/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.pyindex fc8af2e51e87..7b0350ae25fb 100644--- a/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.py+++ b/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.py@@ -30,8 +30,17 @@ from products.customer_analytics.backend.models import (DISABLED_TASK_DIGEST = {"enabled": False, "send_time": "09:00", "cadence": "weekdays"}-def config_body(pinned_properties: list[dict[str, str]], task_digest: dict[str, Any] | None = None) -> dict[str, Any]:- return {"pinned_properties": pinned_properties, "task_digest": task_digest or DISABLED_TASK_DIGEST}+def config_body(+ pinned_properties: list[dict[str, str]],+ task_digest: dict[str, Any] | None = None,+ account_detail_tabs: dict[str, Any] | None = None,+) -> dict:+ return {+ "pinned_properties": pinned_properties,+ "task_digest": task_digest or DISABLED_TASK_DIGEST,+ "account_detail_tabs": account_detail_tabs+ or {"ordered_tab_ids": [], "hidden_tab_ids": [], "default_tab_id": None},+ }class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):@@ -264,6 +273,42 @@ class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):self.assertEqual(response.json()["attr"], f"task_digest__{field}")self.assertEqual(self.client.get(self.endpoint).json(), config_body([]))+ def test_patch_account_detail_tabs_preserves_other_configuration(self) -> None:+ pinned = [{"kind": "custom_property", "id": str(self._custom_property().id)}]+ self.client.patch(self.endpoint, {"pinned_properties": pinned}, format="json")+ self.client.patch(+ self.endpoint,+ {"task_digest": {"enabled": True, "send_time": "07:30", "cadence": "every_day"}},+ format="json",+ )+ account_detail_tabs = {+ "ordered_tab_ids": ["system:usage", "view:11111111-2222-4333-8444-555555555555"],+ "hidden_tab_ids": ["system:notes"],+ "default_tab_id": "system:usage",+ }++ response = self.client.patch(self.endpoint, {"account_detail_tabs": account_detail_tabs}, format="json")++ expected = config_body(+ pinned, {"enabled": True, "send_time": "07:30", "cadence": "every_day"}, account_detail_tabs+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json(), expected)++ rejected = self.client.patch(+ self.endpoint,+ {+ "pinned_properties": [],+ "task_digest": {"enabled": False},+ "account_detail_tabs": {**account_detail_tabs, "hidden_tab_ids": ["not-a-tab"]},+ },+ format="json",+ )++ self.assertEqual(rejected.status_code, status.HTTP_400_BAD_REQUEST, rejected.json())+ self.assertEqual(rejected.json()["attr"], "account_detail_tabs")+ self.assertEqual(self.client.get(self.endpoint).json(), expected)+def test_environment_url_resolves_to_the_canonical_team(self) -> None:# `for_team` canonicalizes its filter but not the create kwargs, so an environment (child# team) id in the URL must resolve to the parent before the row is looked up or created.diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 4204b1a2e02d..cc8a3d7fbb86 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -37,7 +37,6 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc└── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)└── (conversations) AccountConversationsExpansion (accountConversationsLogic, keyed by accountId — combines email threads, accessible Support tickets, and Slack summaries; one failed source leaves the other sources usable; email and Slack counts expose a Load older conversations action; expansions paginate email messages, show the Support thread, and keep Slack message links collapsed by default)└── (meetings) AccountMeetingsExpansion (accountMeetingsLogic, keyed by accountId; synced Google Calendar meetings plus optional Gong call links from the Gong warehouse source, and the matching editor; flag-gated tab, CUSTOMER_ANALYTICS_CSP)- └── (event_stream) AccountEventStreamToggle (`../EventStream/`) flag-gated tab (CUSTOMER_ANALYTICS_CSP); membership toggle for the Slack event stream```### Logics and what each ownsdiff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.test.tsxindex c90ed3b02a48..edf7af026667 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.test.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.test.tsx@@ -19,7 +19,6 @@ jest.mock('lib/utils/accessControlUtils', () => ({ userHasAccess: jest.fn(() =>jest.mock('scenes/notebooks/NotebookPanel/notebookPanelLogic', () => ({notebookPanelLogic: { kind: 'notebookPanel' },}))-jest.mock('../EventStream/AccountEventStreamToggle', () => ({ AccountEventStreamToggle: () => null }))jest.mock('../CustomerTasks/CustomerTasksTabContent', () => ({ CustomerTasksTabContent: () => null }))jest.mock('../CustomerTasks/customerTasksLogic', () => ({ customerTasksLogic: () => ({ kind: 'tasks' }) }))jest.mock('./AccountBillingExpansion', () => ({ AccountBillingExpansion: () => null }))diff --git a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsxindex 295ca99a9230..f1fad8dabb48 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx@@ -3,7 +3,6 @@ import { userHasAccess } from 'lib/utils/accessControlUtils'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { CustomerTasksTabContent } from '../CustomerTasks/CustomerTasksTabContent'-import { AccountEventStreamToggle } from '../EventStream/AccountEventStreamToggle'import { AccountBillingExpansion } from './AccountBillingExpansion'import { AccountConversationsExpansion } from './AccountConversationsExpansion'import { AccountFeatureRequestsExpansion } from './AccountFeatureRequestsExpansion'@@ -64,7 +63,5 @@ export function AccountViewComponent({return <AccountConversationsExpansion accountId={accountId} embedded={embedded} {...tileProps} />case 'meetings':return <AccountMeetingsExpansion accountId={accountId} embedded={embedded} {...tileProps} />- case 'event_stream':- return <AccountEventStreamToggle accountId={accountId} externalId={externalId} />}}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsxindex 13a1de39f2c9..021abaf38034 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx@@ -581,6 +581,7 @@ const PINNED_PROPERTY_VALUES: CustomPropertyValueApi[] = PINNED_PROPERTY_FIXTURE}))const PINNED_PROPERTIES_CONFIG: UserCustomerAnalyticsConfigApi = {task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ account_detail_tabs: { ordered_tab_ids: [], hidden_tab_ids: [], default_tab_id: null },pinned_properties: [{ kind: 'custom_property', id: 'seats' },{ kind: 'relationship', id: RELATIONSHIP_DEFINITIONS.results[0].id },diff --git a/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts b/products/customer_analytics/frontend/components/Accounts/accountViewComponents.tsindex 4e4867063c89..120a247275ba 100644--- a/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts@@ -57,13 +57,6 @@ export const ACCOUNT_VIEW_COMPONENTS: AccountViewComponentDefinition[] = [systemTabId: 'system:meetings',featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,},- {- kind: 'event_stream',- tagName: 'EventStream',- label: 'Event stream',- systemTabId: 'system:event_stream',- featureFlag: FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,- },]export function listAvailableAccountViewComponents(featureFlags: FeatureFlagsSet): AccountViewComponentDefinition[] {diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex 855228a20cde..aead9f1753aa 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -17,7 +17,6 @@ export type AccountExpansionTab =| 'opportunities'| 'conversations'| 'meetings'- | 'event_stream'export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['notes',@@ -30,7 +29,6 @@ export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['opportunities','conversations','meetings',- 'event_stream',]export const DEFAULT_ACCOUNT_TAB: AccountExpansionTab = 'notes'@@ -48,7 +46,7 @@ export function getVisibleAccountExpansionTab(if (tab === 'tasks' && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS]) {return DEFAULT_ACCOUNT_TAB}- if ((tab === 'meetings' || tab === 'event_stream') && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {+ if (tab === 'meetings' && !featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]) {return DEFAULT_ACCOUNT_TAB}return tab as AccountExpansionTabdiff --git a/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsx b/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsxdeleted file mode 100644index 45ac7f7b218a..000000000000--- a/products/customer_analytics/frontend/components/EventStream/AccountEventStreamToggle.tsx+++ /dev/null@@ -1,36 +0,0 @@-import { useValues } from 'kea'--import { IconGear } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'--import { AccountEventStreamMembership } from './AccountEventStreamMembership'-import { eventStreamLogic } from './eventStreamLogic'--// Rendered as flag-gated tab content (AccountNotebooksExpansion), so eventStreamLogic-// only mounts — and only fires its load — when the tab is actually opened.-export function AccountEventStreamToggle({- accountId,- externalId,-}: {- accountId: string- externalId: string-}): JSX.Element {- const { settingsUrl } = useValues(eventStreamLogic)-- return (- <div className="flex flex-col gap-2 items-start">- <div className="flex items-center gap-1">- <h4 className="secondary uppercase text-secondary mb-0">Event stream</h4>- <LemonButton- size="xsmall"- type="tertiary"- icon={<IconGear />}- tooltip="Configure the event stream"- data-attr="configure-event-stream"- to={settingsUrl}- />- </div>- <AccountEventStreamMembership accountId={accountId} externalId={externalId} />- </div>- )-}diff --git a/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.stories.tsx b/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.stories.tsxindex 67bcbdf04eb8..1b5bc4378e81 100644--- a/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.stories.tsx+++ b/products/customer_analytics/frontend/components/TaskDigest/CustomerAnalyticsTaskDigest.stories.tsx@@ -14,11 +14,13 @@ const CONFIG_URL = '/api/projects/:team_id/user_customer_analytics_config/@me/'const disabledConfig: UserCustomerAnalyticsConfigApi = {pinned_properties: [],task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ account_detail_tabs: { ordered_tab_ids: [], hidden_tab_ids: [], default_tab_id: null },}const enabledConfig: UserCustomerAnalyticsConfigApi = {pinned_properties: [],task_digest: { enabled: true, send_time: '07:00', cadence: 'every_day' },+ account_detail_tabs: { ordered_tab_ids: [], hidden_tab_ids: [], default_tab_id: null },}interface TaskDigestStoryProps {diff --git a/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.test.ts b/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.test.tsindex fa4509e2ca90..e702259bc968 100644--- a/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.test.ts+++ b/products/customer_analytics/frontend/components/TaskDigest/taskDigestLogic.test.ts@@ -20,6 +20,7 @@ const buildConfig = (overrides: Partial<UserCustomerAnalyticsConfigApi> = {}): U({pinned_properties: PINNED_PROPERTIES,task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ account_detail_tabs: { ordered_tab_ids: [], hidden_tab_ids: [], default_tab_id: null },...overrides,}) as UserCustomerAnalyticsConfigApidiff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 7b72c8b1f000..1323e6c9eab0 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -566,6 +566,18 @@ export interface PaginatedAccountTrackRuleRunViewListApi {results: AccountTrackRuleRunViewApi[]}+/**+ * * `private` - Personal+ * * `team` - Team+ */+export type AccountViewVisibilityEnumApi =+ (typeof AccountViewVisibilityEnumApi)[keyof typeof AccountViewVisibilityEnumApi]++export const AccountViewVisibilityEnumApi = {+ Private: 'private',+ Team: 'team',+} as const+/*** * `doc` - doc*/@@ -623,8 +635,11 @@ export interface AccountViewApi {readonly id: string/** Name shown in the account view. */readonly name: string- /** Account views created through this API are private. */- readonly visibility: string+ /** Whether the view is personal or available to the project.+ *+ * * `private` - Personal+ * * `team` - Team */+ readonly visibility: AccountViewVisibilityEnumApi/** Validated Markdown notebook document. */readonly content: AccountViewContentApi/** Searchable component labels extracted from content. */@@ -645,6 +660,12 @@ export interface AccountViewApi {readonly created_at: string/** When the view was last changed. */readonly updated_at: string+ /** Whether the requesting user can edit the view. */+ readonly can_edit: boolean+ /** Whether the requesting user can delete the view. */+ readonly can_delete: boolean+ /** Whether the requesting user can change the view visibility. */+ readonly can_change_visibility: boolean}export interface AccountViewCreateApi {@@ -657,16 +678,6 @@ export interface AccountViewCreateApi {content: AccountViewContentApi}-/**- * * `private` - Personal- */-export type AccountViewUpdateVisibilityEnumApi =- (typeof AccountViewUpdateVisibilityEnumApi)[keyof typeof AccountViewUpdateVisibilityEnumApi]--export const AccountViewUpdateVisibilityEnumApi = {- Private: 'private',-} as const-export interface AccountViewUpdateApi {/*** New view name. Omit to keep the current name.@@ -675,10 +686,11 @@ export interface AccountViewUpdateApi {name?: string/** Replacement account view components. Omit to keep current content. */content?: AccountViewContentApi- /** Views can only be private.+ /** New visibility. Only the creator or a project admin can change it.*- * * `private` - Personal */- visibility?: AccountViewUpdateVisibilityEnumApi+ * * `private` - Personal+ * * `team` - Team */+ visibility?: AccountViewVisibilityEnumApi/*** Version returned by the last read.* @minimum 1@@ -4567,11 +4579,25 @@ export interface TaskDigestPreferencesApi {cadence: TaskDigestCadenceEnumApi}+export interface AccountDetailTabsConfigApi {+ /** Tab identifiers in the user's preferred order. */+ ordered_tab_ids: string[]+ /** Tab identifiers hidden from the tab strip. */+ hidden_tab_ids: string[]+ /**+ * Tab identifier opened by default. Null uses the first available system tab.+ * @nullable+ */+ default_tab_id: string | null+}+export interface UserCustomerAnalyticsConfigApi {/** Account properties pinned in sidebar display order. */readonly pinned_properties: readonly PinnedAccountPropertyApi[]/** Task digest email preferences. Disabled until the user turns the digest on. */readonly task_digest: TaskDigestPreferencesApi+ /** Personal order, visibility, and default for account tabs. */+ readonly account_detail_tabs: AccountDetailTabsConfigApi}export interface TaskDigestPreferencesUpdateApi {@@ -4591,6 +4617,8 @@ export interface PatchedUserCustomerAnalyticsConfigUpdateApi {pinned_properties?: PinnedAccountPropertyApi[]/** Task digest email preferences to change. Omit the object to keep them all; omit a field inside it to keep that one. */task_digest?: TaskDigestPreferencesUpdateApi+ /** Complete personal account tab configuration. Omit to keep it unchanged. */+ account_detail_tabs?: AccountDetailTabsConfigApi}export type CustomerAnalyticsExternalAccountRetrieveParams = {diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 78e233d5857c..2f017b875248 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -486,7 +486,7 @@ export const getAccountViewsCreateUrl = (projectId: string) => {}/**- * @summary Create a private account view+ * @summary Create a personal account view*/export const accountViewsCreate = async (projectId: string,diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 202240adcaa5..9fd05a7fb4da 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -234,7 +234,7 @@ export const AccountTrackRulesRunCreateBody = /* @__PURE__ */ zod.object({})/**- * @summary Create a private account view+ * @summary Create a personal account view*/export const accountViewsCreateBodyNameMax = 400@@ -319,10 +319,12 @@ export const AccountViewsPartialUpdateBody = /* @__PURE__ */ zod.object({.optional().describe('Replacement account view components. Omit to keep current content.'),visibility: zod- .enum(['private'])- .describe('\* `private` - Personal')+ .enum(['private', 'team'])+ .describe('\* `private` - Personal\n\* `team` - Team').optional()- .describe('Views can only be private.\n\n\* `private` - Personal'),+ .describe(+ 'New visibility. Only the creator or a project admin can change it.\n\n\* `private` - Personal\n\* `team` - Team'+ ),version: zod.number().min(1).describe('Version returned by the last read.'),})@@ -1902,4 +1904,15 @@ export const UserCustomerAnalyticsConfigPartialUpdateBody = /* @__PURE__ */ zod..describe('Task digest email preferences to change. Omit the object to keep them all; omit a field inside it to keep that one.'),+ account_detail_tabs: zod+ .object({+ ordered_tab_ids: zod.array(zod.string()).describe("Tab identifiers in the user's preferred order."),+ hidden_tab_ids: zod.array(zod.string()).describe('Tab identifiers hidden from the tab strip.'),+ default_tab_id: zod+ .string()+ .nullable()+ .describe('Tab identifier opened by default. Null uses the first available system tab.'),+ })+ .optional()+ .describe('Complete personal account tab configuration. Omit to keep it unchanged.'),})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsxindex c016de8b13fb..c6182bb7d420 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { resetContext } from 'kea'import { FEATURE_FLAGS } from 'lib/constants'@@ -9,7 +9,14 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { AccountDetailActions } from './AccountDetailActions'import { accountViewsLogic } from './accountViewsLogic'-jest.mock('../../generated/api', () => ({ accountViewsList: jest.fn().mockResolvedValue([]) }))+jest.mock('../../generated/api', () => ({+ accountViewsList: jest.fn().mockResolvedValue([]),+ userCustomerAnalyticsConfigRetrieve: jest.fn().mockResolvedValue({+ pinned_properties: [],+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ account_detail_tabs: { ordered_tab_ids: [], hidden_tab_ids: [], default_tab_id: null },+ }),+}))describe('AccountDetailActions', () => {beforeEach(() => {@@ -25,14 +32,44 @@ describe('AccountDetailActions', () => {featureFlagLogic.unmount()})- it('opens the personal account view editor', () => {+ it('opens the account view and tab configuration editors', async () => {const logic = accountViewsLogic({ projectId: 1 })logic.mount()render(<AccountDetailActions projectId={1} />)fireEvent.click(screen.getByText('New view'))-expect(logic.values.editorOpen).toBe(true)++ await waitFor(() => expect(logic.values.config).not.toBeNull())+ fireEvent.click(screen.getByText('Configure tabs'))+ expect(logic.values.configureOpen).toBe(true)+ logic.unmount()+ })++ it('keeps Configure disabled until tab settings load, then initializes a pending draft from them', () => {+ const logic = accountViewsLogic({ projectId: 1 })+ logic.mount()+ render(<AccountDetailActions projectId={1} />)++ const configureButton = screen.getByText('Configure tabs').closest('button')+ expect(configureButton).toHaveAttribute('aria-disabled', 'true')++ logic.actions.openConfigure(null)+ logic.actions.loadConfigSuccess({+ pinned_properties: [],+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ account_detail_tabs: {+ ordered_tab_ids: ['system:users', 'system:notes'],+ hidden_tab_ids: ['system:notes'],+ default_tab_id: 'system:users',+ },+ })++ expect(logic.values.configDraft).toEqual({+ ordered_tab_ids: ['system:users', 'system:notes'],+ hidden_tab_ids: ['system:notes'],+ default_tab_id: 'system:users',+ })logic.unmount()})})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsxindex 495d7b474b62..ae4edc73eb45 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailActions.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { IconPlus } from '@posthog/icons'+import { IconGear, IconPlus } from '@posthog/icons'import { LemonButton } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'@@ -14,21 +14,35 @@ interface AccountDetailActionsProps {export function AccountDetailActions({ projectId }: AccountDetailActionsProps): JSX.Element | null {const { featureFlags } = useValues(featureFlagLogic)- const { openCreateEditor } = useActions(accountViewsLogic({ projectId }))+ const logic = accountViewsLogic({ projectId })+ const { accountDetailTabs, config, configError, configLoading } = useValues(logic)+ const { openConfigure, openCreateEditor } = useActions(logic)if (!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]) {return null}return (- <LemonButton- type="primary"- size="small"- icon={<IconPlus />}- data-attr="account-detail-add-view"- onClick={openCreateEditor}- >- New view- </LemonButton>+ <>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconGear />}+ data-attr="account-detail-configure-tabs"+ disabledReason={configLoading || (!config && !configError) ? 'Loading tab settings' : undefined}+ onClick={() => openConfigure(config && !configError ? accountDetailTabs : null)}+ >+ Configure tabs+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPlus />}+ data-attr="account-detail-add-view"+ onClick={openCreateEditor}+ >+ New view+ </LemonButton>+ </>)}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailNavigation.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailNavigation.tsxindex 5f71b8156ca2..b5acec766dbb 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailNavigation.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountDetailNavigation.tsx@@ -1,14 +1,24 @@import { useActions, useMountedLogic, useValues } from 'kea'+import type { ReactNode } from 'react'import { IconPencil } from '@posthog/icons'import { LemonBanner, LemonButton, LemonSkeleton, LemonTabs } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { userLogic } from 'scenes/userLogic'import { accountBillingLogic } from '../../components/Accounts/accountBillingLogic'import { AccountViewComponent } from '../../components/Accounts/AccountViewComponent'-import { listAvailableAccountViewComponents } from '../../components/Accounts/accountViewComponents'+import { AccountTabLabel } from './AccountTabLabel'+import {+ getAccountTabIdFromRoute,+ getAccountTabRoute,+ getActiveAccountTabId,+ listAccountTabs,+ listVisibleAccountTabs,+ type AccountTabDefinition,+} from './accountTabs'import { AccountViewRenderer } from './AccountViewRenderer'import { accountViewsLogic } from './accountViewsLogic'@@ -29,17 +39,57 @@ export function AccountDetailNavigation({}: AccountDetailNavigationProps): JSX.Element {useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'usage' }))const { featureFlags } = useValues(featureFlagLogic)+ const { user } = useValues(userLogic)const logic = accountViewsLogic({ projectId })- const { views, viewsError, viewsLoading } = useValues(logic)- const { openEditEditor, loadViews } = useActions(logic)+ const { views, accountDetailTabs, config, configError, viewsError, viewsLoading } = useValues(logic)+ const { openEditEditor, openConfigure, loadViews } = useActions(logic)const accountViewsEnabled = !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]- const systemTabs = listAvailableAccountViewComponents(featureFlags)- const selectedViewId =- accountViewsEnabled && requestedTab.startsWith('view:') ? requestedTab.slice('view:'.length) : null- const selectedView = selectedViewId ? views.find((view) => view.id === selectedViewId) : undefined- const selectedSystemTab = systemTabs.find((tab) => tab.kind === requestedTab) ?? systemTabs[0]- const activeKey = selectedViewId ? `view:${selectedViewId}` : selectedSystemTab?.kind- const loadingView = !!selectedViewId && !selectedView && viewsLoading+ const tabs = listAccountTabs(featureFlags, accountViewsEnabled ? views : [])+ const requestedTabIdFromRoute = requestedTab ? getAccountTabIdFromRoute(requestedTab) : undefined+ const requestedTabId =+ requestedTabIdFromRoute?.startsWith('view:') && !accountViewsEnabled ? undefined : requestedTabIdFromRoute+ const activeTabId = getActiveAccountTabId(tabs, accountDetailTabs, requestedTabId, user?.id, accountViewsEnabled)+ const activeTab = tabs.find((tab) => tab.id === activeTabId)+ const loadingView = activeTabId.startsWith('view:') && !activeTab && viewsLoading && accountViewsEnabled+ const viewLoadError = activeTabId.startsWith('view:') && !activeTab && !!viewsError && accountViewsEnabled+ const missingView = activeTabId.startsWith('view:') && !activeTab && !loadingView && !viewLoadError+ const visibleTabs = listVisibleAccountTabs(tabs, accountDetailTabs, activeTabId, user?.id, accountViewsEnabled)+ const tabDefinitions = loadingView+ ? [+ ...visibleTabs,+ {+ id: activeTabId,+ routeKey: activeTabId,+ label: 'Loading view',+ kind: 'view' as const,+ },+ ]+ : missingView+ ? [+ ...visibleTabs,+ {+ id: activeTabId,+ routeKey: activeTabId,+ label: 'View unavailable',+ kind: 'view' as const,+ },+ ]+ : visibleTabs++ const displayedTab = tabDefinitions.find((tab) => tab.id === activeTabId)+ const editableView = activeTab?.view+ const rightSlot =+ editableView && (editableView.can_edit || editableView.can_change_visibility) ? (+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconPencil />}+ onClick={() => openEditEditor(editableView)}+ data-attr="account-view-edit"+ >+ {editableView.can_edit ? 'Edit view' : 'Change visibility'}+ </LemonButton>+ ) : undefinedreturn (<div className="min-w-0">@@ -50,52 +100,81 @@ export function AccountDetailNavigation({) : null}<div className="sticky top-0 z-10 bg-primary"><LemonTabs- activeKey={activeKey}- onChange={onChange}+ key={JSON.stringify(tabDefinitions.map(({ id, label }) => [id, label]))}+ activeKey={activeTabId}+ onChange={(tabId) => onChange(getAccountTabRoute(tabId))}rightSlotClassName="pr-0"size="small"- rightSlot={- selectedView ? (- <LemonButton- size="xsmall"- type="secondary"- icon={<IconPencil />}- onClick={() => openEditEditor(selectedView)}- data-attr="account-view-edit"- >- Edit view- </LemonButton>- ) : undefined- }- tabs={[- ...systemTabs.map((tab) => ({ key: tab.kind, label: tab.label })),- ...(accountViewsEnabled- ? views.map((view) => ({ key: `view:${view.id}`, label: view.name }))- : []),- ]}+ rightSlot={rightSlot}+ tabs={tabDefinitions.map((tab) => ({+ key: tab.id,+ label: <AccountTabLabel tab={tab} />,+ }))}/></div>- {loadingView ? (- <LemonSkeleton className="my-3 h-40" />- ) : selectedView ? (- <AccountViewRenderer- view={selectedView}- projectId={projectId}- accountId={accountId}- externalId={externalId}- />- ) : selectedViewId && !viewsError ? (- <LemonBanner type="warning" className="my-3">- This view was deleted or you no longer have access to it. Choose another tab.+ {viewLoadError ? (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadViews }} className="my-3">+ Couldn't load this view. Try again.</LemonBanner>- ) : selectedSystemTab ? (- <AccountViewComponent- kind={selectedSystemTab.kind}- accountId={accountId}- externalId={externalId}- embedded={false}- />+ ) : displayedTab ? (+ <div key={activeTabId}>+ {renderTabContent({+ tab: displayedTab,+ projectId,+ accountId,+ externalId,+ loadingViewId: loadingView ? activeTabId : undefined,+ openConfigure: accountViewsEnabled+ ? () => openConfigure(config && !configError ? accountDetailTabs : null)+ : undefined,+ })}+ </div>) : null}</div>)}++interface RenderTabContentProps {+ tab: AccountTabDefinition+ projectId: number+ accountId: string+ externalId: string+ loadingViewId?: string+ openConfigure?: () => void+}++function renderTabContent({+ tab,+ projectId,+ accountId,+ externalId,+ loadingViewId,+ openConfigure,+}: RenderTabContentProps): ReactNode {+ if (tab.id === loadingViewId) {+ return <LemonSkeleton className="my-3 h-40" />+ }+ if (tab.systemKind) {+ return (+ <AccountViewComponent+ kind={tab.systemKind}+ accountId={accountId}+ externalId={externalId}+ embedded={false}+ />+ )+ }+ if (tab.view) {+ return (+ <AccountViewRenderer view={tab.view} projectId={projectId} accountId={accountId} externalId={externalId} />+ )+ }+ return (+ <LemonBanner+ type="warning"+ action={openConfigure ? { children: 'Open tab settings', onClick: openConfigure } : undefined}+ >+ This view was deleted or you no longer have access to it. Choose another tab.+ </LemonBanner>+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountTabLabel.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountTabLabel.tsxnew file mode 100644index 000000000000..489566b7908d--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountTabLabel.tsx@@ -0,0 +1,24 @@+import { IconGlobe } from '@posthog/icons'+import { Tooltip } from '@posthog/lemon-ui'++import type { AccountTabDefinition } from './accountTabs'++interface AccountTabLabelProps {+ tab: AccountTabDefinition+}++export function AccountTabLabel({ tab }: AccountTabLabelProps): JSX.Element {+ if (tab.view?.visibility !== 'team') {+ return <>{tab.label}</>+ }++ return (+ <span className="flex items-center gap-1">+ <span>{tab.label}</span>+ <span className="sr-only">Shared with team</span>+ <Tooltip title="This view is shared with the team.">+ <IconGlobe className="shrink-0 text-muted" />+ </Tooltip>+ </span>+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.test.tsxnew file mode 100644index 000000000000..ecea5674453d--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.test.tsx@@ -0,0 +1,95 @@+import '@testing-library/jest-dom'++import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { resetContext } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { accountViewsList, accountViewsPartialUpdate, userCustomerAnalyticsConfigRetrieve } from '../../generated/api'+import type { AccountViewApi } from '../../generated/api.schemas'+import { createAccountViewContent } from './accountViewDocument'+import { AccountViewEditorModal } from './AccountViewEditorModal'+import { accountViewsLogic } from './accountViewsLogic'++const visibilityOnlyTeamView: AccountViewApi = {+ id: '11111111-2222-4333-8444-555555555555',+ name: 'Restricted team view',+ visibility: 'team',+ content: createAccountViewContent([{ nodeId: 'usage-one', kind: 'usage', title: 'Usage' }]),+ text_content: 'Usage',+ version: 1,+ created_by: 2,+ last_modified_by: 2,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ can_edit: false,+ can_delete: true,+ can_change_visibility: true,+}++jest.mock('../../generated/api', () => ({+ accountViewsList: jest.fn(),+ accountViewsPartialUpdate: jest.fn(),+ userCustomerAnalyticsConfigRetrieve: jest.fn(),+}))++const mockAccountViewsList = accountViewsList as jest.MockedFunction<typeof accountViewsList>+const mockAccountViewsPartialUpdate = accountViewsPartialUpdate as jest.MockedFunction<typeof accountViewsPartialUpdate>+const mockUserCustomerAnalyticsConfigRetrieve = userCustomerAnalyticsConfigRetrieve as jest.MockedFunction<+ typeof userCustomerAnalyticsConfigRetrieve+>++describe('AccountViewEditorModal', () => {+ beforeEach(() => {+ resetContext()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]: true })+ mockAccountViewsList.mockResolvedValue([visibilityOnlyTeamView])+ mockAccountViewsPartialUpdate.mockResolvedValue({+ ...visibilityOnlyTeamView,+ visibility: 'private',+ version: 2,+ })+ mockUserCustomerAnalyticsConfigRetrieve.mockResolvedValue({+ pinned_properties: [],+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ account_detail_tabs: { ordered_tab_ids: [], hidden_tab_ids: [], default_tab_id: null },+ })+ mockAccountViewsPartialUpdate.mockClear()+ })++ afterEach(() => {+ cleanup()+ featureFlagLogic.unmount()+ })++ it('allows a visibility-only team view editor to save only the visibility', async () => {+ const logic = accountViewsLogic({ projectId: 1 })+ logic.mount()+ render(<AccountViewEditorModal projectId={1} />)++ await waitFor(() => expect(logic.values.views).toEqual([visibilityOnlyTeamView]))+ act(() => logic.actions.openEditEditor(visibilityOnlyTeamView))++ expect(screen.getByText('Change view visibility')).toBeInTheDocument()+ expect(document.querySelector('[data-attr="account-view-name"]')).not.toBeInTheDocument()+ expect(screen.queryByText('Components')).not.toBeInTheDocument()+ expect(+ screen.getByText(+ "You can change this view's visibility, but only account editors can change its name or contents."+ )+ ).toBeInTheDocument()++ fireEvent.click(screen.getByText('Only me'))+ fireEvent.click(screen.getByText('Save visibility'))++ await waitFor(() =>+ expect(mockAccountViewsPartialUpdate).toHaveBeenCalledWith('1', visibilityOnlyTeamView.id, {+ visibility: 'private',+ version: visibilityOnlyTeamView.version,+ })+ )+ logic.unmount()+ })+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.tsxindex fc17d2f18d98..e9a8e8c0209a 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewEditorModal.tsx@@ -3,7 +3,7 @@ import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiimport { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'import { useActions, useValues } from 'kea'-import { IconTrash } from '@posthog/icons'+import { IconPlus, IconTrash } from '@posthog/icons'import {LemonBanner,LemonButton,@@ -11,6 +11,7 @@ import {LemonInput,LemonLabel,LemonModal,+ LemonSegmentedButton,LemonSelect,LemonTag,} from '@posthog/lemon-ui'@@ -36,6 +37,7 @@ export function AccountViewEditorModal({ projectId }: AccountViewEditorModalPropconst {setEditorOpen,setEditorName,+ setEditorVisibility,addEditorComponent,duplicateEditorComponent,removeEditorComponent,@@ -45,11 +47,15 @@ export function AccountViewEditorModal({ projectId }: AccountViewEditorModalPropdeleteView,} = useActions(logic)const availableComponents = listAvailableAccountViewComponents(featureFlags)- const saveDisabledReason = !editorDraft.name.trim()- ? 'Enter a view name'- : editorDraft.components.length === 0- ? 'Add at least one component'- : undefined+ const canEditContent = !editingView || editingView.can_edit+ const visibilityOnly = !!editingView && !canEditContent && editingView.can_change_visibility+ const saveDisabledReason = canEditContent+ ? !editorDraft.name.trim()+ ? 'Enter a view name'+ : editorDraft.components.length === 0+ ? 'Add at least one component'+ : undefined+ : undefinedconst confirmDelete = (): void => {if (!editingView) {@@ -57,7 +63,10 @@ export function AccountViewEditorModal({ projectId }: AccountViewEditorModalProp}LemonDialog.open({title: `Delete "${editingView.name}"?`,- description: 'This removes the view from your account tabs.',+ description:+ editingView.visibility === 'team'+ ? 'This removes the view for everyone in the project.'+ : 'This removes the view from your account tabs.',primaryButton: {children: 'Delete view',status: 'danger',@@ -71,11 +80,11 @@ export function AccountViewEditorModal({ projectId }: AccountViewEditorModalProp<LemonModalisOpen={editorOpen}onClose={() => setEditorOpen(false)}- title={editingView ? 'Edit view' : 'Add view'}+ title={visibilityOnly ? 'Change view visibility' : editingView ? 'Edit view' : 'Add view'}width={640}footer={<>- {editingView ? (+ {editingView?.can_delete ? (<LemonButtonstatus="danger"type="secondary"@@ -99,7 +108,7 @@ export function AccountViewEditorModal({ projectId }: AccountViewEditorModalPropdisabledReason={saveDisabledReason}data-attr="account-view-save">- {editingView ? 'Save changes' : 'Create view'}+ {visibilityOnly ? 'Save visibility' : editingView ? 'Save changes' : 'Create view'}</LemonButton></>}@@ -110,70 +119,99 @@ export function AccountViewEditorModal({ projectId }: AccountViewEditorModalPropThis view changed since you opened it. Reload the latest version before saving.</LemonBanner>) : null}- <div className="flex flex-col gap-1">- <LemonLabel htmlFor="account-view-name">View name</LemonLabel>- <LemonInput- id="account-view-name"- value={editorDraft.name}- onChange={setEditorName}- placeholder="Account overview"- autoFocus- data-attr="account-view-name"- />- </div>- <div className="flex flex-wrap items-end gap-2">- <div className="flex min-w-56 flex-1 flex-col gap-1">- <LemonLabel>Components</LemonLabel>- <LemonSelect<AccountViewComponentKind>- value={null}- allowClear- onChange={(kind) => kind && addEditorComponent(kind)}- options={availableComponents.map((component) => ({- value: component.kind,- label: component.label,- }))}- placeholder="Choose a component"+ {canEditContent ? (+ <div className="flex flex-col gap-1">+ <LemonLabel htmlFor="account-view-name">View name</LemonLabel>+ <LemonInput+ id="account-view-name"+ value={editorDraft.name}+ onChange={setEditorName}+ placeholder="Account overview"+ autoFocus+ data-attr="account-view-name"/></div>- <LemonTag type="muted">{editorDraft.components.length} added</LemonTag>- </div>- <div className="flex flex-col gap-2">- {editorDraft.components.length === 0 ? (- <div className="rounded border border-dashed p-4 text-center text-secondary">- Add the account sections you want to show in this view.+ ) : null}+ {editingView?.can_change_visibility ? (+ <div className="flex flex-col gap-1">+ <LemonLabel>Visibility</LemonLabel>+ <LemonSegmentedButton+ value={editorDraft.visibility}+ onChange={setEditorVisibility}+ options={[+ { value: 'private', label: 'Only me' },+ { value: 'team', label: 'Team' },+ ]}+ size="small"+ />+ </div>+ ) : null}+ {canEditContent ? (+ <>+ <div className="flex flex-wrap items-end gap-2">+ <div className="flex min-w-56 flex-1 flex-col gap-1">+ <LemonLabel>Components</LemonLabel>+ <LemonSelect<AccountViewComponentKind>+ value={null}+ allowClear+ onChange={(kind) => kind && addEditorComponent(kind)}+ options={availableComponents.map((component) => ({+ value: component.kind,+ label: component.label,+ }))}+ placeholder="Choose a component"+ />+ </div>+ <LemonTag type="muted">{editorDraft.components.length} added</LemonTag></div>- ) : (- <DndContext- onDragEnd={({ active, over }) => {- if (over) {- reorderEditorComponent(String(active.id), String(over.id))- }- }}- modifiers={[restrictToVerticalAxis, restrictToParentElement]}- >- <SortableContext- items={editorDraft.components.map((component) => component.nodeId)}- strategy={verticalListSortingStrategy}- >- <div className="flex flex-col gap-2">- {editorDraft.components.map((component) => {- const definition = getAccountViewComponentByKind(component.kind)- return (- <AccountViewEditorComponentItem- key={component.nodeId}- component={component}- label={component.title ?? definition?.label ?? component.kind}- disabled={editorSaving}- onDuplicate={() => duplicateEditorComponent(component.nodeId)}- onRemove={() => removeEditorComponent(component.nodeId)}- />- )- })}+ <div className="flex flex-col gap-2">+ {editorDraft.components.length === 0 ? (+ <div className="rounded border border-dashed p-4 text-center text-secondary">+ Add the account sections you want to show in this view.</div>- </SortableContext>- </DndContext>- )}- </div>+ ) : (+ <DndContext+ onDragEnd={({ active, over }) => {+ if (over) {+ reorderEditorComponent(String(active.id), String(over.id))+ }+ }}+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}+ >+ <SortableContext+ items={editorDraft.components.map((component) => component.nodeId)}+ strategy={verticalListSortingStrategy}+ >+ <div className="flex flex-col gap-2">+ {editorDraft.components.map((component) => {+ const definition = getAccountViewComponentByKind(component.kind)+ return (+ <AccountViewEditorComponentItem+ key={component.nodeId}+ component={component}+ label={component.title ?? definition?.label ?? component.kind}+ disabled={editorSaving}+ onDuplicate={() => duplicateEditorComponent(component.nodeId)}+ onRemove={() => removeEditorComponent(component.nodeId)}+ />+ )+ })}+ </div>+ </SortableContext>+ </DndContext>+ )}+ </div>+ </>+ ) : (+ <LemonBanner type="info">+ You can change this view's visibility, but only account editors can change its name or contents.+ </LemonBanner>+ )}+ {!editingView ? (+ <LemonBanner type="info" icon={<IconPlus />}>+ New views are personal. You can share the view with your team after creating it.+ </LemonBanner>+ ) : null}</div></LemonModal>)diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.test.tsxindex b3948ccf9a8a..c6e92907564e 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.test.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewRenderer.test.tsx@@ -39,6 +39,9 @@ function createView(searchTerm: string): AccountViewApi {last_modified_by: 1,created_at: '2026-01-01T00:00:00Z',updated_at: '2026-01-01T00:00:00Z',+ can_edit: true,+ can_delete: true,+ can_change_visibility: true,}}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsxindex 9ff44477839c..a410dc19e938 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx@@ -30,7 +30,7 @@ export function AccountViewTile({const { tileSaving, tileConfigReloads } = useValues(logic)const { openTileEditor, removeViewComponent, updateViewComponentConfig } = useActions(logic)const title = component.title ?? getAccountViewComponentByKind(component.kind)?.label ?? component.kind- const menuDisabledReason = tileSaving ? 'Saving changes' : undefined+ const menuDisabledReason = !view.can_edit ? 'You cannot edit this view' : tileSaving ? 'Saving changes' : undefinedconst confirmRemove = (): void => {LemonDialog.open({@@ -89,7 +89,11 @@ export function AccountViewTile({externalId={externalId}instanceId={`${component.nodeId}:${tileConfigReloads[view.id] ?? 0}`}initialConfig={component.config}- onConfigChange={(config) => updateViewComponentConfig(view.id, component.nodeId, config)}+ onConfigChange={+ view.can_edit+ ? (config) => updateViewComponentConfig(view.id, component.nodeId, config)+ : undefined+ }embedded/></div>diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsItem.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsItem.tsxnew file mode 100644index 000000000000..5f939b4527d0--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsItem.tsx@@ -0,0 +1,58 @@+import { useSortable } from '@dnd-kit/sortable'+import { CSS } from '@dnd-kit/utilities'++import { LemonCheckbox } from '@posthog/lemon-ui'++import { SortableDragIcon } from 'lib/lemon-ui/icons'++import { AccountTabLabel } from './AccountTabLabel'+import type { AccountTabDefinition } from './accountTabs'++interface ConfigureAccountTabsItemProps {+ tab: AccountTabDefinition+ visible: boolean+ disabledReason: string | undefined+ onVisibilityChange: (visible: boolean) => void+}++export function ConfigureAccountTabsItem({+ tab,+ visible,+ disabledReason,+ onVisibilityChange,+}: ConfigureAccountTabsItemProps): JSX.Element {+ const { setNodeRef, attributes, listeners, transform, transition, isDragging } = useSortable({+ id: tab.id,+ disabled: !!disabledReason,+ })++ return (+ <div+ ref={setNodeRef}+ // eslint-disable-next-line react/forbid-dom-props+ style={{ transform: CSS.Transform.toString(transform), transition }}+ className={`flex items-center gap-2 rounded border bg-surface-primary p-2 ${isDragging ? 'opacity-50' : ''}`}+ data-attr="account-tabs-item"+ >+ <button+ type="button"+ className={`flex items-center text-secondary ${+ disabledReason ? 'cursor-not-allowed' : 'cursor-grab active:cursor-grabbing'+ }`}+ aria-label={`Reorder ${tab.label}`}+ disabled={!!disabledReason}+ {...attributes}+ {...listeners}+ >+ <SortableDragIcon />+ </button>+ <LemonCheckbox+ checked={visible}+ onChange={onVisibilityChange}+ disabledReason={disabledReason}+ label={<AccountTabLabel tab={tab} />}+ className="min-w-0 flex-1"+ />+ </div>+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsModal.tsxnew file mode 100644index 000000000000..99cd8060964e--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsModal.tsx@@ -0,0 +1,115 @@+import { useActions, useValues } from 'kea'++import { IconPlus } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonModal, LemonSelect } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { userLogic } from 'scenes/userLogic'++import {+ isAccountTabVisible,+ listAccountTabs,+ listOrderedAccountTabs,+ reorderAccountTab,+ setAccountTabVisibility,+ type AccountTabDefinition,+} from './accountTabs'+import { accountViewsLogic } from './accountViewsLogic'+import { ConfigureAccountTabsSection } from './ConfigureAccountTabsSection'++interface ConfigureAccountTabsModalProps {+ projectId: number+}++export function ConfigureAccountTabsModal({ projectId }: ConfigureAccountTabsModalProps): JSX.Element {+ const logic = accountViewsLogic({ projectId })+ const { featureFlags } = useValues(featureFlagLogic)+ const { user } = useValues(userLogic)+ const { configureOpen, configDraft, configError, configLoading, configSaving, config, views } = useValues(logic)+ const accountViewsEnabled = !!featureFlags[FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]+ const { setConfigureOpen, setConfigDraft, saveConfig, openCreateEditor, loadConfig } = useActions(logic)+ const editingDisabledReason = configError+ ? 'Retry loading tab settings before making changes'+ : configLoading || !config+ ? 'Loading tab settings'+ : undefined+ const tabs = listOrderedAccountTabs(listAccountTabs(featureFlags, accountViewsEnabled ? views : []), configDraft)+ const isTabVisible = (tab: AccountTabDefinition): boolean => isAccountTabVisible(tab, configDraft, user?.id)+ const updateVisibility = (tab: AccountTabDefinition, visible: boolean): void =>+ setConfigDraft(setAccountTabVisibility(tabs, tab, configDraft, user?.id, visible))+ const reorderTab = (activeTabId: string, overTabId: string): void =>+ setConfigDraft(reorderAccountTab(tabs, configDraft, user?.id, activeTabId, overTabId))++ return (+ <LemonModal+ isOpen={configureOpen}+ onClose={() => setConfigureOpen(false)}+ title="Configure tabs"+ width={600}+ footer={+ <>+ {accountViewsEnabled ? (+ <LemonButton+ type="secondary"+ icon={<IconPlus />}+ onClick={() => {+ setConfigureOpen(false)+ openCreateEditor()+ }}+ className="mr-auto"+ >+ Add view+ </LemonButton>+ ) : null}+ <LemonButton type="secondary" onClick={() => setConfigureOpen(false)}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ loading={configSaving}+ disabledReason={editingDisabledReason}+ onClick={saveConfig}+ data-attr="account-tabs-save"+ >+ Save settings+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ {configError ? (+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadConfig }}>+ Couldn't load your saved tab settings. Retry before making changes so they are not overwritten.+ </LemonBanner>+ ) : null}+ <div className="flex flex-col gap-1">+ <span className="font-medium">Default tab</span>+ <LemonSelect+ value={configDraft.default_tab_id}+ onChange={(defaultTabId) => setConfigDraft({ ...configDraft, default_tab_id: defaultTabId })}+ disabledReason={editingDisabledReason}+ options={tabs.filter(isTabVisible).map((tab) => ({ value: tab.id, label: tab.label }))}+ placeholder="First available tab"+ />+ </div>+ <ConfigureAccountTabsSection+ title="Views"+ tabs={tabs.filter((tab) => tab.kind === 'view')}+ disabledReason={editingDisabledReason}+ isTabVisible={isTabVisible}+ onVisibilityChange={updateVisibility}+ onReorder={reorderTab}+ />+ <ConfigureAccountTabsSection+ title="System tabs"+ tabs={tabs.filter((tab) => tab.kind === 'system')}+ disabledReason={editingDisabledReason}+ isTabVisible={isTabVisible}+ onVisibilityChange={updateVisibility}+ onReorder={reorderTab}+ />+ </div>+ </LemonModal>+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsSection.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsSection.tsxnew file mode 100644index 000000000000..9e6dce6a9491--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/ConfigureAccountTabsSection.tsx@@ -0,0 +1,56 @@+import { DndContext } from '@dnd-kit/core'+import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'+import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'++import type { AccountTabDefinition } from './accountTabs'+import { ConfigureAccountTabsItem } from './ConfigureAccountTabsItem'++interface ConfigureAccountTabsSectionProps {+ title: string+ tabs: AccountTabDefinition[]+ disabledReason: string | undefined+ isTabVisible: (tab: AccountTabDefinition) => boolean+ onVisibilityChange: (tab: AccountTabDefinition, visible: boolean) => void+ onReorder: (activeTabId: string, overTabId: string) => void+}++export function ConfigureAccountTabsSection({+ title,+ tabs,+ disabledReason,+ isTabVisible,+ onVisibilityChange,+ onReorder,+}: ConfigureAccountTabsSectionProps): JSX.Element | null {+ if (tabs.length === 0) {+ return null+ }++ return (+ <div className="flex flex-col gap-2">+ <span className="font-medium">{title}</span>+ <DndContext+ onDragEnd={({ active, over }) => {+ if (over) {+ onReorder(String(active.id), String(over.id))+ }+ }}+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}+ >+ <SortableContext items={tabs.map((tab) => tab.id)} strategy={verticalListSortingStrategy}>+ <div className="flex flex-col gap-2">+ {tabs.map((tab) => (+ <ConfigureAccountTabsItem+ key={tab.id}+ tab={tab}+ visible={isTabVisible(tab)}+ disabledReason={disabledReason}+ onVisibilityChange={(visible) => onVisibilityChange(tab, visible)}+ />+ ))}+ </div>+ </SortableContext>+ </DndContext>+ </div>+ )+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsxindex 4991a94054a6..db3ab87ecf5c 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx@@ -45,6 +45,9 @@ const accountView = {last_modified_by: 1,created_at: '2026-05-10T10:00:00Z',updated_at: '2026-05-20T14:30:00Z',+ can_edit: true,+ can_delete: true,+ can_change_visibility: true,}const account = {@@ -129,7 +132,15 @@ const meta: Meta = {'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="24" height="24" rx="4" fill="#8f68d4"/></svg>',{ headers: { 'Content-Type': 'image/svg+xml' } }),- [ACCOUNT_SIDEBAR_CONFIG_ENDPOINT]: { pinned_properties: [] },+ [ACCOUNT_SIDEBAR_CONFIG_ENDPOINT]: {+ pinned_properties: [],+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ account_detail_tabs: {+ ordered_tab_ids: [`view:${ACCOUNT_VIEW_ID}`, 'system:notes', 'system:relationships'],+ hidden_tab_ids: [],+ default_tab_id: `view:${ACCOUNT_VIEW_ID}`,+ },+ },[ACCOUNT_VIEWS_ENDPOINT]: [accountView],[VALUES_ENDPOINT]: [],[ASSIGNMENTS_ENDPOINT]: [],diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsxindex 0aa15fd8351b..12afa3788b64 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx@@ -25,6 +25,7 @@ import { AccountPresence } from './AccountPresence'import { AccountSidebar } from './AccountSidebar'import { AccountViewEditorModal } from './AccountViewEditorModal'import { AccountViewTileEditorModal } from './AccountViewTileEditorModal'+import { ConfigureAccountTabsModal } from './ConfigureAccountTabsModal'import {CustomerAnalyticsAccountSceneLogicProps,customerAnalyticsAccountSceneLogic,@@ -160,6 +161,7 @@ function CustomerAnalyticsAccountSceneContent(): JSX.Element {{projectId ? (<><AccountViewEditorModal projectId={projectId} />+ <ConfigureAccountTabsModal projectId={projectId} /><AccountViewTileEditorModal projectId={projectId} /></>) : null}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountDetailWorkInProgress.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountDetailWorkInProgress.tsdeleted file mode 100644index 8767895dfd4d..000000000000--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountDetailWorkInProgress.ts+++ /dev/null@@ -1,8 +0,0 @@-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'--export function openAccountDetailWorkInProgress(title: string): void {- LemonDialog.open({- title,- content: 'This feature is a work in progress.',- })-}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.tsindex 444bef3fd9be..5295231412e4 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts@@ -61,6 +61,7 @@ const defaultMocks = (config: Partial<UserCustomerAnalyticsConfigApi> = {}): Par[CONFIG_URL]: {pinned_properties: [],task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },+ account_detail_tabs: { ordered_tab_ids: [], hidden_tab_ids: [], default_tab_id: null },...config,},[CUSTOM_PROPERTIES_URL]: { count: 1, results: [buildCustomProperty()] },diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.tsnew file mode 100644index 000000000000..a63ab91c48be--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts@@ -0,0 +1,84 @@+import type { AccountDetailTabsConfigApi, AccountViewApi } from '../../generated/api.schemas'+import {+ getActiveAccountTabId,+ getDefaultAccountTabId,+ isAccountTabVisible,+ listOrderedAccountTabs,+ listVisibleAccountTabs,+ reorderAccountTab,+ setAccountTabVisibility,+ type AccountTabDefinition,+} from './accountTabs'++const emptyConfig: AccountDetailTabsConfigApi = {+ ordered_tab_ids: [],+ hidden_tab_ids: [],+ default_tab_id: null,+}++const tabs: AccountTabDefinition[] = [+ { id: 'system:notes', routeKey: 'notes', label: 'Notes', kind: 'system', systemKind: 'notes' },+ { id: 'system:users', routeKey: 'users', label: 'Users', kind: 'system', systemKind: 'users' },+ {+ id: 'view:shared',+ routeKey: 'view:shared',+ label: 'Shared view',+ kind: 'view',+ view: { id: 'shared', name: 'Shared view', visibility: 'team', created_by: 2 } as AccountViewApi,+ },+]++describe('account tabs', () => {+ it('falls back from an unavailable system route but keeps an unknown view route', () => {+ expect(getActiveAccountTabId(tabs, emptyConfig, 'system:tasks', 1)).toBe('system:notes')+ expect(getActiveAccountTabId(tabs, emptyConfig, 'view:missing', 1)).toBe('view:missing')+ })++ it('does not apply tab preferences while account views are disabled', () => {+ const config: AccountDetailTabsConfigApi = {+ ordered_tab_ids: ['system:users'],+ hidden_tab_ids: ['system:notes', 'view:shared'],+ default_tab_id: 'system:users',+ }++ expect(listOrderedAccountTabs(tabs, config, false).map((tab) => tab.id)).toEqual([+ 'view:shared',+ 'system:notes',+ 'system:users',+ ])+ expect(listVisibleAccountTabs(tabs, config, undefined, 1, false).map((tab) => tab.id)).toEqual([+ 'view:shared',+ 'system:notes',+ 'system:users',+ ])+ expect(getDefaultAccountTabId(tabs, config, 1, false)).toBe('system:notes')+ expect(getDefaultAccountTabId(tabs, config, 1, true)).toBe('system:users')+ })++ it('does not opt into another user’s team view while reordering system tabs', () => {+ const config = reorderAccountTab(tabs, emptyConfig, 1, 'system:users', 'system:notes')++ expect(config.ordered_tab_ids).toEqual(['system:users', 'system:notes'])+ expect(config.ordered_tab_ids).not.toContain('view:shared')+ expect(isAccountTabVisible(tabs[2], config, 1)).toBe(false)+ })++ it('lists a newly selected team view with the views, ahead of system tabs', () => {+ const config = setAccountTabVisibility(tabs, tabs[2], emptyConfig, 1, true)++ expect(config.ordered_tab_ids).toEqual(['system:notes', 'system:users', 'view:shared'])+ expect(listVisibleAccountTabs(tabs, config, undefined, 1).map((tab) => tab.id)).toEqual([+ 'view:shared',+ 'system:notes',+ 'system:users',+ ])+ })++ it('defaults to a visible view before a hidden system tab', () => {+ const config = setAccountTabVisibility(tabs, tabs[2], emptyConfig, 1, true)+ const allSystemTabsHidden = { ...config, hidden_tab_ids: ['system:notes', 'system:users'] }++ expect(getDefaultAccountTabId(tabs, allSystemTabsHidden, 1)).toBe('view:shared')+ expect(getDefaultAccountTabId(tabs, { ...allSystemTabsHidden, ordered_tab_ids: [] }, 1)).toBe('system:notes')+ })+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.tsnew file mode 100644index 000000000000..420aa7497ede--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.ts@@ -0,0 +1,188 @@+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'++import {+ listAvailableAccountViewComponents,+ type AccountViewComponentKind,+} from '../../components/Accounts/accountViewComponents'+import type { AccountDetailTabsConfigApi, AccountViewApi } from '../../generated/api.schemas'++export interface AccountTabDefinition {+ id: string+ routeKey: string+ label: string+ kind: 'system' | 'view'+ systemKind?: AccountViewComponentKind+ view?: AccountViewApi+}++export function listAccountTabs(featureFlags: FeatureFlagsSet, views: AccountViewApi[]): AccountTabDefinition[] {+ return [+ ...listAvailableAccountViewComponents(featureFlags).map(+ (component): AccountTabDefinition => ({+ id: component.systemTabId,+ routeKey: component.kind,+ label: component.label,+ kind: 'system',+ systemKind: component.kind,+ })+ ),+ ...views.map(+ (view): AccountTabDefinition => ({+ id: `view:${view.id}`,+ routeKey: `view:${view.id}`,+ label: view.name,+ kind: 'view',+ view,+ })+ ),+ ]+}++function isUnselectedTeamView(+ tab: AccountTabDefinition,+ config: AccountDetailTabsConfigApi,+ userId: number | undefined+): boolean {+ return tab.view?.visibility === 'team' && tab.view.created_by !== userId && !config.ordered_tab_ids.includes(tab.id)+}++function sortAccountTabsByConfig(+ tabs: AccountTabDefinition[],+ config: AccountDetailTabsConfigApi+): AccountTabDefinition[] {+ const byId = new Map(tabs.map((tab) => [tab.id, tab]))+ const ordered = config.ordered_tab_ids.flatMap((id) => {+ const tab = byId.get(id)+ if (!tab) {+ return []+ }+ byId.delete(id)+ return [tab]+ })+ return [...ordered, ...tabs.filter((tab) => byId.has(tab.id))]+}++export function listOrderedAccountTabs(+ tabs: AccountTabDefinition[],+ config: AccountDetailTabsConfigApi,+ applyTabConfiguration = true+): AccountTabDefinition[] {+ const orderedTabs = applyTabConfiguration ? sortAccountTabsByConfig(tabs, config) : tabs+ return [...orderedTabs.filter((tab) => tab.kind === 'view'), ...orderedTabs.filter((tab) => tab.kind === 'system')]+}++export function isAccountTabVisible(+ tab: AccountTabDefinition,+ config: AccountDetailTabsConfigApi,+ userId: number | undefined,+ applyTabConfiguration = true+): boolean {+ if (!applyTabConfiguration) {+ return true+ }+ return !config.hidden_tab_ids.includes(tab.id) && !isUnselectedTeamView(tab, config, userId)+}++export function listVisibleAccountTabs(+ tabs: AccountTabDefinition[],+ config: AccountDetailTabsConfigApi,+ activeTabId: string | undefined,+ userId: number | undefined,+ applyTabConfiguration = true+): AccountTabDefinition[] {+ return listOrderedAccountTabs(tabs, config, applyTabConfiguration).filter(+ (tab) => isAccountTabVisible(tab, config, userId, applyTabConfiguration) || tab.id === activeTabId+ )+}++export function setAccountTabVisibility(+ tabs: AccountTabDefinition[],+ tab: AccountTabDefinition,+ config: AccountDetailTabsConfigApi,+ userId: number | undefined,+ visible: boolean+): AccountDetailTabsConfigApi {+ const shouldOptIntoTeamView = visible && isUnselectedTeamView(tab, config, userId)+ const orderedTabIds = shouldOptIntoTeamView+ ? tabs.filter((candidate) => !isUnselectedTeamView(candidate, config, userId)).map((candidate) => candidate.id)+ : config.ordered_tab_ids+ return {+ ...config,+ ordered_tab_ids: shouldOptIntoTeamView ? [...orderedTabIds, tab.id] : orderedTabIds,+ hidden_tab_ids: visible+ ? config.hidden_tab_ids.filter((id) => id !== tab.id)+ : [...new Set([...config.hidden_tab_ids, tab.id])],+ default_tab_id: !visible && config.default_tab_id === tab.id ? null : config.default_tab_id,+ }+}++export function reorderAccountTab(+ tabs: AccountTabDefinition[],+ config: AccountDetailTabsConfigApi,+ userId: number | undefined,+ activeTabId: string,+ overTabId: string+): AccountDetailTabsConfigApi {+ const orderedTabs = listOrderedAccountTabs(tabs, config)+ const fromIndex = orderedTabs.findIndex((tab) => tab.id === activeTabId)+ const toIndex = orderedTabs.findIndex((tab) => tab.id === overTabId)+ if (+ fromIndex < 0 ||+ toIndex < 0 ||+ fromIndex === toIndex ||+ orderedTabs[fromIndex].kind !== orderedTabs[toIndex].kind+ ) {+ return config+ }+ const reorderedTabs = [...orderedTabs]+ const [moved] = reorderedTabs.splice(fromIndex, 1)+ reorderedTabs.splice(toIndex, 0, moved)+ return {+ ...config,+ ordered_tab_ids: reorderedTabs+ .filter((tab) => !isUnselectedTeamView(tab, config, userId) || tab.id === activeTabId)+ .map((tab) => tab.id),+ }+}++export function getAccountTabIdFromRoute(routeKey: string): string {+ return routeKey.startsWith('view:') ? routeKey : `system:${routeKey}`+}++export function getAccountTabRoute(tabId: string): string {+ return tabId.startsWith('system:') ? tabId.slice('system:'.length) : tabId+}++export function getDefaultAccountTabId(+ tabs: AccountTabDefinition[],+ config: AccountDetailTabsConfigApi,+ userId: number | undefined,+ applyTabConfiguration = true+): string {+ const defaultTab = tabs.find((tab) => tab.id === config.default_tab_id)+ if (defaultTab && applyTabConfiguration && !config.hidden_tab_ids.includes(defaultTab.id)) {+ return defaultTab.id+ }+ const isVisible = (tab: AccountTabDefinition): boolean =>+ isAccountTabVisible(tab, config, userId, applyTabConfiguration)+ return (+ tabs.find((tab) => tab.kind === 'system' && isVisible(tab))?.id ??+ listOrderedAccountTabs(tabs, config, applyTabConfiguration).find(isVisible)?.id ??+ tabs.find((tab) => tab.kind === 'system')?.id ??+ 'system:notes'+ )+}++export function getActiveAccountTabId(+ tabs: AccountTabDefinition[],+ config: AccountDetailTabsConfigApi,+ requestedTabId: string | undefined,+ userId: number | undefined,+ applyTabConfiguration = true+): string {+ const defaultTabId = getDefaultAccountTabId(tabs, config, userId, applyTabConfiguration)+ if (!requestedTabId || !requestedTabId.startsWith('system:')) {+ return requestedTabId ?? defaultTabId+ }+ return tabs.some((tab) => tab.id === requestedTabId) ? requestedTabId : defaultTabId+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.tsindex abe9eb947bdc..967edbaf0974 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts@@ -14,8 +14,16 @@ import {accountViewsList,accountViewsPartialUpdate,accountViewsRetrieve,+ userCustomerAnalyticsConfigPartialUpdate,+ userCustomerAnalyticsConfigRetrieve,} from '../../generated/api'-import type { AccountViewApi, AccountViewContentApi } from '../../generated/api.schemas'+import type {+ AccountDetailTabsConfigApi,+ AccountViewApi,+ AccountViewContentApi,+ AccountViewVisibilityEnumApi,+ UserCustomerAnalyticsConfigApi,+} from '../../generated/api.schemas'import {createAccountViewContent,createAccountViewComponentInstance,@@ -29,6 +37,7 @@ export interface AccountViewsLogicProps {export interface AccountViewEditorDraft {name: string+ visibility: AccountViewVisibilityEnumApicomponents: AccountViewComponentInstance[]}@@ -38,9 +47,23 @@ export interface AccountViewTileEditor {name: string}+const EMPTY_TABS_CONFIG: AccountDetailTabsConfigApi = {+ ordered_tab_ids: [],+ hidden_tab_ids: [],+ default_tab_id: null,+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountViewsLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic+ accountDetailTabs: AccountDetailTabsConfigApi+ config: UserCustomerAnalyticsConfigApi | null+ configDraft: AccountDetailTabsConfigApi+ configDraftPendingLoad: boolean+ configError: unknown+ configLoading: boolean+ configSaving: boolean+ configureOpen: booleaneditingView: AccountViewApi | nulleditingViewId: string | nulleditorConflict: boolean@@ -86,6 +109,15 @@ export interface accountViewsLogicActions {duplicateEditorComponent: (nodeId: string) => {nodeId: string}+ loadConfig: () => {+ value: true+ }+ loadConfigFailure: (error: unknown) => {+ error: unknown+ }+ loadConfigSuccess: (config: UserCustomerAnalyticsConfigApi) => {+ config: UserCustomerAnalyticsConfigApi+ }loadViews: () => {value: true}@@ -95,6 +127,9 @@ export interface accountViewsLogicActions {loadViewsSuccess: (views: AccountViewApi[]) => {views: AccountViewApi[]}+ openConfigure: (config: AccountDetailTabsConfigApi | null) => {+ config: AccountDetailTabsConfigApi | null+ }openCreateEditor: () => {value: true}@@ -133,6 +168,15 @@ export interface accountViewsLogicActions {resetViewComponentConfig: (viewId: string) => {viewId: string}+ saveConfig: () => {+ value: true+ }+ saveConfigFailure: () => {+ value: true+ }+ saveConfigSuccess: (config: UserCustomerAnalyticsConfigApi) => {+ config: UserCustomerAnalyticsConfigApi+ }saveEditor: () => {value: true}@@ -158,6 +202,12 @@ export interface accountViewsLogicActions {saveViewComponentFailure: () => {value: true}+ setConfigDraft: (config: AccountDetailTabsConfigApi) => {+ config: AccountDetailTabsConfigApi+ }+ setConfigureOpen: (open: boolean) => {+ open: boolean+ }setEditorConflict: (conflict: boolean) => {conflict: boolean}@@ -167,6 +217,9 @@ export interface accountViewsLogicActions {setEditorOpen: (open: boolean) => {open: boolean}+ setEditorVisibility: (visibility: AccountViewVisibilityEnumApi) => {+ visibility: AccountViewVisibilityEnumApi+ }setTileEditorName: (name: string) => {name: string}@@ -186,6 +239,7 @@ export interface accountViewsLogicMeta {key: number__keaTypeGenInternalSelectorTypes: {editingView: (views: AccountViewApi[], editingViewId: string | null) => AccountViewApi | null+ accountDetailTabs: (config: UserCustomerAnalyticsConfigApi | null) => AccountDetailTabsConfigApi}}@@ -257,10 +311,14 @@ export const accountViewsLogic = kea<accountViewsLogicType>([loadViews: true,loadViewsSuccess: (views: AccountViewApi[]) => ({ views }),loadViewsFailure: (error: unknown) => ({ error }),+ loadConfig: true,+ loadConfigSuccess: (config: UserCustomerAnalyticsConfigApi) => ({ config }),+ loadConfigFailure: (error: unknown) => ({ error }),setEditorOpen: (open: boolean) => ({ open }),openCreateEditor: true,openEditEditor: (view: AccountViewApi) => ({ view }),setEditorName: (name: string) => ({ name }),+ setEditorVisibility: (visibility: AccountViewVisibilityEnumApi) => ({ visibility }),addEditorComponent: (kind: AccountViewComponentKind) => ({ kind }),duplicateEditorComponent: (nodeId: string) => ({ nodeId }),removeEditorComponent: (nodeId: string) => ({ nodeId }),@@ -290,6 +348,12 @@ export const accountViewsLogic = kea<accountViewsLogicType>([deleteView: (viewId: string, version: number) => ({ viewId, version }),deleteViewFailure: true,deleteViewSuccess: (viewId: string) => ({ viewId }),+ setConfigureOpen: (open: boolean) => ({ open }),+ openConfigure: (config: AccountDetailTabsConfigApi | null) => ({ config }),+ setConfigDraft: (config: AccountDetailTabsConfigApi) => ({ config }),+ saveConfig: true,+ saveConfigSuccess: (config: UserCustomerAnalyticsConfigApi) => ({ config }),+ saveConfigFailure: true,}),reducers({views: [@@ -342,20 +406,48 @@ export const accountViewsLogic = kea<accountViewsLogicType>([loadViewsFailure: (_, { error }: { error: unknown }) => error,},],+ config: [+ null as UserCustomerAnalyticsConfigApi | null,+ {+ loadConfigSuccess: (_, { config }: { config: UserCustomerAnalyticsConfigApi }) => config,+ saveConfigSuccess: (_, { config }: { config: UserCustomerAnalyticsConfigApi }) => config,+ },+ ],+ configLoading: [+ false,+ {+ loadConfig: () => true,+ loadConfigSuccess: () => false,+ loadConfigFailure: () => false,+ },+ ],+ configError: [+ null as unknown,+ {+ loadConfig: () => null,+ loadConfigSuccess: () => null,+ loadConfigFailure: (_, { error }: { error: unknown }) => error,+ },+ ],editorOpen: [false, { setEditorOpen: (_, { open }: { open: boolean }) => open }],editingViewId: [null as string | null,{ openCreateEditor: () => null, openEditEditor: (_, { view }: { view: AccountViewApi }) => view.id },],editorDraft: [- { name: '', components: [] } as AccountViewEditorDraft,+ { name: '', visibility: 'private', components: [] } as AccountViewEditorDraft,{- openCreateEditor: () => ({ name: '', components: [] }),+ openCreateEditor: () => ({ name: '', visibility: 'private', components: [] }),openEditEditor: (_, { view }: { view: AccountViewApi }) => ({name: view.name,+ visibility: view.visibility,components: parseAccountViewContent(view.content),}),setEditorName: (state, { name }: { name: string }) => ({ ...state, name }),+ setEditorVisibility: (state, { visibility }: { visibility: AccountViewVisibilityEnumApi }) => ({+ ...state,+ visibility,+ }),addEditorComponent: (state, { kind }: { kind: AccountViewComponentKind }) => ({...state,components: [...state.components, createAccountViewComponentInstance(kind)],@@ -433,6 +525,30 @@ export const accountViewsLogic = kea<accountViewsLogicType>([saveViewComponentFailure: () => false,},],+ configureOpen: [false, { setConfigureOpen: (_, { open }: { open: boolean }) => open }],+ configDraftPendingLoad: [+ false,+ {+ openConfigure: (_, { config }: { config: AccountDetailTabsConfigApi | null }) => !config,+ setConfigDraft: () => false,+ },+ ],+ configDraft: [+ EMPTY_TABS_CONFIG,+ {+ openConfigure: (state, { config }: { config: AccountDetailTabsConfigApi | null }) =>+ config ? { ...config } : state,+ setConfigDraft: (_, { config }: { config: AccountDetailTabsConfigApi }) => config,+ },+ ],+ configSaving: [+ false,+ {+ saveConfig: () => true,+ saveConfigSuccess: () => false,+ saveConfigFailure: () => false,+ },+ ],}),selectors({editingView: [@@ -440,6 +556,11 @@ export const accountViewsLogic = kea<accountViewsLogicType>([(views: AccountViewApi[], editingViewId: string | null): AccountViewApi | null =>views.find((view) => view.id === editingViewId) ?? null,],+ accountDetailTabs: [+ (selectors) => [selectors.config],+ (config: UserCustomerAnalyticsConfigApi | null): AccountDetailTabsConfigApi =>+ config?.account_detail_tabs ?? EMPTY_TABS_CONFIG,+ ],}),listeners(({ actions, cache, props, values }) => ({setFeatureFlags: () => loadViewsOnceEnabled({ actions, cache, values }),@@ -457,20 +578,35 @@ export const accountViewsLogic = kea<accountViewsLogicType>([actions.loadViewsFailure(error)}},+ loadConfig: async () => {+ try {+ actions.loadConfigSuccess(await userCustomerAnalyticsConfigRetrieve(String(props.projectId), '@me'))+ } catch (error) {+ actions.loadConfigFailure(error)+ }+ },+ loadConfigSuccess: ({ config }) => {+ if (values.configureOpen && values.configDraftPendingLoad) {+ actions.setConfigDraft(config.account_detail_tabs)+ }+ },openCreateEditor: () => actions.setEditorOpen(true),openEditEditor: () => actions.setEditorOpen(true),+ openConfigure: () => actions.setConfigureOpen(true),saveEditor: async () => {- if (!values.editorDraft.name.trim() || values.editorDraft.components.length === 0) {+ const editingView = values.editingView+ const canEditContent = !editingView || editingView.can_edit+ if (canEditContent && (!values.editorDraft.name.trim() || values.editorDraft.components.length === 0)) {actions.saveEditorFailure()return}try {const content = createAccountViewContent(values.editorDraft.components)- const view = values.editingView- ? await accountViewsPartialUpdate(String(props.projectId), values.editingView.id, {- name: values.editorDraft.name.trim(),- content,- version: values.editingView.version,+ const view = editingView+ ? await accountViewsPartialUpdate(String(props.projectId), editingView.id, {+ ...(editingView.can_edit ? { name: values.editorDraft.name.trim(), content } : {}),+ ...(editingView.can_change_visibility ? { visibility: values.editorDraft.visibility } : {}),+ version: editingView.version,}): await accountViewsCreate(String(props.projectId), {name: values.editorDraft.name.trim(),@@ -575,6 +711,22 @@ export const accountViewsLogic = kea<accountViewsLogicType>([}})},+ saveConfig: async () => {+ if (values.configError || !values.config) {+ actions.saveConfigFailure()+ return+ }+ try {+ const config = await userCustomerAnalyticsConfigPartialUpdate(String(props.projectId), '@me', {+ account_detail_tabs: values.configDraft,+ })+ actions.saveConfigSuccess(config)+ actions.setConfigureOpen(false)+ } catch {+ actions.saveConfigFailure()+ lemonToast.error("Couldn't save the tab settings. Try again.")+ }+ },removeViewComponent: async ({ viewId, nodeId }) => {await queueViewWrite(cache, viewId, async () => {const view = values.views.find((candidate) => candidate.id === viewId)@@ -603,5 +755,8 @@ export const accountViewsLogic = kea<accountViewsLogicType>([})},})),- afterMount((logic) => loadViewsOnceEnabled(logic)),+ afterMount((logic) => {+ loadViewsOnceEnabled(logic)+ logic.actions.loadConfig()+ }),])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f473878121f1..d4b2e880cd05 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -1717,6 +1717,18 @@ export namespace Schemas {value?: (string | number | boolean)[] | string | number | boolean | null;}+ export interface AccountDetailTabsConfig {+ /** Tab identifiers in the user's preferred order. */+ ordered_tab_ids: string[];+ /** Tab identifiers hidden from the tab strip. */+ hidden_tab_ids: string[];+ /**+ * Tab identifier opened by default. Null uses the first available system tab.+ * @nullable+ */+ default_tab_id: string | null;+ }+export interface ConversationMessageSender {/** Display name of the message sender. */readonly name: string;@@ -2203,6 +2215,18 @@ export namespace Schemas {groups: AccountTrackRuleGroup[];}+ /**+ * * `private` - Personal+ * * `team` - Team+ */+ export type AccountViewVisibilityEnum = typeof AccountViewVisibilityEnum[keyof typeof AccountViewVisibilityEnum];+++ export const AccountViewVisibilityEnum = {+ Private: 'private',+ Team: 'team',+ } as const;+/*** * `doc` - doc*/@@ -2260,8 +2284,11 @@ export namespace Schemas {readonly id: string;/** Name shown in the account view. */readonly name: string;- /** Account views created through this API are private. */- readonly visibility: string;+ /** Whether the view is personal or available to the project.+ *+ * * `private` - Personal+ * * `team` - Team */+ readonly visibility: AccountViewVisibilityEnum;/** Validated Markdown notebook document. */readonly content: AccountViewContent;/** Searchable component labels extracted from content. */@@ -2282,6 +2309,12 @@ export namespace Schemas {readonly created_at: string;/** When the view was last changed. */readonly updated_at: string;+ /** Whether the requesting user can edit the view. */+ readonly can_edit: boolean;+ /** Whether the requesting user can delete the view. */+ readonly can_delete: boolean;+ /** Whether the requesting user can change the view visibility. */+ readonly can_change_visibility: boolean;}export interface AccountViewCreate {@@ -2294,16 +2327,6 @@ export namespace Schemas {content: AccountViewContent;}- /**- * * `private` - Personal- */- export type AccountViewUpdateVisibilityEnum = typeof AccountViewUpdateVisibilityEnum[keyof typeof AccountViewUpdateVisibilityEnum];--- export const AccountViewUpdateVisibilityEnum = {- Private: 'private',- } as const;-export interface AccountViewUpdate {/*** New view name. Omit to keep the current name.@@ -2312,10 +2335,11 @@ export namespace Schemas {name?: string;/** Replacement account view components. Omit to keep current content. */content?: AccountViewContent;- /** Views can only be private.+ /** New visibility. Only the creator or a project admin can change it.*- * * `private` - Personal */- visibility?: AccountViewUpdateVisibilityEnum;+ * * `private` - Personal+ * * `team` - Team */+ visibility?: AccountViewVisibilityEnum;/*** Version returned by the last read.* @minimum 1@@ -81639,6 +81663,8 @@ export namespace Schemas {pinned_properties?: PinnedAccountProperty[];/** Task digest email preferences to change. Omit the object to keep them all; omit a field inside it to keep that one. */task_digest?: TaskDigestPreferencesUpdate;+ /** Complete personal account tab configuration. Omit to keep it unchanged. */+ account_detail_tabs?: AccountDetailTabsConfig;}/**@@ -104201,6 +104227,8 @@ export namespace Schemas {readonly pinned_properties: readonly PinnedAccountProperty[];/** Task digest email preferences. Disabled until the user turns the digest on. */readonly task_digest: TaskDigestPreferences;+ /** Personal order, visibility, and default for account tabs. */+ readonly account_detail_tabs: AccountDetailTabsConfig;}export interface UserFacetSettings {