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): add account properties view widget (#113540)

Arthur Moreira de Deus426bfadb0dfa
diff --git a/docs/internal/customer-analytics/account-sidebar.md b/docs/internal/customer-analytics/account-sidebar.md
index c4d425dd0f43..3db1e6db6807 100644
--- a/docs/internal/customer-analytics/account-sidebar.md
+++ b/docs/internal/customer-analytics/account-sidebar.md
@@ -64,10 +64,47 @@ the latest state.
`AccountPinnedPropertiesPanel` connects both views to the same configuration, loading states, and editors.
`AccountPropertyField` renders each label, source icon, value, and editor.
-Pin preferences belong to `accountSidebarConfigLogic`, keyed by project. Live values and
-editing state belong to `accountSidebarPropertiesLogic`, keyed by project and account.
+Pin preferences belong to `accountSidebarConfigLogic`, keyed by project.
+`accountPropertyDataLogic` holds live values, keyed by project and account.
+`accountSidebarPropertiesLogic` owns editing state for each property panel.
The Relationships tab and account list refresh after assignment changes.
Successful writes emit the existing custom-property and role-assignment events.
The source is `account_sidebar` for sidebar edits and `list_expansion` for expanded-list edits.
Custom-property events exclude property names and values;
role-assignment events retain the existing role metadata and internal-user identifiers.
+
+## Properties in account views
+
+With `customer-analytics-account-views` enabled, the view component picker offers Properties.
+Each tile stores its own ordered selection in the view document under `config.properties`.
+The tile's Edit action changes its selection and title through the existing view save flow.
+Adding a tile starts with an empty selection.
+These selections do not change sidebar pins or project defaults.
+
+Properties tiles show a vertical list of custom properties, relationships, and supported account properties.
+Tiles use the sidebar's horizontal padding, and editable rows place the pencil beside the property name in both surfaces.
+A tile shows the first ten visible properties before scrolling vertically to the remaining rows.
+The scrollbar sits at the card's right edge while property rows keep their horizontal padding.
+The viewport adjusts to wrapped values, open editors, and width changes.
+Account properties are website domain, billing ID, Slack channel ID, Salesforce ID, Stripe ID, email domains, and known emails.
+Stripe ID appears only when the current account already has one.
+Account name and arbitrary account property keys are not supported.
+Custom properties and relationships use the same editors and access rules as sidebar rows.
+Only project admins with account editor access can edit email domains and known emails.
+
+Account property saves use the account editor's fresh-read merge and list normalization.
+Local account editor and widget saves run in sequence to keep edits to different fields.
+Saved values refresh visible properties tiles and the sidebar without replacing other editors' drafts.
+Account reads do not broadcast changes to other editors.
+A read started before a save cannot replace that saved value.
+Relationship saves refresh every mounted Relationships tile and refresh the shared property data once.
+Custom-property saves do not reload Relationships tiles.
+Each tile keeps separate editor state for the current account.
+A failed save keeps the input for retry.
+Loading failures and refresh failures show retry actions, separate from missing values.
+Deleted property definitions stay in saved selections and show a warning until removed through the tile's Edit action.
+
+Widget edit events record the source and property type, never property names, values, or account identifiers.
+Widget values and property selections opt out of autocapture.
+The edit source is `account_view`.
+`customer analytics account properties widget configured` records only the selected property count.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b8b41fa2e9f5..3de63af81abb 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9130,6 +9130,14 @@ snapshots:
hash: v1.k794b7964.d44827f7d55e749657c87a7737a47e1376401fa04ddacec22d7e3f54d41a03fb.FNYwJjH3B9ZgdOgKC8xIDT7UpXFGrcwAD5-MK9gulUg
scenes-app-customer-analytics-account-detail--pinned-properties-narrow--light:
hash: v1.k794b7964.143c75f12d5a5967393fe957805eb91c86463cfa76d1e890d6a867bb7a7cd51a.2mMepzFefUEAUKA3TIIeOM8xSjb21jg_68RGPJj-2aU
+ scenes-app-customer-analytics-account-detail--properties-widgets--dark:
+ hash: v1.k794b7964.dc98afabaf3cb2645d6d41c4cfa13091a2ef74cef5e0190ac04829b6c2f9c2d5.uZro8QoDOEx2vvUmEsbHpZ5Xpaa0bitdzUA9pjxk2sA
+ scenes-app-customer-analytics-account-detail--properties-widgets--light:
+ hash: v1.k794b7964.859167eabfed15e7371a655084d328293a6cd171a32e3f221cead475bf8ccbad.sM3jcw9MhWD2NJlFaKb8PmUnTea2FfqSkT77uMWioHU
+ scenes-app-customer-analytics-account-detail--properties-widgets-narrow--dark:
+ hash: v1.k794b7964.5e124799b11e3ebd4d254b207fb5fe659ab5b635915f6d928fb88e720f0036ce.-c9qTHv4d65X04qClHXfp1NyGqX2XWundh_ynquyMd0
+ scenes-app-customer-analytics-account-detail--properties-widgets-narrow--light:
+ hash: v1.k794b7964.8ae2858c167199a91109dd3f4a03cb75bdfdc6b090e032817b303edd05f0deae.QnQHVgGx5JB22wS8fDDPLHuZ3Gzca0QSnAecq9ohMso
scenes-app-customer-analytics-account-detail-property-sidebar--custom-property-editors--dark:
hash: v1.k794b7964.caefec23d66985f72f6eb40a23370ec4bf1701b9b6cfccd2a4b2b09cc9c1606f.lJ1UWZ6LkZI-k4XJw5UtuIJx1m5tWlMyvgoPlQH2L-g
scenes-app-customer-analytics-account-detail-property-sidebar--custom-property-editors--light:
@@ -9143,9 +9151,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.b3012fb48d756b957157e313e13bde44fc1eb969b299474e1d5636e6bc7a99fa.fVSUkNrRbGB6j_ZFxchCIRcmqo4YLFzlG9AIfCrDgFo
+ hash: v1.k794b7964.980a541d7fe7ee4cc8c3b9e379a8ef99e01e884823f734a2808d0d0152a1dd9f.hO8zv0Jb4416z9TNPYX8ZxlTbmzzoUwTI4q9zqh0m7I
scenes-app-customer-analytics-account-detail-property-sidebar--filled-and-scrollable--light:
- hash: v1.k794b7964.facb96a5638e0e4ae76a5a784c423c78f58112ce0041cdd9ed2d2a356a113639.4LAw-Ryskom4ZPMds98pToXz2a0AWkzBDjRT3FhxZHk
+ hash: v1.k794b7964.4cb1c71c618a561dd35082a8c685a62ac9c40cab6a5e8d249937ea64e37d28a6.Rzc55hZFRDXwU0LRAXI4J0Etb5dI2HbSCljBV-Ra_Ho
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:
@@ -9211,17 +9219,17 @@ snapshots:
scenes-app-customer-analytics-accounts--row-expanded-no-pinned-properties--light:
hash: v1.k794b7964.d65be977673cf9d1e964e06a6ac3795c7b13a9ad3327205b691f7bf51013432a.P3OmF9kb8NA0DJkXm5dgvJBnlqt1bOA53XjNNnAL-LE
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties--dark:
- hash: v1.k794b7964.e75e428a8349099de2a6d4ba11a0e9194ebbaa66fbacdc93d7ad3f9de8738794.bc5odeBTDWUq_i3QU3c2e-pkMMtVkE0HFDRbywVF8Q4
+ hash: v1.k794b7964.35ee6184f51d95462da4a82bd21a5209f1a5e619f939e2c1211c5b08144da195.9mJ5Y2Z79PxwqzkuFJW-Rk_3hnbRqbD8hvTW2BpdUJg
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties--light:
- hash: v1.k794b7964.908141790d32f0ab4f121ef7017e3517e8b75e9a7ab42b0aed03c2ed603699e8.cKUBb78WLf4UoYzbDiSQHl86Gp2csnyj-Rojd0lQ7L0
+ hash: v1.k794b7964.4ddd7056ee8261518bbd46f5efd7edfde34ad255d7b1f7c22fbe1c762ad43fd7.gYCeYTTBkacfM6zEhIIylSHV1HvjptJOO9hEnpIC8ao
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-error--dark:
hash: v1.k794b7964.435947035814f0d3457b1a5204956987f9df29ee3e6b8a45c1ea29314b3c8d9f.gPFCq4S1UYOe0bgG_e8iVR10sNOiiLGk0CQquB6Uklw
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-error--light:
hash: v1.k794b7964.e815e72a43a321670d01c2a603288e9ff5392c8d561512965f3992b7b9c6814f.e2jyDW8y_bLMcnqQ8b9To4XTpvAATpowuxUeXSL-h9E
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-narrow--dark:
- hash: v1.k794b7964.a810538ef741184c82d24d8c00f44494a0da2d3e086a4eb3229e6549a922b7e3.8hdyPnDByKor8aXfR01h8gkn2vLfhRLG1dvksykXCCI
+ hash: v1.k794b7964.8a41ca72b367e2c34a3df0aab519a1180335ea7a5233f0408b15103977071b85.wG7SGygdx3wzv_yQJfRo023j6zw4kU-yY2q3Q1XDLZQ
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-narrow--light:
- hash: v1.k794b7964.cedd8bbe22b7d3e236b784e1d018d007a12f51f3676d6133f912f1c4e9b265c7.l-utJ4fsDPlG6aoWvqqeBtLmgQGG_7qCvyaFF1ZtFW4
+ hash: v1.k794b7964.b33f72ccbc8582dbca2786e79754319999498baa1043ae291f383ec0a1bfbe75.YcNwzXJq2msIFQg-EXWY1G0SfFAwoZp49ee2nOa2iX4
scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:
hash: v1.k794b7964.76389eaa3764f04933a9708c10c7551316e070f7a3cebf1c8e2d4e0e9fc626e4.5R7QgO5WJok3lg72hJbhNSvCqdAuh2pCo6_LsNJLZgQ
scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:
diff --git a/products/customer_analytics/backend/logic/account_views.py b/products/customer_analytics/backend/logic/account_views.py
index 8eabace3b345..ba6ce2d5fed5 100644
--- a/products/customer_analytics/backend/logic/account_views.py
+++ b/products/customer_analytics/backend/logic/account_views.py
@@ -13,6 +13,7 @@ from products.notebooks.backend.facade import content as notebook_content
from products.notebooks.backend.facade.contracts import NotebookMarkdownContentInvalid
ACCOUNT_VIEW_COMPONENT_LABELS = {
+ "Properties": "Properties",
"Notes": "Notes",
"Tasks": "Tasks",
"Users": "Users",
@@ -39,6 +40,16 @@ ACCOUNT_VIEW_IDENTITY_PROPS = {
"team_id",
}
ACCOUNT_VIEW_NODE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$")
+ACCOUNT_VIEW_NATIVE_PROPERTY_KEYS = {
+ "website_domain",
+ "billing_id",
+ "slack_channel_id",
+ "sfdc_id",
+ "stripe_customer_id",
+ "email_domains",
+ "known_emails",
+}
+ACCOUNT_VIEW_MAX_PROPERTIES = 50
class InvalidAccountViewContent(ValueError):
@@ -78,6 +89,47 @@ def get_account_view(*, team_id: int, user_id: int, view_id: UUID) -> AccountVie
return list_account_views(team_id=team_id, user_id=user_id).filter(id=view_id).first()
+def validate_properties_widget_config(config: dict[str, Any]) -> list[str]:
+ if set(config).difference({"properties"}):
+ return ["Properties config has unsupported fields."]
+ references = config.get("properties", [])
+ if not isinstance(references, list) or len(references) > ACCOUNT_VIEW_MAX_PROPERTIES:
+ return ["Properties config must contain a list of up to 50 properties."]
+ seen: set[tuple[str, str]] = set()
+ for reference in references:
+ if not isinstance(reference, dict):
+ return ["Properties config contains an invalid property reference."]
+ kind = reference.get("kind")
+ if kind == "account":
+ native_key = reference.get("key")
+ if (
+ set(reference) != {"kind", "key"}
+ or not isinstance(native_key, str)
+ or native_key not in ACCOUNT_VIEW_NATIVE_PROPERTY_KEYS
+ ):
+ return ["Properties config contains an unsupported account property."]
+ key = (kind, native_key)
+ elif kind in ("custom_property", "relationship"):
+ definition_id = reference.get("id")
+ if set(reference) != {"kind", "id"} or not isinstance(definition_id, str):
+ return ["Properties config contains an invalid definition reference."]
+ try:
+ definition_uuid = UUID(definition_id)
+ if definition_id.lower() != str(definition_uuid) or (
+ definition_uuid.version not in range(1, 9) and definition_uuid.int not in (0, (1 << 128) - 1)
+ ):
+ return ["Properties config definition IDs must use the standard UUID format."]
+ key = (kind, str(definition_uuid))
+ except ValueError:
+ return ["Properties config definition IDs must be UUIDs."]
+ else:
+ return ["Properties config contains an unsupported property source."]
+ if key in seen:
+ return ["Properties config cannot contain duplicate properties."]
+ seen.add(key)
+ return []
+
+
def validate_account_view_content(content: dict[str, Any]) -> tuple[dict[str, Any], str]:
try:
components = notebook_content.parse_markdown_component_document(content)
@@ -133,6 +185,8 @@ def validate_account_view_content(content: dict[str, Any]) -> tuple[dict[str, An
)
elif len(json.dumps(config, separators=(",", ":")).encode()) > ACCOUNT_VIEW_CONFIG_MAX_BYTES:
errors.append(f"Component {index} config is too large.")
+ elif component.tag_name == "Properties":
+ errors.extend(f"Component {index}: {error}" for error in validate_properties_widget_config(config))
if errors:
raise InvalidAccountViewContent(errors)
diff --git a/products/customer_analytics/backend/test/test_account_views.py b/products/customer_analytics/backend/test/test_account_views.py
index dd62482e08ca..8b69cfdd1529 100644
--- a/products/customer_analytics/backend/test/test_account_views.py
+++ b/products/customer_analytics/backend/test/test_account_views.py
@@ -1,8 +1,11 @@
+import json
+
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.test import SimpleTestCase
+from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
@@ -30,6 +33,47 @@ def account_view_content(*components: str) -> dict:
class TestAccountViewContentValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("unknown_native_key", {"properties": [{"kind": "account", "key": "arbitrary_key"}]}),
+ ("account_name", {"properties": [{"kind": "account", "key": "name"}]}),
+ ("invalid_id", {"properties": [{"kind": "custom_property", "id": "not-a-uuid"}]}),
+ (
+ "unhyphenated_id",
+ {"properties": [{"kind": "custom_property", "id": "11111111111141118111111111111111"}]},
+ ),
+ (
+ "unsupported_uuid_version",
+ {"properties": [{"kind": "relationship", "id": "11111111-1111-9111-8111-111111111111"}]},
+ ),
+ ("unknown_source", {"properties": [{"kind": "sidebar", "id": "11111111-1111-4111-8111-111111111111"}]}),
+ ("duplicate", {"properties": [{"kind": "account", "key": "known_emails"}] * 2}),
+ ("wrong_shape", {"properties": "website_domain"}),
+ ("extra_reference_field", {"properties": [{"kind": "account", "key": "billing_id", "value": "ignored"}]}),
+ ("extra_config_field", {"sidebar_pins": []}),
+ ]
+ )
+ def test_rejects_invalid_properties_config(self, _name: str, config: dict) -> None:
+ with self.assertRaises(InvalidAccountViewContent):
+ validate_account_view_content(
+ account_view_content(f'<Properties nodeId="properties-one" config={{{json.dumps(config)}}} />')
+ )
+
+ @parameterized.expand([(50, None), (51, "Properties config must contain a list of up to 50 properties.")])
+ def test_properties_selection_limit(self, count: int, expected_error: str | None) -> None:
+ config = {
+ "properties": [
+ {"kind": "custom_property", "id": f"00000000-0000-4000-8000-{index:012x}"} for index in range(count)
+ ]
+ }
+ content = account_view_content(f'<Properties nodeId="properties-one" config={{{json.dumps(config)}}} />')
+ if expected_error is None:
+ assert validate_account_view_content(content) == (content, "Properties")
+ else:
+ with self.assertRaises(InvalidAccountViewContent) as context:
+ validate_account_view_content(content)
+ assert context.exception.errors == [f"Component 1: {expected_error}"]
+
def test_accepts_replay_tile_with_date_config(self) -> None:
content = account_view_content(
'<SessionReplays nodeId="replay-one" title="Recent recordings" config={{"dateRange":{"date_from":"-7d","date_to":null}}} />'
@@ -104,6 +148,42 @@ class TestAccountViews(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
return response.json()
+ def test_properties_widgets_roundtrip_independent_ordered_selections_with_stale_references(self) -> None:
+ first = {
+ "properties": [
+ {"kind": "account", "key": "website_domain"},
+ {"kind": "custom_property", "id": "11111111-1111-4111-8111-111111111111"},
+ ]
+ }
+ second = {
+ "properties": [
+ {"kind": "relationship", "id": "22222222-2222-4222-8222-222222222222"},
+ {"kind": "account", "key": "known_emails"},
+ ]
+ }
+ content = account_view_content(
+ f'<Properties nodeId="properties-one" config={{{json.dumps(first)}}} />',
+ '<Notes nodeId="notes-one" />',
+ f'<Properties nodeId="properties-two" config={{{json.dumps(second)}}} />',
+ )
+ response = self.client.post(self.endpoint, {"name": "Account properties", "content": content}, format="json")
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ view = response.json()
+ self.assertEqual(view["content"], content)
+ self.assertEqual(view["text_content"], "Properties\nNotes\nProperties")
+ reloaded = self.client.get(f"{self.endpoint}{view['id']}/").json()
+ self.assertEqual(reloaded["content"], content)
+ updated_content = account_view_content(
+ f'<Properties nodeId="properties-one" config={{{json.dumps(second)}}} />',
+ f'<Properties nodeId="properties-two" config={{{json.dumps(first)}}} />',
+ )
+ updated = self.client.patch(
+ f"{self.endpoint}{view['id']}/", {"version": view["version"], "content": updated_content}, format="json"
+ )
+ self.assertEqual(updated.status_code, status.HTTP_200_OK, updated.json())
+ self.assertEqual(updated.json()["content"], updated_content)
+ self.assertEqual(self.client.get(f"{self.endpoint}{view['id']}/").json()["content"], updated_content)
+
def test_private_view_is_not_visible_to_other_users(self) -> None:
view = self._create()
@@ -302,12 +382,18 @@ class TestAccountViews(APIBaseTest):
self.assertEqual(stale.status_code, status.HTTP_409_CONFLICT)
self.assertEqual(AccountView.objects.for_team(self.team.id).get(id=view["id"]).name, "First save")
- def test_invalid_content_changes_no_state(self) -> None:
+ @parameterized.expand(
+ [
+ ('<Usage nodeId="same" accountId="customer-1" />',),
+ ('<Properties nodeId="properties" config={{"properties":[{"kind":"account","key":"name"}]}} />',),
+ ]
+ )
+ def test_invalid_content_changes_no_state(self, component: str) -> None:
response = self.client.post(
self.endpoint,
{
"name": "Invalid",
- "content": account_view_content('<Usage nodeId="same" accountId="customer-1" />'),
+ "content": account_view_content(component),
},
format="json",
)
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 24c140528e51..e972a670a114 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -50,7 +50,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`). It translates supported tile definitions into typed Postgres metrics for `accountsLogic.metricsQuery`, then reads the separate metrics data node. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |
| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |
| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). It debounces name and email searches, and owns the table's sort (`sorting`, on `level` or `last_login`) and access-level filter (`levels`); both reset to page 1 and reload. US-region orgs use the org-members endpoint, which takes `search`, `levels` and a whitelisted `ordering`. When it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only), fetched once per expansion then searched, filtered, sorted and paginated in pages of 20 client-side (mirroring the backend's ordering, "never logged in" at the far end). Once a US request has returned members the org is remembered as US-hosted and an empty filtered page is treated as "no match"; until then an empty US page falls back to the EU view, so a filter set before the first load finishes still applies. Both reads supply the member's organization access level and last-login data. EU values refresh daily. The EU view also includes the source Django user ID. Each member carries its source region so staff admin links open the correct user's detail page in the correct cloud. A missing view (local dev) degrades to the normal empty state. |
-| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint), `endRelationship` (per active row, POSTs the end endpoint), and `deleteRelationship` (admin-only, confirmation-gated hard delete). All mutations share the `relationshipSaving` guard, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |
+| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint), `endRelationship` (per active row, POSTs the end endpoint), and `deleteRelationship` (admin-only, confirmation-gated hard delete). All mutations share the `relationshipSaving` guard, refresh mounted relationship views through `relationshipsUpdated`, and force-refresh the list's data nodes. `accountPropertyDataLogic` refreshes shared property data once per change. |
| `accountFeatureRequestsLogic` | Feature requests for one account (keyed by `accountId`): loads linked requests in server pages of five with debounced search, then searches a bounded server page of accessible, editable active requests for the link picker. The picker keeps a selected search result available when the select clears its input, so requests outside the default page remain linkable. Request links carry the account's Feature requests deep link as their origin, so the detail breadcrumb returns to the same account tab. The picker exposes load failures with retry guidance and refreshes stale options after optimistic-concurrency conflicts. |
| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, preloads each insight result when the account expands, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |
| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |
@@ -59,7 +59,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
| `accountEmailThreadsLogic` | Matched email communication used by the Conversations tab (keyed by `accountId`): fetches server-paginated summaries from `accountsEmailThreadsList`, keeps one row expanded, and fetches paginated ordered messages through `accountsEmailThreadMessagesList`. The current message page is cached while the row remains expanded; list and detail failures leave explicit retry guidance instead of an infinite skeleton. |
| `accountConversationsLogic` | The unified Conversations timeline (keyed by `accountId`): loads email, Support, and Slack independently so one denied or failed source does not blank successful sources; merges them newest-first; owns search, source filters, expansion state, Support message loading, and collapsed Slack message links. It preserves email and Slack response counts and loads older source pages on demand instead of silently limiting search to the first 50 rows. |
| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `list_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). The endpoint discovers synced Gong `calls` tables and matches `calendar_event_id` to the meeting's iCal UID plus recurrence instance. Matching rows include a validated `gong_url`; the table shows an "Open in Gong" button and records `GongCallOpened`. Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the project-admin-gated "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching`; merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |
-| `accountLinksLogic` | The "Useful links" sidebar and editor for one account (keyed by `accountId`). The editor updates `website_domain` and external links through `accountsPartialUpdate` without replacing unrelated account properties. |
+| `accountLinksLogic` | The "Useful links" sidebar and editor for one account (keyed by `accountId`). The editor updates `website_domain` and external links through `accountsPartialUpdate` without replacing unrelated account properties. Pending reads retain newer saved values. Only successful writes broadcast `accountUpdated`. |
## Data & query model
@@ -166,6 +166,12 @@ Pinned property preferences belong to the current user and project, never to an
Project admins set the ordered defaults under Customer analytics > Accounts settings. A user config without `properties.pinned_properties` reads those current defaults without copying them into the user row. The first personal save stores a complete override. An explicit empty list is an override with no pins.
Omitting `pinned_properties` from a PATCH leaves existing pins unchanged. Personal API keys and OAuth tokens need `account:write` for PATCH. Session-authenticated viewers can still personalize their own sidebar.
Account views store a reusable Markdown document, not an account ID. `accountViewComponents.ts` lists the system tabs and view components. `listAvailableAccountSystemTabs` selects only entries with a `systemTabId`, so widget-only entries cannot become standalone tabs. `accountViewsLogic` owns view editing and tile settings. The account scene supplies the current account ID when it renders a view. Each tile keeps a stable `nodeId`, so two tiles of the same kind keep separate settings. `UserCustomerAnalyticsConfig.account_detail_tabs` stores each user's tab order, hidden tabs, and default for the project. A direct link can still open a hidden tab. View components render in document order and use `span` to share a row in a wide container. They stack in a narrow container.
+The view-only Properties component stores ordered custom-property, relationship, and supported account JSONB references under each tile's `config.properties`.
+`AccountViewTileEditorModal` uses the shared property selector to edit that configuration through the existing queued view save.
+`accountPropertyDataLogic` shares live values by project and account, while tile-keyed editor state remains separate from sidebar pins.
+`accountPropertyUpdatesLogic` broadcasts native account updates and refreshes mounted Relationships tiles.
+`accountNativeProperties.updateAccountNativeProperties` shares the account modal's fresh-read merge and serializes local modal and widget saves.
+See [Account sidebar properties](../../../../../docs/internal/customer-analytics/account-sidebar.md) when changing property editors, view selections, or refresh behavior.
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.
@@ -407,10 +413,14 @@ Account detail view events use singular `accountViewsLogic`, separate from Accou
| `customer analytics accounts view updated` | `accountsViewsLogic` `updateViewSuccess` listener after content or metadata changes | _(none)_ |
| `customer analytics accounts view selected` | `accountsViewsLogic` `applyView` listener on explicit selection or saved-view restoration | `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 \| `account_sidebar` or `list_expansion` from shared-field edits) |
+| `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 \| `account_sidebar`, `list_expansion`, or `account_view` from shared-field edits). `account_view` omits the role name |
| `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`, `source` (`account_sidebar` or `list_expansion` for shared-field edits; property names and values stay out) |
+| `customer analytics account custom property updated` | `accountsLogic` `updateAccountCustomProperty` listener and `accountSidebarPropertiesLogic` `persistCustomPropertySuccess` listener (after the custom-property-values write succeeds) | `display_type`, `workflow_reference`, `source` (`account_sidebar`, `list_expansion`, or `account_view` for shared-field edits; property names and values stay out) |
+| `customer analytics account property editor opened` | Widget custom/relationship and native editor listeners | `source` (`account_view`), `property_source` (`custom`, `relationship`, or `account`) |
+| `customer analytics account property save failed` | Widget custom/relationship and native save failure listeners | `source` (`account_view`), `property_source` (`custom`, `relationship`, or `account`) |
+| `customer analytics account properties widget configured` | `accountViewsLogic` after a successful properties tile settings save | `property_count` |
+| `customer analytics account edited` | Account modal submit and properties widget native save | `name_changed`, fixed native `changed_fields` for modal edits. Widget edits have only `name_changed: false` and `source: account_view` |
| `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` |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
index 1ffbbcf270e6..1897e89f5f66 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
@@ -2,6 +2,7 @@ import { userHasAccess } from 'lib/utils/accessControlUtils'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
+import { AccountPropertiesWidget } from '../../scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidget'
import { CustomerTasksTabContent } from '../CustomerTasks/CustomerTasksTabContent'
import { AccountBillingExpansion } from './AccountBillingExpansion'
import { AccountConversationsExpansion } from './AccountConversationsExpansion'
@@ -19,6 +20,7 @@ interface AccountViewComponentProps {
kind: AccountViewComponentKind
accountId: string
externalId: string
+ projectId?: number
instanceId?: string
initialConfig?: AccountViewTileConfig
onConfigChange?: (config: AccountViewTileConfig) => void
@@ -29,6 +31,7 @@ export function AccountViewComponent({
kind,
accountId,
externalId,
+ projectId,
instanceId,
initialConfig,
onConfigChange,
@@ -36,6 +39,8 @@ export function AccountViewComponent({
}: AccountViewComponentProps): JSX.Element {
const tileProps = { instanceId, initialConfig, onConfigChange }
switch (kind) {
+ case 'properties':
+ return <AccountPropertiesWidget accountId={accountId} projectId={projectId} {...tileProps} />
case 'session_replays':
return <AccountSessionReplays accountId={accountId} externalId={externalId} {...tileProps} />
case 'notes':
diff --git a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts
index 08d99a27a0d3..32145a374702 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.test.ts
@@ -1,5 +1,6 @@
import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'
+import { waitFor } from '@testing-library/react'
import { combineUrl, router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
@@ -8,6 +9,8 @@ import { initKeaTests } from '~/test/init'
import { accountsPartialUpdate, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'
import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import { accountPropertyDataLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountPropertyDataLogic'
+import { accountPropertyUpdatesLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountPropertyUpdatesLogic'
import { accountLinksLogic } from './accountLinksLogic'
jest.mock('products/customer_analytics/frontend/generated/api', () => ({
@@ -43,6 +46,7 @@ const buildAccount = (overrides: Partial<AccountApi> = {}): AccountApi => ({
describe('accountLinksLogic', () => {
let logic: ReturnType<typeof accountLinksLogic.build>
+ let shared: ReturnType<typeof accountPropertyDataLogic.build>
const mountWith = async (initial: AccountApi): Promise<void> => {
mockAccountsRetrieve.mockResolvedValue(initial)
@@ -54,10 +58,41 @@ describe('accountLinksLogic', () => {
beforeEach(() => {
initKeaTests()
jest.resetAllMocks()
+ shared = accountPropertyDataLogic({ projectId: MOCK_DEFAULT_TEAM.id, accountId: 'acc-1' })
+ shared.mount()
})
afterEach(() => {
logic?.unmount()
+ shared.unmount()
+ })
+
+ it.each(['initial', 'refresh'])('keeps a widget save when a stale %s read finishes', async (phase) => {
+ const initial = buildAccount()
+ if (phase === 'refresh') {
+ await mountWith(initial)
+ }
+ mockAccountsRetrieve.mockClear()
+ let resolveRead!: (value: AccountApi) => void
+ mockAccountsRetrieve.mockReturnValueOnce(new Promise<AccountApi>((resolve) => (resolveRead = resolve)))
+ if (phase === 'initial') {
+ logic = accountLinksLogic({ accountId: initial.id })
+ logic.mount()
+ } else {
+ logic.actions.loadAccount()
+ }
+ const saved = buildAccount({ properties: { billing_id: 'saved-billing' } })
+ try {
+ await waitFor(() => expect(mockAccountsRetrieve).toHaveBeenCalledTimes(1))
+ accountPropertyUpdatesLogic.actions.accountUpdated(MOCK_DEFAULT_TEAM.id, saved)
+ resolveRead(initial)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.currentFieldValues.billing_id).toBe('saved-billing')
+ expect(shared.values.account).toEqual(saved)
+ } finally {
+ resolveRead(initial)
+ await expectLogic(logic).toFinishAllListeners()
+ }
})
it('openEditor pre-fills the form from the current account', async () => {
@@ -118,6 +153,7 @@ describe('accountLinksLogic', () => {
},
})
expect(logic.values.account).toEqual(updated)
+ expect(shared.values.account).toEqual(updated)
expect(logic.values.editorOpen).toBe(false)
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts
index bf171bcc985e..e958cdcee2b6 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountLinksLogic.ts
@@ -14,6 +14,7 @@ import type {
PatchedAccountApiProperties,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import { accountPropertyUpdatesLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountPropertyUpdatesLogic'
import { SALESFORCE_ORIGIN } from './constants'
const ORGANIZATION_GROUP_TYPE_INDEX = 0
@@ -166,6 +167,7 @@ export const accountLinksLogic = kea<accountLinksLogicType>([
key((props) => props.accountId),
connect(() => ({
values: [teamLogic, ['currentTeamId']],
+ logic: [accountPropertyUpdatesLogic],
})),
actions({
openEditor: true,
@@ -176,16 +178,18 @@ export const accountLinksLogic = kea<accountLinksLogicType>([
saveStarted: true,
saveFinished: true,
}),
- loaders(({ props, values }) => ({
+ loaders(({ props, values, cache }) => ({
account: [
null as AccountApi | null,
{
loadAccount: async (): Promise<AccountApi | null> => {
+ const revision = cache.accountRevision ?? 0
try {
- return await accountsRetrieve(String(values.currentTeamId), props.accountId)
+ const account = await accountsRetrieve(String(values.currentTeamId), props.accountId)
+ return revision === (cache.accountRevision ?? 0) ? account : values.account
} catch (error) {
posthog.captureException(error as Error, { scope: 'accountLinksLogic.loadAccount' })
- return null
+ return revision === (cache.accountRevision ?? 0) ? null : values.account
}
},
},
@@ -323,7 +327,13 @@ export const accountLinksLogic = kea<accountLinksLogicType>([
},
],
}),
- listeners(({ actions, values, props }) => ({
+ listeners(({ actions, values, props, cache }) => ({
+ [accountPropertyUpdatesLogic.actionTypes.accountUpdated]: ({ projectId, account }) => {
+ if (projectId === values.currentTeamId && account.id === props.accountId) {
+ cache.accountRevision = (cache.accountRevision ?? 0) + 1
+ actions.loadAccountSuccess(account)
+ }
+ },
openEditor: () => {
actions.setFormValues(values.currentFieldValues)
},
@@ -349,6 +359,9 @@ export const accountLinksLogic = kea<accountLinksLogicType>([
sfdc_id: orNull(form.sfdc_id),
} as PatchedAccountApiProperties,
})
+ if (values.currentTeamId) {
+ accountPropertyUpdatesLogic.actions.accountUpdated(values.currentTeamId, updated)
+ }
actions.loadAccountSuccess(updated)
actions.closeEditor()
lemonToast.success('Links updated')
diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts
index d6b780417f0c..9b20b12110ae 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.test.ts
@@ -16,6 +16,7 @@ import {
} from 'products/customer_analytics/frontend/generated/api'
import type { AccountApi, PaginatedMeetingListApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import { accountPropertyDataLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountPropertyDataLogic'
import { accountMeetingsLogic, PAGE_SIZE } from './accountMeetingsLogic'
jest.mock('products/customer_analytics/frontend/generated/api', () => ({
@@ -37,6 +38,7 @@ function pageOf(meetings: any[], count?: number): PaginatedMeetingListApi {
describe('accountMeetingsLogic', () => {
let logic: ReturnType<typeof accountMeetingsLogic.build>
+ let shared: ReturnType<typeof accountPropertyDataLogic.build>
beforeEach(() => {
initKeaTests()
@@ -44,10 +46,13 @@ describe('accountMeetingsLogic', () => {
jest.spyOn(posthog, 'captureException').mockReturnValue(undefined as any)
jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
mockRetrieve.mockResolvedValue({ id: 'acc-1', properties: {} } as AccountApi)
+ shared = accountPropertyDataLogic({ projectId: MOCK_DEFAULT_TEAM.id, accountId: 'acc-1' })
+ shared.mount()
})
afterEach(() => {
logic?.unmount()
+ shared.unmount()
})
const mount = async (): Promise<void> => {
@@ -118,7 +123,11 @@ describe('accountMeetingsLogic', () => {
id: 'acc-1',
properties: { billing_id: 'cus_123', email_domains: ['old.com'] },
} as AccountApi)
- mockPartialUpdate.mockResolvedValue({ id: 'acc-1', properties: {} } as AccountApi)
+ const saved = {
+ id: 'acc-1',
+ properties: { billing_id: 'cus_123', email_domains: ['acme.com'], known_emails: ['[email protected]'] },
+ } as AccountApi
+ mockPartialUpdate.mockResolvedValue(saved)
await mount()
logic.actions.setDomainsDraft(['@Acme.com', 'acme.com', ' '])
@@ -133,6 +142,7 @@ describe('accountMeetingsLogic', () => {
known_emails: ['[email protected]'],
},
})
+ expect(shared.values.account).toEqual(saved)
expect(logic.values.matchingEditorOpen).toBe(false)
expect(logic.values.savingMatching).toBe(false)
})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
index c96196b8ead6..81af6df400d3 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountMeetingsLogic.ts
@@ -18,6 +18,7 @@ import type {
PatchedAccountApiProperties,
} from 'products/customer_analytics/frontend/generated/api.schemas'
+import { accountPropertyUpdatesLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountPropertyUpdatesLogic'
import { canEditEmailMatching, cleanDomains, cleanEmails } from './accountEmailMatching'
import { accountLinksLogic } from './accountLinksLogic'
import { getTileString, type AccountViewTileLogicProps } from './accountViewTileConfig'
@@ -260,6 +261,9 @@ export const accountMeetingsLogic = kea<accountMeetingsLogicType>([
known_emails: emails,
} as PatchedAccountApiProperties,
})
+ if (values.currentTeamId) {
+ accountPropertyUpdatesLogic.actions.accountUpdated(values.currentTeamId, updated)
+ }
actions.loadAccountSuccess(updated)
actions.closeMatchingEditor()
lemonToast.success('Meeting matching updated')
diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
index 9b446f1e3175..6c700435739f 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts
@@ -21,7 +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 { accountPropertyUpdatesLogic } from '../../scenes/CustomerAnalyticsAccountScene/accountPropertyUpdatesLogic'
import { accountsColumnConfigLogic, ROLE_KEY_BY_NAME } from './accountsColumnConfigLogic'
import { getTileString, type AccountViewTileLogicProps } from './accountViewTileConfig'
import { AccountsEvents } from './constants'
@@ -135,6 +135,7 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
key((props) => `${props.accountId}:${props.instanceId ?? 'default'}`),
connect(() => ({
values: [teamLogic, ['currentTeam', 'currentTeamId'], accountsColumnConfigLogic, ['relationshipDefinitions']],
+ logic: [accountPropertyUpdatesLogic],
})),
actions({
openDeleteConfirmation: (relationship: AccountRelationshipApi) => ({ relationship }),
@@ -237,92 +238,94 @@ export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([
},
],
}),
- listeners(({ actions, props, values }) => ({
- setDefinitionFilter: () => {
- props.onConfigChange?.({ definitionFilter: values.definitionFilter })
- },
- loadRelationshipsSuccess: () => {
+ listeners(({ actions, props, values }) => {
+ const refreshRelationships = (): void => {
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' })
- },
- assignRelationship: async ({ definition, user }) => {
- if (values.relationshipSaving) {
- return
- }
- actions.relationshipSaveStarted()
- try {
- // Assigning a single-holder relationship ends the current holder server-side.
- await accountsRelationshipsCreate(String(values.currentTeamId), props.accountId, {
- definition: definition.id,
- user: user.id,
- })
- posthog.capture(AccountsEvents.RoleAssigned, {
- role: ROLE_KEY_BY_NAME[definition.name] ?? definition.name,
- is_assigned: true,
- assigned_user_id: user.id,
- source: 'relationships_tab',
- })
- actions.setAssignDefinitionId(null)
- actions.loadRelationships()
- refreshAccountsList()
- } catch (error) {
- posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.assignRelationship' })
- lemonToast.error(`Failed to assign ${definition.name}`)
- } finally {
- actions.relationshipSaveFinished()
- }
- },
- endRelationship: async ({ relationship }) => {
- if (values.relationshipSaving) {
- return
- }
- actions.relationshipSaveStarted()
- try {
- await accountsRelationshipsEndCreate(String(values.currentTeamId), props.accountId, relationship.id)
- posthog.capture(AccountsEvents.RoleAssigned, {
- role: ROLE_KEY_BY_NAME[relationship.definition.name] ?? relationship.definition.name,
- is_assigned: false,
- assigned_user_id: null,
- source: 'relationships_tab',
- })
- actions.loadRelationships()
- refreshAccountsList()
- } catch (error) {
- posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.endRelationship' })
- lemonToast.error(`Failed to end ${relationship.definition.name}`)
- } finally {
- actions.relationshipSaveFinished()
- }
- },
- deleteRelationship: async ({ relationship }) => {
- if (values.relationshipSaving) {
- return
- }
- actions.relationshipSaveStarted()
- try {
- await accountsRelationshipsDestroy(String(values.currentTeamId), props.accountId, relationship.id)
- posthog.capture(AccountsEvents.RelationshipDeleted)
- actions.closeDeleteConfirmation()
+ accountPropertyUpdatesLogic.actions.relationshipsUpdated(values.currentTeamId, props.accountId)
+ } else {
actions.loadRelationships()
- refreshAccountsList()
- } catch (error) {
- posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.deleteRelationship' })
- lemonToast.error(`Failed to delete ${relationship.definition.name} assignment`)
- } finally {
- actions.relationshipSaveFinished()
}
- },
- })),
+ refreshAccountsList()
+ }
+ return {
+ [accountPropertyUpdatesLogic.actionTypes.relationshipsUpdated]: ({ projectId, accountId }) => {
+ if (projectId === values.currentTeamId && accountId === props.accountId) {
+ actions.loadRelationships()
+ }
+ },
+ setDefinitionFilter: () => {
+ props.onConfigChange?.({ definitionFilter: values.definitionFilter })
+ },
+ loadRelationshipsFailure: ({ error }) => {
+ // No toast: `relationships === null` renders the table's failure empty state.
+ posthog.captureException(error, { scope: 'accountRelationshipsLogic.loadRelationships' })
+ },
+ assignRelationship: async ({ definition, user }) => {
+ if (values.relationshipSaving) {
+ return
+ }
+ actions.relationshipSaveStarted()
+ try {
+ // Assigning a single-holder relationship ends the current holder server-side.
+ await accountsRelationshipsCreate(String(values.currentTeamId), props.accountId, {
+ definition: definition.id,
+ user: user.id,
+ })
+ posthog.capture(AccountsEvents.RoleAssigned, {
+ role: ROLE_KEY_BY_NAME[definition.name] ?? definition.name,
+ is_assigned: true,
+ assigned_user_id: user.id,
+ source: 'relationships_tab',
+ })
+ actions.setAssignDefinitionId(null)
+ refreshRelationships()
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.assignRelationship' })
+ lemonToast.error(`Failed to assign ${definition.name}`)
+ } finally {
+ actions.relationshipSaveFinished()
+ }
+ },
+ endRelationship: async ({ relationship }) => {
+ if (values.relationshipSaving) {
+ return
+ }
+ actions.relationshipSaveStarted()
+ try {
+ await accountsRelationshipsEndCreate(String(values.currentTeamId), props.accountId, relationship.id)
+ posthog.capture(AccountsEvents.RoleAssigned, {
+ role: ROLE_KEY_BY_NAME[relationship.definition.name] ?? relationship.definition.name,
+ is_assigned: false,
+ assigned_user_id: null,
+ source: 'relationships_tab',
+ })
+ refreshRelationships()
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.endRelationship' })
+ lemonToast.error(`Failed to end ${relationship.definition.name}`)
+ } finally {
+ actions.relationshipSaveFinished()
+ }
+ },
+ deleteRelationship: async ({ relationship }) => {
+ if (values.relationshipSaving) {
+ return
+ }
+ actions.relationshipSaveStarted()
+ try {
+ await accountsRelationshipsDestroy(String(values.currentTeamId), props.accountId, relationship.id)
+ posthog.capture(AccountsEvents.RelationshipDeleted)
+ actions.closeDeleteConfirmation()
+ refreshRelationships()
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'accountRelationshipsLogic.deleteRelationship' })
+ lemonToast.error(`Failed to delete ${relationship.definition.name} assignment`)
+ } finally {
+ actions.relationshipSaveFinished()
+ }
+ },
+ }
+ }),
afterMount(({ actions }) => {
actions.loadRelationships()
}),
diff --git a/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts b/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts
index c8a111738710..8a777e795931 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts
@@ -3,7 +3,7 @@ import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import type { AccountExpansionTab } from './accountsExpansionLogic'
-export type AccountViewComponentKind = AccountExpansionTab | 'session_replays'
+export type AccountViewComponentKind = AccountExpansionTab | 'properties' | 'session_replays'
interface AccountViewComponentBase {
tagName: string
@@ -19,11 +19,12 @@ export interface AccountSystemTabDefinition extends AccountViewComponentBase {
export type AccountViewComponentDefinition =
| AccountSystemTabDefinition
| (AccountViewComponentBase & {
- kind: 'session_replays'
+ kind: 'properties' | 'session_replays'
systemTabId?: never
})
export const ACCOUNT_VIEW_COMPONENTS: AccountViewComponentDefinition[] = [
+ { kind: 'properties', tagName: 'Properties', label: 'Properties' },
{ kind: 'session_replays', tagName: 'SessionReplays', label: 'Session replays' },
{ kind: 'notes', tagName: 'Notes', label: 'Notes', systemTabId: 'system:notes' },
{
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index 1c2634721d77..aa4ce81041c3 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -45,6 +45,9 @@ export const AccountsEvents = {
RelationshipDeleted: 'customer analytics accounts relationship deleted',
TagsUpdated: 'customer analytics account tags updated',
CustomPropertyUpdated: 'customer analytics account custom property updated',
+ AccountPropertyEditorOpened: 'customer analytics account property editor opened',
+ PropertiesWidgetConfigured: 'customer analytics account properties widget configured',
+ AccountPropertySaveFailed: 'customer analytics account property save failed',
PinnedPropertiesSaved: 'customer analytics account pinned properties saved',
LinkClicked: 'customer analytics account link clicked',
NoteClicked: 'customer analytics account note clicked',
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx
index 616b6eae0c43..fcd9b362682f 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx
@@ -8,7 +8,8 @@ import { teamLogic } from 'scenes/teamLogic'
import { canEditEmailMatching } from 'products/customer_analytics/frontend/components/Accounts/accountEmailMatching'
-import { ACCOUNT_ID_FIELDS, customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+import { ACCOUNT_ID_FIELDS } from './accountNativeProperties'
+import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
export function AccountEditModal(): JSX.Element {
const { account, accountEditorOpen, accountFormHasErrors, isAccountFormSubmitting } = useValues(
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidget.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidget.test.tsx
new file mode 100644
index 000000000000..b2ca325c2969
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidget.test.tsx
@@ -0,0 +1,296 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import '@testing-library/jest-dom'
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { AccountApi, CustomPropertyDefinitionApi } from '../../generated/api.schemas'
+import { AccountPropertiesWidget } from './AccountPropertiesWidget'
+import type { AccountWidgetPropertyReference } from './accountPropertiesWidgetConfig'
+import { accountPropertyDataLogic } from './accountPropertyDataLogic'
+import { accountSidebarConfigLogic } from './accountSidebarConfigLogic'
+
+jest.mock('lib/utils/accessControlUtils', () => ({
+ ...jest.requireActual('lib/utils/accessControlUtils'),
+ userHasAccess: () => true,
+}))
+
+const PROJECT_ID = MOCK_DEFAULT_TEAM.id
+const ACCOUNT_ID = '11111111-1111-4111-8111-111111111111'
+const ACCOUNT_URL = '/api/projects/:project_id/accounts/:account_id/'
+const DEFINITIONS_URL = '/api/projects/:project_id/custom_property_definitions/'
+const EMPTY_PAGE = { count: 0, results: [] }
+const nativeReferences: AccountWidgetPropertyReference[] = [{ kind: 'account', key: 'billing_id' }]
+const mixedReferences: AccountWidgetPropertyReference[] = [
+ ...nativeReferences,
+ { kind: 'custom_property', id: '22222222-2222-4222-8222-222222222222' },
+]
+const account: AccountApi = {
+ id: ACCOUNT_ID,
+ name: 'Example account',
+ notebooks: [],
+ ignored_at: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ properties: { billing_id: 'billing-example' },
+}
+
+function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
+}
+
+function createWidget(references = nativeReferences): JSX.Element {
+ return (
+ <AccountPropertiesWidget
+ projectId={PROJECT_ID}
+ accountId={ACCOUNT_ID}
+ instanceId="first"
+ initialConfig={{ properties: references }}
+ />
+ )
+}
+
+function renderWidget(references = nativeReferences): ReturnType<typeof render> {
+ return render(createWidget(references))
+}
+
+async function waitForNativeAccount(): Promise<void> {
+ await waitFor(() =>
+ expect(accountPropertyDataLogic({ projectId: PROJECT_ID, accountId: ACCOUNT_ID }).values.account).toEqual(
+ account
+ )
+ )
+}
+
+async function finishRequests<T>(pending: { resolve: (value: T) => void }, value: T): Promise<void> {
+ await act(async () => {
+ pending.resolve(value)
+ await expectLogic(accountSidebarConfigLogic({ projectId: PROJECT_ID })).toFinishAllListeners()
+ })
+}
+
+describe('AccountPropertiesWidget source resolution', () => {
+ beforeEach(() => {
+ initKeaTests()
+ silenceKeaLoadersErrors()
+ useMocks({
+ get: {
+ [ACCOUNT_URL]: account,
+ [DEFINITIONS_URL]: EMPTY_PAGE,
+ '/api/projects/:project_id/account_relationship_definitions/': EMPTY_PAGE,
+ '/api/projects/:project_id/user_customer_analytics_config/@me/': { pinned_properties: [] },
+ },
+ })
+ })
+
+ afterEach(() => {
+ cleanup()
+ resumeKeaLoadersErrors()
+ })
+
+ it.each([
+ {
+ selection: 'native-only',
+ references: nativeReferences,
+ source: 'definitions',
+ state: 'pending',
+ expected: 'ready',
+ },
+ {
+ selection: 'native-only',
+ references: nativeReferences,
+ source: 'definitions',
+ state: 'failed',
+ expected: 'ready',
+ },
+ {
+ selection: 'mixed',
+ references: mixedReferences,
+ source: 'definitions',
+ state: 'pending',
+ expected: 'loading',
+ },
+ { selection: 'mixed', references: mixedReferences, source: 'definitions', state: 'failed', expected: 'failed' },
+ {
+ selection: 'native-only',
+ references: nativeReferences,
+ source: 'account',
+ state: 'pending',
+ expected: 'loading',
+ },
+ {
+ selection: 'native-only',
+ references: nativeReferences,
+ source: 'account',
+ state: 'failed',
+ expected: 'failed',
+ },
+ ] as const)(
+ 'shows $expected for a $selection widget when $source is $state',
+ async ({ references, source, state, expected }) => {
+ const pending = createDeferred<AccountApi | typeof EMPTY_PAGE>()
+ useMocks({
+ get: {
+ [source === 'account' ? ACCOUNT_URL : DEFINITIONS_URL]: () =>
+ state === 'pending' ? pending.promise : [500, { detail: 'Source unavailable' }],
+ },
+ })
+ const { container } = renderWidget(references)
+ try {
+ const definitions = accountSidebarConfigLogic({ projectId: PROJECT_ID })
+ const data = accountPropertyDataLogic({ projectId: PROJECT_ID, accountId: ACCOUNT_ID })
+ await waitFor(() => {
+ const loading =
+ source === 'account'
+ ? data.values.accountLoading
+ : definitions.values.availableDefinitionsLoading
+ const failed =
+ source === 'account'
+ ? data.values.accountLoadFailed
+ : definitions.values.availableDefinitionsLoadFailed
+ expect(state === 'pending' ? loading : failed).toBe(true)
+ })
+ if (source === 'account') {
+ await waitFor(() => expect(definitions.values.availableDefinitions).not.toBeNull())
+ } else {
+ await waitForNativeAccount()
+ }
+ if (expected === 'ready') {
+ expect(await screen.findByText('billing-example')).toBeVisible()
+ } else if (expected === 'failed') {
+ expect(await screen.findByText('Could not load properties.')).toBeVisible()
+ }
+ expect(!!container.querySelector('[data-attr="account-properties-widget-loading"]')).toBe(
+ expected === 'loading'
+ )
+ expect(!!screen.queryByText('Could not load properties.')).toBe(expected === 'failed')
+ expect(!!screen.queryByText('billing-example')).toBe(expected === 'ready')
+ expect(
+ screen.queryByText('Could not refresh properties. These values may be out of date.')
+ ).not.toBeInTheDocument()
+ } finally {
+ await finishRequests(pending, source === 'account' ? account : EMPTY_PAGE)
+ }
+ }
+ )
+
+ it('retries a native account failure without waiting for or refetching pending definitions', async () => {
+ const pendingDefinitions = createDeferred<typeof EMPTY_PAGE>()
+ const retriedAccount = createDeferred<AccountApi>()
+ let failAccount = true
+ const accountGet = jest.fn(() =>
+ failAccount ? [500, { detail: 'Account unavailable' }] : retriedAccount.promise
+ )
+ const definitionsGet = jest.fn(() => pendingDefinitions.promise)
+ useMocks({ get: { [ACCOUNT_URL]: accountGet, [DEFINITIONS_URL]: definitionsGet } })
+ renderWidget()
+ try {
+ expect(await screen.findByText('Could not load properties.')).toBeVisible()
+ await waitFor(() => expect(definitionsGet).toHaveBeenCalledTimes(1))
+ const retryButton = screen.getAllByText('Try again')[0].closest('button')!
+ expect(retryButton).not.toHaveAttribute('aria-disabled', 'true')
+ failAccount = false
+ act(() => {
+ fireEvent.click(retryButton)
+ fireEvent.click(retryButton)
+ })
+ await waitFor(() => expect(accountGet).toHaveBeenCalledTimes(2))
+ await act(async () => {
+ retriedAccount.resolve(account)
+ })
+ expect(await screen.findByText('billing-example')).toBeVisible()
+ expect(accountGet).toHaveBeenCalledTimes(2)
+ expect(definitionsGet).toHaveBeenCalledTimes(1)
+ const definitions = accountSidebarConfigLogic({ projectId: PROJECT_ID })
+ expect(definitions.values.availableDefinitions).toBeNull()
+ expect(definitions.values.availableDefinitionsLoading).toBe(true)
+ } finally {
+ await act(async () => {
+ retriedAccount.resolve(account)
+ pendingDefinitions.resolve(EMPTY_PAGE)
+ await expectLogic(accountSidebarConfigLogic({ projectId: PROJECT_ID })).toFinishAllListeners()
+ })
+ }
+ })
+
+ it('applies configuration changes without losing custom or native drafts or changing pins', async () => {
+ const definition: CustomPropertyDefinitionApi = {
+ id: '22222222-2222-4222-8222-222222222222',
+ name: 'Plan',
+ display_type: 'text',
+ target_type: 'account',
+ is_canonical: false,
+ has_workflow_reference: false,
+ source: null,
+ references: [],
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: 1,
+ updated_at: null,
+ }
+ useMocks({
+ get: {
+ [DEFINITIONS_URL]: { count: 1, results: [definition] },
+ '/api/projects/:project_id/accounts/:account_id/custom_property_values/': [
+ {
+ id: 'value-1',
+ account_id: ACCOUNT_ID,
+ definition_id: definition.id,
+ value: 'Starter',
+ created_at: '2026-01-01T00:00:00Z',
+ created_by_id: 1,
+ },
+ ],
+ '/api/projects/:project_id/accounts/:account_id/relationships/': [],
+ },
+ })
+ const { rerender } = renderWidget([])
+ const definitions = accountSidebarConfigLogic({ projectId: PROJECT_ID })
+ await act(async () => {
+ await expectLogic(definitions).toFinishAllListeners()
+ })
+ expect(
+ screen.getByText("No properties selected. Use the tile's Edit action to choose properties.")
+ ).toBeVisible()
+ rerender(createWidget([{ kind: 'custom_property', id: definition.id }]))
+ expect(await screen.findByText('Starter')).toBeVisible()
+ fireEvent.click(screen.getByLabelText('Edit Plan'))
+ fireEvent.change(screen.getByDisplayValue('Starter'), { target: { value: 'Unsaved plan' } })
+ rerender(createWidget(mixedReferences))
+ expect(await screen.findByText('billing-example')).toBeVisible()
+ expect(screen.getByDisplayValue('Unsaved plan')).toBeVisible()
+ fireEvent.click(screen.getByText('Cancel'))
+ fireEvent.click(screen.getByLabelText('Edit Billing ID'))
+ fireEvent.change(screen.getByDisplayValue('billing-example'), { target: { value: 'unsaved-billing' } })
+ rerender(createWidget(nativeReferences))
+ expect(screen.getByDisplayValue('unsaved-billing')).toBeVisible()
+ expect(screen.queryByText('Starter')).not.toBeInTheDocument()
+ expect(definitions.values.config?.pinned_properties).toEqual([])
+ })
+
+ it('does not show a definitions refresh warning for a native-only widget', async () => {
+ renderWidget()
+ const definitions = accountSidebarConfigLogic({ projectId: PROJECT_ID })
+ await act(async () => {
+ await expectLogic(definitions).toFinishAllListeners()
+ })
+ expect(await screen.findByText('billing-example')).toBeVisible()
+ useMocks({ get: { [DEFINITIONS_URL]: () => [500, { detail: 'Definitions unavailable' }] } })
+ await act(async () => {
+ await expectLogic(definitions, () => definitions.actions.loadAvailableDefinitions()).toFinishAllListeners()
+ })
+ expect(screen.getByText('billing-example')).toBeVisible()
+ expect(
+ screen.queryByText('Could not refresh properties. These values may be out of date.')
+ ).not.toBeInTheDocument()
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidget.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidget.tsx
new file mode 100644
index 000000000000..c318ffc0c622
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidget.tsx
@@ -0,0 +1,229 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import type { AccountViewTileLogicProps } from '../../components/Accounts/accountViewTileConfig'
+import type { PinnedAccountPropertyApi } from '../../generated/api.schemas'
+import { getAccountWidgetPropertyKey } from './accountPropertiesWidgetConfig'
+import { accountPropertiesWidgetLogic } from './accountPropertiesWidgetLogic'
+import { useAccountPropertiesViewport } from './accountPropertiesWidgetViewport'
+import { accountSidebarConfigLogic } from './accountSidebarConfigLogic'
+import { accountSidebarPropertiesLogic } from './accountSidebarPropertiesLogic'
+import { AccountNativePropertyField } from './components/AccountNativePropertyField'
+import { AccountPropertyField } from './components/AccountPropertyField'
+
+interface AccountPropertiesWidgetProps extends AccountViewTileLogicProps {
+ accountId: string
+ projectId?: number
+}
+
+export function AccountPropertiesWidget({
+ accountId,
+ projectId: suppliedProjectId,
+ instanceId,
+ initialConfig,
+ onConfigChange,
+}: AccountPropertiesWidgetProps): JSX.Element {
+ const { currentProjectId } = useValues(projectLogic)
+ const { contentRef, maxHeight } = useAccountPropertiesViewport()
+ const projectId = suppliedProjectId ?? currentProjectId ?? 0
+ const nativeLogic = accountPropertiesWidgetLogic({
+ projectId,
+ accountId,
+ instanceId,
+ initialConfig,
+ onConfigChange,
+ })
+ const {
+ references,
+ account,
+ accountLoading,
+ accountLoadFailed,
+ nativeEditingKey,
+ nativeDraft,
+ nativeSaveFailed,
+ savedAccountLoading,
+ canEditNativeProperties,
+ canEditMatching,
+ } = useValues(nativeLogic)
+ const { editNativeProperty, cancelNativeEditing, setNativeDraft, saveNativeProperty, loadAccount } =
+ useActions(nativeLogic)
+ const propertyReferences = references.filter(
+ (reference): reference is PinnedAccountPropertyApi => reference.kind !== 'account'
+ )
+ const propertyLogic = accountSidebarPropertiesLogic({
+ projectId,
+ accountId,
+ instanceId: `view:${instanceId ?? 'default'}`,
+ propertyReferences,
+ })
+ const {
+ sidebarProperties,
+ propertiesPanelState,
+ propertiesRefreshFailed,
+ propertyDataLoading,
+ propertySaveFailed,
+ editingPropertyKey,
+ savingPropertyKey,
+ availableMembers,
+ membersLoading,
+ } = useValues(propertyLogic)
+ const { loadPropertyData, editProperty, cancelEditing, saveCustomProperty, saveRelationship } =
+ useActions(propertyLogic)
+ const definitionsLogic = accountSidebarConfigLogic({ projectId })
+ const { availableDefinitionsLoading } = useValues(definitionsLogic)
+ const { loadAvailableDefinitions } = useActions(definitionsLogic)
+ const hasNativeProperties = references.some((reference) => reference.kind === 'account')
+ const hasPropertyReferences = propertyReferences.length > 0
+ const retryLoading =
+ (hasNativeProperties && accountLoading) ||
+ (hasPropertyReferences && (propertyDataLoading || availableDefinitionsLoading))
+ const saving = !!savingPropertyKey || savedAccountLoading
+ const retry = (): void => {
+ if (
+ (hasNativeProperties && nativeLogic.values.accountLoading) ||
+ (hasPropertyReferences &&
+ (propertyLogic.values.propertyDataLoading || definitionsLogic.values.availableDefinitionsLoading))
+ ) {
+ return
+ }
+ if (hasNativeProperties) {
+ loadAccount()
+ }
+ if (hasPropertyReferences) {
+ loadPropertyData()
+ loadAvailableDefinitions()
+ }
+ }
+ const failed =
+ (hasPropertyReferences && propertiesPanelState === 'failed') ||
+ (hasNativeProperties && !account && accountLoadFailed)
+ const loading =
+ !failed && ((hasPropertyReferences && propertiesPanelState === 'loading') || (hasNativeProperties && !account))
+ if (references.length === 0) {
+ return (
+ <p className="text-secondary text-sm pb-2">
+ No properties selected. Use the tile's Edit action to choose properties.
+ </p>
+ )
+ }
+ if (failed) {
+ return (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: retry, loading: retryLoading }}>
+ Could not load properties.
+ </LemonBanner>
+ )
+ }
+ if (loading) {
+ return (
+ <div className="flex flex-col gap-2 pb-2" data-attr="account-properties-widget-loading">
+ <LemonSkeleton className="h-8" />
+ <LemonSkeleton className="h-8" />
+ </div>
+ )
+ }
+ return (
+ <div className="flex flex-col gap-3 min-w-0 pb-3 ph-no-capture" data-attr="account-properties-widget">
+ {propertySaveFailed || nativeSaveFailed ? (
+ <LemonBanner type="error">
+ Could not save this property. Your input is kept. Review the value and try Save again.
+ </LemonBanner>
+ ) : null}
+ {(hasPropertyReferences && propertiesRefreshFailed) || (hasNativeProperties && accountLoadFailed) ? (
+ <LemonBanner type="warning" action={{ children: 'Try again', onClick: retry, loading: retryLoading }}>
+ Could not refresh properties. These values may be out of date.
+ </LemonBanner>
+ ) : null}
+ <div
+ className="min-w-0 -mr-4 pr-4 overflow-y-auto [scrollbar-gutter:stable]"
+ style={maxHeight === null ? undefined : { maxHeight }}
+ {...(maxHeight === null ? {} : { role: 'region', 'aria-label': 'Properties', tabIndex: 0 })}
+ data-attr="account-properties-widget-list"
+ >
+ <div ref={contentRef} className="relative flex flex-col gap-3 min-w-0">
+ {references.map((reference) => {
+ const key = getAccountWidgetPropertyKey(reference)
+ if (reference.kind === 'account') {
+ if (reference.key === 'stripe_customer_id' && !account?.properties?.stripe_customer_id) {
+ return null
+ }
+ const list = reference.key === 'email_domains' || reference.key === 'known_emails'
+ const disabledReason = !canEditNativeProperties
+ ? 'You need editor access to edit account properties.'
+ : list && !canEditMatching
+ ? 'Only project admins can edit email domains and known emails.'
+ : undefined
+ return (
+ <AccountNativePropertyField
+ key={key}
+ propertyKey={reference.key}
+ value={account?.properties?.[reference.key] ?? (list ? [] : '')}
+ draft={nativeDraft}
+ editing={nativeEditingKey === reference.key}
+ saving={savedAccountLoading}
+ disabledReason={disabledReason}
+ onEdit={() => {
+ if (!saving && !disabledReason) {
+ cancelEditing()
+ editNativeProperty(reference.key)
+ }
+ }}
+ onChange={setNativeDraft}
+ onSave={saveNativeProperty}
+ onCancel={() => {
+ if (!saving) {
+ cancelNativeEditing()
+ }
+ }}
+ />
+ )
+ }
+ const property = sidebarProperties.find((property) => property.key === key)
+ return property ? (
+ <AccountPropertyField
+ key={key}
+ property={property}
+ editing={editingPropertyKey === key}
+ saving={savingPropertyKey === key}
+ availableMembers={availableMembers}
+ membersLoading={membersLoading}
+ onEdit={() => {
+ if (!saving) {
+ cancelNativeEditing()
+ editProperty(property)
+ }
+ }}
+ onCancel={() => {
+ if (
+ !propertyLogic.values.savingPropertyKey &&
+ !nativeLogic.values.savedAccountLoading
+ ) {
+ cancelEditing()
+ }
+ }}
+ onSaveCustomProperty={(property, value) =>
+ saveCustomProperty(property.key, value, 'account_view')
+ }
+ onSaveRelationship={(property, memberIds) =>
+ saveRelationship(property.key, memberIds, 'account_view')
+ }
+ />
+ ) : (
+ <LemonBanner key={key} type="warning">
+ This property definition was deleted. Use the tile's Edit action to remove it.
+ </LemonBanner>
+ )
+ })}
+ </div>
+ </div>
+ {references.every((reference) => reference.kind === 'account' && reference.key === 'stripe_customer_id') &&
+ !account?.properties?.stripe_customer_id ? (
+ <p className="text-secondary text-sm mb-0">
+ Stripe ID is not linked for this account. Use the tile's Edit action to choose another property.
+ </p>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidgetConfiguration.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidgetConfiguration.tsx
new file mode 100644
index 000000000000..ac73bef11937
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPropertiesWidgetConfiguration.tsx
@@ -0,0 +1,99 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'
+
+import type { AccountViewTileConfig } from '../../components/Accounts/accountViewTileConfig'
+import { ACCOUNT_ID_FIELDS, ACCOUNT_LIST_FIELDS } from './accountNativeProperties'
+import {
+ accountWidgetKeysToReferences,
+ getAccountWidgetProperties,
+ getAccountWidgetPropertyKey,
+} from './accountPropertiesWidgetConfig'
+import { accountPropertyDataLogic } from './accountPropertyDataLogic'
+import { accountSidebarConfigLogic } from './accountSidebarConfigLogic'
+import { AccountPropertySelection } from './components/AccountPropertySelection'
+import { MAX_PINNED_ACCOUNT_PROPERTIES, type AccountPropertyOption } from './components/accountPropertyTypes'
+
+interface AccountPropertiesWidgetConfigurationProps {
+ projectId: number
+ accountId: string
+ config: AccountViewTileConfig
+ saving: boolean
+ onChange: (config: AccountViewTileConfig) => void
+}
+
+export function AccountPropertiesWidgetConfiguration({
+ projectId,
+ accountId,
+ config,
+ saving,
+ onChange,
+}: AccountPropertiesWidgetConfigurationProps): JSX.Element {
+ const definitionsLogic = accountSidebarConfigLogic({ projectId })
+ const { availableDefinitions, availableDefinitionsLoading, availableDefinitionsLoadFailed } =
+ useValues(definitionsLogic)
+ const { loadAvailableDefinitions } = useActions(definitionsLogic)
+ const { account } = useValues(accountPropertyDataLogic({ projectId, accountId }))
+ const references = getAccountWidgetProperties(config)
+ const options: AccountPropertyOption[] = [
+ ...(availableDefinitions?.customProperties ?? []).map((definition) => ({
+ key: `custom:${definition.id}`,
+ label: definition.name,
+ kind: 'custom' as const,
+ })),
+ ...(availableDefinitions?.relationships ?? []).map((definition) => ({
+ key: `relationship:${definition.id}`,
+ label: definition.name,
+ kind: 'relationship' as const,
+ })),
+ ...[...ACCOUNT_ID_FIELDS, ...ACCOUNT_LIST_FIELDS]
+ .filter((field) => field.key !== 'stripe_customer_id' || account?.properties?.stripe_customer_id)
+ .map((field) => ({ key: `account:${field.key}`, label: field.label, kind: 'account' as const })),
+ ]
+ for (const reference of references) {
+ const key = getAccountWidgetPropertyKey(reference)
+ if (!options.some((option) => option.key === key)) {
+ options.push({
+ key,
+ label:
+ reference.kind === 'account'
+ ? 'Stripe ID (not linked for this account)'
+ : 'Deleted property definition',
+ kind:
+ reference.kind === 'custom_property'
+ ? 'custom'
+ : reference.kind === 'account'
+ ? 'account'
+ : 'relationship',
+ })
+ }
+ }
+ return (
+ <div className="flex flex-col gap-2 ph-no-capture">
+ <span className="font-semibold">Properties</span>
+ {availableDefinitionsLoadFailed ? (
+ <LemonBanner
+ type="error"
+ action={{
+ children: 'Try again',
+ onClick: loadAvailableDefinitions,
+ loading: availableDefinitionsLoading,
+ }}
+ >
+ Could not load property definitions.
+ </LemonBanner>
+ ) : !availableDefinitions ? (
+ <LemonSkeleton className="h-8" />
+ ) : (
+ <AccountPropertySelection
+ options={options}
+ selectedKeys={references.map(getAccountWidgetPropertyKey)}
+ saving={saving}
+ emptyLabel="No properties selected."
+ limitDisabledReason={`You can select up to ${MAX_PINNED_ACCOUNT_PROPERTIES} properties`}
+ onChange={(keys) => onChange({ ...config, properties: accountWidgetKeysToReferences(keys) })}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx
index ba284e8f4719..cac12308c688 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTile.tsx
@@ -1,3 +1,4 @@
+import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { IconEllipsis, IconPencil, IconTrash } from '@posthog/icons'
@@ -32,6 +33,8 @@ export function AccountViewTile({
const { tileSaving, tileConfigReloads } = useValues(logic)
const { openTileEditor, removeViewComponent, updateViewComponentConfig } = useActions(logic)
const title = component.title ?? getAccountViewComponentByKind(component.kind)?.label ?? component.kind
+ // Match the sidebar's property inset.
+ const insetClassName = component.kind === 'properties' ? 'px-4' : 'px-2'
const menuDisabledReason = !view.can_edit ? 'You cannot edit this view' : tileSaving ? 'Saving changes' : undefined
const confirmRemove = (): void => {
@@ -53,7 +56,15 @@ export function AccountViewTile({
{
label: 'Edit',
icon: <IconPencil />,
- onClick: () => openTileEditor(view.id, component.nodeId, title),
+ onClick: () =>
+ openTileEditor(
+ view.id,
+ component.nodeId,
+ title,
+ component.kind === 'properties'
+ ? { propertiesConfig: component.config ?? {}, accountId }
+ : undefined
+ ),
disabledReason: menuDisabledReason,
},
{
@@ -70,7 +81,7 @@ export function AccountViewTile({
return (
<LemonCard hoverEffect={false} className={`col-span-12 min-w-0 overflow-hidden p-0 ${spanClassName}`}>
- <div className="flex items-center gap-2 border-b px-2 py-1">
+ <div className={clsx('flex items-center gap-2 border-b py-1', insetClassName)}>
<span className="min-w-0 flex-1 truncate text-xs font-medium text-secondary">{title}</span>
<LemonMenu items={items}>
<LemonButton
@@ -84,10 +95,16 @@ export function AccountViewTile({
/>
</LemonMenu>
</div>
- <div className="min-w-0 px-2 pt-2 pb-0 [&_.LemonTable]:-mx-2 [&_.LemonTable]:!w-[calc(100%+1rem)]">
+ <div
+ className={clsx(
+ 'min-w-0 pt-2 pb-0 [&_.LemonTable]:-mx-2 [&_.LemonTable]:!w-[calc(100%+1rem)]',
+ insetClassName
+ )}
+ >
<AccountViewComponent
kind={component.kind}
accountId={accountId}
+ projectId={projectId}
externalId={externalId}
instanceId={`${component.nodeId}:${tileConfigReloads[view.id] ?? 0}`}
initialConfig={component.config}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTileEditorModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTileEditorModal.tsx
index 846e71b468b4..a11a58a32bfe 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTileEditorModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountViewTileEditorModal.tsx
@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'
import { LemonButton, LemonInput, LemonLabel, LemonModal } from '@posthog/lemon-ui'
+import { AccountPropertiesWidgetConfiguration } from './AccountPropertiesWidgetConfiguration'
import { accountViewsLogic } from './accountViewsLogic'
interface AccountViewTileEditorModalProps {
@@ -11,7 +12,7 @@ interface AccountViewTileEditorModalProps {
export function AccountViewTileEditorModal({ projectId }: AccountViewTileEditorModalProps): JSX.Element {
const logic = accountViewsLogic({ projectId })
const { tileEditor, tileSaving } = useValues(logic)
- const { closeTileEditor, saveTileEditor, setTileEditorName } = useActions(logic)
+ const { closeTileEditor, saveTileEditor, setTileEditorName, setTileEditorPropertiesConfig } = useActions(logic)
const saveDisabledReason = tileSaving
? 'Saving changes'
: !tileEditor?.name.trim()
@@ -53,6 +54,7 @@ export function AccountViewTileEditorModal({ projectId }: AccountViewTileEditorM
<LemonInput
id="account-view-tile-name"
value={tileEditor?.name ?? ''}
+ disabled={tileSaving}
onChange={setTileEditorName}
onPressEnter={tileSaving ? undefined : saveTileEditor}
autoFocus
@@ -60,6 +62,17 @@ export function AccountViewTileEditorModal({ projectId }: AccountViewTileEditorM
data-attr="account-view-tile-name"
/>
</div>
+ {tileEditor?.propertiesConfig && tileEditor.accountId ? (
+ <div className="mt-4">
+ <AccountPropertiesWidgetConfiguration
+ projectId={projectId}
+ accountId={tileEditor.accountId}
+ config={tileEditor.propertiesConfig}
+ saving={tileSaving}
+ onChange={setTileEditorPropertiesConfig}
+ />
+ </div>
+ ) : null}
</LemonModal>
)
}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
index 488efd798d11..ae818c4eb93a 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
@@ -422,3 +422,94 @@ export const PinnedPropertiesNarrow: Story = {
testOptions: { waitForSelector: '[data-attr="account-property-row"]', viewport: { width: 800, height: 900 } },
},
}
+
+const widgetCustomId = '33333333-3333-4333-8333-333333333333'
+const widgetRelationshipId = '44444444-4444-4444-8444-444444444444'
+const widgetCanonicalId = '55555555-5555-4555-8555-555555555555'
+const widgetDefinitions = [
+ { ...pinnedDefinitions[0].definition, id: widgetCustomId },
+ { ...pinnedDefinitions[9].definition, id: widgetCanonicalId },
+]
+const widgetRelationship = { ...pinnedRelationships[0], id: widgetRelationshipId }
+const propertiesView = {
+ ...accountView,
+ content: createAccountViewContent([
+ {
+ nodeId: 'properties-first',
+ kind: 'properties',
+ span: 6,
+ title: 'Account information',
+ config: {
+ properties: [
+ { kind: 'account', key: 'website_domain' },
+ { kind: 'custom_property', id: widgetCustomId },
+ { kind: 'relationship', id: widgetRelationshipId },
+ { kind: 'account', key: 'billing_id' },
+ ],
+ },
+ },
+ {
+ nodeId: 'properties-second',
+ kind: 'properties',
+ span: 6,
+ title: 'Contact properties',
+ config: {
+ properties: [
+ { kind: 'account', key: 'known_emails' },
+ { kind: 'relationship', id: widgetRelationshipId },
+ { kind: 'custom_property', id: widgetCanonicalId },
+ { kind: 'custom_property', id: '66666666-6666-4666-8666-666666666666' },
+ ],
+ },
+ },
+ ]),
+}
+const propertiesWidgetDecorator = mswDecorator({
+ get: {
+ [ACCOUNT_VIEWS_ENDPOINT]: [propertiesView],
+ [CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT]: { count: widgetDefinitions.length, results: widgetDefinitions },
+ [RELATIONSHIP_DEFINITIONS_ENDPOINT]: { count: 1, results: [widgetRelationship] },
+ [VALUES_ENDPOINT]: widgetDefinitions.map((definition, index) => ({
+ ...pinnedDefinitions[index === 0 ? 0 : 9].value,
+ definition_id: definition.id,
+ })),
+ [ASSIGNMENTS_ENDPOINT]: [
+ {
+ id: 'widget-assignment',
+ definition: widgetRelationship,
+ user: pinnedMembers[0],
+ started_at: '2026-05-10T10:00:00Z',
+ ended_at: null,
+ },
+ ],
+ [ACCOUNT_RETRIEVE_ENDPOINT]: {
+ ...account,
+ properties: {
+ ...account.properties,
+ website_domain: 'a-long-company-website-domain.example.com',
+ known_emails: ['[email protected]', '[email protected]'],
+ },
+ },
+ },
+})
+
+export const PropertiesWidgets: Story = {
+ render: () => <App />,
+ decorators: [propertiesWidgetDecorator],
+ parameters: {
+ testOptions: {
+ waitForSelector: '[data-attr="account-properties-widget"]',
+ viewport: { width: 1800, height: 900 },
+ },
+ },
+}
+
+export const PropertiesWidgetsNarrow: Story = {
+ ...PropertiesWidgets,
+ parameters: {
+ testOptions: {
+ waitForSelector: '[data-attr="account-properties-widget"]',
+ viewport: { width: 1000, height: 900 },
+ },
+ },
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountNativeProperties.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountNativeProperties.ts
new file mode 100644
index 000000000000..920190dcccf8
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountNativeProperties.ts
@@ -0,0 +1,72 @@
+import { cleanDomains, cleanEmails } from '../../components/Accounts/accountEmailMatching'
+import { accountsPartialUpdate, accountsRetrieve } from '../../generated/api'
+import type { AccountApi, PatchedAccountApiProperties } from '../../generated/api.schemas'
+
+export const ACCOUNT_ID_FIELDS = [
+ { key: 'website_domain', label: 'Website domain', placeholder: 'example.com' },
+ { key: 'billing_id', label: 'Billing ID', placeholder: 'e.g. cus_acme_123' },
+ { key: 'slack_channel_id', label: 'Slack channel ID', placeholder: 'e.g. C0123456789' },
+ { key: 'sfdc_id', label: 'Salesforce ID', placeholder: 'e.g. 0011t00000AbCdEfGhI' },
+ { key: 'stripe_customer_id', label: 'Stripe ID', placeholder: 'e.g. cus_acme_123' },
+] as const
+
+export const ACCOUNT_LIST_FIELDS = [
+ { key: 'email_domains', label: 'Email domains', placeholder: 'example.com' },
+ { key: 'known_emails', label: 'Known emails', placeholder: '[email protected]' },
+] as const
+
+export type AccountNativePropertyKey =
+ | (typeof ACCOUNT_ID_FIELDS)[number]['key']
+ | (typeof ACCOUNT_LIST_FIELDS)[number]['key']
+export type AccountNativePropertyValue = string | string[]
+export type AccountNativePropertyPatch = Partial<
+ Pick<NonNullable<PatchedAccountApiProperties>, AccountNativePropertyKey>
+>
+
+export function isAccountNativePropertyKey(key: unknown): key is AccountNativePropertyKey {
+ return [...ACCOUNT_ID_FIELDS, ...ACCOUNT_LIST_FIELDS].some((field) => field.key === key)
+}
+
+const accountWrites = new Map<string, Promise<unknown>>()
+
+export async function updateAccountNativeProperties(
+ projectId: number,
+ accountId: string,
+ properties: AccountNativePropertyPatch,
+ name?: string
+): Promise<AccountApi> {
+ const key = `${projectId}:${accountId}`
+ const previous = accountWrites.get(key) ?? Promise.resolve()
+ const write = previous
+ .catch(() => undefined)
+ .then(async (): Promise<AccountApi> => {
+ const current = await accountsRetrieve(String(projectId), accountId)
+ const changes: AccountNativePropertyPatch = { ...properties }
+ for (const { key } of ACCOUNT_ID_FIELDS) {
+ if (key === 'stripe_customer_id' && !current.properties?.stripe_customer_id) {
+ delete changes[key]
+ } else if (typeof changes[key] === 'string') {
+ changes[key] = changes[key]?.trim() || null
+ }
+ }
+ if (changes.email_domains) {
+ changes.email_domains = cleanDomains(changes.email_domains)
+ }
+ if (changes.known_emails) {
+ changes.known_emails = cleanEmails(changes.known_emails)
+ }
+ // Serialize local editors and merge against a fresh read so another field's edit is not replaced.
+ return accountsPartialUpdate(String(projectId), accountId, {
+ ...(name === undefined ? {} : { name }),
+ properties: { ...current.properties, ...changes },
+ })
+ })
+ accountWrites.set(key, write)
+ try {
+ return await write
+ } finally {
+ if (accountWrites.get(key) === write) {
+ accountWrites.delete(key)
+ }
+ }
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetConfig.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetConfig.test.ts
new file mode 100644
index 000000000000..4018295a116f
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetConfig.test.ts
@@ -0,0 +1,75 @@
+import {
+ accountWidgetKeysToReferences,
+ getAccountWidgetProperties,
+ getAccountWidgetPropertyKey,
+} from './accountPropertiesWidgetConfig'
+import { createAccountViewContent, parseAccountViewContent } from './accountViewDocument'
+
+const CUSTOM_ID = '11111111-1111-4111-8111-111111111111'
+const RELATIONSHIP_ID = '22222222-2222-4222-8222-222222222222'
+
+const first = [
+ { kind: 'account', key: 'website_domain' },
+ { kind: 'custom_property', id: CUSTOM_ID },
+]
+const second = [
+ { kind: 'relationship', id: RELATIONSHIP_ID },
+ { kind: 'account', key: 'known_emails' },
+ { kind: 'custom_property', id: CUSTOM_ID },
+]
+
+describe('account properties widget config', () => {
+ it('round-trips independent mixed selections in order, including stale definition IDs', () => {
+ const components = parseAccountViewContent(
+ createAccountViewContent([
+ { nodeId: 'first', kind: 'properties', span: 6, config: { properties: first } },
+ { nodeId: 'notes', kind: 'notes', span: 12, config: { searchTerm: 'Note search' } },
+ { nodeId: 'second', kind: 'properties', span: 6, config: { properties: second } },
+ ])
+ )
+ expect(components.map(({ nodeId }) => nodeId)).toEqual(['first', 'notes', 'second'])
+ expect(getAccountWidgetProperties(components[0].config)).toEqual(first)
+ expect(getAccountWidgetProperties(components[2].config)).toEqual(second)
+ expect(components[1].config).toEqual({ searchTerm: 'Note search' })
+ expect(
+ accountWidgetKeysToReferences(
+ getAccountWidgetProperties(components[2].config).map(getAccountWidgetPropertyKey)
+ )
+ ).toEqual(second)
+ })
+
+ it.each([undefined, { properties: null }, { properties: 'website_domain' }])(
+ 'reads missing or malformed config as an empty selection (%s)',
+ (config) => {
+ expect(getAccountWidgetProperties(config)).toEqual([])
+ }
+ )
+
+ it('resolves UUID case consistently and treats equivalent spellings as one reference', () => {
+ const id = 'abcdefab-cdef-4abc-8def-abcdefabcdef'
+ expect(
+ getAccountWidgetProperties({
+ properties: [
+ { kind: 'custom_property', id: id.toUpperCase() },
+ { kind: 'custom_property', id },
+ ],
+ })
+ ).toEqual([{ kind: 'custom_property', id }])
+ })
+
+ it('omits unknown sources, arbitrary account keys and malformed IDs without replacing valid references', () => {
+ expect(
+ getAccountWidgetProperties({
+ properties: [
+ { kind: 'account', key: 'name' },
+ { kind: 'account', key: 'arbitrary_key' },
+ { kind: 'custom_property', id: 'invalid' },
+ { kind: 'unknown', id: CUSTOM_ID },
+ null,
+ ...first,
+ ...first,
+ ],
+ })
+ ).toEqual(first)
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetConfig.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetConfig.ts
new file mode 100644
index 000000000000..6158d0b895bb
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetConfig.ts
@@ -0,0 +1,58 @@
+import { validate as isUuid } from 'uuid'
+
+import type { AccountViewTileConfig } from '../../components/Accounts/accountViewTileConfig'
+import type { PinnedAccountPropertyApi } from '../../generated/api.schemas'
+import { AccountNativePropertyKey, isAccountNativePropertyKey } from './accountNativeProperties'
+import { MAX_PINNED_ACCOUNT_PROPERTIES } from './components/accountPropertyTypes'
+
+export type AccountWidgetPropertyReference =
+ | PinnedAccountPropertyApi
+ | { kind: 'account'; key: AccountNativePropertyKey }
+
+export function getAccountWidgetPropertyKey(reference: AccountWidgetPropertyReference): string {
+ return reference.kind === 'account'
+ ? `account:${reference.key}`
+ : `${reference.kind === 'custom_property' ? 'custom' : 'relationship'}:${reference.id}`
+}
+
+export function getAccountWidgetProperties(
+ config: AccountViewTileConfig | undefined
+): AccountWidgetPropertyReference[] {
+ if (!Array.isArray(config?.properties)) {
+ return []
+ }
+ const references: AccountWidgetPropertyReference[] = []
+ const seen = new Set<string>()
+ for (const item of config.properties) {
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
+ continue
+ }
+ let reference: AccountWidgetPropertyReference
+ if (item.kind === 'account' && isAccountNativePropertyKey(item.key)) {
+ reference = { kind: 'account', key: item.key }
+ } else if (
+ (item.kind === 'custom_property' || item.kind === 'relationship') &&
+ typeof item.id === 'string' &&
+ isUuid(item.id)
+ ) {
+ reference = { kind: item.kind, id: item.id.toLowerCase() }
+ } else {
+ continue
+ }
+ const key = getAccountWidgetPropertyKey(reference)
+ if (!seen.has(key) && references.length < MAX_PINNED_ACCOUNT_PROPERTIES) {
+ references.push(reference)
+ seen.add(key)
+ }
+ }
+ return references
+}
+
+export function accountWidgetKeysToReferences(keys: string[]): AccountWidgetPropertyReference[] {
+ return getAccountWidgetProperties({
+ properties: keys.map((key) => {
+ const [kind, id] = key.split(':')
+ return kind === 'account' ? { kind, key: id } : { kind: kind === 'custom' ? 'custom_property' : kind, id }
+ }),
+ })
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetLogic.test.ts
new file mode 100644
index 000000000000..3dc9d7d629ae
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetLogic.test.ts
@@ -0,0 +1,188 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { waitFor } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+
+import { OrganizationMembershipLevel } from 'lib/constants'
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { initKeaTests } from '~/test/init'
+
+import { accountsPartialUpdate, accountsRetrieve } from '../../generated/api'
+import type { AccountApi } from '../../generated/api.schemas'
+import { accountPropertiesWidgetLogic } from './accountPropertiesWidgetLogic'
+
+jest.mock('lib/utils/accessControlUtils', () => ({ userHasAccess: jest.fn(() => true) }))
+jest.mock('../../generated/api', () => ({
+ ...jest.requireActual('../../generated/api'),
+ accountsRetrieve: jest.fn(),
+ accountsPartialUpdate: jest.fn(),
+}))
+
+const PROJECT_ID = MOCK_DEFAULT_TEAM.id
+const ACCOUNT_ID = '11111111-1111-4111-8111-111111111111'
+const initialAccount: AccountApi = {
+ id: ACCOUNT_ID,
+ name: 'Example account',
+ external_id: 'example-account',
+ notebooks: [],
+ ignored_at: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ properties: {
+ billing_id: 'billing-example',
+ website_domain: 'example.com',
+ slack_channel_id: 'CEXAMPLE',
+ usage_dashboard_link: 'https://example.com/usage',
+ },
+}
+const mockRetrieve = jest.mocked(accountsRetrieve)
+const mockUpdate = jest.mocked(accountsPartialUpdate)
+
+describe('accountPropertiesWidgetLogic', () => {
+ let account: AccountApi
+ const mounted: ReturnType<typeof accountPropertiesWidgetLogic.build>[] = []
+ const mount = async (instanceId: string): Promise<ReturnType<typeof accountPropertiesWidgetLogic.build>> => {
+ const logic = accountPropertiesWidgetLogic({
+ projectId: PROJECT_ID,
+ accountId: ACCOUNT_ID,
+ instanceId,
+ initialConfig: {
+ properties: [
+ { kind: 'account', key: 'website_domain' },
+ { kind: 'account', key: 'billing_id' },
+ { kind: 'account', key: 'email_domains' },
+ { kind: 'account', key: 'known_emails' },
+ { kind: 'account', key: 'stripe_customer_id' },
+ ],
+ },
+ })
+ logic.mount()
+ mounted.push(logic)
+ await waitFor(() => expect(logic.values.account).not.toBeNull())
+ return logic
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.clearAllMocks()
+ jest.mocked(userHasAccess).mockReturnValue(true)
+ account = structuredClone(initialAccount)
+ mockRetrieve.mockImplementation(async () => structuredClone(account))
+ mockUpdate.mockImplementation(async (_, __, patch) => {
+ account = { ...account, properties: patch?.properties ?? account.properties }
+ return account
+ })
+ })
+ afterEach(() => {
+ mounted.splice(0).forEach((logic) => logic.unmount())
+ resumeKeaLoadersErrors()
+ })
+
+ it('retains failed input, blocks duplicate saves and refreshes other instances without replacing their drafts', async () => {
+ silenceKeaLoadersErrors()
+ const first = await mount('first')
+ const second = await mount('second')
+ first.actions.editNativeProperty('website_domain')
+ first.actions.setNativeDraft('new.example.com')
+ second.actions.editNativeProperty('billing_id')
+ second.actions.setNativeDraft('unsaved-billing')
+ account = { ...account, properties: { ...account.properties, slack_channel_id: 'CCONCURRENT' } }
+ mockUpdate.mockRejectedValueOnce(new Error('Save failed'))
+ await expectLogic(first, () => {
+ first.actions.saveNativeProperty()
+ first.actions.saveNativeProperty()
+ }).toFinishAllListeners()
+ expect(mockUpdate).toHaveBeenCalledTimes(1)
+ expect(first.values).toMatchObject({
+ nativeSaveFailed: true,
+ nativeEditingKey: 'website_domain',
+ nativeDraft: 'new.example.com',
+ })
+ expect(second.values).toMatchObject({ nativeEditingKey: 'billing_id', nativeDraft: 'unsaved-billing' })
+ await expectLogic(first, () => first.actions.saveNativeProperty()).toFinishAllListeners()
+ expect(mockUpdate).toHaveBeenLastCalledWith(String(PROJECT_ID), ACCOUNT_ID, {
+ properties: {
+ ...initialAccount.properties,
+ website_domain: 'new.example.com',
+ slack_channel_id: 'CCONCURRENT',
+ },
+ })
+ expect(first.values.nativeEditingKey).toBeNull()
+ expect(second.values.account?.properties?.website_domain).toBe('new.example.com')
+ expect(second.values.nativeDraft).toBe('unsaved-billing')
+ })
+
+ it('serializes two widget saves so each fresh merge keeps the other changed field', async () => {
+ const first = await mount('first')
+ const second = await mount('second')
+ let releaseWrite!: () => void
+ const pendingWrite = new Promise<void>((resolve) => {
+ releaseWrite = resolve
+ })
+ mockUpdate.mockImplementationOnce(async (_, __, patch) => {
+ await pendingWrite
+ account = { ...account, properties: patch?.properties ?? account.properties }
+ return account
+ })
+ first.actions.editNativeProperty('website_domain')
+ first.actions.setNativeDraft('saved.example.com')
+ second.actions.editNativeProperty('billing_id')
+ second.actions.setNativeDraft('saved-billing')
+ first.actions.saveNativeProperty()
+ second.actions.saveNativeProperty()
+ try {
+ await waitFor(() => expect(mockUpdate).toHaveBeenCalledTimes(1))
+ } finally {
+ releaseWrite()
+ }
+ await expectLogic(first).toFinishAllListeners()
+ expect(mockUpdate).toHaveBeenCalledTimes(2)
+ expect(account.properties).toMatchObject({
+ website_domain: 'saved.example.com',
+ billing_id: 'saved-billing',
+ slack_channel_id: 'CEXAMPLE',
+ })
+ expect(first.values.account).toEqual(account)
+ expect(second.values.account).toEqual(account)
+ })
+
+ it.each([
+ ['email_domains', [' @EXAMPLE.COM ', 'example.com', 'other.example.com'], ['example.com', 'other.example.com']],
+ ['known_emails', [' [email protected] ', '[email protected]'], ['[email protected]']],
+ ] as const)('uses the account modal normalization for %s', async (propertyKey, input, expected) => {
+ const logic = await mount('first')
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ effective_membership_level: OrganizationMembershipLevel.Admin,
+ })
+ logic.actions.editNativeProperty(propertyKey)
+ logic.actions.setNativeDraft([...input])
+ await expectLogic(logic, () => logic.actions.saveNativeProperty()).toFinishAllListeners()
+ expect(account.properties?.[propertyKey]).toEqual(expected)
+ expect(account.properties?.usage_dashboard_link).toBe(initialAccount.properties?.usage_dashboard_link)
+ })
+
+ it.each([
+ { propertyKey: 'website_domain' as const, editor: false, level: OrganizationMembershipLevel.Admin },
+ { propertyKey: 'email_domains' as const, editor: true, level: OrganizationMembershipLevel.Member },
+ { propertyKey: 'known_emails' as const, editor: true, level: OrganizationMembershipLevel.Member },
+ { propertyKey: 'stripe_customer_id' as const, editor: true, level: OrganizationMembershipLevel.Admin },
+ ])(
+ 'blocks a restricted native write for $propertyKey (editor: $editor, level: $level)',
+ async ({ propertyKey, editor, level }) => {
+ jest.mocked(userHasAccess).mockReturnValue(editor)
+ const logic = await mount('first')
+ teamLogic.actions.loadCurrentTeamSuccess({ ...MOCK_DEFAULT_TEAM, effective_membership_level: level })
+ logic.actions.editNativeProperty(propertyKey)
+ logic.actions.setNativeDraft(
+ propertyKey === 'email_domains' || propertyKey === 'known_emails' ? ['example.com'] : 'blocked'
+ )
+ await expectLogic(logic, () => logic.actions.saveNativeProperty()).toFinishAllListeners()
+ expect(mockUpdate).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetLogic.ts
new file mode 100644
index 000000000000..304379102145
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetLogic.ts
@@ -0,0 +1,266 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ propsChanged,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { AccessControlLevel, AccessControlResourceType, type TeamPublicType, type TeamType } from '~/types'
+
+import { canEditEmailMatching } from '../../components/Accounts/accountEmailMatching'
+import type { AccountViewTileLogicProps } from '../../components/Accounts/accountViewTileConfig'
+import { AccountsEvents } from '../../components/Accounts/constants'
+import { ACCOUNTS_METRICS_DATA_NODE_KEY, ACCOUNTS_TABLE_DATA_NODE_KEY } from '../../constants'
+import type { AccountApi } from '../../generated/api.schemas'
+import {
+ AccountNativePropertyKey,
+ AccountNativePropertyPatch,
+ AccountNativePropertyValue,
+ updateAccountNativeProperties,
+} from './accountNativeProperties'
+import {
+ getAccountWidgetProperties,
+ getAccountWidgetPropertyKey,
+ AccountWidgetPropertyReference,
+} from './accountPropertiesWidgetConfig'
+import { accountPropertyDataLogic } from './accountPropertyDataLogic'
+import { accountPropertyUpdatesLogic } from './accountPropertyUpdatesLogic'
+
+export interface AccountPropertiesWidgetLogicProps extends AccountViewTileLogicProps {
+ projectId: number
+ accountId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountPropertiesWidgetLogicValues {
+ account: AccountApi | null // accountPropertyDataLogic
+ accountLoadFailed: boolean // accountPropertyDataLogic
+ accountLoading: boolean // accountPropertyDataLogic
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
+ canEditMatching: boolean
+ canEditNativeProperties: boolean
+ nativeDraft: AccountNativePropertyValue
+ nativeEditingKey: AccountNativePropertyKey | null
+ nativeSaveFailed: boolean
+ references: AccountWidgetPropertyReference[]
+ savedAccount: AccountApi | null
+ savedAccountLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountPropertiesWidgetLogicActions {
+ loadAccount: (_?: void | undefined) => void // accountPropertyDataLogic
+ cancelNativeEditing: () => {
+ value: true
+ }
+ editNativeProperty: (propertyKey: AccountNativePropertyKey) => {
+ propertyKey: AccountNativePropertyKey
+ }
+ persistNativeProperty: ({
+ propertyKey,
+ draft,
+ }: {
+ draft: AccountNativePropertyValue
+ propertyKey: AccountNativePropertyKey
+ }) => {
+ propertyKey: AccountNativePropertyKey
+ draft: AccountNativePropertyValue
+ }
+ persistNativePropertyFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ persistNativePropertySuccess: (
+ savedAccount: AccountApi,
+ payload?: {
+ propertyKey: AccountNativePropertyKey
+ draft: AccountNativePropertyValue
+ }
+ ) => {
+ savedAccount: AccountApi
+ payload?: {
+ propertyKey: AccountNativePropertyKey
+ draft: AccountNativePropertyValue
+ }
+ }
+ saveNativeProperty: () => {
+ value: true
+ }
+ setNativeDraft: (draft: AccountNativePropertyValue) => {
+ draft: AccountNativePropertyValue
+ }
+ setReferences: (references: AccountWidgetPropertyReference[]) => {
+ references: AccountWidgetPropertyReference[]
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountPropertiesWidgetLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ canEditMatching: (currentTeam: TeamPublicType | TeamType | null) => boolean
+ }
+}
+
+export type accountPropertiesWidgetLogicType = MakeLogicType<
+ accountPropertiesWidgetLogicValues,
+ accountPropertiesWidgetLogicActions,
+ AccountPropertiesWidgetLogicProps,
+ accountPropertiesWidgetLogicMeta
+>
+
+export const accountPropertiesWidgetLogic: LogicWrapper<accountPropertiesWidgetLogicType> =
+ kea<accountPropertiesWidgetLogicType>([
+ props({} as AccountPropertiesWidgetLogicProps),
+ key(({ projectId, accountId, instanceId }) => `${projectId}:${accountId}:${instanceId ?? 'default'}`),
+ path((key) => ['products', 'customer_analytics', 'accountPropertiesWidgetLogic', key]),
+ connect(({ projectId, accountId }: AccountPropertiesWidgetLogicProps) => ({
+ values: [
+ accountPropertyDataLogic({ projectId, accountId }),
+ ['account', 'accountLoading', 'accountLoadFailed'],
+ teamLogic,
+ ['currentTeam'],
+ ],
+ actions: [accountPropertyDataLogic({ projectId, accountId }), ['loadAccount']],
+ logic: [accountPropertyUpdatesLogic],
+ })),
+ actions({
+ editNativeProperty: (propertyKey: AccountNativePropertyKey) => ({ propertyKey }),
+ cancelNativeEditing: true,
+ setNativeDraft: (draft: AccountNativePropertyValue) => ({ draft }),
+ saveNativeProperty: true,
+ setReferences: (references: AccountWidgetPropertyReference[]) => ({ references }),
+ }),
+ loaders(({ props }) => ({
+ savedAccount: [
+ null as AccountApi | null,
+ {
+ persistNativeProperty: async ({
+ propertyKey,
+ draft,
+ }: {
+ propertyKey: AccountNativePropertyKey
+ draft: AccountNativePropertyValue
+ }): Promise<AccountApi> =>
+ updateAccountNativeProperties(props.projectId, props.accountId, {
+ [propertyKey]: draft,
+ } as AccountNativePropertyPatch),
+ },
+ ],
+ })),
+ reducers(({ props }) => ({
+ // Props mutate in place. Redux-backed references keep selectors current when tile configuration changes.
+ references: [
+ getAccountWidgetProperties(props.initialConfig),
+ { setReferences: (_, { references }) => references },
+ ],
+ nativeEditingKey: [
+ null as AccountNativePropertyKey | null,
+ {
+ editNativeProperty: (_, { propertyKey }) => propertyKey,
+ cancelNativeEditing: () => null,
+ persistNativePropertySuccess: () => null,
+ },
+ ],
+ nativeDraft: ['' as AccountNativePropertyValue, { setNativeDraft: (_, { draft }) => draft }],
+ nativeSaveFailed: [
+ false,
+ {
+ editNativeProperty: () => false,
+ cancelNativeEditing: () => false,
+ persistNativeProperty: () => false,
+ persistNativePropertySuccess: () => false,
+ persistNativePropertyFailure: () => true,
+ },
+ ],
+ })),
+ selectors({
+ canEditNativeProperties: [
+ () => [],
+ (): boolean => userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Editor),
+ ],
+ canEditMatching: [
+ (s) => [s.currentTeam],
+ (team: TeamPublicType | TeamType | null): boolean => canEditEmailMatching(team),
+ ],
+ }),
+ listeners(({ actions, values, props }) => ({
+ editNativeProperty: ({ propertyKey }) => {
+ posthog.capture(AccountsEvents.AccountPropertyEditorOpened, {
+ source: 'account_view',
+ property_source: 'account',
+ })
+ actions.setNativeDraft(
+ values.account?.properties?.[propertyKey] ??
+ (propertyKey === 'email_domains' || propertyKey === 'known_emails' ? [] : '')
+ )
+ },
+ saveNativeProperty: () => {
+ const propertyKey = values.nativeEditingKey
+ if (
+ !propertyKey ||
+ values.savedAccountLoading ||
+ !values.canEditNativeProperties ||
+ !values.account ||
+ !values.references.some(
+ (reference) => reference.kind === 'account' && reference.key === propertyKey
+ ) ||
+ ((propertyKey === 'email_domains' || propertyKey === 'known_emails') && !values.canEditMatching) ||
+ (propertyKey === 'stripe_customer_id' && !values.account.properties?.stripe_customer_id)
+ ) {
+ return
+ }
+ actions.persistNativeProperty({ propertyKey, draft: values.nativeDraft })
+ },
+ persistNativePropertySuccess: ({ savedAccount }) => {
+ accountPropertyUpdatesLogic.actions.accountUpdated(props.projectId, savedAccount)
+ dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
+ dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
+ posthog.capture(AccountsEvents.AccountEdited, { source: 'account_view', name_changed: false })
+ },
+ persistNativePropertyFailure: () => {
+ posthog.capture(AccountsEvents.AccountPropertySaveFailed, {
+ source: 'account_view',
+ property_source: 'account',
+ })
+ },
+ })),
+ afterMount(({ actions, values }) => {
+ if (!values.account && !values.accountLoading) {
+ actions.loadAccount()
+ }
+ }),
+ propsChanged(({ actions, props, values }, previousProps) => {
+ if (props.initialConfig !== previousProps.initialConfig) {
+ const references = getAccountWidgetProperties(props.initialConfig)
+ if (
+ references.length !== values.references.length ||
+ references.some(
+ (reference, index) =>
+ getAccountWidgetPropertyKey(reference) !==
+ getAccountWidgetPropertyKey(values.references[index])
+ )
+ ) {
+ actions.setReferences(references)
+ }
+ }
+ }),
+ ])
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetViewport.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetViewport.test.ts
new file mode 100644
index 000000000000..5c79fce1e936
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetViewport.test.ts
@@ -0,0 +1,42 @@
+import { getVisibleRowsHeight } from './accountPropertiesWidgetViewport'
+
+function buildContent(heights: number[], alertAfterRow?: number): HTMLElement {
+ const content = document.createElement('div')
+ jest.spyOn(content, 'getBoundingClientRect').mockReturnValue({ top: 100 } as DOMRect)
+ let top = 0
+ const add = (dataAttr: string | null, height: number): void => {
+ const child = document.createElement('div')
+ if (dataAttr) {
+ child.setAttribute('data-attr', dataAttr)
+ }
+ // jsdom has no layout, so rows report the geometry a browser would.
+ jest.spyOn(child, 'getBoundingClientRect').mockReturnValue({ bottom: 100 + top + height } as DOMRect)
+ top += height + 12
+ content.appendChild(child)
+ }
+ heights.forEach((height, index) => {
+ add(index % 2 ? 'account-native-property-row' : 'account-property-row', height)
+ if (index === alertAfterRow) {
+ add(null, 40)
+ }
+ })
+ return content
+}
+
+describe('getVisibleRowsHeight', () => {
+ it('does not limit ten rows', () => {
+ expect(getVisibleRowsHeight(buildContent(Array(10).fill(30)))).toBeNull()
+ })
+
+ it.each([
+ [30, 80, 30, 30, 120, 30, 30, 30, 30, 50, 30],
+ [30.2, 80.3, 30.1, 30, 120.4, 30.2, 30, 30.3, 30, 50.2, 30],
+ ])('fully includes the tenth row when the first row height is %s', (...heights) => {
+ const tenthBottom = heights.slice(0, 10).reduce((sum, height) => sum + height + 12, 0) - 12
+ expect(getVisibleRowsHeight(buildContent(heights))).toBe(Math.ceil(tenthBottom))
+ })
+
+ it('does not count alerts as properties', () => {
+ expect(getVisibleRowsHeight(buildContent(Array(10).fill(30), 2))).toBeNull()
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetViewport.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetViewport.ts
new file mode 100644
index 000000000000..08c32751549a
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertiesWidgetViewport.ts
@@ -0,0 +1,52 @@
+import { RefCallback, useCallback, useLayoutEffect, useState } from 'react'
+
+export const ACCOUNT_PROPERTIES_VISIBLE_ROW_LIMIT = 10
+
+// Alert banners must not count toward the property limit.
+const PROPERTY_ROW_SELECTOR = '[data-attr="account-property-row"], [data-attr="account-native-property-row"]'
+
+export function getVisibleRowsHeight(
+ content: HTMLElement,
+ rowLimit = ACCOUNT_PROPERTIES_VISIBLE_ROW_LIMIT
+): number | null {
+ const rows = Array.from(content.children).filter((child): child is HTMLElement =>
+ child.matches(PROPERTY_ROW_SELECTOR)
+ )
+ if (rows.length <= rowLimit) {
+ return null
+ }
+ const lastVisibleRow = rows[rowLimit - 1]
+ return Math.ceil(lastVisibleRow.getBoundingClientRect().bottom - content.getBoundingClientRect().top)
+}
+
+// Observe unclamped content to avoid resize feedback when the viewport height changes.
+export function useAccountPropertiesViewport(): {
+ contentRef: RefCallback<HTMLDivElement>
+ maxHeight: number | null
+} {
+ const [content, setContent] = useState<HTMLDivElement | null>(null)
+ const [maxHeight, setMaxHeight] = useState<number | null>(null)
+ const contentRef = useCallback((element: HTMLDivElement | null) => setContent(element), [])
+
+ // Row count can change without resizing the list.
+ useLayoutEffect(() => {
+ if (content) {
+ const next = getVisibleRowsHeight(content)
+ setMaxHeight((previous) => (previous === next ? previous : next))
+ }
+ })
+
+ useLayoutEffect(() => {
+ if (!content || typeof ResizeObserver === 'undefined') {
+ return
+ }
+ const observer = new ResizeObserver(() => {
+ const next = getVisibleRowsHeight(content)
+ setMaxHeight((previous) => (previous === next ? previous : next))
+ })
+ observer.observe(content)
+ return () => observer.disconnect()
+ }, [content])
+
+ return { contentRef, maxHeight }
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyDataLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyDataLogic.test.ts
new file mode 100644
index 000000000000..07d677af06b7
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyDataLogic.test.ts
@@ -0,0 +1,73 @@
+import { waitFor } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { accountsRetrieve } from '../../generated/api'
+import type { AccountApi } from '../../generated/api.schemas'
+import { accountPropertyDataLogic } from './accountPropertyDataLogic'
+import { accountPropertyUpdatesLogic } from './accountPropertyUpdatesLogic'
+
+jest.mock('../../generated/api', () => ({ accountsRetrieve: jest.fn() }))
+
+const PROJECT_ID = 1
+const ACCOUNT_ID = '11111111-1111-4111-8111-111111111111'
+const account: AccountApi = {
+ id: ACCOUNT_ID,
+ name: 'Example account',
+ notebooks: [],
+ ignored_at: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ properties: { website_domain: 'example.com' },
+}
+const mockRetrieve = jest.mocked(accountsRetrieve)
+
+describe('accountPropertyDataLogic', () => {
+ let logic: ReturnType<typeof accountPropertyDataLogic.build>
+
+ beforeEach(() => {
+ initKeaTests(false)
+ mockRetrieve.mockReset().mockResolvedValue(account)
+ logic = accountPropertyDataLogic({ projectId: PROJECT_ID, accountId: ACCOUNT_ID })
+ logic.mount()
+ })
+
+ afterEach(() => logic.unmount())
+
+ it.each(['succeeds', 'fails'])('keeps a saved value when an earlier account read %s', async (outcome) => {
+ let settleRead!: () => void
+ mockRetrieve.mockReturnValueOnce(
+ new Promise<AccountApi>((resolve, reject) => {
+ settleRead = () => (outcome === 'succeeds' ? resolve(account) : reject(new Error('Unavailable')))
+ })
+ )
+ logic.actions.loadAccount()
+ try {
+ await waitFor(() => expect(mockRetrieve).toHaveBeenCalledTimes(1))
+ accountPropertyUpdatesLogic.actions.accountUpdated(PROJECT_ID, {
+ ...account,
+ properties: { website_domain: 'saved.example.com' },
+ })
+ } finally {
+ settleRead()
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.account?.properties?.website_domain).toBe('saved.example.com')
+ expect(logic.values.accountLoadFailed).toBe(false)
+ })
+
+ it.each([
+ { label: 'project', projectId: PROJECT_ID + 1, accountId: ACCOUNT_ID },
+ { label: 'account', projectId: PROJECT_ID, accountId: 'other-account' },
+ ])('ignores updates for another $label', async ({ projectId, accountId }) => {
+ await expectLogic(logic, () => logic.actions.loadAccount()).toFinishAllListeners()
+ accountPropertyUpdatesLogic.actions.accountUpdated(projectId, {
+ ...account,
+ id: accountId,
+ name: 'Other account',
+ })
+ expect(logic.values.account).toEqual(account)
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyDataLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyDataLogic.ts
new file mode 100644
index 000000000000..867a91accf9c
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyDataLogic.ts
@@ -0,0 +1,141 @@
+import { LogicWrapper, MakeLogicType, connect, kea, key, listeners, path, props, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import * as api from '../../generated/api'
+import type { AccountApi } from '../../generated/api.schemas'
+import { accountPropertyUpdatesLogic } from './accountPropertyUpdatesLogic'
+import type { AccountSidebarPropertyData } from './accountSidebarProperties'
+
+export interface AccountPropertyDataLogicProps {
+ projectId: number
+ accountId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountPropertyDataLogicValues {
+ account: AccountApi | null
+ accountLoadFailed: boolean
+ accountLoading: boolean
+ propertyData: AccountSidebarPropertyData | null
+ propertyDataLoadFailed: boolean
+ propertyDataLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountPropertyDataLogicActions {
+ loadAccount: (_: void) => void
+ loadAccountFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAccountSuccess: (
+ account: AccountApi,
+ payload?: void
+ ) => {
+ account: AccountApi
+ payload?: void
+ }
+ loadPropertyData: (_: void) => void
+ loadPropertyDataFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadPropertyDataSuccess: (
+ propertyData: AccountSidebarPropertyData,
+ payload?: void
+ ) => {
+ propertyData: AccountSidebarPropertyData
+ payload?: void
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountPropertyDataLogicMeta {
+ key: string
+}
+
+export type accountPropertyDataLogicType = MakeLogicType<
+ accountPropertyDataLogicValues,
+ accountPropertyDataLogicActions,
+ AccountPropertyDataLogicProps,
+ accountPropertyDataLogicMeta
+>
+
+export const accountPropertyDataLogic: LogicWrapper<accountPropertyDataLogicType> = kea<accountPropertyDataLogicType>([
+ props({} as AccountPropertyDataLogicProps),
+ key(({ projectId, accountId }) => `${projectId}:${accountId}`),
+ path((key) => ['products', 'customer_analytics', 'accountPropertyDataLogic', key]),
+ connect(() => ({ logic: [accountPropertyUpdatesLogic] })),
+ loaders(({ props, cache, values }) => ({
+ propertyData: [
+ null as AccountSidebarPropertyData | null,
+ {
+ loadPropertyData: async (_: void, breakpoint): Promise<AccountSidebarPropertyData> => {
+ const [customValues, relationships] = await Promise.all([
+ api.accountsCustomPropertyValuesList(String(props.projectId), props.accountId),
+ api.accountsRelationshipsList(String(props.projectId), props.accountId),
+ ])
+ breakpoint()
+ return { customValues, relationships }
+ },
+ },
+ ],
+ account: [
+ null as AccountApi | null,
+ {
+ loadAccount: async (_: void, breakpoint): Promise<AccountApi> => {
+ const revision = cache.accountRevision ?? 0
+ let account: AccountApi
+ try {
+ account = await api.accountsRetrieve(String(props.projectId), props.accountId)
+ } catch (error) {
+ breakpoint()
+ if (revision !== (cache.accountRevision ?? 0) && values.account) {
+ return values.account
+ }
+ throw error
+ }
+ breakpoint()
+ return revision !== (cache.accountRevision ?? 0) ? (values.account ?? account) : account
+ },
+ },
+ ],
+ })),
+ reducers({
+ propertyDataLoadFailed: [
+ false,
+ {
+ loadPropertyData: () => false,
+ loadPropertyDataSuccess: () => false,
+ loadPropertyDataFailure: () => true,
+ },
+ ],
+ accountLoadFailed: [
+ false,
+ { loadAccount: () => false, loadAccountSuccess: () => false, loadAccountFailure: () => true },
+ ],
+ }),
+ listeners(({ actions, props, cache, values }) => ({
+ [accountPropertyUpdatesLogic.actionTypes.accountUpdated]: ({ projectId, account }) => {
+ if (projectId === props.projectId && account.id === props.accountId) {
+ cache.accountRevision = (cache.accountRevision ?? 0) + 1
+ actions.loadAccountSuccess(account)
+ }
+ },
+ [accountPropertyUpdatesLogic.actionTypes.relationshipsUpdated]: ({ projectId, accountId }) => {
+ if (
+ projectId === props.projectId &&
+ accountId === props.accountId &&
+ (values.propertyData !== null || values.propertyDataLoading || values.propertyDataLoadFailed)
+ ) {
+ actions.loadPropertyData()
+ }
+ },
+ })),
+])
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyUpdatesLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyUpdatesLogic.ts
new file mode 100644
index 000000000000..e75946bb25fb
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountPropertyUpdatesLogic.ts
@@ -0,0 +1,31 @@
+import { MakeLogicType, actions, kea, path } from 'kea'
+
+import type { AccountApi } from '../../generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountPropertyUpdatesLogicActions {
+ accountUpdated: (
+ projectId: number,
+ account: AccountApi
+ ) => {
+ account: AccountApi
+ projectId: number
+ }
+ relationshipsUpdated: (
+ projectId: number,
+ accountId: string
+ ) => {
+ accountId: string
+ projectId: number
+ }
+}
+
+export type accountPropertyUpdatesLogicType = MakeLogicType<{}, accountPropertyUpdatesLogicActions>
+
+export const accountPropertyUpdatesLogic = kea<accountPropertyUpdatesLogicType>([
+ path(['products', 'customer_analytics', 'accountPropertyUpdatesLogic']),
+ actions({
+ accountUpdated: (projectId: number, account: AccountApi) => ({ projectId, account }),
+ relationshipsUpdated: (projectId: number, accountId: string) => ({ projectId, accountId }),
+ }),
+])
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.ts
index adc09e5cf07d..61bd58de57e0 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarConfigLogic.ts
@@ -108,7 +108,7 @@ const loadEveryPage = async <T>(
return results
}
-const resolvePinnedProperties = (
+export const resolvePinnedProperties = (
references: readonly PinnedAccountProperty[],
definitions: AvailableDefinitions
): PinnedPropertyResolution => {
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts
index 1e46f8989d90..3b7726df1c62 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.test.ts
@@ -9,6 +9,7 @@ import { userHasAccess } from 'lib/utils/accessControlUtils'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import type { UserBasicType } from '~/types'
import { accountRelationshipsLogic } from '../../components/Accounts/accountRelationshipsLogic'
import { AccountsEvents } from '../../components/Accounts/constants'
@@ -214,14 +215,74 @@ describe('accountSidebarPropertiesLogic', () => {
tab.mount()
try {
await expectLogic(tab).toFinishAllListeners()
- assignments.push(assignment(4))
- await expectLogic(logic, () => tab.actions.loadRelationships()).toFinishAllListeners()
+ await expectLogic(logic, () =>
+ tab.actions.assignRelationship(relationshipDefinition, { id: 4 } as UserBasicType)
+ ).toFinishAllListeners()
expect(logic.values.sidebarProperties[0]).toMatchObject({ members: [{ id: 1 }, { id: 2 }, { id: 4 }] })
} finally {
tab.unmount()
}
})
+ it.each([
+ { kind: 'custom', timelineReads: 0, expectedMembers: [1, 2] },
+ { kind: 'relationship', timelineReads: 2, expectedMembers: [2, 4] },
+ ])(
+ 'refreshes only changed data once after a $kind widget save',
+ async ({ kind, timelineReads, expectedMembers }) => {
+ const readValues = jest.fn(() => [{ id: 'value-1', definition_id: definition.id, value: storedValue }])
+ const readTimeline = jest.fn(() => assignments)
+ useMocks({
+ get: {
+ [VALUES_URL]: readValues,
+ [RELATIONSHIPS_URL]: ({ request }) =>
+ new URL(request.url).searchParams.has('include_history') ? readTimeline() : assignments,
+ },
+ })
+ logic = accountSidebarPropertiesLogic({
+ projectId: MOCK_DEFAULT_TEAM.id,
+ accountId: 'account-1',
+ instanceId: 'view:properties',
+ propertyReferences: [
+ { kind: 'custom_property', id: definition.id },
+ { kind: 'relationship', id: relationshipDefinition.id },
+ ],
+ })
+ logic.mount()
+ const first = accountRelationshipsLogic({ accountId: 'account-1', instanceId: 'first' })
+ const second = accountRelationshipsLogic({ accountId: 'account-1', instanceId: 'second' })
+ first.mount()
+ second.mount()
+ try {
+ await expectLogic(logic).toFinishAllListeners()
+ readValues.mockClear()
+ readTimeline.mockClear()
+ await expectLogic(logic, () => {
+ if (kind === 'custom') {
+ logic.actions.saveCustomProperty('custom:property-1', 'Changed', 'account_view')
+ } else {
+ logic.actions.saveRelationship('relationship:relationship-1', expectedMembers, 'account_view')
+ }
+ }).toFinishAllListeners()
+ expect(logic.values.sidebarProperties[0]).toMatchObject({
+ value: kind === 'custom' ? 'Changed' : 'Starter',
+ })
+ for (const tile of [first, second]) {
+ expect(
+ tile.values.activeRelationships
+ .filter((row) => row.definition.id === relationshipDefinition.id)
+ .map((row) => row.user?.id)
+ ).toEqual(expectedMembers)
+ }
+ expect(readValues).toHaveBeenCalledTimes(1)
+ expect(readTimeline).toHaveBeenCalledTimes(timelineReads)
+ } finally {
+ first.unmount()
+ second.unmount()
+ }
+ }
+ )
+
it.each([
['text', 'Growth'],
['number', 0],
@@ -247,6 +308,7 @@ describe('accountSidebarPropertiesLogic', () => {
it.each([
{ source: undefined, expectedSource: 'account_sidebar' },
{ source: 'list_expansion', expectedSource: 'list_expansion' },
+ { source: 'account_view', expectedSource: 'account_view' },
] as const)(
'reports saved values and assignments with $expectedSource attribution',
async ({ source, expectedSource }) => {
@@ -264,7 +326,7 @@ describe('accountSidebarPropertiesLogic', () => {
logic.actions.saveRelationship('relationship:relationship-1', [2], source)
).toFinishAllListeners()
expect(capture).toHaveBeenCalledWith(AccountsEvents.RoleAssigned, {
- role: relationshipDefinition.name,
+ ...(source === 'account_view' ? {} : { role: relationshipDefinition.name }),
is_assigned: true,
assigned_user_id: 2,
source: expectedSource,
@@ -478,6 +540,88 @@ describe('accountSidebarPropertiesLogic', () => {
expect(write).not.toHaveBeenCalled()
})
+ it('loads values when an empty widget is configured without remounting it', async () => {
+ useMocks({
+ get: { '/api/projects/:project_id/user_customer_analytics_config/@me/': { pinned_properties: [] } },
+ })
+ const props = { projectId: 1, accountId: 'account-1', instanceId: 'view:first', propertyReferences: [] }
+ logic = accountSidebarPropertiesLogic(props)
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.propertyData).toBeNull()
+ expect(logic.values.propertiesPanelState).toBe('ready')
+ accountSidebarPropertiesLogic.build({
+ ...props,
+ propertyReferences: [{ kind: 'custom_property', id: definition.id }],
+ })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.propertiesPanelState).toBe('ready')
+ expect(logic.values.sidebarProperties).toMatchObject([{ key: 'custom:property-1', value: 'Starter' }])
+ expect(accountSidebarConfigLogic({ projectId: 1 }).values.config?.pinned_properties).toEqual([])
+ })
+
+ it('keeps widget selections and edits separate while sharing saved values with the sidebar', async () => {
+ silenceKeaLoadersErrors()
+ await mount()
+ const first = accountSidebarPropertiesLogic({
+ projectId: 1,
+ accountId: 'account-1',
+ instanceId: 'view:first',
+ propertyReferences: [{ kind: 'custom_property', id: definition.id }],
+ })
+ const second = accountSidebarPropertiesLogic({
+ projectId: 1,
+ accountId: 'account-1',
+ instanceId: 'view:second',
+ propertyReferences: [
+ { kind: 'custom_property', id: definition.id },
+ { kind: 'relationship', id: relationshipDefinition.id },
+ ],
+ })
+ first.mount()
+ second.mount()
+ try {
+ await expectLogic(first).toFinishAllListeners()
+ await expectLogic(second).toFinishAllListeners()
+ expect(first.values.sidebarProperties.map(({ key }) => key)).toEqual(['custom:property-1'])
+ expect(second.values.sidebarProperties.map(({ key }) => key)).toEqual([
+ 'custom:property-1',
+ 'relationship:relationship-1',
+ ])
+ first.actions.editProperty(first.values.sidebarProperties[0])
+ second.actions.editProperty(second.values.sidebarProperties[1])
+ useMocks({ post: { [VALUES_URL]: () => [500, { detail: 'Try again' }] } })
+ await expectLogic(first, () =>
+ first.actions.saveCustomProperty('custom:property-1', 'Changed', 'account_view')
+ ).toFinishAllListeners()
+ expect(first.values.propertySaveFailed).toBe(true)
+ expect(first.values.editingPropertyKey).toBe('custom:property-1')
+ expect(second.values.editingPropertyKey).toBe('relationship:relationship-1')
+ useMocks({
+ post: {
+ [VALUES_URL]: async ({ request }) => {
+ const body = (await request.json()) as CustomPropertyValueWriteApi
+ storedValue = body.value
+ return [201, { id: 'saved-value', definition_id: body.definition, value: storedValue }]
+ },
+ },
+ })
+ await expectLogic(first, () =>
+ first.actions.saveCustomProperty('custom:property-1', 'Changed', 'account_view')
+ ).toFinishAllListeners()
+ await waitFor(() => expect(second.values.sidebarProperties[0]).toMatchObject({ value: 'Changed' }))
+ expect(logic.values.sidebarProperties[1]).toMatchObject({ value: 'Changed' })
+ expect(second.values.editingPropertyKey).toBe('relationship:relationship-1')
+ expect(accountSidebarConfigLogic({ projectId: 1 }).values.config?.pinned_properties).toEqual([
+ { kind: 'relationship', id: relationshipDefinition.id },
+ { kind: 'custom_property', id: definition.id },
+ ])
+ } finally {
+ first.unmount()
+ second.unmount()
+ }
+ })
+
it('does not show another account values while loading', async () => {
await mount()
const other = accountSidebarPropertiesLogic({ projectId: 1, accountId: 'account-2' })
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts
index 076c4bdf4015..0201b1287e19 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountSidebarPropertiesLogic.ts
@@ -9,6 +9,7 @@ import {
listeners,
path,
props,
+ propsChanged,
reducers,
selectors,
} from 'kea'
@@ -21,7 +22,6 @@ 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 {
@@ -31,10 +31,15 @@ import {
import * as api from 'products/customer_analytics/frontend/generated/api'
import type { UserCustomerAnalyticsConfigApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type { PinnedAccountPropertyApi } from '../../generated/api.schemas'
+import { accountPropertyDataLogic } from './accountPropertyDataLogic'
+import { accountPropertyUpdatesLogic } from './accountPropertyUpdatesLogic'
import {
accountSidebarConfigLogic,
AvailableDefinitions,
ResolvedPinnedAccountProperty,
+ PinnedAccountProperty,
+ resolvePinnedProperties,
} from './accountSidebarConfigLogic'
import { AccountSidebarPropertyData, buildAccountSidebarProperties } from './accountSidebarProperties'
import {
@@ -48,10 +53,12 @@ import {
export interface AccountSidebarPropertiesLogicProps {
accountId: string
projectId: number
+ instanceId?: string
+ propertyReferences?: PinnedAccountProperty[]
}
export type AccountPropertiesPanelState = 'loading' | 'failed' | 'ready'
-export type AccountPropertyEditSource = 'account_sidebar' | 'list_expansion'
+export type AccountPropertyEditSource = 'account_sidebar' | 'list_expansion' | 'account_view'
export interface RelationshipEditBaseline {
propertyKey: string
@@ -61,24 +68,27 @@ export interface RelationshipEditBaseline {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountSidebarPropertiesLogicValues {
+ propertyData: AccountSidebarPropertyData | null // accountPropertyDataLogic
+ propertyDataLoading: boolean // accountPropertyDataLogic
+ sharedPropertyDataLoadFailed: boolean // accountPropertyDataLogic
availableDefinitions: AvailableDefinitions | null // accountSidebarConfigLogic
availableDefinitionsLoadFailed: boolean // accountSidebarConfigLogic
config: UserCustomerAnalyticsConfigApi | null // accountSidebarConfigLogic
configLoadFailed: boolean // accountSidebarConfigLogic
- resolvedPinnedProperties: ResolvedPinnedAccountProperty[] // accountSidebarConfigLogic
+ sidebarPinnedProperties: ResolvedPinnedAccountProperty[] // accountSidebarConfigLogic
members: OrganizationMemberType[] | null // membersLogic
membersLoading: boolean // membersLogic
availableMembers: AccountRelationshipMember[]
+ configuredPropertyReferences: PinnedAccountPropertyApi[] | null
editingPropertyKey: string | null
propertiesAvailable: boolean
propertiesLoadFailed: boolean
propertiesPanelState: AccountPropertiesPanelState
propertiesRefreshFailed: boolean
- propertyData: AccountSidebarPropertyData | null
propertyDataLoadFailed: boolean
- propertyDataLoading: boolean
propertySaveFailed: boolean
relationshipEditBaseline: RelationshipEditBaseline | null
+ resolvedPinnedProperties: ResolvedPinnedAccountProperty[]
savedPropertyKey: string | null
savedPropertyKeyLoading: boolean
savingPropertyKey: string | null
@@ -87,6 +97,21 @@ export interface accountSidebarPropertiesLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface accountSidebarPropertiesLogicActions {
+ loadPropertyDataFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ } // accountPropertyDataLogic
+ loadPropertyDataSuccess: (
+ propertyData: AccountSidebarPropertyData,
+ payload?: void | undefined
+ ) => {
+ payload?: void | undefined
+ propertyData: AccountSidebarPropertyData
+ } // accountPropertyDataLogic
+ reloadPropertyData: (_?: void | undefined) => void // accountPropertyDataLogic
ensureAllMembersLoaded: () => {
value: true
} // membersLogic
@@ -96,20 +121,8 @@ export interface accountSidebarPropertiesLogicActions {
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
+ loadPropertyData: () => {
+ value: true
}
persistCustomProperty: ({
propertyKey,
@@ -235,6 +248,9 @@ export interface accountSidebarPropertiesLogicActions {
propertyKey: string
source: AccountPropertyEditSource
}
+ setConfiguredPropertyReferences: (references: PinnedAccountProperty[] | null) => {
+ references: PinnedAccountPropertyApi[] | null
+ }
setRelationshipEditBaseline: (baseline: RelationshipEditBaseline) => {
baseline: RelationshipEditBaseline
}
@@ -244,6 +260,15 @@ export interface accountSidebarPropertiesLogicActions {
export interface accountSidebarPropertiesLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
+ propertyDataLoadFailed: (
+ resolvedPinnedProperties: ResolvedPinnedAccountProperty[],
+ sharedPropertyDataLoadFailed: boolean
+ ) => boolean
+ resolvedPinnedProperties: (
+ sidebarPinnedProperties: ResolvedPinnedAccountProperty[],
+ availableDefinitions: AvailableDefinitions | null,
+ configuredPropertyReferences: PinnedAccountPropertyApi[] | null
+ ) => ResolvedPinnedAccountProperty[]
sidebarProperties: (
resolvedPinnedProperties: ResolvedPinnedAccountProperty[],
propertyData: AccountSidebarPropertyData | null
@@ -256,13 +281,15 @@ export interface accountSidebarPropertiesLogicMeta {
config: UserCustomerAnalyticsConfigApi | null,
availableDefinitions: AvailableDefinitions | null,
resolvedPinnedProperties: ResolvedPinnedAccountProperty[],
- propertyData: AccountSidebarPropertyData | null
+ propertyData: AccountSidebarPropertyData | null,
+ configuredPropertyReferences: PinnedAccountPropertyApi[] | null
) => boolean
propertiesLoadFailed: (
configLoadFailed: boolean,
availableDefinitionsLoadFailed: boolean,
resolvedPinnedProperties: ResolvedPinnedAccountProperty[],
- propertyDataLoadFailed: boolean
+ propertyDataLoadFailed: boolean,
+ configuredPropertyReferences: PinnedAccountPropertyApi[] | null
) => boolean
propertiesPanelState: (
propertiesAvailable: boolean,
@@ -282,9 +309,9 @@ export type accountSidebarPropertiesLogicType = MakeLogicType<
export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertiesLogicType> =
kea<accountSidebarPropertiesLogicType>([
props({} as AccountSidebarPropertiesLogicProps),
- key(({ projectId, accountId }) => `${projectId}:${accountId}`),
+ key(({ projectId, accountId, instanceId }) => `${projectId}:${accountId}${instanceId ? `:${instanceId}` : ''}`),
path((key) => ['products', 'customer_analytics', 'accountSidebarPropertiesLogic', key]),
- connect(({ projectId }: AccountSidebarPropertiesLogicProps) => ({
+ connect(({ projectId, accountId }: AccountSidebarPropertiesLogicProps) => ({
values: [
accountSidebarConfigLogic({ projectId }),
[
@@ -292,14 +319,23 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
'availableDefinitionsLoadFailed',
'config',
'configLoadFailed',
- 'resolvedPinnedProperties',
+ 'resolvedPinnedProperties as sidebarPinnedProperties',
],
+ accountPropertyDataLogic({ projectId, accountId }),
+ ['propertyData', 'propertyDataLoading', 'propertyDataLoadFailed as sharedPropertyDataLoadFailed'],
membersLogic,
['members', 'membersLoading'],
],
- actions: [membersLogic, ['ensureAllMembersLoaded']],
+ actions: [
+ membersLogic,
+ ['ensureAllMembersLoaded'],
+ accountPropertyDataLogic({ projectId, accountId }),
+ ['loadPropertyData as reloadPropertyData', 'loadPropertyDataSuccess', 'loadPropertyDataFailure'],
+ ],
})),
actions({
+ loadPropertyData: true,
+ setConfiguredPropertyReferences: (references: PinnedAccountProperty[] | null) => ({ references }),
editProperty: (property: AccountSidebarProperty) => ({ property }),
cancelEditing: true,
saveCustomProperty: (
@@ -324,23 +360,7 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
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 }
- },
- },
- ],
+ loaders(({ props, actions }) => ({
savedPropertyKey: [
null as string | null,
{
@@ -416,7 +436,12 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
},
],
})),
- reducers({
+ reducers(({ props }) => ({
+ // Props mutate in place. Redux-backed references keep selectors current when tile configuration changes.
+ configuredPropertyReferences: [
+ props.propertyReferences ?? (null as PinnedAccountProperty[] | null),
+ { setConfiguredPropertyReferences: (_, { references }) => references },
+ ],
relationshipEditBaseline: [
null as RelationshipEditBaseline | null,
{
@@ -466,14 +491,6 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
persistRelationshipFailure: () => null,
},
],
- propertyDataLoadFailed: [
- false,
- {
- loadPropertyData: () => false,
- loadPropertyDataSuccess: () => false,
- loadPropertyDataFailure: () => true,
- },
- ],
propertySaveFailed: [
false,
{
@@ -485,8 +502,26 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
persistRelationshipFailure: () => true,
},
],
- }),
+ })),
selectors({
+ propertyDataLoadFailed: [
+ (s) => [s.resolvedPinnedProperties, s.sharedPropertyDataLoadFailed],
+ (references: ResolvedPinnedAccountProperty[], failed: boolean): boolean =>
+ references.length > 0 && failed,
+ ],
+ resolvedPinnedProperties: [
+ (s) => [s.sidebarPinnedProperties, s.availableDefinitions, s.configuredPropertyReferences],
+ (
+ sidebar: ResolvedPinnedAccountProperty[],
+ definitions: AvailableDefinitions | null,
+ references: PinnedAccountProperty[] | null
+ ): ResolvedPinnedAccountProperty[] =>
+ references === null
+ ? sidebar
+ : definitions
+ ? resolvePinnedProperties(references, definitions).resolved
+ : [],
+ ],
sidebarProperties: [
(s) => [s.resolvedPinnedProperties, s.propertyData],
(
@@ -522,13 +557,23 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
},
],
propertiesAvailable: [
- (s) => [s.config, s.availableDefinitions, s.resolvedPinnedProperties, s.propertyData],
+ (s) => [
+ s.config,
+ s.availableDefinitions,
+ s.resolvedPinnedProperties,
+ s.propertyData,
+ s.configuredPropertyReferences,
+ ],
(
config: UserCustomerAnalyticsConfigApi | null,
definitions: AvailableDefinitions | null,
pinned: ResolvedPinnedAccountProperty[],
- data: AccountSidebarPropertyData | null
- ): boolean => config !== null && definitions !== null && (pinned.length === 0 || data !== null),
+ data: AccountSidebarPropertyData | null,
+ references: PinnedAccountProperty[] | null
+ ): boolean =>
+ (references !== null || config !== null) &&
+ definitions !== null &&
+ (pinned.length === 0 || data !== null),
],
propertiesLoadFailed: [
(s) => [
@@ -536,13 +581,16 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
s.availableDefinitionsLoadFailed,
s.resolvedPinnedProperties,
s.propertyDataLoadFailed,
+ s.configuredPropertyReferences,
],
(
configFailed: boolean,
definitionsFailed: boolean,
pinned: ResolvedPinnedAccountProperty[],
- dataFailed: boolean
- ): boolean => configFailed || definitionsFailed || (pinned.length > 0 && dataFailed),
+ dataFailed: boolean,
+ references: PinnedAccountProperty[] | null
+ ): boolean =>
+ (references === null && 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.
@@ -564,14 +612,32 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
.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()
+ const refreshAccountsList = (): void => {
dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
}
+ const refreshRelationships = (): void => {
+ accountPropertyUpdatesLogic.actions.relationshipsUpdated(props.projectId, props.accountId)
+ refreshAccountsList()
+ }
return {
+ setConfiguredPropertyReferences: () => {
+ if (!values.propertyDataLoading) {
+ actions.loadPropertyData()
+ }
+ },
+ loadPropertyData: () => {
+ if (values.resolvedPinnedProperties.length > 0) {
+ actions.reloadPropertyData()
+ }
+ },
editProperty: ({ property }) => {
+ if (props.instanceId?.startsWith('view:') && values.editingPropertyKey === property.key) {
+ posthog.capture(AccountsEvents.AccountPropertyEditorOpened, {
+ source: 'account_view',
+ property_source: property.kind,
+ })
+ }
if (property.kind === 'relationship' && property.editable !== false) {
actions.setRelationshipEditBaseline(baselineFor(property))
actions.ensureAllMembersLoaded()
@@ -630,22 +696,41 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
source: payload?.source ?? 'account_sidebar',
})
}
- refresh()
+ actions.loadPropertyData()
+ refreshAccountsList()
},
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,
+ ...(payload?.source === 'account_view'
+ ? {}
+ : { 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: payload?.source ?? 'account_sidebar',
})
}
- refresh()
+ refreshRelationships()
+ },
+ persistCustomPropertyFailure: () => {
+ if (props.instanceId?.startsWith('view:')) {
+ posthog.capture(AccountsEvents.AccountPropertySaveFailed, {
+ source: 'account_view',
+ property_source: 'custom',
+ })
+ }
+ },
+ persistRelationshipFailure: () => {
+ if (props.instanceId?.startsWith('view:')) {
+ posthog.capture(AccountsEvents.AccountPropertySaveFailed, {
+ source: 'account_view',
+ property_source: 'relationship',
+ })
+ }
+ refreshRelationships()
},
- persistRelationshipFailure: refresh,
[accountSidebarConfigLogic({ projectId: props.projectId }).actionTypes.loadConfigSuccess]: () =>
actions.loadPropertyData(),
[accountSidebarConfigLogic({ projectId: props.projectId }).actionTypes.persistPinnedPropertiesSuccess]:
@@ -655,4 +740,18 @@ export const accountSidebarPropertiesLogic: LogicWrapper<accountSidebarPropertie
}
}),
afterMount(({ actions }) => actions.loadPropertyData()),
+ propsChanged(({ actions, props }, previousProps) => {
+ const references = props.propertyReferences ?? []
+ const previous = previousProps.propertyReferences ?? []
+ const changed =
+ (props.propertyReferences === undefined) !== (previousProps.propertyReferences === undefined) ||
+ references.length !== previous.length ||
+ references.some(
+ (reference, index) =>
+ reference.kind !== previous[index]?.kind || reference.id !== previous[index]?.id
+ )
+ if (changed) {
+ actions.setConfiguredPropertyReferences(props.propertyReferences ?? null)
+ }
+ }),
])
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts
index 0cea51b2ad10..4ba6a557a8a0 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts
@@ -31,9 +31,9 @@ const tabs: AccountTabDefinition[] = [
]
describe('account tabs', () => {
- it('offers replay tiles without adding a system tab', () => {
- expect(listAvailableAccountViewComponents({}).map((component) => component.kind)).toContain('session_replays')
- expect(listAccountTabs({}, []).map((tab) => tab.routeKey)).not.toContain('session_replays')
+ it.each(['properties', 'session_replays'])('offers %s tiles without adding a system tab', (kind) => {
+ expect(listAvailableAccountViewComponents({}).map((component) => component.kind)).toContain(kind)
+ expect(listAccountTabs({}, []).map((tab) => tab.routeKey)).not.toContain(kind)
})
it('falls back from an unavailable system route but keeps an unknown view route', () => {
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.test.ts
index a6fb0142af01..f79eaf721649 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.test.ts
@@ -23,7 +23,11 @@ import type {
AccountViewApi,
UserCustomerAnalyticsConfigApi,
} from '../../generated/api.schemas'
-import { createAccountViewContent, type AccountViewComponentInstance } from './accountViewDocument'
+import {
+ createAccountViewContent,
+ parseAccountViewContent,
+ type AccountViewComponentInstance,
+} from './accountViewDocument'
import { accountViewsLogic, type accountViewsLogicValues } from './accountViewsLogic'
jest.mock('../../generated/api', () => ({
@@ -325,6 +329,51 @@ describe('accountViewsLogic tracking', () => {
}
)
+ it('retains a failed properties tile config and saves it without changing other tiles or pins', async () => {
+ const firstConfig = { properties: [{ kind: 'account', key: 'website_domain' }] }
+ const secondConfig = {
+ properties: [
+ { kind: 'account', key: 'known_emails' },
+ { kind: 'relationship', id: '22222222-2222-4222-8222-222222222222' },
+ ],
+ }
+ let propertiesView: AccountViewApi = {
+ ...view,
+ content: createAccountViewContent([
+ { nodeId: 'first', kind: 'properties', span: 6, config: firstConfig },
+ { nodeId: 'second', kind: 'properties', span: 6, config: secondConfig },
+ ...components,
+ ]),
+ }
+ jest.mocked(accountViewsList).mockResolvedValue([propertiesView])
+ mockUpdate.mockImplementation(async (_, __, patch) => {
+ propertiesView = { ...propertiesView, content: patch.content ?? propertiesView.content, version: 2 }
+ return propertiesView
+ })
+ await expectLogic(logic, () => logic.actions.loadViews()).toFinishAllListeners()
+ const changed = { properties: [...secondConfig.properties].reverse() }
+ logic.actions.openTileEditor(view.id, 'first', 'Properties', {
+ propertiesConfig: firstConfig,
+ accountId: 'account-one',
+ })
+ logic.actions.setTileEditorPropertiesConfig(changed)
+ mockUpdate.mockRejectedValueOnce(new ApiError('Save failed', 500))
+ await expectLogic(logic, () => {
+ logic.actions.saveTileEditor()
+ logic.actions.saveTileEditor()
+ }).toFinishAllListeners()
+ expect(mockUpdate).toHaveBeenCalledTimes(1)
+ expect(logic.values.tileEditor?.propertiesConfig).toEqual(changed)
+ await expectLogic(logic, () => logic.actions.saveTileEditor()).toFinishAllListeners()
+ expect(logic.values.tileEditor).toBeNull()
+ expect(parseAccountViewContent(logic.values.views[0].content).map(({ config }) => config)).toEqual([
+ changed,
+ secondConfig,
+ ...components.map(({ config }) => config),
+ ])
+ expect(logic.values.config?.pinned_properties).toEqual([])
+ })
+
it.each(['editor', 'tabs'])('reports a blocked %s save without a write or success', async (surface) => {
if (surface === 'editor') {
logic.actions.openCreateEditor()
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts
index 8b509fd5c80b..96f3d9f817fb 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts
@@ -25,6 +25,7 @@ import type {
AccountViewVisibilityEnumApi,
UserCustomerAnalyticsConfigApi,
} from '../../generated/api.schemas'
+import { getAccountWidgetProperties } from './accountPropertiesWidgetConfig'
import {
createAccountViewContent,
createAccountViewComponentInstance,
@@ -46,6 +47,8 @@ export interface AccountViewTileEditor {
viewId: string
nodeId: string
name: string
+ propertiesConfig?: AccountViewTileConfig
+ accountId?: string
}
const EMPTY_TABS_CONFIG: AccountDetailTabsConfigApi = {
@@ -140,10 +143,16 @@ export interface accountViewsLogicActions {
openTileEditor: (
viewId: string,
nodeId: string,
- name: string
+ name: string,
+ properties?: {
+ accountId: string
+ propertiesConfig: AccountViewTileConfig
+ }
) => {
+ accountId?: string | undefined
name: string
nodeId: string
+ propertiesConfig?: AccountViewTileConfig | undefined
viewId: string
}
reloadEditor: () => {
@@ -231,6 +240,9 @@ export interface accountViewsLogicActions {
setTileEditorName: (name: string) => {
name: string
}
+ setTileEditorPropertiesConfig: (propertiesConfig: AccountViewTileConfig) => {
+ propertiesConfig: AccountViewTileConfig
+ }
updateViewComponentConfig: (
viewId: string,
nodeId: string,
@@ -335,7 +347,13 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
duplicateEditorComponent: (nodeId: string) => ({ nodeId }),
removeEditorComponent: (nodeId: string) => ({ nodeId }),
reorderEditorComponent: (activeNodeId: string, overNodeId: string) => ({ activeNodeId, overNodeId }),
- openTileEditor: (viewId: string, nodeId: string, name: string) => ({ viewId, nodeId, name }),
+ openTileEditor: (
+ viewId: string,
+ nodeId: string,
+ name: string,
+ properties?: { propertiesConfig: AccountViewTileConfig; accountId: string }
+ ) => ({ viewId, nodeId, name, ...properties }),
+ setTileEditorPropertiesConfig: (propertiesConfig: AccountViewTileConfig) => ({ propertiesConfig }),
closeTileEditor: true,
setTileEditorName: (name: string) => ({ name }),
saveTileEditor: true,
@@ -530,7 +548,11 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
tileEditor: [
null as AccountViewTileEditor | null,
{
- openTileEditor: (_, { viewId, nodeId, name }: AccountViewTileEditor) => ({ viewId, nodeId, name }),
+ openTileEditor: (_, editor: AccountViewTileEditor) => editor,
+ setTileEditorPropertiesConfig: (
+ state,
+ { propertiesConfig }: { propertiesConfig: AccountViewTileConfig }
+ ) => (state ? { ...state, propertiesConfig } : state),
closeTileEditor: () => null,
setTileEditorName: (state, { name }: { name: string }) => (state ? { ...state, name } : state),
},
@@ -705,7 +727,10 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
actions.deleteViewFailure()
}
},
- saveTileEditor: async () => {
+ saveTileEditor: async (_, __, ___, previousState) => {
+ if (accountViewsLogic({ projectId: props.projectId }).selectors.tileSaving(previousState)) {
+ return
+ }
const tileEditor = values.tileEditor
if (!tileEditor) {
posthog.capture(AccountsEvents.AccountViewTileRenameFailed, { failure_type: 'validation' })
@@ -715,18 +740,29 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
await queueViewWrite(cache, tileEditor.viewId, async () => {
const view = values.views.find((candidate) => candidate.id === tileEditor.viewId)
const name = tileEditor.name.trim()
- if (!view || !name) {
+ if (!view || !view.can_edit || !name) {
posthog.capture(AccountsEvents.AccountViewTileRenameFailed, { failure_type: 'validation' })
actions.saveViewComponentFailure()
return
}
const components = parseAccountViewContent(view.content).map((component) =>
- component.nodeId === tileEditor.nodeId ? { ...component, title: name } : component
+ component.nodeId === tileEditor.nodeId
+ ? {
+ ...component,
+ title: name,
+ ...(tileEditor.propertiesConfig ? { config: tileEditor.propertiesConfig } : {}),
+ }
+ : component
)
try {
const updatedView = await updateAccountViewComponents(props.projectId, view, components)
posthog.capture(AccountsEvents.AccountViewTileRenamed, { component_count: components.length })
actions.saveEditorSuccess(updatedView)
+ if (tileEditor.propertiesConfig) {
+ posthog.capture(AccountsEvents.PropertiesWidgetConfigured, {
+ property_count: getAccountWidgetProperties(tileEditor.propertiesConfig).length,
+ })
+ }
actions.closeTileEditor()
} catch (error) {
const failureType = getAccountViewFailureType(error)
@@ -736,7 +772,7 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
lemonToast.error(
failureType === 'conflict'
? 'This view changed. Refresh and try again.'
- : "Couldn't rename the tile. Try again."
+ : "Couldn't save the tile. Try again."
)
actions.saveViewComponentFailure()
actions.loadViews()
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountCustomPropertyEditor.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountCustomPropertyEditor.test.tsx
index b39d31067f3c..80f8b76d1755 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountCustomPropertyEditor.test.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountCustomPropertyEditor.test.tsx
@@ -141,13 +141,14 @@ describe('AccountCustomPropertyEditor', () => {
'retains an attempted %s selection when the save does not succeed',
(display_type) => {
const onSave = jest.fn()
+ const onCancel = jest.fn()
const value = '2026-01-01T00:00:00+00:00'
const { container } = render(
<AccountCustomPropertyEditor
definition={{ ...definition, display_type }}
value={value}
onSave={onSave}
- onCancel={jest.fn()}
+ onCancel={onCancel}
/>
)
fireEvent.click(container.querySelector('[data-attr="account-property-date-input"]')!)
@@ -158,6 +159,7 @@ describe('AccountCustomPropertyEditor', () => {
fireEvent.click(day)
fireEvent.click(calendar.querySelector('[data-attr="lemon-calendar-select-apply"]')!)
expect(onSave).toHaveBeenCalledTimes(1)
+ expect(onCancel).not.toHaveBeenCalled()
const attempted = onSave.mock.calls[0][0]
expect(dayjs(attempted).date()).toBe(15)
expect(container.querySelector('[data-attr="account-property-date-input"]')).toHaveTextContent(
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountNativePropertyField.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountNativePropertyField.tsx
new file mode 100644
index 000000000000..450f2eb51bbd
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountNativePropertyField.tsx
@@ -0,0 +1,114 @@
+import { IconPencil } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonInputSelect } from '@posthog/lemon-ui'
+
+import {
+ ACCOUNT_ID_FIELDS,
+ ACCOUNT_LIST_FIELDS,
+ AccountNativePropertyKey,
+ AccountNativePropertyValue,
+} from '../accountNativeProperties'
+
+export interface AccountNativePropertyFieldProps {
+ propertyKey: AccountNativePropertyKey
+ value: AccountNativePropertyValue
+ draft: AccountNativePropertyValue
+ editing: boolean
+ saving: boolean
+ disabledReason?: string
+ onEdit: () => void
+ onChange: (value: AccountNativePropertyValue) => void
+ onSave: () => void
+ onCancel: () => void
+}
+
+export function AccountNativePropertyField({
+ propertyKey,
+ value,
+ draft,
+ editing,
+ saving,
+ disabledReason,
+ onEdit,
+ onChange,
+ onSave,
+ onCancel,
+}: AccountNativePropertyFieldProps): JSX.Element {
+ const field = [...ACCOUNT_ID_FIELDS, ...ACCOUNT_LIST_FIELDS].find(({ key }) => key === propertyKey)!
+ return (
+ <div
+ className="flex flex-col gap-1 min-w-0"
+ role="group"
+ aria-label={field.label}
+ data-attr="account-native-property-row"
+ >
+ <div className="flex items-center gap-2 min-w-0 min-h-7">
+ <span className="min-w-0 text-xs text-secondary truncate">{field.label}</span>
+ {!editing ? (
+ <LemonButton
+ size="xsmall"
+ icon={<IconPencil />}
+ aria-label={`Edit ${field.label}`}
+ tooltip="Edit value"
+ disabledReason={disabledReason}
+ onClick={onEdit}
+ className="shrink-0"
+ data-attr="account-native-property-edit"
+ />
+ ) : null}
+ </div>
+ {editing ? (
+ <div className="flex flex-col gap-2 min-w-0">
+ {Array.isArray(draft) ? (
+ <LemonInputSelect
+ mode="multiple"
+ allowCustomValues
+ disableFiltering
+ value={draft}
+ onChange={onChange}
+ placeholder={field.placeholder}
+ fullWidth
+ disabledReason={saving ? 'Saving' : disabledReason}
+ data-attr="account-native-property-input"
+ />
+ ) : (
+ <LemonInput
+ aria-label={field.label}
+ value={draft}
+ onChange={onChange}
+ onPressEnter={saving ? undefined : onSave}
+ placeholder={field.placeholder}
+ fullWidth
+ disabled={saving || !!disabledReason}
+ autoFocus
+ data-attr="account-native-property-input"
+ />
+ )}
+ <div className="flex flex-wrap justify-end gap-1">
+ <LemonButton
+ size="xsmall"
+ onClick={onCancel}
+ disabledReason={saving ? 'Saving' : undefined}
+ data-attr="account-native-property-cancel"
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ type="primary"
+ onClick={onSave}
+ loading={saving}
+ disabledReason={disabledReason}
+ data-attr="account-native-property-save"
+ >
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ ) : (
+ <span className="text-sm break-words whitespace-pre-wrap" translate="no">
+ {Array.isArray(value) ? value.join(', ') || 'Not set' : value || 'Not set'}
+ </span>
+ )}
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfigurator.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfigurator.tsx
index cb08575d8779..1170fb258861 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfigurator.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfigurator.tsx
@@ -1,11 +1,7 @@
-import { DndContext } from '@dnd-kit/core'
-import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'
-import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
+import { LemonButton, LemonModal } from '@posthog/lemon-ui'
-import { LemonButton, LemonInputSelect, LemonModal } from '@posthog/lemon-ui'
-
-import { AccountPropertyConfiguratorItem } from './AccountPropertyConfiguratorItem'
-import { AccountPropertyOption, MAX_PINNED_ACCOUNT_PROPERTIES } from './accountPropertyTypes'
+import { AccountPropertySelection } from './AccountPropertySelection'
+import { AccountPropertyOption } from './accountPropertyTypes'
export interface AccountPropertyConfiguratorProps {
isOpen: boolean
@@ -30,37 +26,6 @@ export function AccountPropertyConfigurator({
saveDisabledReason,
title = 'Pin properties',
}: AccountPropertyConfiguratorProps): JSX.Element {
- const optionsByKey = new Map(options.map((option) => [option.key, option]))
- const selectedOptions = pinnedPropertyKeys.map(
- (key): AccountPropertyOption =>
- optionsByKey.get(key) ?? {
- key,
- label: key,
- kind: 'custom',
- }
- )
- const availableOptions = options.filter((option) => !pinnedPropertyKeys.includes(option.key))
- const pinLimitReached = pinnedPropertyKeys.length >= MAX_PINNED_ACCOUNT_PROPERTIES
-
- const addPinnedProperty = (keys: string[]): void => {
- const key = keys[0]
- if (key && !pinLimitReached && !pinnedPropertyKeys.includes(key)) {
- onChange([...pinnedPropertyKeys, key])
- }
- }
-
- const movePinnedProperty = (activeKey: string, overKey: string): void => {
- const fromIndex = pinnedPropertyKeys.indexOf(activeKey)
- const toIndex = pinnedPropertyKeys.indexOf(overKey)
- if (fromIndex < 0 || toIndex < 0 || fromIndex === toIndex) {
- return
- }
- const reordered = [...pinnedPropertyKeys]
- const [moved] = reordered.splice(fromIndex, 1)
- reordered.splice(toIndex, 0, moved)
- onChange(reordered)
- }
-
return (
<LemonModal
isOpen={isOpen}
@@ -83,68 +48,12 @@ export function AccountPropertyConfigurator({
</>
}
>
- <div className="flex flex-col gap-2 min-w-80">
- <p className="text-sm text-secondary mb-0">
- Choose up to {MAX_PINNED_ACCOUNT_PROPERTIES} properties. Drag selected properties to reorder them.
- </p>
- {selectedOptions.length > 0 ? (
- <DndContext
- onDragEnd={({ active, over }) => {
- if (over) {
- movePinnedProperty(String(active.id), String(over.id))
- }
- }}
- modifiers={[restrictToVerticalAxis, restrictToParentElement]}
- >
- <SortableContext items={pinnedPropertyKeys} strategy={verticalListSortingStrategy}>
- <div
- className="flex max-h-80 flex-col gap-1 overflow-y-auto"
- data-attr="account-pinned-properties-list"
- >
- {selectedOptions.map((option) => (
- <AccountPropertyConfiguratorItem
- key={option.key}
- option={option}
- disabled={saving}
- onRemove={() =>
- onChange(pinnedPropertyKeys.filter((key) => key !== option.key))
- }
- />
- ))}
- </div>
- </SortableContext>
- </DndContext>
- ) : (
- <span className="text-sm text-muted">No properties pinned.</span>
- )}
- <LemonInputSelect
- mode="single"
- limit={1}
- value={[]}
- onChange={addPinnedProperty}
- options={availableOptions.map((option) => ({
- key: option.key,
- label: option.label,
- labelComponent: (
- <span className="flex w-full items-center justify-between gap-2">
- <span className="truncate">{option.label}</span>
- <span className="text-xs text-secondary">
- {option.kind === 'custom' ? 'Custom property' : 'Relationship'}
- </span>
- </span>
- ),
- }))}
- placeholder="Add a property"
- title="Available properties"
- fullWidth
- disabledReason={
- saving
- ? 'Saving'
- : pinLimitReached
- ? `You can pin up to ${MAX_PINNED_ACCOUNT_PROPERTIES} properties`
- : undefined
- }
- data-attr="account-pinned-property-selector"
+ <div className="min-w-80">
+ <AccountPropertySelection
+ options={options}
+ selectedKeys={pinnedPropertyKeys}
+ onChange={onChange}
+ saving={saving}
/>
</div>
</LemonModal>
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfiguratorItem.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfiguratorItem.tsx
index 761b1a83a8dc..22b92ddc0c5d 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfiguratorItem.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyConfiguratorItem.tsx
@@ -48,7 +48,11 @@ export function AccountPropertyConfiguratorItem({
</button>
<span className="min-w-0 flex-1 truncate text-sm font-medium">{option.label}</span>
<span className="shrink-0 text-xs text-secondary">
- {option.kind === 'custom' ? 'Custom property' : 'Relationship'}
+ {option.kind === 'custom'
+ ? 'Custom property'
+ : option.kind === 'account'
+ ? 'Account property'
+ : 'Relationship'}
</span>
<LemonButton
size="xsmall"
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyField.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyField.tsx
index 5fa4a5939f44..7742909e672c 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyField.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertyField.tsx
@@ -51,13 +51,8 @@ export function AccountPropertyField({
// Keep the data-attr stable for existing selectors and autocapture.
return (
<div className="flex flex-col gap-1 min-w-0" data-attr="account-property-row">
- <div className="flex items-center gap-1 min-w-0 min-h-7">
- <span className="text-xs text-secondary truncate">{property.definition.name}</span>
- {provenance ? (
- <Tooltip title={provenance.title}>
- <span className="flex items-center text-secondary text-xs">{provenance.icon}</span>
- </Tooltip>
- ) : null}
+ <div className="flex items-center gap-2 min-w-0 min-h-7">
+ <span className="min-w-0 text-xs text-secondary truncate">{property.definition.name}</span>
{editable && !editing ? (
<LemonButton
size="xsmall"
@@ -65,10 +60,15 @@ export function AccountPropertyField({
tooltip="Edit value"
aria-label={`Edit ${property.definition.name}`}
onClick={onEdit}
- className="ml-auto"
+ className="shrink-0"
data-attr="account-property-edit"
/>
) : null}
+ {provenance ? (
+ <Tooltip title={provenance.title}>
+ <span className="flex shrink-0 items-center text-secondary text-xs">{provenance.icon}</span>
+ </Tooltip>
+ ) : null}
</div>
{editing && editable ? (
<div className="flex flex-col gap-1.5">
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertySelection.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertySelection.tsx
new file mode 100644
index 000000000000..8da7fe52be2e
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/AccountPropertySelection.tsx
@@ -0,0 +1,124 @@
+import { DndContext } from '@dnd-kit/core'
+import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers'
+import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'
+
+import { LemonInputSelect } from '@posthog/lemon-ui'
+
+import { AccountPropertyConfiguratorItem } from './AccountPropertyConfiguratorItem'
+import { AccountPropertyOption, MAX_PINNED_ACCOUNT_PROPERTIES } from './accountPropertyTypes'
+
+export interface AccountPropertySelectionProps {
+ options: AccountPropertyOption[]
+ selectedKeys: string[]
+ saving?: boolean
+ onChange: (keys: string[]) => void
+ emptyLabel?: string
+ limitDisabledReason?: string
+}
+
+export function AccountPropertySelection({
+ options,
+ selectedKeys,
+ saving = false,
+ onChange,
+ emptyLabel = 'No properties pinned.',
+ limitDisabledReason,
+}: AccountPropertySelectionProps): JSX.Element {
+ const optionsByKey = new Map(options.map((option) => [option.key, option]))
+ const selectedOptions = selectedKeys.map(
+ (key): AccountPropertyOption =>
+ optionsByKey.get(key) ?? {
+ key,
+ label: key,
+ kind: key.startsWith('account:')
+ ? 'account'
+ : key.startsWith('relationship:')
+ ? 'relationship'
+ : 'custom',
+ }
+ )
+ const availableOptions = options.filter((option) => !selectedKeys.includes(option.key))
+ const limitReached = selectedKeys.length >= MAX_PINNED_ACCOUNT_PROPERTIES
+ return (
+ <div className="flex flex-col gap-2 min-w-0">
+ <p className="text-sm text-secondary mb-0">
+ Choose up to {MAX_PINNED_ACCOUNT_PROPERTIES} properties. Drag selected properties to reorder them.
+ </p>
+ {selectedOptions.length > 0 ? (
+ <DndContext
+ modifiers={[restrictToVerticalAxis, restrictToParentElement]}
+ onDragEnd={({ active, over }) => {
+ if (saving || !over) {
+ return
+ }
+ const from = selectedKeys.indexOf(String(active.id))
+ const to = selectedKeys.indexOf(String(over.id))
+ if (from < 0 || to < 0 || from === to) {
+ return
+ }
+ const reordered = [...selectedKeys]
+ const [moved] = reordered.splice(from, 1)
+ reordered.splice(to, 0, moved)
+ onChange(reordered)
+ }}
+ >
+ <SortableContext items={selectedKeys} strategy={verticalListSortingStrategy}>
+ <div
+ className="flex max-h-80 flex-col gap-1 overflow-y-auto"
+ data-attr="account-pinned-properties-list"
+ >
+ {selectedOptions.map((option) => (
+ <AccountPropertyConfiguratorItem
+ key={option.key}
+ option={option}
+ disabled={saving}
+ onRemove={() => onChange(selectedKeys.filter((key) => key !== option.key))}
+ />
+ ))}
+ </div>
+ </SortableContext>
+ </DndContext>
+ ) : (
+ <span className="text-sm text-muted">{emptyLabel}</span>
+ )}
+ <LemonInputSelect
+ mode="single"
+ limit={1}
+ value={[]}
+ onChange={(keys) => {
+ const key = keys[0]
+ if (key && !saving && !limitReached && !selectedKeys.includes(key)) {
+ onChange([...selectedKeys, key])
+ }
+ }}
+ options={availableOptions.map((option) => ({
+ key: option.key,
+ label: option.label,
+ labelComponent: (
+ <span className="flex w-full items-center justify-between gap-2">
+ <span className="truncate">{option.label}</span>
+ <span className="text-xs text-secondary">
+ {option.kind === 'custom'
+ ? 'Custom property'
+ : option.kind === 'account'
+ ? 'Account property'
+ : 'Relationship'}
+ </span>
+ </span>
+ ),
+ }))}
+ placeholder="Add a property"
+ title="Available properties"
+ fullWidth
+ disabledReason={
+ saving
+ ? 'Saving'
+ : limitReached
+ ? (limitDisabledReason ?? `You can pin up to ${MAX_PINNED_ACCOUNT_PROPERTIES} properties`)
+ : undefined
+ }
+ data-attr="account-pinned-property-selector"
+ />
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/accountPropertyTypes.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/accountPropertyTypes.ts
index fa4ac0648967..730c2083f2ca 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/accountPropertyTypes.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/components/accountPropertyTypes.ts
@@ -37,7 +37,7 @@ export type AccountSidebarProperty = AccountCustomProperty | AccountRelationship
export interface AccountPropertyOption {
key: string
label: string
- kind: AccountSidebarProperty['kind']
+ kind: AccountSidebarProperty['kind'] | 'account'
}
export function isCustomPropertyEditable(provenance: AccountCustomPropertyProvenance): boolean {
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
index ed03c2c97740..81d369785a91 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
@@ -1,3 +1,4 @@
+import { waitFor } from '@testing-library/react'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -18,6 +19,8 @@ import {
} from 'products/customer_analytics/frontend/generated/api'
import type { AccountApi, AccountPresenceViewerApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import { accountPropertyDataLogic } from './accountPropertyDataLogic'
+import { accountPropertyUpdatesLogic } from './accountPropertyUpdatesLogic'
import { scene } from './CustomerAnalyticsAccountScene'
import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
import {
@@ -116,6 +119,43 @@ describe('customerAnalyticsAccountSceneLogic', () => {
expect(logic.values.breadcrumbs.at(-1)?.name).toBe(account.name)
})
+ it.each([false, true])(
+ 'keeps widget saves and editor drafts when a stale read finishes (external route: %s)',
+ async (externalRoute) => {
+ mockAccountsRetrieve.mockResolvedValue(account)
+ mockAccountsByExternalIdRetrieve.mockResolvedValue(account)
+ if (externalRoute) {
+ router.actions.push(urls.customerAnalyticsAccountByExternalId(account.external_id!))
+ mountExternalIdLogic(account.external_id!)
+ } else {
+ mountLogic()
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.openAccountEditor()
+ logic.actions.setAccountFormValue('website_domain', 'draft.example.com')
+ const pending = createDeferred<AccountApi>()
+ const retrieve = externalRoute ? mockAccountsByExternalIdRetrieve : mockAccountsRetrieve
+ retrieve.mockClear().mockReturnValueOnce(pending.promise)
+ logic.actions.loadAccount()
+ try {
+ await waitFor(() => expect(retrieve).toHaveBeenCalledTimes(1))
+ accountPropertyUpdatesLogic.actions.accountUpdated(PROJECT_ID, {
+ ...account,
+ properties: { website_domain: 'saved.example.com', billing_id: 'saved-billing' },
+ })
+ } finally {
+ pending.resolve(account)
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.account?.properties).toEqual({
+ website_domain: 'saved.example.com',
+ billing_id: 'saved-billing',
+ })
+ expect(logic.values.accountForm.website_domain).toBe('draft.example.com')
+ expect(logic.values.accountEditorOpen).toBe(true)
+ }
+ )
+
it('loads a UUID account while the account scene flag is disabled', async () => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
@@ -277,12 +317,18 @@ describe('customerAnalyticsAccountSceneLogic', () => {
})
describe('account editor', () => {
+ let shared: ReturnType<typeof accountPropertyDataLogic.build>
+
beforeEach(async () => {
+ shared = accountPropertyDataLogic({ projectId: PROJECT_ID, accountId: ACCOUNT_ID })
+ shared.mount()
mockAccountsRetrieve.mockResolvedValue(account)
mountLogic()
await expectLogic(logic).toFinishAllListeners()
})
+ afterEach(() => shared.unmount())
+
it('saves only edited fields without replacing concurrent or unrelated properties', async () => {
const currentAccount = {
...account,
@@ -334,6 +380,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {
email_domains: ['example.com'],
},
})
+ expect(shared.values.account).toEqual(updatedAccount)
expect(logic.values.accountEditorOpen).toBe(false)
expect(logic.values.breadcrumbs.at(-1)?.name).toBe('Renamed account')
})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
index 810a77a2aa7a..b2a439b94370 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
@@ -46,24 +46,14 @@ import {
accountsPresenceCreate,
accountsRetrieve,
} from 'products/customer_analytics/frontend/generated/api'
-import type {
- AccountApi,
- AccountPresenceViewerApi,
- PatchedAccountApiProperties,
-} from 'products/customer_analytics/frontend/generated/api.schemas'
+import type { AccountApi, AccountPresenceViewerApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import { ACCOUNT_ID_FIELDS, updateAccountNativeProperties, AccountNativePropertyPatch } from './accountNativeProperties'
+import { accountPropertyUpdatesLogic } from './accountPropertyUpdatesLogic'
import { EXTERNAL_ACCOUNT_ROUTE_PATTERN, parseExternalAccountPath } from './customerAnalyticsAccountSceneUtils'
const ACCOUNT_PRESENCE_POLL_INTERVAL_MS = 30_000
-export const ACCOUNT_ID_FIELDS = [
- { key: 'website_domain', label: 'Website domain', placeholder: 'example.com' },
- { key: 'billing_id', label: 'Billing ID', placeholder: 'e.g. cus_acme_123' },
- { key: 'slack_channel_id', label: 'Slack channel ID', placeholder: 'e.g. C0123456789' },
- { key: 'sfdc_id', label: 'Salesforce ID', placeholder: 'e.g. 0011t00000AbCdEfGhI' },
- { key: 'stripe_customer_id', label: 'Stripe ID', placeholder: 'e.g. cus_acme_123' },
-] as const
-
type AccountIdFieldKey = (typeof ACCOUNT_ID_FIELDS)[number]['key']
export type AccountEditFormValues = Record<AccountIdFieldKey, string> & {
@@ -291,6 +281,7 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
['user'],
],
actions: [featureFlagLogic, ['setFeatureFlags']],
+ logic: [accountPropertyUpdatesLogic],
})),
actions({
loadAccount: true,
@@ -323,13 +314,11 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
if (!props.projectId || !values.account) {
throw new Error('Could not determine the current project or account.')
}
- const projectId = String(props.projectId)
const openedValues = values.accountEditorOpenedValues
const changedPropertyKeys = ACCOUNT_ID_FIELDS.map(({ key }) => key).filter(
(key) => formValues[key] !== openedValues[key]
)
const name = formValues.name.trim()
- const currentAccount = await accountsRetrieve(projectId, values.account.id)
// Sending only edited fields keeps concurrent edits to the other fields.
const listCleaners = { email_domains: cleanDomains, known_emails: cleanEmails }
const cleanedLists = {
@@ -340,19 +329,16 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
(key) => !objectsEqual(cleanedLists[key], listCleaners[key](openedValues[key]))
)
const changedProperties = {
- ...Object.fromEntries(
- changedPropertyKeys
- .filter(
- (key) => key !== 'stripe_customer_id' || currentAccount.properties?.stripe_customer_id
- )
- .map((key) => [key, formValues[key].trim() || null])
- ),
+ ...Object.fromEntries(changedPropertyKeys.map((key) => [key, formValues[key].trim() || null])),
...Object.fromEntries(changedListKeys.map((key) => [key, cleanedLists[key]])),
}
- const updatedAccount = await accountsPartialUpdate(projectId, values.account.id, {
- ...(name !== openedValues.name ? { name } : {}),
- properties: { ...currentAccount.properties, ...changedProperties } as PatchedAccountApiProperties,
- })
+ const updatedAccount = await updateAccountNativeProperties(
+ props.projectId,
+ values.account.id,
+ changedProperties as AccountNativePropertyPatch,
+ name !== openedValues.name ? name : undefined
+ )
+ accountPropertyUpdatesLogic.actions.accountUpdated(props.projectId, updatedAccount)
actions.loadAccountSuccess(updatedAccount)
posthog.capture(AccountsEvents.AccountEdited, {
name_changed: name !== openedValues.name,
@@ -361,11 +347,17 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
},
},
})),
- reducers({
+ reducers(({ props }) => ({
account: [
null as AccountApi | null,
{
loadAccountSuccess: (_, { account }) => account,
+ [accountPropertyUpdatesLogic.actionTypes.accountUpdated]: (state, { projectId, account }) =>
+ projectId === props.projectId &&
+ (account.id === (state?.id ?? props.accountId) ||
+ (!state && !!props.externalId && account.external_id === props.externalId))
+ ? account
+ : state,
updateTags: (state, { tags }) => (state ? { ...state, tags } : state),
updateTagsDone: (state, { account }) => account ?? state,
},
@@ -421,7 +413,7 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
{ resetAccountForm: (_, { values }) => values ?? EMPTY_ACCOUNT_EDIT_FORM },
],
eventStreamModalOpen: [false, { openEventStreamModal: () => true, closeEventStreamModal: () => false }],
- }),
+ })),
selectors({
activeTab: [
(s) => [s.requestedTab, s.featureFlags],
@@ -489,7 +481,13 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
actions.loadAccount()
}
},
+ [accountPropertyUpdatesLogic.actionTypes.accountUpdated]: ({ projectId, account }) => {
+ if (projectId === props.projectId && account.id === values.account?.id) {
+ cache.accountRevision = (cache.accountRevision ?? 0) + 1
+ }
+ },
loadAccount: async (_, breakpoint) => {
+ const revision = cache.accountRevision ?? 0
try {
const projectId = props.projectId
const identifier = props.externalId ?? props.accountId
@@ -505,13 +503,19 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
? await accountsByExternalIdRetrieve(String(projectId), { external_id: identifier })
: await accountsRetrieve(String(projectId), identifier)
await breakpoint()
- actions.loadAccountSuccess(account)
+ actions.loadAccountSuccess(
+ revision === (cache.accountRevision ?? 0) ? account : (values.account ?? account)
+ )
} catch (error) {
if (error instanceof Error && isBreakpoint(error)) {
throw error
}
await breakpoint()
- actions.loadAccountFailure(error)
+ if (revision !== (cache.accountRevision ?? 0) && values.account) {
+ actions.loadAccountSuccess(values.account)
+ } else {
+ actions.loadAccountFailure(error)
+ }
}
},
loadAccountSuccess: ({ account }) => {
@@ -564,6 +568,11 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
}
}
},
+ updateTagsDone: ({ account }) => {
+ if (account && props.projectId) {
+ accountPropertyUpdatesLogic.actions.accountUpdated(props.projectId, account)
+ }
+ },
setActiveTab: ({ tab }) => {
posthog.capture(AccountsEvents.TabViewed, { tab })
},