Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(customer-analytics): display and edit pinned account properties (#95542)

Arthur Moreira de Deusc08477d2bba8
diff --git a/docs/internal/customer-analytics-account-sidebar.md b/docs/internal/customer-analytics-account-sidebar.md
new file mode 100644
index 000000000000..89472e0d60b4
--- /dev/null
+++ b/docs/internal/customer-analytics-account-sidebar.md
@@ -0,0 +1,43 @@
+# Account detail sidebar properties
+
+Each user can pin up to 50 account custom properties and relationships in their project.
+The Pin properties button and the Properties gear open the same ordered selector.
+Dragging entries changes their saved display order. The sidebar scrolls independently of
+the main account content on wide account scenes.
+
+Pinned rows load current values for the selected account. Missing custom values display
+"Not set" and relationships without current assignees display "Unassigned". Loading and
+failed requests have separate states, with retry available after a failure.
+The empty configuration does not request account values or relationships, so account-data
+failures cannot block the Pin properties action. Saving the first pin starts loading values.
+Refresh failures retain the last loaded rows and any open editor, with a non-blocking retry
+warning. Only a failed initial load replaces the rows with a blocking error.
+
+Account editors can edit manual and workflow-backed properties inline. Workflow-backed
+rows warn that a workflow may overwrite a manual change. Warehouse-backed and canonical
+properties are read-only. Date and datetime pickers provide their own apply and cancel
+controls; other editors use Clear value, Cancel, and Save.
+
+Clearing a custom value requires confirmation and posts a null value to
+`POST /api/projects/:project_id/accounts/:account_id/custom_property_values/`.
+The endpoint returns 204, soft-deletes the current value, and preserves its history.
+Warehouse-backed and canonical values reject both manual sets and clears.
+
+Relationship editors support single and multiple holders. Removing a holder ends the
+assignment without deleting its history. Multi-holder changes retain unchanged holders.
+Relationship saves apply the edits relative to the assignments shown when editing began.
+Concurrent additions and removals are preserved. A retry tracks assignments created by
+its own partial save, so those can still be removed if the draft changes before retrying.
+Clearing every holder requires confirmation. Failed saves keep the editor open; after a
+partial relationship failure, the sidebar reloads current assignments so a retry uses
+the latest state.
+
+Saved values report the same product events as the account list.
+Their source is the account sidebar.
+
+Pin preferences belong to `accountSidebarConfigLogic`, keyed by project. Live values and
+editing state belong to `accountSidebarPropertiesLogic`, keyed by project and account.
+The Relationships tab and account list refresh after assignment changes.
+Successful sidebar writes emit the existing custom-property and role-assignment events
+with `source: account_sidebar`. Custom-property events exclude property names and values;
+role-assignment events retain the existing role metadata and internal-user identifiers.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 62488c856b1e..25bafd9af12b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6340,6 +6340,14 @@ snapshots:
hash: v1.k794b7964.31ffca7eb6c59cf545dd8f16e7a532149448b95c65444aa14d5e776a0875dafd.lULK4-DoenY3SeZK1Sfr50doCkqdIbyl9U35M4ah00g
scenes-app-customer-analytics-account-detail--narrow--light:
hash: v1.k794b7964.5a6763d49a273274f686f1517da9d2ba4af64b5be6897a9886addc04f429c209.JZ6O0iGKO-5AKZyg0XnVZ8JoOZ2-Jg4i9E746aSUm2I
+ scenes-app-customer-analytics-account-detail--pinned-properties--dark:
+ hash: v1.k794b7964.c07338213b06adf9bfd4b50f3ffa1a453bd341f09873f555462fe342347e3f00.8fzRLH13b5ApNO_5iC6HUegL5AWjTd_keBTI7hxjQaQ
+ scenes-app-customer-analytics-account-detail--pinned-properties--light:
+ hash: v1.k794b7964.339c333ebc1367f2084c3e1f5210a887499307f0794c8ad1bd62fe85aaecdfc7.0rEF00np1G0v1HBOY0-dAEWIKhrvy8AduFWiy7DvLnc
+ scenes-app-customer-analytics-account-detail--pinned-properties-narrow--dark:
+ hash: v1.k794b7964.ff9da4647c64580046ded4d93bfd5d1f5b9ddeb91afa106e89b290b1294caba3.v7FVsOduvBV8A7I35N0H0rNRbTs70559gvkezl-TZJs
+ scenes-app-customer-analytics-account-detail--pinned-properties-narrow--light:
+ hash: v1.k794b7964.2abb48fdc076ac41b8fc614e2917b8eb5075b0f88d3d0fc904eaab2c97a2eca0.UrfORDRAfYTngPUcDgRb8nS6pT4ExcEp0HmF9kD7zf0
scenes-app-customer-analytics-account-detail-property-sidebar--custom-property-editors--dark:
hash: v1.k794b7964.66592dcf1b3fd0392d3fb40b6137fe122b85b735099f7b073568caa1b7556210.EcnIneYAPaWxcrA3krEwqQ3-1VM66r-alaQvyVFbRxc
scenes-app-customer-analytics-account-detail-property-sidebar--custom-property-editors--light:
@@ -6353,9 +6361,9 @@ snapshots:
scenes-app-customer-analytics-account-detail-property-sidebar--empty--light:
hash: v1.k794b7964.80932bda346697628be7627a1729c3fe6a5c860637dc9626bae39febdc22d3f5.tl_7hj4nr98S-dkzOcAIA7Cs4z6guQG7lR1IvbzsJgQ
scenes-app-customer-analytics-account-detail-property-sidebar--filled-and-scrollable--dark:
- hash: v1.k794b7964.75d86eaa79d518fdce67a3d91053dcbdff1ee6efae7e533c31533cdd57ee6700.9jA6_-_9pS7ApCzy-uJitof965VYwovXPMrLIPgXMxI
+ hash: v1.k794b7964.8aa0fb46f5b5fe78831081935412d41f180d6c1d7b1c82254507616a32e956c8.FkD1WwJOeWbl6OhgTd4eM3RsxATvgSfAqZ2Pa2XpugU
scenes-app-customer-analytics-account-detail-property-sidebar--filled-and-scrollable--light:
- hash: v1.k794b7964.6697caf7d48ede16cf590979eda41cf45991adc22a6c479fdb93db46913fd800.JTcXD-8tNV94GfJgIjp9WObCJShaCxQCn_ichggYrZs
+ hash: v1.k794b7964.8cfa7db1f6d44e6d4b40f72cf335ffb24c3d9229ffbc9d2f45fbef65f4015d1a.VyzZd3tKHtaBr94myujgWZac0OaK0TX88AqoIvfdUXg
scenes-app-customer-analytics-account-detail-property-sidebar--pin-and-reorder--dark:
hash: v1.k794b7964.ae32ab54e49606fc28e9a68b1274acc5193d58e55a144e66a36de73ed5352687.lFgL26WepIZ4NNnjQP38vqOEAleJXw1HwqLgjJqSvi4
scenes-app-customer-analytics-account-detail-property-sidebar--pin-and-reorder--light:
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 1cbc4491ffa5..7a2fa48e9859 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -888,9 +888,9 @@ class CustomPropertyDefinitionConflictError(Exception):
class CanonicalCustomPropertyReadOnlyError(Exception):
- """Raised when an update would change a field PostHog owns on a canonical custom property —
- its name or display type. Both are what the write path matches on, so a user editing them
- would silently stop the values from being recorded (→ 400)."""
+ """Canonical names and types identify the properties that PostHog records.
+ Manual API writes must preserve those identifiers and their system-managed values.
+ """
class ResourceForbiddenError(Exception):
@@ -1297,7 +1297,7 @@ def list_custom_property_definitions(
``has_workflow_reference`` is included for every caller. ``references`` carries only workflow
metadata the caller can read. ``exclude_group_targets`` hides group-target definitions from callers
without ``group`` read authorization."""
- queryset = CustomPropertyDefinition.objects.filter(team_id=team_id).select_related("source").order_by("name")
+ queryset = CustomPropertyDefinition.objects.for_team(team_id).select_related("source").order_by("name")
if exclude_group_targets:
queryset = queryset.exclude(target_type=TargetType.GROUP.value)
total_count = queryset.count()
@@ -1324,14 +1324,14 @@ def list_custom_property_definitions(
def get_custom_property_definition_target_type(team_id: int, definition_id: str) -> str | None:
- definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ definition = _get_custom_property_definition(team_id, definition_id)
return definition.target_type if definition is not None else None
def get_custom_property_definition(
team_id: int, definition_id: str, *, user_access_control: "UserAccessControl"
) -> contracts.CustomPropertyDefinitionView | None:
- definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ definition = _get_custom_property_definition(team_id, definition_id)
if definition is None:
return None
workflow_references_by_definition_id = _custom_property_references_by_definition_id(
@@ -1372,7 +1372,7 @@ def create_custom_property_definition(
was_impersonated: bool,
) -> contracts.CustomPropertyDefinitionView:
try:
- definition = CustomPropertyDefinition.objects.create(
+ definition = CustomPropertyDefinition.objects.for_team(team_id).create(
team_id=team_id,
created_by=user,
name=name,
@@ -1426,11 +1426,11 @@ def update_custom_property_definition(
) -> contracts.CustomPropertyDefinitionView | None:
"""Apply ``fields`` (only the keys the caller sent) to a team-scoped definition. Returns the
updated view, or None when no definition matches the id for this team (→ 404)."""
- definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ definition = _get_custom_property_definition(team_id, definition_id)
if definition is None:
return None
_assert_canonical_fields_unchanged(definition, fields)
- previous = CustomPropertyDefinition.objects.get(pk=definition.pk)
+ previous = CustomPropertyDefinition.objects.for_team(team_id).get(pk=definition.pk)
for attr, value in fields.items():
setattr(definition, attr, value)
# Re-coerce against the effective display type: a PATCH that only flips the type to a
@@ -1492,7 +1492,7 @@ def delete_custom_property_definition(
was_impersonated: bool,
) -> bool:
"""Delete a team-scoped definition. Returns False when none matched (→ 404)."""
- definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ definition = _get_custom_property_definition(team_id, definition_id)
if definition is None:
return False
_log_activity_swallowing(
@@ -2239,7 +2239,7 @@ def create_custom_property_source(
column_descriptions: dict | None = None,
user_access_control: "UserAccessControl | None" = None,
) -> contracts.CustomPropertySourceView:
- definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
+ definition = _get_custom_property_definition(team_id, definition_id)
if definition is None:
raise CustomPropertySourceValidationError("Custom property definition not found for this team.")
@@ -4303,6 +4303,13 @@ def _get_team_scoped(model, team_id: int, pk: str | UUID):
return None
+def _get_custom_property_definition(team_id: int, definition_id: str | UUID) -> CustomPropertyDefinition | None:
+ try:
+ return CustomPropertyDefinition.objects.for_team(team_id).get(pk=definition_id)
+ except (CustomPropertyDefinition.DoesNotExist, ValidationError, ValueError):
+ return None
+
+
def _get_object_or_raise(queryset, pk: str, model):
"""Fetch by pk from an already-scoped queryset, raising ``model.DoesNotExist`` for
absent/malformed ids (the view maps that to 404)."""
@@ -4372,6 +4379,11 @@ def set_custom_property_value(
*,
actor: "User | None" = None,
) -> contracts.CustomPropertyValue:
+ definition = _get_custom_property_definition(team_id, definition_id)
+ if definition is not None and definition.name in CANONICAL_DISPLAY_TYPE_BY_NAME:
+ raise CanonicalCustomPropertyReadOnlyError(
+ "This custom property is managed by PostHog and can't be edited manually."
+ )
if _source_backed_definition_ids(team_id, [definition_id]):
raise CustomPropertyValueSourceManaged(
"This custom property is managed by a data warehouse source and can't be set manually."
@@ -4387,6 +4399,27 @@ def set_custom_property_value(
return _to_custom_property_value(row)
+def clear_custom_property_value(
+ team_id: int,
+ account_id: str | UUID,
+ definition_id: str | UUID,
+ *,
+ actor: "User | None" = None,
+) -> None:
+ definition = _get_custom_property_definition(team_id, definition_id)
+ if definition is not None and definition.name in CANONICAL_DISPLAY_TYPE_BY_NAME:
+ raise CanonicalCustomPropertyReadOnlyError(
+ "This custom property is managed by PostHog and can't be edited manually."
+ )
+ if _source_backed_definition_ids(team_id, [definition_id]):
+ raise CustomPropertyValueSourceManaged(
+ "This custom property is managed by a data warehouse source and can't be cleared manually."
+ )
+ _custom_property_values_logic.set_account_custom_properties_by_id(
+ team_id=team_id, account_id=account_id, properties={str(definition_id): None}, actor=actor
+ )
+
+
def record_last_slack_message_at(*, team_id: int, account_id: str | UUID, timestamp: datetime) -> bool:
"""Record when a customer last messaged in the Slack channel bound to `account_id`.
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 134055f7e2d1..509e3461a594 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -1915,11 +1915,12 @@ class CustomPropertyValueWriteSerializer(serializers.Serializer):
help_text="UUID of the custom property definition whose value to set for this account."
)
value = CustomPropertyValueField(
+ allow_null=True,
help_text=(
"Value to store, matching the definition's type: a number for number/currency/percent, a "
"boolean for boolean, an ISO-8601 string for date/datetime, an HTTP or HTTPS URL for link properties, "
- "or text for text properties."
- )
+ "or text for text properties. Null clears the current value while preserving its history."
+ ),
)
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 4f5e7acadaa3..0c94730be545 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -2266,8 +2266,10 @@ class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
values = api.list_active_custom_property_values(self.team_id, account_id)
return Response(CustomPropertyValueSerializer(values, many=True).data)
- @extend_schema(request=CustomPropertyValueWriteSerializer, responses={201: CustomPropertyValueSerializer})
- def create(self, request: Request, *args, **kwargs) -> Response:
+ @extend_schema(
+ request=CustomPropertyValueWriteSerializer, responses={201: CustomPropertyValueSerializer, 204: None}
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
account_id = self._accessible_account_id()
if account_id is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
@@ -2275,6 +2277,14 @@ class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
write.is_valid(raise_exception=True)
try:
+ if write.validated_data["value"] is None:
+ api.clear_custom_property_value(
+ team_id=self.team_id,
+ account_id=account_id,
+ definition_id=write.validated_data["definition"],
+ actor=cast(User, request.user),
+ )
+ return Response(status=status.HTTP_204_NO_CONTENT)
value = api.set_custom_property_value(
team_id=self.team_id,
account_id=account_id,
@@ -2287,7 +2297,7 @@ class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMix
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
except api.CustomPropertyDefinitionNotFound:
raise ValidationError({"definition": "Custom property definition not found."})
- except api.CustomPropertyValueSourceManaged as exc:
+ except (api.CustomPropertyValueSourceManaged, api.CanonicalCustomPropertyReadOnlyError) as exc:
raise ValidationError({"definition": str(exc)})
except api.InvalidCustomPropertyValue as exc:
raise ValidationError({"value": str(exc)})
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 20f608596fa4..955c199769e7 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -2036,6 +2036,27 @@ class TestCustomPropertyValueViewSet(APIBaseTest):
endpoint or self.endpoint, {"definition": str(definition_id), "value": value}, format="json"
)
+ @parameterized.expand([("text", "enterprise"), ("number", 42)])
+ def test_clear_value_preserves_history(self, property_type: str, value: str | int) -> None:
+ definition = self.text_def if property_type == "text" else self.number_def
+ created = self._set(definition.id, value).json()
+ self._set(
+ self.number_def.id if property_type == "text" else self.text_def.id,
+ 7 if property_type == "text" else "other",
+ )
+
+ response = self._set(definition.id, None)
+
+ self.assertEqual(status.HTTP_204_NO_CONTENT, response.status_code)
+ self.assertTrue(CustomPropertyValue.objects.for_team(self.team.id).get(id=created["id"]).is_deleted)
+ active = self.client.get(self.endpoint).json()
+ self.assertEqual(1, len(active))
+ self.assertNotEqual(str(definition.id), active[0]["definition_id"])
+ self.assertEqual(status.HTTP_204_NO_CONTENT, self._set(definition.id, None).status_code)
+
+ def test_clear_unknown_definition_is_rejected(self) -> None:
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, self._set(uuid4(), None).status_code)
+
def test_create_value_success(self):
response = self._set(self.text_def.id, "enterprise")
@@ -2082,12 +2103,13 @@ class TestCustomPropertyValueViewSet(APIBaseTest):
values = {v["definition_id"]: v["value"] for v in response.json()}
self.assertEqual({str(self.text_def.id): "enterprise", str(self.number_def.id): 42}, values)
- def test_account_from_another_team_returns_404(self):
+ @parameterized.expand([("write", "x"), ("clear", None)])
+ def test_account_from_another_team_returns_404(self, _name: str, value: str | None) -> None:
other_team = Team.objects.create(organization=self.organization)
other_account = create_account(team_id=other_team.id)
endpoint = f"/api/projects/{self.team.id}/accounts/{other_account.id}/custom_property_values/"
- response = self._set(self.text_def.id, "x", endpoint=endpoint)
+ response = self._set(self.text_def.id, value, endpoint=endpoint)
self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)
@@ -2107,7 +2129,30 @@ class TestCustomPropertyValueViewSet(APIBaseTest):
self.assertIn(response.status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN])
- def test_source_backed_definition_rejects_manual_write(self):
+ @parameterized.expand([("write", "2026-01-01T00:00:00Z"), ("clear", None)])
+ def test_canonical_definition_rejects_manual_write(self, _name: str, value: str | None) -> None:
+ definition = create_custom_property_definition(
+ team_id=self.team.id, name="Last Slack message at", display_type=DisplayType.DATETIME
+ )
+ recorded_at = timezone.now()
+ current = CustomPropertyValue.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ account=self.account,
+ definition=definition,
+ value_datetime=recorded_at,
+ )
+
+ response = self._set(definition.id, value)
+
+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())
+ self.assertEqual("definition", response.json()["attr"])
+ current.refresh_from_db()
+ self.assertFalse(current.is_deleted)
+ self.assertEqual(recorded_at, current.value_datetime)
+ self.assertEqual(1, len(self.client.get(self.endpoint).json()))
+
+ @parameterized.expand([("write", "manual"), ("clear", None)])
+ def test_source_backed_definition_rejects_manual_write(self, _name: str, value: str | None) -> None:
saved_query_model = apps.get_model("data_modeling", "DataWarehouseSavedQuery")
view = saved_query_model.objects.create(team=self.team, name="v", columns={"k": {}, "c": {}})
CustomPropertySource.objects.unscoped().create(
@@ -2118,7 +2163,7 @@ class TestCustomPropertyValueViewSet(APIBaseTest):
key_column="k",
)
- response = self._set(self.text_def.id, "manual")
+ response = self._set(self.text_def.id, value)
self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)
self.assertEqual("definition", response.json()["attr"])
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 53bd096019f3..27bcff8ef53f 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -155,8 +155,10 @@ Pinned property preferences belong to the current user and project, never to an
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.
+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.
+`accountSidebarPropertiesLogic({ projectId, accountId })` loads current custom values and relationship assignments, resolves them in pin order, and owns inline editing. Resource-level Customer analytics editors can change manual/workflow values and relationships; canonical and warehouse-backed rows are read-only.
+Clearing posts a null custom value and preserves history. Relationship removals end assignments; single-holder replacements let the server end the previous holder. Multi-holder retries reload current assignments to avoid duplicating a partially completed save. Failed saves keep the draft open.
+Sidebar saves refresh the mounted Relationships tab and account-list data nodes. Tab relationship reloads also refresh sidebar values. See `docs/internal/customer-analytics-account-sidebar.md` for the behavior and API contract.
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.
@@ -335,54 +337,54 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
### Tracked events
-| Event | Fires from | Properties |
-| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |
-| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `assignment_status` \| `my_accounts` \| `assigned_to` \| `custom_property`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assignment_status` `value` is the status (`all` \| `assigned` \| `unassigned`) and `is_cleared` is `value === 'all'`; for `assigned_to` also `role_count`; for `custom_property` only `filter_count` + `is_cleared` (no `value` — property values can carry customer data) |
-| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |
-| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |
-| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |
-| `customer analytics accounts column resized` | `accountsViewsLogic` `reportColumnResize` after a header drag | _(none — column names can contain customer property names)_ |
-| `customer analytics accounts account opened` | `AccountsTableNameCell.tsx` account-name `<Link>` `onClick` (only when the row expands in the legacy experience) | _(none — the row's `id` is customer PII-adjacent and kept out)_ |
-| ~~`customer analytics accounts columns saved`~~ | _Deprecated — no longer emitted. Column changes are now saved as part of a view (see view events below)._ | _n/a_ |
-| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |
-| `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed |
-| `customer analytics accounts view saved` | `accountsViewsLogic` `submitViewForm` listener after a create succeeds | `visibility` (`private` \| `shared`) |
-| `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener after content or metadata changes | _(none)_ |
-| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |
-| `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ |
-| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner` for the seeded definitions, else the definition name), `is_assigned`, `assigned_user_id`, `source` (`list_row` from `accountsLogic.updateAccountRole` \| `relationships_tab` from `accountRelationshipsLogic` assign/end) |
-| `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` |
-| `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
-| `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |
-| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities` \| `summaries` \| `support_tickets` \| `email_threads` \| `meetings` \| `event_stream`) |
-| `customer analytics account usage series toggled` | `accountBillingLogic` `toggleHiddenSeriesKey` listener (dispatched by the `AccountBillingSeriesToggle` chips) | `kind` (`usage` \| `spend`), `is_hidden` (the post-click state), `series_count` (no series label / no PII) |
-| `customer analytics account usage series bulk toggled` | `accountBillingLogic` `setAllSeriesHidden` listener (dispatched by the Select all / Clear all buttons in `AccountBillingSeriesToggle`) | `kind` (`usage` \| `spend`), `is_hidden` (`true` when hiding all, `false` when showing all), `series_count` (no series label / no PII) |
-| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |
-| `customer analytics account related user admin opened` | `AccountRelatedUsersExpansion.tsx` staff-only "Impersonate" button | `region` (`US` \| `EU`; user ID kept out) |
-| `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |
-| `customer analytics account summary cadence changed` | `accountSummariesLogic` `setCadence` listener (after the PATCH succeeds) | `cadence` (`daily` \| `weekly` \| `monthly` \| `off`) |
-| `customer analytics account summary expanded` | `accountSummariesLogic` `toggleSummaryExpanded` listener (only when the toggle opens a summary, not on collapse) | _(none — summary content/period is customer data and kept out)_ |
-| `customer analytics account summaries page changed` | `accountSummariesLogic` `loadSummariesPage` listener (only dispatched by the pagination controls) | `page` |
-| `customer analytics account support ticket clicked` | `AccountSupportTicketsExpansion.tsx` ticket `<Link>` `onClick` | _(none — ticket number/customer content kept out)_ |
-| `customer analytics account meeting matching saved` | `accountMeetingsLogic` `saveMatching` listener (after the PATCH succeeds) | `domain_count`, `email_count` (no raw domains/emails — customer PII kept out) |
-| `customer analytics account meetings searched` | `accountMeetingsLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
-| `customer analytics account meeting attendee clicked` | `AccountMeetingsExpansion.tsx` attendee `<Link>` `onClick` (person links only) | _(none — attendee email/person id is customer PII and kept out)_ |
-| `customer analytics account gong call opened` | `AccountMeetingsExpansion.tsx` "Open in Gong" button | _(none; meeting and Gong identifiers stay out)_ |
-| `customer analytics account event stream toggled` | `eventStreamLogic` (`../EventStream/`) `setAccountMembership` listener — the "Include in event stream" toggle in the expanded row's Event stream tab | `account_id`, `included`, `member_count` |
-| `customer analytics event stream config saved` | `eventStreamLogic` `saveEventStreamSuccess` listener — the Save button in the Event stream settings section | `enabled`, `event_count`, `has_slack_channel`, `member_count` |
-| `customer analytics event stream test message sent` | `eventStreamLogic` `sendTestMessageSuccess` listener — the "Send test message" button in the Event stream settings section | `event_count`, `member_count` |
-| `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ |
-| `customer analytics notes tab searched` | `accountNotesLogic` `setSearch` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
-| `customer analytics notes tab filtered` | `accountNotesLogic` `reportFilterChange` listener (dispatched by the filter controls only, so the "My notes"/"My accounts" cascade doesn't double-fire) | `filter_type` (`created_by` \| `account` \| `my_notes` \| `my_accounts`), `is_cleared`; for `created_by` also `user_count`; for `my_notes`/`my_accounts` also `value` (no account id/name logged) |
-| `customer analytics notes tab note clicked` | `AccountNotesTabContent.tsx` note title `<Link>` `onClick` (opens side panel) | `notebook_short_id` |
-| `customer analytics notes tab account clicked` | `AccountNotesTabContent.tsx` account `<Link>` `onClick` | `account_id` |
+| Event | Fires from | Properties |
+| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |
+| `customer analytics accounts filter changed` | `accountsLogic` `reportFilterChange` listener (dispatched by the filter controls) | `filter_type` (`tag` \| `assignment_status` \| `my_accounts` \| `assigned_to` \| `custom_property`), `value`, `is_cleared`, `active_filter_count`; for `tag` also `tag_count`; for `assignment_status` `value` is the status (`all` \| `assigned` \| `unassigned`) and `is_cleared` is `value === 'all'`; for `assigned_to` also `role_count`; for `custom_property` only `filter_count` + `is_cleared` (no `value` — property values can carry customer data) |
+| `customer analytics accounts searched` | `accountsLogic` `setSearchInput` listener (post-debounce) | `query_length`, `has_query`, `active_filter_count` |
+| `customer analytics accounts refreshed` | `accountsLogic` `refresh` | `has_search`, `active_filter_count`, `sort_column` |
+| `customer analytics accounts sorted` | `accountsLogic` `toggleSort` | `column`, `direction` (`asc` \| `desc` \| `cleared`) |
+| `customer analytics accounts column resized` | `accountsViewsLogic` `reportColumnResize` after a header drag | _(none — column names can contain customer property names)_ |
+| `customer analytics accounts account opened` | `AccountsTableNameCell.tsx` account-name `<Link>` `onClick` (only when the row expands in the legacy experience) | _(none — the row's `id` is customer PII-adjacent and kept out)_ |
+| ~~`customer analytics accounts columns saved`~~ | _Deprecated — no longer emitted. Column changes are now saved as part of a view (see view events below)._ | _n/a_ |
+| `customer analytics accounts overview tiles edited` | `accountsOverviewTilesLogic` editor close (diffed vs open snapshot, only when changed) | `tiles_added`, `tiles_removed`, `tiles_updated`, `reordered`, `tile_count_before`, `tile_count_after` |
+| `customer analytics accounts overview tiles localstorage read` | `accountsOverviewTilesLogic` `afterMount` (only when a legacy custom value exists) | `tile_count` — **tombstone**: a legacy localStorage tiles value was read; once this stops firing, no browser still carries one and the read path can be removed |
+| `customer analytics accounts view saved` | `accountsViewsLogic` `submitViewForm` listener after a create succeeds | `visibility` (`private` \| `shared`) |
+| `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener after content or metadata changes | _(none)_ |
+| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener | `visibility` |
+| `customer analytics accounts view deleted` | `accountsViewsLogic` `deleteViewSuccess` listener | _(none)_ |
+| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner` for the seeded definitions, else the definition name), `is_assigned`, `assigned_user_id`, `source` (`list_row` from `accountsLogic.updateAccountRole` \| `relationships_tab` from `accountRelationshipsLogic` assign/end) |
+| `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 and `accountSidebarPropertiesLogic` `persistCustomPropertySuccess` 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` |
+| `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
+| `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |
+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities` \| `summaries` \| `support_tickets` \| `email_threads` \| `meetings` \| `event_stream`) |
+| `customer analytics account usage series toggled` | `accountBillingLogic` `toggleHiddenSeriesKey` listener (dispatched by the `AccountBillingSeriesToggle` chips) | `kind` (`usage` \| `spend`), `is_hidden` (the post-click state), `series_count` (no series label / no PII) |
+| `customer analytics account usage series bulk toggled` | `accountBillingLogic` `setAllSeriesHidden` listener (dispatched by the Select all / Clear all buttons in `AccountBillingSeriesToggle`) | `kind` (`usage` \| `spend`), `is_hidden` (`true` when hiding all, `false` when showing all), `series_count` (no series label / no PII) |
+| `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ |
+| `customer analytics account related user admin opened` | `AccountRelatedUsersExpansion.tsx` staff-only "Impersonate" button | `region` (`US` \| `EU`; user ID kept out) |
+| `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ |
+| `customer analytics account summary cadence changed` | `accountSummariesLogic` `setCadence` listener (after the PATCH succeeds) | `cadence` (`daily` \| `weekly` \| `monthly` \| `off`) |
+| `customer analytics account summary expanded` | `accountSummariesLogic` `toggleSummaryExpanded` listener (only when the toggle opens a summary, not on collapse) | _(none — summary content/period is customer data and kept out)_ |
+| `customer analytics account summaries page changed` | `accountSummariesLogic` `loadSummariesPage` listener (only dispatched by the pagination controls) | `page` |
+| `customer analytics account support ticket clicked` | `AccountSupportTicketsExpansion.tsx` ticket `<Link>` `onClick` | _(none — ticket number/customer content kept out)_ |
+| `customer analytics account meeting matching saved` | `accountMeetingsLogic` `saveMatching` listener (after the PATCH succeeds) | `domain_count`, `email_count` (no raw domains/emails — customer PII kept out) |
+| `customer analytics account meetings searched` | `accountMeetingsLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
+| `customer analytics account meeting attendee clicked` | `AccountMeetingsExpansion.tsx` attendee `<Link>` `onClick` (person links only) | _(none — attendee email/person id is customer PII and kept out)_ |
+| `customer analytics account gong call opened` | `AccountMeetingsExpansion.tsx` "Open in Gong" button | _(none; meeting and Gong identifiers stay out)_ |
+| `customer analytics account event stream toggled` | `eventStreamLogic` (`../EventStream/`) `setAccountMembership` listener — the "Include in event stream" toggle in the expanded row's Event stream tab | `account_id`, `included`, `member_count` |
+| `customer analytics event stream config saved` | `eventStreamLogic` `saveEventStreamSuccess` listener — the Save button in the Event stream settings section | `enabled`, `event_count`, `has_slack_channel`, `member_count` |
+| `customer analytics event stream test message sent` | `eventStreamLogic` `sendTestMessageSuccess` listener — the "Send test message" button in the Event stream settings section | `event_count`, `member_count` |
+| `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ |
+| `customer analytics notes tab searched` | `accountNotesLogic` `setSearch` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
+| `customer analytics notes tab filtered` | `accountNotesLogic` `reportFilterChange` listener (dispatched by the filter controls only, so the "My notes"/"My accounts" cascade doesn't double-fire) | `filter_type` (`created_by` \| `account` \| `my_notes` \| `my_accounts`), `is_cleared`; for `created_by` also `user_count`; for `my_notes`/`my_accounts` also `value` (no account id/name logged) |
+| `customer analytics notes tab note clicked` | `AccountNotesTabContent.tsx` note title `<Link>` `onClick` (opens side panel) | `notebook_short_id` |
+| `customer analytics notes tab account clicked` | `AccountNotesTabContent.tsx` account `<Link>` `onClick` | `account_id` |
> **Keep this table up to date.** Whenever you add, rename, or remove a `posthog.capture()` event in the Accounts area — or change its properties — update this table in the same change. An agent reading this file should be able to trust it as the source of truth for what the Accounts list reports.
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
index 80ea6d2aaa56..253d07156dce 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
@@ -21,6 +21,7 @@ import type {
} from 'products/customer_analytics/frontend/generated/api.schemas'
import { ACCOUNTS_TABLE_DATA_NODE_KEY, ACCOUNTS_METRICS_DATA_NODE_KEY } from '../../constants'
+import { accountSidebarPropertiesLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic'
import { accountsColumnConfigLogic, ROLE_KEY_BY_NAME } from './accountsColumnConfigLogic'
import { AccountsEvents } from './constants'
@@ -236,6 +237,16 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
],
}),
listeners(({ actions, props, values }) => ({
+ loadRelationshipsSuccess: () => {
+ if (values.currentTeamId) {
+ accountSidebarPropertiesLogic
+ .findMounted({
+ projectId: values.currentTeamId,
+ accountId: props.accountId,
+ })
+ ?.actions.loadPropertyData()
+ }
+ },
loadRelationshipsFailure: ({ error }) => {
// No toast: `relationships === null` renders the table's failure empty state.
posthog.captureException(error, { scope: 'accountRelationshipsLogic.loadRelationships' })
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index 0a298e06d4a1..a140a3c1f39c 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -466,7 +466,7 @@ export interface accountsLogicActions {
) => {
accountId: string
definition: CustomPropertyDefinitionApi
- value: boolean | number | string
+ value: boolean | number | string | null
}
updateAccountFilters: (filters: AccountFilter[]) => {
filters: AccountFilter[]
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index d81961ef869c..68d90a80b804 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -465,8 +465,8 @@ export interface CustomPropertyValueApi {
export interface CustomPropertyValueWriteApi {
/** UUID of the custom property definition whose value to set for this account. */
definition: string
- /** Value to store, matching the definition's type: a number for number/currency/percent, a boolean for boolean, an ISO-8601 string for date/datetime, an HTTP or HTTPS URL for link properties, or text for text properties. */
- value: string | number | boolean
+ /** Value to store, matching the definition's type: a number for number/currency/percent, a boolean for boolean, an ISO-8601 string for date/datetime, an HTTP or HTTPS URL for link properties, or text for text properties. Null clears the current value while preserving its history. */
+ value: string | number | boolean | null
}
export interface AccountNotebookApi {
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index 7a334ffc7075..c93a90bb462b 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -469,8 +469,8 @@ export const accountsCustomPropertyValuesCreate = async (
accountId: string,
customPropertyValueWriteApi: CustomPropertyValueWriteApi,
options?: RequestInit
-): Promise<CustomPropertyValueApi> => {
- return apiMutator<CustomPropertyValueApi>(getAccountsCustomPropertyValuesCreateUrl(projectId, accountId), {
+): Promise<CustomPropertyValueApi | void> => {
+ return apiMutator<CustomPropertyValueApi | void>(getAccountsCustomPropertyValuesCreateUrl(projectId, accountId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index 1db598293789..0f3a68054c99 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -250,9 +250,9 @@ export const AccountsCreateBody = /* @__PURE__ */ zod
export const AccountsCustomPropertyValuesCreateBody = /* @__PURE__ */ zod.object({
definition: zod.uuid().describe('UUID of the custom property definition whose value to set for this account.'),
value: zod
- .union([zod.string(), zod.number(), zod.boolean()])
+ .union([zod.string(), zod.number(), zod.boolean(), zod.null()])
.describe(
- "Value to store, matching the definition's type: a number for number\/currency\/percent, a boolean for boolean, an ISO-8601 string for date\/datetime, an HTTP or HTTPS URL for link properties, or text for text properties."
+ "Value to store, matching the definition's type: a number for number\/currency\/percent, a boolean for boolean, an ISO-8601 string for date\/datetime, an HTTP or HTTPS URL for link properties, or text for text properties. Null clears the current value while preserving its history."
),
})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.test.tsx
new file mode 100644
index 000000000000..bb73e3a73fbd
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.test.tsx
@@ -0,0 +1,96 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { BindLogic } from 'kea'
+import { expectLogic } from 'kea-test-utils'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { AccountApi, CustomPropertyDefinitionApi } from '../../generated/api.schemas'
+import { AccountSidebar } from './AccountSidebar'
+import { accountSidebarPropertiesLogic } from './accountSidebarPropertiesLogic'
+import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+
+jest.mock('lib/utils/accessControlUtils', () => ({
+ ...jest.requireActual('lib/utils/accessControlUtils'),
+ userHasAccess: () => true,
+}))
+
+describe('AccountSidebar refresh recovery', () => {
+ afterEach(() => {
+ cleanup()
+ resumeKeaLoadersErrors()
+ })
+
+ it('keeps the typed draft mounted when a refresh fails', async () => {
+ initKeaTests()
+ silenceKeaLoadersErrors()
+ const account: AccountApi = {
+ id: 'account-1',
+ name: 'Example account',
+ notebooks: [],
+ ignored_at: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ tags: [],
+ }
+ const definition: CustomPropertyDefinitionApi = {
+ id: 'property-1',
+ name: 'Plan',
+ display_type: 'text',
+ target_type: 'account',
+ is_canonical: false,
+ has_workflow_reference: false,
+ references: [],
+ source: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: 1,
+ updated_at: null,
+ }
+ const valuesUrl = '/api/projects/:project_id/accounts/:account_id/custom_property_values/'
+ useMocks({
+ get: {
+ '/api/projects/:project_id/accounts/:account_id/': account,
+ '/api/projects/:project_id/user_customer_analytics_config/@me/': {
+ pinned_properties: [{ kind: 'custom_property', id: definition.id }],
+ },
+ '/api/projects/:project_id/custom_property_definitions/': { count: 1, results: [definition] },
+ '/api/projects/:project_id/account_relationship_definitions/': { count: 0, results: [] },
+ '/api/projects/:project_id/accounts/:account_id/relationships/': [],
+ [valuesUrl]: [
+ {
+ id: 'value-1',
+ definition_id: definition.id,
+ account_id: account.id,
+ value: 'Starter',
+ created_at: '2026-01-01T00:00:00Z',
+ created_by_id: 1,
+ },
+ ],
+ },
+ })
+ const { container } = render(
+ <BindLogic logic={customerAnalyticsAccountSceneLogic} props={{ accountId: account.id }}>
+ <AccountSidebar account={account} />
+ </BindLogic>
+ )
+ await screen.findByText('Starter')
+ fireEvent.click(container.querySelector('[data-attr="account-property-edit"]')!)
+ fireEvent.change(screen.getByDisplayValue('Starter'), { target: { value: 'Draft to retain' } })
+ useMocks({ get: { [valuesUrl]: () => [500, { detail: 'Unavailable' }] } })
+ const logic = accountSidebarPropertiesLogic({
+ projectId: projectLogic.values.currentProjectId!,
+ accountId: account.id,
+ })
+ await act(async () => {
+ await expectLogic(logic, () => logic.actions.loadPropertyData()).toFinishAllListeners()
+ })
+ expect(screen.getByText("Couldn't refresh pinned properties. These values might be out of date.")).toBeVisible()
+ expect(screen.getByDisplayValue('Draft to retain')).toBeVisible()
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx
index e019f0e4ad9d..11d5c3afb0fc 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountSidebar.tsx
@@ -1,7 +1,6 @@
import { useActions, useValues } from 'kea'
-import { IconGear } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonDivider, LemonSkeleton } from '@posthog/lemon-ui'
+import { LemonBanner, LemonDivider, LemonSkeleton } from '@posthog/lemon-ui'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { projectLogic } from 'scenes/projectLogic'
@@ -14,7 +13,8 @@ import {
configuratorKeysToPinnedProperties,
pinnedPropertyToConfiguratorKey,
} from './accountSidebarConfigLogic'
-import { AccountPinnedPropertiesEmptyState } from './components/AccountPinnedProperties'
+import { accountSidebarPropertiesLogic } from './accountSidebarPropertiesLogic'
+import { AccountPinnedProperties } from './components/AccountPinnedProperties'
import { AccountPropertyConfigurator } from './components/AccountPropertyConfigurator'
import type { AccountPropertyOption } from './components/accountPropertyTypes'
import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
@@ -27,10 +27,8 @@ export function AccountSidebar({ account }: { account: AccountApi }): JSX.Elemen
const configLogic = accountSidebarConfigLogic({ projectId: currentProjectId ?? 0 })
const {
availableDefinitions,
- availableDefinitionsLoadFailed,
canSavePinnedProperties,
config,
- configLoadFailed,
configLoading,
draftPinnedProperties,
isConfiguring,
@@ -44,10 +42,24 @@ export function AccountSidebar({ account }: { account: AccountApi }): JSX.Elemen
savePinnedProperties,
setDraftPinnedProperties,
} = useActions(configLogic)
-
- const configurationLoadFailed = configLoadFailed || availableDefinitionsLoadFailed
- const configurationLoading = !configurationLoadFailed && (config === null || availableDefinitions === null)
- const pinnedPropertyCount = config?.pinned_properties.length ?? 0
+ const propertyLogic = accountSidebarPropertiesLogic({ accountId: account.id, projectId: currentProjectId ?? 0 })
+ const {
+ sidebarProperties,
+ propertiesPanelState,
+ propertiesRefreshFailed,
+ propertySaveFailed,
+ editingPropertyKey,
+ savingPropertyKey,
+ availableMembers,
+ membersLoading,
+ } = useValues(propertyLogic)
+ const { loadPropertyData, editProperty, cancelEditing, saveCustomProperty, saveRelationship } =
+ useActions(propertyLogic)
+ const retryLoad = (): void => {
+ loadConfig()
+ loadAvailableDefinitions()
+ loadPropertyData()
+ }
const propertyOptions: AccountPropertyOption[] = [
...(availableDefinitions?.customProperties ?? []).map((definition) => ({
key: pinnedPropertyToConfiguratorKey({ kind: 'custom_property', id: definition.id }),
@@ -61,11 +73,6 @@ export function AccountSidebar({ account }: { account: AccountApi }): JSX.Elemen
})),
]
- 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:h-full @min-[60rem]/account-detail:min-h-0 @min-[60rem]/account-detail:w-60 @min-[60rem]/account-detail:overflow-y-auto"
@@ -82,47 +89,65 @@ export function AccountSidebar({ account }: { account: AccountApi }): JSX.Elemen
/>
</div>
<LemonDivider className="my-0" />
- <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>
- {!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>
- {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 className="flex flex-col flex-1 min-h-0" data-attr="account-rail-properties">
+ {propertiesPanelState !== 'ready' ? (
+ <div className="flex flex-col gap-3 p-4">
+ <span className="secondary text-secondary">Properties</span>
+ {propertiesPanelState === 'failed' ? (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: retryLoad }}>
+ Couldn't load pinned properties.
+ </LemonBanner>
+ ) : (
+ <div className="flex flex-col gap-2" data-attr="account-pinned-properties-loading">
+ <LemonSkeleton className="h-4 w-full" />
+ <LemonSkeleton className="h-4 w-3/4" />
+ </div>
+ )}
</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>
+ <div className="px-4 pt-4">
+ <LemonBanner type="warning">
+ Some pinned properties are no longer available. Update your pins to remove them.
+ </LemonBanner>
+ </div>
) : null}
- </div>
+ {propertySaveFailed ? (
+ <div className="px-4 pt-4">
+ <LemonBanner type="error">
+ Couldn't save this property. Review the value and try again.
+ </LemonBanner>
+ </div>
+ ) : null}
+ {propertiesRefreshFailed ? (
+ <div className="px-4 pt-4">
+ <LemonBanner type="warning" action={{ children: 'Try again', onClick: retryLoad }}>
+ Couldn't refresh pinned properties. These values might be out of date.
+ </LemonBanner>
+ </div>
+ ) : null}
+ <AccountPinnedProperties
+ properties={sidebarProperties}
+ editingPropertyKey={editingPropertyKey}
+ savingPropertyKey={savingPropertyKey}
+ availableMembers={availableMembers}
+ membersLoading={membersLoading}
+ onConfigure={beginConfiguring}
+ onEdit={(property) => {
+ if (!savingPropertyKey) {
+ editProperty(property)
+ }
+ }}
+ onCancelEdit={() => {
+ if (!savingPropertyKey) {
+ cancelEditing()
+ }
+ }}
+ onSaveCustomProperty={(property, value) => saveCustomProperty(property.key, value)}
+ onSaveRelationship={(property, memberIds) => saveRelationship(property.key, memberIds)}
+ />
+ </>
)}
</div>
<AccountPropertyConfigurator
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
index ccf720be3538..133a07078e01 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
@@ -6,10 +6,14 @@ import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
+import type { CustomPropertyValueWriteApi, AccountRelationshipWriteApi } from '../../generated/api.schemas'
+
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 VALUES_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/custom_property_values/'
+const ASSIGNMENTS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/relationships/'
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/'
@@ -88,6 +92,8 @@ const meta: Meta = {
{ headers: { 'Content-Type': 'image/svg+xml' } }
),
[ACCOUNT_SIDEBAR_CONFIG_ENDPOINT]: { pinned_properties: [] },
+ [VALUES_ENDPOINT]: [],
+ [ASSIGNMENTS_ENDPOINT]: [],
[CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT]: {
count: 1,
results: [
@@ -144,3 +150,164 @@ export const Narrow: Story = {
},
},
}
+
+const pinnedDefinitions = [
+ ['summary', 'Account summary', 'text', 'Evaluating the new dashboard'],
+ ['website', 'Success plan', 'link', 'https://example.com/plan'],
+ ['seats', 'Seats', 'number', 42],
+ ['arr', 'Annual recurring revenue', 'currency', 125000],
+ ['growth', 'Monthly growth', 'percent', 0.15],
+ ['renewal', 'Renewal date', 'date', '2026-11-14'],
+ ['check-in', 'Next check-in', 'datetime', '2026-11-14T10:30:00Z'],
+ ['active', 'Active', 'boolean', false],
+ ['segment', 'Segment', 'select', 'Growth'],
+ ['canonical', 'Last Slack message', 'datetime', '2026-05-20T10:00:00Z'],
+].map(([id, name, display_type, value]) => ({
+ definition: {
+ id,
+ name,
+ display_type,
+ target_type: 'account',
+ is_canonical: id === 'canonical',
+ has_workflow_reference: id === 'active',
+ source: null,
+ references: [],
+ options:
+ id === 'segment'
+ ? [
+ { id: 'growth', label: 'Growth', color: 'preset-1' },
+ { id: 'enterprise', label: 'Enterprise', color: 'preset-2' },
+ ]
+ : null,
+ created_at: '2026-05-10T10:00:00Z',
+ created_by: 1,
+ updated_at: null,
+ },
+ value: {
+ id: `value-${id}`,
+ definition_id: id,
+ account_id: ACCOUNT_ID,
+ value,
+ created_at: '2026-05-10T10:00:00Z',
+ created_by_id: 1,
+ },
+}))
+const pinnedRelationships = [
+ { id: 'csm', name: 'Customer success manager', is_single_holder: true },
+ { id: 'team', name: 'Account team', is_single_holder: false },
+]
+const pinnedMembers = [
+ {
+ id: 1,
+ email: '[email protected]',
+ first_name: 'Alex',
+ last_name: 'River',
+ uuid: '11111111-1111-4111-8111-111111111111',
+ },
+ {
+ id: 2,
+ email: '[email protected]',
+ first_name: 'Jordan',
+ last_name: 'Bell',
+ uuid: '22222222-2222-4222-8222-222222222222',
+ },
+]
+const pinnedValues = new Map(pinnedDefinitions.map(({ definition, value }) => [definition.id, value]))
+let pinnedAssignments = pinnedRelationships.map((definition) => ({
+ id: `assignment-${definition.id}`,
+ definition,
+ user: pinnedMembers[0],
+ started_at: '2026-05-10T10:00:00Z',
+ ended_at: null as string | null,
+}))
+const pinnedDecorator = mswDecorator({
+ get: {
+ [ACCOUNT_SIDEBAR_CONFIG_ENDPOINT]: {
+ pinned_properties: [
+ ...pinnedDefinitions.map(({ definition }) => ({ kind: 'custom_property', id: definition.id })),
+ ...pinnedRelationships.map(({ id }) => ({ kind: 'relationship', id })),
+ ],
+ },
+ [CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT]: {
+ count: pinnedDefinitions.length,
+ results: pinnedDefinitions.map(({ definition }) => definition),
+ },
+ [RELATIONSHIP_DEFINITIONS_ENDPOINT]: { count: pinnedRelationships.length, results: pinnedRelationships },
+ [VALUES_ENDPOINT]: () => [...pinnedValues.values()],
+ [ASSIGNMENTS_ENDPOINT]: () => pinnedAssignments,
+ 'api/organizations/:organization_id/members/': {
+ count: pinnedMembers.length,
+ results: pinnedMembers.map((user) => ({ id: user.uuid, user, level: 1 })),
+ },
+ },
+ post: {
+ [VALUES_ENDPOINT]: async ({ request }) => {
+ const { definition, value } = (await request.json()) as CustomPropertyValueWriteApi
+ if (value === null) {
+ pinnedValues.delete(definition)
+ return [204, null]
+ }
+ const row = {
+ id: `value-${definition}`,
+ definition_id: definition,
+ account_id: ACCOUNT_ID,
+ value,
+ created_at: '2026-05-21T10:00:00Z',
+ created_by_id: 1,
+ }
+ pinnedValues.set(definition, row)
+ return [201, row]
+ },
+ [ASSIGNMENTS_ENDPOINT]: async ({ request }) => {
+ const { definition: definitionId, user: userId } = (await request.json()) as AccountRelationshipWriteApi
+ const definition = pinnedRelationships.find(({ id }) => id === definitionId)!
+ if (definition.is_single_holder) {
+ pinnedAssignments = pinnedAssignments.map((row) =>
+ row.definition.id === definitionId ? { ...row, ended_at: '2026-05-21T10:00:00Z' } : row
+ )
+ }
+ const row = {
+ id: `assignment-${definitionId}-${userId}`,
+ definition,
+ user: pinnedMembers.find(({ id }) => id === userId)!,
+ started_at: '2026-05-21T10:00:00Z',
+ ended_at: null,
+ }
+ pinnedAssignments.push(row)
+ return [201, row]
+ },
+ 'api/projects/:team_id/accounts/:account_id/relationships/:id/end/': ({ params }) => {
+ const row = pinnedAssignments.find(({ id }) => id === params.id)!
+ row.ended_at = '2026-05-21T10:00:00Z'
+ return [200, row]
+ },
+ },
+})
+
+export const PinnedProperties: Story = {
+ render: () => <App />,
+ beforeEach: () => {
+ pinnedValues.clear()
+ for (const { definition, value } of pinnedDefinitions) {
+ pinnedValues.set(definition.id, value)
+ }
+ pinnedAssignments = pinnedRelationships.map((definition) => ({
+ id: `assignment-${definition.id}`,
+ definition,
+ user: pinnedMembers[0],
+ started_at: '2026-05-10T10:00:00Z',
+ ended_at: null,
+ }))
+ },
+ decorators: [pinnedDecorator],
+ parameters: {
+ testOptions: { waitForSelector: '[data-attr="account-property-row"]', viewport: { width: 1440, height: 900 } },
+ },
+}
+
+export const PinnedPropertiesNarrow: Story = {
+ ...PinnedProperties,
+ parameters: {
+ testOptions: { waitForSelector: '[data-attr="account-property-row"]', viewport: { width: 800, height: 900 } },
+ },
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarProperties.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarProperties.ts
new file mode 100644
index 000000000000..5aac17256c01
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarProperties.ts
@@ -0,0 +1,54 @@
+import type {
+ AccountRelationshipApi,
+ CustomPropertyValueApi,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { pinnedPropertyToConfiguratorKey, ResolvedPinnedAccountProperty } from './accountSidebarConfigLogic'
+import type { AccountSidebarProperty } from './components/accountPropertyTypes'
+
+export interface AccountSidebarPropertyData {
+ customValues: CustomPropertyValueApi[]
+ relationships: AccountRelationshipApi[]
+}
+
+export function buildAccountSidebarProperties(
+ pinnedProperties: ResolvedPinnedAccountProperty[],
+ data: AccountSidebarPropertyData | null,
+ editable: boolean
+): AccountSidebarProperty[] {
+ if (!data) {
+ return []
+ }
+ const valuesByDefinition = new Map(data.customValues.map((value) => [value.definition_id, value.value]))
+ return pinnedProperties.map((property): AccountSidebarProperty => {
+ const key = pinnedPropertyToConfiguratorKey(property.reference)
+ if (property.kind === 'custom_property') {
+ const { definition } = property
+ return {
+ key,
+ kind: 'custom',
+ definition,
+ value: valuesByDefinition.get(definition.id) ?? null,
+ editable,
+ provenance: definition.is_canonical
+ ? 'canonical'
+ : definition.source
+ ? 'warehouse'
+ : definition.has_workflow_reference
+ ? 'workflow'
+ : 'manual',
+ }
+ }
+ return {
+ key,
+ kind: 'relationship',
+ definition: property.definition,
+ editable,
+ members: data.relationships.flatMap((relationship) =>
+ relationship.definition.id === property.definition.id && !relationship.ended_at && relationship.user
+ ? [relationship.user]
+ : []
+ ),
+ }
+ })
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts
new file mode 100644
index 000000000000..ee20b442960c
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts
@@ -0,0 +1,508 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { waitFor } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { accountRelationshipsLogic } from '../../components/Accounts/accountRelationshipsLogic'
+import { AccountsEvents } from '../../components/Accounts/constants'
+import type {
+ AccountRelationshipApi,
+ AccountRelationshipDefinitionApi,
+ CustomPropertyDefinitionApi,
+ CustomPropertyValueWriteApi,
+ AccountRelationshipWriteApi,
+} from '../../generated/api.schemas'
+import { accountSidebarConfigLogic } from './accountSidebarConfigLogic'
+import { accountSidebarPropertiesLogic } from './accountSidebarPropertiesLogic'
+
+jest.mock('lib/utils/accessControlUtils', () => ({ userHasAccess: jest.fn(() => true) }))
+
+const definition: CustomPropertyDefinitionApi = {
+ id: 'property-1',
+ name: 'Plan',
+ display_type: 'text',
+ target_type: 'account',
+ is_canonical: false,
+ source: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: 1,
+ updated_at: null,
+ references: [],
+ has_workflow_reference: false,
+}
+const relationshipDefinition: AccountRelationshipDefinitionApi = {
+ id: 'relationship-1',
+ name: 'Account team',
+ is_single_holder: false,
+}
+const VALUES_URL = '/api/projects/:project_id/accounts/:account_id/custom_property_values/'
+const RELATIONSHIPS_URL = '/api/projects/:project_id/accounts/:account_id/relationships/'
+
+describe('accountSidebarPropertiesLogic', () => {
+ let logic: ReturnType<typeof accountSidebarPropertiesLogic.build>
+ let storedValue: string | number | boolean | null
+ let assignments: AccountRelationshipApi[]
+
+ const assignment = (id: number, definition = relationshipDefinition): AccountRelationshipApi => ({
+ id: `assignment-${id}`,
+ definition,
+ user: { id, email: `member${id}@example.com` },
+ started_at: '2026-01-01T00:00:00Z',
+ ended_at: null,
+ })
+ const mount = async (): Promise<void> => {
+ logic = accountSidebarPropertiesLogic({ projectId: 1, accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ await waitFor(() => expect(logic.values.sidebarProperties).toHaveLength(2))
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ storedValue = 'Starter'
+ assignments = [assignment(1), assignment(2), assignment(3, { ...relationshipDefinition, id: 'other-role' })]
+ useMocks({
+ get: {
+ '/api/projects/:project_id/user_customer_analytics_config/@me/': {
+ pinned_properties: [
+ { kind: 'relationship', id: relationshipDefinition.id },
+ { kind: 'custom_property', id: definition.id },
+ ],
+ },
+ '/api/projects/:project_id/custom_property_definitions/': { count: 1, results: [definition] },
+ '/api/projects/:project_id/account_relationship_definitions/': {
+ count: 1,
+ results: [relationshipDefinition],
+ },
+ [VALUES_URL]: ({ params }) =>
+ storedValue === null
+ ? []
+ : [
+ {
+ id: 'value-1',
+ definition_id: definition.id,
+ account_id: params.account_id,
+ value: params.account_id === 'account-2' ? 'Other account' : storedValue,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by_id: 1,
+ },
+ ],
+ [RELATIONSHIPS_URL]: () => assignments,
+ },
+ post: {
+ [VALUES_URL]: async ({ request }) => {
+ const body = (await request.json()) as CustomPropertyValueWriteApi
+ storedValue = body.value
+ return storedValue === null
+ ? [204, null]
+ : [201, { id: 'new-value', definition_id: body.definition, value: storedValue }]
+ },
+ [RELATIONSHIPS_URL]: async ({ request }) => {
+ const body = (await request.json()) as AccountRelationshipWriteApi
+ const next = assignment(body.user)
+ assignments.push(next)
+ return [201, next]
+ },
+ '/api/projects/:project_id/accounts/:account_id/relationships/:id/end/': ({ params }) => {
+ assignments = assignments.map((row) =>
+ row.id === params.id ? { ...row, ended_at: '2026-01-02T00:00:00Z' } : row
+ )
+ return assignments.find((row) => row.id === params.id)!
+ },
+ },
+ })
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ resumeKeaLoadersErrors()
+ jest.clearAllMocks()
+ })
+
+ it('defers account data until pinning and recovers the empty state after an account-data failure', async () => {
+ silenceKeaLoadersErrors()
+ const accountDataRequest = jest.fn(() => [500, { detail: 'Account data unavailable' }])
+ useMocks({
+ get: {
+ '/api/projects/:project_id/user_customer_analytics_config/@me/': { pinned_properties: [] },
+ [VALUES_URL]: accountDataRequest,
+ [RELATIONSHIPS_URL]: accountDataRequest,
+ },
+ patch: {
+ '/api/projects/:project_id/user_customer_analytics_config/@me/': async ({ request }) => [
+ 200,
+ await request.json(),
+ ],
+ },
+ })
+ logic = accountSidebarPropertiesLogic({ projectId: 1, accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({
+ propertyData: null,
+ propertyDataLoadFailed: false,
+ sidebarProperties: [],
+ })
+ expect(accountDataRequest).not.toHaveBeenCalled()
+ const config = accountSidebarConfigLogic({ projectId: 1 })
+ config.actions.beginConfiguring()
+ config.actions.setDraftPinnedProperties([{ kind: 'custom_property', id: definition.id }])
+ expect(config.values.canSavePinnedProperties).toBe(true)
+ await expectLogic(logic, () => config.actions.savePinnedProperties()).toFinishAllListeners()
+ expect(logic.values.propertyDataLoadFailed).toBe(true)
+ expect(accountDataRequest).toHaveBeenCalled()
+ accountDataRequest.mockClear()
+ config.actions.beginConfiguring()
+ config.actions.setDraftPinnedProperties([])
+ await expectLogic(logic, () => config.actions.savePinnedProperties()).toFinishAllListeners()
+ expect(logic.values.propertyDataLoadFailed).toBe(false)
+ expect(logic.values.sidebarProperties).toEqual([])
+ expect(accountDataRequest).not.toHaveBeenCalled()
+ })
+
+ it('blocks the panel only until properties load, then keeps them through a failed refresh', async () => {
+ silenceKeaLoadersErrors()
+ let accountDataFails = true
+ const accountData = <T>(rows: () => T): (() => T | [number, { detail: string }]) => {
+ return () => (accountDataFails ? [500, { detail: 'Account data unavailable' }] : rows())
+ }
+ useMocks({
+ get: {
+ [VALUES_URL]: accountData(() => [{ id: 'value-1', definition_id: definition.id, value: storedValue }]),
+ [RELATIONSHIPS_URL]: accountData(() => assignments),
+ },
+ })
+ logic = accountSidebarPropertiesLogic({ projectId: 1, accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({
+ propertiesPanelState: 'failed',
+ propertiesRefreshFailed: false,
+ sidebarProperties: [],
+ })
+
+ accountDataFails = false
+ await expectLogic(logic, () => logic.actions.loadPropertyData())
+ .toFinishAllListeners()
+ .toMatchValues({ propertiesPanelState: 'ready', propertiesRefreshFailed: false })
+
+ accountDataFails = true
+ logic.actions.editProperty(logic.values.sidebarProperties[1])
+ await expectLogic(logic, () => logic.actions.loadPropertyData())
+ .toFinishAllListeners()
+ .toMatchValues({
+ propertiesPanelState: 'ready',
+ propertiesRefreshFailed: true,
+ editingPropertyKey: 'custom:property-1',
+ })
+ expect(logic.values.sidebarProperties[1]).toMatchObject({ value: 'Starter' })
+ })
+
+ it('refreshes from relationship-tab changes without mounting that tab for the sidebar', async () => {
+ logic = accountSidebarPropertiesLogic({ projectId: MOCK_DEFAULT_TEAM.id, accountId: 'account-1' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(accountRelationshipsLogic.findMounted({ accountId: 'account-1' })).toBeNull()
+ const tab = accountRelationshipsLogic({ accountId: 'account-1' })
+ tab.mount()
+ try {
+ await expectLogic(tab).toFinishAllListeners()
+ assignments.push(assignment(4))
+ await expectLogic(logic, () => tab.actions.loadRelationships()).toFinishAllListeners()
+ expect(logic.values.sidebarProperties[0]).toMatchObject({ members: [{ id: 1 }, { id: 2 }, { id: 4 }] })
+ } finally {
+ tab.unmount()
+ }
+ })
+
+ it.each([
+ ['text', 'Growth'],
+ ['number', 0],
+ ['boolean', false],
+ ['clear', null],
+ ])('saves %s values and reloads the row', async (_, value) => {
+ const captureSpy = jest.spyOn(posthog, 'capture')
+ await mount()
+ const property = logic.values.sidebarProperties[1]
+ logic.actions.editProperty(property)
+ await expectLogic(logic, () => logic.actions.saveCustomProperty(property.key, value))
+ .toFinishAllListeners()
+ .toMatchValues({ editingPropertyKey: null, savingPropertyKey: null })
+ expect(storedValue).toBe(value)
+ expect(logic.values.sidebarProperties[1]).toMatchObject({ value })
+ expect(captureSpy).toHaveBeenCalledWith(AccountsEvents.CustomPropertyUpdated, {
+ display_type: 'text',
+ workflow_reference: false,
+ source: 'account_sidebar',
+ })
+ })
+
+ it('reports saved values and assignments as account product events', async () => {
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ await mount()
+ await expectLogic(logic, () =>
+ logic.actions.saveCustomProperty('custom:property-1', 'Growth')
+ ).toFinishAllListeners()
+ expect(capture).toHaveBeenCalledWith(AccountsEvents.CustomPropertyUpdated, {
+ display_type: 'text',
+ workflow_reference: false,
+ source: 'account_sidebar',
+ })
+ await expectLogic(logic, () =>
+ logic.actions.saveRelationship('relationship:relationship-1', [2])
+ ).toFinishAllListeners()
+ expect(capture).toHaveBeenCalledWith(AccountsEvents.RoleAssigned, {
+ role: relationshipDefinition.name,
+ is_assigned: true,
+ assigned_user_id: 2,
+ source: 'account_sidebar',
+ })
+ })
+
+ it('keeps the editor and existing value after a failed save', async () => {
+ silenceKeaLoadersErrors()
+ useMocks({ post: { [VALUES_URL]: () => [400, { detail: 'Invalid value' }] } })
+ await mount()
+ logic.actions.editProperty(logic.values.sidebarProperties[1])
+ await expectLogic(logic, () => logic.actions.saveCustomProperty('custom:property-1', 'invalid'))
+ .toFinishAllListeners()
+ .toMatchValues({
+ editingPropertyKey: 'custom:property-1',
+ savingPropertyKey: null,
+ propertySaveFailed: true,
+ })
+ expect(logic.values.sidebarProperties[1]).toMatchObject({ value: 'Starter' })
+ })
+
+ it('replaces a multi-holder selection without ending retained or unrelated assignments', async () => {
+ const captureSpy = jest.spyOn(posthog, 'capture')
+ await mount()
+ await expectLogic(logic, () =>
+ logic.actions.saveRelationship('relationship:relationship-1', [2, 4])
+ ).toFinishAllListeners()
+ expect(
+ assignments
+ .filter((row) => !row.ended_at)
+ .map((row) => row.user?.id)
+ .sort()
+ ).toEqual([2, 3, 4])
+ expect(logic.values.sidebarProperties[0]).toMatchObject({ members: [{ id: 2 }, { id: 4 }] })
+ await expectLogic(logic, () =>
+ logic.actions.saveRelationship('relationship:relationship-1', [])
+ ).toFinishAllListeners()
+ expect(assignments.filter((row) => !row.ended_at).map((row) => row.user?.id)).toEqual([3])
+ expect(assignments).toHaveLength(4)
+ expect(captureSpy).toHaveBeenCalledWith(AccountsEvents.RoleAssigned, {
+ role: relationshipDefinition.name,
+ is_assigned: true,
+ assigned_user_id: null,
+ source: 'account_sidebar',
+ })
+ })
+
+ it.each([
+ { label: 'unchanged', desired: [1, 2], expected: [2, 4], reassign: false },
+ { label: 'added holder', desired: [1, 2, 5], expected: [2, 4, 5], reassign: false },
+ { label: 'removed holder', desired: [2, 5], expected: [2, 4, 5], reassign: false },
+ { label: 'reassigned holder', desired: [2, 5], expected: [1, 2, 4, 5], reassign: true },
+ ])('preserves concurrent assignments when saving $label', async ({ desired, expected, reassign }) => {
+ await mount()
+ logic.actions.editProperty(logic.values.sidebarProperties[0])
+ assignments = assignments.map((row) =>
+ row.id === 'assignment-1' ? { ...row, ended_at: '2026-01-02T00:00:00Z' } : row
+ )
+ assignments.push(assignment(4))
+ if (reassign) {
+ assignments.push({ ...assignment(1), id: 'concurrent-reassignment' })
+ }
+ await expectLogic(logic, () => logic.actions.loadPropertyData()).toFinishAllListeners()
+ await expectLogic(logic, () =>
+ logic.actions.saveRelationship('relationship:relationship-1', desired)
+ ).toFinishAllListeners()
+ const property = logic.values.sidebarProperties[0]
+ expect(property.kind === 'relationship' && property.members.map((member) => member.id).sort()).toEqual(expected)
+ expect(assignments.find((row) => row.id === 'assignment-4')?.ended_at).toBeNull()
+ })
+
+ it('retains loaded rows and the edit after both a save and its refresh fail', async () => {
+ silenceKeaLoadersErrors()
+ await mount()
+ logic.actions.editProperty(logic.values.sidebarProperties[0])
+ const data = logic.values.propertyData
+ useMocks({
+ get: {
+ [VALUES_URL]: () => [500, { detail: 'Unavailable' }],
+ [RELATIONSHIPS_URL]: () => [500, { detail: 'Unavailable' }],
+ },
+ })
+ await expectLogic(logic, () => logic.actions.saveRelationship('relationship:relationship-1', [2, 4]))
+ .toFinishAllListeners()
+ .toMatchValues({
+ propertySaveFailed: true,
+ propertyDataLoadFailed: true,
+ editingPropertyKey: 'relationship:relationship-1',
+ })
+ expect(logic.values.propertyData).toEqual(data)
+ expect(logic.values.sidebarProperties).toHaveLength(2)
+ })
+
+ it.each([true, false])(
+ 'retries a partial addition without duplicates (keep the addition: %s)',
+ async (keepAddition) => {
+ silenceKeaLoadersErrors()
+ let fail = true
+ useMocks({
+ post: {
+ [RELATIONSHIPS_URL]: async ({ request }) => {
+ const { user } = (await request.json()) as AccountRelationshipWriteApi
+ if (user === 5 && fail) {
+ return [500, { detail: 'Try again' }]
+ }
+ const row = assignment(user)
+ assignments.push(row)
+ return [201, row]
+ },
+ },
+ })
+ await mount()
+ logic.actions.editProperty(logic.values.sidebarProperties[0])
+ await expectLogic(logic, () => logic.actions.saveRelationship('relationship:relationship-1', [2, 4, 5]))
+ .toFinishAllListeners()
+ .toMatchValues({ propertySaveFailed: true, editingPropertyKey: 'relationship:relationship-1' })
+ expect(logic.values.sidebarProperties[0]).toMatchObject({ members: [{ id: 1 }, { id: 2 }, { id: 4 }] })
+ fail = false
+ await expectLogic(logic, () =>
+ logic.actions.saveRelationship('relationship:relationship-1', keepAddition ? [2, 4, 5] : [2, 5])
+ )
+ .toFinishAllListeners()
+ .toMatchValues({ propertySaveFailed: false, editingPropertyKey: null })
+ expect(assignments.filter((row) => row.user?.id === 4)).toHaveLength(1)
+ expect(logic.values.sidebarProperties[0]).toMatchObject({
+ members: (keepAddition ? [2, 4, 5] : [2, 5]).map((id) => ({ id })),
+ })
+ }
+ )
+
+ it('can restore its own ended holder when changing a draft after a partial failure', async () => {
+ silenceKeaLoadersErrors()
+ let fail = true
+ useMocks({
+ post: {
+ '/api/projects/:project_id/accounts/:account_id/relationships/:id/end/': ({ params }) => {
+ if (params.id === 'assignment-2' && fail) {
+ return [500, { detail: 'Try again' }]
+ }
+ assignments = assignments.map((row) =>
+ row.id === params.id ? { ...row, ended_at: '2026-01-02T00:00:00Z' } : row
+ )
+ return assignments.find((row) => row.id === params.id)!
+ },
+ [RELATIONSHIPS_URL]: async ({ request }) => {
+ const { user } = (await request.json()) as AccountRelationshipWriteApi
+ const row = { ...assignment(user), id: `restored-${user}` }
+ assignments.push(row)
+ return [201, row]
+ },
+ },
+ })
+ await mount()
+ logic.actions.editProperty(logic.values.sidebarProperties[0])
+ await expectLogic(logic, () => logic.actions.saveRelationship('relationship:relationship-1', []))
+ .toFinishAllListeners()
+ .toMatchValues({ propertySaveFailed: true })
+ fail = false
+ await expectLogic(logic, () => logic.actions.saveRelationship('relationship:relationship-1', [1]))
+ .toFinishAllListeners()
+ .toMatchValues({ propertySaveFailed: false })
+ expect(logic.values.sidebarProperties[0]).toMatchObject({ members: [{ id: 1 }] })
+ expect(assignments.filter((row) => row.user?.id === 1)).toHaveLength(2)
+ })
+
+ it('lets the server end the previous single-holder assignment when replacing it', async () => {
+ const single = { ...relationshipDefinition, is_single_holder: true }
+ assignments = [assignment(1, single)]
+ const endRequest = jest.fn(() => [409, { detail: 'Already ended' }])
+ useMocks({
+ get: { '/api/projects/:project_id/account_relationship_definitions/': { count: 1, results: [single] } },
+ post: {
+ [RELATIONSHIPS_URL]: async ({ request }) => {
+ const { user } = (await request.json()) as AccountRelationshipWriteApi
+ assignments = assignments.map((row) => ({ ...row, ended_at: '2026-01-02T00:00:00Z' }))
+ const row = assignment(user, single)
+ assignments.push(row)
+ return [201, row]
+ },
+ '/api/projects/:project_id/accounts/:account_id/relationships/:id/end/': endRequest,
+ },
+ })
+ await mount()
+ await expectLogic(logic, () =>
+ logic.actions.saveRelationship('relationship:relationship-1', [2, 3])
+ ).toFinishAllListeners()
+ expect(assignments).toHaveLength(1)
+ await expectLogic(logic, () => logic.actions.saveRelationship('relationship:relationship-1', [2]))
+ .toFinishAllListeners()
+ .toMatchValues({ propertySaveFailed: false })
+ expect(logic.values.sidebarProperties[0]).toMatchObject({ members: [{ id: 2 }] })
+ expect(assignments).toHaveLength(2)
+ expect(endRequest).not.toHaveBeenCalled()
+ })
+
+ it('does not edit or save properties without resource-level editor access', async () => {
+ jest.mocked(userHasAccess).mockReturnValueOnce(false)
+ await mount()
+ const write = jest.fn()
+ useMocks({ post: { [VALUES_URL]: write, [RELATIONSHIPS_URL]: write } })
+ for (const property of logic.values.sidebarProperties) {
+ expect(property.editable).toBe(false)
+ logic.actions.editProperty(property)
+ }
+ await expectLogic(logic, () => {
+ logic.actions.saveCustomProperty('custom:property-1', 'blocked')
+ logic.actions.saveRelationship('relationship:relationship-1', [4])
+ }).toFinishAllListeners()
+ expect(logic.values.editingPropertyKey).toBeNull()
+ expect(write).not.toHaveBeenCalled()
+ })
+
+ it('does not show another account values while loading', async () => {
+ await mount()
+ const other = accountSidebarPropertiesLogic({ projectId: 1, accountId: 'account-2' })
+ other.mount()
+ try {
+ expect(other.values.sidebarProperties).toEqual([])
+ await expectLogic(other).toFinishAllListeners()
+ expect(other.values.sidebarProperties[1]).toMatchObject({ value: 'Other account' })
+ expect(logic.values.sidebarProperties[1]).toMatchObject({ value: 'Starter' })
+ } finally {
+ other.unmount()
+ }
+ })
+
+ it.each([
+ ['canonical', { is_canonical: true }],
+ ['warehouse', { source: { id: 'source-1' } }],
+ ['workflow', { has_workflow_reference: true }],
+ ])('resolves %s provenance and restricts editing', async (provenance, overrides) => {
+ useMocks({
+ get: {
+ '/api/projects/:project_id/custom_property_definitions/': {
+ count: 1,
+ results: [{ ...definition, ...overrides }],
+ },
+ },
+ })
+ await mount()
+ const property = logic.values.sidebarProperties[1]
+ expect(property).toMatchObject({ provenance })
+ logic.actions.editProperty(property)
+ expect(logic.values.editingPropertyKey).toBe(provenance === 'workflow' ? property.key : null)
+ await expectLogic(logic, () => logic.actions.saveCustomProperty(property.key, 'Updated')).toFinishAllListeners()
+ expect(storedValue).toBe(provenance === 'workflow' ? 'Updated' : 'Starter')
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts
new file mode 100644
index 000000000000..ec655816fdcd
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts
@@ -0,0 +1,634 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { membersLogic } from 'scenes/organization/membersLogic'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { AccessControlLevel, AccessControlResourceType, OrganizationMemberType } from '~/types'
+
+import { accountRelationshipsLogic } from 'products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic'
+import { ROLE_KEY_BY_NAME } from 'products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic'
+import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'
+import {
+ ACCOUNTS_METRICS_DATA_NODE_KEY,
+ ACCOUNTS_TABLE_DATA_NODE_KEY,
+} from 'products/customer_analytics/frontend/constants'
+import * as api from 'products/customer_analytics/frontend/generated/api'
+import type { UserCustomerAnalyticsConfigApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import {
+ accountSidebarConfigLogic,
+ AvailableDefinitions,
+ ResolvedPinnedAccountProperty,
+} from './accountSidebarConfigLogic'
+import { AccountSidebarPropertyData, buildAccountSidebarProperties } from './accountSidebarProperties'
+import {
+ AccountCustomPropertyValue,
+ AccountRelationshipProperty,
+ AccountRelationshipMember,
+ AccountSidebarProperty,
+ isCustomPropertyEditable,
+} from './components/accountPropertyTypes'
+
+export interface AccountSidebarPropertiesLogicProps {
+ accountId: string
+ projectId: number
+}
+
+export type AccountPropertiesPanelState = 'loading' | 'failed' | 'ready'
+
+export interface RelationshipEditBaseline {
+ propertyKey: string
+ memberIds: number[]
+ assignmentIds: string[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountSidebarPropertiesLogicValues {
+ availableDefinitions: AvailableDefinitions | null // accountSidebarConfigLogic
+ availableDefinitionsLoadFailed: boolean // accountSidebarConfigLogic
+ config: UserCustomerAnalyticsConfigApi | null // accountSidebarConfigLogic
+ configLoadFailed: boolean // accountSidebarConfigLogic
+ resolvedPinnedProperties: ResolvedPinnedAccountProperty[] // accountSidebarConfigLogic
+ members: OrganizationMemberType[] | null // membersLogic
+ membersLoading: boolean // membersLogic
+ availableMembers: AccountRelationshipMember[]
+ editingPropertyKey: string | null
+ propertiesAvailable: boolean
+ propertiesLoadFailed: boolean
+ propertiesPanelState: AccountPropertiesPanelState
+ propertiesRefreshFailed: boolean
+ propertyData: AccountSidebarPropertyData | null
+ propertyDataLoadFailed: boolean
+ propertyDataLoading: boolean
+ propertySaveFailed: boolean
+ relationshipEditBaseline: RelationshipEditBaseline | null
+ savedPropertyKey: string | null
+ savedPropertyKeyLoading: boolean
+ savingPropertyKey: string | null
+ sidebarProperties: AccountSidebarProperty[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountSidebarPropertiesLogicActions {
+ ensureAllMembersLoaded: () => {
+ value: true
+ } // membersLogic
+ cancelEditing: () => {
+ value: true
+ }
+ editProperty: (property: AccountSidebarProperty) => {
+ property: AccountSidebarProperty
+ }
+ loadPropertyData: (_: void) => void
+ loadPropertyDataFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPropertyDataSuccess: (
+ propertyData: AccountSidebarPropertyData | null,
+ payload?: void
+ ) => {
+ propertyData: AccountSidebarPropertyData | null
+ payload?: void
+ }
+ persistCustomProperty: ({
+ propertyKey,
+ definitionId,
+ value,
+ }: {
+ definitionId: string
+ propertyKey: string
+ value: AccountCustomPropertyValue
+ }) => {
+ propertyKey: string
+ definitionId: string
+ value: AccountCustomPropertyValue
+ }
+ persistCustomPropertyFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ persistCustomPropertySuccess: (
+ savedPropertyKey: string,
+ payload?: {
+ propertyKey: string
+ definitionId: string
+ value: AccountCustomPropertyValue
+ }
+ ) => {
+ savedPropertyKey: string
+ payload?: {
+ propertyKey: string
+ definitionId: string
+ value: AccountCustomPropertyValue
+ }
+ }
+ persistRelationship: ({
+ propertyKey,
+ definitionId,
+ memberIds,
+ singleHolder,
+ baseline,
+ }: {
+ baseline: RelationshipEditBaseline
+ definitionId: string
+ memberIds: number[]
+ propertyKey: string
+ singleHolder: boolean
+ }) => {
+ propertyKey: string
+ definitionId: string
+ memberIds: number[]
+ singleHolder: boolean
+ baseline: RelationshipEditBaseline
+ }
+ persistRelationshipFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ persistRelationshipSuccess: (
+ savedPropertyKey: string,
+ payload?: {
+ propertyKey: string
+ definitionId: string
+ memberIds: number[]
+ singleHolder: boolean
+ baseline: RelationshipEditBaseline
+ }
+ ) => {
+ savedPropertyKey: string
+ payload?: {
+ propertyKey: string
+ definitionId: string
+ memberIds: number[]
+ singleHolder: boolean
+ baseline: RelationshipEditBaseline
+ }
+ }
+ recordRelationshipAddition: (
+ propertyKey: string,
+ memberId: number,
+ assignmentId: string
+ ) => {
+ assignmentId: string
+ memberId: number
+ propertyKey: string
+ }
+ recordRelationshipRemoval: (
+ propertyKey: string,
+ memberId: number,
+ assignmentId: string
+ ) => {
+ assignmentId: string
+ memberId: number
+ propertyKey: string
+ }
+ saveCustomProperty: (
+ propertyKey: string,
+ value: AccountCustomPropertyValue
+ ) => {
+ propertyKey: string
+ value: AccountCustomPropertyValue
+ }
+ saveRelationship: (
+ propertyKey: string,
+ memberIds: number[]
+ ) => {
+ memberIds: number[]
+ propertyKey: string
+ }
+ setRelationshipEditBaseline: (baseline: RelationshipEditBaseline) => {
+ baseline: RelationshipEditBaseline
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountSidebarPropertiesLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ sidebarProperties: (
+ resolvedPinnedProperties: ResolvedPinnedAccountProperty[],
+ propertyData: AccountSidebarPropertyData | null
+ ) => AccountSidebarProperty[]
+ availableMembers: (
+ members: OrganizationMemberType[] | null,
+ propertyData: AccountSidebarPropertyData | null
+ ) => AccountRelationshipMember[]
+ propertiesAvailable: (
+ config: UserCustomerAnalyticsConfigApi | null,
+ availableDefinitions: AvailableDefinitions | null,
+ resolvedPinnedProperties: ResolvedPinnedAccountProperty[],
+ propertyData: AccountSidebarPropertyData | null
+ ) => boolean
+ propertiesLoadFailed: (
+ configLoadFailed: boolean,
+ availableDefinitionsLoadFailed: boolean,
+ resolvedPinnedProperties: ResolvedPinnedAccountProperty[],
+ propertyDataLoadFailed: boolean
+ ) => boolean
+ propertiesPanelState: (
+ propertiesAvailable: boolean,
+ propertiesLoadFailed: boolean
+ ) => AccountPropertiesPanelState
+ propertiesRefreshFailed: (propertiesAvailable: boolean, propertiesLoadFailed: boolean) => boolean
+ }
+}
+
+export type accountSidebarPropertiesLogicType = MakeLogicType<
+ accountSidebarPropertiesLogicValues,
+ accountSidebarPropertiesLogicActions,
+ AccountSidebarPropertiesLogicProps,
+ accountSidebarPropertiesLogicMeta
+>
+
+export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertiesLogicType> =
+ kea<accountSidebarPropertiesLogicType>([
+ props({} as AccountSidebarPropertiesLogicProps),
+ key(({ projectId, accountId }) => `${projectId}:${accountId}`),
+ path((key) => ['products', 'customer_analytics', 'accountSidebarPropertiesLogic', key]),
+ connect(({ projectId }: AccountSidebarPropertiesLogicProps) => ({
+ values: [
+ accountSidebarConfigLogic({ projectId }),
+ [
+ 'availableDefinitions',
+ 'availableDefinitionsLoadFailed',
+ 'config',
+ 'configLoadFailed',
+ 'resolvedPinnedProperties',
+ ],
+ membersLogic,
+ ['members', 'membersLoading'],
+ ],
+ actions: [membersLogic, ['ensureAllMembersLoaded']],
+ })),
+ actions({
+ editProperty: (property: AccountSidebarProperty) => ({ property }),
+ cancelEditing: true,
+ saveCustomProperty: (propertyKey: string, value: AccountCustomPropertyValue) => ({ propertyKey, value }),
+ saveRelationship: (propertyKey: string, memberIds: number[]) => ({ propertyKey, memberIds }),
+ setRelationshipEditBaseline: (baseline: RelationshipEditBaseline) => ({ baseline }),
+ recordRelationshipRemoval: (propertyKey: string, memberId: number, assignmentId: string) => ({
+ propertyKey,
+ memberId,
+ assignmentId,
+ }),
+ recordRelationshipAddition: (propertyKey: string, memberId: number, assignmentId: string) => ({
+ propertyKey,
+ memberId,
+ assignmentId,
+ }),
+ }),
+ loaders(({ props, values, actions }) => ({
+ propertyData: [
+ null as AccountSidebarPropertyData | null,
+ {
+ loadPropertyData: async (_: void, breakpoint): Promise<AccountSidebarPropertyData | null> => {
+ if (values.resolvedPinnedProperties.length === 0) {
+ return null
+ }
+ const [customValues, relationships] = await Promise.all([
+ api.accountsCustomPropertyValuesList(String(props.projectId), props.accountId),
+ api.accountsRelationshipsList(String(props.projectId), props.accountId),
+ ])
+ breakpoint()
+ return { customValues, relationships }
+ },
+ },
+ ],
+ savedPropertyKey: [
+ null as string | null,
+ {
+ persistCustomProperty: async ({
+ propertyKey,
+ definitionId,
+ value,
+ }: {
+ propertyKey: string
+ definitionId: string
+ value: AccountCustomPropertyValue
+ }): Promise<string> => {
+ await api.accountsCustomPropertyValuesCreate(String(props.projectId), props.accountId, {
+ definition: definitionId,
+ value,
+ })
+ return propertyKey
+ },
+ persistRelationship: async ({
+ propertyKey,
+ definitionId,
+ memberIds,
+ singleHolder,
+ baseline,
+ }: {
+ propertyKey: string
+ definitionId: string
+ memberIds: number[]
+ singleHolder: boolean
+ baseline: RelationshipEditBaseline
+ }): Promise<string> => {
+ const projectId = String(props.projectId)
+ const current = await api.accountsRelationshipsList(projectId, props.accountId)
+ const assignments = current.filter(
+ (relationship) => relationship.definition.id === definitionId && !relationship.ended_at
+ )
+ const additions = memberIds.filter(
+ (id) =>
+ !baseline.memberIds.includes(id) &&
+ !assignments.some((relationship) => relationship.user?.id === id)
+ )
+ for (const user of additions) {
+ const created = await api.accountsRelationshipsCreate(projectId, props.accountId, {
+ definition: definitionId,
+ user,
+ })
+ actions.recordRelationshipAddition(propertyKey, user, created.id)
+ }
+ if (!singleHolder || additions.length === 0) {
+ for (const relationship of assignments) {
+ if (
+ baseline.assignmentIds.includes(relationship.id) &&
+ relationship.user &&
+ !memberIds.includes(relationship.user.id)
+ ) {
+ await api.accountsRelationshipsEndCreate(
+ projectId,
+ props.accountId,
+ relationship.id
+ )
+ actions.recordRelationshipRemoval(
+ propertyKey,
+ relationship.user.id,
+ relationship.id
+ )
+ }
+ }
+ }
+ return propertyKey
+ },
+ },
+ ],
+ })),
+ reducers({
+ relationshipEditBaseline: [
+ null as RelationshipEditBaseline | null,
+ {
+ setRelationshipEditBaseline: (_, { baseline }) => baseline,
+ recordRelationshipRemoval: (baseline, { propertyKey, memberId, assignmentId }) =>
+ baseline?.propertyKey === propertyKey
+ ? {
+ ...baseline,
+ memberIds: baseline.memberIds.filter((id) => id !== memberId),
+ assignmentIds: baseline.assignmentIds.filter((id) => id !== assignmentId),
+ }
+ : baseline,
+ recordRelationshipAddition: (baseline, { propertyKey, memberId, assignmentId }) =>
+ baseline?.propertyKey === propertyKey
+ ? {
+ ...baseline,
+ memberIds: [...new Set([...baseline.memberIds, memberId])],
+ assignmentIds: [...new Set([...baseline.assignmentIds, assignmentId])],
+ }
+ : baseline,
+ cancelEditing: () => null,
+ persistRelationshipSuccess: () => null,
+ persistCustomPropertySuccess: () => null,
+ },
+ ],
+ editingPropertyKey: [
+ null as string | null,
+ {
+ editProperty: (state, { property }) =>
+ property.editable !== false &&
+ (property.kind === 'relationship' || isCustomPropertyEditable(property.provenance))
+ ? property.key
+ : state,
+ cancelEditing: () => null,
+ persistCustomPropertySuccess: () => null,
+ persistRelationshipSuccess: () => null,
+ },
+ ],
+ savingPropertyKey: [
+ null as string | null,
+ {
+ persistCustomProperty: (_, { propertyKey }) => propertyKey,
+ persistRelationship: (_, { propertyKey }) => propertyKey,
+ persistCustomPropertySuccess: () => null,
+ persistRelationshipSuccess: () => null,
+ persistCustomPropertyFailure: () => null,
+ persistRelationshipFailure: () => null,
+ },
+ ],
+ propertyDataLoadFailed: [
+ false,
+ {
+ loadPropertyData: () => false,
+ loadPropertyDataSuccess: () => false,
+ loadPropertyDataFailure: () => true,
+ },
+ ],
+ propertySaveFailed: [
+ false,
+ {
+ editProperty: () => false,
+ cancelEditing: () => false,
+ persistCustomProperty: () => false,
+ persistRelationship: () => false,
+ persistCustomPropertyFailure: () => true,
+ persistRelationshipFailure: () => true,
+ },
+ ],
+ }),
+ selectors({
+ sidebarProperties: [
+ (s) => [s.resolvedPinnedProperties, s.propertyData],
+ (
+ pinned: ResolvedPinnedAccountProperty[],
+ data: AccountSidebarPropertyData | null
+ ): AccountSidebarProperty[] =>
+ buildAccountSidebarProperties(
+ pinned,
+ data,
+ userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Editor)
+ ),
+ ],
+ availableMembers: [
+ (s) => [s.members, s.propertyData],
+ (
+ members: OrganizationMemberType[] | null,
+ data: AccountSidebarPropertyData | null
+ ): AccountRelationshipMember[] => {
+ const byId = new Map<number, AccountRelationshipMember>()
+ for (const relationship of data?.relationships ?? []) {
+ if (relationship.user) {
+ byId.set(relationship.user.id, relationship.user)
+ }
+ }
+ for (const member of members ?? []) {
+ byId.set(member.user.id, {
+ id: member.user.id,
+ email: member.user.email,
+ name: member.user.first_name,
+ })
+ }
+ return [...byId.values()]
+ },
+ ],
+ propertiesAvailable: [
+ (s) => [s.config, s.availableDefinitions, s.resolvedPinnedProperties, s.propertyData],
+ (
+ config: UserCustomerAnalyticsConfigApi | null,
+ definitions: AvailableDefinitions | null,
+ pinned: ResolvedPinnedAccountProperty[],
+ data: AccountSidebarPropertyData | null
+ ): boolean => config !== null && definitions !== null && (pinned.length === 0 || data !== null),
+ ],
+ propertiesLoadFailed: [
+ (s) => [
+ s.configLoadFailed,
+ s.availableDefinitionsLoadFailed,
+ s.resolvedPinnedProperties,
+ s.propertyDataLoadFailed,
+ ],
+ (
+ configFailed: boolean,
+ definitionsFailed: boolean,
+ pinned: ResolvedPinnedAccountProperty[],
+ dataFailed: boolean
+ ): boolean => configFailed || definitionsFailed || (pinned.length > 0 && dataFailed),
+ ],
+ // A failed load keeps the values of the previous successful load, so the blocking error
+ // state is only for a panel that has nothing to show.
+ propertiesPanelState: [
+ (s) => [s.propertiesAvailable, s.propertiesLoadFailed],
+ (available: boolean, failed: boolean): AccountPropertiesPanelState =>
+ available ? 'ready' : failed ? 'failed' : 'loading',
+ ],
+ propertiesRefreshFailed: [
+ (s) => [s.propertiesAvailable, s.propertiesLoadFailed],
+ (available: boolean, failed: boolean): boolean => available && failed,
+ ],
+ }),
+ listeners(({ actions, props, values }) => {
+ const baselineFor = (property: AccountRelationshipProperty): RelationshipEditBaseline => ({
+ propertyKey: property.key,
+ memberIds: property.members.map(({ id }) => id),
+ assignmentIds: (values.propertyData?.relationships ?? [])
+ .filter((row) => row.definition.id === property.definition.id && !row.ended_at)
+ .map(({ id }) => id),
+ })
+ const refresh = (): void => {
+ actions.loadPropertyData()
+ accountRelationshipsLogic.findMounted({ accountId: props.accountId })?.actions.loadRelationships()
+ dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
+ dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
+ }
+ return {
+ editProperty: ({ property }) => {
+ if (property.kind === 'relationship' && property.editable !== false) {
+ actions.setRelationshipEditBaseline(baselineFor(property))
+ actions.ensureAllMembersLoaded()
+ }
+ },
+ saveCustomProperty: ({ propertyKey, value }) => {
+ const property = values.sidebarProperties.find((row) => row.key === propertyKey)
+ if (
+ values.savingPropertyKey ||
+ property?.kind !== 'custom' ||
+ property.editable === false ||
+ !isCustomPropertyEditable(property.provenance)
+ ) {
+ return
+ }
+ actions.persistCustomProperty({ propertyKey, definitionId: property.definition.id, value })
+ },
+ saveRelationship: ({ propertyKey, memberIds }) => {
+ const property = values.sidebarProperties.find((row) => row.key === propertyKey)
+ if (values.savingPropertyKey || property?.kind !== 'relationship' || property.editable === false) {
+ return
+ }
+ const selected = [...new Set(memberIds)]
+ if (property.definition.is_single_holder !== false && selected.length > 1) {
+ return
+ }
+ const baseline =
+ values.relationshipEditBaseline?.propertyKey === propertyKey
+ ? values.relationshipEditBaseline
+ : baselineFor(property)
+ if (
+ selected.length === baseline.memberIds.length &&
+ selected.every((id) => baseline.memberIds.includes(id))
+ ) {
+ actions.cancelEditing()
+ actions.loadPropertyData()
+ return
+ }
+ actions.setRelationshipEditBaseline(baseline)
+ actions.persistRelationship({
+ propertyKey,
+ definitionId: property.definition.id,
+ memberIds: selected,
+ singleHolder: property.definition.is_single_holder !== false,
+ baseline,
+ })
+ },
+ persistCustomPropertySuccess: ({ savedPropertyKey }) => {
+ const property = values.sidebarProperties.find((row) => row.key === savedPropertyKey)
+ if (property?.kind === 'custom') {
+ // The property name and value stay out because they can hold customer data.
+ posthog.capture(AccountsEvents.CustomPropertyUpdated, {
+ display_type: property.definition.display_type,
+ workflow_reference: property.definition.has_workflow_reference,
+ source: 'account_sidebar',
+ })
+ }
+ refresh()
+ },
+ persistRelationshipSuccess: ({ savedPropertyKey, payload }) => {
+ const property = values.sidebarProperties.find((row) => row.key === savedPropertyKey)
+ if (property?.kind === 'relationship') {
+ const memberIds = payload?.memberIds ?? []
+ posthog.capture(AccountsEvents.RoleAssigned, {
+ role: ROLE_KEY_BY_NAME[property.definition.name] ?? property.definition.name,
+ is_assigned: memberIds.length > 0,
+ assigned_user_id: memberIds.length === 1 ? memberIds[0] : null,
+ source: 'account_sidebar',
+ })
+ }
+ refresh()
+ },
+ persistRelationshipFailure: refresh,
+ [accountSidebarConfigLogic({ projectId: props.projectId }).actionTypes.loadConfigSuccess]: () =>
+ actions.loadPropertyData(),
+ [accountSidebarConfigLogic({ projectId: props.projectId }).actionTypes.persistPinnedPropertiesSuccess]:
+ () => actions.loadPropertyData(),
+ [accountSidebarConfigLogic({ projectId: props.projectId }).actionTypes.loadAvailableDefinitionsSuccess]:
+ () => actions.loadPropertyData(),
+ }
+ }),
+ afterMount(({ actions }) => actions.loadPropertyData()),
+ ])
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountCustomPropertyEditor.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountCustomPropertyEditor.tsx
index 051934933d2a..2699e507b512 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountCustomPropertyEditor.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountCustomPropertyEditor.tsx
@@ -141,6 +141,7 @@ export function AccountCustomPropertyEditor({
<div className="flex flex-col gap-2 w-full">
{definition.display_type === 'boolean' ? (
<LemonSwitch
+ disabled={saving}
checked={draft === true}
onChange={setDraft}
size="small"
@@ -149,6 +150,7 @@ export function AccountCustomPropertyEditor({
/>
) : definition.display_type === 'select' ? (
<LemonSelect
+ disabledReason={saving ? 'Saving' : undefined}
value={typeof draft === 'string' ? draft : ''}
onChange={(next) => setDraft(next ?? '')}
options={(definition.options ?? []).map((option) => ({ value: option.label, label: option.label }))}
@@ -194,7 +196,12 @@ export function AccountCustomPropertyEditor({
>
Clear value
</LemonButton>
- <LemonButton size="xsmall" onClick={onCancel} data-attr="account-property-cancel">
+ <LemonButton
+ size="xsmall"
+ onClick={onCancel}
+ disabledReason={saving ? 'Saving' : undefined}
+ data-attr="account-property-cancel"
+ >
Cancel
</LemonButton>
<LemonButton
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPinnedProperties.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPinnedProperties.tsx
index 070f37f0d687..70b5869054c2 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPinnedProperties.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPinnedProperties.tsx
@@ -14,6 +14,7 @@ export interface AccountPinnedPropertiesProps {
editingPropertyKey?: string | null
savingPropertyKey?: string | null
availableMembers?: AccountPropertyRowProps['availableMembers']
+ membersLoading?: boolean
onConfigure: () => void
onEdit: (property: AccountSidebarProperty) => void
onCancelEdit: () => void
@@ -44,6 +45,7 @@ export function AccountPinnedProperties({
editingPropertyKey = null,
savingPropertyKey = null,
availableMembers,
+ membersLoading,
onConfigure,
onEdit,
onCancelEdit,
@@ -52,7 +54,7 @@ export function AccountPinnedProperties({
}: AccountPinnedPropertiesProps): JSX.Element {
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">
+ <div className="flex items-center shrink-0 px-4 pt-4">
<span className="secondary text-secondary">Properties</span>
{properties.length > 0 ? (
<LemonButton
@@ -69,7 +71,7 @@ export function AccountPinnedProperties({
{properties.length === 0 ? (
<AccountPinnedPropertiesEmptyState onConfigure={onConfigure} />
) : (
- <div className="flex flex-col gap-4 min-h-0 overflow-y-auto px-5 pt-4 pb-5">
+ <div className="flex flex-col gap-4 min-h-0 overflow-y-auto px-4 pt-4 pb-5">
{properties.map((property) => (
<AccountPropertyRow
key={property.key}
@@ -77,6 +79,7 @@ export function AccountPinnedProperties({
editing={editingPropertyKey === property.key}
saving={savingPropertyKey === property.key}
availableMembers={availableMembers}
+ membersLoading={membersLoading}
onEdit={() => onEdit(property)}
onCancel={onCancelEdit}
onSaveCustomProperty={onSaveCustomProperty}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyRow.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyRow.tsx
index 1a3c0d630264..f562fc146f51 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyRow.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyRow.tsx
@@ -24,6 +24,7 @@ export interface AccountPropertyRowProps {
editing?: boolean
saving?: boolean
availableMembers?: AccountRelationshipMember[]
+ membersLoading?: boolean
onEdit: () => void
onCancel: () => void
onSaveCustomProperty: (property: AccountCustomProperty, value: AccountCustomPropertyValue) => void
@@ -35,13 +36,15 @@ export function AccountPropertyRow({
editing = false,
saving = false,
availableMembers = [],
+ membersLoading = false,
onEdit,
onCancel,
onSaveCustomProperty,
onSaveRelationship,
}: AccountPropertyRowProps): JSX.Element {
const editable =
- property.kind === 'custom' ? isCustomPropertyEditable(property.provenance) : property.editable !== false
+ property.editable !== false &&
+ (property.kind === 'relationship' || isCustomPropertyEditable(property.provenance))
const provenance =
property.kind === 'custom' && property.provenance !== 'manual' ? PROVENANCE[property.provenance] : null
@@ -83,6 +86,7 @@ export function AccountPropertyRow({
definition={property.definition}
members={property.members}
availableMembers={availableMembers}
+ membersLoading={membersLoading}
saving={saving}
onSave={(memberIds) => onSaveRelationship(property, memberIds)}
onCancel={onCancel}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountRelationshipEditor.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountRelationshipEditor.tsx
index bdf6636122e5..0a5212ff8c3d 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountRelationshipEditor.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountRelationshipEditor.tsx
@@ -10,6 +10,7 @@ export interface AccountRelationshipEditorProps {
definition: AccountRelationshipDefinitionApi
members: AccountRelationshipMember[]
availableMembers: AccountRelationshipMember[]
+ membersLoading?: boolean
saving?: boolean
onSave: (memberIds: number[]) => void
onCancel: () => void
@@ -19,6 +20,7 @@ export function AccountRelationshipEditor({
definition,
members,
availableMembers,
+ membersLoading = false,
saving = false,
onSave,
onCancel,
@@ -28,7 +30,7 @@ export function AccountRelationshipEditor({
const confirmClear = (): void => {
LemonDialog.open({
title: `Clear ${definition.name}?`,
- content: 'This will remove all current assignments. You can assign people again later.',
+ content: 'This clears the assignments you were editing. New assignments added elsewhere will be kept.',
primaryButton: {
children: 'Clear value',
status: 'danger',
@@ -43,6 +45,7 @@ export function AccountRelationshipEditor({
return (
<div className="flex flex-col gap-2 w-full">
<LemonInputSelect<number>
+ loading={membersLoading}
mode={definition.is_single_holder === false ? 'multiple' : 'single'}
value={draftMemberIds}
onChange={setDraftMemberIds}
@@ -63,12 +66,19 @@ export function AccountRelationshipEditor({
size="xsmall"
status="danger"
onClick={confirmClear}
- disabledReason={members.length === 0 ? 'This relationship is unassigned' : undefined}
+ disabledReason={
+ saving ? 'Saving' : members.length === 0 ? 'This relationship is unassigned' : undefined
+ }
data-attr="account-relationship-clear"
>
Clear value
</LemonButton>
- <LemonButton size="xsmall" onClick={onCancel} data-attr="account-relationship-cancel">
+ <LemonButton
+ size="xsmall"
+ onClick={onCancel}
+ disabledReason={saving ? 'Saving' : undefined}
+ data-attr="account-relationship-cancel"
+ >
Cancel
</LemonButton>
<LemonButton
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/accountPropertyTypes.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/accountPropertyTypes.ts
index 77e298ceddf1..fa4ac0648967 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/accountPropertyTypes.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/accountPropertyTypes.ts
@@ -21,6 +21,7 @@ export interface AccountCustomProperty {
definition: CustomPropertyDefinitionApi
value: AccountCustomPropertyValue
provenance: AccountCustomPropertyProvenance
+ editable?: boolean
}
export interface AccountRelationshipProperty {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 14e8db24eaee..c413070d0d25 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -20904,8 +20904,8 @@ export namespace Schemas {
export interface CustomPropertyValueWrite {
/** UUID of the custom property definition whose value to set for this account. */
definition: string;
- /** Value to store, matching the definition's type: a number for number/currency/percent, a boolean for boolean, an ISO-8601 string for date/datetime, an HTTP or HTTPS URL for link properties, or text for text properties. */
- value: string | number | boolean;
+ /** Value to store, matching the definition's type: a number for number/currency/percent, a boolean for boolean, an ISO-8601 string for date/datetime, an HTTP or HTTPS URL for link properties, or text for text properties. Null clears the current value while preserving its history. */
+ value: string | number | boolean | null;
}
export interface CustomerJourney {
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 82b32bd48aed..94fab7b89874 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -240,9 +240,9 @@ export const AccountsCustomPropertyValuesCreateParams = () => zod.object({
export const AccountsCustomPropertyValuesCreateBody = () => zod.object({
definition: zod.string().describe('UUID of the custom property definition whose value to set for this account.'),
value: zod
- .union([zod.string(), zod.number(), zod.boolean()])
+ .union([zod.string(), zod.number(), zod.boolean(), zod.null()])
.describe(
- "Value to store, matching the definition's type: a number for number\/currency\/percent, a boolean for boolean, an ISO-8601 string for date\/datetime, an HTTP or HTTPS URL for link properties, or text for text properties."
+ "Value to store, matching the definition's type: a number for number\/currency\/percent, a boolean for boolean, an ISO-8601 string for date\/datetime, an HTTP or HTTPS URL for link properties, or text for text properties. Null clears the current value while preserving its history."
),
})