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.

fix(customer-analytics): allow clearing account custom properties (#112136)

Arthur Moreira de Deusc9e473bacbdf
diff --git a/docs/internal/customer-analytics/accounts-table.md b/docs/internal/customer-analytics/accounts-table.md
index 845ac1427ce9..0c5fcb6a1fd8 100644
--- a/docs/internal/customer-analytics/accounts-table.md
+++ b/docs/internal/customer-analytics/accounts-table.md
@@ -105,9 +105,23 @@ Automatic sizing uses the existing resized-table layout and does not change scro
The `ManyColumns` story in `AccountsTab.stories.tsx` covers six added custom properties alongside native and relationship columns.
Its browser assertions check content-dependent widths, the 200px cap, horizontal scrolling, and the row expansion control.
-At narrow widths, it also covers custom-property inline editing: the input fits the available column width, and Save and Cancel stay together below it when needed, aligned to the right.
+At narrow widths, it also covers custom-property inline editing: the input and Clear value action fit the available column width, and Save and Cancel stay together below it when needed, aligned to the right.
+Wrapped editor controls have an 8px gap between rows.
The row grows without widening the column.
+## Clearing custom properties
+
+Every editable custom-property cell offers Clear value, including select, boolean, numeric, date, and datetime properties.
+The action asks for confirmation before saving `null` through the existing custom-property-values endpoint.
+Canceling the confirmation keeps the value unchanged.
+A cleared cell shows an unset value while the table refreshes, rather than falling back to its stale value.
+A failed write restores the previous value and lets the user try again.
+Canonical and warehouse-backed properties remain read-only.
+Workflow-backed properties remain editable, with the existing warning that a future workflow run can overwrite a manual change.
+
+The `ClearCustomProperties` story checks clearing every display type and canceling the confirmation.
+It includes zero and false values, which must stay distinct from an unset value.
+
## Relationship member pickers
Each editable single-holder relationship cell mounts a member picker.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 1ad119cbaa24..98ea983dc5e4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9034,14 +9034,18 @@ snapshots:
hash: v1.k794b7964.d40fa817713dd10abed32ed3192c3a4b77f6b4965aa08f22b5e0df956aae8aea.uOS17zi2Qakr6PZ0Wyqp_5GEI5fI0uGlz_kTxtZe4kM
scenes-app-customer-analytics-account-detail-property-sidebar--relationship-editors--light:
hash: v1.k794b7964.6a05a5185d65c3453772d59fc900639806645f2bed4312fae645c378b92434db.3oa4FH1trEpqenwjacxbL7ghR3_4phrO37CcwbJq4zw
+ scenes-app-customer-analytics-accounts--clear-custom-properties--dark:
+ hash: v1.k794b7964.62c61c0aa5418037ea924b699a9a7934013ec6934664fe62a0174feffe64c3d0.AbrKY22SHj-n5_B_vExSHUBLLile12ETpGmT7Hj0zws
+ scenes-app-customer-analytics-accounts--clear-custom-properties--light:
+ hash: v1.k794b7964.42e5a6db8c93590613636f6fb6450bea8a96aa6298610d922284e23ce69adbfd.Btn6U03TmjZhQXWmCxH8NKhQ8DMhFBQT2CAj59FNHR4
scenes-app-customer-analytics-accounts--default--dark:
hash: v1.k794b7964.87b94a84ccaa2040f2a63a4e1cd35dd0c315d1d2b109373e999ab033095d9991.Z0zI1_Ksb54CS0M_eO3B_EaIXjiDdPDUAxp2G556P5o
scenes-app-customer-analytics-accounts--default--light:
hash: v1.k794b7964.b986d24c5b87d97314d1b6fcd605ef453d56ffef2c2f3d6408722db977cf1fb2.1CjtHSZqb1ZDLB_hE3PLlIdf4IE4oCpn_BhAJh_DsQs
scenes-app-customer-analytics-accounts--empty--dark:
- hash: v1.k794b7964.438df1869b5277d02ec0f8f8dc6ffda458f257203a885dc34d0cdf6681665f4b.MfhdrLGE7U65Q0md0ydoz254zQmGDPW4Xilis8C8gxc
+ hash: v1.k794b7964.962ba84279119ab92e48c352b1e1b39084c5a1d267d65c54af790cd79fae2b59.oyN7WtxCxnFN2f5NJ2B2VNlAxmwQvnJcS_qUZhAPdFg
scenes-app-customer-analytics-accounts--empty--light:
- hash: v1.k794b7964.d440a51b1fea226d13d070be68297057ec12bbd72ee7ac4ba61fe41b9ed53cb3.dEhN6yGCfnCaECmg3tof6UcHiHCk2k5XBtTE6xDmezQ
+ hash: v1.k794b7964.ed8345063a6d0a3e9a548c29f573e2e0627e0eabe1a70b0ba81fdd5ec4bf3852.G0-FgLIKE5A8w4SXzTCZR6J3snyELXCznWipjnmHz64
scenes-app-customer-analytics-accounts--feature-gate-off--dark:
hash: v1.k794b7964.4b8d5226ee154debdf333ff93d65a90ca766bcb25951e1baf36affb8b84b548d.dWZSHssPc83RkHVE-JPJA562bJR7MUim2yfqhjfNE50
scenes-app-customer-analytics-accounts--feature-gate-off--light:
@@ -9059,9 +9063,9 @@ snapshots:
scenes-app-customer-analytics-accounts--filter-groups-narrow--light:
hash: v1.k794b7964.f45c2a3028c57dfb15c2e920cbe17f8c4719bf0a4b678c57af013a628e59fe7c.bgetcxQYMZvG4VWXZgzrMV5t-4t1VdKTwRfpgS8ENcQ
scenes-app-customer-analytics-accounts--many-columns--dark:
- hash: v1.k794b7964.c4c14cff203abdcb043554c234992f8f9c5fd402593321ac273ed11f56008c87.jOW1vwhYZ7YROPN6kZEfuCAK_dMmpXqNPwQ5LoqE-z4
+ hash: v1.k794b7964.a2a473bc95254786959613fca36e7e530ae55be6d1fde64ebb78c771fd19bc35.Crh-PJqTQudPhm8LWlNAQp8B30SsXvOf17q9Ki-2BQc
scenes-app-customer-analytics-accounts--many-columns--light:
- hash: v1.k794b7964.1768294dde4750497834dd820aeafddb70f696feae609c2a3ea623dbfb34083b.pScO4R-ZrH5Rp71laUMaPLo9U97DBOyRnJVJesjRB4Q
+ hash: v1.k794b7964.0a2ee3a18a52f0b113c8e5630d9741677ce20e541a434b61237525987ae987c1.qhY5hAKOEmpx-dh1vti-vt7RtucjvftEc1F0DRtNR9g
scenes-app-customer-analytics-accounts--row-expanded-conversations--dark:
hash: v1.k794b7964.bd5d33f06635b1fa2ac401e370dfad9e7c125e349f41bd172cafb5e38aeab721.7jRlvWfxiKE6Dp9YRZQ9MWzbZlKypIJd7WQbE-Zscjw
scenes-app-customer-analytics-accounts--row-expanded-conversations--light:
@@ -9083,9 +9087,9 @@ snapshots:
scenes-app-customer-analytics-accounts--row-expanded-no-pinned-properties--light:
hash: v1.k794b7964.d1bbe7fadec01dcf5468bc307e5ddaf120c0a05cf354a8107be95a3d08cba094.a-jmv3Srry1RzTZNouTKL2SWYazNQqcwBvP2fWbCGgE
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties--dark:
- hash: v1.k794b7964.0ba788c8004420790805420e9fda4e5aff7d7998e1fd99a727aaf7bbcfdca91d.LSIRN0fG5xJ2vaBijLX79E90sMHQjE60Hv0b-5upebQ
+ hash: v1.k794b7964.1a6a6a811b74d997851b9eb81d93c0c5a5c75cbbcdd9c4a81535da756f308847.mP5q4EFqTMDAID3pFx24qLVCfviBoaNmqN6xxDOJUqs
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties--light:
- hash: v1.k794b7964.d8070b3478d26d3b52732d8aaba87a87d8bcbd48d69bd393058ac8c00c0b8bb4.2ByzGyRTZ8iYL0G9DunC3aP2yNPGjHsXDLMN0zya1hA
+ hash: v1.k794b7964.95fda5852833bb19b7d0ec626dbe228297c6296c179215f69f835f5c76fb740f.PHQ2Hjp_qXXmXMYGCkY-E-ULQaNfEQ3zYZMg6Rn44ls
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-error--dark:
hash: v1.k794b7964.48fbedcb90e1b63a9f3472a750d84a9aed6226671a529eaacf20c832dd33be29.dPfzWKCqVueqTXahDik4Xgw_2dxOau-s9rE-AMbHegQ
scenes-app-customer-analytics-accounts--row-expanded-pinned-properties-error--light:
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 96060e2817f5..c90ef6edde00 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -124,7 +124,7 @@ 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 unless its definition is canonical or has a data warehouse source. Workflow-referenced properties stay editable and show a warning that a future workflow run overwrites a manual value. `AccountsTable` passes this condition as `isEditable` to `CustomPropertyCell`. Editable cells show a pencil that replaces the rendered value with a compact, type-aware editor. In inline edit mode, the input fits the available column width. Save and Cancel stay together and wrap below the input when needed, aligned to the right. The row grows without widening the column. 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.
+A custom-property column is editable unless its definition is canonical or has a data warehouse source. Workflow-referenced properties stay editable and show a warning that a future workflow run overwrites a manual value. `AccountsTable` passes this condition as `isEditable` to `CustomPropertyCell`. Editable cells show a pencil that replaces the rendered value with a compact, type-aware editor. In inline edit mode, the input fits the available column width. Save and Cancel stay together and wrap below the input when needed, aligned to the right. Wrapped controls have an 8px gap between rows. The row grows without widening the column. 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. Every inline editor offers Clear value with confirmation, including date and datetime editors. Clearing writes `null`, which remains an explicit override so the cell shows an unset value while the query refreshes. An absent override is `undefined`, not `null`. `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 restores the previous override after a failed write. The list response for a write's refresh clears the overrides of completed writes. The override of a write that is still pending stays until the refresh that follows it. 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.
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
index 021abaf38034..09843407f64a 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
@@ -420,7 +420,7 @@ export const ManyColumns: Story = {
mswDecorator({
get: {
'api/projects/:team_id/column_configurations/': { count: 0, next: null, results: [] },
- 'api/environments/:team_id/customer_journeys/': { count: 0, next: null, results: [] },
+ 'api/projects/:team_id/customer_journeys/': { count: 0, next: null, results: [] },
'api/projects/:team_id/custom_property_definitions/': {
count: ADDITIONAL_COLUMN_DEFINITIONS.length,
next: null,
@@ -482,11 +482,12 @@ export const ManyColumns: Story = {
const input = cell.querySelector('[data-attr="accounts-custom-property-value-input"]')
const save = cell.querySelector('[data-attr="accounts-custom-property-value-save"]')
const cancel = cell.querySelector('[data-attr="accounts-custom-property-value-cancel"]')
- if (!input || !save || !cancel) {
+ const clear = cell.querySelector('[data-attr="accounts-custom-property-value-clear"]')
+ if (!input || !save || !cancel || !clear) {
throw new Error('Inline editor controls are missing')
}
const cellBounds = cell.getBoundingClientRect()
- for (const control of [input, save, cancel]) {
+ for (const control of [input, save, cancel, clear]) {
const bounds = control.getBoundingClientRect()
if (
bounds.left < cellBounds.left ||
@@ -500,8 +501,8 @@ export const ManyColumns: Story = {
const inputBounds = input.getBoundingClientRect()
const saveBounds = save.getBoundingClientRect()
const cancelBounds = cancel.getBoundingClientRect()
- if (saveBounds.top < inputBounds.bottom || saveBounds.top !== cancelBounds.top) {
- throw new Error('Save and Cancel must wrap together below the input in narrow columns')
+ if (saveBounds.top < inputBounds.bottom + 8 || saveBounds.top !== cancelBounds.top) {
+ throw new Error('Save and Cancel must wrap together with an 8px gap below the input')
}
if (cancelBounds.right <= inputBounds.right) {
throw new Error('Save and Cancel must align to the right of the available cell space')
@@ -515,6 +516,149 @@ export const ManyColumns: Story = {
},
}
+const CLEARABLE_PROPERTY_FIXTURES = [
+ { name: 'Onboarding status', display_type: 'select' as const, value: 'New account' },
+ { name: 'Seats', display_type: 'number' as const, value: '0' },
+ { name: 'Active', display_type: 'boolean' as const, value: 'false' },
+ { name: 'Start date', display_type: 'date' as const, value: '2026-05-01' },
+ { name: 'Check-in time', display_type: 'datetime' as const, value: '2026-05-01T10:00:00Z' },
+ { name: 'Website', display_type: 'link' as const, value: 'https://example.com' },
+ { name: 'Description', display_type: 'text' as const, value: 'Example account' },
+ { name: 'Subscription cost', display_type: 'currency' as const, value: '100' },
+ { name: 'Progress', display_type: 'percent' as const, value: '0.5' },
+]
+const CLEARABLE_PROPERTY_DEFINITIONS: CustomPropertyDefinitionApi[] = CLEARABLE_PROPERTY_FIXTURES.map(
+ (fixture, index) => ({
+ ...ADDITIONAL_COLUMN_DEFINITIONS[0],
+ id: `10000000-0000-0000-0000-00000000000${index}`,
+ name: fixture.name,
+ display_type: fixture.display_type,
+ options: fixture.display_type === 'select' ? [{ label: 'New account', color: 'preset-1' }] : undefined,
+ })
+)
+
+let finishClearPropertyWrite: (() => void) | undefined
+
+export const ClearCustomProperties: Story = {
+ render: () => <App />,
+ parameters: {
+ pageUrl: `${urls.customerAnalyticsAccounts()}#view=${encodeURIComponent(
+ JSON.stringify({
+ columns: [
+ ...ACCOUNTS_DEFAULT_COLUMNS,
+ ...CLEARABLE_PROPERTY_DEFINITIONS.map(
+ ({ id }) => `accounts.custom_properties.values.\`${id}\` AS ${customPropertyAlias(id)}`
+ ),
+ ],
+ })
+ )}`,
+ testOptions: { viewport: { width: 1280, height: 960 } },
+ },
+ decorators: [
+ (Story, context) => {
+ const values = Object.fromEntries(
+ CLEARABLE_PROPERTY_FIXTURES.map(({ value }, index) => [CLEARABLE_PROPERTY_DEFINITIONS[index].id, value])
+ )
+ return mswDecorator({
+ get: {
+ 'api/projects/:team_id/column_configurations/': { count: 0, next: null, results: [] },
+ 'api/projects/:team_id/customer_journeys/': { count: 0, next: null, results: [] },
+ [CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT]: {
+ count: CLEARABLE_PROPERTY_DEFINITIONS.length,
+ next: null,
+ previous: null,
+ results: CLEARABLE_PROPERTY_DEFINITIONS,
+ },
+ },
+ post: {
+ [QUERY_ENDPOINT]: mockAccountsTableQuery(SINGLE_ROW, values),
+ [ACCOUNT_PROPERTY_VALUES_ENDPOINT]: async ({ request }) => {
+ const body = (await request.json()) as { definition: string; value: unknown }
+ if (body.value !== null) {
+ throw new Error('Clearing a property must send null')
+ }
+ await new Promise<void>((resolve) => {
+ finishClearPropertyWrite = () => {
+ delete values[body.definition]
+ resolve()
+ }
+ })
+ return [204, null]
+ },
+ },
+ })(Story, context)
+ },
+ ],
+ // A failed run leaves its resolver behind, and a remount in the same page would release the wrong request.
+ beforeEach: () => {
+ finishClearPropertyWrite = undefined
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await canvas.findByText('New account')
+ for (const definition of CLEARABLE_PROPERTY_DEFINITIONS) {
+ const header = canvasElement
+ .querySelector(`[data-attr="accounts-table-sort-${customPropertyAlias(definition.id)}"]`)
+ ?.closest('th')
+ const cell = header?.closest('table')?.querySelector('tbody tr')?.children[header.cellIndex]
+ const edit = cell?.querySelector<HTMLElement>('[data-attr="accounts-custom-property-value-edit"]')
+ if (!cell || !edit) {
+ throw new Error('Editable custom property cell is missing')
+ }
+ await userEvent.click(edit)
+ const clear = cell.querySelector<HTMLElement>('[data-attr="accounts-custom-property-value-clear"]')
+ if (!clear) {
+ throw new Error('Every custom property editor must offer Clear value')
+ }
+ await userEvent.click(clear)
+ const dialog = await within(document.body).findByText(`Clear ${definition.name}?`)
+ const modal = dialog.closest('.LemonModal')
+ if (!modal) {
+ throw new Error('Clear confirmation dialog is missing')
+ }
+ if (definition.display_type === 'select') {
+ await userEvent.click(within(modal as HTMLElement).getByText('Cancel'))
+ if (!cell.querySelector('[data-attr="accounts-custom-property-value-clear"]')) {
+ throw new Error('Canceling a clear must keep the inline editor open')
+ }
+ await waitFor(() => {
+ if (document.body.contains(modal)) {
+ throw new Error('Canceled confirmation must close')
+ }
+ })
+ await userEvent.click(clear)
+ }
+ const confirmation = (await within(document.body).findByText(`Clear ${definition.name}?`)).closest(
+ '.LemonModal'
+ )
+ await userEvent.click(within(confirmation as HTMLElement).getByText('Clear value'))
+ await waitFor(() => {
+ if (cell.querySelector('[data-attr="accounts-custom-property-value-clear"]')) {
+ throw new Error('Confirming a clear must close the inline editor')
+ }
+ if (!within(cell as HTMLElement).queryByText('—')) {
+ throw new Error('Cleared values must render as unset')
+ }
+ if (!finishClearPropertyWrite) {
+ throw new Error('Clear request must reach the API')
+ }
+ })
+ finishClearPropertyWrite?.()
+ finishClearPropertyWrite = undefined
+ await waitFor(() => {
+ const currentEdit = cell.querySelector('[data-attr="accounts-custom-property-value-edit"]')
+ if (
+ !currentEdit ||
+ currentEdit.hasAttribute('disabled') ||
+ currentEdit.getAttribute('aria-disabled') === 'true'
+ ) {
+ throw new Error('Property write must finish before the next edit')
+ }
+ })
+ }
+ },
+}
+
export const Empty: Story = {
render: () => <App />,
decorators: [
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
index 893e83521d99..9243676aa2c5 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx
@@ -5,6 +5,7 @@ import { IconCheck, IconInfo, IconPencil, IconX } from '@posthog/icons'
import {
LemonButton,
LemonColorGlyph,
+ LemonDialog,
LemonInput,
LemonSelect,
LemonSkeleton,
@@ -583,7 +584,7 @@ function CustomPropertyCell({
const currentValue = display
? (buildHistoryDisplay(parseHistoryPoints(raw), display.window_days, dayjs().valueOf()).latest?.[1] ?? null)
: raw
- const value = override ?? currentValue
+ const value = override !== undefined ? override : currentValue
const [isEditing, setIsEditing] = useState(false)
const [draft, setDraft] = useState<CustomPropertyDraft>(() => customPropertyDraftValue(value, definition))
const saving = accountId ? isCustomPropertySaving(accountId, definition.id) : false
@@ -592,23 +593,59 @@ function CustomPropertyCell({
setDraft(customPropertyDraftValue(value, definition))
setIsEditing(true)
}
- const saveValue = (nextValue: CustomPropertyDraft = draft): void => {
- if (!accountId || !isCustomPropertyValueValid(nextValue, definition)) {
+ const saveValue = (nextValue: CustomPropertyDraft | null = draft): void => {
+ if (!accountId || saving || (nextValue !== null && !isCustomPropertyValueValid(nextValue, definition))) {
return
}
- updateAccountCustomProperty(accountId, definition, customPropertyValueToSave(nextValue, definition))
+ updateAccountCustomProperty(
+ accountId,
+ definition,
+ nextValue === null ? null : customPropertyValueToSave(nextValue, definition)
+ )
setIsEditing(false)
}
+ const confirmClear = (): void => {
+ if (saving) {
+ return
+ }
+ LemonDialog.open({
+ title: `Clear ${definition.name}?`,
+ content: 'This will remove the current value. You can set it again later.',
+ primaryButton: {
+ children: 'Clear value',
+ status: 'danger',
+ onClick: () => saveValue(null),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
const isDatePicker = definition.display_type === 'date' || definition.display_type === 'datetime'
if (isEditing && accountId) {
return (
<div
- className={`inline-flex w-fit min-w-0 max-w-full flex-wrap items-center ${definition.display_type === 'boolean' ? 'gap-2' : 'gap-1'}`}
+ className={`inline-flex w-fit min-w-0 max-w-full flex-wrap items-center gap-y-2 ${definition.display_type === 'boolean' ? 'gap-x-2' : 'gap-x-1'}`}
>
<div className={definition.display_type === 'boolean' ? undefined : 'w-40 min-w-0 max-w-full'}>
{renderCustomPropertyEditor(draft, definition, setDraft, saveValue, () => setIsEditing(false))}
</div>
+ <LemonButton
+ size="xsmall"
+ status="danger"
+ tooltip="Clear value"
+ aria-label="Clear value"
+ onClick={confirmClear}
+ disabledReason={
+ saving
+ ? 'Saving…'
+ : value === null || value === undefined
+ ? 'This property has no value'
+ : undefined
+ }
+ data-attr="accounts-custom-property-value-clear"
+ >
+ Clear
+ </LemonButton>
{!isDatePicker && (
<div
className={`ml-auto flex shrink-0 items-center ${definition.display_type === 'boolean' ? 'gap-2' : 'gap-1'}`}
@@ -619,6 +656,7 @@ function CustomPropertyCell({
icon={<IconCheck />}
tooltip="Save"
onClick={() => saveValue()}
+ loading={saving}
disabledReason={
isCustomPropertyValueValid(draft, definition)
? undefined
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
index b665f9b049a8..d431ba1d231d 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts
@@ -1463,27 +1463,27 @@ describe('accountsLogic', () => {
})
describe('updateAccountCustomProperty', () => {
- it('writes the value and masks stale query data with the saved value', async () => {
+ it.each([42, 0, false, null])('writes %s and masks stale query data with the saved value', async (value) => {
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,
+ value: value ?? 42,
created_at: '2026-01-01T00:00:00Z',
created_by_id: 1,
})
- logic.actions.updateAccountCustomProperty('acc-1', definition, 42)
+ logic.actions.updateAccountCustomProperty('acc-1', definition, value)
- expect(logic.values.customPropertyOverrides[customPropertySavingKey('acc-1', definition.id)]).toBe(42)
+ expect(logic.values.customPropertyOverrides[customPropertySavingKey('acc-1', definition.id)]).toBe(value)
await expectLogic(logic).toFinishAllListeners()
expect(mockCustomPropertyValuesCreate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), 'acc-1', {
definition: definition.id,
- value: 42,
+ value,
})
expect(
logic.values.customPropertyOverrides[customPropertySavingKey('acc-1', definition.id)]
@@ -1495,11 +1495,72 @@ describe('accountsLogic', () => {
})
})
+ it('blocks duplicate clear requests while a write is pending', async () => {
+ const definition = buildCustomPropertyDefinition()
+ let finishWrite!: (value: Awaited<ReturnType<typeof accountsCustomPropertyValuesCreate>>) => void
+ mockCustomPropertyValuesCreate.mockImplementationOnce(
+ () =>
+ new Promise<Awaited<ReturnType<typeof accountsCustomPropertyValuesCreate>>>(
+ (resolve) => (finishWrite = resolve)
+ )
+ )
+
+ logic.actions.updateAccountCustomProperty('acc-1', definition, null)
+ logic.actions.updateAccountCustomProperty('acc-1', definition, null)
+
+ expect(mockCustomPropertyValuesCreate).toHaveBeenCalledTimes(1)
+ expect(logic.values.isCustomPropertySaving('acc-1', definition.id)).toBe(true)
+ expect(logic.values.customPropertyOverrides[customPropertySavingKey('acc-1', definition.id)]).toBeNull()
+
+ finishWrite({
+ id: 'value-1',
+ account_id: 'acc-1',
+ definition_id: definition.id,
+ value: 42,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by_id: 1,
+ })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.isCustomPropertySaving('acc-1', definition.id)).toBe(false)
+ })
+
+ it('clears only refreshed overrides when the refresh of an earlier write lands during a pending write', async () => {
+ const saved = buildCustomPropertyDefinition()
+ const pending = buildCustomPropertyDefinition({ id: 'custom-property-2' })
+ const pendingKey = customPropertySavingKey('acc-1', pending.id)
+ const writeResult: Awaited<ReturnType<typeof accountsCustomPropertyValuesCreate>> = {
+ id: 'value-1',
+ account_id: 'acc-1',
+ definition_id: saved.id,
+ value: 42,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by_id: 1,
+ }
+ let finishPendingWrite!: (value: typeof writeResult) => void
+ mockCustomPropertyValuesCreate
+ .mockResolvedValueOnce(writeResult)
+ .mockImplementationOnce(() => new Promise((resolve) => (finishPendingWrite = resolve)))
+
+ logic.actions.updateAccountCustomProperty('acc-1', saved, null)
+ logic.actions.updateAccountCustomProperty('acc-1', pending, null)
+ await expectLogic(logic).toDispatchActions(['listLoadDataSuccess'])
+
+ expect(logic.values.isCustomPropertySaving('acc-1', pending.id)).toBe(true)
+ expect(logic.values.customPropertyOverrides).toEqual({ [pendingKey]: null })
+
+ finishPendingWrite({ ...writeResult, definition_id: pending.id })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.customPropertyOverrides).toEqual({})
+ })
+
it.each([
- ['canonical', buildCustomPropertyDefinition({ is_canonical: true })],
- ['data warehouse managed', buildCustomPropertyDefinition({ source: createCustomPropertySource() })],
- ])('does not write a %s property', async (_, definition) => {
- logic.actions.updateAccountCustomProperty('acc-1', definition, 42)
+ ['canonical', buildCustomPropertyDefinition({ is_canonical: true }), 42],
+ ['canonical', buildCustomPropertyDefinition({ is_canonical: true }), null],
+ ['data warehouse managed', buildCustomPropertyDefinition({ source: createCustomPropertySource() }), 42],
+ ['data warehouse managed', buildCustomPropertyDefinition({ source: createCustomPropertySource() }), null],
+ ] as const)('does not write a %s property', async (_, definition, value) => {
+ logic.actions.updateAccountCustomProperty('acc-1', definition, value)
await expectLogic(logic).toFinishAllListeners()
expect(mockCustomPropertyValuesCreate).not.toHaveBeenCalled()
@@ -1530,11 +1591,11 @@ describe('accountsLogic', () => {
})
})
- it('reverts the optimistic override after a failed write', async () => {
+ it.each([42, null])('reverts the optimistic override after a failed write of %s', async (value) => {
const definition = buildCustomPropertyDefinition()
mockCustomPropertyValuesCreate.mockRejectedValueOnce(new Error('boom'))
- logic.actions.updateAccountCustomProperty('acc-1', definition, 42)
+ logic.actions.updateAccountCustomProperty('acc-1', definition, value)
await expectLogic(logic).toFinishAllListeners()
expect(
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
index cf374959aa7d..ffdbb2c83f5d 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts
@@ -484,8 +484,8 @@ export interface accountsLogicActions {
options: ApplyAccountsViewStateOptions
viewState: AccountsViewState
}
- clearCustomPropertyOverrides: () => {
- value: true
+ clearCustomPropertyOverrides: (keys: string[]) => {
+ keys: string[]
}
customPropertyUpdateFinished: (
accountId: string,
@@ -577,11 +577,11 @@ export interface accountsLogicActions {
setCustomPropertyOverride: (
accountId: string,
definitionId: string,
- value: CustomPropertyValueWriteApi['value'] | null
+ value: CustomPropertyValueWriteApi['value'] | undefined
) => {
accountId: string
definitionId: string
- value: boolean | number | string | null
+ value: boolean | number | string | null | undefined
}
setDraftRestored: (restored: boolean) => {
restored: boolean
@@ -888,11 +888,11 @@ export const accountsLogic = kea<accountsLogicType>([
) => ({ accountId, definition, value }),
customPropertyUpdateStarted: (accountId: string, definitionId: string) => ({ accountId, definitionId }),
customPropertyUpdateFinished: (accountId: string, definitionId: string) => ({ accountId, definitionId }),
- clearCustomPropertyOverrides: true,
+ clearCustomPropertyOverrides: (keys: string[]) => ({ keys }),
setCustomPropertyOverride: (
accountId: string,
definitionId: string,
- value: CustomPropertyValueWriteApi['value'] | null
+ value: CustomPropertyValueWriteApi['value'] | undefined
) => ({ accountId, definitionId, value }),
updateAccountRole: (accountId: string, column: string, user: UserBasicType | null) => ({
accountId,
@@ -1039,14 +1039,20 @@ export const accountsLogic = kea<accountsLogicType>([
setCustomPropertyOverride: (state, { accountId, definitionId, value }) => {
const next = { ...state }
const key = customPropertySavingKey(accountId, definitionId)
- if (value === null) {
+ if (value === undefined) {
delete next[key]
} else {
next[key] = value
}
return next
},
- clearCustomPropertyOverrides: () => ({}),
+ clearCustomPropertyOverrides: (state, { keys }) => {
+ const next = { ...state }
+ for (const key of keys) {
+ delete next[key]
+ }
+ return next
+ },
},
],
savingRoles: [
@@ -1565,7 +1571,12 @@ export const accountsLogic = kea<accountsLogicType>([
}
if (queryId === cache.customPropertyRefreshQueryId) {
cache.customPropertyRefreshQueryId = undefined
- actions.clearCustomPropertyOverrides()
+ // The override of a write that is still pending is newer than this response.
+ // It stays until the refresh that follows that write.
+ const writtenKeys: string[] = cache.writtenCustomPropertyKeys ?? []
+ const isPending = (key: string): boolean => !!values.savingCustomProperties[key]
+ cache.writtenCustomPropertyKeys = writtenKeys.filter(isPending)
+ actions.clearCustomPropertyOverrides(writtenKeys.filter((key) => !isPending(key)))
}
},
loadAccountPresence: async ({ accountIds }) => {
@@ -1982,7 +1993,7 @@ export const accountsLogic = kea<accountsLogicType>([
return
}
const key = customPropertySavingKey(accountId, definition.id)
- const previous = values.customPropertyOverrides[key] ?? null
+ const previous = values.customPropertyOverrides[key]
actions.customPropertyUpdateStarted(accountId, definition.id)
actions.setCustomPropertyOverride(accountId, definition.id, value)
try {
@@ -1994,6 +2005,7 @@ export const accountsLogic = kea<accountsLogicType>([
display_type: definition.display_type,
workflow_reference: definition.has_workflow_reference,
})
+ cache.writtenCustomPropertyKeys = [...(cache.writtenCustomPropertyKeys ?? []), key]
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')