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): edit account custom properties (#91884)

Arthur Moreira de Deusa3bc97fb7cf6
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 923a0ec053f0..f3ac0b331e08 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -42,7 +42,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_TABLE_DATA_NODE_KEY, acc
| Logic | Owns |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / native-field / relationship / custom-property filters, sort, inline role assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |
+| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / native-field / relationship / custom-property filters, sort, inline role and editable custom-property assignment, typed Postgres list and metrics queries, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references. `connect`s column-config, overview-tiles, and expansion logics. |
| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |
| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), Postgres-backed column-picker groups, the per-team saved column config (`columnConfigurations` API), and custom-property definitions. It seeds `propertyDefinitionsModel` so the filter UI resolves per-type operator sets. Warehouse-backed columns and SQL expressions are not offered. |
| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |
@@ -105,6 +105,8 @@ Operator sets honor each field's type because `accountsColumnConfigLogic` seeds
`accountsTableQuery.ts` translates all three filter kinds into typed query filters. The backend filters relationships through active assignments, native model or JSON fields directly, and custom properties through storage chosen from the definition type. Negative operators include accounts where the value is unset. Invalid native combinations and deleted or incompatible custom properties are omitted rather than changing query engines.
Custom property value suggestions load from `GET /api/projects/:team_id/custom_property_definitions/values/?key=<definition-id>&value=<search>`. Native account fields do not fetch suggestions.
+A custom-property column is editable only when its definition has no data warehouse source or workflow references and is not canonical. `AccountsTable` passes this condition as `isEditable` to `CustomPropertyCell`. Editable cells show a pencil that replaces the rendered value with a compact, type-aware editor. Date and datetime properties use the Lemon Calendar picker and save from its Apply action. Link properties reject values outside HTTP and HTTPS before saving. `accountsLogic.updateAccountCustomProperty` writes through the generated custom-property-values endpoint, blocks duplicate writes, masks stale query data with a per-account override, refreshes the list and metrics, and clears the override after the next list response or a failed write. The event records only the display type, never the property name or value.
+
**Overview tile math** (`accountsOverviewTilesLogic` / `AccountsOverviewTilesEditor`). A tile's metric is a discriminated union: `count`, the column aggregations `sum`/`avg`/`min`/`max`/`median`, and `count_threshold`. `tileQueryMetric` translates these into the typed `AccountsTableMetric` union. Column aggregations carry an optional `scale` multiplier, and threshold tiles translate into typed custom-property filters when clicked.
**Tile display** (title / subtitle / value format). A tile also carries two optional presentation fields, independent of the metric: `caption` (custom subtitle) and `format` (`TileValueFormat` = `unit`/`currency`/`percentage`, a subset of `OverviewGrid`'s `WebAnalyticsItemKind` so `format ?? 'unit'` maps 1:1 to the render `kind`). `tileCaption(tile)` resolves the subtitle: the trimmed custom `caption` when set, else `autoCaption(tile)` (the derived `agg of col × n` / `col op val` text; `count` has no derived caption, so a custom one is the only subtitle it can show). The editor edits `caption` (empty → `undefined`) and `format` (`unit` → `undefined`); both flow through the row's `emit(patch)` merge so a metric edit never drops them. Render formatting lives in `OverviewGrid.formatItem`: `currency` uses the team `baseCurrency`, `percentage` treats the value as already in percent units (`85` → "85%", combine with `scale × 100` for a 0-1 fraction). Both fields ride along in `properties.tiles` (no backend/schema/migration) and default cleanly for older saved/legacy tiles.
@@ -318,6 +320,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
| `customer analytics account role assigned` | `accountsLogic` `updateAccountRole` | `role` (`csm` \| `account_executive` \| `account_owner` for the seeded definitions, else the definition name), `is_assigned`, `assigned_user_id`, `source` (`list_row` from `accountsLogic.updateAccountRole` \| `relationships_tab` from `accountRelationshipsLogic` assign/end) |
| `customer analytics accounts relationship deleted` | `accountRelationshipsLogic` `deleteRelationship` listener (after the DELETE succeeds) | _(none - count only; relationship and account identifiers stay out)_ |
| `customer analytics account tags updated` | `accountsLogic` `updateAccountTags` listener (after the debounced PATCH succeeds; dispatched by the tags cell editor) | `tag_count` (tag names kept out — they can name customers) |
+| `customer analytics account custom property updated` | `accountsLogic` `updateAccountCustomProperty` listener (after the custom-property-values write succeeds) | `display_type` (property name and value stay out because they can contain customer data) |
| `customer analytics account link clicked` | `AccountNotebooksExpansion.tsx` useful-link `onClick` (incl. the "Copy link to account" row, `link_key: 'copy-account-link'`) | `link_key`, `has_destination` |
| `customer analytics account note clicked` | `AccountNotebooksExpansion.tsx` note `<Link>` `onClick` | `notebook_short_id` |
| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts b/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
index 1b630a9545b0..5debc85315f7 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.test.ts
@@ -1,6 +1,14 @@
-import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import type {
+ CustomPropertyDefinitionApi,
+ CustomPropertySourceApi,
+} from 'products/customer_analytics/frontend/generated/api.schemas'
-import { buildHistoryDisplay, getCanonicalPropertyTab } from './AccountsTable'
+import {
+ buildHistoryDisplay,
+ getCanonicalPropertyTab,
+ isCustomPropertyEditable,
+ isCustomPropertyValueValid,
+} from './AccountsTable'
const DAY = 24 * 60 * 60
const NOW_MS = 1_800_000_000_000
@@ -45,6 +53,69 @@ describe('buildHistoryDisplay', () => {
})
})
+const createCustomPropertySource = (): CustomPropertySourceApi => ({
+ id: 'source-1',
+ definition: 'custom-property-1',
+ key_column: 'external_id',
+ consecutive_failures: 0,
+ last_synced_at: null,
+ last_sync_error: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ sync_frequency_interval_seconds: null,
+ next_sync_at: null,
+ latest_run: null,
+ external_data_source: null,
+ table_name: null,
+ saved_query_name: null,
+})
+
+const createCustomPropertyDefinition = (
+ overrides: Partial<CustomPropertyDefinitionApi> = {}
+): CustomPropertyDefinitionApi => ({
+ id: 'custom-property-1',
+ name: 'Health score',
+ display_type: 'number',
+ is_canonical: false,
+ source: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ references: [],
+ ...overrides,
+})
+
+describe('isCustomPropertyEditable', () => {
+ it.each([
+ ['manual', createCustomPropertyDefinition(), true],
+ ['canonical', createCustomPropertyDefinition({ is_canonical: true }), false],
+ ['data warehouse managed', createCustomPropertyDefinition({ source: createCustomPropertySource() }), false],
+ [
+ 'workflow managed',
+ createCustomPropertyDefinition({
+ references: [{ id: 'workflow-1', name: 'Update value', status: 'active', type: 'workflow' }],
+ }),
+ false,
+ ],
+ ])('marks %s definitions editable only when users can safely set their value', (_, value, expected) => {
+ expect(isCustomPropertyEditable(value)).toBe(expected)
+ })
+})
+
+describe('isCustomPropertyValueValid', () => {
+ it.each([
+ ['accepts HTTP URLs', 'http://example.com', true],
+ ['accepts HTTPS URLs', 'https://example.com', true],
+ ['rejects a URL without a scheme', 'example.com', false],
+ ['rejects unsupported URL schemes', 'ftp://example.com', false],
+ ])('%s', (_, value, expected) => {
+ expect(isCustomPropertyValueValid(value, createCustomPropertyDefinition({ display_type: 'link' }))).toBe(
+ expected
+ )
+ })
+})
+
describe('getCanonicalPropertyTab', () => {
const definition = (name: string, isCanonical: boolean): CustomPropertyDefinitionApi =>
({ name, is_canonical: isCanonical }) as CustomPropertyDefinitionApi
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index 22bc00911143..b748ff919032 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -1,8 +1,17 @@
import { useActions, useValues } from 'kea'
-import { useMemo } from 'react'
-
-import { IconCheck, IconX } from '@posthog/icons'
-import { LemonButton, LemonColorGlyph, LemonSkeleton, LemonTable, ProfilePicture } from '@posthog/lemon-ui'
+import { useMemo, useState } from 'react'
+
+import { IconCheck, IconPencil, IconX } from '@posthog/icons'
+import {
+ LemonButton,
+ LemonColorGlyph,
+ LemonInput,
+ LemonSelect,
+ LemonSkeleton,
+ LemonSwitch,
+ LemonTable,
+ ProfilePicture,
+} from '@posthog/lemon-ui'
import type { DataColorToken } from 'lib/colors'
import { MemberSelect } from 'lib/components/MemberSelect'
@@ -11,6 +20,7 @@ import { Sparkline } from 'lib/components/Sparkline'
import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
import { SortingIndicator } from 'lib/lemon-ui/LemonTable/sorting'
import { Link } from 'lib/lemon-ui/Link'
@@ -36,7 +46,7 @@ import { formatCustomPropertyValue } from '../../scenes/CustomerAnalyticsConfigu
import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'
import { AccountColumnDisplayConfig, LEGACY_ROLE_COLUMNS, accountsColumnConfigLogic } from './accountsColumnConfigLogic'
import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'
-import { accountsLogic, savingRoleKey } from './accountsLogic'
+import { accountsLogic, customPropertySavingKey, savingRoleKey } from './accountsLogic'
import { AccountsTableNameCell } from './AccountsTableNameCell'
import { accountsTableCell, isAccountsTableRow } from './accountsTableQuery'
@@ -342,24 +352,76 @@ function CanonicalTimestampCell({
)
}
-function CustomPropertyCell({
- record,
- column,
- definition,
- display,
-}: {
- record: unknown
- column: string
+export function isCustomPropertyEditable(definition: CustomPropertyDefinitionApi): boolean {
+ return !definition.is_canonical && !definition.source && definition.references.length === 0
+}
+
+type CustomPropertyDraft = boolean | string
+
+function customPropertyDraftValue(value: unknown, definition: CustomPropertyDefinitionApi): CustomPropertyDraft {
+ if (definition.display_type === 'boolean') {
+ return value === true || value === 'true' || value === '1'
+ }
+ if (value === null || value === undefined) {
+ return ''
+ }
+ if (definition.display_type === 'percent') {
+ const percentageValue = Number(value) * 100
+ return Number.isFinite(percentageValue) ? String(percentageValue) : ''
+ }
+ return String(value)
+}
+
+function customPropertyValueToSave(
+ draft: CustomPropertyDraft,
definition: CustomPropertyDefinitionApi
- display?: AccountColumnDisplayConfig
-}): JSX.Element {
- const getCell = useGetCell()
- const raw = getCell(record, column)
- if (display) {
- return <CustomPropertyHistoryCell raw={raw} definition={definition} display={display} />
+): string | number | boolean {
+ if (definition.display_type === 'boolean') {
+ return draft === true
+ }
+ if (definition.display_type === 'number' || definition.display_type === 'currency') {
+ return Number(draft)
+ }
+ if (definition.display_type === 'percent') {
+ return Number(draft) / 100
}
- const value = raw === null || raw === undefined ? '' : String(raw)
+ return draft
+}
+
+function isHttpUrl(value: string): boolean {
+ try {
+ const url = new URL(value)
+ return url.protocol === 'http:' || url.protocol === 'https:'
+ } catch {
+ return false
+ }
+}
+export function isCustomPropertyValueValid(
+ draft: CustomPropertyDraft,
+ definition: CustomPropertyDefinitionApi
+): boolean {
+ if (definition.display_type === 'boolean') {
+ return true
+ }
+ if (
+ definition.display_type === 'number' ||
+ definition.display_type === 'currency' ||
+ definition.display_type === 'percent'
+ ) {
+ return draft !== '' && Number.isFinite(Number(draft))
+ }
+ if (definition.display_type === 'link') {
+ return typeof draft === 'string' && isHttpUrl(draft)
+ }
+ return definition.display_type !== 'date' && definition.display_type !== 'datetime' ? true : draft !== ''
+}
+
+function renderCustomPropertyValue(
+ record: unknown,
+ value: string,
+ definition: CustomPropertyDefinitionApi
+): JSX.Element {
if (!value) {
return <span className="text-muted">—</span>
}
@@ -392,6 +454,207 @@ function CustomPropertyCell({
return <span>{formatCustomPropertyValue(value, definition)}</span>
}
+function renderCustomPropertyEditor(
+ draft: CustomPropertyDraft,
+ definition: CustomPropertyDefinitionApi,
+ setDraft: (draft: CustomPropertyDraft) => void,
+ saveValue: (nextValue?: CustomPropertyDraft) => void,
+ cancelEdit: () => void
+): JSX.Element {
+ if (definition.display_type === 'boolean') {
+ return (
+ <LemonSwitch
+ checked={draft === true}
+ onChange={setDraft}
+ size="small"
+ aria-label="Custom property value"
+ data-attr="accounts-custom-property-value-input"
+ />
+ )
+ }
+ if (definition.display_type === 'select') {
+ return (
+ <LemonSelect
+ value={typeof draft === 'string' ? draft : ''}
+ onChange={(value) => setDraft(value ?? '')}
+ options={(definition.options ?? []).map((option) => ({
+ value: option.label,
+ label: (
+ <span className="inline-flex items-center gap-1.5">
+ <LemonColorGlyph colorToken={option.color as DataColorToken} size="small" />
+ {option.label}
+ </span>
+ ),
+ }))}
+ size="small"
+ className="w-full"
+ data-attr="accounts-custom-property-value-input"
+ />
+ )
+ }
+ if (definition.display_type === 'date' || definition.display_type === 'datetime') {
+ return (
+ <LemonCalendarSelectInput
+ value={typeof draft === 'string' && draft ? dayjs(draft) : null}
+ onChange={(value) =>
+ value &&
+ saveValue(definition.display_type === 'datetime' ? value.toISOString() : value.format('YYYY-MM-DD'))
+ }
+ granularity={definition.display_type === 'datetime' ? 'minute' : 'day'}
+ format={definition.display_type === 'datetime' ? 'MMM D, YYYY HH:mm' : 'MMM D, YYYY'}
+ use24HourFormat
+ onClickOutside={cancelEdit}
+ onClose={cancelEdit}
+ buttonProps={{
+ size: 'small',
+ className: 'w-40',
+ 'data-attr': 'accounts-custom-property-value-input',
+ }}
+ />
+ )
+ }
+ const isNumeric =
+ definition.display_type === 'number' ||
+ definition.display_type === 'currency' ||
+ definition.display_type === 'percent'
+ if (isNumeric) {
+ const numericValue = typeof draft === 'string' && draft ? Number(draft) : undefined
+ return (
+ <LemonInput
+ type="number"
+ value={numericValue}
+ onChange={(value) => setDraft(value === undefined ? '' : String(value))}
+ onPressEnter={() => saveValue()}
+ size="small"
+ step="any"
+ suffix={definition.display_type === 'percent' ? <span>%</span> : undefined}
+ data-attr="accounts-custom-property-value-input"
+ />
+ )
+ }
+ return (
+ <LemonInput
+ type={definition.display_type === 'link' ? 'url' : 'text'}
+ value={typeof draft === 'string' ? draft : ''}
+ onChange={setDraft}
+ onPressEnter={() => saveValue()}
+ size="small"
+ status={
+ definition.display_type === 'link' && typeof draft === 'string' && draft && !isHttpUrl(draft)
+ ? 'danger'
+ : 'default'
+ }
+ className="w-40"
+ data-attr="accounts-custom-property-value-input"
+ />
+ )
+}
+
+function CustomPropertyCell({
+ record,
+ column,
+ definition,
+ display,
+ isEditable,
+}: {
+ record: unknown
+ column: string
+ definition: CustomPropertyDefinitionApi
+ display?: AccountColumnDisplayConfig
+ isEditable: boolean
+}): JSX.Element {
+ const { customPropertyOverrides, isCustomPropertySaving } = useValues(accountsLogic)
+ const { updateAccountCustomProperty } = useActions(accountsLogic)
+ const getCell = useGetCell()
+ const raw = getCell(record, column)
+ const accountId = getNameCell(record)?.id
+ const override = accountId ? customPropertyOverrides[customPropertySavingKey(accountId, definition.id)] : undefined
+ const currentValue = display
+ ? (buildHistoryDisplay(parseHistoryPoints(raw), display.window_days, dayjs().valueOf()).latest?.[1] ?? null)
+ : raw
+ const value = override ?? currentValue
+ const [isEditing, setIsEditing] = useState(false)
+ const [draft, setDraft] = useState<CustomPropertyDraft>(() => customPropertyDraftValue(value, definition))
+ const saving = accountId ? isCustomPropertySaving(accountId, definition.id) : false
+
+ const openEditor = (): void => {
+ setDraft(customPropertyDraftValue(value, definition))
+ setIsEditing(true)
+ }
+ const saveValue = (nextValue: CustomPropertyDraft = draft): void => {
+ if (!accountId || !isCustomPropertyValueValid(nextValue, definition)) {
+ return
+ }
+ updateAccountCustomProperty(accountId, definition, customPropertyValueToSave(nextValue, definition))
+ setIsEditing(false)
+ }
+ const isDatePicker = definition.display_type === 'date' || definition.display_type === 'datetime'
+
+ if (isEditing && accountId) {
+ return (
+ <div
+ className={`inline-flex w-fit items-center ${definition.display_type === 'boolean' ? 'gap-2' : 'gap-1'}`}
+ >
+ <div className={definition.display_type === 'boolean' ? undefined : 'w-40'}>
+ {renderCustomPropertyEditor(draft, definition, setDraft, saveValue, () => setIsEditing(false))}
+ </div>
+ {!isDatePicker && (
+ <>
+ <LemonButton
+ type="primary"
+ size="xsmall"
+ icon={<IconCheck />}
+ tooltip="Save"
+ onClick={() => saveValue()}
+ disabledReason={
+ isCustomPropertyValueValid(draft, definition)
+ ? undefined
+ : definition.display_type === 'link'
+ ? 'Enter a valid HTTP or HTTPS URL'
+ : 'Enter a value'
+ }
+ data-attr="accounts-custom-property-value-save"
+ />
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ icon={<IconX />}
+ tooltip="Cancel"
+ onClick={() => setIsEditing(false)}
+ data-attr="accounts-custom-property-value-cancel"
+ />
+ </>
+ )}
+ </div>
+ )
+ }
+
+ const displayValue = value === null || value === undefined ? '' : String(value)
+ const renderedValue =
+ display && override === undefined ? (
+ <CustomPropertyHistoryCell raw={raw} definition={definition} display={display} />
+ ) : (
+ renderCustomPropertyValue(record, displayValue, definition)
+ )
+ return (
+ <div className="flex min-w-0 items-center gap-1">
+ <span className="min-w-0 truncate">{renderedValue}</span>
+ {isEditable && accountId && (
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ icon={<IconPencil />}
+ tooltip="Edit"
+ loading={saving}
+ disabledReason={saving ? 'Saving…' : undefined}
+ onClick={openEditor}
+ data-attr="accounts-custom-property-value-edit"
+ />
+ )}
+ </div>
+ )
+}
+
function SortableColumnHeader({ column, label }: { column: string; label: string }): JSX.Element {
const { sortOrder } = useValues(accountsLogic)
const { toggleSort } = useActions(accountsLogic)
@@ -465,7 +728,13 @@ function useContextColumns(): Record<string, QueryContextColumn> {
columns[key] = {
renderTitle: () => <SortableColumnHeader column={key} label={definition.name} />,
render: ({ record }) => (
- <CustomPropertyCell record={record} column={key} definition={definition} display={display} />
+ <CustomPropertyCell
+ record={record}
+ column={key}
+ definition={definition}
+ display={display}
+ isEditable={isCustomPropertyEditable(definition)}
+ />
),
}
continue
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index 1ed8ff1f2408..d7d13d529384 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -19,6 +19,7 @@ import { PropertyFilterType, PropertyOperator, type UserBasicType, type UserType
import {
accountRelationshipDefinitionsList,
+ accountsCustomPropertyValuesCreate,
accountsPartialUpdate,
accountsRelationshipsCreate,
accountsRelationshipsEndCreate,
@@ -30,6 +31,7 @@ import type {
AccountRelationshipApi,
AccountRelationshipDefinitionApi,
CustomPropertyDefinitionApi,
+ CustomPropertySourceApi,
} from 'products/customer_analytics/frontend/generated/api.schemas'
import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'
@@ -40,7 +42,7 @@ import {
relationshipAlias,
} from './accountsColumnConfigLogic'
import { DEFAULT_ACCOUNT_TAB, accountsExpansionLogic } from './accountsExpansionLogic'
-import { accountsLogic, savingRoleKey } from './accountsLogic'
+import { accountsLogic, customPropertySavingKey, savingRoleKey } from './accountsLogic'
import { AccountsEvents } from './constants'
const assignedToFilterOf = (query: AccountsTableQuery | null): number[] | undefined =>
@@ -52,6 +54,7 @@ jest.mock('products/customer_analytics/frontend/generated/api', () => ({
...jest.requireActual('products/customer_analytics/frontend/generated/api'),
accountRelationshipDefinitionsList: jest.fn(),
customPropertyDefinitionsList: jest.fn(),
+ accountsCustomPropertyValuesCreate: jest.fn(),
accountsPartialUpdate: jest.fn(),
accountsRelationshipsCreate: jest.fn(),
accountsRelationshipsEndCreate: jest.fn(),
@@ -69,6 +72,9 @@ const mockRelationshipsEnd = accountsRelationshipsEndCreate as jest.MockedFuncti
typeof accountsRelationshipsEndCreate
>
const mockRelationshipsList = accountsRelationshipsList as jest.MockedFunction<typeof accountsRelationshipsList>
+const mockCustomPropertyValuesCreate = accountsCustomPropertyValuesCreate as jest.MockedFunction<
+ typeof accountsCustomPropertyValuesCreate
+>
const mockPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>
const CSM_DEFINITION_ID = '11111111-2222-3333-4444-555555555555'
@@ -121,6 +127,39 @@ const buildUser = (overrides: Partial<UserBasicType> = {}): UserBasicType =>
...overrides,
}) as UserBasicType
+const createCustomPropertySource = (): CustomPropertySourceApi => ({
+ id: 'source-1',
+ definition: 'custom-property-1',
+ key_column: 'external_id',
+ consecutive_failures: 0,
+ last_synced_at: null,
+ last_sync_error: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ sync_frequency_interval_seconds: null,
+ next_sync_at: null,
+ latest_run: null,
+ external_data_source: null,
+ table_name: null,
+ saved_query_name: null,
+})
+
+const buildCustomPropertyDefinition = (
+ overrides: Partial<CustomPropertyDefinitionApi> = {}
+): CustomPropertyDefinitionApi => ({
+ id: 'custom-property-1',
+ name: 'Health score',
+ display_type: 'number',
+ is_canonical: false,
+ source: null,
+ references: [],
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ ...overrides,
+})
+
describe('accountsLogic', () => {
let logic: ReturnType<typeof accountsLogic.build>
@@ -754,6 +793,66 @@ describe('accountsLogic', () => {
})
})
+ describe('updateAccountCustomProperty', () => {
+ it('writes the value and masks stale query data with the saved value', async () => {
+ const definition = buildCustomPropertyDefinition()
+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()
+ mockCustomPropertyValuesCreate.mockResolvedValue({
+ id: 'value-1',
+ account_id: 'acc-1',
+ definition_id: definition.id,
+ value: 42,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by_id: 1,
+ })
+
+ logic.actions.updateAccountCustomProperty('acc-1', definition, 42)
+
+ expect(logic.values.customPropertyOverrides[customPropertySavingKey('acc-1', definition.id)]).toBe(42)
+
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockCustomPropertyValuesCreate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {
+ definition: definition.id,
+ value: 42,
+ })
+ expect(
+ logic.values.customPropertyOverrides[customPropertySavingKey('acc-1', definition.id)]
+ ).toBeUndefined()
+ expect(logic.values.isCustomPropertySaving('acc-1', definition.id)).toBe(false)
+ expect(capture).toHaveBeenCalledWith(AccountsEvents.CustomPropertyUpdated, { display_type: 'number' })
+ })
+
+ it.each([
+ ['canonical', buildCustomPropertyDefinition({ is_canonical: true })],
+ ['data warehouse managed', buildCustomPropertyDefinition({ source: createCustomPropertySource() })],
+ [
+ 'workflow managed',
+ buildCustomPropertyDefinition({
+ references: [{ id: 'workflow-1', name: 'Update health score', status: 'active', type: 'workflow' }],
+ }),
+ ],
+ ])('does not write a %s property', async (_, definition) => {
+ logic.actions.updateAccountCustomProperty('acc-1', definition, 42)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockCustomPropertyValuesCreate).not.toHaveBeenCalled()
+ })
+
+ it('reverts the optimistic override after a failed write', async () => {
+ const definition = buildCustomPropertyDefinition()
+ mockCustomPropertyValuesCreate.mockRejectedValueOnce(new Error('boom'))
+
+ logic.actions.updateAccountCustomProperty('acc-1', definition, 42)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(
+ logic.values.customPropertyOverrides[customPropertySavingKey('acc-1', definition.id)]
+ ).toBeUndefined()
+ expect(logic.values.isCustomPropertySaving('acc-1', definition.id)).toBe(false)
+ })
+ })
+
describe('updateAccountRole', () => {
it('assigns via the relationships API and masks the cell with an override', async () => {
const user = buildUser()
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index cc1a5cf907b0..c37e37797469 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -25,6 +25,7 @@ import {
import type { UserBasicType } from '~/types'
import {
+ accountsCustomPropertyValuesCreate,
accountsPartialUpdate,
accountsRelationshipsCreate,
accountsRelationshipsEndCreate,
@@ -38,7 +39,11 @@ import {
CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS,
} from '../../constants'
import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'
-import type { AccountRelationshipDefinitionApi, CustomPropertyDefinitionApi } from '../../generated/api.schemas'
+import type {
+ AccountRelationshipDefinitionApi,
+ CustomPropertyDefinitionApi,
+ CustomPropertyValueWriteApi,
+} from '../../generated/api.schemas'
import { accountsColumnConfigLogic, isLegacyRoleColumn } from './accountsColumnConfigLogic'
import type { AccountColumnDisplayState } from './accountsColumnConfigLogic'
import {
@@ -108,6 +113,9 @@ export type AccountSortOrder = { column: AccountSortableColumn; direction: Accou
export const savingRoleKey = (accountId: string, column: string): string => `${accountId}:${column}`
+export const customPropertySavingKey = (accountId: string, definitionId: string): string =>
+ `${accountId}:${definitionId}`
+
// Which accounts path the shareable view state gets written back to. It must be the path we are
// already on: the setters that mirror view state into the URL also fire while state is being
// restored (the default-column upgrade once relationship definitions load, the auto-restored saved
@@ -169,11 +177,14 @@ export interface accountsLogicValues {
assignedToFilter: RoleFilterValue
canSortClientSide: boolean
currentUserId: number | null
+ customPropertyOverrides: Record<string, CustomPropertyValueWriteApi['value']>
+ isCustomPropertySaving: (accountId: string, definitionId: string) => boolean
isRoleSaving: (accountId: string, column: string) => boolean
isTagsSaving: (accountId: string) => boolean
listPaginated: boolean
metricsQuery: AccountsTableQuery | null
relationshipOverrides: Record<string, number[]>
+ savingCustomProperties: Record<string, true>
savingRoles: Record<string, true>
savingTags: Record<string, true>
searchInput: string
@@ -260,6 +271,55 @@ export interface accountsLogicActions {
queryId: string
refresh: RefreshType | undefined
} // dataNodeLogic
+ listLoadDataSuccess: (
+ response:
+ | Record<string, any>
+ | null
+ | import('~/queries/schema').ErrorTrackingQueryResponse
+ | import('~/queries/schema').HogQLAutocompleteResponse
+ | import('~/queries/schema').HogQLMetadataResponse
+ | import('~/queries/schema').HogQLQueryResponse<any[]>
+ | import('~/queries/schema').HogQueryResponse
+ | import('~/queries/schema').LogAttributesQueryResponse
+ | import('~/queries/schema').LogValuesQueryResponse
+ | import('~/queries/schema').MetricsQueryResponse
+ | import('~/queries/schema').SessionsQueryResponse
+ | import('~/queries/schema').TraceSpansAggregationQueryResponse
+ | import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse
+ | import('~/queries/schema').TraceSpansQueryResponse
+ | undefined,
+ payload?:
+ | {
+ overrideQuery: DataNode<Record<string, any>> | undefined
+ pollOnly: boolean
+ queryId: string
+ refresh: RefreshType | undefined
+ }
+ | undefined
+ ) => {
+ payload?: {
+ overrideQuery: DataNode<Record<string, any>> | undefined
+ pollOnly: boolean
+ queryId: string
+ refresh: RefreshType | undefined
+ }
+ response:
+ | Record<string, any>
+ | null
+ | import('~/queries/schema').ErrorTrackingQueryResponse
+ | import('~/queries/schema').HogQLAutocompleteResponse
+ | import('~/queries/schema').HogQLMetadataResponse
+ | import('~/queries/schema').HogQLQueryResponse<any[]>
+ | import('~/queries/schema').HogQueryResponse
+ | import('~/queries/schema').LogAttributesQueryResponse
+ | import('~/queries/schema').LogValuesQueryResponse
+ | import('~/queries/schema').MetricsQueryResponse
+ | import('~/queries/schema').SessionsQueryResponse
+ | import('~/queries/schema').TraceSpansAggregationQueryResponse
+ | import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse
+ | import('~/queries/schema').TraceSpansQueryResponse
+ | undefined
+ } // dataNodeLogic
listLoadNextData: () => any // dataNodeLogic
ensureAllMembersLoaded: () => {
value: true
@@ -280,6 +340,23 @@ export interface accountsLogicActions {
addTagToFilter: (tag: string) => {
tag: string
}
+ clearCustomPropertyOverrides: () => {
+ value: true
+ }
+ customPropertyUpdateFinished: (
+ accountId: string,
+ definitionId: string
+ ) => {
+ accountId: string
+ definitionId: string
+ }
+ customPropertyUpdateStarted: (
+ accountId: string,
+ definitionId: string
+ ) => {
+ accountId: string
+ definitionId: string
+ }
openAccount: (
accountId: string,
externalId: string | null,
@@ -326,6 +403,15 @@ export interface accountsLogicActions {
setAssignedToFilter: (value: RoleFilterValue) => {
value: RoleFilterValue
}
+ setCustomPropertyOverride: (
+ accountId: string,
+ definitionId: string,
+ value: CustomPropertyValueWriteApi['value'] | null
+ ) => {
+ accountId: string
+ definitionId: string
+ value: boolean | number | string | null
+ }
setRelationshipOverride: (
accountId: string,
column: string,
@@ -363,6 +449,15 @@ export interface accountsLogicActions {
toggleSort: (column: AccountSortableColumn) => {
column: string
}
+ updateAccountCustomProperty: (
+ accountId: string,
+ definition: CustomPropertyDefinitionApi,
+ value: CustomPropertyValueWriteApi['value']
+ ) => {
+ accountId: string
+ definition: CustomPropertyDefinitionApi
+ value: boolean | number | string
+ }
updateAccountFilters: (filters: AccountFilter[]) => {
filters: AccountFilter[]
}
@@ -389,6 +484,9 @@ export interface accountsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
currentUserId: (user: UserType | null) => number | null
assignedToCurrentUser: (assignedToFilter: RoleFilterValue, currentUserId: number | null) => boolean
+ isCustomPropertySaving: (
+ savingCustomProperties: Record<string, true>
+ ) => (accountId: string, definitionId: string) => boolean
isRoleSaving: (savingRoles: Record<string, true>) => (accountId: string, column: string) => boolean
isTagsSaving: (savingTags: Record<string, true>) => (accountId: string) => boolean
activeFilterCount: (
@@ -511,7 +609,7 @@ export const accountsLogic = kea<accountsLogicType>([
membersLogic,
['ensureAllMembersLoaded'],
dataNodeLogic({ key: ACCOUNTS_TABLE_DATA_NODE_KEY } as DataNodeLogicProps),
- ['loadData as listLoadData', 'loadNextData as listLoadNextData'],
+ ['loadData as listLoadData', 'loadDataSuccess as listLoadDataSuccess', 'loadNextData as listLoadNextData'],
],
})),
actions({
@@ -532,6 +630,19 @@ export const accountsLogic = kea<accountsLogicType>([
// The raw filter setters are also fired by URL sync and cross-filter
// cascades, so capturing analytics here keeps phantom events out.
reportFilterChange: (filterType: AccountFilterType) => ({ filterType }),
+ updateAccountCustomProperty: (
+ accountId: string,
+ definition: CustomPropertyDefinitionApi,
+ value: CustomPropertyValueWriteApi['value']
+ ) => ({ accountId, definition, value }),
+ customPropertyUpdateStarted: (accountId: string, definitionId: string) => ({ accountId, definitionId }),
+ customPropertyUpdateFinished: (accountId: string, definitionId: string) => ({ accountId, definitionId }),
+ clearCustomPropertyOverrides: true,
+ setCustomPropertyOverride: (
+ accountId: string,
+ definitionId: string,
+ value: CustomPropertyValueWriteApi['value'] | null
+ ) => ({ accountId, definitionId, value }),
updateAccountRole: (accountId: string, column: string, user: UserBasicType | null) => ({
accountId,
column,
@@ -623,6 +734,36 @@ export const accountsLogic = kea<accountsLogicType>([
listLoadNextData: () => true,
},
],
+ savingCustomProperties: [
+ {} as Record<string, true>,
+ {
+ customPropertyUpdateStarted: (state, { accountId, definitionId }) => ({
+ ...state,
+ [customPropertySavingKey(accountId, definitionId)]: true,
+ }),
+ customPropertyUpdateFinished: (state, { accountId, definitionId }) => {
+ const next = { ...state }
+ delete next[customPropertySavingKey(accountId, definitionId)]
+ return next
+ },
+ },
+ ],
+ customPropertyOverrides: [
+ {} as Record<string, CustomPropertyValueWriteApi['value']>,
+ {
+ setCustomPropertyOverride: (state, { accountId, definitionId, value }) => {
+ const next = { ...state }
+ const key = customPropertySavingKey(accountId, definitionId)
+ if (value === null) {
+ delete next[key]
+ } else {
+ next[key] = value
+ }
+ return next
+ },
+ clearCustomPropertyOverrides: () => ({}),
+ },
+ ],
savingRoles: [
{} as Record<string, true>,
{
@@ -686,6 +827,12 @@ export const accountsLogic = kea<accountsLogicType>([
(assignedToFilter: RoleFilterValue, currentUserId: number | null): boolean =>
currentUserId !== null && assignedToFilter.length === 1 && assignedToFilter[0] === currentUserId,
],
+ isCustomPropertySaving: [
+ (s) => [s.savingCustomProperties],
+ (savingCustomProperties: Record<string, true>) =>
+ (accountId: string, definitionId: string): boolean =>
+ !!savingCustomProperties[customPropertySavingKey(accountId, definitionId)],
+ ],
isRoleSaving: [
(s) => [s.savingRoles],
(savingRoles: Record<string, true>) =>
@@ -884,6 +1031,19 @@ export const accountsLogic = kea<accountsLogicType>([
],
}),
listeners(({ actions, values, cache, selectors }) => ({
+ listLoadData: ({ queryId }) => {
+ if (cache.awaitingCustomPropertyRefresh) {
+ cache.awaitingCustomPropertyRefresh = false
+ cache.customPropertyRefreshQueryId = queryId
+ }
+ },
+ listLoadDataSuccess: ({ payload }) => {
+ if (payload?.queryId !== cache.customPropertyRefreshQueryId) {
+ return
+ }
+ cache.customPropertyRefreshQueryId = undefined
+ actions.clearCustomPropertyOverrides()
+ },
loadCustomPropertyDefinitionsSuccess: ({ customPropertyDefinitions }) => {
cache.customPropertyDefinitionsLoaded = true
if (!cache.relationshipDefinitionsLoaded) {
@@ -1069,6 +1229,36 @@ export const accountsLogic = kea<accountsLogicType>([
dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
},
+ updateAccountCustomProperty: async ({ accountId, definition, value }) => {
+ if (
+ definition.is_canonical ||
+ definition.source ||
+ definition.references.length > 0 ||
+ values.isCustomPropertySaving(accountId, definition.id)
+ ) {
+ return
+ }
+ const key = customPropertySavingKey(accountId, definition.id)
+ const previous = values.customPropertyOverrides[key] ?? null
+ actions.customPropertyUpdateStarted(accountId, definition.id)
+ actions.setCustomPropertyOverride(accountId, definition.id, value)
+ try {
+ await accountsCustomPropertyValuesCreate(String(values.currentTeamId), accountId, {
+ definition: definition.id,
+ value,
+ })
+ posthog.capture(AccountsEvents.CustomPropertyUpdated, { display_type: definition.display_type })
+ cache.awaitingCustomPropertyRefresh = true
+ dataNodeLogic.findMounted({ key: ACCOUNTS_TABLE_DATA_NODE_KEY })?.actions.loadData('force_async')
+ dataNodeLogic.findMounted({ key: ACCOUNTS_METRICS_DATA_NODE_KEY })?.actions.loadData('force_async')
+ } catch (error) {
+ actions.setCustomPropertyOverride(accountId, definition.id, previous)
+ posthog.captureException(error as Error, { scope: 'accountsLogic.updateAccountCustomProperty' })
+ lemonToast.error('Failed to update custom property')
+ } finally {
+ actions.customPropertyUpdateFinished(accountId, definition.id)
+ }
+ },
updateAccountRole: async ({ accountId, column, user }) => {
if (values.isRoleSaving(accountId, column)) {
return
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index a13194b13473..be5517a05350 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -43,6 +43,7 @@ export const AccountsEvents = {
RoleAssigned: 'customer analytics account role assigned',
RelationshipDeleted: 'customer analytics accounts relationship deleted',
TagsUpdated: 'customer analytics account tags updated',
+ CustomPropertyUpdated: 'customer analytics account custom property updated',
LinkClicked: 'customer analytics account link clicked',
NoteClicked: 'customer analytics account note clicked',
NoteCreated: 'customer analytics accounts note created',