: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): configure pinned account properties (#95503)
Arthur Moreira de Deused77d91a6c62
diff --git a/docs/internal/customer-analytics-property-editors.md b/docs/internal/customer-analytics-property-editors.mdindex d270d1e0c2e1..082b93093caf 100644--- a/docs/internal/customer-analytics-property-editors.md+++ b/docs/internal/customer-analytics-property-editors.md@@ -6,3 +6,21 @@ Saving converts the entered percentage back to its stored fraction.Date-only properties preserve the calendar date from the API, including when the APIreturns a UTC-midnight timestamp. Datetime properties retain local timezone handling.The date picker keeps an attempted selection available after a failed save.++## Pin preferences++Omitting `pinned_properties` from a PATCH to+`/api/projects/:team_id/user_customer_analytics_config/@me/` preserves the existing+selection. An explicit empty list clears it.++API keys and OAuth tokens require `account:write` to change pins. Session-authenticated+viewers can personalize their own sidebar without permission to edit account values.++A failed save keeps the pin selector open with the attempted selection and order.+The user can retry the save or remove a rejected property.++Legacy child-environment URLs read and update the same user configuration as their parent project.+They require access to the parent project and its Customer analytics resource. Scoped+credentials must include the parent project, not only the child environment.+Successful pin saves emit `customer analytics account pinned properties saved` with aggregate+counts only. Failed attempts do not emit a success event.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 22107cffc09a..62488c856b1e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6349,9 +6349,9 @@ snapshots:scenes-app-customer-analytics-account-detail-property-sidebar--date-and-datetime-editors--light:hash: v1.k794b7964.34b994fa9a3b92bb93f70bbcd7f95c6410187da93539e4ff5c9834ffaa6618e7.Fvdistl0g6mQAeJ9qgXVqZWJmMSUopy5YEBZTr7VAW4scenes-app-customer-analytics-account-detail-property-sidebar--empty--dark:- hash: v1.k794b7964.c4a38e5e46e71a34d9afdfedf083087e5387710d526fdc6066a0a6b4eea4f720.m3rWBzL-w_OU7qA7inUpJpnKHBY76Fet3r_ho2z1kU4+ hash: v1.k794b7964.3f250e8e47cb5e0d5fd6aba1b4c57dc3978db9f296a093e53c7b46fa6ca93528.ZsLhX7VF2gO8fS9hbGyCbahwLIVa-GP5EkJI1ij-ToQscenes-app-customer-analytics-account-detail-property-sidebar--empty--light:- hash: v1.k794b7964.0fedccb0aed3ba24d39e42f7700b77096ca9f7ae3fffb2df4aa573ea4e6d764b.cCX43P0wrfkD6GYGsquNyoq5I2lPwdwAtTrpPmO6H1Y+ hash: v1.k794b7964.80932bda346697628be7627a1729c3fe6a5c860637dc9626bae39febdc22d3f5.tl_7hj4nr98S-dkzOcAIA7Cs4z6guQG7lR1IvbzsJgQscenes-app-customer-analytics-account-detail-property-sidebar--filled-and-scrollable--dark:hash: v1.k794b7964.75d86eaa79d518fdce67a3d91053dcbdff1ee6efae7e533c31533cdd57ee6700.9jA6_-_9pS7ApCzy-uJitof965VYwovXPMrLIPgXMxIscenes-app-customer-analytics-account-detail-property-sidebar--filled-and-scrollable--light:diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex ed066f20a53a..1cbc4491ffa5 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -96,6 +96,7 @@ from products.customer_analytics.backend.facade.contracts import (InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,)from products.customer_analytics.backend.facade.email_matching import schedule_email_thread_link_recalculation+from products.customer_analytics.backend.facade.enums import AccountPropertyPinKindfrom products.customer_analytics.backend.logic import (account_track_rules as _account_track_rules_logic,announcements as _announcements_logic,@@ -104,6 +105,7 @@ from products.customer_analytics.backend.logic import (customer_tasks as _customer_tasks_logic,feature_requests as _feature_requests_logic,relationships as _relationships_logic,+ user_customer_analytics_config as _user_customer_analytics_config_logic,)from products.customer_analytics.backend.logic.account_filters import (InvalidAccountFilter,@@ -154,6 +156,7 @@ from products.customer_analytics.backend.models import (SyncStatus,SyncTrigger,TargetType,+ UserCustomerAnalyticsConfig as UserCustomerAnalyticsConfigModel,)from products.customer_analytics.backend.models.account import (RETIRED_ROLE_KEYS,@@ -1163,6 +1166,40 @@ def delete_customer_profile_config(return True+# --- UserCustomerAnalyticsConfig ---+++InvalidPinnedAccountProperties = _user_customer_analytics_config_logic.InvalidPinnedAccountProperties+++def _to_user_customer_analytics_config(+ config: UserCustomerAnalyticsConfigModel,+) -> contracts.UserCustomerAnalyticsConfig:+ raw_references = config.properties[_user_customer_analytics_config_logic.PINNED_PROPERTIES_KEY]+ return contracts.UserCustomerAnalyticsConfig(+ pinned_properties=[+ contracts.PinnedAccountProperty(kind=reference["kind"], id=UUID(str(reference["id"])))+ for reference in raw_references+ ]+ )+++def get_user_customer_analytics_config(*, team_id: int, user_id: int) -> contracts.UserCustomerAnalyticsConfig:+ config = _user_customer_analytics_config_logic.get_or_create_config(team_id=team_id, user_id=user_id)+ return _to_user_customer_analytics_config(config)+++def update_user_customer_analytics_config(+ *, team_id: int, user_id: int, pinned_properties: list[contracts.PinnedAccountProperty]+) -> contracts.UserCustomerAnalyticsConfig:+ config = _user_customer_analytics_config_logic.update_pinned_properties(+ team_id=team_id,+ user_id=user_id,+ references=[(AccountPropertyPinKind(reference.kind), reference.id) for reference in pinned_properties],+ )+ return _to_user_customer_analytics_config(config)++# --- CustomPropertyDefinition ---diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex b64a6f50e161..f5a3c2628861 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -16,7 +16,7 @@ from dataclasses import ()from datetime import date, datetimefrom enum import Enum-from typing import Any, TypedDict+from typing import Any, Literal, TypedDictfrom uuid import UUIDfrom pydantic.dataclasses import dataclass@@ -52,6 +52,17 @@ class AccountRelationshipDefinition:is_single_holder: bool = True+@dataclass(frozen=True)+class PinnedAccountProperty:+ kind: Literal["custom_property", "relationship"]+ id: UUID+++@dataclass(frozen=True)+class UserCustomerAnalyticsConfig:+ pinned_properties: list[PinnedAccountProperty] = field(default_factory=list)++@dataclass(frozen=True)class AccountRelationship:"""One assignment of a user to an account relationship, with its effective range."""diff --git a/products/customer_analytics/backend/facade/enums.py b/products/customer_analytics/backend/facade/enums.pynew file mode 100644index 000000000000..46c05aa6eb8f--- /dev/null+++ b/products/customer_analytics/backend/facade/enums.py@@ -0,0 +1,6 @@+from enum import Enum+++class AccountPropertyPinKind(str, Enum):+ CUSTOM_PROPERTY = "custom_property"+ RELATIONSHIP = "relationship"diff --git a/products/customer_analytics/backend/logic/user_customer_analytics_config.py b/products/customer_analytics/backend/logic/user_customer_analytics_config.pynew file mode 100644index 000000000000..4def80475727--- /dev/null+++ b/products/customer_analytics/backend/logic/user_customer_analytics_config.py@@ -0,0 +1,105 @@+from collections.abc import Sequence+from uuid import UUID++from posthog.models.scoping.manager import resolve_effective_team_id++from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind+from products.customer_analytics.backend.models import (+ AccountRelationshipDefinition,+ CustomPropertyDefinition,+ TargetType,+ UserCustomerAnalyticsConfig,+)++PINNED_PROPERTIES_KEY = "pinned_properties"+MAX_PINNED_PROPERTIES = 50+++class InvalidPinnedAccountProperties(ValueError):+ def __init__(self, errors: list[str]) -> None:+ super().__init__("; ".join(errors))+ self.errors = errors+++def get_or_create_config(*, team_id: int, user_id: int) -> UserCustomerAnalyticsConfig:+ # Resolve an environment (child team) id to its root team once. `for_team` canonicalizes its+ # filter but not the create kwargs, so a raw id makes the lookup never match, and the unique+ # constraint then rejects every call after the first.+ canonical_team_id = resolve_effective_team_id(team_id)+ config, _ = UserCustomerAnalyticsConfig.objects.for_team(canonical_team_id, canonical=True).get_or_create(+ team_id=canonical_team_id,+ user_id=user_id,+ defaults={"properties": {PINNED_PROPERTIES_KEY: []}},+ )+ if PINNED_PROPERTIES_KEY in config.properties:+ return config++ legacy_references = [+ {"kind": AccountPropertyPinKind.CUSTOM_PROPERTY.value, "id": str(definition_id)}+ for definition_id in config.pinned_custom_property_definition_ids+ ]+ config.properties = {**config.properties, PINNED_PROPERTIES_KEY: legacy_references}+ config.save(update_fields=["properties", "updated_at"])+ return config+++def update_pinned_properties(+ *, team_id: int, user_id: int, references: Sequence[tuple[AccountPropertyPinKind, UUID]]+) -> UserCustomerAnalyticsConfig:+ _validate_pinned_properties(team_id=team_id, references=references)+ config = get_or_create_config(team_id=team_id, user_id=user_id)+ config.properties = {+ **config.properties,+ PINNED_PROPERTIES_KEY: [{"kind": kind.value, "id": str(definition_id)} for kind, definition_id in references],+ }+ config.pinned_custom_property_definition_ids = [+ definition_id for kind, definition_id in references if kind == AccountPropertyPinKind.CUSTOM_PROPERTY+ ]+ config.save(update_fields=["properties", "pinned_custom_property_definition_ids", "updated_at"])+ return config+++def _validate_pinned_properties(*, team_id: int, references: Sequence[tuple[AccountPropertyPinKind, UUID]]) -> None:+ if len(references) > MAX_PINNED_PROPERTIES:+ raise InvalidPinnedAccountProperties([f"Pin at most {MAX_PINNED_PROPERTIES} account properties."])++ errors: list[str] = []+ first_index_by_reference: dict[tuple[AccountPropertyPinKind, UUID], int] = {}+ for index, reference in enumerate(references):+ if reference in first_index_by_reference:+ errors.append(f"Item {index + 1} duplicates item {first_index_by_reference[reference] + 1}.")+ else:+ first_index_by_reference[reference] = index++ referenced_ids = {definition_id for _, definition_id in references}+ custom_property_targets = dict(+ CustomPropertyDefinition.objects.for_team(team_id)+ .filter(id__in=referenced_ids)+ .values_list("id", "target_type")+ )+ matching_relationship_ids = set(+ AccountRelationshipDefinition.objects.for_team(team_id)+ .filter(id__in=referenced_ids)+ .values_list("id", flat=True)+ )++ for index, (kind, definition_id) in enumerate(references):+ item = index + 1+ if kind == AccountPropertyPinKind.CUSTOM_PROPERTY:+ target_type = custom_property_targets.get(definition_id)+ if target_type is not None:+ if target_type != TargetType.ACCOUNT.value:+ errors.append(f"Item {item} must reference an account property.")+ elif definition_id in matching_relationship_ids:+ errors.append(f"Item {item} is a relationship, not a custom property.")+ else:+ errors.append(f"Item {item} custom property was not found in this project.")+ elif definition_id in matching_relationship_ids:+ continue+ elif definition_id in custom_property_targets:+ errors.append(f"Item {item} is a custom property, not a relationship.")+ else:+ errors.append(f"Item {item} relationship was not found in this project.")++ if errors:+ raise InvalidPinnedAccountProperties(errors)diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 4b3f25726250..134055f7e2d1 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -74,6 +74,7 @@ from products.customer_analytics.backend.facade.contracts import (MeetingParticipantView,MeetingView,)+from products.customer_analytics.backend.facade.enums import AccountPropertyPinKindclass AccountTrackRuleFieldSerializer(serializers.Serializer):@@ -1956,6 +1957,36 @@ class CustomPropertyValueSuggestionsResponseSerializer(serializers.Serializer):)+class PinnedAccountPropertySerializer(serializers.Serializer):+ kind = serializers.ChoiceField(+ choices=[+ (AccountPropertyPinKind.CUSTOM_PROPERTY.value, "Custom property"),+ (AccountPropertyPinKind.RELATIONSHIP.value, "Relationship"),+ ],+ help_text="Definition type for this pinned account property.",+ )+ id = serializers.UUIDField(+ help_text="Team-scoped custom property or relationship definition UUID.",+ )+++class UserCustomerAnalyticsConfigSerializer(serializers.Serializer):+ pinned_properties = PinnedAccountPropertySerializer(+ many=True,+ read_only=True,+ help_text="Account properties pinned in sidebar display order.",+ )+++class UserCustomerAnalyticsConfigUpdateSerializer(serializers.Serializer):+ pinned_properties = PinnedAccountPropertySerializer(+ many=True,+ allow_empty=True,+ required=False,+ help_text="Complete ordered list of account properties to pin. Omit to keep the current pins; pass an empty list to clear them.",+ )++class AccountRelationshipDefinitionSerializer(DataclassSerializer):"""A team-defined account relationship type (CSM, Onboarding manager, ...)."""diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex ddc465aadfdf..4f5e7acadaa3 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport jsonimport builtinsfrom dataclasses import asdict+from functools import cached_propertyfrom typing import Any, castfrom uuid import UUID@@ -37,17 +38,20 @@ from rest_framework.throttling import UserRateThrottlefrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.tagged_item import TaggedItemViewSetMixin+from posthog.auth import SessionAuthenticationfrom posthog.cdp.services.icons import CDPIconsServicefrom posthog.event_usage import report_user_actionfrom posthog.exceptions import Conflictfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.models import OrganizationMembership+from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.permissions import (PostHogFeatureFlagPermission,TeamMemberAccessPermission,TeamMemberLightManagementPermission,TeamMemberStrictManagementPermission,+ get_authenticator_scoped_team_ids,get_authenticator_scopes,is_service_auth,)@@ -107,6 +111,8 @@ from products.customer_analytics.backend.presentation.views.serializers import (MeetingSerializer,SupportTicketMessageSerializer,SupportTicketSerializer,+ UserCustomerAnalyticsConfigSerializer,+ UserCustomerAnalyticsConfigUpdateSerializer,)from ee.hogai.tools.create_notebook.tiptap import markdown_to_tiptap_nodes@@ -778,6 +784,104 @@ class FeatureRequestViewSet(return Response(FeatureRequestStatusHistorySerializer(instance=history, many=True).data)+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"]+ scope_object_write_actions = ["partial_update"]+ serializer_class = UserCustomerAnalyticsConfigSerializer+ queryset = None+ lookup_value_regex = "@me"+ permission_classes = [UserConfigCanonicalTeamAccessPermission]++ @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_required_scopes(self, request: Request, view: Any) -> list[str] | None:+ # Browser viewers can personalize their own sidebar without account edit access.+ # Scoped credentials still need write permission to change their owner's preferences.+ if self.action == "partial_update" and isinstance(request.successful_authenticator, SessionAuthentication):+ return ["account:read"]+ return None++ @extend_schema(+ responses={+ 200: OpenApiResponse(+ response=UserCustomerAnalyticsConfigSerializer,+ description="The requesting user's account sidebar configuration.",+ )+ },+ summary="Get account sidebar configuration",+ description=(+ "Get the requesting user's account sidebar configuration for this project. "+ "The first read creates an empty configuration row."+ ),+ )+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ config = api.get_user_customer_analytics_config(+ team_id=self.team_id,+ user_id=cast(User, request.user).id,+ )+ return Response(UserCustomerAnalyticsConfigSerializer(instance=config).data)++ @validated_request(+ request_serializer=UserCustomerAnalyticsConfigUpdateSerializer,+ responses={+ 200: OpenApiResponse(+ response=UserCustomerAnalyticsConfigSerializer,+ description="The updated account sidebar configuration.",+ ),+ 400: OpenApiResponse(description="A pinned definition is invalid for this project."),+ },+ summary="Update account sidebar configuration",+ description=(+ "Replace the requesting user's ordered account sidebar properties when pinned_properties is provided. "+ "Omitting pinned_properties leaves the configuration unchanged. "+ "At most 50 account custom properties and relationships can be pinned."+ ),+ )+ def partial_update(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ if "pinned_properties" not in request.validated_data:+ return self.retrieve(request, *args, **kwargs)+ 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=cast(User, request.user).id,+ pinned_properties=pinned_properties,+ )+ except api.InvalidPinnedAccountProperties as error:+ raise ValidationError({"pinned_properties": error.errors})+ return Response(UserCustomerAnalyticsConfigSerializer(instance=config).data)++class CustomerProfileConfigViewSet(TeamAndOrgViewSetMixin,_FacadePaginationMixin,diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex 6feff06c5b7e..9c1142ac38f9 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -22,6 +22,7 @@ from products.customer_analytics.backend.presentation.views.views import (EventStreamViewSet,FeatureRequestProductAreaViewSet,FeatureRequestViewSet,+ UserCustomerAnalyticsConfigViewSet,)@@ -105,6 +106,12 @@ def register_routes(routers: RouterRegistry) -> None:"project_calendar_sync",["team_id"],)+ routers.projects.register(+ r"user_customer_analytics_config",+ UserCustomerAnalyticsConfigViewSet,+ "project_user_customer_analytics_config",+ ["team_id"],+ )project_accounts_router = routers.projects.register(r"accounts", AccountViewSet, "project_accounts", ["team_id"])project_accounts_router.register(r"notebooks", AccountNotebookViewSet, "project_account_notebooks", ["team_id", "account_id"]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.pynew file mode 100644index 000000000000..6bb5292f151b--- /dev/null+++ b/products/customer_analytics/backend/test/test_user_customer_analytics_config_api.py@@ -0,0 +1,323 @@+from datetime import timedelta+from uuid import uuid4++from posthog.test.base import APIBaseTest++from django.utils import timezone++from parameterized import parameterized+from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models.oauth import OAuthAccessToken, OAuthApplication+from posthog.models.organization import OrganizationMembership+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.team import Team+from posthog.models.user import User+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.access_control.backend.models.access_control import AccessControl+from products.customer_analytics.backend.models import (+ AccountRelationshipDefinition,+ CustomPropertyDefinition,+ TargetType,+ UserCustomerAnalyticsConfig,+)+++class TestUserCustomerAnalyticsConfigAPI(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.endpoint = f"/api/projects/{self.team.id}/user_customer_analytics_config/@me/"++ def _custom_property(+ self, *, team: Team | None = None, target_type: TargetType = TargetType.ACCOUNT+ ) -> CustomPropertyDefinition:+ owning_team = team or self.team+ return CustomPropertyDefinition.objects.for_team(owning_team.id).create(+ team_id=owning_team.id,+ name=f"Property {uuid4()}",+ target_type=target_type.value,+ )++ def _relationship(self, *, team: Team | None = None) -> AccountRelationshipDefinition:+ owning_team = team or self.team+ return AccountRelationshipDefinition.objects.for_team(owning_team.id).create(+ team_id=owning_team.id,+ name=f"Relationship {uuid4()}",+ )++ def test_get_creates_empty_config_without_rewriting_an_explicit_empty_list(self) -> None:+ response = self.client.get(self.endpoint)++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json(), {"pinned_properties": []})+ config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).get(user_id=self.user.id)+ self.assertEqual(config.properties, {"pinned_properties": []})++ legacy_definition = self._custom_property()+ config.properties = {"pinned_properties": [], "future_setting": "kept"}+ config.pinned_custom_property_definition_ids = [legacy_definition.id]+ config.save(update_fields=["properties", "pinned_custom_property_definition_ids"])+ updated_at = config.updated_at++ repeated = self.client.get(self.endpoint)++ self.assertEqual(repeated.status_code, status.HTTP_200_OK, repeated.json())+ self.assertEqual(repeated.json(), {"pinned_properties": []})+ config.refresh_from_db()+ self.assertEqual(config.properties, {"pinned_properties": [], "future_setting": "kept"})+ self.assertEqual(config.updated_at, updated_at)++ def test_get_migrates_legacy_custom_property_ids_in_order(self) -> None:+ first = self._custom_property()+ second = self._custom_property()+ config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ user_id=self.user.id,+ pinned_custom_property_definition_ids=[second.id, first.id],+ properties={"future_setting": "kept"},+ )++ response = self.client.get(self.endpoint)++ expected = [+ {"kind": "custom_property", "id": str(second.id)},+ {"kind": "custom_property", "id": str(first.id)},+ ]+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json(), {"pinned_properties": expected})+ config.refresh_from_db()+ self.assertEqual(config.properties, {"future_setting": "kept", "pinned_properties": expected})++ def test_patch_round_trips_heterogeneous_order_and_custom_projection(self) -> None:+ first_custom = self._custom_property()+ relationship = self._relationship()+ second_custom = self._custom_property()+ pinned_properties = [+ {"kind": "custom_property", "id": str(first_custom.id)},+ {"kind": "relationship", "id": str(relationship.id)},+ {"kind": "custom_property", "id": str(second_custom.id)},+ ]++ response = self.client.patch(self.endpoint, {"pinned_properties": pinned_properties}, format="json")++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.json(), {"pinned_properties": pinned_properties})+ self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": pinned_properties})+ config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).get(user_id=self.user.id)+ self.assertEqual(config.properties["pinned_properties"], pinned_properties)+ self.assertEqual(config.pinned_custom_property_definition_ids, [first_custom.id, second_custom.id])++ payload: dict[str, object] | None+ for payload in ({}, None):+ with self.subTest(payload=payload):+ unchanged = self.client.patch(self.endpoint, payload, format="json")+ self.assertEqual(unchanged.status_code, status.HTTP_200_OK, unchanged.json())+ self.assertEqual(unchanged.json(), {"pinned_properties": pinned_properties})+ self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": pinned_properties})++ cleared = self.client.patch(self.endpoint, {"pinned_properties": []}, format="json")++ self.assertEqual(cleared.status_code, status.HTTP_200_OK, cleared.json())+ self.assertEqual(cleared.json(), {"pinned_properties": []})+ config.refresh_from_db()+ self.assertEqual(config.properties["pinned_properties"], [])+ self.assertEqual(config.pinned_custom_property_definition_ids, [])++ def test_config_is_isolated_by_requesting_user_and_project(self) -> None:+ definition = self._custom_property()+ pinned = [{"kind": "custom_property", "id": str(definition.id)}]+ response = self.client.patch(self.endpoint, {"pinned_properties": pinned}, format="json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ other_user = User.objects.create_and_join(+ self.organization,+ "[email protected]",+ "testtest",+ )+ self.client.force_login(other_user)+ self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": []})++ other_team = Team.objects.create(organization=self.organization, name="Other project")+ self.client.force_login(self.user)+ other_team_endpoint = f"/api/projects/{other_team.id}/user_customer_analytics_config/@me/"+ self.assertEqual(self.client.get(other_team_endpoint).json(), {"pinned_properties": []})++ self.assertEqual(+ UserCustomerAnalyticsConfig.objects.unscoped().filter(team_id=self.team.id, user_id=self.user.id).count(),+ 1,+ )+ self.assertEqual(+ UserCustomerAnalyticsConfig.objects.unscoped().filter(team_id=self.team.id, user_id=other_user.id).count(),+ 1,+ )+ self.assertEqual(+ UserCustomerAnalyticsConfig.objects.unscoped().filter(team_id=other_team.id, user_id=self.user.id).count(),+ 1,+ )++ 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.+ # A raw id makes the lookup never match and the unique constraint reject every later call.+ environment = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")+ environment_endpoint = f"/api/projects/{environment.id}/user_customer_analytics_config/@me/"+ pinned = [{"kind": "custom_property", "id": str(self._custom_property().id)}]++ first = self.client.get(environment_endpoint)+ saved = self.client.patch(environment_endpoint, {"pinned_properties": pinned}, format="json")+ reread = self.client.get(environment_endpoint)++ self.assertEqual(first.status_code, status.HTTP_200_OK, first.json())+ self.assertEqual(saved.status_code, status.HTTP_200_OK, saved.json())+ self.assertEqual(reread.status_code, status.HTTP_200_OK, reread.json())+ self.assertEqual(reread.json(), {"pinned_properties": pinned})+ self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": pinned})+ config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).get(user_id=self.user.id)+ self.assertEqual(config.team_id, self.team.id)+ self.assertEqual(UserCustomerAnalyticsConfig.objects.unscoped().filter(user_id=self.user.id).count(), 1)++ def test_patch_rejects_invalid_references_on_the_pinned_properties_field(self) -> None:+ valid_custom = self._custom_property()+ person_custom = self._custom_property(target_type=TargetType.PERSON)+ relationship = self._relationship()+ other_team = Team.objects.create(organization=self.organization, name="Foreign project")+ foreign_custom = self._custom_property(team=other_team)+ valid_reference = {"kind": "custom_property", "id": str(valid_custom.id)}+ cases = [+ ("duplicates", [valid_reference, valid_reference], "duplicates"),+ ("wrong target", [{"kind": "custom_property", "id": str(person_custom.id)}], "account property"),+ ("relationship as custom", [{"kind": "custom_property", "id": str(relationship.id)}], "relationship"),+ ("custom as relationship", [{"kind": "relationship", "id": str(valid_custom.id)}], "custom property"),+ ("foreign team", [{"kind": "custom_property", "id": str(foreign_custom.id)}], "not found"),+ ("unknown", [{"kind": "relationship", "id": str(uuid4())}], "not found"),+ ("over limit", [valid_reference] * 51, "at most 50"),+ ]++ for label, pinned_properties, expected_detail in cases:+ with self.subTest(label):+ response = self.client.patch(+ self.endpoint,+ {"pinned_properties": pinned_properties},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertEqual(response.json()["attr"], "pinned_properties")+ self.assertIn(expected_detail, response.json()["detail"])++ self.assertFalse(+ UserCustomerAnalyticsConfig.objects.unscoped().filter(team_id=self.team.id, user_id=self.user.id).exists()+ )++ @parameterized.expand(+ [+ ("personal", "account:read", status.HTTP_403_FORBIDDEN),+ ("personal", "account:write", status.HTTP_200_OK),+ ("oauth", "account:read", status.HTTP_403_FORBIDDEN),+ ("oauth", "account:write", status.HTTP_200_OK),+ ("personal", "account:write", status.HTTP_403_FORBIDDEN, "child_only"),+ ("personal", "account:write", status.HTTP_200_OK, "parent_and_child"),+ ("oauth", "account:write", status.HTTP_403_FORBIDDEN, "child_only"),+ ("oauth", "account:write", status.HTTP_200_OK, "parent_and_child"),+ ]+ )+ def test_token_requires_write_scope(+ self, kind: str, scope: str, expected_status: int, environment_scope: str | None = None+ ) -> None:+ pinned = [{"kind": "custom_property", "id": str(self._custom_property().id)}]+ self.client.patch(self.endpoint, {"pinned_properties": pinned}, format="json")+ endpoint = self.endpoint+ scoped_teams: list[int] = []+ if environment_scope:+ environment = Team.objects.create(organization=self.organization, parent_team=self.team)+ endpoint = f"/api/projects/{environment.id}/user_customer_analytics_config/@me/"+ scoped_teams = [environment.id] + ([self.team.id] if environment_scope == "parent_and_child" else [])+ if kind == "personal":+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="Sidebar test",+ secure_value=hash_key_value(token),+ scopes=[scope],+ scoped_teams=scoped_teams,+ )+ else:+ application = OAuthApplication.objects.create(+ name="Sidebar test",+ user=self.user,+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ redirect_uris="https://example.com/callback",+ algorithm="RS256",+ )+ token = "pha_sidebar_test_token"+ OAuthAccessToken.objects.create(+ application=application,+ user=self.user,+ token=token,+ scope=scope,+ expires=timezone.now() + timedelta(hours=1),+ scoped_teams=scoped_teams,+ )+ self.client.logout()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")+ expected_read_status = status.HTTP_403_FORBIDDEN if environment_scope == "child_only" else status.HTTP_200_OK+ self.assertEqual(self.client.get(endpoint).status_code, expected_read_status)+ response = self.client.patch(endpoint, {"pinned_properties": []}, format="json")+ self.assertEqual(response.status_code, expected_status, response.json())+ expected_pins = [] if expected_status == status.HTTP_200_OK else pinned+ config = UserCustomerAnalyticsConfig.objects.for_team(self.team.id).get(user_id=self.user.id)+ self.assertEqual(config.properties["pinned_properties"], expected_pins)++ @parameterized.expand([("project",), ("customer_analytics",)])+ def test_child_access_does_not_grant_parent_access(self, resource: str) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ environment = Team.objects.create(organization=self.organization, parent_team=self.team)+ member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=member, organization=self.organization)+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=str(self.team.id) if resource == "project" else None,+ access_level="none",+ organization_member=membership,+ )+ AccessControl.objects.create(+ team=environment,+ resource=resource,+ resource_id=str(environment.id) if resource == "project" else None,+ access_level="member" if resource == "project" else "editor",+ organization_member=membership,+ )+ self.client.force_login(member)+ endpoint = f"/api/projects/{environment.id}/user_customer_analytics_config/@me/"+ self.assertEqual(self.client.get(endpoint).status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(+ self.client.patch(endpoint, {"pinned_properties": []}, format="json").status_code, status.HTTP_403_FORBIDDEN+ )+ self.assertFalse(UserCustomerAnalyticsConfig.objects.for_team(self.team.id).filter(user_id=member.id).exists())++ def test_session_viewer_can_personalize_their_sidebar(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ AccessControl.objects.create(+ team=self.team,+ resource="customer_analytics",+ resource_id=None,+ access_level="viewer",+ organization_member=OrganizationMembership.objects.get(user=viewer, organization=self.organization),+ )+ self.client.force_login(viewer)+ pinned = [{"kind": "custom_property", "id": str(self._custom_property().id)}]+ response = self.client.patch(self.endpoint, {"pinned_properties": pinned}, format="json")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(self.client.get(self.endpoint).json(), {"pinned_properties": pinned})diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 07feab423ce2..53bd096019f3 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -149,12 +149,18 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove`CUSTOMER_ANALYTICS_ACCOUNT_SCENE` changes account links from inline row expansion to `CustomerAnalyticsAccountScene` at `/customer_analytics/accounts/:accountId`.The keyed scene logic loads the account through `accountsRetrieve` when it mounts, including direct navigation between account routes.The scene renders the account logo in `SceneTitleSection`.-`AccountSidebar` holds editable tags and a Properties section. It sits flush with the scene's left edge and uses only a right border.+`AccountSidebar` holds editable tags and the account property configuration. It sits flush with the scene's left edge and uses only a right border.Tag edits save through `accountsPartialUpdate` and update optimistically. Only the latest save can replace or reload the account.+Pinned property preferences belong to the current user and project, never to an account. `accountSidebarConfigLogic({ projectId })` owns their load, draft, cancel, reorder, and save lifecycle through generated API functions. Keep that logic keyed by project so switching projects cannot briefly expose another project's preferences.+Omitting `pinned_properties` from a PATCH leaves existing pins unchanged; an explicit empty list clears them. Personal API keys and OAuth tokens need `account:write` for PATCH. Session-authenticated viewers can still personalize their own sidebar.+The configuration is one ordered list containing both account custom-property and relationship references. Definitions load across every API page, account custom properties are filtered by target, and the shared limit is 50. Missing definitions remain visible as a stale warning; opening the configurator omits them from its draft, so the next save cleans them up.+The empty Properties state uses the hedgehog and primary **Pin properties** action, with no gear. Once at least one reference is pinned, the gear opens the same configurator.+Property reference keys at the component boundary are namespaced as `custom:<uuid>` and `relationship:<uuid>`; persistence maps custom keys back to the API's `custom_property` kind. Preserve this mapping when adding property value loading.+Property configuration and property values have separate responsibilities: the configuration logic selects and orders definitions, while the property display path resolves account-specific values and handles edits.+On wide layouts, the sidebar and the active account-detail tab are separate vertical scroll containers. Narrow layouts retain the single stacked page scroll.It reuses `AccountDetailTabs` and `AccountNotesExpansion` with the expanded row, but mounts only the active tab so inactive detail tabs do not load data.Tables use borders in the detail scene and remain embedded in expanded rows.Configure tabs and Add view sit in the scene header. They open work-in-progress dialogs.-The Properties section stays visible when empty, and its gear opens the same work-in-progress dialog.The active tab is path-backed at `/customer_analytics/accounts/:accountId/:tab`.The bare path, unknown tabs, and tabs hidden by feature flags render Notes.@@ -349,6 +355,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics accounts relationship deleted` | `accountRelationshipsLogic` `deleteRelationship` listener (after the DELETE succeeds) | _(none - count only; relationship and account identifiers stay out)_ || `customer analytics account tags updated` | `accountsLogic` `updateAccountTags` listener (after the debounced PATCH succeeds; dispatched by the tags cell editor) | `tag_count` (tag names kept out — they can name customers) || `customer analytics account custom property updated` | `accountsLogic` `updateAccountCustomProperty` listener (after the custom-property-values write succeeds) | `display_type`, `workflow_reference` (property name and value stay out because they can contain customer data) |+| `customer analytics account pinned properties saved` | `accountSidebarConfigLogic` `persistPinnedPropertiesSuccess` listener (after the PATCH succeeds) | `pinned_count`, `custom_property_count`, `relationship_count` (counts only; definition names and ids stay out because property names can name customers) || `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` (incl. the "Copy link to account" row, `link_key: 'copy-account-link'`) | `link_key`, `has_destination` || `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` || `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` |diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.tsindex 5989a1c42e59..8faf31f14344 100644--- a/products/customer_analytics/frontend/components/Accounts/constants.ts+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts@@ -45,6 +45,7 @@ export const AccountsEvents = {RelationshipDeleted: 'customer analytics accounts relationship deleted',TagsUpdated: 'customer analytics account tags updated',CustomPropertyUpdated: 'customer analytics account custom property updated',+ PinnedPropertiesSaved: 'customer analytics account pinned properties saved',LinkClicked: 'customer analytics account link clicked',NoteClicked: 'customer analytics account note clicked',NoteCreated: 'customer analytics accounts note created',diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex be2bc6646f0e..d81961ef869c 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -3930,6 +3930,38 @@ export interface PatchedGroupUsageMetricApi {math_property?: string | null}+/**+ * * `custom_property` - Custom property+ * * `relationship` - Relationship+ */+export type PinnedAccountPropertyKindEnumApi =+ (typeof PinnedAccountPropertyKindEnumApi)[keyof typeof PinnedAccountPropertyKindEnumApi]++export const PinnedAccountPropertyKindEnumApi = {+ CustomProperty: 'custom_property',+ Relationship: 'relationship',+} as const++export interface PinnedAccountPropertyApi {+ /** Definition type for this pinned account property.+ *+ * * `custom_property` - Custom property+ * * `relationship` - Relationship */+ kind: PinnedAccountPropertyKindEnumApi+ /** Team-scoped custom property or relationship definition UUID. */+ id: string+}++export interface UserCustomerAnalyticsConfigApi {+ /** Account properties pinned in sidebar display order. */+ readonly pinned_properties: readonly PinnedAccountPropertyApi[]+}++export interface PatchedUserCustomerAnalyticsConfigUpdateApi {+ /** Complete ordered list of account properties to pin. Omit to keep the current pins; pass an empty list to clear them. */+ pinned_properties?: PinnedAccountPropertyApi[]+}+export type CustomerAnalyticsExternalAccountsRetrieveParams = {/*** When true, return only accounts with at least one active relationship assignment to a current member of the project's organization.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 6d4e390d261d..7a334ffc7075 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -108,8 +108,10 @@ import type {PatchedFeatureRequestProductAreaApi,PatchedFeatureRequestUpdateApi,PatchedGroupUsageMetricApi,+ PatchedUserCustomerAnalyticsConfigUpdateApi,QueryStatusResponseApi,SupportTicketApi,+ UserCustomerAnalyticsConfigApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -2341,3 +2343,44 @@ export const groupsTypesMetricsDestroy = async (method: 'DELETE',})}++export const getUserCustomerAnalyticsConfigRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/user_customer_analytics_config/${id}/`+}++/**+ * Get the requesting user's account sidebar configuration for this project. The first read creates an empty configuration row.+ * @summary Get account sidebar configuration+ */+export const userCustomerAnalyticsConfigRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<UserCustomerAnalyticsConfigApi> => {+ return apiMutator<UserCustomerAnalyticsConfigApi>(getUserCustomerAnalyticsConfigRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getUserCustomerAnalyticsConfigPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/user_customer_analytics_config/${id}/`+}++/**+ * Replace the requesting user's ordered account sidebar properties when pinned_properties is provided. Omitting pinned_properties leaves the configuration unchanged. At most 50 account custom properties and relationships can be pinned.+ * @summary Update account sidebar configuration+ */+export const userCustomerAnalyticsConfigPartialUpdate = async (+ projectId: string,+ id: string,+ patchedUserCustomerAnalyticsConfigUpdateApi?: PatchedUserCustomerAnalyticsConfigUpdateApi,+ options?: RequestInit+): Promise<UserCustomerAnalyticsConfigApi> => {+ return apiMutator<UserCustomerAnalyticsConfigApi>(getUserCustomerAnalyticsConfigPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedUserCustomerAnalyticsConfigUpdateApi),+ })+}diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex ec10daac189e..1db598293789 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -1631,3 +1631,26 @@ export const GroupsTypesMetricsPartialUpdateBody = /* @__PURE__ */ zod.object({'Required when `math` is `sum`; must be empty when `math` is `count`. For events metrics this is an event property name. For data warehouse metrics this is the column name (or HogQL expression) to sum on the DW table.'),})++/**+ * Replace the requesting user's ordered account sidebar properties when pinned_properties is provided. Omitting pinned_properties leaves the configuration unchanged. At most 50 account custom properties and relationships can be pinned.+ * @summary Update account sidebar configuration+ */+export const UserCustomerAnalyticsConfigPartialUpdateBody = /* @__PURE__ */ zod.object({+ pinned_properties: zod+ .array(+ zod.object({+ kind: zod+ .enum(['custom_property', 'relationship'])+ .describe('\* `custom_property` - Custom property\n\* `relationship` - Relationship')+ .describe(+ 'Definition type for this pinned account property.\n\n\* `custom_property` - Custom property\n\* `relationship` - Relationship'+ ),+ id: zod.uuid().describe('Team-scoped custom property or relationship definition UUID.'),+ })+ )+ .optional()+ .describe(+ 'Complete ordered list of account properties to pin. Omit to keep the current pins; pass an empty list to clear them.'+ ),+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsxindex e47b901c0165..e019f0e4ad9d 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx@@ -1,24 +1,74 @@import { useActions, useValues } from 'kea'import { IconGear } from '@posthog/icons'-import { LemonButton, LemonDivider } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonDivider, LemonSkeleton } from '@posthog/lemon-ui'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'+import { projectLogic } from 'scenes/projectLogic'import { tagsModel } from '~/models/tagsModel'import type { AccountApi } from '../../generated/api.schemas'-import { openAccountDetailWorkInProgress } from './accountDetailWorkInProgress'+import {+ accountSidebarConfigLogic,+ configuratorKeysToPinnedProperties,+ pinnedPropertyToConfiguratorKey,+} from './accountSidebarConfigLogic'+import { AccountPinnedPropertiesEmptyState } from './components/AccountPinnedProperties'+import { AccountPropertyConfigurator } from './components/AccountPropertyConfigurator'+import type { AccountPropertyOption } from './components/accountPropertyTypes'import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'export function AccountSidebar({ account }: { account: AccountApi }): JSX.Element {const { tagsSaving } = useValues(customerAnalyticsAccountSceneLogic)const { updateTags } = useActions(customerAnalyticsAccountSceneLogic)const { tags: tagsAvailable } = useValues(tagsModel)+ const { currentProjectId } = useValues(projectLogic)+ const configLogic = accountSidebarConfigLogic({ projectId: currentProjectId ?? 0 })+ const {+ availableDefinitions,+ availableDefinitionsLoadFailed,+ canSavePinnedProperties,+ config,+ configLoadFailed,+ configLoading,+ draftPinnedProperties,+ isConfiguring,+ stalePinnedProperties,+ } = useValues(configLogic)+ const {+ beginConfiguring,+ cancelConfiguring,+ loadAvailableDefinitions,+ loadConfig,+ savePinnedProperties,+ setDraftPinnedProperties,+ } = useActions(configLogic)++ const configurationLoadFailed = configLoadFailed || availableDefinitionsLoadFailed+ const configurationLoading = !configurationLoadFailed && (config === null || availableDefinitions === null)+ const pinnedPropertyCount = config?.pinned_properties.length ?? 0+ const propertyOptions: AccountPropertyOption[] = [+ ...(availableDefinitions?.customProperties ?? []).map((definition) => ({+ key: pinnedPropertyToConfiguratorKey({ kind: 'custom_property', id: definition.id }),+ label: definition.name,+ kind: 'custom' as const,+ })),+ ...(availableDefinitions?.relationships ?? []).map((definition) => ({+ key: pinnedPropertyToConfiguratorKey({ kind: 'relationship', id: definition.id }),+ label: definition.name,+ kind: 'relationship' as const,+ })),+ ]++ const reloadConfiguration = (): void => {+ loadConfig()+ loadAvailableDefinitions()+ }return (<aside- className="w-full shrink-0 @max-[60rem]:border @max-[60rem]:rounded border-r rounded-r bg-surface-primary flex flex-col @min-[60rem]/account-detail:w-60"+ className="w-full shrink-0 @max-[60rem]:border @max-[60rem]:rounded border-r rounded-r bg-surface-primary flex flex-col @min-[60rem]/account-detail:h-full @min-[60rem]/account-detail:min-h-0 @min-[60rem]/account-detail:w-60 @min-[60rem]/account-detail:overflow-y-auto"data-attr="account-sidebar"><div className="flex flex-col gap-1 p-4" data-attr="account-rail-tags">@@ -32,21 +82,59 @@ export function AccountSidebar({ account }: { account: AccountApi }): JSX.Elemen/></div><LemonDivider className="my-0" />- <div className="flex flex-col gap-3 p-4" data-attr="account-rail-properties">- <div className="flex items-center gap-2">+ <div className="flex flex-col gap-3 py-4" data-attr="account-rail-properties">+ <div className="flex items-center gap-2 px-4"><span className="secondary text-secondary">Properties</span>- <LemonButton- size="xsmall"- icon={<IconGear />}- className="ml-auto"- tooltip="Configure properties"- aria-label="Configure properties"- onClick={() => openAccountDetailWorkInProgress('Configure properties')}- data-attr="account-detail-configure-properties"- />+ {!configurationLoading && !configurationLoadFailed && pinnedPropertyCount > 0 ? (+ <LemonButton+ size="xsmall"+ icon={<IconGear />}+ className="ml-auto"+ tooltip="Choose pinned properties"+ aria-label="Configure pinned properties"+ onClick={beginConfiguring}+ data-attr="account-configure-pinned-properties"+ />+ ) : null}</div>- <span className="text-xs text-muted">No properties pinned.</span>+ {configurationLoading ? (+ <div className="flex flex-col gap-2 px-4" data-attr="account-pinned-properties-loading">+ <LemonSkeleton className="h-4 w-full" />+ <LemonSkeleton className="h-4 w-3/4" />+ </div>+ ) : configurationLoadFailed ? (+ <div className="px-4">+ <LemonBanner type="error" action={{ children: 'Try again', onClick: reloadConfiguration }}>+ Couldn't load pinned properties.+ </LemonBanner>+ </div>+ ) : pinnedPropertyCount === 0 ? (+ <AccountPinnedPropertiesEmptyState onConfigure={beginConfiguring} />+ ) : (+ <div className="flex flex-col gap-3 px-4">+ <span className="text-xs text-muted">+ {pinnedPropertyCount === 1+ ? '1 property pinned.'+ : `${pinnedPropertyCount} properties pinned.`}+ </span>+ {stalePinnedProperties.length > 0 ? (+ <LemonBanner type="warning">+ Some pinned properties are no longer available. Update your pins to remove them.+ </LemonBanner>+ ) : null}+ </div>+ )}</div>+ <AccountPropertyConfigurator+ isOpen={isConfiguring}+ options={propertyOptions}+ pinnedPropertyKeys={draftPinnedProperties.map(pinnedPropertyToConfiguratorKey)}+ onChange={(keys) => setDraftPinnedProperties(configuratorKeysToPinnedProperties(keys))}+ onSave={() => savePinnedProperties()}+ onCancel={cancelConfiguring}+ saving={configLoading && config !== null}+ saveDisabledReason={!configLoading && !canSavePinnedProperties ? 'No changes to save' : undefined}+ /></aside>)}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsxindex a7b932375ce2..ccf720be3538 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx@@ -10,6 +10,9 @@ const ACCOUNT_ID = '11111111-2222-4333-8444-555555555555'const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'const ACCOUNT_ICON_ENDPOINT = 'api/projects/:team_id/accounts/icon/'+const ACCOUNT_SIDEBAR_CONFIG_ENDPOINT = 'api/projects/:team_id/user_customer_analytics_config/@me/'+const CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/custom_property_definitions/'+const RELATIONSHIP_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/account_relationship_definitions/'const account = {id: ACCOUNT_ID,@@ -84,6 +87,42 @@ 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: [] },+ [CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT]: {+ count: 1,+ results: [+ {+ id: '22222222-3333-4444-8555-666666666666',+ name: 'Annual recurring revenue',+ description: null,+ display_type: 'currency',+ target_type: 'account',+ is_big_number: false,+ is_canonical: false,+ options: null,+ source: null,+ created_at: '2026-05-10T10:00:00Z',+ created_by: 1,+ updated_at: '2026-05-20T14:30:00Z',+ references: [],+ has_workflow_reference: false,+ },+ ],+ },+ [RELATIONSHIP_DEFINITIONS_ENDPOINT]: {+ count: 1,+ results: [+ {+ id: '33333333-4444-4555-8666-777777777777',+ name: 'Customer success manager',+ description: null,+ is_single_holder: true,+ },+ ],+ },+ },+ patch: {+ [ACCOUNT_SIDEBAR_CONFIG_ENDPOINT]: async ({ request }) => [200, await request.json()],},}),],diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsxindex 35d8208521fe..d06ca494cb57 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx@@ -100,9 +100,12 @@ function CustomerAnalyticsAccountSceneContent(): JSX.Element {/><SceneDivider /><div className="@container/account-detail flex flex-1 min-h-0 overflow-y-auto @min-[60rem]:-mt-4 @min-[60rem]:-ml-4">- <div className="flex min-h-full w-full flex-col gap-4 @min-[60rem]/account-detail:flex-row">+ <div className="flex min-h-full w-full flex-col gap-4 @min-[60rem]/account-detail:h-full @min-[60rem]/account-detail:min-h-0 @min-[60rem]/account-detail:flex-row"><AccountSidebar account={account} />- <main className="flex-1 min-w-0" data-attr="account-detail-tabs">+ <main+ className="flex-1 min-w-0 @min-[60rem]/account-detail:h-full @min-[60rem]/account-detail:min-h-0 @min-[60rem]/account-detail:overflow-y-auto"+ data-attr="account-detail-tabs"+ ><AccountDetailTabsaccountId={account.id}externalId={account.external_id ?? ''}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.tsnew file mode 100644index 000000000000..30234f36b554--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.test.ts@@ -0,0 +1,298 @@+import { waitFor } from '@testing-library/react'+import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'++import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'+import type {+ AccountRelationshipDefinitionApi,+ CustomPropertyDefinitionApi,+ UserCustomerAnalyticsConfigApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import {+ accountSidebarConfigLogic,+ configuratorKeysToPinnedProperties,+ pinnedPropertyToConfiguratorKey,+} from './accountSidebarConfigLogic'+import { MAX_PINNED_ACCOUNT_PROPERTIES } from './components/accountPropertyTypes'++const CONFIG_URL = '/api/projects/:team_id/user_customer_analytics_config/@me/'+const CUSTOM_PROPERTIES_URL = '/api/projects/:team_id/custom_property_definitions/'+const RELATIONSHIPS_URL = '/api/projects/:team_id/account_relationship_definitions/'++const buildCustomProperty = (overrides: Partial<CustomPropertyDefinitionApi> = {}): CustomPropertyDefinitionApi =>+ ({+ id: 'custom-1',+ name: 'ARR',+ description: null,+ display_type: 'currency',+ target_type: 'account',+ is_big_number: false,+ is_canonical: false,+ options: null,+ source: null,+ created_at: '2026-01-01T00:00:00Z',+ created_by: 1,+ updated_at: '2026-01-01T00:00:00Z',+ references: [],+ has_workflow_reference: false,+ ...overrides,+ }) as CustomPropertyDefinitionApi++const buildRelationship = (+ overrides: Partial<AccountRelationshipDefinitionApi> = {}+): AccountRelationshipDefinitionApi => ({+ id: 'relationship-1',+ name: 'CSM',+ description: null,+ is_single_holder: true,+ ...overrides,+})++const defaultMocks = (+ config: UserCustomerAnalyticsConfigApi = { pinned_properties: [] }+): Parameters<typeof useMocks>[0] => ({+ get: {+ [CONFIG_URL]: config,+ [CUSTOM_PROPERTIES_URL]: { count: 1, results: [buildCustomProperty()] },+ [RELATIONSHIPS_URL]: { count: 1, results: [buildRelationship()] },+ },+ patch: {+ [CONFIG_URL]: async ({ request }) => await request.json(),+ },+})++describe('accountSidebarConfigLogic', () => {+ let logic: ReturnType<typeof accountSidebarConfigLogic.build>++ const mountLogic = async (): Promise<void> => {+ logic = accountSidebarConfigLogic({ projectId: 1 })+ logic.mount()+ await expectLogic(logic)+ .toDispatchActionsInAnyOrder(['loadConfigSuccess', 'loadAvailableDefinitionsSuccess'])+ .toFinishAllListeners()+ }++ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ resumeKeaLoadersErrors()+ jest.restoreAllMocks()+ })++ it('keys state by project and converts heterogeneous configurator keys', () => {+ const firstProjectLogic = accountSidebarConfigLogic({ projectId: 1 })+ const secondProjectLogic = accountSidebarConfigLogic({ projectId: 2 })++ expect(firstProjectLogic.key).not.toEqual(secondProjectLogic.key)+ expect(pinnedPropertyToConfiguratorKey({ kind: 'custom_property', id: 'shared-id' })).toBe('custom:shared-id')+ expect(pinnedPropertyToConfiguratorKey({ kind: 'relationship', id: 'shared-id' })).toBe(+ 'relationship:shared-id'+ )+ expect(+ configuratorKeysToPinnedProperties([+ 'relationship:relationship-1',+ 'custom:custom-1',+ 'unknown:ignored',+ 'custom:',+ ])+ ).toEqual([+ { kind: 'relationship', id: 'relationship-1' },+ { kind: 'custom_property', id: 'custom-1' },+ ])+ })++ it('loads every definition page and keeps account custom properties only', async () => {+ const customOffsets: number[] = []+ const relationshipOffsets: number[] = []+ useMocks({+ get: {+ [CONFIG_URL]: { pinned_properties: [] },+ [CUSTOM_PROPERTIES_URL]: ({ request }) => {+ const offset = Number(new URL(request.url).searchParams.get('offset'))+ customOffsets.push(offset)+ return offset === 0+ ? {+ count: 101,+ results: Array.from({ length: 100 }, (_, index) =>+ buildCustomProperty({ id: `custom-${index}` })+ ),+ }+ : {+ count: 101,+ results: [buildCustomProperty({ id: 'person-1', target_type: 'person' })],+ }+ },+ [RELATIONSHIPS_URL]: ({ request }) => {+ const offset = Number(new URL(request.url).searchParams.get('offset'))+ relationshipOffsets.push(offset)+ return offset === 0+ ? {+ count: 101,+ results: Array.from({ length: 100 }, (_, index) =>+ buildRelationship({ id: `relationship-${index}` })+ ),+ }+ : { count: 101, results: [buildRelationship({ id: 'relationship-last' })] }+ },+ },+ })++ await mountLogic()++ expect(customOffsets).toEqual([0, 100])+ expect(relationshipOffsets).toEqual([0, 100])+ expect(logic.values.availableDefinitions?.customProperties).toHaveLength(100)+ expect(logic.values.availableDefinitions?.relationships).toHaveLength(101)+ })++ it('exposes configuration load failures for an inline retry state', async () => {+ silenceKeaLoadersErrors()+ useMocks({+ get: {+ [CONFIG_URL]: () => [500, { detail: 'Could not load configuration.' }],+ [CUSTOM_PROPERTIES_URL]: { count: 0, results: [] },+ [RELATIONSHIPS_URL]: { count: 0, results: [] },+ },+ })+ logic = accountSidebarConfigLogic({ projectId: 1 })+ logic.mount()++ await expectLogic(logic)+ .toDispatchActionsInAnyOrder(['loadConfigFailure', 'loadAvailableDefinitionsSuccess'])+ .toFinishAllListeners()++ expect(logic.values.configLoadFailed).toBe(true)+ expect(logic.values.availableDefinitionsLoadFailed).toBe(false)+ })++ it('resolves pins in stored order and exposes stale references', async () => {+ useMocks(+ defaultMocks({+ pinned_properties: [+ { kind: 'custom_property', id: 'custom-1' },+ { kind: 'relationship', id: 'relationship-1' },+ { kind: 'custom_property', id: 'missing' },+ ],+ })+ )++ await mountLogic()++ expect(logic.values.resolvedPinnedProperties.map(({ reference }) => reference.id)).toEqual([+ 'custom-1',+ 'relationship-1',+ ])+ expect(logic.values.stalePinnedProperties).toEqual([{ kind: 'custom_property', id: 'missing' }])+ })++ it('supports configure, toggle, reorder, cancel, and the 50-property limit', async () => {+ useMocks(defaultMocks({ pinned_properties: [{ kind: 'custom_property', id: 'custom-1' }] }))+ await mountLogic()++ logic.actions.beginConfiguring()+ logic.actions.togglePinnedProperty({ kind: 'relationship', id: 'relationship-1' })+ logic.actions.movePinnedProperty(1, 0)+ expect(logic.values.draftPinnedProperties.map(({ id }) => id)).toEqual(['relationship-1', 'custom-1'])++ logic.actions.cancelConfiguring()+ expect(logic.values.isConfiguring).toBe(false)+ expect(logic.values.draftPinnedProperties).toEqual([{ kind: 'custom_property', id: 'custom-1' }])++ const fullDraft = Array.from({ length: MAX_PINNED_ACCOUNT_PROPERTIES }, (_, index) => ({+ kind: 'custom_property' as const,+ id: `custom-${index}`,+ }))+ logic.actions.setDraftPinnedProperties(fullDraft)+ logic.actions.togglePinnedProperty({ kind: 'custom_property', id: 'overflow' })+ expect(logic.values.draftPinnedProperties).toEqual(fullDraft)+ expect(logic.values.draftPinLimitReached).toBe(true)+ })++ it('saves once while a request is active and adopts the server response', async () => {+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)+ let releasePatch: (() => void) | undefined+ let patchCount = 0+ let submittedBody: unknown+ useMocks({+ ...defaultMocks({ pinned_properties: [{ kind: 'custom_property', id: 'custom-1' }] }),+ patch: {+ [CONFIG_URL]: async ({ request }) => {+ patchCount += 1+ submittedBody = await request.json()+ await new Promise<void>((resolve) => {+ releasePatch = resolve+ })+ return submittedBody+ },+ },+ })+ await mountLogic()+ logic.actions.beginConfiguring()+ logic.actions.togglePinnedProperty({ kind: 'relationship', id: 'relationship-1' })++ await expectLogic(logic, () => logic.actions.savePinnedProperties()).toDispatchActions([+ 'persistPinnedProperties',+ ])+ await waitFor(() => expect(patchCount).toBe(1))+ await expectLogic(logic, () => logic.actions.savePinnedProperties()).toNotHaveDispatchedActions([+ 'persistPinnedProperties',+ ])+ releasePatch?.()+ await expectLogic(logic).toDispatchActions(['persistPinnedPropertiesSuccess']).toFinishAllListeners()++ expect(patchCount).toBe(1)+ expect(submittedBody).toEqual({+ pinned_properties: [+ { kind: 'custom_property', id: 'custom-1' },+ { kind: 'relationship', id: 'relationship-1' },+ ],+ })+ expect(logic.values.config?.pinned_properties).toEqual(+ (submittedBody as UserCustomerAnalyticsConfigApi).pinned_properties+ )+ expect(logic.values.isConfiguring).toBe(false)+ expect(captureSpy).toHaveBeenCalledWith(AccountsEvents.PinnedPropertiesSaved, {+ pinned_count: 2,+ custom_property_count: 1,+ relationship_count: 1,+ })+ })++ it('keeps the draft open for retry and shows one notification when saving fails', async () => {+ silenceKeaLoadersErrors()+ const toastSpy = jest.spyOn(lemonToast, 'error')+ const captureSpy = jest.spyOn(posthog, 'capture')+ useMocks({+ ...defaultMocks({ pinned_properties: [{ kind: 'custom_property', id: 'custom-1' }] }),+ patch: { [CONFIG_URL]: () => [500, { detail: 'Could not save pinned properties.' }] },+ })+ await mountLogic()+ logic.actions.beginConfiguring()+ logic.actions.togglePinnedProperty({ kind: 'relationship', id: 'relationship-1' })+ logic.actions.movePinnedProperty(1, 0)++ await expectLogic(logic, () => logic.actions.savePinnedProperties())+ .toDispatchActions(['persistPinnedPropertiesFailure'])+ .toFinishAllListeners()++ expect(logic.values.config?.pinned_properties).toEqual([{ kind: 'custom_property', id: 'custom-1' }])+ expect(logic.values.draftPinnedProperties).toEqual([+ { kind: 'relationship', id: 'relationship-1' },+ { kind: 'custom_property', id: 'custom-1' },+ ])+ expect(logic.values.isConfiguring).toBe(true)+ expect(logic.values.canSavePinnedProperties).toBe(true)+ expect(toastSpy).toHaveBeenCalledTimes(1)+ expect(captureSpy).not.toHaveBeenCalledWith(AccountsEvents.PinnedPropertiesSaved, expect.anything())+ })+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.tsnew file mode 100644index 000000000000..7e4fbf97ef82--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.ts@@ -0,0 +1,421 @@+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'+import * as api from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountRelationshipDefinitionApi,+ CustomPropertyDefinitionApi,+ PinnedAccountPropertyApi,+ UserCustomerAnalyticsConfigApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { MAX_PINNED_ACCOUNT_PROPERTIES } from './components/accountPropertyTypes'++export { MAX_PINNED_ACCOUNT_PROPERTIES } from './components/accountPropertyTypes'+const DEFINITION_PAGE_SIZE = 100+// The requesting user always owns this configuration, so the endpoint accepts only this fixed lookup token.+const CURRENT_USER_CONFIG_ID = '@me'++export type PinnedAccountProperty = PinnedAccountPropertyApi++export interface AccountSidebarConfigLogicProps {+ projectId: number+}++export type ResolvedPinnedAccountProperty =+ | {+ kind: 'custom_property'+ reference: PinnedAccountProperty+ definition: CustomPropertyDefinitionApi+ }+ | {+ kind: 'relationship'+ reference: PinnedAccountProperty+ definition: AccountRelationshipDefinitionApi+ }++export interface AvailableDefinitions {+ customProperties: CustomPropertyDefinitionApi[]+ relationships: AccountRelationshipDefinitionApi[]+}++interface PinnedPropertyResolution {+ resolved: ResolvedPinnedAccountProperty[]+ stale: PinnedAccountProperty[]+}++export function pinnedPropertyToConfiguratorKey(reference: PinnedAccountProperty): string {+ const kind = reference.kind === 'custom_property' ? 'custom' : 'relationship'+ return `${kind}:${reference.id}`+}++export function configuratorKeysToPinnedProperties(keys: string[]): PinnedAccountProperty[] {+ return keys.flatMap((key): PinnedAccountProperty[] => {+ const separatorIndex = key.indexOf(':')+ if (separatorIndex < 1 || separatorIndex === key.length - 1) {+ return []+ }+ const kind = key.slice(0, separatorIndex)+ const id = key.slice(separatorIndex + 1)+ if (kind === 'custom') {+ return [{ kind: 'custom_property', id }]+ }+ if (kind === 'relationship') {+ return [{ kind: 'relationship', id }]+ }+ return []+ })+}++const referenceKey = (reference: PinnedAccountProperty): string => `${reference.kind}:${reference.id}`++const pinnedPropertiesEqual = (+ first: readonly PinnedAccountProperty[],+ second: readonly PinnedAccountProperty[]+): boolean =>+ first.length === second.length &&+ first.every((reference, index) => referenceKey(reference) === referenceKey(second[index]))++const loadEveryPage = async <T>(+ loadPage: (params: { limit: number; offset: number }) => Promise<{ count: number; results: T[] }>+): Promise<T[]> => {+ const results: T[] = []+ let offset = 0+ let count = 1+ while (offset < count) {+ const page = await loadPage({ limit: DEFINITION_PAGE_SIZE, offset })+ count = page.count+ results.push(...page.results)+ if (page.results.length === 0) {+ break+ }+ offset += page.results.length+ }+ return results+}++const resolvePinnedProperties = (+ references: readonly PinnedAccountProperty[],+ definitions: AvailableDefinitions+): PinnedPropertyResolution => {+ const customPropertiesById = new Map(definitions.customProperties.map((definition) => [definition.id, definition]))+ const relationshipsById = new Map(definitions.relationships.map((definition) => [definition.id, definition]))+ const resolved: ResolvedPinnedAccountProperty[] = []+ const stale: PinnedAccountProperty[] = []++ for (const reference of references) {+ if (reference.kind === 'custom_property') {+ const definition = customPropertiesById.get(reference.id)+ if (definition) {+ resolved.push({ kind: reference.kind, reference, definition })+ } else {+ stale.push(reference)+ }+ } else {+ const definition = relationshipsById.get(reference.id)+ if (definition) {+ resolved.push({ kind: reference.kind, reference, definition })+ } else {+ stale.push(reference)+ }+ }+ }+ return { resolved, stale }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountSidebarConfigLogicValues {+ availableDefinitions: AvailableDefinitions | null+ availableDefinitionsLoadFailed: boolean+ availableDefinitionsLoading: boolean+ canSavePinnedProperties: boolean+ config: UserCustomerAnalyticsConfigApi | null+ configLoadFailed: boolean+ configLoading: boolean+ draftPinLimitReached: boolean+ draftPinnedProperties: PinnedAccountProperty[]+ isConfiguring: boolean+ pinnedPropertyResolution: PinnedPropertyResolution+ resolvedPinnedProperties: ResolvedPinnedAccountProperty[]+ stalePinnedProperties: PinnedAccountProperty[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountSidebarConfigLogicActions {+ beginConfiguring: () => {+ value: true+ }+ cancelConfiguring: () => {+ value: true+ }+ loadAvailableDefinitions: () => any+ loadAvailableDefinitionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadAvailableDefinitionsSuccess: (+ availableDefinitions: AvailableDefinitions,+ payload?: any+ ) => {+ availableDefinitions: AvailableDefinitions+ payload?: any+ }+ loadConfig: () => any+ loadConfigFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadConfigSuccess: (+ config: UserCustomerAnalyticsConfigApi,+ payload?: any+ ) => {+ config: UserCustomerAnalyticsConfigApi+ payload?: any+ }+ movePinnedProperty: (+ fromIndex: number,+ toIndex: number+ ) => {+ fromIndex: number+ toIndex: number+ }+ persistPinnedProperties: ({ pinnedProperties }: { pinnedProperties: PinnedAccountProperty[] }) => {+ pinnedProperties: PinnedAccountProperty[]+ }+ persistPinnedPropertiesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ persistPinnedPropertiesSuccess: (+ config: UserCustomerAnalyticsConfigApi,+ payload?: {+ pinnedProperties: PinnedAccountProperty[]+ }+ ) => {+ config: UserCustomerAnalyticsConfigApi+ payload?: {+ pinnedProperties: PinnedAccountProperty[]+ }+ }+ savePinnedProperties: () => {+ value: true+ }+ setDraftPinnedProperties: (pinnedProperties: PinnedAccountProperty[]) => {+ pinnedProperties: PinnedAccountPropertyApi[]+ }+ togglePinnedProperty: (pinnedProperty: PinnedAccountProperty) => {+ pinnedProperty: PinnedAccountPropertyApi+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface accountSidebarConfigLogicMeta {+ key: number+ __keaTypeGenInternalSelectorTypes: {+ pinnedPropertyResolution: (+ config: UserCustomerAnalyticsConfigApi | null,+ availableDefinitions: AvailableDefinitions | null+ ) => PinnedPropertyResolution+ resolvedPinnedProperties: (+ pinnedPropertyResolution: PinnedPropertyResolution+ ) => ResolvedPinnedAccountProperty[]+ stalePinnedProperties: (pinnedPropertyResolution: PinnedPropertyResolution) => PinnedAccountProperty[]+ draftPinLimitReached: (draftPinnedProperties: PinnedAccountPropertyApi[]) => boolean+ canSavePinnedProperties: (+ isConfiguring: boolean,+ config: UserCustomerAnalyticsConfigApi | null,+ draftPinnedProperties: PinnedAccountPropertyApi[],+ configLoading: boolean+ ) => boolean+ }+}++export type accountSidebarConfigLogicType = MakeLogicType<+ accountSidebarConfigLogicValues,+ accountSidebarConfigLogicActions,+ AccountSidebarConfigLogicProps,+ accountSidebarConfigLogicMeta+>++export const accountSidebarConfigLogic = kea<accountSidebarConfigLogicType>([+ path([+ 'products',+ 'customer_analytics',+ 'frontend',+ 'scenes',+ 'CustomerAnalyticsAccountScene',+ 'accountSidebarConfigLogic',+ ]),+ props({} as AccountSidebarConfigLogicProps),+ key((props) => props.projectId),+ actions({+ beginConfiguring: true,+ cancelConfiguring: true,+ setDraftPinnedProperties: (pinnedProperties: PinnedAccountProperty[]) => ({ pinnedProperties }),+ togglePinnedProperty: (pinnedProperty: PinnedAccountProperty) => ({ pinnedProperty }),+ movePinnedProperty: (fromIndex: number, toIndex: number) => ({ fromIndex, toIndex }),+ savePinnedProperties: true,+ }),+ loaders(({ props }) => ({+ config: [+ null as UserCustomerAnalyticsConfigApi | null,+ {+ loadConfig: async (): Promise<UserCustomerAnalyticsConfigApi> =>+ await api.userCustomerAnalyticsConfigRetrieve(String(props.projectId), CURRENT_USER_CONFIG_ID),+ persistPinnedProperties: async ({+ pinnedProperties,+ }: {+ pinnedProperties: PinnedAccountProperty[]+ }): Promise<UserCustomerAnalyticsConfigApi> =>+ await api.userCustomerAnalyticsConfigPartialUpdate(+ String(props.projectId),+ CURRENT_USER_CONFIG_ID,+ {+ pinned_properties: pinnedProperties.map(({ kind, id }) => ({ kind, id })),+ }+ ),+ },+ ],+ availableDefinitions: [+ null as AvailableDefinitions | null,+ {+ loadAvailableDefinitions: async (): Promise<AvailableDefinitions> => {+ const projectId = String(props.projectId)+ const [customProperties, relationships] = await Promise.all([+ loadEveryPage((params) => api.customPropertyDefinitionsList(projectId, params)),+ loadEveryPage((params) => api.accountRelationshipDefinitionsList(projectId, params)),+ ])+ return {+ customProperties: customProperties.filter(({ target_type }) => target_type === 'account'),+ relationships,+ }+ },+ },+ ],+ })),+ reducers({+ configLoadFailed: [+ false,+ {+ loadConfig: () => false,+ loadConfigSuccess: () => false,+ loadConfigFailure: () => true,+ },+ ],+ availableDefinitionsLoadFailed: [+ false,+ {+ loadAvailableDefinitions: () => false,+ loadAvailableDefinitionsSuccess: () => false,+ loadAvailableDefinitionsFailure: () => true,+ },+ ],+ isConfiguring: [+ false,+ {+ beginConfiguring: () => true,+ cancelConfiguring: () => false,+ persistPinnedPropertiesSuccess: () => false,+ // A failed save keeps the selector open, so the user can retry or correct the+ // draft that the request did not store.+ },+ ],+ draftPinnedProperties: [+ [] as PinnedAccountProperty[],+ {+ setDraftPinnedProperties: (_, { pinnedProperties }) => [...pinnedProperties],+ togglePinnedProperty: (state, { pinnedProperty }) => {+ const existingIndex = state.findIndex(+ (reference) => referenceKey(reference) === referenceKey(pinnedProperty)+ )+ if (existingIndex >= 0) {+ return state.filter((_, index) => index !== existingIndex)+ }+ return state.length < MAX_PINNED_ACCOUNT_PROPERTIES ? [...state, pinnedProperty] : state+ },+ movePinnedProperty: (state, { fromIndex, toIndex }) => {+ if (fromIndex === toIndex || !state[fromIndex] || toIndex < 0 || toIndex >= state.length) {+ return state+ }+ const reordered = [...state]+ const [moved] = reordered.splice(fromIndex, 1)+ reordered.splice(toIndex, 0, moved)+ return reordered+ },+ },+ ],+ }),+ selectors({+ pinnedPropertyResolution: [+ (s) => [s.config, s.availableDefinitions],+ (+ config: UserCustomerAnalyticsConfigApi | null,+ definitions: AvailableDefinitions | null+ ): PinnedPropertyResolution =>+ config && definitions+ ? resolvePinnedProperties(config.pinned_properties, definitions)+ : { resolved: [], stale: [] },+ ],+ resolvedPinnedProperties: [+ (s) => [s.pinnedPropertyResolution],+ (resolution: PinnedPropertyResolution): ResolvedPinnedAccountProperty[] => resolution.resolved,+ ],+ stalePinnedProperties: [+ (s) => [s.pinnedPropertyResolution],+ (resolution: PinnedPropertyResolution): PinnedAccountProperty[] => resolution.stale,+ ],+ draftPinLimitReached: [+ (s) => [s.draftPinnedProperties],+ (draft: PinnedAccountProperty[]): boolean => draft.length >= MAX_PINNED_ACCOUNT_PROPERTIES,+ ],+ canSavePinnedProperties: [+ (s) => [s.isConfiguring, s.config, s.draftPinnedProperties, s.configLoading],+ (+ isConfiguring: boolean,+ config: UserCustomerAnalyticsConfigApi | null,+ draft: PinnedAccountProperty[],+ saving: boolean+ ): boolean =>+ isConfiguring && config !== null && !saving && !pinnedPropertiesEqual(config.pinned_properties, draft),+ ],+ }),+ listeners(({ actions, values }) => ({+ beginConfiguring: () => {+ actions.setDraftPinnedProperties(values.resolvedPinnedProperties.map(({ reference }) => reference))+ },+ cancelConfiguring: () => {+ actions.setDraftPinnedProperties(values.resolvedPinnedProperties.map(({ reference }) => reference))+ },+ savePinnedProperties: () => {+ if (values.canSavePinnedProperties) {+ actions.persistPinnedProperties({ pinnedProperties: values.draftPinnedProperties })+ }+ },+ persistPinnedPropertiesSuccess: ({ config }) => {+ actions.setDraftPinnedProperties([...config.pinned_properties])+ const customPropertyCount = config.pinned_properties.filter(({ kind }) => kind === 'custom_property').length+ posthog.capture(AccountsEvents.PinnedPropertiesSaved, {+ pinned_count: config.pinned_properties.length,+ custom_property_count: customPropertyCount,+ relationship_count: config.pinned_properties.length - customPropertyCount,+ })+ },+ })),+ afterMount(({ actions, props }) => {+ if (props.projectId > 0) {+ actions.loadConfig()+ actions.loadAvailableDefinitions()+ }+ }),+])diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPinnedProperties.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPinnedProperties.tsxindex fcce14ebfc57..070f37f0d687 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPinnedProperties.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPinnedProperties.tsx@@ -21,6 +21,24 @@ export interface AccountPinnedPropertiesProps {onSaveRelationship: AccountPropertyRowProps['onSaveRelationship']}+export function AccountPinnedPropertiesEmptyState({ onConfigure }: { onConfigure: () => void }): JSX.Element {+ return (+ <div className="flex flex-col items-center gap-3 px-5 py-6 text-center">+ <HedgehogBusiness className="w-16 h-16" />+ <p className="text-sm text-secondary mb-0">Pin the account details you use most.</p>+ <LemonButton+ type="primary"+ size="small"+ icon={<IconPin />}+ onClick={onConfigure}+ data-attr="account-pin-properties-empty"+ >+ Pin properties+ </LemonButton>+ </div>+ )+}+export function AccountPinnedProperties({properties,editingPropertyKey = null,@@ -35,7 +53,7 @@ export function AccountPinnedProperties({return (<section className="flex flex-col flex-1 min-h-0 overflow-hidden" data-attr="account-pinned-properties"><div className="flex items-center shrink-0 px-5 pt-4">- <span className="text-xxs font-semibold uppercase tracking-wider text-secondary">Properties</span>+ <span className="secondary text-secondary">Properties</span>{properties.length > 0 ? (<LemonButtonsize="xsmall"@@ -49,19 +67,7 @@ export function AccountPinnedProperties({) : null}</div>{properties.length === 0 ? (- <div className="flex flex-col items-center gap-3 px-5 py-6 text-center">- <HedgehogBusiness className="w-16 h-16" />- <p className="text-sm text-secondary mb-0">Pin the account details you use most.</p>- <LemonButton- type="primary"- size="small"- icon={<IconPin />}- onClick={onConfigure}- data-attr="account-pin-properties-empty"- >- Pin properties- </LemonButton>- </div>+ <AccountPinnedPropertiesEmptyState onConfigure={onConfigure} />) : (<div className="flex flex-col gap-4 min-h-0 overflow-y-auto px-5 pt-4 pb-5">{properties.map((property) => (diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfigurator.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfigurator.tsxindex b4ed268c3d20..37f65bf0fac9 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfigurator.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfigurator.tsx@@ -15,6 +15,7 @@ export interface AccountPropertyConfiguratorProps {onChange: (pinnedPropertyKeys: string[]) => voidonSave: (pinnedPropertyKeys: string[]) => voidonCancel: () => void+ saveDisabledReason?: string}export function AccountPropertyConfigurator({@@ -25,6 +26,7 @@ export function AccountPropertyConfigurator({onChange,onSave,onCancel,+ saveDisabledReason,}: AccountPropertyConfiguratorProps): JSX.Element {const optionsByKey = new Map(options.map((option) => [option.key, option]))const selectedOptions = pinnedPropertyKeys.map(@@ -71,6 +73,7 @@ export function AccountPropertyConfigurator({type="primary"onClick={() => onSave(pinnedPropertyKeys)}loading={saving}+ disabledReason={saveDisabledReason}data-attr="account-pinned-properties-save">Savediff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex e97fc41b0ffd..cbfbfe0cb7ab 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -1339,3 +1339,9 @@ tools:usage-metrics-update:operation: groups_types_metrics_updateenabled: false+ user-customer-analytics-config-partial-update:+ operation: user_customer_analytics_config_partial_update+ enabled: false+ user-customer-analytics-config-retrieve:+ operation: user_customer_analytics_config_retrieve+ enabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1857dd34ba74..14e8db24eaee 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -69322,6 +69322,33 @@ export namespace Schemas {readonly requires_credential_review?: boolean;}+ /**+ * * `custom_property` - Custom property+ * * `relationship` - Relationship+ */+ export type PinnedAccountPropertyKindEnum = typeof PinnedAccountPropertyKindEnum[keyof typeof PinnedAccountPropertyKindEnum];+++ export const PinnedAccountPropertyKindEnum = {+ CustomProperty: 'custom_property',+ Relationship: 'relationship',+ } as const;++ export interface PinnedAccountProperty {+ /** Definition type for this pinned account property.+ *+ * * `custom_property` - Custom property+ * * `relationship` - Relationship */+ kind: PinnedAccountPropertyKindEnum;+ /** Team-scoped custom property or relationship definition UUID. */+ id: string;+ }++ export interface PatchedUserCustomerAnalyticsConfigUpdate {+ /** Complete ordered list of account properties to pin. Omit to keep the current pins; pass an empty list to clear them. */+ pinned_properties?: PinnedAccountProperty[];+ }+/*** * `attribute` - attribute* * `resourceAttribute` - resourceAttribute@@ -87745,6 +87772,11 @@ export namespace Schemas {total: number;}+ export interface UserCustomerAnalyticsConfig {+ /** Account properties pinned in sidebar display order. */+ readonly pinned_properties: readonly PinnedAccountProperty[];+ }+export interface UserFacetSettings {/** Ordered list of custom facets the user has pinned for this product, within the current team. Send the full list to replace the existing set. */custom_facets: UserFacetSettingsEntry[];