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): show and edit churned and ignored account status (#113619)

Arthur Moreira de Deus93e9dedf03e8
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2c041cf132e5..47947fc22b1d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9146,10 +9146,18 @@ snapshots:
hash: v1.k794b7964.6dfdfa963cd528d998f0fec6cad0e97b3d999d584c03513cb02aaebfac0df7b1.p1pRi00v4RXJ6t8fXTtzfgLTTMnU0-efeu_N-yFdeL8
scenes-app-businessknowledge-knowledgesourcenamecell--user-text--light:
hash: v1.k794b7964.fba04716b8f344e21fa3bb2ec69e627bd9836ff2161986538ac2b562973b0edc.Xl-YJ8Poqz1nofU4nIyAfnM4GbZZ1YYtbM37mIzZ4w4
+ scenes-app-customer-analytics-account-detail--churned-and-ignored--dark:
+ hash: v1.k794b7964.9c6436aba85f3a114d4a5d7cec25c188131dfb1963f637f43fa6da973d34ae6c.ofneyf9YQP_TSCsA6KbPXDKXjqEC2xyeHfljSG957Bc
+ scenes-app-customer-analytics-account-detail--churned-and-ignored--light:
+ hash: v1.k794b7964.b059230a0cef776a2ae19b0f0b116fa8598c55f87dc21f5399f93e5e540b56f1.h9vvfcf-nEYaEVSpIv0Q8Oy01Bt4G4LojokghXJ2KgA
scenes-app-customer-analytics-account-detail--default--dark:
hash: v1.k794b7964.4a2c8fd1f6e62fadf3a11ec937086d0ab3e97c820541fe568789683d1517124d.TDZuljsH5Uy2rQ4pSkDrrazjA-SlyfGn52R4n9Ix4ac
scenes-app-customer-analytics-account-detail--default--light:
hash: v1.k794b7964.3dc16f08d0f41b7d7cf6b0e84392580fb009090e3bb7fc8ad9ff8c6a4b8b5c0e.hTnJ40qtoFvmt2g1j9aw7zm4mSIulD0osQgS2SjLKI4
+ scenes-app-customer-analytics-account-detail--edit-status-dates--dark:
+ hash: v1.k794b7964.621eb2ecd55d586073ed167a2f727bf3c923ce4057c8880040e0de639ef86991.jpgBJawhros6cJyc_L1cGLCO0JWNZ4HfKRky8hX_TiY
+ scenes-app-customer-analytics-account-detail--edit-status-dates--light:
+ hash: v1.k794b7964.220e9463403db401ceaf2c4c95be892641d7bda4488a31b192b3e789a5c59756.WAPP_4Co_p5fU9n7q8VRJCmmq4OIF53Q84teairAX2g
scenes-app-customer-analytics-account-detail--external-id--dark:
hash: v1.k794b7964.26a93f54f5fe293e17ee0f7315163a5b14c71e1e78e1bb8adc78f09ca04412f3.4gU8PFyIaVQrS8zOPX6Al_eLweeNi9XIAQ9hfr2pzag
scenes-app-customer-analytics-account-detail--external-id--light:
diff --git a/frontend/src/lib/components/Search/Search.tsx b/frontend/src/lib/components/Search/Search.tsx
index 95cdea8a5ee8..84b508e995a8 100644
--- a/frontend/src/lib/components/Search/Search.tsx
+++ b/frontend/src/lib/components/Search/Search.tsx
@@ -16,7 +16,7 @@ import {
} from 'react'
import { IconDay, IconNight, IconSearch, IconSparkles, IconX } from '@posthog/icons'
-import { Link, Spinner } from '@posthog/lemon-ui'
+import { LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'
import { filterSearchItems } from 'lib/components/Search/utils'
@@ -891,6 +891,20 @@ function SearchResults({
<span className="truncate">
{String(item.displayName || item.name)}
</span>
+ {item.badges?.map((badge) => (
+ <Tooltip
+ key={badge.label}
+ title={badge.tooltip}
+ >
+ <LemonTag
+ type={badge.type}
+ size="small"
+ className="shrink-0"
+ >
+ {badge.label}
+ </LemonTag>
+ </Tooltip>
+ ))}
{(group.category === 'recents' ||
group.category === 'starred' ||
group.category === 'groups') &&
diff --git a/frontend/src/lib/components/Search/searchItems.tsx b/frontend/src/lib/components/Search/searchItems.tsx
index f6a4195d7c9e..3e6fd7396711 100644
--- a/frontend/src/lib/components/Search/searchItems.tsx
+++ b/frontend/src/lib/components/Search/searchItems.tsx
@@ -1,4 +1,5 @@
import { IconBuilding } from '@posthog/icons'
+import type { LemonTagType } from '@posthog/lemon-ui'
import { getEntryAccessDisabledReason } from 'lib/utils/accessControlUtils'
import { GroupQueryResult } from 'lib/utils/groups'
@@ -12,6 +13,7 @@ import { FileSystemEntry } from '~/queries/schema/schema-general'
import { FileSystemIconColor, GroupTypeIndex, SearchResponse } from '~/types'
import type { TicketApi } from 'products/conversations/frontend/generated/api.schemas'
+import { getAccountStatusTags } from 'products/customer_analytics/frontend/components/Accounts/accountStatusTags'
import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
import { filterSearchItems } from './utils'
@@ -43,6 +45,8 @@ export interface SearchItem {
/** When set, the item is shown greyed out and non-clickable, with this reason as tooltip
* (e.g. the user has no access to the product or resource). */
disabledReason?: string
+ /** Status tags rendered after the name, e.g. "Churned" on an account. */
+ badges?: { label: string; type: LemonTagType; tooltip?: string }[]
}
let cachedProductIconColorByType: Map<string, FileSystemIconColor> | null = null
@@ -193,6 +197,11 @@ export const accountToSearchItem = (account: AccountApi): SearchItem => {
icon: <IconBuilding />,
itemType: 'account',
record: { type: 'account', id: account.id },
+ badges: getAccountStatusTags(account).map(({ label, type, dateLabel }) => ({
+ label,
+ type,
+ tooltip: dateLabel,
+ })),
}
}
diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsx
index 9c7b25b3922c..760048b64676 100644
--- a/frontend/src/lib/components/Search/searchLogic.tsx
+++ b/frontend/src/lib/components/Search/searchLogic.tsx
@@ -552,6 +552,9 @@ export const searchLogic = kea<searchLogicType>([
{
search: trimmed,
limit: SEARCH_LIMIT,
+ include_churned: true,
+ include_ignored: true,
+ inactive_last: true,
},
{ signal: cache.searchAbortController?.signal }
)
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index ae2f01cdaffe..a902507d7965 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -37,6 +37,7 @@ from django.db.models import (
Count,
DateTimeField,
Exists,
+ ExpressionWrapper,
F,
Field,
FloatField,
@@ -3701,6 +3702,7 @@ def list_accounts_for_view(
include_churned: bool = False,
include_ignored: bool = False,
ordering: str | None = None,
+ inactive_last: bool = False,
) -> tuple[list[contracts.AccountDetails], int]:
"""The accounts list endpoint, behind the facade: team + object-level access filtering,
the search / tags / unassigned / ordering query filters, notebook + tag prefetching, and
@@ -3731,7 +3733,15 @@ def list_accounts_for_view(
.values("account_id")
)
- queryset = queryset.order_by(ordering) if ordering else queryset.order_by("-created_at")
+ order_fields = [ordering or "-created_at"]
+ if inactive_last:
+ queryset = queryset.annotate(
+ is_inactive=ExpressionWrapper(
+ Q(churned_at__isnull=False) | Q(ignored_at__isnull=False), output_field=BooleanField()
+ )
+ )
+ order_fields.insert(0, "is_inactive")
+ queryset = queryset.order_by(*order_fields)
total_count = queryset.count()
page = list(queryset[offset : offset + limit])
@@ -3786,6 +3796,7 @@ def update_account(
properties: "dict | _ModelAccountProperties | _Unset" = _UNSET,
slack_summary_cadence: "str | None | _Unset" = _UNSET,
churned_at: "datetime | None | _Unset" = _UNSET,
+ ignored_at: "datetime | None | _Unset" = _UNSET,
allow_matching_updates: bool = False,
) -> Account:
"""Field-write primitive shared by every account update path. Only the fields passed are
@@ -3818,6 +3829,9 @@ def update_account(
if not isinstance(churned_at, _Unset):
account.churned_at = churned_at
update_fields.append("churned_at")
+ if not isinstance(ignored_at, _Unset):
+ account.ignored_at = ignored_at
+ update_fields.append("ignored_at")
if update_fields:
account.save(update_fields=update_fields)
if matching_expanded:
@@ -3837,6 +3851,7 @@ def create_account(
tags: list[str] | None = None,
slack_summary_cadence: str | None = None,
churned_at: datetime | None = None,
+ ignored_at: datetime | None = None,
was_impersonated: bool = False,
trigger: Trigger | None = None,
) -> Account:
@@ -3855,6 +3870,7 @@ def create_account(
_properties=validated.model_dump(mode="json", exclude_unset=True),
slack_summary_cadence=slack_summary_cadence,
churned_at=churned_at,
+ ignored_at=ignored_at,
)
_set_tags(tags, account, actor=created_by)
except PydanticValidationError as exc:
@@ -3891,6 +3907,7 @@ def create_account_for_view(
tags=input.tags,
slack_summary_cadence=input.slack_summary_cadence,
churned_at=input.churned_at,
+ ignored_at=input.ignored_at,
was_impersonated=was_impersonated,
)
return _to_account_details(account)
@@ -3923,6 +3940,8 @@ def update_account_for_view(
update_kwargs["slack_summary_cadence"] = input.slack_summary_cadence
if input.churned_at_provided:
update_kwargs["churned_at"] = input.churned_at
+ if input.ignored_at_provided:
+ update_kwargs["ignored_at"] = input.ignored_at
update_kwargs["allow_matching_updates"] = allow_matching_updates
try:
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index f5ab08a597f6..b984a6cad771 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -1236,6 +1236,7 @@ class CreateAccountInput:
tags: list[str] | None = None
slack_summary_cadence: str | None = None
churned_at: datetime | None = None
+ ignored_at: datetime | None = None
@dataclass(frozen=True)
@@ -1253,11 +1254,13 @@ class UpdateAccountInput:
tags: list[str] | None = None
slack_summary_cadence: str | None = None
churned_at: datetime | None = None
+ ignored_at: datetime | None = None
# Distinguishes omitted fields from fields explicitly set to null.
external_id_provided: bool = False
properties_provided: bool = False
slack_summary_cadence_provided: bool = False
churned_at_provided: bool = False
+ ignored_at_provided: bool = False
@dataclass(frozen=True)
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 81b956263e0d..2c35fc1f33eb 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -1157,9 +1157,9 @@ class AccountSerializer(DataclassSerializer):
help_text="When the account churned. Null means the account has not churned.",
)
ignored_at = serializers.DateTimeField(
- read_only=True,
+ required=False,
allow_null=True,
- help_text="When Track Rules ignored the account. Null means the account is tracked.",
+ help_text=("When the account was ignored, set by Track Rules or by hand. Null means the account is tracked."),
)
created_at = serializers.DateTimeField(read_only=True)
created_by = serializers.IntegerField(read_only=True, allow_null=True)
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 5ff2f3ea57c6..392997bf67eb 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -1987,6 +1987,17 @@ class AccountViewSet(
enum=["name", "-name", "created_at", "-created_at", "updated_at", "-updated_at"],
description="Sort order. Defaults to '-created_at'.",
),
+ OpenApiParameter(
+ name="inactive_last",
+ type=OpenApiTypes.BOOL,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ default=False,
+ description=(
+ "When true, active and tracked accounts come before churned or ignored ones, "
+ "and `ordering` applies within each group. Use with `include_churned` or `include_ignored`."
+ ),
+ ),
],
)
def list(self, request: Request, *args, **kwargs) -> Response:
@@ -2006,6 +2017,7 @@ class AccountViewSet(
include_churned=request.query_params.get("include_churned", "").lower() == "true",
include_ignored=request.query_params.get("include_ignored", "").lower() == "true",
ordering=ordering,
+ inactive_last=request.query_params.get("inactive_last", "").lower() == "true",
),
AccountSerializer,
)
@@ -2294,6 +2306,7 @@ class AccountViewSet(
tags=_account_tags_input(serializer),
slack_summary_cadence=data.slack_summary_cadence,
churned_at=data.churned_at,
+ ignored_at=data.ignored_at,
),
user=cast(User, request.user),
was_impersonated=is_impersonated(request),
@@ -2329,6 +2342,8 @@ class AccountViewSet(
slack_summary_cadence_provided="slack_summary_cadence" in request.data,
churned_at=data.churned_at if "churned_at" in request.data else None,
churned_at_provided="churned_at" in request.data,
+ ignored_at=data.ignored_at if "ignored_at" in request.data else None,
+ ignored_at_provided="ignored_at" in request.data,
),
user_access_control=self.user_access_control,
required_level=_object_required_level(request, write=True),
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 8ae3b294d9a1..2c69b694ba59 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -486,18 +486,20 @@ class TestAccountViewSet(APIBaseTest):
self.assertIsNone(data["churned_at"])
self.assertIsNone(data["ignored_at"])
- def test_create_with_churned_at(self):
+ @parameterized.expand([("churned_at",), ("ignored_at",)])
+ def test_create_with_status_date(self, field: str) -> None:
response = self.client.post(
self.endpoint_base,
- {"name": "Former customer", "churned_at": "2026-08-01T12:30:00Z"},
+ {"name": "Former customer", field: "2026-08-01T12:30:00Z"},
format="json",
)
self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())
- self.assertEqual(response.json()["churned_at"], "2026-08-01T12:30:00Z")
+ self.assertEqual(response.json()[field], "2026-08-01T12:30:00Z")
account = Account.objects.unscoped().get(id=response.json()["id"]) # nosemgrep: idor-lookup-without-team
- assert account.churned_at is not None
- self.assertEqual(account.churned_at.isoformat(), "2026-08-01T12:30:00+00:00")
+ status_date = getattr(account, field)
+ assert status_date is not None
+ self.assertEqual(status_date.isoformat(), "2026-08-01T12:30:00+00:00")
def test_list(self):
a1 = self._create_account(name="Account 1")
@@ -544,6 +546,23 @@ class TestAccountViewSet(APIBaseTest):
self.assertEqual(status.HTTP_200_OK, response.status_code)
self.assertEqual({account["name"] for account in response.json()["results"]}, expected_names)
+ def test_list_inactive_last_puts_churned_and_ignored_accounts_after_active_ones(self) -> None:
+ self._create_account(name="A churned", churned_at=timezone.now())
+ self._create_account(name="B ignored", ignored_at=timezone.now())
+ self._create_account(name="C active")
+ self._create_account(name="D active")
+
+ response = self.client.get(
+ self.endpoint_base,
+ data={"include_churned": "true", "include_ignored": "true", "inactive_last": "true", "ordering": "name"},
+ )
+
+ self.assertEqual(status.HTTP_200_OK, response.status_code)
+ self.assertEqual(
+ [account["name"] for account in response.json()["results"]],
+ ["C active", "D active", "A churned", "B ignored"],
+ )
+
def test_retrieve(self):
ignored_at = timezone.now()
account = self._create_account(
@@ -760,33 +779,24 @@ class TestAccountViewSet(APIBaseTest):
self.assertEqual(account.properties.sfdc_id, "001xx")
self.assertEqual(account.properties.website_domain, "acme.example")
- def test_update_does_not_accept_ignored_at(self):
- ignored_at = timezone.now()
- account = self._create_account(ignored_at=ignored_at)
-
- response = self.client.patch(f"{self.endpoint_base}{account.id}/", {"ignored_at": None}, format="json")
-
- self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
- account.refresh_from_db()
- self.assertEqual(account.ignored_at, ignored_at)
-
- def test_update_and_clear_churned_at(self):
+ @parameterized.expand([("churned_at",), ("ignored_at",)])
+ def test_update_and_clear_status_date(self, field: str) -> None:
account = self._create_account()
url = f"{self.endpoint_base}{account.id}/"
- response = self.client.patch(url, {"churned_at": "2026-08-02T09:00:00Z"}, format="json")
+ response = self.client.patch(url, {field: "2026-08-02T09:00:00Z"}, format="json")
self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
- self.assertEqual(response.json()["churned_at"], "2026-08-02T09:00:00Z")
+ self.assertEqual(response.json()[field], "2026-08-02T09:00:00Z")
account.refresh_from_db()
- self.assertEqual(account.churned_at.isoformat(), "2026-08-02T09:00:00+00:00")
+ self.assertEqual(getattr(account, field).isoformat(), "2026-08-02T09:00:00+00:00")
- response = self.client.patch(url, {"churned_at": None}, format="json")
+ response = self.client.patch(url, {field: None}, format="json")
self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())
- self.assertIsNone(response.json()["churned_at"])
+ self.assertIsNone(response.json()[field])
account.refresh_from_db()
- self.assertIsNone(account.churned_at)
+ self.assertIsNone(getattr(account, field))
@parameterized.expand(
[
diff --git a/products/customer_analytics/frontend/components/Accounts/accountStatusTags.ts b/products/customer_analytics/frontend/components/Accounts/accountStatusTags.ts
new file mode 100644
index 000000000000..4b403e89d41c
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountStatusTags.ts
@@ -0,0 +1,39 @@
+import type { LemonTagType } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+
+import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+export interface AccountStatusTag {
+ field: 'churned_at' | 'ignored_at'
+ label: string
+ type: LemonTagType
+ dateLabel: string
+ dataAttr: string
+}
+
+const STATUS_TAGS = [
+ {
+ field: 'churned_at',
+ label: 'Churned',
+ type: 'danger',
+ datePrefix: 'Churned on',
+ dataAttr: 'account-churned-tag',
+ },
+ {
+ field: 'ignored_at',
+ label: 'Ignored',
+ type: 'warning',
+ datePrefix: 'Ignored since',
+ dataAttr: 'account-ignored-tag',
+ },
+] as const
+
+export function getAccountStatusTags(account: Pick<AccountApi, 'churned_at' | 'ignored_at'>): AccountStatusTag[] {
+ return STATUS_TAGS.flatMap(({ field, label, type, datePrefix, dataAttr }) => {
+ const date = account[field]
+ return date
+ ? [{ field, label, type, dataAttr, dateLabel: `${datePrefix} ${dayjs(date).format('MMM D, YYYY')}` }]
+ : []
+ })
+}
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 67226a4be624..02d68ebed3b9 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -780,10 +780,10 @@ export interface AccountApi {
*/
churned_at?: string | null
/**
- * When Track Rules ignored the account. Null means the account is tracked.
+ * When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.
* @nullable
*/
- readonly ignored_at: string | null
+ ignored_at?: string | null
readonly created_at: string
/** @nullable */
readonly created_by: number | null
@@ -993,10 +993,10 @@ export interface PatchedAccountApi {
*/
churned_at?: string | null
/**
- * When Track Rules ignored the account. Null means the account is tracked.
+ * When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.
* @nullable
*/
- readonly ignored_at?: string | null
+ ignored_at?: string | null
readonly created_at?: string
/** @nullable */
readonly created_by?: number | null
@@ -4769,6 +4769,10 @@ export type AccountsListParams = {
* When true, returns only accounts where no user actively holds any relationship.
*/
all_roles_unassigned?: boolean
+ /**
+ * When true, active and tracked accounts come before churned or ignored ones, and `ordering` applies within each group. Use with `include_churned` or `include_ignored`.
+ */
+ inactive_last?: boolean
/**
* Include churned accounts. Churned accounts are hidden by default.
*/
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index eaab9845a741..f639e709bd99 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -390,6 +390,12 @@ export const AccountsCreateBody = /* @__PURE__ */ zod
.datetime({ offset: true })
.nullish()
.describe('When the account churned. Null means the account has not churned.'),
+ ignored_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe(
+ 'When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.'
+ ),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
@@ -488,6 +494,12 @@ export const AccountsUpdateBody = /* @__PURE__ */ zod
.datetime({ offset: true })
.nullish()
.describe('When the account churned. Null means the account has not churned.'),
+ ignored_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe(
+ 'When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.'
+ ),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
@@ -557,6 +569,12 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod
.datetime({ offset: true })
.nullish()
.describe('When the account churned. Null means the account has not churned.'),
+ ignored_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe(
+ 'When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.'
+ ),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx
index fcd9b362682f..c0f4a86f5e05 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountEditModal.tsx
@@ -3,6 +3,8 @@ import { Form } from 'kea-forms'
import { LemonButton, LemonInput, LemonInputSelect, LemonModal } from '@posthog/lemon-ui'
+import { dayjs } from 'lib/dayjs'
+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { teamLogic } from 'scenes/teamLogic'
@@ -11,6 +13,11 @@ import { canEditEmailMatching } from 'products/customer_analytics/frontend/compo
import { ACCOUNT_ID_FIELDS } from './accountNativeProperties'
import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+const STATUS_DATE_FIELDS = [
+ { key: 'churned_at', label: 'Churned at', placeholder: 'Not churned' },
+ { key: 'ignored_at', label: 'Ignored at', placeholder: 'Not ignored' },
+] as const
+
export function AccountEditModal(): JSX.Element {
const { account, accountEditorOpen, accountFormHasErrors, isAccountFormSubmitting } = useValues(
customerAnalyticsAccountSceneLogic
@@ -90,6 +97,22 @@ export function AccountEditModal(): JSX.Element {
/>
)}
</LemonField>
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3">
+ {STATUS_DATE_FIELDS.map((field) => (
+ <LemonField key={field.key} name={field.key} label={field.label}>
+ {({ value, onChange }) => (
+ <LemonCalendarSelectInput
+ value={value ? dayjs(value) : null}
+ onChange={(date) => onChange(date ? date.toISOString() : null)}
+ granularity="minute"
+ clearable
+ placeholder={field.placeholder}
+ buttonProps={{ 'data-attr': `account-edit-${field.key}` }}
+ />
+ )}
+ </LemonField>
+ ))}
+ </div>
</div>
</Form>
</LemonModal>
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountStatusTags.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountStatusTags.tsx
new file mode 100644
index 000000000000..8c4e6156ab16
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountStatusTags.tsx
@@ -0,0 +1,30 @@
+import { useActions } from 'kea'
+
+import { LemonTag, Tooltip } from '@posthog/lemon-ui'
+
+import { getAccountStatusTags } from '../../components/Accounts/accountStatusTags'
+import type { AccountApi } from '../../generated/api.schemas'
+import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+
+export function AccountStatusTags({ account }: { account: AccountApi }): JSX.Element | null {
+ const { openAccountEditor } = useActions(customerAnalyticsAccountSceneLogic)
+ const statusTags = getAccountStatusTags(account)
+
+ if (statusTags.length === 0) {
+ return null
+ }
+
+ return (
+ <div className="flex items-center gap-2">
+ {statusTags.map(({ field, label, type, dateLabel, dataAttr }) => (
+ <Tooltip key={field} title={dateLabel}>
+ <button type="button" className="inline-flex cursor-pointer" onClick={openAccountEditor}>
+ <LemonTag type={type} data-attr={dataAttr}>
+ {label}
+ </LemonTag>
+ </button>
+ </Tooltip>
+ ))}
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
index ae818c4eb93a..fe42a3428da6 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
@@ -1,4 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
+import { within } from '@testing-library/dom'
+import userEvent from '@testing-library/user-event'
import { FEATURE_FLAGS } from 'lib/constants'
import { App } from 'scenes/App'
@@ -229,6 +231,38 @@ export const ExternalId: Story = {
},
}
+export const ChurnedAndIgnored: Story = {
+ render: () => <App />,
+ decorators: [
+ mswDecorator({
+ get: {
+ [ACCOUNT_RETRIEVE_ENDPOINT]: {
+ ...account,
+ churned_at: '2026-05-01T10:00:00Z',
+ ignored_at: '2026-05-15T10:00:00Z',
+ },
+ },
+ }),
+ ],
+ parameters: {
+ testOptions: {
+ waitForSelector: ['[data-attr="account-churned-tag"]', '[data-attr="account-ignored-tag"]'],
+ viewport: { width: 1280, height: 900 },
+ // The scene's tab panel is its own <main>, so the default snapshot crops out the title tags.
+ includeNavigationInSnapshot: true,
+ },
+ },
+}
+
+export const EditStatusDates: Story = {
+ ...ChurnedAndIgnored,
+ play: async ({ canvasElement }) => {
+ const tag = await within(canvasElement).findByText('Churned', {}, { timeout: 15000 })
+ await userEvent.click(tag)
+ await within(document.body).findByText('Edit account')
+ },
+}
+
export const Narrow: Story = {
render: () => <App />,
parameters: {
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
index b3c8c06bfdd0..3c69e5923d9f 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
@@ -24,6 +24,7 @@ import { AccountDetailNavigation } from './AccountDetailNavigation'
import { AccountExternalId } from './AccountExternalId'
import { AccountPresence } from './AccountPresence'
import { AccountSidebar } from './AccountSidebar'
+import { AccountStatusTags } from './AccountStatusTags'
import { AccountViewEditorModal } from './AccountViewEditorModal'
import { AccountViewTileEditorModal } from './AccountViewTileEditorModal'
import { ConfigureAccountTabsModal } from './ConfigureAccountTabsModal'
@@ -128,6 +129,7 @@ function CustomerAnalyticsAccountSceneContent(): JSX.Element {
<SceneContent className="h-full min-h-0" data-attr="customer-analytics-account-scene">
<SceneTitleSection
name={account.name}
+ nameSuffix={<AccountStatusTags account={account} />}
resourceType={{
type: 'cohort',
forceIcon: <AccountLogo domain={getAccountLogoDomain(account)} name={account.name} />,
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountNativeProperties.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountNativeProperties.ts
index 920190dcccf8..ea30304cdfd1 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountNativeProperties.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountNativeProperties.ts
@@ -1,6 +1,6 @@
import { cleanDomains, cleanEmails } from '../../components/Accounts/accountEmailMatching'
import { accountsPartialUpdate, accountsRetrieve } from '../../generated/api'
-import type { AccountApi, PatchedAccountApiProperties } from '../../generated/api.schemas'
+import type { AccountApi, PatchedAccountApi, PatchedAccountApiProperties } from '../../generated/api.schemas'
export const ACCOUNT_ID_FIELDS = [
{ key: 'website_domain', label: 'Website domain', placeholder: 'example.com' },
@@ -23,6 +23,8 @@ export type AccountNativePropertyPatch = Partial<
Pick<NonNullable<PatchedAccountApiProperties>, AccountNativePropertyKey>
>
+export type AccountTopLevelPatch = Partial<Pick<PatchedAccountApi, 'name' | 'churned_at' | 'ignored_at'>>
+
export function isAccountNativePropertyKey(key: unknown): key is AccountNativePropertyKey {
return [...ACCOUNT_ID_FIELDS, ...ACCOUNT_LIST_FIELDS].some((field) => field.key === key)
}
@@ -33,7 +35,7 @@ export async function updateAccountNativeProperties(
projectId: number,
accountId: string,
properties: AccountNativePropertyPatch,
- name?: string
+ topLevelFields: AccountTopLevelPatch = {}
): Promise<AccountApi> {
const key = `${projectId}:${accountId}`
const previous = accountWrites.get(key) ?? Promise.resolve()
@@ -57,7 +59,7 @@ export async function updateAccountNativeProperties(
}
// 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 }),
+ ...topLevelFields,
properties: { ...current.properties, ...changes },
})
})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
index 81d369785a91..fbd437d0fe3c 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
@@ -402,6 +402,29 @@ describe('customerAnalyticsAccountSceneLogic', () => {
})
})
+ it('sends only status dates that changed, including cleared ones', async () => {
+ const datedAccount = {
+ ...account,
+ churned_at: '2026-05-01T10:00:00Z',
+ ignored_at: '2026-05-15T10:00:00Z',
+ properties: {},
+ }
+ logic.actions.loadAccountSuccess(datedAccount)
+ mockAccountsRetrieve.mockResolvedValueOnce(datedAccount)
+ mockAccountsPartialUpdate.mockResolvedValue({ ...datedAccount, ignored_at: null })
+
+ logic.actions.openAccountEditor()
+ logic.actions.setAccountFormValues({ churned_at: '2026-05-01T10:00:00.000Z', ignored_at: null })
+ logic.actions.submitAccountForm()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockAccountsPartialUpdate).toHaveBeenCalledWith(String(PROJECT_ID), ACCOUNT_ID, {
+ ignored_at: null,
+ properties: {},
+ })
+ expect(logic.values.account?.ignored_at).toBeNull()
+ })
+
it('keeps the draft open when the save fails', async () => {
mockAccountsPartialUpdate.mockRejectedValue(new ApiError('Unavailable', 500))
jest.spyOn(posthog, 'captureException').mockImplementation()
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
index b2a439b94370..55ebc7e8a288 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
@@ -19,6 +19,7 @@ import posthog from 'posthog-js'
import { ApiError } from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic, FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { objectsEqual } from 'lib/utils/objects'
@@ -56,10 +57,19 @@ const ACCOUNT_PRESENCE_POLL_INTERVAL_MS = 30_000
type AccountIdFieldKey = (typeof ACCOUNT_ID_FIELDS)[number]['key']
-export type AccountEditFormValues = Record<AccountIdFieldKey, string> & {
- name: string
- email_domains: string[]
- known_emails: string[]
+const ACCOUNT_STATUS_DATE_FIELDS = ['churned_at', 'ignored_at'] as const
+
+type AccountStatusDateField = (typeof ACCOUNT_STATUS_DATE_FIELDS)[number]
+
+export type AccountEditFormValues = Record<AccountIdFieldKey, string> &
+ Record<AccountStatusDateField, string | null> & {
+ name: string
+ email_domains: string[]
+ known_emails: string[]
+ }
+
+function isSameStatusDate(left: string | null, right: string | null): boolean {
+ return left === right || (!!left && !!right && dayjs(left).isSame(dayjs(right)))
}
function getAccountEditFormValues(account: AccountApi | null): AccountEditFormValues {
@@ -72,6 +82,8 @@ function getAccountEditFormValues(account: AccountApi | null): AccountEditFormVa
stripe_customer_id: account?.properties?.stripe_customer_id ?? '',
email_domains: account?.properties?.email_domains ?? [],
known_emails: account?.properties?.known_emails ?? [],
+ churned_at: account?.churned_at ?? null,
+ ignored_at: account?.ignored_at ?? null,
}
}
@@ -328,6 +340,9 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
const changedListKeys = (['email_domains', 'known_emails'] as const).filter(
(key) => !objectsEqual(cleanedLists[key], listCleaners[key](openedValues[key]))
)
+ const changedStatusDateKeys = ACCOUNT_STATUS_DATE_FIELDS.filter(
+ (key) => !isSameStatusDate(formValues[key], openedValues[key])
+ )
const changedProperties = {
...Object.fromEntries(changedPropertyKeys.map((key) => [key, formValues[key].trim() || null])),
...Object.fromEntries(changedListKeys.map((key) => [key, cleanedLists[key]])),
@@ -336,13 +351,16 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
props.projectId,
values.account.id,
changedProperties as AccountNativePropertyPatch,
- name !== openedValues.name ? name : undefined
+ {
+ ...(name !== openedValues.name ? { name } : {}),
+ ...Object.fromEntries(changedStatusDateKeys.map((key) => [key, formValues[key]])),
+ }
)
accountPropertyUpdatesLogic.actions.accountUpdated(props.projectId, updatedAccount)
actions.loadAccountSuccess(updatedAccount)
posthog.capture(AccountsEvents.AccountEdited, {
name_changed: name !== openedValues.name,
- changed_fields: [...changedPropertyKeys, ...changedListKeys],
+ changed_fields: [...changedPropertyKeys, ...changedListKeys, ...changedStatusDateKeys],
})
},
},
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 766cb6dc9c80..5213a3555226 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1618,10 +1618,10 @@ export namespace Schemas {
*/
churned_at?: string | null;
/**
- * When Track Rules ignored the account. Null means the account is tracked.
+ * When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.
* @nullable
*/
- readonly ignored_at: string | null;
+ ignored_at?: string | null;
readonly created_at: string;
/** @nullable */
readonly created_by: number | null;
@@ -75673,10 +75673,10 @@ export namespace Schemas {
*/
churned_at?: string | null;
/**
- * When Track Rules ignored the account. Null means the account is tracked.
+ * When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.
* @nullable
*/
- readonly ignored_at?: string | null;
+ ignored_at?: string | null;
readonly created_at?: string;
/** @nullable */
readonly created_by?: number | null;
@@ -114798,6 +114798,10 @@ export namespace Schemas {
* When true, returns only accounts where no user actively holds any relationship.
*/
all_roles_unassigned?: boolean;
+ /**
+ * When true, active and tracked accounts come before churned or ignored ones, and `ordering` applies within each group. Use with `include_churned` or `include_ignored`.
+ */
+ inactive_last?: boolean;
/**
* Include churned accounts. Churned accounts are hidden by default.
*/
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index e31e2666cc5f..465b7ac65f94 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -113,6 +113,7 @@ export const AccountsListParams = () => zod.object({
),
})
+export const accountsListQueryInactiveLastDefault = false
export const accountsListQueryIncludeChurnedDefault = false
export const accountsListQueryIncludeIgnoredDefault = false
@@ -121,6 +122,12 @@ export const AccountsListQueryParams = () => zod.object({
.boolean()
.optional()
.describe('When true, returns only accounts where no user actively holds any relationship.'),
+ inactive_last: zod
+ .boolean()
+ .default(accountsListQueryInactiveLastDefault)
+ .describe(
+ 'When true, active and tracked accounts come before churned or ignored ones, and `ordering` applies within each group. Use with `include_churned` or `include_ignored`.'
+ ),
include_churned: zod
.boolean()
.default(accountsListQueryIncludeChurnedDefault)
@@ -216,6 +223,12 @@ export const AccountsCreateBody = () => zod
.datetime({ offset: true })
.nullish()
.describe('When the account churned. Null means the account has not churned.'),
+ ignored_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe(
+ 'When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.'
+ ),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
@@ -434,6 +447,12 @@ export const AccountsPartialUpdateBody = () => zod
.datetime({ offset: true })
.nullish()
.describe('When the account churned. Null means the account has not churned.'),
+ ignored_at: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe(
+ 'When the account was ignored, set by Track Rules or by hand. Null means the account is tracked.'
+ ),
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.ts
index 946921a7c4b0..8259a85865fc 100644
--- a/services/mcp/src/tools/generated/customer_analytics.ts
+++ b/services/mcp/src/tools/generated/customer_analytics.ts
@@ -210,6 +210,9 @@ const accountsCreate = (): ToolBase<ReturnType<typeof AccountsCreateSchema>, Sch
if (params.churned_at !== undefined) {
body['churned_at'] = params.churned_at
}
+ if (params.ignored_at !== undefined) {
+ body['ignored_at'] = params.ignored_at
+ }
const result = await context.api.request<Schemas.Account>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/accounts/`,
@@ -318,6 +321,7 @@ const accountsList = (): ToolBase<
path: `/api/projects/${encodeURIComponent(String(projectId))}/accounts/`,
query: {
all_roles_unassigned: params.all_roles_unassigned,
+ inactive_last: params.inactive_last,
include_churned: params.include_churned,
include_ignored: params.include_ignored,
limit: params.limit,
@@ -512,6 +516,9 @@ const accountsPartialUpdate = (): ToolBase<ReturnType<typeof AccountsPartialUpda
if (params.churned_at !== undefined) {
body['churned_at'] = params.churned_at
}
+ if (params.ignored_at !== undefined) {
+ body['ignored_at'] = params.ignored_at
+ }
const result = await context.api.request<Schemas.Account>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/accounts/${encodeURIComponent(String(params.id))}/`,