: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): add account track rules (#87301)
Arthur Moreira de Deus10661b212a71
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex ebcd960c313a..874bde332dc5 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -59,6 +59,7 @@ rules:|AccountChannelSummary|AccountRelationship|AccountRelationshipDefinition+ |AccountTrackRuleRun|Action|AgentApplication|AgentArtifact@@ -430,6 +431,7 @@ rules:|AccountChannelSummary|AccountRelationship|AccountRelationshipDefinition+ |AccountTrackRuleRun|Action|AgentApplication|AgentArtifactdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 590994544091..cf2bdd4a3bc1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6020,6 +6020,18 @@ snapshots:hash: v1.k794b7964.7b105d74e4bd6c48e6ffee982e294557b0230d3c43769a252c753745f0d8ec0a.j2wHTrpAU0iVskR8PYJPk9KNhWUYrGDbwyxM0h9015Mscenes-app-customer-analytics-journeys-nodes-profileflownode--optional-not-completed--light:hash: v1.k794b7964.165b884e9e737c00707811f9efa7d348927a432402c544b41495eac9722a1fca.wqLWQTzb1O7RBTeeyTR5l_hUeX0IpJXkgexpAQbuNWs+ scenes-app-customer-analytics-track-rules--configured--dark:+ hash: v1.k794b7964.92413e6fb8d66612327d784c9271dd19b7a8cb0b7b3d7107f6dd78f4136fade5.bpIJQ9Olj4PCyxgWtgIiVDmzh8pQhIyKAKoO9z_UABE+ scenes-app-customer-analytics-track-rules--configured--light:+ hash: v1.k794b7964.de5a3e9672100bbd083b4608693261a0e5624693afd5de70b0014a9adfa13b3e.k9pAMbCur-xOSs_utBsXvuCXde14rcNor-R-C89EedA+ scenes-app-customer-analytics-track-rules--feature-gate-off--dark:+ hash: v1.k794b7964.247e31dff1b806907ec4c327f1ad132fc186861cbe8f2265fa05296f1aa2a95b.KZZKeqM5D6IpwNrMdlEf5EbTm6KGmcdapADEzg755Gw+ scenes-app-customer-analytics-track-rules--feature-gate-off--light:+ hash: v1.k794b7964.5bf2ef575702ea1997fa9c147c10662b40445407894616a915c9e330cbc8c06a.0vS8B765QPDhC4h_KtJPlL5o3f5b_PZ-giJD2DPRkd4+ scenes-app-customer-analytics-track-rules--preview--dark:+ hash: v1.k794b7964.4d60ac636f3d4b309108ff038058f81c38dfd65d4badfb9dcf780b2dedf88c25.ZUVE6wN40QhrIaL0iR-shEMXZja7utjNvptDYTLVxPY+ scenes-app-customer-analytics-track-rules--preview--light:+ hash: v1.k794b7964.f3e9732eec6742b719985abae4f9cc65b75c83ede8dbd6747d5de837683b8535.dIq1nmuGMZsPilVhqTSflVsNnWIqT2tCutG50_HjX7Iscenes-app-data-management--data-warehouse-managed-viewsets--dark:hash: v1.k794b7964.c8b8c112665a993ec00602d6f00602775548a3aa782ae541e4738e879b5a1107.KTg2KYEs4UHmHOuVj0Py_3WERNbAjQ1UQHf5n6yxhScscenes-app-data-management--data-warehouse-managed-viewsets--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 812921c54980..f93a6271ff81 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -283,6 +283,7 @@ export const FEATURE_FLAGS = {CUSTOMER_ANALYTICS_CSP: 'customer-analytics-csp', // owner: @arthurdedeus #team-customer-analytics, gates the Customer analytics > Accounts settings tab (account_group_type_index dropdown)CUSTOMER_ANALYTICS_FEATURE_REQUESTS: 'customer-analytics-feature-requests',CUSTOMER_ANALYTICS_JOURNEYS: 'customer-analytics-journeys', // owner: @arthurdedeus #team-customer-analytics+ CUSTOMER_ANALYTICS_TRACK_RULES: 'customer-analytics-track-rules', // owner: @arthurdedeus #team-customer-analyticsCUSTOMER_PROFILE_CONFIG_BUTTON: 'customer-profile-config-button', // owner: @arthurdedeus #team-customer-analyticsDASHBOARD_AUTO_PREVIEW_LIMIT: 'dashboard-auto-preview-limit', // owner: @pauldambra #team-product-analyticsDASHBOARD_CUSTOMIZATION: 'dashboard-customization', // owner: @MattPua #team-analytics-platformdiff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 895782cf04ac..802019598d13 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -49,6 +49,7 @@ import { GeneralSection } from 'products/conversations/frontend/scenes/settings/import { NotificationsSection } from 'products/conversations/frontend/scenes/settings/NotificationsSection'import { ZendeskImportSection } from 'products/conversations/frontend/scenes/settings/ZendeskImportSection'import { CustomerAnalyticsEventStream } from 'products/customer_analytics/frontend/components/EventStream/CustomerAnalyticsEventStream'+import { AccountTrackRules } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules'import { CustomerAnalyticsAccountConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig'import {WarehouseGroupPropertiesSetting,@@ -454,6 +455,14 @@ export const SETTINGS_MAP: SettingSection[] = [flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],keywords: ['accounts', 'group', 'b2b'],},+ {+ id: 'customer-analytics-track-rules',+ title: 'Track rules',+ description: 'Choose which active accounts appear in Customer analytics.',+ component: <AccountTrackRules />,+ flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_TRACK_RULES'],+ keywords: ['accounts', 'track', 'ignore', 'rules', 'filter'],+ },{id: 'customer-analytics-calendar-sync',title: 'Google account sync',diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex e1583f172e7d..7f90db2ffbfe 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -127,6 +127,7 @@ export type SettingId =| 'customer-analytics-event-stream'| 'customer-analytics-group-properties'| 'customer-analytics-person-properties'+ | 'customer-analytics-track-rules'| 'customer-analytics-usage-metrics'| 'customization-irl'| 'data-theme'diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.pyindex 2a4b6ab63a92..24c74009e4a3 100644--- a/products/customer_analytics/backend/constants.py+++ b/products/customer_analytics/backend/constants.py@@ -8,6 +8,7 @@ SLACK_ARCHIVES_ORIGIN = "https://posthog.slack.com/archives"# Mirrors frontend `FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP`.CUSTOMER_ANALYTICS_CSP_FLAG = "customer-analytics-csp"CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG = "customer-analytics-feature-requests"+CUSTOMER_ANALYTICS_TRACK_RULES_FLAG = "customer-analytics-track-rules"# Mirrors frontend `FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES`. Gates the whole warehouse -> person# properties feature: creating person-target custom property sources (API + UI), staging rows duringdiff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex aa55def0b967..21670c3551d3 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -17,7 +17,7 @@ Do NOT:import asynciofrom collections.abc import Iterable-from datetime import UTC, datetime, time, timedelta+from datetime import UTC, datetime, timedeltafrom enum import Enumfrom typing import TYPE_CHECKING, Any, Optional, castfrom uuid import UUID@@ -55,7 +55,6 @@ from django.db.models import (from django.db.models.fields.json import KeyTextTransformfrom django.db.models.functions import Coalescefrom django.utils import timezone-from django.utils.dateparse import parse_date, parse_datetimeimport structlogfrom celery import current_app@@ -97,12 +96,14 @@ from products.customer_analytics.backend.facade.contracts import ()from products.customer_analytics.backend.facade.email_matching import schedule_email_thread_link_recalculationfrom products.customer_analytics.backend.logic import (+ account_track_rules as _account_track_rules_logic,announcements as _announcements_logic,channel_summaries as _channel_summaries_logic,custom_property_values as _custom_property_values_logic,feature_requests as _feature_requests_logic,relationships as _relationships_logic,)+from products.customer_analytics.backend.logic.account_filters import InvalidAccountFilter, apply_account_filtersfrom products.customer_analytics.backend.logic.custom_property_definitions import (apply_option_side_effects,coerce_is_big_number,@@ -2688,221 +2689,12 @@ def _validate_account_table_definitions(return custom_property_display_types-ACCOUNT_TABLE_TEXT_FIELDS = frozenset(- {- contracts.AccountTableField.NAME,- contracts.AccountTableField.EXTERNAL_ID,- contracts.AccountTableField.STRIPE_CUSTOMER_ID,- contracts.AccountTableField.HUBSPOT_DEAL_ID,- contracts.AccountTableField.BILLING_ID,- contracts.AccountTableField.SFDC_ID,- contracts.AccountTableField.ZENDESK_ID,- }-)-ACCOUNT_TABLE_DATETIME_FIELDS = frozenset(- {- contracts.AccountTableField.CREATED_AT,- contracts.AccountTableField.UPDATED_AT,- contracts.AccountTableField.CHURNED_AT,- contracts.AccountTableField.IGNORED_AT,- }-)-ACCOUNT_TABLE_DIRECT_FIELDS = {- contracts.AccountTableField.NAME: "name",- contracts.AccountTableField.EXTERNAL_ID: "external_id",- contracts.AccountTableField.CREATED_AT: "created_at",- contracts.AccountTableField.UPDATED_AT: "updated_at",- contracts.AccountTableField.CHURNED_AT: "churned_at",- contracts.AccountTableField.IGNORED_AT: "ignored_at",-}---def _coerce_datetime_filter_value(value: float | bool | str) -> datetime:- if not isinstance(value, str):- raise InvalidAccountTableColumn("Date filters require ISO-8601 values.")- parsed_datetime = parse_datetime(value)- if parsed_datetime is None:- parsed_date = parse_date(value)- if parsed_date is None:- raise InvalidAccountTableColumn("Date filters require ISO-8601 values.")- parsed_datetime = datetime.combine(parsed_date, time.min, tzinfo=UTC)- elif timezone.is_naive(parsed_datetime):- parsed_datetime = timezone.make_aware(parsed_datetime, UTC)- return parsed_datetime---def _apply_account_table_field_filter(- queryset: QuerySet[Account], filter_: contracts.AccountTableFieldFilter-) -> QuerySet[Account]:- field = filter_.field- operator = filter_.operator- values = filter_.values- field_lookup = ACCOUNT_TABLE_DIRECT_FIELDS.get(field)- if field_lookup is None:- field_lookup = f"_account_table_filter_{field.value}"- queryset = queryset.annotate(**{field_lookup: KeyTextTransform(field.value, "_properties")})-- if operator == contracts.AccountTableFieldOperator.IS_SET:- return queryset.filter(**{f"{field_lookup}__isnull": False})- if operator == contracts.AccountTableFieldOperator.IS_NOT_SET:- return queryset.filter(**{f"{field_lookup}__isnull": True})- if not values:- raise InvalidAccountTableColumn("Account field filters require at least one value.")-- if field in ACCOUNT_TABLE_TEXT_FIELDS:- if operator == contracts.AccountTableFieldOperator.EXACT:- return queryset.filter(**{f"{field_lookup}__in": values})- if operator == contracts.AccountTableFieldOperator.IS_NOT:- return queryset.filter(Q(**{f"{field_lookup}__isnull": True}) | ~Q(**{f"{field_lookup}__in": values}))- if operator in {- contracts.AccountTableFieldOperator.CONTAINS,- contracts.AccountTableFieldOperator.DOES_NOT_CONTAIN,- }:- predicate = Q()- for value in values:- predicate |= Q(**{f"{field_lookup}__icontains": value})- if operator == contracts.AccountTableFieldOperator.DOES_NOT_CONTAIN:- return queryset.filter(Q(**{f"{field_lookup}__isnull": True}) | ~predicate)- return queryset.filter(predicate)- raise InvalidAccountTableColumn(f"Operator {operator.value} does not support text account fields.")-- if field in ACCOUNT_TABLE_DATETIME_FIELDS:- if len(values) != 1:- raise InvalidAccountTableColumn("Date account field filters require one value.")- target = _coerce_datetime_filter_value(values[0])- if operator == contracts.AccountTableFieldOperator.DATE_EXACT:- target_date = target.replace(hour=0, minute=0, second=0, microsecond=0)- return queryset.filter(- **{f"{field_lookup}__gte": target_date, f"{field_lookup}__lt": target_date + timedelta(days=1)}- )- lookup = {- contracts.AccountTableFieldOperator.DATE_BEFORE: "lt",- contracts.AccountTableFieldOperator.DATE_AFTER: "gt",- }.get(operator)- if lookup is None:- raise InvalidAccountTableColumn(f"Operator {operator.value} does not support date account fields.")- return queryset.filter(**{f"{field_lookup}__{lookup}": target})-- raise InvalidAccountTableColumn(f"Unsupported account table field: {field.value}")--def _filters_account_table_field(filters: tuple[contracts.AccountTableFilter, ...], field: contracts.AccountTableField) -> bool:return any(isinstance(filter_, contracts.AccountTableFieldFilter) and filter_.field == field for filter_ in filters)-def _coerce_custom_property_filter_values(- filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType-) -> tuple[float | bool | str | datetime, ...]:- data_type = DATA_TYPE_BY_DISPLAY_TYPE[display_type]- values = filter_.values- if filter_.operator in {- contracts.AccountTableCustomPropertyOperator.IS_SET,- contracts.AccountTableCustomPropertyOperator.IS_NOT_SET,- }:- return ()- if not values:- raise InvalidAccountTableColumn("Custom property filters require at least one value.")-- if data_type == DataType.NUMERIC:- if any(isinstance(value, bool) for value in values):- raise InvalidAccountTableColumn("Numeric custom property filters require numeric values.")- try:- return tuple(float(value) for value in values)- except (TypeError, ValueError) as error:- raise InvalidAccountTableColumn("Numeric custom property filters require numeric values.") from error- if data_type == DataType.BOOLEAN:- coerced: list[bool] = []- for value in values:- if isinstance(value, bool):- coerced.append(value)- elif str(value).lower() in {"true", "1"}:- coerced.append(True)- elif str(value).lower() in {"false", "0"}:- coerced.append(False)- else:- raise InvalidAccountTableColumn("Boolean custom property filters require true or false values.")- return tuple(coerced)- if data_type == DataType.DATETIME:- return tuple(_coerce_datetime_filter_value(value) for value in values)- return tuple(str(value) for value in values)---def _custom_property_filter_predicate(- filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType-) -> tuple[Q, bool]:- operator = filter_.operator- data_type = DATA_TYPE_BY_DISPLAY_TYPE[display_type]- values = _coerce_custom_property_filter_values(filter_, display_type)- value_field = {- DataType.STRING: "value_str",- DataType.NUMERIC: "value_num",- DataType.BOOLEAN: "value_bool",- DataType.DATETIME: "value_datetime",- }[data_type]-- if operator == contracts.AccountTableCustomPropertyOperator.IS_SET:- return Q(), False- if operator == contracts.AccountTableCustomPropertyOperator.IS_NOT_SET:- return Q(), True- if operator in {- contracts.AccountTableCustomPropertyOperator.EXACT,- contracts.AccountTableCustomPropertyOperator.IS_NOT,- }:- return Q(**{f"{value_field}__in": values}), operator == contracts.AccountTableCustomPropertyOperator.IS_NOT- if operator in {- contracts.AccountTableCustomPropertyOperator.REGEX,- contracts.AccountTableCustomPropertyOperator.NOT_REGEX,- }:- raise InvalidAccountTableColumn("Regex custom property filters are not supported by account table queries.")- if operator in {- contracts.AccountTableCustomPropertyOperator.CONTAINS,- contracts.AccountTableCustomPropertyOperator.DOES_NOT_CONTAIN,- }:- if data_type != DataType.STRING:- raise InvalidAccountTableColumn("Contains operators require a text custom property.")- predicate = Q()- for value in values:- predicate |= Q(value_str__icontains=value)- return predicate, operator == contracts.AccountTableCustomPropertyOperator.DOES_NOT_CONTAIN- if operator in {- contracts.AccountTableCustomPropertyOperator.GREATER_THAN,- contracts.AccountTableCustomPropertyOperator.GREATER_THAN_OR_EQUAL,- contracts.AccountTableCustomPropertyOperator.LESS_THAN,- contracts.AccountTableCustomPropertyOperator.LESS_THAN_OR_EQUAL,- }:- if data_type != DataType.NUMERIC:- raise InvalidAccountTableColumn("Comparison operators require a numeric custom property.")- if len(values) != 1:- raise InvalidAccountTableColumn("Numeric comparison filters require one value.")- lookup = {- contracts.AccountTableCustomPropertyOperator.GREATER_THAN: "gt",- contracts.AccountTableCustomPropertyOperator.GREATER_THAN_OR_EQUAL: "gte",- contracts.AccountTableCustomPropertyOperator.LESS_THAN: "lt",- contracts.AccountTableCustomPropertyOperator.LESS_THAN_OR_EQUAL: "lte",- }[operator]- return Q(**{f"value_num__{lookup}": values[0]}), False- if operator in {- contracts.AccountTableCustomPropertyOperator.DATE_EXACT,- contracts.AccountTableCustomPropertyOperator.DATE_BEFORE,- contracts.AccountTableCustomPropertyOperator.DATE_AFTER,- }:- if data_type != DataType.DATETIME:- raise InvalidAccountTableColumn("Date operators require a date or datetime custom property.")- if len(values) != 1:- raise InvalidAccountTableColumn("Date comparison filters require one value.")- if operator == contracts.AccountTableCustomPropertyOperator.DATE_EXACT:- target_date = cast(datetime, values[0]).replace(hour=0, minute=0, second=0, microsecond=0)- return Q(value_datetime__gte=target_date, value_datetime__lt=target_date + timedelta(days=1)), False- lookup = {- contracts.AccountTableCustomPropertyOperator.DATE_BEFORE: "lt",- contracts.AccountTableCustomPropertyOperator.DATE_AFTER: "gt",- }[operator]- return Q(**{f"value_datetime__{lookup}": values[0]}), False- raise InvalidAccountTableColumn(f"Unsupported custom property filter operator: {operator.value}")--def _apply_account_table_filters(queryset: QuerySet[Account],*,@@ -2910,39 +2702,15 @@ def _apply_account_table_filters(filters: tuple[contracts.AccountTableFilter, ...],custom_property_display_types: dict[UUID, DisplayType],) -> QuerySet[Account]:- active_relationships = AccountRelationship.objects.for_team(team_id).filter(- account_id=OuterRef("pk"), ended_at__isnull=True, user_id__isnull=False- )- for filter_ in filters:- if isinstance(filter_, contracts.AccountTableSearchFilter):- query = filter_.query.strip()- if query:- queryset = queryset.filter(Q(name__icontains=query) | Q(external_id__icontains=query))- elif isinstance(filter_, contracts.AccountTableTagsFilter):- if filter_.tag_names:- matching_tags = TaggedItem.objects.filter(- account_id=OuterRef("pk"), tag__team_id=team_id, tag__name__in=filter_.tag_names- )- queryset = queryset.filter(Exists(matching_tags))- elif isinstance(filter_, contracts.AccountTableAssignedToFilter):- if filter_.user_ids:- queryset = queryset.filter(Exists(active_relationships.filter(user_id__in=filter_.user_ids)))- elif isinstance(filter_, contracts.AccountTableUnassignedFilter):- queryset = queryset.filter(~Exists(active_relationships))- elif isinstance(filter_, contracts.AccountTableAccountIdFilter):- queryset = queryset.filter(id=filter_.account_id)- elif isinstance(filter_, contracts.AccountTableFieldFilter):- queryset = _apply_account_table_field_filter(queryset, filter_)- elif isinstance(filter_, contracts.AccountTableCustomPropertyFilter):- active_values = CustomPropertyValue.objects.for_team(team_id).filter(- account_id=OuterRef("pk"), definition_id=filter_.definition_id, is_deleted=False- )- predicate, negate_exists = _custom_property_filter_predicate(- filter_, custom_property_display_types[filter_.definition_id]- )- matching_values = active_values.filter(predicate)- queryset = queryset.filter(~Exists(matching_values) if negate_exists else Exists(matching_values))- return queryset+ try:+ return apply_account_filters(+ queryset,+ team_id=team_id,+ filters=filters,+ custom_property_display_types=custom_property_display_types,+ )+ except InvalidAccountFilter as error:+ raise InvalidAccountTableColumn(str(error)) from errordef _custom_property_sort_output_field(display_type: DisplayType) -> Field:@@ -3940,6 +3708,95 @@ def get_account_email_thread_messages(return list_account_email_thread_messages(team_id, account_id, thread_id, offset=offset, limit=limit)+AccountTrackRuleValidationError = _account_track_rules_logic.AccountTrackRuleValidationError+AccountTrackRuleVersionConflict = _account_track_rules_logic.AccountTrackRuleVersionConflict+AccountTrackRuleRunError = _account_track_rules_logic.AccountTrackRuleRunError+++class AccountTrackRuleRunAlreadyActive(ValueError):+ pass+++def get_account_track_rules(team_id: int) -> contracts.AccountTrackRulesConfig:+ return _account_track_rules_logic.get_account_track_rules(team_id)+++def update_account_track_rules(+ *,+ team_id: int,+ raw_config: dict[str, Any],+ user: "User",+ organization_id: UUID,+ was_impersonated: bool,+) -> contracts.AccountTrackRulesConfig:+ return _account_track_rules_logic.update_account_track_rules(+ team_id=team_id,+ raw_config=raw_config,+ user=user,+ organization_id=organization_id,+ was_impersonated=was_impersonated,+ )+++def preview_account_track_rules(+ team_id: int, raw_config: dict[str, Any] | None = None+) -> contracts.AccountTrackRulePreview:+ return _account_track_rules_logic.preview_account_track_rules(team_id, raw_config)+++def list_account_track_rule_runs(+ team_id: int, *, offset: int, limit: int+) -> tuple[list[contracts.AccountTrackRuleRunView], int]:+ return _account_track_rules_logic.list_account_track_rule_runs(team_id, offset=offset, limit=limit)+++def trigger_account_track_rule_run(+ *,+ team_id: int,+ idempotency_key: UUID,+ user_id: int,+) -> tuple[contracts.AccountTrackRuleRunView, bool]:+ run, created = _account_track_rules_logic.create_account_track_rule_run(+ team_id=team_id,+ idempotency_key=idempotency_key,+ user_id=user_id,+ )+ if not created:+ return _account_track_rules_logic.to_run_view(run), False++ from posthog.temporal.common.client import sync_connect # noqa: PLC0415++ from products.customer_analytics.backend.temporal.account_track_rules import ( # noqa: PLC0415+ AccountTrackRuleEvaluationInput,+ AccountTrackRuleEvaluationWorkflow,+ account_track_rule_workflow_id,+ )++ try:+ client = sync_connect()+ asyncio.run(+ client.start_workflow(+ AccountTrackRuleEvaluationWorkflow.run,+ AccountTrackRuleEvaluationInput(+ team_id=team_id,+ run_id=str(run.id),+ config_version=run.config_version,+ ),+ id=account_track_rule_workflow_id(team_id),+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ )+ except WorkflowAlreadyStartedError as error:+ _account_track_rules_logic.fail_account_track_rule_run(team_id, run.id)+ raise AccountTrackRuleRunAlreadyActive("Another Track Rules run is already in progress.") from error+ except Exception:+ _account_track_rules_logic.fail_account_track_rule_run(team_id, run.id)+ raise+ return _account_track_rules_logic.to_run_view(run), True++def list_calendar_sync_statuses(team_id: int) -> list[contracts.CalendarSyncStatus]:"""Sync state of every connected calendar for the team: last completed sync andwhether a run is currently in flight (started but not finished, within the syncdiff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.pyindex 96f880543935..f051895f6e51 100644--- a/products/customer_analytics/backend/facade/constants.py+++ b/products/customer_analytics/backend/facade/constants.py@@ -12,6 +12,7 @@ from products.customer_analytics.backend.constants import (CUSTOM_PROPERTY_OPTION_COLORS,CUSTOMER_ANALYTICS_CSP_FLAG,CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG,+ CUSTOMER_ANALYTICS_TRACK_RULES_FLAG,DEFAULT_ACTIVITY_EVENT,MAX_ANNOUNCEMENT_CHANNELS,SLACK_ARCHIVES_ORIGIN,@@ -25,6 +26,7 @@ __all__ = ["CUSTOM_PROPERTY_OPTION_COLORS","CUSTOMER_ANALYTICS_CSP_FLAG","CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG",+ "CUSTOMER_ANALYTICS_TRACK_RULES_FLAG","DEFAULT_ACTIVITY_EVENT","MAX_ANNOUNCEMENT_CHANNELS","SLACK_ARCHIVES_ORIGIN",diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 28452efc7c8c..0bef9a098339 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -290,6 +290,79 @@ AccountTableFilter = ()+class AccountTrackRuleFieldKind(str, Enum):+ ACCOUNT_FIELD = "account_field"+ CUSTOM_PROPERTY = "custom_property"+++@dataclass(frozen=True, kw_only=True)+class AccountTrackRuleField:+ kind: AccountTrackRuleFieldKind+ field: AccountTableField | None = None+ definition_id: UUID | None = None+++@dataclass(frozen=True, kw_only=True)+class AccountTrackRuleCondition:+ field: AccountTrackRuleField+ operator: str+ values: tuple[float | bool | str, ...] = ()+++@dataclass(frozen=True, kw_only=True)+class AccountTrackRuleGroup:+ conditions: tuple[AccountTrackRuleCondition, ...]+++@dataclass(frozen=True, kw_only=True)+class AccountTrackRulesConfig:+ schema_version: int = 1+ version: int = 0+ enabled: bool = False+ groups: tuple[AccountTrackRuleGroup, ...] = ()+++@dataclass(frozen=True, kw_only=True)+class AccountTrackRuleSample:+ id: UUID+ name: str+ external_id: str | None+ rule_values: dict[str, float | bool | str | None]+++@dataclass(frozen=True, kw_only=True)+class AccountTrackRulePreview:+ config_version: int+ eligible_active: int+ skipped_churned: int+ tracked: int+ ignored: int+ newly_ignored: int+ restored: int+ tracked_samples: tuple[AccountTrackRuleSample, ...]+ ignored_samples: tuple[AccountTrackRuleSample, ...]+ validation_errors: tuple[str, ...] = ()+++@dataclass(frozen=True, kw_only=True)+class AccountTrackRuleRunView:+ id: UUID+ config_version: int+ trigger: str+ status: str+ eligible_active: int+ skipped_churned: int+ tracked: int+ ignored: int+ newly_ignored: int+ restored: int+ started_at: datetime | None+ finished_at: datetime | None+ error: str | None+ created_by: int | None+ created_at: datetime++class AccountTableSortKind(str, Enum):ACCOUNT_FIELD = "account_field"TAGS = "tags"diff --git a/products/customer_analytics/backend/logic/account_filters.py b/products/customer_analytics/backend/logic/account_filters.pynew file mode 100644index 000000000000..e695c6943377--- /dev/null+++ b/products/customer_analytics/backend/logic/account_filters.py@@ -0,0 +1,286 @@+from datetime import UTC, datetime, time, timedelta+from typing import cast+from uuid import UUID++from django.db.models import Exists, OuterRef, Q, QuerySet+from django.db.models.fields.json import KeyTextTransform+from django.utils import timezone+from django.utils.dateparse import parse_date, parse_datetime++from posthog.models.tagged_item import TaggedItem++from products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.models import Account, AccountRelationship, CustomPropertyValue, DisplayType+from products.customer_analytics.backend.models.custom_property_definition import DATA_TYPE_BY_DISPLAY_TYPE, DataType+++class InvalidAccountFilter(ValueError):+ pass+++ACCOUNT_TEXT_FIELDS = frozenset(+ {+ contracts.AccountTableField.NAME,+ contracts.AccountTableField.EXTERNAL_ID,+ contracts.AccountTableField.STRIPE_CUSTOMER_ID,+ contracts.AccountTableField.HUBSPOT_DEAL_ID,+ contracts.AccountTableField.BILLING_ID,+ contracts.AccountTableField.SFDC_ID,+ contracts.AccountTableField.ZENDESK_ID,+ }+)+ACCOUNT_DATETIME_FIELDS = frozenset(+ {+ contracts.AccountTableField.CREATED_AT,+ contracts.AccountTableField.UPDATED_AT,+ contracts.AccountTableField.CHURNED_AT,+ contracts.AccountTableField.IGNORED_AT,+ }+)+ACCOUNT_DIRECT_FIELDS = {+ contracts.AccountTableField.NAME: "name",+ contracts.AccountTableField.EXTERNAL_ID: "external_id",+ contracts.AccountTableField.CREATED_AT: "created_at",+ contracts.AccountTableField.UPDATED_AT: "updated_at",+ contracts.AccountTableField.CHURNED_AT: "churned_at",+ contracts.AccountTableField.IGNORED_AT: "ignored_at",+}+++def _coerce_datetime_filter_value(value: float | bool | str) -> datetime:+ if not isinstance(value, str):+ raise InvalidAccountFilter("Date filters require ISO-8601 values.")+ parsed_datetime = parse_datetime(value)+ if parsed_datetime is None:+ parsed_date = parse_date(value)+ if parsed_date is None:+ raise InvalidAccountFilter("Date filters require ISO-8601 values.")+ parsed_datetime = datetime.combine(parsed_date, time.min, tzinfo=UTC)+ elif timezone.is_naive(parsed_datetime):+ parsed_datetime = timezone.make_aware(parsed_datetime, UTC)+ return parsed_datetime+++def _apply_account_field_filter(+ queryset: QuerySet[Account], filter_: contracts.AccountTableFieldFilter+) -> QuerySet[Account]:+ field = filter_.field+ operator = filter_.operator+ values = filter_.values+ field_lookup = ACCOUNT_DIRECT_FIELDS.get(field)+ if field_lookup is None:+ field_lookup = f"_account_filter_{field.value}"+ queryset = queryset.annotate(**{field_lookup: KeyTextTransform(field.value, "_properties")})++ if operator == contracts.AccountTableFieldOperator.IS_SET:+ return queryset.filter(**{f"{field_lookup}__isnull": False}) # nosemgrep: orm-field-injection -- enum allowlist+ if operator == contracts.AccountTableFieldOperator.IS_NOT_SET:+ return queryset.filter(**{f"{field_lookup}__isnull": True}) # nosemgrep: orm-field-injection -- enum allowlist+ if not values:+ raise InvalidAccountFilter("Account field filters require at least one value.")++ if field in ACCOUNT_TEXT_FIELDS:+ if operator == contracts.AccountTableFieldOperator.EXACT:+ return queryset.filter( # nosemgrep: orm-field-injection -- enum allowlist+ **{f"{field_lookup}__in": values} # nosemgrep: orm-field-injection -- enum allowlist+ )+ if operator == contracts.AccountTableFieldOperator.IS_NOT:+ return queryset.filter( # nosemgrep: orm-field-injection -- enum allowlist+ Q(**{f"{field_lookup}__isnull": True}) # nosemgrep: orm-field-injection -- enum allowlist+ | ~Q(**{f"{field_lookup}__in": values}) # nosemgrep: orm-field-injection -- enum allowlist+ )+ if operator in {+ contracts.AccountTableFieldOperator.CONTAINS,+ contracts.AccountTableFieldOperator.DOES_NOT_CONTAIN,+ }:+ predicate = Q()+ for value in values:+ predicate |= Q( # nosemgrep: orm-field-injection -- enum allowlist+ **{f"{field_lookup}__icontains": value} # nosemgrep: orm-field-injection -- enum allowlist+ )+ if operator == contracts.AccountTableFieldOperator.DOES_NOT_CONTAIN:+ return queryset.filter( # nosemgrep: orm-field-injection -- enum allowlist+ Q(**{f"{field_lookup}__isnull": True}) # nosemgrep: orm-field-injection -- enum allowlist+ | ~predicate+ )+ return queryset.filter(predicate)+ raise InvalidAccountFilter(f"Operator {operator.value} does not support text account fields.")++ if field in ACCOUNT_DATETIME_FIELDS:+ if len(values) != 1:+ raise InvalidAccountFilter("Date account field filters require one value.")+ target = _coerce_datetime_filter_value(values[0])+ if operator == contracts.AccountTableFieldOperator.DATE_EXACT:+ target_date = target.replace(hour=0, minute=0, second=0, microsecond=0)+ return queryset.filter(+ **{f"{field_lookup}__gte": target_date, f"{field_lookup}__lt": target_date + timedelta(days=1)}+ )+ lookup = {+ contracts.AccountTableFieldOperator.DATE_BEFORE: "lt",+ contracts.AccountTableFieldOperator.DATE_AFTER: "gt",+ }.get(operator)+ if lookup is None:+ raise InvalidAccountFilter(f"Operator {operator.value} does not support date account fields.")+ return queryset.filter( # nosemgrep: orm-field-injection -- enum allowlists+ **{f"{field_lookup}__{lookup}": target} # nosemgrep: orm-field-injection -- enum allowlists+ )++ raise InvalidAccountFilter(f"Unsupported account field: {field.value}")+++def _coerce_custom_property_filter_values(+ filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType+) -> tuple[float | bool | str | datetime, ...]:+ data_type = DATA_TYPE_BY_DISPLAY_TYPE[display_type]+ values = filter_.values+ if filter_.operator in {+ contracts.AccountTableCustomPropertyOperator.IS_SET,+ contracts.AccountTableCustomPropertyOperator.IS_NOT_SET,+ }:+ return ()+ if not values:+ raise InvalidAccountFilter("Custom property filters require at least one value.")++ if data_type == DataType.NUMERIC:+ if any(isinstance(value, bool) for value in values):+ raise InvalidAccountFilter("Numeric custom property filters require numeric values.")+ try:+ return tuple(float(value) for value in values)+ except (TypeError, ValueError) as error:+ raise InvalidAccountFilter("Numeric custom property filters require numeric values.") from error+ if data_type == DataType.BOOLEAN:+ coerced: list[bool] = []+ for value in values:+ if isinstance(value, bool):+ coerced.append(value)+ elif str(value).lower() in {"true", "1"}:+ coerced.append(True)+ elif str(value).lower() in {"false", "0"}:+ coerced.append(False)+ else:+ raise InvalidAccountFilter("Boolean custom property filters require true or false values.")+ return tuple(coerced)+ if data_type == DataType.DATETIME:+ return tuple(_coerce_datetime_filter_value(value) for value in values)+ return tuple(str(value) for value in values)+++def _custom_property_filter_predicate(+ filter_: contracts.AccountTableCustomPropertyFilter, display_type: DisplayType+) -> tuple[Q, bool]:+ operator = filter_.operator+ data_type = DATA_TYPE_BY_DISPLAY_TYPE[display_type]+ values = _coerce_custom_property_filter_values(filter_, display_type)+ value_field = {+ DataType.STRING: "value_str",+ DataType.NUMERIC: "value_num",+ DataType.BOOLEAN: "value_bool",+ DataType.DATETIME: "value_datetime",+ }[data_type]++ if operator == contracts.AccountTableCustomPropertyOperator.IS_SET:+ return Q(), False+ if operator == contracts.AccountTableCustomPropertyOperator.IS_NOT_SET:+ return Q(), True+ if operator in {+ contracts.AccountTableCustomPropertyOperator.EXACT,+ contracts.AccountTableCustomPropertyOperator.IS_NOT,+ }:+ return ( # nosemgrep: orm-field-injection -- data-type allowlist+ Q(**{f"{value_field}__in": values}), # nosemgrep: orm-field-injection -- data-type allowlist+ operator == contracts.AccountTableCustomPropertyOperator.IS_NOT,+ )+ if operator in {+ contracts.AccountTableCustomPropertyOperator.REGEX,+ contracts.AccountTableCustomPropertyOperator.NOT_REGEX,+ }:+ raise InvalidAccountFilter("Regex custom property filters are not supported by account queries.")+ if operator in {+ contracts.AccountTableCustomPropertyOperator.CONTAINS,+ contracts.AccountTableCustomPropertyOperator.DOES_NOT_CONTAIN,+ }:+ if data_type != DataType.STRING:+ raise InvalidAccountFilter("Contains operators require a text custom property.")+ predicate = Q()+ for value in values:+ predicate |= Q(value_str__icontains=value)+ return predicate, operator == contracts.AccountTableCustomPropertyOperator.DOES_NOT_CONTAIN+ if operator in {+ contracts.AccountTableCustomPropertyOperator.GREATER_THAN,+ contracts.AccountTableCustomPropertyOperator.GREATER_THAN_OR_EQUAL,+ contracts.AccountTableCustomPropertyOperator.LESS_THAN,+ contracts.AccountTableCustomPropertyOperator.LESS_THAN_OR_EQUAL,+ }:+ if data_type != DataType.NUMERIC:+ raise InvalidAccountFilter("Comparison operators require a numeric custom property.")+ if len(values) != 1:+ raise InvalidAccountFilter("Numeric comparison filters require one value.")+ lookup = {+ contracts.AccountTableCustomPropertyOperator.GREATER_THAN: "gt",+ contracts.AccountTableCustomPropertyOperator.GREATER_THAN_OR_EQUAL: "gte",+ contracts.AccountTableCustomPropertyOperator.LESS_THAN: "lt",+ contracts.AccountTableCustomPropertyOperator.LESS_THAN_OR_EQUAL: "lte",+ }[operator]+ return Q(**{f"value_num__{lookup}": values[0]}), False # nosemgrep: orm-field-injection -- operator allowlist+ if operator in {+ contracts.AccountTableCustomPropertyOperator.DATE_EXACT,+ contracts.AccountTableCustomPropertyOperator.DATE_BEFORE,+ contracts.AccountTableCustomPropertyOperator.DATE_AFTER,+ }:+ if data_type != DataType.DATETIME:+ raise InvalidAccountFilter("Date operators require a date or datetime custom property.")+ if len(values) != 1:+ raise InvalidAccountFilter("Date comparison filters require one value.")+ if operator == contracts.AccountTableCustomPropertyOperator.DATE_EXACT:+ target_date = cast(datetime, values[0]).replace(hour=0, minute=0, second=0, microsecond=0)+ return Q(value_datetime__gte=target_date, value_datetime__lt=target_date + timedelta(days=1)), False+ lookup = {+ contracts.AccountTableCustomPropertyOperator.DATE_BEFORE: "lt",+ contracts.AccountTableCustomPropertyOperator.DATE_AFTER: "gt",+ }[operator]+ return Q( # nosemgrep: orm-field-injection -- operator allowlist+ **{f"value_datetime__{lookup}": values[0]} # nosemgrep: orm-field-injection -- operator allowlist+ ), False+ raise InvalidAccountFilter(f"Unsupported custom property filter operator: {operator.value}")+++def apply_account_filters(+ queryset: QuerySet[Account],+ *,+ team_id: int,+ filters: tuple[contracts.AccountTableFilter, ...],+ custom_property_display_types: dict[UUID, DisplayType],+) -> QuerySet[Account]:+ active_relationships = AccountRelationship.objects.for_team(team_id).filter(+ account_id=OuterRef("pk"), ended_at__isnull=True, user_id__isnull=False+ )+ for filter_ in filters:+ if isinstance(filter_, contracts.AccountTableSearchFilter):+ query = filter_.query.strip()+ if query:+ queryset = queryset.filter(Q(name__icontains=query) | Q(external_id__icontains=query))+ elif isinstance(filter_, contracts.AccountTableTagsFilter):+ if filter_.tag_names:+ matching_tags = TaggedItem.objects.filter(+ account_id=OuterRef("pk"), tag__team_id=team_id, tag__name__in=filter_.tag_names+ )+ queryset = queryset.filter(Exists(matching_tags))+ elif isinstance(filter_, contracts.AccountTableAssignedToFilter):+ if filter_.user_ids:+ queryset = queryset.filter(Exists(active_relationships.filter(user_id__in=filter_.user_ids)))+ elif isinstance(filter_, contracts.AccountTableUnassignedFilter):+ queryset = queryset.filter(~Exists(active_relationships))+ elif isinstance(filter_, contracts.AccountTableAccountIdFilter):+ queryset = queryset.filter(id=filter_.account_id)+ elif isinstance(filter_, contracts.AccountTableFieldFilter):+ queryset = _apply_account_field_filter(queryset, filter_)+ elif isinstance(filter_, contracts.AccountTableCustomPropertyFilter):+ active_values = CustomPropertyValue.objects.for_team(team_id).filter(+ account_id=OuterRef("pk"), definition_id=filter_.definition_id, is_deleted=False+ )+ predicate, negate_exists = _custom_property_filter_predicate(+ filter_, custom_property_display_types[filter_.definition_id]+ )+ matching_values = active_values.filter(predicate)+ queryset = queryset.filter(~Exists(matching_values) if negate_exists else Exists(matching_values))+ return querysetdiff --git a/products/customer_analytics/backend/logic/account_track_rules.py b/products/customer_analytics/backend/logic/account_track_rules.pynew file mode 100644index 000000000000..c5d989cc1c86--- /dev/null+++ b/products/customer_analytics/backend/logic/account_track_rules.py@@ -0,0 +1,738 @@+from __future__ import annotations++from dataclasses import dataclass+from datetime import datetime+from typing import Any+from uuid import UUID++from django.db import transaction+from django.db.models import Count, Q, QuerySet, Subquery+from django.utils import timezone++import structlog++from posthog.event_usage import report_user_action+from posthog.exceptions_capture import capture_exception+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.models.user import User++from products.customer_analytics.backend.facade import contracts+from products.customer_analytics.backend.logic.account_filters import (+ ACCOUNT_DIRECT_FIELDS,+ InvalidAccountFilter,+ apply_account_filters,+)+from products.customer_analytics.backend.models import (+ Account,+ AccountTrackRuleRun,+ AccountTrackRuleRunStatus,+ CustomPropertyDefinition,+ CustomPropertyValue,+ DisplayType,+ TargetType,+ TeamCustomerAnalyticsConfig,+)++logger = structlog.get_logger(__name__)++ACCOUNT_TRACK_RULE_SCHEMA_VERSION = 1+ACCOUNT_TRACK_RULE_MAX_GROUPS = 20+ACCOUNT_TRACK_RULE_MAX_CONDITIONS = 20+ACCOUNT_TRACK_RULE_MAX_VALUES = 100+ACCOUNT_TRACK_RULE_MAX_STRING_LENGTH = 1_000+ACCOUNT_TRACK_RULE_SAMPLE_SIZE = 5+ACCOUNT_TRACK_RULE_BATCH_SIZE = 1_000++ALLOWED_ACCOUNT_FIELDS = frozenset(contracts.AccountTableField) - {+ contracts.AccountTableField.CHURNED_AT,+ contracts.AccountTableField.IGNORED_AT,+}+++class AccountTrackRuleValidationError(ValueError):+ def __init__(self, errors: list[str]):+ self.errors = errors+ super().__init__(errors[0] if errors else "Invalid account Track Rules.")+++class AccountTrackRuleVersionConflict(ValueError):+ pass+++class AccountTrackRuleRunError(ValueError):+ pass+++@dataclass(frozen=True)+class ParsedAccountTrackRules:+ config: contracts.AccountTrackRulesConfig+ custom_property_display_types: dict[UUID, DisplayType]+++@dataclass(frozen=True)+class AccountTrackRuleBatchResult:+ status: str+ processed: int+++def _config_to_json(config: contracts.AccountTrackRulesConfig) -> dict[str, Any]:+ groups = []+ for group in config.groups:+ conditions = []+ for condition in group.conditions:+ field: dict[str, Any] = {"kind": condition.field.kind.value}+ if condition.field.kind == contracts.AccountTrackRuleFieldKind.ACCOUNT_FIELD:+ field["field"] = condition.field.field.value if condition.field.field else None+ else:+ field["definition_id"] = str(condition.field.definition_id)+ conditions.append(+ {+ "field": field,+ "operator": condition.operator,+ "values": list(condition.values),+ }+ )+ groups.append({"conditions": conditions})+ return {+ "schema_version": config.schema_version,+ "version": config.version,+ "enabled": config.enabled,+ "groups": groups,+ }+++def _parse_rule_field(raw_field: Any, path: str) -> contracts.AccountTrackRuleField:+ if not isinstance(raw_field, dict):+ raise AccountTrackRuleValidationError([f"{path} must be an object."])+ try:+ kind = contracts.AccountTrackRuleFieldKind(raw_field.get("kind"))+ except ValueError as error:+ raise AccountTrackRuleValidationError([f"{path}.kind is unknown."]) from error++ if kind == contracts.AccountTrackRuleFieldKind.ACCOUNT_FIELD:+ if set(raw_field) != {"kind", "field"}:+ raise AccountTrackRuleValidationError([f"{path} must contain only kind and field."])+ try:+ field = contracts.AccountTableField(raw_field.get("field"))+ except ValueError as error:+ raise AccountTrackRuleValidationError([f"{path}.field is unknown."]) from error+ if field not in ALLOWED_ACCOUNT_FIELDS:+ raise AccountTrackRuleValidationError([f"{path}.field cannot be used in Track Rules."])+ return contracts.AccountTrackRuleField(kind=kind, field=field)++ if set(raw_field) != {"kind", "definition_id"}:+ raise AccountTrackRuleValidationError([f"{path} must contain only kind and definition_id."])+ try:+ definition_id = UUID(str(raw_field.get("definition_id")))+ except (TypeError, ValueError) as error:+ raise AccountTrackRuleValidationError([f"{path}.definition_id must be a UUID."]) from error+ return contracts.AccountTrackRuleField(kind=kind, definition_id=definition_id)+++def _parse_condition(raw_condition: Any, path: str) -> contracts.AccountTrackRuleCondition:+ if not isinstance(raw_condition, dict) or set(raw_condition) != {"field", "operator", "values"}:+ raise AccountTrackRuleValidationError([f"{path} must contain field, operator, and values."])+ field = _parse_rule_field(raw_condition["field"], f"{path}.field")+ operator = raw_condition["operator"]+ if not isinstance(operator, str):+ raise AccountTrackRuleValidationError([f"{path}.operator must be a string."])+ values = raw_condition["values"]+ if not isinstance(values, list):+ raise AccountTrackRuleValidationError([f"{path}.values must be a list."])+ if len(values) > ACCOUNT_TRACK_RULE_MAX_VALUES:+ raise AccountTrackRuleValidationError(+ [f"{path}.values cannot contain more than {ACCOUNT_TRACK_RULE_MAX_VALUES} values."]+ )+ for value in values:+ if not isinstance(value, str | int | float | bool) or value is None:+ raise AccountTrackRuleValidationError([f"{path}.values contains an unsupported value."])+ if isinstance(value, str) and len(value) > ACCOUNT_TRACK_RULE_MAX_STRING_LENGTH:+ raise AccountTrackRuleValidationError(+ [f"{path}.values strings cannot exceed {ACCOUNT_TRACK_RULE_MAX_STRING_LENGTH} characters."]+ )+ if field.kind == contracts.AccountTrackRuleFieldKind.ACCOUNT_FIELD and any(+ not isinstance(value, str) for value in values+ ):+ raise AccountTrackRuleValidationError([f"{path}.values for account fields must be strings."])+ return contracts.AccountTrackRuleCondition(field=field, operator=operator, values=tuple(values))+++def _config_from_json(raw_config: dict[str, Any]) -> contracts.AccountTrackRulesConfig:+ return contracts.AccountTrackRulesConfig(+ schema_version=raw_config["schema_version"],+ version=raw_config["version"],+ enabled=raw_config["enabled"],+ groups=tuple(+ contracts.AccountTrackRuleGroup(+ conditions=tuple(+ _parse_condition(condition, f"groups[{group_index}].conditions[{condition_index}]")+ for condition_index, condition in enumerate(group["conditions"])+ )+ )+ for group_index, group in enumerate(raw_config["groups"])+ ),+ )+++def parse_account_track_rules(team_id: int, raw_config: Any) -> ParsedAccountTrackRules:+ if not isinstance(raw_config, dict):+ raise AccountTrackRuleValidationError(["Track Rules must be an object."])+ if set(raw_config) != {"schema_version", "version", "enabled", "groups"}:+ raise AccountTrackRuleValidationError(+ ["Track Rules must contain schema_version, version, enabled, and groups."]+ )+ if raw_config["schema_version"] != ACCOUNT_TRACK_RULE_SCHEMA_VERSION:+ raise AccountTrackRuleValidationError(["Unsupported Track Rules schema version."])+ if (+ not isinstance(raw_config["version"], int)+ or isinstance(raw_config["version"], bool)+ or raw_config["version"] < 0+ ):+ raise AccountTrackRuleValidationError(["Track Rules version must be a non-negative integer."])+ if not isinstance(raw_config["enabled"], bool):+ raise AccountTrackRuleValidationError(["Track Rules enabled must be a boolean."])+ raw_groups = raw_config["groups"]+ if not isinstance(raw_groups, list):+ raise AccountTrackRuleValidationError(["Track Rules groups must be a list."])+ if len(raw_groups) > ACCOUNT_TRACK_RULE_MAX_GROUPS:+ raise AccountTrackRuleValidationError(+ [f"Track Rules cannot contain more than {ACCOUNT_TRACK_RULE_MAX_GROUPS} groups."]+ )+ if raw_config["enabled"] and not raw_groups:+ raise AccountTrackRuleValidationError(["Enabled Track Rules require at least one group."])++ groups: list[contracts.AccountTrackRuleGroup] = []+ custom_property_ids: set[UUID] = set()+ for group_index, raw_group in enumerate(raw_groups):+ path = f"groups[{group_index}]"+ if not isinstance(raw_group, dict) or set(raw_group) != {"conditions"}:+ raise AccountTrackRuleValidationError([f"{path} must contain conditions."])+ raw_conditions = raw_group["conditions"]+ if not isinstance(raw_conditions, list) or not raw_conditions:+ raise AccountTrackRuleValidationError([f"{path}.conditions must contain at least one condition."])+ if len(raw_conditions) > ACCOUNT_TRACK_RULE_MAX_CONDITIONS:+ raise AccountTrackRuleValidationError(+ [f"{path} cannot contain more than {ACCOUNT_TRACK_RULE_MAX_CONDITIONS} conditions."]+ )+ conditions = tuple(+ _parse_condition(raw_condition, f"{path}.conditions[{condition_index}]")+ for condition_index, raw_condition in enumerate(raw_conditions)+ )+ custom_property_ids.update(+ condition.field.definition_id+ for condition in conditions+ if condition.field.kind == contracts.AccountTrackRuleFieldKind.CUSTOM_PROPERTY+ and condition.field.definition_id is not None+ )+ groups.append(contracts.AccountTrackRuleGroup(conditions=conditions))++ display_types = {+ definition_id: DisplayType(display_type)+ for definition_id, display_type in CustomPropertyDefinition.objects.for_team(team_id)+ .filter(id__in=custom_property_ids, target_type=TargetType.ACCOUNT)+ .values_list("id", "display_type")+ }+ if missing_ids := custom_property_ids - set(display_types):+ raise AccountTrackRuleValidationError(+ [f"Unknown account custom property definition: {sorted(str(value) for value in missing_ids)[0]}."]+ )++ config = contracts.AccountTrackRulesConfig(+ schema_version=ACCOUNT_TRACK_RULE_SCHEMA_VERSION,+ version=raw_config["version"],+ enabled=raw_config["enabled"],+ groups=tuple(groups),+ )+ parsed = ParsedAccountTrackRules(config=config, custom_property_display_types=display_types)+ _validate_compiler_inputs(team_id, parsed)+ return parsed+++def _condition_to_filter(condition: contracts.AccountTrackRuleCondition) -> contracts.AccountTableFilter:+ try:+ if condition.field.kind == contracts.AccountTrackRuleFieldKind.ACCOUNT_FIELD:+ assert condition.field.field is not None+ return contracts.AccountTableFieldFilter(+ field=condition.field.field,+ operator=contracts.AccountTableFieldOperator(condition.operator),+ values=tuple(str(value) for value in condition.values),+ )+ assert condition.field.definition_id is not None+ return contracts.AccountTableCustomPropertyFilter(+ definition_id=condition.field.definition_id,+ operator=contracts.AccountTableCustomPropertyOperator(condition.operator),+ values=condition.values,+ )+ except ValueError as error:+ raise AccountTrackRuleValidationError([f"Unknown operator: {condition.operator}."]) from error+++def _group_filters(group: contracts.AccountTrackRuleGroup) -> tuple[contracts.AccountTableFilter, ...]:+ return tuple(_condition_to_filter(condition) for condition in group.conditions)+++def _validate_compiler_inputs(team_id: int, parsed: ParsedAccountTrackRules) -> None:+ base = Account.objects.for_team(team_id).all()+ try:+ for group in parsed.config.groups:+ apply_account_filters(+ base,+ team_id=team_id,+ filters=_group_filters(group),+ custom_property_display_types=parsed.custom_property_display_types,+ )+ except (InvalidAccountFilter, TypeError) as error:+ raise AccountTrackRuleValidationError([str(error)]) from error+++def matching_accounts_queryset(+ queryset: QuerySet[Account], *, team_id: int, parsed: ParsedAccountTrackRules+) -> QuerySet[Account]:+ if not parsed.config.groups:+ return queryset.none()+ matching_groups = Q()+ for group in parsed.config.groups:+ group_matches = apply_account_filters(+ queryset.order_by(),+ team_id=team_id,+ filters=_group_filters(group),+ custom_property_display_types=parsed.custom_property_display_types,+ )+ matching_groups |= Q(id__in=Subquery(group_matches.values("id")))+ return queryset.filter(matching_groups)+++def get_account_track_rules(team_id: int) -> contracts.AccountTrackRulesConfig:+ row, _ = TeamCustomerAnalyticsConfig.objects.get_or_create(team_id=team_id)+ try:+ return _config_from_json(row.account_track_rules)+ except (AccountTrackRuleValidationError, KeyError, TypeError, ValueError):+ return contracts.AccountTrackRulesConfig()+++def update_account_track_rules(+ *,+ team_id: int,+ raw_config: dict[str, Any],+ user: User,+ organization_id: UUID,+ was_impersonated: bool,+) -> contracts.AccountTrackRulesConfig:+ parsed = parse_account_track_rules(team_id, raw_config)+ with transaction.atomic():+ row, _ = TeamCustomerAnalyticsConfig.objects.select_for_update().get_or_create(team_id=team_id)+ current_version = row.account_track_rules.get("version", 0)+ if parsed.config.version != current_version:+ raise AccountTrackRuleVersionConflict("Track Rules changed since this page loaded. Reload and try again.")+ candidate = contracts.AccountTrackRulesConfig(+ schema_version=ACCOUNT_TRACK_RULE_SCHEMA_VERSION,+ version=current_version + 1,+ enabled=parsed.config.enabled,+ groups=parsed.config.groups,+ )+ candidate_json = _config_to_json(candidate)+ current_without_version = {**row.account_track_rules, "version": candidate.version}+ if current_without_version == candidate_json:+ return contracts.AccountTrackRulesConfig(+ schema_version=ACCOUNT_TRACK_RULE_SCHEMA_VERSION,+ version=current_version,+ enabled=candidate.enabled,+ groups=candidate.groups,+ )+ previous_summary = {+ "version": current_version,+ "enabled": bool(row.account_track_rules.get("enabled", False)),+ "group_count": len(row.account_track_rules.get("groups", [])),+ "condition_count": sum(+ len(group.get("conditions", [])) for group in row.account_track_rules.get("groups", [])+ ),+ }+ current_summary = {+ "version": candidate.version,+ "enabled": candidate.enabled,+ "group_count": len(candidate.groups),+ "condition_count": sum(len(group.conditions) for group in candidate.groups),+ }+ row.account_track_rules = candidate_json+ row.save(update_fields=["account_track_rules"])++ try:+ log_activity(+ organization_id=organization_id,+ team_id=team_id,+ user=user,+ was_impersonated=was_impersonated,+ item_id=str(team_id),+ scope="TeamCustomerAnalyticsConfig",+ activity="updated",+ detail=Detail(+ name="Account Track Rules",+ changes=[+ Change(+ type="TeamCustomerAnalyticsConfig",+ action="changed",+ field="account_track_rules",+ before=previous_summary,+ after=current_summary,+ )+ ],+ ),+ )+ except Exception as error:+ capture_exception(error)+ return candidate+++def _rule_field_key(field: contracts.AccountTrackRuleField) -> str:+ if field.kind == contracts.AccountTrackRuleFieldKind.ACCOUNT_FIELD:+ assert field.field is not None+ return f"account_field:{field.field.value}"+ assert field.definition_id is not None+ return f"custom_property:{field.definition_id}"+++def _rule_fields(config: contracts.AccountTrackRulesConfig) -> tuple[contracts.AccountTrackRuleField, ...]:+ fields: list[contracts.AccountTrackRuleField] = []+ for group in config.groups:+ for condition in group.conditions:+ if condition.field not in fields:+ fields.append(condition.field)+ return tuple(fields)+++def _serialize_rule_value(value: Any) -> float | bool | str | None:+ if isinstance(value, datetime):+ return value.isoformat()+ if value is None or isinstance(value, bool | float | int | str):+ return value+ return str(value)+++def _custom_property_value(row: CustomPropertyValue) -> float | bool | str | None:+ for value in (row.value_str, row.value_bool, row.value_num, row.value_datetime):+ if value is not None:+ return _serialize_rule_value(value)+ return None+++def _sample_accounts(+ queryset: QuerySet[Account], *, team_id: int, config: contracts.AccountTrackRulesConfig+) -> tuple[contracts.AccountTrackRuleSample, ...]:+ accounts = list(queryset.order_by("id")[:ACCOUNT_TRACK_RULE_SAMPLE_SIZE])+ fields = _rule_fields(config)+ custom_definition_ids = [+ field.definition_id+ for field in fields+ if field.kind == contracts.AccountTrackRuleFieldKind.CUSTOM_PROPERTY and field.definition_id is not None+ ]+ custom_values = {+ (value.account_id, value.definition_id): _custom_property_value(value)+ for value in CustomPropertyValue.objects.for_team(team_id).filter(+ account_id__in=[account.id for account in accounts],+ definition_id__in=custom_definition_ids,+ is_deleted=False,+ )+ }++ samples = []+ for account in accounts:+ rule_values = {}+ for field in fields:+ if field.kind == contracts.AccountTrackRuleFieldKind.ACCOUNT_FIELD:+ assert field.field is not None+ direct_field = ACCOUNT_DIRECT_FIELDS.get(field.field)+ value = getattr(account, direct_field) if direct_field else account._properties.get(field.field.value)+ else:+ assert field.definition_id is not None+ value = custom_values.get((account.id, field.definition_id))+ rule_values[_rule_field_key(field)] = _serialize_rule_value(value)+ samples.append(+ contracts.AccountTrackRuleSample(+ id=account.id,+ name=account.name,+ external_id=account.external_id,+ rule_values=rule_values,+ )+ )+ return tuple(samples)+++def preview_account_track_rules(+ team_id: int, raw_config: dict[str, Any] | None = None+) -> contracts.AccountTrackRulePreview:+ if raw_config is None:+ row, _ = TeamCustomerAnalyticsConfig.objects.get_or_create(team_id=team_id)+ raw_config = row.account_track_rules+ parsed = parse_account_track_rules(team_id, raw_config)+ active = Account.objects.for_team(team_id).filter(churned_at__isnull=True)+ matching = matching_accounts_queryset(active, team_id=team_id, parsed=parsed)+ nonmatching = active.exclude(id__in=Subquery(matching.order_by().values("id")))++ matching_counts = matching.aggregate(+ total=Count("id"),+ restored=Count("id", filter=Q(ignored_at__isnull=False)),+ )+ nonmatching_counts = nonmatching.aggregate(+ total=Count("id"),+ newly_ignored=Count("id", filter=Q(ignored_at__isnull=True)),+ )+ tracked = matching_counts["total"]+ ignored = nonmatching_counts["total"]+ tracked_samples = _sample_accounts(matching, team_id=team_id, config=parsed.config)+ ignored_samples = _sample_accounts(nonmatching, team_id=team_id, config=parsed.config)+ return contracts.AccountTrackRulePreview(+ config_version=parsed.config.version,+ eligible_active=tracked + ignored,+ skipped_churned=Account.objects.for_team(team_id).filter(churned_at__isnull=False).count(),+ tracked=tracked,+ ignored=ignored,+ newly_ignored=nonmatching_counts["newly_ignored"],+ restored=matching_counts["restored"],+ tracked_samples=tracked_samples,+ ignored_samples=ignored_samples,+ )+++def to_run_view(run: AccountTrackRuleRun) -> contracts.AccountTrackRuleRunView:+ return contracts.AccountTrackRuleRunView(+ id=run.id,+ config_version=run.config_version,+ trigger=run.trigger,+ status=run.status,+ eligible_active=run.eligible_active,+ skipped_churned=run.skipped_churned,+ tracked=run.tracked,+ ignored=run.ignored,+ newly_ignored=run.newly_ignored,+ restored=run.restored,+ started_at=run.started_at,+ finished_at=run.finished_at,+ error=run.error,+ created_by=run.created_by_id,+ created_at=run.created_at,+ )+++def list_account_track_rule_runs(+ team_id: int, *, offset: int, limit: int+) -> tuple[list[contracts.AccountTrackRuleRunView], int]:+ queryset = AccountTrackRuleRun.objects.for_team(team_id).order_by("-created_at")+ return [to_run_view(run) for run in queryset[offset : offset + limit]], queryset.count()+++def create_account_track_rule_run(+ *,+ team_id: int,+ idempotency_key: UUID,+ user_id: int,+) -> tuple[AccountTrackRuleRun, bool]:+ row, _ = TeamCustomerAnalyticsConfig.objects.get_or_create(team_id=team_id)+ parsed = parse_account_track_rules(team_id, row.account_track_rules)+ if not parsed.config.enabled:+ raise AccountTrackRuleRunError("Enable and save Track Rules before running them.")+ return AccountTrackRuleRun.objects.for_team(team_id).get_or_create(+ idempotency_key=idempotency_key,+ defaults={+ "team_id": team_id,+ "created_by_id": user_id,+ "config_version": parsed.config.version,+ },+ )+++def _report_run_outcome(team_id: int, run_id: UUID) -> None:+ run = AccountTrackRuleRun.objects.for_team(team_id).select_related("created_by", "team").filter(id=run_id).first()+ if run is None or run.created_by is None:+ return+ event = (+ "account track rules run completed"+ if run.status == AccountTrackRuleRunStatus.COMPLETED+ else "account track rules run failed"+ )+ properties = {+ "config_version": run.config_version,+ "trigger": run.trigger,+ "status": run.status,+ "eligible_active": run.eligible_active,+ "skipped_churned": run.skipped_churned,+ "tracked": run.tracked,+ "ignored": run.ignored,+ "newly_ignored": run.newly_ignored,+ "restored": run.restored,+ "duration_seconds": (+ (run.finished_at - run.started_at).total_seconds()+ if run.finished_at is not None and run.started_at is not None+ else None+ ),+ }+ try:+ report_user_action(run.created_by, event, properties, team=run.team)+ except Exception as error:+ capture_exception(error, {"team_id": team_id, "run_id": str(run_id), "stage": "report_outcome"})+++def _report_run_outcome_after_commit(team_id: int, run_id: UUID) -> None:+ transaction.on_commit(lambda: _report_run_outcome(team_id, run_id))+++def process_next_account_track_rule_batch(+ team_id: int, run_id: UUID, *, batch_size: int = ACCOUNT_TRACK_RULE_BATCH_SIZE+) -> AccountTrackRuleBatchResult:+ with transaction.atomic():+ run = AccountTrackRuleRun.objects.for_team(team_id).select_for_update().get(id=run_id)+ if run.status in {+ AccountTrackRuleRunStatus.COMPLETED,+ AccountTrackRuleRunStatus.FAILED,+ AccountTrackRuleRunStatus.STALE,+ }:+ return AccountTrackRuleBatchResult(status=run.status, processed=run.processed)++ config_row = TeamCustomerAnalyticsConfig.objects.select_for_update().get(team_id=run.team_id)+ if config_row.account_track_rules.get("version") != run.config_version:+ run.status = AccountTrackRuleRunStatus.STALE+ run.finished_at = timezone.now()+ run.error = "Track Rules changed while this run was in progress."+ run.save(update_fields=["status", "finished_at", "error"])+ logger.warning(+ "account_track_rule_run_stale",+ team_id=run.team_id,+ run_id=str(run.id),+ config_version=run.config_version,+ processed=run.processed,+ )+ _report_run_outcome_after_commit(run.team_id, run.id)+ return AccountTrackRuleBatchResult(status=run.status, processed=run.processed)++ try:+ parsed = parse_account_track_rules(run.team_id, config_row.account_track_rules)+ except AccountTrackRuleValidationError:+ run.status = AccountTrackRuleRunStatus.FAILED+ run.finished_at = timezone.now()+ run.error = "Track Rules are no longer valid."+ run.save(update_fields=["status", "finished_at", "error"])+ logger.warning(+ "account_track_rule_run_invalid_config",+ team_id=run.team_id,+ run_id=str(run.id),+ config_version=run.config_version,+ )+ _report_run_outcome_after_commit(run.team_id, run.id)+ return AccountTrackRuleBatchResult(status=run.status, processed=run.processed)++ if run.status == AccountTrackRuleRunStatus.PENDING:+ run.status = AccountTrackRuleRunStatus.RUNNING+ run.started_at = timezone.now()+ run.eligible_active = Account.objects.for_team(run.team_id).filter(churned_at__isnull=True).count()+ run.skipped_churned = Account.objects.for_team(run.team_id).filter(churned_at__isnull=False).count()+ logger.info(+ "account_track_rule_run_started",+ team_id=run.team_id,+ run_id=str(run.id),+ config_version=run.config_version,+ eligible_active=run.eligible_active,+ skipped_churned=run.skipped_churned,+ )++ active = Account.objects.for_team(run.team_id).filter(churned_at__isnull=True)+ if run.last_account_id:+ active = active.filter(id__gt=run.last_account_id)+ account_ids = list(active.order_by("id").values_list("id", flat=True)[:batch_size])+ if not account_ids:+ run.status = AccountTrackRuleRunStatus.COMPLETED+ run.finished_at = timezone.now()+ run.save(+ update_fields=[+ "status",+ "started_at",+ "finished_at",+ "eligible_active",+ "skipped_churned",+ ]+ )+ logger.info(+ "account_track_rule_run_completed",+ team_id=run.team_id,+ run_id=str(run.id),+ config_version=run.config_version,+ eligible_active=run.eligible_active,+ skipped_churned=run.skipped_churned,+ tracked=run.tracked,+ ignored=run.ignored,+ newly_ignored=run.newly_ignored,+ restored=run.restored,+ duration_seconds=(run.finished_at - run.started_at).total_seconds() if run.started_at else None,+ )+ _report_run_outcome_after_commit(run.team_id, run.id)+ return AccountTrackRuleBatchResult(status=run.status, processed=run.processed)++ active_batch_ids = set(+ Account.objects.for_team(run.team_id)+ .select_for_update()+ .filter(id__in=account_ids, churned_at__isnull=True)+ .values_list("id", flat=True)+ )+ batch = Account.objects.for_team(run.team_id).filter(id__in=active_batch_ids, churned_at__isnull=True)+ matching = matching_accounts_queryset(batch, team_id=run.team_id, parsed=parsed)+ matching_ids = set(matching.values_list("id", flat=True))+ nonmatching_ids = active_batch_ids - matching_ids+ restored_ids = set(batch.filter(id__in=matching_ids, ignored_at__isnull=False).values_list("id", flat=True))+ newly_ignored_ids = set(+ batch.filter(id__in=nonmatching_ids, ignored_at__isnull=True).values_list("id", flat=True)+ )++ if restored_ids:+ Account.objects.for_team(run.team_id).filter(id__in=restored_ids, churned_at__isnull=True).update(+ ignored_at=None+ )+ if newly_ignored_ids:+ Account.objects.for_team(run.team_id).filter(id__in=newly_ignored_ids, churned_at__isnull=True).update(+ ignored_at=timezone.now()+ )++ run.tracked += len(matching_ids)+ run.ignored += len(nonmatching_ids)+ run.restored += len(restored_ids)+ run.newly_ignored += len(newly_ignored_ids)+ run.processed += len(active_batch_ids)+ run.last_account_id = account_ids[-1]+ run.save(+ update_fields=[+ "status",+ "started_at",+ "eligible_active",+ "skipped_churned",+ "tracked",+ "ignored",+ "restored",+ "newly_ignored",+ "processed",+ "last_account_id",+ ]+ )+ logger.info(+ "account_track_rule_batch_completed",+ team_id=run.team_id,+ run_id=str(run.id),+ config_version=run.config_version,+ processed=run.processed,+ batch_size=len(account_ids),+ )+ return AccountTrackRuleBatchResult(status=run.status, processed=run.processed)+++def fail_account_track_rule_run(team_id: int, run_id: UUID) -> None:+ updated = (+ AccountTrackRuleRun.objects.for_team(team_id)+ .filter(+ id=run_id,+ status__in=[AccountTrackRuleRunStatus.PENDING, AccountTrackRuleRunStatus.RUNNING],+ )+ .update(+ status=AccountTrackRuleRunStatus.FAILED,+ finished_at=timezone.now(),+ error="The Track Rules run failed. Try again or inspect Error Tracking.",+ )+ )+ if updated:+ logger.error("account_track_rule_run_failed", team_id=team_id, run_id=str(run_id))+ _report_run_outcome(team_id, run_id)diff --git a/products/customer_analytics/backend/migrations/0040_account_track_rules.py b/products/customer_analytics/backend/migrations/0040_account_track_rules.pynew file mode 100644index 000000000000..4e5af1120177--- /dev/null+++ b/products/customer_analytics/backend/migrations/0040_account_track_rules.py@@ -0,0 +1,102 @@+# Generated by Django 5.2.17 on 2026-08-20 23:39++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt++import products.customer_analytics.backend.models.team_customer_analytics_config+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0039_feature_request_evidence_images"),+ ("posthog", "1312_oauthrefreshtoken_oauthrefreshtoken_family_idx"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AddField(+ model_name="teamcustomeranalyticsconfig",+ name="account_track_rules",+ field=models.JSONField(+ default=products.customer_analytics.backend.models.team_customer_analytics_config.default_account_track_rules+ ),+ ),+ migrations.CreateModel(+ name="AccountTrackRuleRun",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("config_version", models.PositiveIntegerField()),+ (+ "trigger",+ models.CharField(+ choices=[("manual", "manual"), ("scheduled", "scheduled")], default="manual", max_length=20+ ),+ ),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "pending"),+ ("running", "running"),+ ("completed", "completed"),+ ("failed", "failed"),+ ("stale", "stale"),+ ],+ default="pending",+ max_length=20,+ ),+ ),+ ("idempotency_key", models.UUIDField()),+ ("eligible_active", models.PositiveIntegerField(default=0)),+ ("skipped_churned", models.PositiveIntegerField(default=0)),+ ("tracked", models.PositiveIntegerField(default=0)),+ ("ignored", models.PositiveIntegerField(default=0)),+ ("newly_ignored", models.PositiveIntegerField(default=0)),+ ("restored", models.PositiveIntegerField(default=0)),+ ("processed", models.PositiveIntegerField(default=0)),+ ("last_account_id", models.UUIDField(blank=True, null=True)),+ ("started_at", models.DateTimeField(blank=True, null=True)),+ ("finished_at", models.DateTimeField(blank=True, null=True)),+ ("error", models.TextField(blank=True, null=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [models.Index(fields=["team", "-created_at"], name="ca_track_run_team_created")],+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "idempotency_key"),+ name="ca_track_run_team_idem_uniq",+ )+ ],+ },+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex 23a7ed7c87a0..51147d7cf4e8 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0039_feature_request_evidence_images+0040_account_track_rulesdiff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.pyindex 47323d619f3a..256e0b3d3ea1 100644--- a/products/customer_analytics/backend/models/__init__.py+++ b/products/customer_analytics/backend/models/__init__.py@@ -1,5 +1,6 @@from .account import Accountfrom .account_channel_summary import AccountChannelSummary, SlackSummaryCadence+from .account_track_rule_run import AccountTrackRuleRun, AccountTrackRuleRunStatus, AccountTrackRuleRunTriggerfrom .announcement import Announcementfrom .announcement_delivery import AnnouncementDeliveryfrom .custom_property_definition import (@@ -38,6 +39,9 @@ __all__ = ["DATA_TYPE_BY_DISPLAY_TYPE","Account","AccountChannelSummary",+ "AccountTrackRuleRun",+ "AccountTrackRuleRunStatus",+ "AccountTrackRuleRunTrigger","AccountRelationship","AccountRelationshipDefinition","Announcement",diff --git a/products/customer_analytics/backend/models/account_track_rule_run.py b/products/customer_analytics/backend/models/account_track_rule_run.pynew file mode 100644index 000000000000..b42e3e48a545--- /dev/null+++ b/products/customer_analytics/backend/models/account_track_rule_run.py@@ -0,0 +1,59 @@+from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import CreatedMetaFields, UUIDModel+++class AccountTrackRuleRunTrigger(models.TextChoices):+ MANUAL = "manual", "manual"+ SCHEDULED = "scheduled", "scheduled"+++class AccountTrackRuleRunStatus(models.TextChoices):+ PENDING = "pending", "pending"+ RUNNING = "running", "running"+ COMPLETED = "completed", "completed"+ FAILED = "failed", "failed"+ STALE = "stale", "stale"+++class AccountTrackRuleRun(TeamScopedRootMixin, UUIDModel, CreatedMetaFields):+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False+ )++ config_version = models.PositiveIntegerField()+ trigger = models.CharField(+ max_length=20,+ choices=AccountTrackRuleRunTrigger.choices,+ default=AccountTrackRuleRunTrigger.MANUAL,+ )+ status = models.CharField(+ max_length=20,+ choices=AccountTrackRuleRunStatus.choices,+ default=AccountTrackRuleRunStatus.PENDING,+ )+ idempotency_key = models.UUIDField()++ eligible_active = models.PositiveIntegerField(default=0)+ skipped_churned = models.PositiveIntegerField(default=0)+ tracked = models.PositiveIntegerField(default=0)+ ignored = models.PositiveIntegerField(default=0)+ newly_ignored = models.PositiveIntegerField(default=0)+ restored = models.PositiveIntegerField(default=0)+ processed = models.PositiveIntegerField(default=0)+ last_account_id = models.UUIDField(null=True, blank=True)++ started_at = models.DateTimeField(null=True, blank=True)+ finished_at = models.DateTimeField(null=True, blank=True)+ error = models.TextField(null=True, blank=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["team", "idempotency_key"],+ name="ca_track_run_team_idem_uniq",+ )+ ]+ indexes = [models.Index(fields=["team", "-created_at"], name="ca_track_run_team_created")]diff --git a/products/customer_analytics/backend/models/team_customer_analytics_config.py b/products/customer_analytics/backend/models/team_customer_analytics_config.pyindex 181a5386ce45..07d56167887c 100644--- a/products/customer_analytics/backend/models/team_customer_analytics_config.py+++ b/products/customer_analytics/backend/models/team_customer_analytics_config.py@@ -11,6 +11,15 @@ from products.customer_analytics.backend.constants import DEFAULT_ACTIVITY_EVENTlogger = logging.getLogger(__name__)+def default_account_track_rules() -> dict:+ return {+ "schema_version": 1,+ "version": 0,+ "enabled": False,+ "groups": [],+ }++class TeamCustomerAnalyticsConfig(models.Model):team = models.OneToOneField(Team, on_delete=models.CASCADE, primary_key=True)@@ -20,6 +29,9 @@ class TeamCustomerAnalyticsConfig(models.Model):subscription_event = field_access_control(models.JSONField(default=dict), "project", "admin")payment_event = field_access_control(models.JSONField(default=dict), "project", "admin")account_group_type_index = field_access_control(models.IntegerField(null=True, blank=True), "project", "admin")+ account_track_rules = field_access_control(+ models.JSONField(default=default_account_track_rules), "project", "admin"+ )def to_cache_key_dict(self) -> dict:return {diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 220576c69d26..36b27982728c 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -21,7 +21,7 @@ by the sibling ``organization_members`` module.import jsonfrom typing import Any-from drf_spectacular.utils import extend_schema_field+from drf_spectacular.utils import extend_schema_field, extend_schema_serializerfrom rest_framework import serializersfrom rest_framework_dataclasses.serializers import DataclassSerializer@@ -50,6 +50,10 @@ from products.customer_analytics.backend.facade.contracts import (AccountNoteView,AccountRelationship,AccountRelationshipDefinition,+ AccountTableField,+ AccountTrackRuleFieldKind,+ AccountTrackRulePreview,+ AccountTrackRuleRunView,AccountView,CalendarSyncStatus,CustomerJourneyView,@@ -71,6 +75,114 @@ from products.customer_analytics.backend.facade.contracts import (MeetingView,)++class AccountTrackRuleFieldSerializer(serializers.Serializer):+ kind = serializers.ChoiceField(choices=[kind.value for kind in AccountTrackRuleFieldKind])+ field = serializers.ChoiceField(+ choices=[field.value for field in AccountTableField], required=False, allow_null=True+ )+ definition_id = serializers.UUIDField(required=False, allow_null=True)++ def to_internal_value(self, data):+ return {key: value for key, value in super().to_internal_value(data).items() if value is not None}++ def to_representation(self, instance):+ return {key: value for key, value in super().to_representation(instance).items() if value is not None}+++class AccountTrackRuleConditionSerializer(serializers.Serializer):+ field = AccountTrackRuleFieldSerializer()+ operator = serializers.CharField()+ values = serializers.ListField(child=serializers.JSONField(), required=False, default=list)+++class AccountTrackRuleGroupSerializer(serializers.Serializer):+ conditions = AccountTrackRuleConditionSerializer(many=True)+++@extend_schema_serializer(many=False)+class AccountTrackRulesConfigSerializer(serializers.Serializer):+ schema_version = serializers.IntegerField()+ version = serializers.IntegerField(min_value=0)+ enabled = serializers.BooleanField()+ groups = AccountTrackRuleGroupSerializer(many=True)+++class AccountTrackRuleSampleSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True)+ name = serializers.CharField(read_only=True)+ external_id = serializers.CharField(read_only=True, allow_null=True)+ rule_values = serializers.DictField(child=serializers.JSONField(), read_only=True)+++class AccountTrackRulePreviewSerializer(DataclassSerializer):+ tracked_samples = AccountTrackRuleSampleSerializer(many=True, read_only=True)+ ignored_samples = AccountTrackRuleSampleSerializer(many=True, read_only=True)++ class Meta:+ dataclass = AccountTrackRulePreview+ fields = [+ "config_version",+ "eligible_active",+ "skipped_churned",+ "tracked",+ "ignored",+ "newly_ignored",+ "restored",+ "tracked_samples",+ "ignored_samples",+ "validation_errors",+ ]+++class AccountTrackRuleRunSerializer(DataclassSerializer):+ id = serializers.UUIDField(read_only=True)+ config_version = serializers.IntegerField(read_only=True, min_value=0)+ trigger = serializers.CharField(read_only=True)+ status = serializers.CharField(read_only=True)+ eligible_active = serializers.IntegerField(read_only=True, min_value=0)+ skipped_churned = serializers.IntegerField(read_only=True, min_value=0)+ tracked = serializers.IntegerField(read_only=True, min_value=0)+ ignored = serializers.IntegerField(read_only=True, min_value=0)+ newly_ignored = serializers.IntegerField(read_only=True, min_value=0)+ restored = serializers.IntegerField(read_only=True, min_value=0)+ started_at = serializers.DateTimeField(read_only=True, allow_null=True)+ finished_at = serializers.DateTimeField(read_only=True, allow_null=True)+ error = serializers.CharField(read_only=True, allow_null=True)+ created_by = serializers.IntegerField(read_only=True, allow_null=True)+ created_at = serializers.DateTimeField(read_only=True)++ class Meta:+ dataclass = AccountTrackRuleRunView+ fields = [+ "id",+ "config_version",+ "trigger",+ "status",+ "eligible_active",+ "skipped_churned",+ "tracked",+ "ignored",+ "newly_ignored",+ "restored",+ "started_at",+ "finished_at",+ "error",+ "created_by",+ "created_at",+ ]+++class AccountTrackRuleRunRequestSerializer(serializers.Serializer):+ idempotency_key = serializers.UUIDField()+ confirmed = serializers.BooleanField()++ def validate_confirmed(self, value: bool) -> bool:+ if not value:+ raise serializers.ValidationError("Confirm before running Track Rules.")+ return value++# Scope (value, label) pairs, kept in sync with ``CustomerProfileConfig.Scope``. Declared# here rather than read off the model so this module imports no product models — the# generated ``CustomerProfileConfigScopeEnum`` stays identical to the model-derived one.diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex d48c31128958..4cb0a2a525b0 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -49,7 +49,10 @@ from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControl, model_to_resourcefrom products.customer_analytics.backend.facade import api, contracts-from products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG+from products.customer_analytics.backend.facade.constants import (+ CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG,+ CUSTOMER_ANALYTICS_TRACK_RULES_FLAG,+)from products.customer_analytics.backend.presentation.views.serializers import (AccountChannelSummarySerializer,AccountEmailThreadMessageSerializer,@@ -60,6 +63,10 @@ from products.customer_analytics.backend.presentation.views.serializers import (AccountRelationshipSerializer,AccountRelationshipWriteSerializer,AccountSerializer,+ AccountTrackRulePreviewSerializer,+ AccountTrackRuleRunRequestSerializer,+ AccountTrackRuleRunSerializer,+ AccountTrackRulesConfigSerializer,CalendarSyncStatusSerializer,CalendarSyncTriggerResponseSerializer,CalendarSyncTriggerSerializer,@@ -221,6 +228,169 @@ def _assert_group_scope(request: Request, *, write: bool) -> None:raise PermissionDenied(f"This action requires the `group:{'write' if write else 'read'}` API scope.")+class AccountTrackRuleThrottle(UserRateThrottle):+ scope = "account_track_rules"+ rate = "10/minute"+++class AccountTrackRuleViewSet(+ TeamAndOrgViewSetMixin,+ AccessControlViewSetMixin,+ _FacadePaginationMixin,+ viewsets.GenericViewSet,+):+ scope_object = "customer_analytics"+ serializer_class = AccountTrackRulesConfigSerializer+ queryset = None+ pagination_class = None+ permission_classes = [PostHogFeatureFlagPermission, TeamMemberStrictManagementPermission]+ posthog_feature_flag = CUSTOMER_ANALYTICS_TRACK_RULES_FLAG++ @classmethod+ def as_view(cls, actions=None, **initkwargs):+ if actions and actions.get("get") == "list":+ actions = {**actions, "put": "update_config"}+ return super().as_view(actions, **initkwargs)++ def dangerously_get_required_scopes(self, _request: Request, _view: Any) -> list[str] | None:+ if self.action == "update_config":+ return ["customer_analytics:write"]+ return None++ @extend_schema(responses={200: AccountTrackRulesConfigSerializer(many=False)})+ def list(self, request: Request, *args, **kwargs) -> Response:+ config = api.get_account_track_rules(self.team_id)+ return Response(AccountTrackRulesConfigSerializer(instance=config).data)++ def _report_usage(self, request: Request, event: str, **properties: Any) -> None:+ report_user_action(cast(User, request.user), event, properties, team=self.team)++ @extend_schema(+ request=AccountTrackRulesConfigSerializer,+ responses={200: AccountTrackRulesConfigSerializer},+ )+ def update_config(self, request: Request, *args, **kwargs) -> Response:+ serializer = AccountTrackRulesConfigSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ try:+ config = api.update_account_track_rules(+ team_id=self.team_id,+ raw_config=dict(serializer.validated_data),+ user=cast(User, request.user),+ organization_id=self.organization.id,+ was_impersonated=is_impersonated(request),+ )+ except api.AccountTrackRuleValidationError as error:+ raise ValidationError({"validation_errors": error.errors})+ except api.AccountTrackRuleVersionConflict as error:+ raise Conflict(str(error))+ self._report_usage(+ request,+ "account track rules config saved",+ schema_version=config.schema_version,+ config_version=config.version,+ enabled=config.enabled,+ group_count=len(config.groups),+ condition_count=sum(len(group.conditions) for group in config.groups),+ )+ return Response(AccountTrackRulesConfigSerializer(instance=config).data)++ @extend_schema(+ request=AccountTrackRulesConfigSerializer,+ responses={200: AccountTrackRulePreviewSerializer},+ )+ @action(+ detail=False,+ methods=["post"],+ url_path="preview",+ required_scopes=["customer_analytics:write"],+ throttle_classes=[AccountTrackRuleThrottle],+ )+ def preview(self, request: Request, *args, **kwargs) -> Response:+ raw_config = None+ if request.data:+ serializer = AccountTrackRulesConfigSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ raw_config = dict(serializer.validated_data)+ try:+ preview = api.preview_account_track_rules(self.team_id, raw_config)+ except api.AccountTrackRuleValidationError as error:+ self._report_usage(request, "account track rules preview failed", failure_type="validation")+ raise ValidationError({"validation_errors": error.errors})+ self._report_usage(+ request,+ "account track rules preview completed",+ config_version=preview.config_version,+ eligible_active=preview.eligible_active,+ skipped_churned=preview.skipped_churned,+ tracked=preview.tracked,+ ignored=preview.ignored,+ newly_ignored=preview.newly_ignored,+ restored=preview.restored,+ )+ return Response(AccountTrackRulePreviewSerializer(instance=preview).data)++ @extend_schema(+ request=AccountTrackRuleRunRequestSerializer,+ responses={202: AccountTrackRuleRunSerializer},+ )+ @action(+ detail=False,+ methods=["post"],+ url_path="run",+ required_scopes=["customer_analytics:write"],+ throttle_classes=[AccountTrackRuleThrottle],+ )+ def run(self, request: Request, *args, **kwargs) -> Response:+ serializer = AccountTrackRuleRunRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ data = serializer.validated_data+ try:+ run, started = api.trigger_account_track_rule_run(+ team_id=self.team_id,+ idempotency_key=data["idempotency_key"],+ user_id=cast(User, request.user).id,+ )+ except api.AccountTrackRuleValidationError as error:+ self._report_usage(request, "account track rules run start failed", failure_type="validation")+ raise ValidationError({"validation_errors": error.errors})+ except api.AccountTrackRuleRunError as error:+ self._report_usage(request, "account track rules run start failed", failure_type="disabled")+ raise ValidationError({"detail": str(error)})+ except api.AccountTrackRuleRunAlreadyActive as error:+ self._report_usage(request, "account track rules run start failed", failure_type="overlap")+ raise Conflict(str(error))+ if started:+ self._report_usage(+ request,+ "account track rules run started",+ config_version=run.config_version,+ trigger=run.trigger,+ )+ return Response(AccountTrackRuleRunSerializer(instance=run).data, status=status.HTTP_202_ACCEPTED)++ @extend_schema(+ responses={200: AccountTrackRuleRunSerializer(many=True)},+ )+ @action(+ detail=False,+ methods=["get"],+ url_path="runs",+ pagination_class=LimitOffsetPagination,+ required_scopes=["customer_analytics:read"],+ )+ def runs(self, request: Request, *args, **kwargs) -> Response:+ return self._paginate_via_facade(+ request,+ lambda offset, limit: api.list_account_track_rule_runs(+ self.team_id,+ offset=offset,+ limit=limit,+ ),+ AccountTrackRuleRunSerializer,+ )++class FeatureRequestProductAreaViewSet(TeamAndOrgViewSetMixin,AccessControlViewSetMixin,diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex bcafc3c8bf53..ef84d4d30954 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -9,6 +9,7 @@ from products.customer_analytics.backend.presentation.views.views import (AccountNotesViewSet,AccountRelationshipDefinitionViewSet,AccountRelationshipViewSet,+ AccountTrackRuleViewSet,AccountViewSet,CalendarSyncViewSet,CustomerJourneyViewSet,@@ -23,6 +24,12 @@ from products.customer_analytics.backend.presentation.views.views import (def register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(+ r"account_track_rules",+ AccountTrackRuleViewSet,+ "project_account_track_rules",+ ["team_id"],+ )routers.projects.register(r"announcements",AnnouncementViewSet,diff --git a/products/customer_analytics/backend/temporal/__init__.py b/products/customer_analytics/backend/temporal/__init__.pyindex 24afeb02c8af..bce13a6b4c9c 100644--- a/products/customer_analytics/backend/temporal/__init__.py+++ b/products/customer_analytics/backend/temporal/__init__.py@@ -1,3 +1,8 @@+from products.customer_analytics.backend.temporal.account_track_rules import (+ AccountTrackRuleEvaluationWorkflow,+ account_track_rule_fail_run_activity,+ account_track_rule_process_batch_activity,+)from products.customer_analytics.backend.temporal.calendar_sync import (CalendarSyncCoordinatorWorkflow,CalendarSyncWorkflow,@@ -5,5 +10,10 @@ from products.customer_analytics.backend.temporal.calendar_sync import (calendar_sync_integration_activity,)-WORKFLOWS = [CalendarSyncCoordinatorWorkflow, CalendarSyncWorkflow]-ACTIVITIES = [calendar_sync_collect_integrations_activity, calendar_sync_integration_activity]+WORKFLOWS = [AccountTrackRuleEvaluationWorkflow, CalendarSyncCoordinatorWorkflow, CalendarSyncWorkflow]+ACTIVITIES = [+ account_track_rule_process_batch_activity,+ account_track_rule_fail_run_activity,+ calendar_sync_collect_integrations_activity,+ calendar_sync_integration_activity,+]diff --git a/products/customer_analytics/backend/temporal/account_track_rules.py b/products/customer_analytics/backend/temporal/account_track_rules.pynew file mode 100644index 000000000000..edee864207d2--- /dev/null+++ b/products/customer_analytics/backend/temporal/account_track_rules.py@@ -0,0 +1,116 @@+from __future__ import annotations++import json+import asyncio+from uuid import UUID++from temporalio import activity, workflow+from temporalio.common import RetryPolicy++with workflow.unsafe.imports_passed_through():+ from datetime import timedelta++ import structlog++ from posthog.dataclasses import frozen+ from posthog.exceptions_capture import capture_exception+ from posthog.sync import database_sync_to_async+ from posthog.temporal.common.heartbeat import Heartbeater++ from products.customer_analytics.backend.logic.account_track_rules import (+ fail_account_track_rule_run,+ process_next_account_track_rule_batch,+ )++ACCOUNT_TRACK_RULE_WORKFLOW_NAME = "customer-analytics-account-track-rule-evaluation"++logger = structlog.get_logger(__name__)+++@frozen+class AccountTrackRuleEvaluationInput:+ team_id: int+ run_id: str+ config_version: int+++@frozen+class AccountTrackRuleEvaluationOutput:+ status: str+ processed: int+++def account_track_rule_workflow_id(team_id: int) -> str:+ return f"customer-analytics-account-track-rules-{team_id}"+++async def account_track_rule_process_batch_activity(+ input: AccountTrackRuleEvaluationInput,+) -> AccountTrackRuleEvaluationOutput:+ try:+ async with Heartbeater():+ result = await database_sync_to_async(process_next_account_track_rule_batch, thread_sensitive=False)(+ input.team_id, UUID(input.run_id)+ )+ return AccountTrackRuleEvaluationOutput(status=result.status, processed=result.processed)+ except Exception as error:+ logger.error( # noqa: TRY400 — exception text can contain rule values+ "account_track_rule_batch_failed",+ team_id=input.team_id,+ run_id=input.run_id,+ config_version=input.config_version,+ exception_type=type(error).__name__,+ )+ capture_exception(+ error,+ {+ "team_id": input.team_id,+ "run_id": input.run_id,+ "config_version": input.config_version,+ "stage": "process_batch",+ },+ )+ raise+++async def account_track_rule_fail_run_activity(input: AccountTrackRuleEvaluationInput) -> None:+ await database_sync_to_async(fail_account_track_rule_run, thread_sensitive=False)(input.team_id, UUID(input.run_id))++[email protected](name=ACCOUNT_TRACK_RULE_WORKFLOW_NAME)+class AccountTrackRuleEvaluationWorkflow:+ @staticmethod+ def parse_inputs(inputs: list[str]) -> AccountTrackRuleEvaluationInput:+ return AccountTrackRuleEvaluationInput(**json.loads(inputs[0]))++ @workflow.run+ async def run(self, input: AccountTrackRuleEvaluationInput) -> AccountTrackRuleEvaluationOutput:+ try:+ while True:+ result = await workflow.execute_activity(+ account_track_rule_process_batch_activity,+ input,+ start_to_close_timeout=timedelta(minutes=10),+ heartbeat_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=5)),+ )+ if result.status not in {"pending", "running"}:+ return result+ except asyncio.CancelledError:+ await workflow.execute_activity(+ account_track_rule_fail_run_activity,+ input,+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ raise+ except Exception:+ await workflow.execute_activity(+ account_track_rule_fail_run_activity,+ input,+ start_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ raisediff --git a/products/customer_analytics/backend/test/test_account_track_rules.py b/products/customer_analytics/backend/test/test_account_track_rules.pynew file mode 100644index 000000000000..4e856e97a969--- /dev/null+++ b/products/customer_analytics/backend/test/test_account_track_rules.py@@ -0,0 +1,727 @@+import json+import asyncio+from dataclasses import asdict+from datetime import UTC, datetime+from uuid import uuid4++import pytest+from freezegun import freeze_time+from posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import AsyncMock, patch++from rest_framework import status+from temporalio import activity+from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from posthog.models import OrganizationMembership, Team+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.customer_analytics.backend.logic.account_track_rules import (+ AccountTrackRuleValidationError,+ create_account_track_rule_run,+ get_account_track_rules,+ preview_account_track_rules,+ process_next_account_track_rule_batch,+)+from products.customer_analytics.backend.models import (+ AccountTrackRuleRun,+ AccountTrackRuleRunStatus,+ CustomPropertyValue,+ DisplayType,+ TargetType,+ TeamCustomerAnalyticsConfig,+)+from products.customer_analytics.backend.temporal.account_track_rules import (+ ACCOUNT_TRACK_RULE_WORKFLOW_NAME,+ AccountTrackRuleEvaluationInput,+ AccountTrackRuleEvaluationOutput,+ AccountTrackRuleEvaluationWorkflow,+ account_track_rule_fail_run_activity,+ account_track_rule_workflow_id,+)+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition+++async def test_workflow_processes_batches_until_the_run_finishes() -> None:+ calls = 0++ @activity.defn(name="account_track_rule_process_batch_activity")+ async def process_batch(_input: AccountTrackRuleEvaluationInput) -> AccountTrackRuleEvaluationOutput:+ nonlocal calls+ calls += 1+ return AccountTrackRuleEvaluationOutput(+ status="running" if calls == 1 else "completed",+ processed=1_000 * calls,+ )++ @activity.defn(name="account_track_rule_fail_run_activity")+ async def fail_run(_input: AccountTrackRuleEvaluationInput) -> None:+ raise AssertionError("The success path must not mark the run failed")++ input = AccountTrackRuleEvaluationInput(team_id=1, run_id=str(uuid4()), config_version=3)+ async with await WorkflowEnvironment.start_time_skipping() as environment:+ async with Worker(+ environment.client,+ task_queue="account-track-rules-test",+ workflows=[AccountTrackRuleEvaluationWorkflow],+ activities=[process_batch, fail_run],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result = await environment.client.execute_workflow(+ ACCOUNT_TRACK_RULE_WORKFLOW_NAME,+ asdict(input),+ id=f"account-track-rules-test-{uuid4()}",+ task_queue="account-track-rules-test",+ )++ assert result == {"status": "completed", "processed": 2_000}+ assert calls == 2+++async def test_workflow_marks_the_run_failed_when_cancelled() -> None:+ input = AccountTrackRuleEvaluationInput(team_id=1, run_id=str(uuid4()), config_version=3)+ execute_activity = AsyncMock(side_effect=[asyncio.CancelledError(), None])++ with (+ patch(+ "products.customer_analytics.backend.temporal.account_track_rules.workflow.execute_activity",+ execute_activity,+ ),+ pytest.raises(asyncio.CancelledError),+ ):+ await AccountTrackRuleEvaluationWorkflow().run(input)++ assert execute_activity.await_count == 2+ assert execute_activity.await_args_list[1].args[0] is account_track_rule_fail_run_activity+++def track_rules_config(*, version: int, definition_id: str, enabled: bool = True) -> dict:+ return {+ "schema_version": 1,+ "version": version,+ "enabled": enabled,+ "groups": [+ {+ "conditions": [+ {+ "field": {"kind": "custom_property", "definition_id": definition_id},+ "operator": "gt",+ "values": [0],+ },+ {+ "field": {"kind": "account_field", "field": "name"},+ "operator": "exact",+ "values": ["Paying"],+ },+ ]+ },+ {+ "conditions": [+ {+ "field": {"kind": "account_field", "field": "name"},+ "operator": "exact",+ "values": ["VIP"],+ }+ ]+ },+ ],+ }+++class AccountTrackRulesTestMixin:+ team: Team++ def create_rule_fixtures(self):+ definition = create_custom_property_definition(+ team_id=self.team.id,+ name="MRR",+ display_type=DisplayType.CURRENCY,+ )+ paying = create_account(team_id=self.team.id, name="Paying", external_id="paying-workspace")+ vip = create_account(+ team_id=self.team.id,+ name="VIP",+ external_id="vip-workspace",+ ignored_at=datetime(2025, 1, 1, tzinfo=UTC),+ )+ unmatched = create_account(team_id=self.team.id, name="Unmatched", external_id="unmatched-workspace")+ ignored = create_account(+ team_id=self.team.id,+ name="Already ignored",+ external_id="ignored-workspace",+ ignored_at=datetime(2025, 1, 2, tzinfo=UTC),+ )+ churned = create_account(+ team_id=self.team.id,+ name="VIP",+ external_id="churned-workspace",+ churned_at=datetime(2025, 1, 3, tzinfo=UTC),+ ignored_at=datetime(2025, 1, 4, tzinfo=UTC),+ )+ CustomPropertyValue.objects.unscoped().create(+ team=self.team,+ account=paying,+ definition=definition,+ value_num=100,+ )+ return definition, paying, vip, unmatched, ignored, churned++ def save_config(self, config: dict) -> None:+ TeamCustomerAnalyticsConfig.objects.filter(team_id=self.team.id).update(account_track_rules=config)+++@freeze_time("2026-08-20T12:00:00Z")+class TestAccountTrackRuleLogic(AccountTrackRulesTestMixin, BaseTest):+ def test_config_defaults_to_a_disabled_empty_version(self) -> None:+ config = TeamCustomerAnalyticsConfig.objects.get(team_id=self.team.id).account_track_rules++ assert config == {"schema_version": 1, "version": 0, "enabled": False, "groups": []}++ def test_preview_uses_or_groups_and_skips_churned_accounts(self) -> None:+ definition, paying, vip, unmatched, ignored, churned = self.create_rule_fixtures()+ self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))++ preview = preview_account_track_rules(self.team.id)++ assert preview.config_version == 3+ assert preview.eligible_active == 4+ assert preview.skipped_churned == 1+ assert preview.tracked == 2+ assert preview.ignored == 2+ assert preview.newly_ignored == 1+ assert preview.restored == 1+ assert {sample.id for sample in preview.tracked_samples} == {paying.id, vip.id}+ assert {sample.id for sample in preview.ignored_samples} == {unmatched.id, ignored.id}+ paying_sample = next(sample for sample in preview.tracked_samples if sample.id == paying.id)+ assert paying_sample.external_id == "paying-workspace"+ assert paying_sample.rule_values == {+ f"custom_property:{definition.id}": 100.0,+ "account_field:name": "Paying",+ }+ vip_sample = next(sample for sample in preview.tracked_samples if sample.id == vip.id)+ assert vip_sample.rule_values == {+ f"custom_property:{definition.id}": None,+ "account_field:name": "VIP",+ }+ churned.refresh_from_db()+ assert churned.ignored_at == datetime(2025, 1, 4, tzinfo=UTC)++ def test_apply_batches_preserve_ignored_timestamps_and_restore_matches(self) -> None:+ definition, paying, vip, unmatched, ignored, churned = self.create_rule_fixtures()+ original_ignored_at = ignored.ignored_at+ original_churned_ignored_at = churned.ignored_at+ self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))+ run = AccountTrackRuleRun.objects.unscoped().create(+ team=self.team,+ config_version=3,+ idempotency_key=uuid4(),+ created_by=self.user,+ )++ while True:+ result = process_next_account_track_rule_batch(self.team.id, run.id, batch_size=2)+ if result.status != AccountTrackRuleRunStatus.RUNNING:+ break++ run.refresh_from_db()+ paying.refresh_from_db()+ vip.refresh_from_db()+ unmatched.refresh_from_db()+ ignored.refresh_from_db()+ churned.refresh_from_db()+ assert run.status == AccountTrackRuleRunStatus.COMPLETED+ assert (run.eligible_active, run.skipped_churned) == (4, 1)+ assert (run.tracked, run.ignored, run.newly_ignored, run.restored) == (2, 2, 1, 1)+ assert paying.ignored_at is None+ assert vip.ignored_at is None+ assert unmatched.ignored_at == datetime(2026, 8, 20, 12, 0, tzinfo=UTC)+ assert ignored.ignored_at == original_ignored_at+ assert churned.ignored_at == original_churned_ignored_at++ no_change_run = AccountTrackRuleRun.objects.unscoped().create(+ team=self.team,+ config_version=3,+ idempotency_key=uuid4(),+ created_by=self.user,+ )+ while (+ process_next_account_track_rule_batch(self.team.id, no_change_run.id, batch_size=2).status+ == AccountTrackRuleRunStatus.RUNNING+ ):+ pass+ no_change_run.refresh_from_db()+ ignored.refresh_from_db()+ assert (no_change_run.newly_ignored, no_change_run.restored) == (0, 0)+ assert ignored.ignored_at == original_ignored_at++ churned.churned_at = None+ churned.save(update_fields=["churned_at"])+ reactivation_run = AccountTrackRuleRun.objects.unscoped().create(+ team=self.team,+ config_version=3,+ idempotency_key=uuid4(),+ created_by=self.user,+ )+ while (+ process_next_account_track_rule_batch(self.team.id, reactivation_run.id, batch_size=2).status+ == AccountTrackRuleRunStatus.RUNNING+ ):+ pass+ churned.refresh_from_db()+ assert churned.ignored_at is None++ def test_config_change_marks_run_stale_before_later_batches(self) -> None:+ definition, paying, vip, unmatched, ignored, churned = self.create_rule_fixtures()+ self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))+ run = AccountTrackRuleRun.objects.unscoped().create(+ team=self.team,+ config_version=3,+ idempotency_key=uuid4(),+ created_by=self.user,+ )++ first = process_next_account_track_rule_batch(self.team.id, run.id, batch_size=1)+ assert first.status == AccountTrackRuleRunStatus.RUNNING+ config = track_rules_config(version=4, definition_id=str(definition.id))+ self.save_config(config)+ for account in [paying, vip, unmatched, ignored, churned]:+ account.refresh_from_db()+ states_before = {account.id: account.ignored_at for account in [paying, vip, unmatched, ignored, churned]}++ second = process_next_account_track_rule_batch(self.team.id, run.id, batch_size=1)++ assert second.status == AccountTrackRuleRunStatus.STALE+ run.refresh_from_db()+ assert run.status == AccountTrackRuleRunStatus.STALE+ for account in [paying, vip, unmatched, ignored, churned]:+ account.refresh_from_db()+ assert account.ignored_at == states_before[account.id]++ def test_deleted_or_wrong_target_definitions_fail_before_writes(self) -> None:+ definition, paying, vip, unmatched, ignored, churned = self.create_rule_fixtures()+ self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))+ definition.delete()+ initial_states = {account.id: account.ignored_at for account in [paying, vip, unmatched, ignored, churned]}++ assert len(get_account_track_rules(self.team.id).groups) == 2+ with pytest.raises(AccountTrackRuleValidationError):+ preview_account_track_rules(self.team.id)++ for account in [paying, vip, unmatched, ignored, churned]:+ account.refresh_from_db()+ assert account.ignored_at == initial_states[account.id]++ def test_lifecycle_fields_are_rejected(self) -> None:+ for field in ["ignored_at", "churned_at"]:+ with self.subTest(field=field):+ config = {+ "schema_version": 1,+ "version": 0,+ "enabled": False,+ "groups": [+ {+ "conditions": [+ {+ "field": {"kind": "account_field", "field": field},+ "operator": "is_set",+ "values": [],+ }+ ]+ }+ ],+ }+ self.save_config(config)++ with pytest.raises(AccountTrackRuleValidationError):+ preview_account_track_rules(self.team.id)++ def test_negative_custom_property_operator_includes_unset_values(self) -> None:+ definition, paying, vip, unmatched, ignored, churned = self.create_rule_fixtures()+ self.save_config(+ {+ "schema_version": 1,+ "version": 1,+ "enabled": True,+ "groups": [+ {+ "conditions": [+ {+ "field": {"kind": "custom_property", "definition_id": str(definition.id)},+ "operator": "is_not",+ "values": [100],+ }+ ]+ }+ ],+ }+ )++ preview = preview_account_track_rules(self.team.id)++ assert preview.tracked == 3+ assert preview.ignored == 1+ assert {sample.id for sample in preview.tracked_samples} == {vip.id, unmatched.id, ignored.id}+ assert preview.ignored_samples[0].id == paying.id++ def test_rejects_cross_team_and_non_account_definitions(self) -> None:+ other_team = Team.objects.create(organization=self.organization)+ other_definition = create_custom_property_definition(team_id=other_team.id, name="Other MRR")+ person_definition = create_custom_property_definition(+ team_id=self.team.id,+ name="Person plan",+ target_type=TargetType.PERSON,+ )++ for definition_id in [other_definition.id, person_definition.id]:+ with self.subTest(definition_id=definition_id):+ self.save_config(track_rules_config(version=1, definition_id=str(definition_id)))+ with pytest.raises(AccountTrackRuleValidationError):+ preview_account_track_rules(self.team.id)++ def test_rejects_unknown_operators_and_excessive_limits(self) -> None:+ definition = create_custom_property_definition(+ team_id=self.team.id,+ name="MRR",+ display_type=DisplayType.CURRENCY,+ )+ valid_condition = {+ "field": {"kind": "account_field", "field": "name"},+ "operator": "exact",+ "values": ["Acme"],+ }+ invalid_configs = [+ {+ "schema_version": 2,+ "version": 1,+ "enabled": False,+ "groups": [],+ },+ {+ "schema_version": 1,+ "version": 1,+ "enabled": False,+ "groups": [{"conditions": [valid_condition]}] * 21,+ },+ {+ "schema_version": 1,+ "version": 1,+ "enabled": False,+ "groups": [{"conditions": [valid_condition] * 21}],+ },+ {+ "schema_version": 1,+ "version": 1,+ "enabled": False,+ "groups": [{"conditions": [{**valid_condition, "values": ["a"] * 101}]}],+ },+ {+ "schema_version": 1,+ "version": 1,+ "enabled": False,+ "groups": [{"conditions": [{**valid_condition, "values": ["a" * 1_001]}]}],+ },+ {+ "schema_version": 1,+ "version": 1,+ "enabled": False,+ "groups": [{"conditions": [{**valid_condition, "operator": "gt"}]}],+ },+ {+ "schema_version": 1,+ "version": 1,+ "enabled": False,+ "groups": [+ {+ "conditions": [+ {+ "field": {"kind": "custom_property", "definition_id": str(definition.id)},+ "operator": "icontains",+ "values": ["secret"],+ }+ ]+ }+ ],+ },+ ]++ for config in invalid_configs:+ with self.subTest(config=config):+ self.save_config(config)+ with pytest.raises(AccountTrackRuleValidationError):+ preview_account_track_rules(self.team.id)++ def test_run_creation_is_idempotent_and_workflow_id_is_per_team(self) -> None:+ definition, *_ = self.create_rule_fixtures()+ self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))+ key = uuid4()++ first, first_created = create_account_track_rule_run(+ team_id=self.team.id,+ idempotency_key=key,+ user_id=self.user.id,+ )+ second, second_created = create_account_track_rule_run(+ team_id=self.team.id,+ idempotency_key=key,+ user_id=self.user.id,+ )++ assert first_created is True+ assert second_created is False+ assert first.id == second.id+ assert AccountTrackRuleRun.objects.for_team(self.team.id).count() == 1+ assert account_track_rule_workflow_id(self.team.id) == f"customer-analytics-account-track-rules-{self.team.id}"+++@patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True)+class TestAccountTrackRuleAPI(AccountTrackRulesTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save(update_fields=["level"])+ self.url = f"/api/projects/{self.team.id}/account_track_rules"++ def _token(self, scopes: list[str]) -> str:+ value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="track-rules",+ user=self.user,+ secure_value=hash_key_value(value),+ scopes=scopes,+ scoped_teams=[],+ scoped_organizations=[],+ )+ return value++ def test_admin_can_save_without_changing_accounts_and_stale_save_conflicts(self, _flag) -> None:+ definition, paying, vip, unmatched, ignored, churned = self.create_rule_fixtures()+ initial_states = {account.id: account.ignored_at for account in [paying, vip, unmatched, ignored, churned]}+ config = track_rules_config(version=0, definition_id=str(definition.id), enabled=False)++ with patch(+ "products.customer_analytics.backend.presentation.views.views.report_user_action"+ ) as report_user_action:+ response = self.client.put(self.url, config, format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["version"] == 1+ assert ActivityLog.objects.filter(+ team_id=self.team.id,+ scope="TeamCustomerAnalyticsConfig",+ activity="updated",+ ).exists()+ event_properties = report_user_action.call_args.args[2]+ assert event_properties == {+ "schema_version": 1,+ "config_version": 1,+ "enabled": False,+ "group_count": 2,+ "condition_count": 3,+ }+ serialized_properties = json.dumps(event_properties)+ assert str(definition.id) not in serialized_properties+ assert "Paying" not in serialized_properties+ for account in [paying, vip, unmatched, ignored, churned]:+ account.refresh_from_db()+ assert account.ignored_at == initial_states[account.id]++ saved_config = response.json()+ assert saved_config["groups"][0]["conditions"][0]["field"] == {+ "kind": "custom_property",+ "definition_id": str(definition.id),+ }+ echoed_payload = json.loads(json.dumps(saved_config))+ echoed_payload["groups"][0]["conditions"][0]["field"]["field"] = None+ echoed_payload["groups"][0]["conditions"][1]["field"]["definition_id"] = None+ echoed_response = self.client.put(self.url, echoed_payload, format="json")+ assert echoed_response.status_code == status.HTTP_200_OK, echoed_response.json()+ assert echoed_response.json()["version"] == 1++ stale_response = self.client.put(self.url, config, format="json")+ assert stale_response.status_code == status.HTTP_409_CONFLICT++ def test_preview_accepts_an_unsaved_draft_without_persisting_it(self, _flag) -> None:+ definition, _, _, unmatched, _, _ = self.create_rule_fixtures()+ saved_config = track_rules_config(version=3, definition_id=str(definition.id))+ self.save_config(saved_config)+ draft_config = {+ "schema_version": 1,+ "version": 3,+ "enabled": True,+ "groups": [+ {+ "conditions": [+ {+ "field": {"kind": "account_field", "field": "name"},+ "operator": "exact",+ "values": ["Unmatched"],+ }+ ]+ }+ ],+ }++ response = self.client.post(f"{self.url}/preview", draft_config, format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["tracked"] == 1+ assert response.json()["tracked_samples"] == [+ {+ "id": str(unmatched.id),+ "name": "Unmatched",+ "external_id": "unmatched-workspace",+ "rule_values": {"account_field:name": "Unmatched"},+ }+ ]+ assert TeamCustomerAnalyticsConfig.objects.get(team_id=self.team.id).account_track_rules == saved_config++ def test_api_token_scopes_separate_reads_from_writes(self, _flag) -> None:+ read_token = self._token(["customer_analytics:read"])+ headers = {"authorization": f"Bearer {read_token}"}+ assert self.client.get(self.url, headers=headers).status_code == status.HTTP_200_OK+ assert self.client.get(f"{self.url}/runs", headers=headers).status_code == status.HTTP_200_OK+ assert (+ self.client.put(+ self.url,+ {"schema_version": 1, "version": 0, "enabled": False, "groups": []},+ format="json",+ headers=headers,+ ).status_code+ == status.HTTP_403_FORBIDDEN+ )+ assert (+ self.client.post(f"{self.url}/preview", {}, format="json", headers=headers).status_code+ == status.HTTP_403_FORBIDDEN+ )++ write_token = self._token(["customer_analytics:write"])+ response = self.client.put(+ self.url,+ {"schema_version": 1, "version": 0, "enabled": False, "groups": []},+ format="json",+ headers={"authorization": f"Bearer {write_token}"},+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ preview = self.client.post(+ f"{self.url}/preview",+ {},+ format="json",+ headers={"authorization": f"Bearer {write_token}"},+ )+ assert preview.status_code == status.HTTP_200_OK, preview.json()++ def test_common_project_payload_omits_track_rules(self, _flag) -> None:+ response = self.client.get(f"/api/projects/{self.team.id}")++ assert response.status_code == status.HTTP_200_OK+ assert "account_track_rules" not in response.json()["customer_analytics_config"]++ def test_feature_flag_blocks_the_surface(self, _flag) -> None:+ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=False):+ assert self.client.get(self.url).status_code == status.HTTP_403_FORBIDDEN+ assert self.client.post(f"{self.url}/preview", {}, format="json").status_code == status.HTTP_403_FORBIDDEN++ def test_viewer_can_read_but_cannot_change_preview_or_run(self, _flag) -> None:+ definition, *_ = self.create_rule_fixtures()+ self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save(update_fields=["level"])++ assert self.client.get(self.url).status_code == status.HTTP_200_OK+ assert self.client.get(f"{self.url}/runs").status_code == status.HTTP_200_OK+ assert (+ self.client.put(+ self.url,+ track_rules_config(version=3, definition_id=str(definition.id)),+ format="json",+ ).status_code+ == status.HTTP_403_FORBIDDEN+ )+ assert self.client.post(f"{self.url}/preview", {}, format="json").status_code == status.HTTP_403_FORBIDDEN+ assert (+ self.client.post(+ f"{self.url}/run",+ {+ "idempotency_key": str(uuid4()),+ "confirmed": True,+ },+ format="json",+ ).status_code+ == status.HTTP_403_FORBIDDEN+ )++ def test_temporal_connection_failure_marks_run_failed(self, _flag) -> None:+ definition, *_ = self.create_rule_fixtures()+ self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))++ with patch("posthog.temporal.common.client.sync_connect", side_effect=ConnectionError("unavailable")):+ response = self.client.post(+ f"{self.url}/run",+ {"idempotency_key": str(uuid4()), "confirmed": True},+ format="json",+ )++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ run = AccountTrackRuleRun.objects.for_team(self.team.id).get()+ assert run.status == AccountTrackRuleRunStatus.FAILED+ assert run.finished_at is not None++ def test_overlapping_run_is_rejected_and_recorded(self, _flag) -> None:+ definition, *_ = self.create_rule_fixtures()+ self.save_config(track_rules_config(version=3, definition_id=str(definition.id)))+ client = AsyncMock()+ client.start_workflow.side_effect = WorkflowAlreadyStartedError("workflow", "track-rules")++ with patch("posthog.temporal.common.client.sync_connect", return_value=client):+ response = self.client.post(+ f"{self.url}/run",+ {+ "idempotency_key": str(uuid4()),+ "confirmed": True,+ },+ format="json",+ )++ assert response.status_code == status.HTTP_409_CONFLICT+ run = AccountTrackRuleRun.objects.for_team(self.team.id).get()+ assert run.status == AccountTrackRuleRunStatus.FAILED+ assert run.error == "The Track Rules run failed. Try again or inspect Error Tracking."++ def test_run_requires_enabled_saved_rules_and_confirmation_but_not_a_preview(self, _flag) -> None:+ definition, *_ = self.create_rule_fixtures()+ disabled_config = track_rules_config(version=3, definition_id=str(definition.id), enabled=False)+ self.save_config(disabled_config)++ disabled = self.client.post(+ f"{self.url}/run",+ {"idempotency_key": str(uuid4()), "confirmed": True},+ format="json",+ )+ assert disabled.status_code == status.HTTP_400_BAD_REQUEST++ enabled_config = {**disabled_config, "enabled": True}+ self.save_config(enabled_config)+ unconfirmed = self.client.post(+ f"{self.url}/run",+ {"idempotency_key": str(uuid4()), "confirmed": False},+ format="json",+ )+ assert unconfirmed.status_code == status.HTTP_400_BAD_REQUEST++ client = AsyncMock()+ with patch("posthog.temporal.common.client.sync_connect", return_value=client):+ started = self.client.post(+ f"{self.url}/run",+ {"idempotency_key": str(uuid4()), "confirmed": True},+ format="json",+ )+ assert started.status_code == status.HTTP_202_ACCEPTED, started.json()+ assert started.json()["status"] == AccountTrackRuleRunStatus.PENDING+ assert started.json()["config_version"] == 3+ client.start_workflow.assert_awaited_once()diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex ab655971545f..b1012dc4a9c3 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -68,7 +68,7 @@ Ignored accounts (`ignored_at IS NOT NULL`) are excluded from list rows and overOverview tiles run as a separate metrics-only `AccountsTableQuery` (`metrics` set and `columns: []`; `null` when there are no tiles or while definitions are loading). Count, sum, average, minimum, maximum, median, scaling, and threshold counts execute in Postgres. The "My accounts" checkbox resolves to the current user's explicit ID before either query is built, so shared URLs remain viewer-independent. Two cell shapes matter:-- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — read directly from the keyed row's `id`, `name`, and `externalId`. This is the row's identity: `id` (the account PK) drives expansion/scroll/role updates; `externalId` is the copy-able group key. `getNameCell()` in `AccountsTable.tsx` is the canonical accessor. In `NameCell` the name renders as the prominent (`font-semibold`) primary label: a plain click opens the account details inline (toggles the row's expansion via `accountsExpansionLogic`, firing `AccountOpened` on open), while the `<Link>` href points at `urls.customerAnalyticsAccount(id)` so cmd/ctrl-click opens the account's deep-link page in a new tab. The `external_id` sits beneath it as de-emphasized (`text-xs text-muted`) copy-to-clipboard text.+- **`name` column** (mandatory, `ACCOUNTS_NAME_COLUMN`) — read directly from the keyed row's `id`, `name`, and `externalId`. This is the row's identity: `id` (the account PK) drives expansion/scroll/role updates; `externalId` is the copy-able group key. `getNameCell()` in `AccountsTable.tsx` is the canonical accessor. `AccountNameCell.tsx` owns the shared name, deep link, and copyable external ID presentation. The Accounts list wraps it with inline expansion behavior and fires `AccountOpened` when a plain click opens a row. Other account tables reuse it with normal deep-link navigation.- **relationship columns** — returned in `AccountsTableRow.relationships` as arrays of active assignee user ids keyed by definition id (`[]` when unassigned). The legacy names `csm`/`account_executive`/`account_owner` remain stored in defaults, saved views, and URL state, then translate into typed relationship columns matched by seeded definition name (`LEGACY_ROLE_COLUMNS`); a legacy column with no matching definition is dropped from the query. Other definitions are pickable from the "Relationships" column group with opaque `rel_<id>` aliases, resolved back via `aliasToRelationshipDefinition`. Cells render `RelationshipCell`: single-holder definitions get an editable `MemberSelect` (writes via the relationships assign/end endpoints — assign auto-ends the previous holder server-side); multi-holder definitions render read-only. User ids resolve to members via `membersLogic` (loaded up front in `accountsLogic.afterMount`). Sorting uses the alias directly (arrays of ids — deterministic but not email order).The `tag_names` cell is editable in place: `TagsCell` renders the editable `ObjectTags` variant (available tags from `tagsModel`), saving through the account PATCH via `accountsLogic.updateAccountTags` — optimistic per-account override (`tagOverrides`, masking the stale fetched cell like `relationshipOverrides`), debounced full-list PATCH (`TAGS_SAVE_DEBOUNCE_MS`, since `ObjectTags` fires per added/removed tag), `savingTags` guard, revert + toast + captured exception on failure. Clicking a tag in the cell adds it to the tags filter, compounding with tags already filtered (`addTagToFilter` — dedupes, and reports through `reportFilterChange('tag')` like the filter control).diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNameCell.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNameCell.tsxnew file mode 100644index 000000000000..b318f69c6920--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountNameCell.tsx@@ -0,0 +1,44 @@+import type { MouseEventHandler } from 'react'++import { Link } from '@posthog/lemon-ui'++import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { urls } from 'scenes/urls'++export interface AccountNameCellProps {+ accountId?: string+ name: string+ externalId?: string | null+ onClick?: MouseEventHandler<HTMLElement>+ target?: '_blank'+}++export function AccountNameCell({ accountId, name, externalId, onClick, target }: AccountNameCellProps): JSX.Element {+ return (+ <div className="flex flex-col min-w-40" data-account-id={accountId}>+ {accountId ? (+ <Link+ to={urls.customerAnalyticsAccount(accountId)}+ className="font-semibold"+ onClick={onClick}+ target={target}+ >+ {name}+ </Link>+ ) : (+ <span className="font-semibold">{name}</span>+ )}+ {externalId ? (+ <CopyToClipboardInline+ explicitValue={externalId}+ iconStyle={{ color: 'var(--color-accent)' }}+ iconSize="xsmall"+ description="external ID"+ className="text-xs text-muted"+ >+ {externalId}+ </CopyToClipboardInline>+ ) : null}+ </div>+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsxindex a7c276958a12..cfa8394d75f5 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx@@ -6,7 +6,6 @@ import { IconCheck, IconX } from '@posthog/icons'import { LemonButton, LemonColorGlyph, LemonSkeleton, LemonTable, ProfilePicture } from '@posthog/lemon-ui'import type { DataColorToken } from 'lib/colors'-import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { MemberSelect } from 'lib/components/MemberSelect'import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'import { Sparkline } from 'lib/components/Sparkline'@@ -33,6 +32,7 @@ import type {import { ACCOUNTS_TABLE_DATA_NODE_KEY } from '../../constants'import { formatCustomPropertyValue } from '../../scenes/CustomerAnalyticsConfigurationScene/account/customPropertyTypes'+import { AccountNameCell } from './AccountNameCell'import { AccountNotebooksExpansion } from './AccountNotebooksExpansion'import { AccountColumnDisplayConfig, LEGACY_ROLE_COLUMNS, accountsColumnConfigLogic } from './accountsColumnConfigLogic'import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'@@ -41,7 +41,7 @@ import { accountsTableCell, isAccountsTableRow } from './accountsTableQuery'import { AccountsEvents } from './constants'// Shape the name renderer uses from the keyed AccountsTableRow identity fields.-type AccountNameCell = { name: string; external_id: string | null; id: string }+type AccountNameCellData = { name: string; external_id: string | null; id: string }const COLUMN_WIDTHS = {name: '240px',@@ -56,7 +56,7 @@ function useGetCell(): (record: unknown, column: string) => unknown {isAccountsTableRow(record) ? accountsTableCell(record, column, accountsTableQueryPlan) : undefined}-function getNameCell(record: unknown): AccountNameCell | undefined {+function getNameCell(record: unknown): AccountNameCellData | undefined {if (!isAccountsTableRow(record)) {return undefined}@@ -75,46 +75,24 @@ function NameCell({ record }: { record: unknown }): JSX.Element {const { isAccountExpanded } = useValues(accountsExpansionLogic)const { toggleAccountExpanded } = useActions(accountsExpansionLogic)const cell = getNameCell(record)- const name = cell?.name ?? ''- const externalId = cell?.external_id ?? ''const accountId = cell?.idreturn (- <div className="flex flex-col min-w-40" data-account-id={accountId}>- {accountId ? (- <Link- // Plain click opens the account details inline (keeping the list mounted); the href- // stays so a modifier-click (cmd/ctrl/shift) opens the account's deep-link page in a new tab/window.- to={urls.customerAnalyticsAccount(accountId)}- className="font-semibold"- onClick={(event) => {- if (event.metaKey || event.ctrlKey || event.shiftKey) {- return- }- event.preventDefault()- event.stopPropagation()- if (!isAccountExpanded(accountId)) {- posthog.capture(AccountsEvents.AccountOpened)- }- toggleAccountExpanded(accountId)- }}- >- {name}- </Link>- ) : (- <span className="font-semibold">{name}</span>- )}- {externalId ? (- <CopyToClipboardInline- explicitValue={externalId}- iconStyle={{ color: 'var(--color-accent)' }}- iconSize="xsmall"- description="account ID"- className="text-xs text-muted"- >- {externalId}- </CopyToClipboardInline>- ) : null}- </div>+ <AccountNameCell+ accountId={accountId}+ name={cell?.name ?? ''}+ externalId={cell?.external_id}+ onClick={(event) => {+ if (!accountId || event.metaKey || event.ctrlKey || event.shiftKey) {+ return+ }+ event.preventDefault()+ event.stopPropagation()+ if (!isAccountExpanded(accountId)) {+ posthog.capture(AccountsEvents.AccountOpened)+ }+ toggleAccountExpanded(accountId)+ }}+ />)}diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 628daec40870..1834c60b70a5 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -206,6 +206,139 @@ export interface PatchedAccountRelationshipDefinitionApi {is_single_holder?: boolean}+/**+ * * `account_field` - account_field+ * * `custom_property` - custom_property+ */+export type AccountTrackRuleFieldKindEnumApi =+ (typeof AccountTrackRuleFieldKindEnumApi)[keyof typeof AccountTrackRuleFieldKindEnumApi]++export const AccountTrackRuleFieldKindEnumApi = {+ AccountField: 'account_field',+ CustomProperty: 'custom_property',+} as const++/**+ * * `name` - name+ * * `external_id` - external_id+ * * `created_at` - created_at+ * * `updated_at` - updated_at+ * * `churned_at` - churned_at+ * * `ignored_at` - ignored_at+ * * `stripe_customer_id` - stripe_customer_id+ * * `hubspot_deal_id` - hubspot_deal_id+ * * `billing_id` - billing_id+ * * `sfdc_id` - sfdc_id+ * * `zendesk_id` - zendesk_id+ */+export type AccountTrackRuleFieldFieldEnumApi =+ (typeof AccountTrackRuleFieldFieldEnumApi)[keyof typeof AccountTrackRuleFieldFieldEnumApi]++export const AccountTrackRuleFieldFieldEnumApi = {+ Name: 'name',+ ExternalId: 'external_id',+ CreatedAt: 'created_at',+ UpdatedAt: 'updated_at',+ ChurnedAt: 'churned_at',+ IgnoredAt: 'ignored_at',+ StripeCustomerId: 'stripe_customer_id',+ HubspotDealId: 'hubspot_deal_id',+ BillingId: 'billing_id',+ SfdcId: 'sfdc_id',+ ZendeskId: 'zendesk_id',+} as const++export interface AccountTrackRuleFieldApi {+ kind: AccountTrackRuleFieldKindEnumApi+ field?: AccountTrackRuleFieldFieldEnumApi | null+ /** @nullable */+ definition_id?: string | null+}++export interface AccountTrackRuleConditionApi {+ field: AccountTrackRuleFieldApi+ operator: string+ values?: unknown[]+}++export interface AccountTrackRuleGroupApi {+ conditions: AccountTrackRuleConditionApi[]+}++export interface AccountTrackRulesConfigApi {+ schema_version: number+ /** @minimum 0 */+ version: number+ enabled: boolean+ groups: AccountTrackRuleGroupApi[]+}++export type AccountTrackRuleSampleApiRuleValues = { [key: string]: unknown }++export interface AccountTrackRuleSampleApi {+ readonly id: string+ readonly name: string+ /** @nullable */+ readonly external_id: string | null+ readonly rule_values: AccountTrackRuleSampleApiRuleValues+}++export interface AccountTrackRulePreviewApi {+ config_version: number+ eligible_active: number+ skipped_churned: number+ tracked: number+ ignored: number+ newly_ignored: number+ restored: number+ readonly tracked_samples: readonly AccountTrackRuleSampleApi[]+ readonly ignored_samples: readonly AccountTrackRuleSampleApi[]+ validation_errors?: string[]+}++export interface AccountTrackRuleRunRequestApi {+ idempotency_key: string+ confirmed: boolean+}++export interface AccountTrackRuleRunViewApi {+ readonly id: string+ /** @minimum 0 */+ readonly config_version: number+ readonly trigger: string+ readonly status: string+ /** @minimum 0 */+ readonly eligible_active: number+ /** @minimum 0 */+ readonly skipped_churned: number+ /** @minimum 0 */+ readonly tracked: number+ /** @minimum 0 */+ readonly ignored: number+ /** @minimum 0 */+ readonly newly_ignored: number+ /** @minimum 0 */+ readonly restored: number+ /** @nullable */+ readonly started_at: string | null+ /** @nullable */+ readonly finished_at: string | null+ /** @nullable */+ readonly error: string | null+ /** @nullable */+ readonly created_by: number | null+ readonly created_at: string+}++export interface PaginatedAccountTrackRuleRunViewListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: AccountTrackRuleRunViewApi[]+}+/*** * `daily` - daily* * `weekly` - weekly@@ -1963,9 +2096,10 @@ export interface FeatureRequestVersionApi {* * `evidence` - Evidence* * `product_areas` - Product areas*/-export type FieldEnumApi = (typeof FieldEnumApi)[keyof typeof FieldEnumApi]+export type FeatureRequestHistoryChangeFieldEnumApi =+ (typeof FeatureRequestHistoryChangeFieldEnumApi)[keyof typeof FeatureRequestHistoryChangeFieldEnumApi]-export const FieldEnumApi = {+export const FeatureRequestHistoryChangeFieldEnumApi = {Status: 'status',Priority: 'priority',Account: 'account',@@ -2043,7 +2177,7 @@ export interface FeatureRequestHistoryChangeApi {* * `accounts` - Accounts* * `evidence` - Evidence* * `product_areas` - Product areas */- readonly field: FieldEnumApi+ readonly field: FeatureRequestHistoryChangeFieldEnumApi/** Value before the update, including relation snapshots. */readonly before: FeatureRequestHistoryChangeApiBefore/** Value after the update, including relation snapshots. */@@ -2357,6 +2491,17 @@ export type AccountRelationshipDefinitionsListParams = {offset?: number}+export type AccountTrackRulesRunsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}+export type AccountsListParams = {/*** When true, returns only accounts where no user actively holds any relationship.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 8d2c354183f6..97346de3d152 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -16,6 +16,11 @@ import type {AccountRelationshipDefinitionApi,AccountRelationshipDefinitionsListParams,AccountRelationshipWriteApi,+ AccountTrackRulePreviewApi,+ AccountTrackRuleRunRequestApi,+ AccountTrackRuleRunViewApi,+ AccountTrackRulesConfigApi,+ AccountTrackRulesRunsListParams,AccountsEmailThreadMessagesListParams,AccountsEmailThreadsListParams,AccountsListParams,@@ -73,6 +78,7 @@ import type {PaginatedAccountNotebookListApi,PaginatedAccountRelationshipDefinitionListApi,PaginatedAccountSupportTicketMessageListApi,+ PaginatedAccountTrackRuleRunViewListApi,PaginatedAnnouncementListApi,PaginatedCustomPropertyDefinitionListApi,PaginatedCustomPropertySourceListApi,@@ -290,6 +296,98 @@ export const accountRelationshipDefinitionsDestroy = async (})}+export const getAccountTrackRulesListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/account_track_rules/`+}++export const accountTrackRulesList = async (+ projectId: string,+ options?: RequestInit+): Promise<AccountTrackRulesConfigApi> => {+ return apiMutator<AccountTrackRulesConfigApi>(getAccountTrackRulesListUrl(projectId), {+ ...options,+ method: 'GET',+ })+}++export const getAccountTrackRulesUpdateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/account_track_rules/`+}++export const accountTrackRulesUpdate = async (+ projectId: string,+ accountTrackRulesConfigApi: AccountTrackRulesConfigApi,+ options?: RequestInit+): Promise<AccountTrackRulesConfigApi> => {+ return apiMutator<AccountTrackRulesConfigApi>(getAccountTrackRulesUpdateUrl(projectId), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(accountTrackRulesConfigApi),+ })+}++export const getAccountTrackRulesPreviewCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/account_track_rules/preview/`+}++export const accountTrackRulesPreviewCreate = async (+ projectId: string,+ accountTrackRulesConfigApi: AccountTrackRulesConfigApi,+ options?: RequestInit+): Promise<AccountTrackRulePreviewApi> => {+ return apiMutator<AccountTrackRulePreviewApi>(getAccountTrackRulesPreviewCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(accountTrackRulesConfigApi),+ })+}++export const getAccountTrackRulesRunCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/account_track_rules/run/`+}++export const accountTrackRulesRunCreate = async (+ projectId: string,+ accountTrackRuleRunRequestApi: AccountTrackRuleRunRequestApi,+ options?: RequestInit+): Promise<AccountTrackRuleRunViewApi> => {+ return apiMutator<AccountTrackRuleRunViewApi>(getAccountTrackRulesRunCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(accountTrackRuleRunRequestApi),+ })+}++export const getAccountTrackRulesRunsListUrl = (projectId: string, params?: AccountTrackRulesRunsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/account_track_rules/runs/?${stringifiedParams}`+ : `/api/projects/${projectId}/account_track_rules/runs/`+}++export const accountTrackRulesRunsList = async (+ projectId: string,+ params?: AccountTrackRulesRunsListParams,+ options?: RequestInit+): Promise<PaginatedAccountTrackRuleRunViewListApi> => {+ return apiMutator<PaginatedAccountTrackRuleRunViewListApi>(getAccountTrackRulesRunsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getAccountsListUrl = (projectId: string, params?: AccountsListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex e178c4f162ce..802abadb2fa7 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -85,6 +85,103 @@ export const AccountRelationshipDefinitionsPartialUpdateBody = /* @__PURE__ */ z}).describe('A team-defined account relationship type (CSM, Onboarding manager, ...).')+export const accountTrackRulesUpdateBodyVersionMin = 0++export const AccountTrackRulesUpdateBody = /* @__PURE__ */ zod.object({+ schema_version: zod.number(),+ version: zod.number().min(accountTrackRulesUpdateBodyVersionMin),+ enabled: zod.boolean(),+ groups: zod.array(+ zod.object({+ conditions: zod.array(+ zod.object({+ field: zod.object({+ kind: zod+ .enum(['account_field', 'custom_property'])+ .describe('\* `account_field` - account_field\n\* `custom_property` - custom_property'),+ field: zod+ .union([+ zod+ .enum([+ 'name',+ 'external_id',+ 'created_at',+ 'updated_at',+ 'churned_at',+ 'ignored_at',+ 'stripe_customer_id',+ 'hubspot_deal_id',+ 'billing_id',+ 'sfdc_id',+ 'zendesk_id',+ ])+ .describe(+ '\* `name` - name\n\* `external_id` - external_id\n\* `created_at` - created_at\n\* `updated_at` - updated_at\n\* `churned_at` - churned_at\n\* `ignored_at` - ignored_at\n\* `stripe_customer_id` - stripe_customer_id\n\* `hubspot_deal_id` - hubspot_deal_id\n\* `billing_id` - billing_id\n\* `sfdc_id` - sfdc_id\n\* `zendesk_id` - zendesk_id'+ ),+ zod.null(),+ ])+ .optional(),+ definition_id: zod.uuid().nullish(),+ }),+ operator: zod.string(),+ values: zod.array(zod.unknown()).optional(),+ })+ ),+ })+ ),+})++export const accountTrackRulesPreviewCreateBodyVersionMin = 0++export const AccountTrackRulesPreviewCreateBody = /* @__PURE__ */ zod.object({+ schema_version: zod.number(),+ version: zod.number().min(accountTrackRulesPreviewCreateBodyVersionMin),+ enabled: zod.boolean(),+ groups: zod.array(+ zod.object({+ conditions: zod.array(+ zod.object({+ field: zod.object({+ kind: zod+ .enum(['account_field', 'custom_property'])+ .describe('\* `account_field` - account_field\n\* `custom_property` - custom_property'),+ field: zod+ .union([+ zod+ .enum([+ 'name',+ 'external_id',+ 'created_at',+ 'updated_at',+ 'churned_at',+ 'ignored_at',+ 'stripe_customer_id',+ 'hubspot_deal_id',+ 'billing_id',+ 'sfdc_id',+ 'zendesk_id',+ ])+ .describe(+ '\* `name` - name\n\* `external_id` - external_id\n\* `created_at` - created_at\n\* `updated_at` - updated_at\n\* `churned_at` - churned_at\n\* `ignored_at` - ignored_at\n\* `stripe_customer_id` - stripe_customer_id\n\* `hubspot_deal_id` - hubspot_deal_id\n\* `billing_id` - billing_id\n\* `sfdc_id` - sfdc_id\n\* `zendesk_id` - zendesk_id'+ ),+ zod.null(),+ ])+ .optional(),+ definition_id: zod.uuid().nullish(),+ }),+ operator: zod.string(),+ values: zod.array(zod.unknown()).optional(),+ })+ ),+ })+ ),+})++export const AccountTrackRulesRunCreateBody = /* @__PURE__ */ zod.object({+ idempotency_key: zod.uuid(),+ confirmed: zod.boolean(),+})+export const accountsCreateBodyNameMax = 400export const accountsCreateBodyExternalIdMax = 400diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsxnew file mode 100644index 000000000000..8c462e7d00dd--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.stories.tsx@@ -0,0 +1,181 @@+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'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++const TRACK_RULES_ENDPOINT = 'api/projects/:team_id/account_track_rules/'+const TRACK_RULE_PREVIEW_ENDPOINT = 'api/projects/:team_id/account_track_rules/preview/'+const TRACK_RULE_RUNS_ENDPOINT = 'api/projects/:team_id/account_track_rules/runs/'+const CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/custom_property_definitions/'+const RELATIONSHIP_DEFINITIONS_ENDPOINT = 'api/projects/:team_id/account_relationship_definitions/'++const config = {+ schema_version: 1,+ version: 3,+ enabled: true,+ groups: [+ {+ conditions: [+ {+ field: {+ kind: 'custom_property',+ definition_id: '01980d7c-0000-7000-8000-000000000001',+ },+ operator: 'gt',+ values: [0],+ },+ ],+ },+ {+ conditions: [+ {+ field: { kind: 'account_field', field: 'name' },+ operator: 'icontains',+ values: ['internal'],+ },+ ],+ },+ ],+}++function previewSample(id: string, name: string, externalId: string, mrr: number | null): Record<string, unknown> {+ return {+ id,+ name,+ external_id: externalId,+ rule_values: {+ 'custom_property:01980d7c-0000-7000-8000-000000000001': mrr,+ 'account_field:name': name,+ },+ }+}++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Customer Analytics/Track Rules',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ featureFlags: [+ FEATURE_FLAGS.CUSTOMER_ANALYTICS,+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP,+ FEATURE_FLAGS.CUSTOMER_ANALYTICS_TRACK_RULES,+ ],+ pageUrl: `${urls.customerAnalyticsConfiguration()}?tab=customer-analytics-track-rules`,+ testOptions: {+ waitForSelector: '[data-attr="account-track-rules"]',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ [TRACK_RULES_ENDPOINT]: config,+ [TRACK_RULE_RUNS_ENDPOINT]: {+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: '01980d7c-0000-7000-8000-000000000010',+ config_version: 3,+ trigger: 'manual',+ status: 'completed',+ eligible_active: 120,+ skipped_churned: 12,+ tracked: 95,+ ignored: 25,+ newly_ignored: 3,+ restored: 2,+ started_at: '2026-08-20T12:00:00Z',+ finished_at: '2026-08-20T12:00:03Z',+ error: null,+ created_by: 1,+ created_at: '2026-08-20T12:00:00Z',+ },+ ],+ },+ [CUSTOM_PROPERTY_DEFINITIONS_ENDPOINT]: {+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: '01980d7c-0000-7000-8000-000000000001',+ name: 'MRR',+ description: 'Monthly recurring revenue',+ display_type: 'currency',+ is_canonical: false,+ is_big_number: false,+ options: null,+ },+ ],+ },+ [RELATIONSHIP_DEFINITIONS_ENDPOINT]: { count: 0, next: null, previous: null, results: [] },+ },+ post: {+ [TRACK_RULE_PREVIEW_ENDPOINT]: {+ config_version: 3,+ eligible_active: 120,+ skipped_churned: 12,+ tracked: 95,+ ignored: 25,+ newly_ignored: 3,+ restored: 0,+ tracked_samples: [+ previewSample('01980d7c-0000-7000-8000-000000000101', 'Acme', 'acme-prod', 12_000),+ previewSample('01980d7c-0000-7000-8000-000000000102', 'Hooli', 'hooli-main', 8_500),+ previewSample('01980d7c-0000-7000-8000-000000000103', 'Initech', 'initech-us', 4_200),+ previewSample('01980d7c-0000-7000-8000-000000000104', 'Pied Piper', 'pied-piper', 2_100),+ previewSample('01980d7c-0000-7000-8000-000000000105', 'Stark Industries', 'stark-hq', 18_000),+ ],+ ignored_samples: [+ previewSample('01980d7c-0000-7000-8000-000000000201', 'Massive Dynamic', 'massive-dynamic', 0),+ previewSample('01980d7c-0000-7000-8000-000000000202', 'Soylent Corp', 'soylent', null),+ previewSample('01980d7c-0000-7000-8000-000000000203', 'Umbrella Corp', 'umbrella', 0),+ previewSample('01980d7c-0000-7000-8000-000000000204', 'Wonka Industries', 'wonka', null),+ previewSample('01980d7c-0000-7000-8000-000000000205', 'Cyberdyne Systems', 'cyberdyne', 0),+ ],+ validation_errors: [],+ },+ },+ }),+ ],+}++export default meta++type Story = StoryObj<{}>++export const Configured: Story = {+ render: () => <App />,+}++export const Preview: Story = {+ render: () => <App />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(await canvas.findByRole('button', { name: 'Preview' }))+ await canvas.findByText('Preview results')+ await userEvent.click(await canvas.findByRole('button', { name: 'Excluded' }))+ const accountLink = await canvas.findByRole('link', { name: 'Massive Dynamic' })+ if (accountLink.getAttribute('target') !== '_blank') {+ throw new Error('Preview account links must open in a new tab')+ }+ await canvas.findAllByText('$0.00')+ },+}++export const FeatureGateOff: Story = {+ render: () => <App />,+ parameters: {+ featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS, FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP],+ testOptions: {+ waitForSelector: '[data-attr="settings-menu-item-customer-analytics-accounts"]',+ },+ },+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.test.tsnew file mode 100644index 000000000000..a540eb4df0c1--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.test.ts@@ -0,0 +1,106 @@+import { PropertyFilterType, PropertyOperator } from '~/types'++import type {+ AccountTrackRuleGroupApi,+ CustomPropertyDefinitionApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountFiltersToRuleGroup, getPreviewRuleColumns, ruleGroupToAccountFilters } from './AccountTrackRules'++describe('AccountTrackRules filter translation', () => {+ const definition = {+ id: '01980d7c-0000-7000-8000-000000000001',+ name: 'MRR',+ display_type: 'currency',+ } as CustomPropertyDefinitionApi++ it('round-trips native and custom property conditions without display labels', () => {+ const group: AccountTrackRuleGroupApi = {+ conditions: [+ {+ field: { kind: 'account_field', field: 'name' },+ operator: 'icontains',+ values: ['PostHog'],+ },+ {+ field: { kind: 'custom_property', definition_id: definition.id },+ operator: 'gt',+ values: [100],+ },+ ],+ }++ const filters = ruleGroupToAccountFilters(group, { [definition.id]: definition })++ expect(filters).toEqual([+ {+ key: 'name',+ value: ['PostHog'],+ operator: PropertyOperator.IContains,+ type: PropertyFilterType.Account,+ },+ {+ key: definition.id,+ value: [100],+ operator: PropertyOperator.GreaterThan,+ type: PropertyFilterType.AccountCustomProperty,+ label: 'MRR',+ },+ ])+ expect(accountFiltersToRuleGroup(filters)).toEqual(group)+ expect(JSON.stringify(accountFiltersToRuleGroup(filters))).not.toContain('MRR')+ })++ it('shows distinct rule properties after the account and external ID columns', () => {+ const groups: AccountTrackRuleGroupApi[] = [+ {+ conditions: [+ { field: { kind: 'account_field', field: 'name' }, operator: 'exact', values: ['Acme'] },+ {+ field: { kind: 'custom_property', definition_id: definition.id },+ operator: 'gt',+ values: [100],+ },+ ],+ },+ {+ conditions: [+ { field: { kind: 'account_field', field: 'external_id' }, operator: 'is_set', values: [] },+ {+ field: { kind: 'custom_property', definition_id: definition.id },+ operator: 'is_set',+ values: [],+ },+ {+ field: { kind: 'account_field', field: 'stripe_customer_id' },+ operator: 'is_set',+ values: [],+ },+ ],+ },+ ]++ expect(getPreviewRuleColumns(groups, { [definition.id]: definition })).toEqual([+ { key: `custom_property:${definition.id}`, label: 'MRR', definition },+ { key: 'account_field:stripe_customer_id', label: 'Stripe customer ID' },+ ])+ })++ it('keeps set operators value-free', () => {+ const group = accountFiltersToRuleGroup([+ {+ key: 'external_id',+ operator: PropertyOperator.IsNotSet,+ type: PropertyFilterType.Account,+ },+ ])++ expect(group.conditions).toEqual([+ {+ field: { kind: 'account_field', field: 'external_id' },+ operator: 'is_not_set',+ values: [],+ },+ ])+ })+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsxnew file mode 100644index 000000000000..bcb43faa3deb--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/AccountTrackRules.tsx@@ -0,0 +1,526 @@+import { useActions, useValues } from 'kea'+import { useState } from 'react'++import { IconCheck, IconPlus, IconTrash, IconX } from '@posthog/icons'+import {+ LemonButton,+ LemonCard,+ LemonColorGlyph,+ LemonDivider,+ LemonSegmentedButton,+ LemonSwitch,+ LemonTable,+ LemonTableColumns,+ LemonTag,+ Tooltip,+} from '@posthog/lemon-ui'++import type { DataColorToken } from 'lib/colors'+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TZLabel } from 'lib/components/TZLabel'+import { TeamMembershipLevel } from 'lib/constants'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'++import { PropertyFilterType, PropertyOperator, type AnyPropertyFilter } from '~/types'++import { AccountNameCell } from 'products/customer_analytics/frontend/components/Accounts/AccountNameCell'+import { accountsColumnConfigLogic } from 'products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic'+import {+ ACCOUNT_FIELD_TAXONOMIC_OPTIONS,+ ACCOUNT_FILTER_OPERATOR_ALLOWLIST,+ accountFilterStaticValueOptions,+ type AccountFilter,+ isAccountPropertyFilter,+} from 'products/customer_analytics/frontend/components/Accounts/accountsPropertyFilters'+import type {+ AccountTrackRuleConditionApi,+ AccountTrackRuleGroupApi,+ AccountTrackRuleRunViewApi,+ AccountTrackRuleSampleApi,+ CustomPropertyDefinitionApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountTrackRulesLogic, type accountTrackRulesLogicValues } from './accountTrackRulesLogic'+import { formatCustomPropertyValue } from './customPropertyTypes'++const TRACK_RULE_ACCOUNT_FIELDS = ACCOUNT_FIELD_TAXONOMIC_OPTIONS.filter(+ ({ id }) => id !== 'ignored_at' && id !== 'churned_at'+)+const ACCOUNT_FIELD_LABELS = Object.fromEntries(ACCOUNT_FIELD_TAXONOMIC_OPTIONS.map(({ id, name }) => [id, name]))+const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed', 'stale'])++function primitiveValues(value: AccountFilter['value']): (string | number | boolean)[] {+ const values = Array.isArray(value) ? value : value == null ? [] : [value]+ return values.filter(+ (item): item is string | number | boolean =>+ typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean'+ )+}++export function accountFiltersToRuleGroup(filters: AccountFilter[]): AccountTrackRuleGroupApi {+ return {+ conditions: filters.map(+ (filter): AccountTrackRuleConditionApi => ({+ field: isAccountPropertyFilter(filter)+ ? { kind: 'account_field', field: filter.key as AccountTrackRuleConditionApi['field']['field'] }+ : { kind: 'custom_property', definition_id: filter.key },+ operator: filter.operator,+ values: primitiveValues(filter.value),+ })+ ),+ }+}++export function ruleGroupToAccountFilters(+ group: AccountTrackRuleGroupApi,+ definitionsById: Record<string, CustomPropertyDefinitionApi>+): AccountFilter[] {+ return group.conditions.map((condition) => {+ const isNative = condition.field.kind === 'account_field'+ const key = isNative ? (condition.field.field ?? '') : (condition.field.definition_id ?? '')+ return {+ key,+ value: condition.values ?? [],+ operator: condition.operator as PropertyOperator,+ type: isNative ? PropertyFilterType.Account : PropertyFilterType.AccountCustomProperty,+ label: isNative ? undefined : definitionsById[key]?.name,+ } as AccountFilter+ })+}++export function AccountTrackRules(): JSX.Element {+ const {+ config,+ configLoading,+ draft,+ hasUnsavedChanges,+ canSave,+ canPreview,+ saveResponseLoading,+ previewResponse,+ previewResponseLoading,+ previewedDraft,+ previewMatchesDraft,+ runs,+ runsLoading,+ canRun,+ currentRunLoading,+ } = useValues(accountTrackRulesLogic)+ const { toggleEnabled, addGroup, updateGroup, removeGroup, saveConfig, previewDraft, startRun, loadRuns } =+ useActions(accountTrackRulesLogic)+ const { customPropertyTaxonomicOptions, customPropertyDefinitionsById, customPropertyDefinitionsLoading } =+ useValues(accountsColumnConfigLogic)+ const restrictionReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ const confirmRun = (): void => {+ if (!config?.enabled || hasUnsavedChanges || !canRun) {+ return+ }+ LemonDialog.open({+ title: 'Apply these track rules?',+ description: 'This applies the saved rules to active accounts. Churned accounts will not change.',+ primaryButton: {+ children: 'Run now',+ onClick: startRun,+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ if ((configLoading && !config) || customPropertyDefinitionsLoading) {+ return <div className="text-secondary">Loading track rules…</div>+ }++ return (+ <div className="flex flex-col gap-4 max-w-240" data-attr="account-track-rules">+ <div className="flex items-start justify-between gap-4">+ <div>+ <h2 className="text-lg font-semibold mb-1">Account track rules</h2>+ <p className="text-secondary mb-0">+ Accounts matching any group stay tracked. Conditions inside a group must all match. Previewing+ does not save changes. Turning rules on saves and applies them immediately. Turning rules off+ stops future runs and does not restore accounts.+ </p>+ </div>+ <LemonSwitch+ checked={draft.enabled}+ onChange={toggleEnabled}+ label="Enabled"+ disabledReason={+ restrictionReason ||+ (saveResponseLoading+ ? 'Saving track rules'+ : hasUnsavedChanges+ ? 'Save changes before enabling or disabling track rules'+ : !canPreview+ ? 'Add and save at least one group before enabling track rules'+ : undefined)+ }+ />+ </div>++ {draft.groups.map((group, index) => (+ <LemonCard key={index} hoverEffect={false} className="p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <div>+ <span className="font-semibold">Group {index + 1}</span>+ {index > 0 && <span className="text-secondary ml-2">OR</span>}+ </div>+ <LemonButton+ size="small"+ icon={<IconTrash />}+ status="danger"+ onClick={() => removeGroup(index)}+ disabledReason={restrictionReason}+ tooltip="Remove group"+ />+ </div>+ <PropertyFilters+ propertyFilters={+ ruleGroupToAccountFilters(+ group,+ customPropertyDefinitionsById+ ) as unknown as AnyPropertyFilter[]+ }+ onChange={(filters) =>+ updateGroup(index, accountFiltersToRuleGroup(filters as unknown as AccountFilter[]))+ }+ pageKey={`customer-analytics-account-track-rules-${index}`}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.AccountFields,+ TaxonomicFilterGroupType.AccountCustomProperties,+ ]}+ taxonomicFilterOptionsFromProp={{+ [TaxonomicFilterGroupType.AccountFields]: TRACK_RULE_ACCOUNT_FIELDS,+ [TaxonomicFilterGroupType.AccountCustomProperties]: customPropertyTaxonomicOptions,+ }}+ operatorAllowlist={ACCOUNT_FILTER_OPERATOR_ALLOWLIST}+ staticValueOptions={accountFilterStaticValueOptions}+ editable={!restrictionReason}+ disabledReason={restrictionReason ?? undefined}+ hasRowOperator={false}+ />+ <span className="text-xs text-secondary">All conditions in this group use AND.</span>+ </LemonCard>+ ))}++ <div>+ <LemonButton+ type="secondary"+ icon={<IconPlus />}+ onClick={addGroup}+ disabledReason={+ restrictionReason || (draft.groups.length >= 20 ? 'A rule can have up to 20 groups' : undefined)+ }+ >+ Add OR group+ </LemonButton>+ </div>++ <div className="flex flex-wrap gap-2">+ <LemonButton+ type="primary"+ onClick={saveConfig}+ loading={saveResponseLoading}+ disabledReason={+ restrictionReason ||+ (!hasUnsavedChanges+ ? 'No changes to save'+ : !canSave+ ? 'Add at least one condition to every group'+ : undefined)+ }+ >+ Save+ </LemonButton>+ <LemonButton+ type="secondary"+ onClick={previewDraft}+ loading={previewResponseLoading}+ disabledReason={+ restrictionReason || (!canPreview ? 'Add at least one condition to every group' : undefined)+ }+ >+ Preview+ </LemonButton>+ <LemonButton+ type="secondary"+ onClick={confirmRun}+ loading={currentRunLoading}+ disabledReason={+ restrictionReason ||+ (hasUnsavedChanges+ ? 'Save changes before running track rules'+ : !config?.enabled+ ? 'Enable track rules before running them'+ : !canRun+ ? 'Another run is in progress'+ : undefined)+ }+ >+ Run now+ </LemonButton>+ </div>++ {previewResponse && (+ <PreviewResult+ preview={previewResponse}+ current={previewMatchesDraft}+ ruleGroups={previewedDraft?.groups ?? []}+ definitionsById={customPropertyDefinitionsById}+ />+ )}++ <LemonDivider />+ <div className="flex items-center justify-between">+ <h3 className="text-base font-semibold mb-0">Recent runs</h3>+ <LemonButton type="secondary" size="small" onClick={loadRuns} loading={runsLoading}>+ Refresh+ </LemonButton>+ </div>+ <RunHistory runs={runs} loading={runsLoading} />+ </div>+ )+}++type PreviewMetric = {+ key: 'eligible_active' | 'skipped_churned' | 'tracked' | 'ignored'+ deltaKey?: 'restored' | 'newly_ignored'+ label: string+ tooltip: string+}++const PREVIEW_METRICS = [+ {+ key: 'eligible_active',+ label: 'Eligible active',+ tooltip: 'Active accounts evaluated by this preview. Churned accounts are not eligible.',+ },+ {+ key: 'skipped_churned',+ label: 'Churned skipped',+ tooltip: 'Churned accounts excluded from evaluation. Applying these rules will not change them.',+ },+ {+ key: 'tracked',+ deltaKey: 'restored',+ label: 'Tracked',+ tooltip:+ 'Eligible accounts that match at least one group. The number in parentheses shows ignored accounts that will be restored.',+ },+ {+ key: 'ignored',+ deltaKey: 'newly_ignored',+ label: 'Ignored',+ tooltip:+ 'Eligible accounts that do not match any group. The number in parentheses shows tracked accounts that will become ignored.',+ },+] satisfies PreviewMetric[]++type PreviewSampleKind = 'included' | 'excluded'++type PreviewRuleColumn = {+ key: string+ label: string+ definition?: CustomPropertyDefinitionApi+}++export function getPreviewRuleColumns(+ groups: readonly AccountTrackRuleGroupApi[],+ definitionsById: Record<string, CustomPropertyDefinitionApi>+): PreviewRuleColumn[] {+ const columns: PreviewRuleColumn[] = []+ const keys = new Set<string>()+ for (const group of groups) {+ for (const condition of group.conditions) {+ if (condition.field.kind === 'account_field') {+ const field = condition.field.field+ if (!field || field === 'name' || field === 'external_id') {+ continue+ }+ const key = `account_field:${field}`+ if (!keys.has(key)) {+ keys.add(key)+ columns.push({ key, label: ACCOUNT_FIELD_LABELS[field] ?? field })+ }+ } else {+ const definitionId = condition.field.definition_id+ if (!definitionId) {+ continue+ }+ const key = `custom_property:${definitionId}`+ if (!keys.has(key)) {+ keys.add(key)+ const definition = definitionsById[definitionId]+ columns.push({ key, label: definition?.name ?? definitionId, definition })+ }+ }+ }+ }+ return columns+}++function PreviewRuleValue({+ value,+ definition,+}: {+ value: unknown+ definition?: CustomPropertyDefinitionApi+}): JSX.Element {+ if (value === null || value === undefined || value === '') {+ return <span className="text-muted">—</span>+ }+ const stringValue = String(value)+ if (definition?.display_type === 'date' || definition?.display_type === 'datetime') {+ return <TZLabel time={stringValue} showSeconds={definition.display_type === 'datetime'} />+ }+ if (definition?.display_type === 'boolean') {+ return stringValue === 'true' || stringValue === '1' ? <IconCheck /> : <IconX className="text-muted" />+ }+ if (definition?.display_type === 'select') {+ const option = definition.options?.find((candidate) => candidate.label === stringValue)+ return (+ <span className="inline-flex items-center gap-1.5">+ {option && <LemonColorGlyph colorToken={option.color as DataColorToken} size="small" />}+ <span>{stringValue}</span>+ </span>+ )+ }+ return <span>{definition ? formatCustomPropertyValue(stringValue, definition) : stringValue}</span>+}++function PreviewResult({+ preview,+ current,+ ruleGroups,+ definitionsById,+}: {+ preview: NonNullable<accountTrackRulesLogicValues['previewResponse']>+ current: boolean+ ruleGroups: readonly AccountTrackRuleGroupApi[]+ definitionsById: Record<string, CustomPropertyDefinitionApi>+}): JSX.Element {+ const [sampleKind, setSampleKind] = useState<PreviewSampleKind>('included')+ const samples = sampleKind === 'included' ? preview.tracked_samples : preview.ignored_samples+ const ruleColumns = getPreviewRuleColumns(ruleGroups, definitionsById)+ const columns: LemonTableColumns<AccountTrackRuleSampleApi> = [+ {+ title: 'Account',+ render: (_, account) => (+ <AccountNameCell+ accountId={account.id}+ name={account.name}+ externalId={account.external_id}+ target="_blank"+ />+ ),+ },+ ...ruleColumns.map(({ key, label, definition }) => ({+ title: label,+ render: (_: unknown, account: AccountTrackRuleSampleApi) => (+ <PreviewRuleValue value={account.rule_values[key]} definition={definition} />+ ),+ })),+ ]++ return (+ <LemonCard hoverEffect={false} className="p-0 overflow-hidden">+ <div className="p-4 flex flex-col gap-3">+ <div className="flex items-center gap-2">+ <span className="font-semibold">Preview for version {preview.config_version}</span>+ <LemonTag type={current ? 'success' : 'warning'}>{current ? 'Current' : 'Stale'}</LemonTag>+ </div>+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ {PREVIEW_METRICS.map(({ key, deltaKey, label, tooltip }) => {+ const delta = deltaKey ? preview[deltaKey] : 0+ return (+ <div key={key}>+ <Tooltip title={tooltip}>+ <span className="text-xs text-secondary cursor-help border-b border-dotted">+ {label}+ </span>+ </Tooltip>+ <div className="text-lg font-semibold">+ {preview[key].toLocaleString()}+ {delta > 0 && <span className="text-secondary"> (+{delta.toLocaleString()})</span>}+ </div>+ </div>+ )+ })}+ </div>+ </div>++ <div className="flex flex-wrap items-center justify-between gap-3 p-4">+ <div className="font-semibold">Preview results</div>+ <LemonSegmentedButton<PreviewSampleKind>+ value={sampleKind}+ onChange={setSampleKind}+ options={[+ { value: 'included', label: 'Included' },+ { value: 'excluded', label: 'Excluded' },+ ]}+ size="small"+ />+ </div>+ <LemonTable+ embedded+ dataSource={[...samples]}+ columns={columns}+ emptyState={`No ${sampleKind} accounts`}+ className="border-t border-primary"+ />+ </LemonCard>+ )+}++function RunHistory({ runs, loading }: { runs: AccountTrackRuleRunViewApi[]; loading: boolean }): JSX.Element {+ const columns: LemonTableColumns<AccountTrackRuleRunViewApi> = [+ {+ title: 'Started',+ render: (_, run) => <TZLabel time={run.started_at ?? run.created_at} />,+ },+ {+ title: 'Version',+ dataIndex: 'config_version',+ },+ {+ title: 'Status',+ render: (_, run) => (+ <LemonTag+ type={+ run.status === 'completed'+ ? 'success'+ : TERMINAL_RUN_STATUSES.has(run.status)+ ? 'danger'+ : 'primary'+ }+ >+ {run.status}+ </LemonTag>+ ),+ },+ {+ title: 'Tracked',+ dataIndex: 'tracked',+ },+ {+ title: 'Ignored',+ dataIndex: 'ignored',+ },+ {+ title: 'Changed',+ render: (_, run) =>+ `${run.newly_ignored.toLocaleString()} ignored · ${run.restored.toLocaleString()} restored`,+ },+ {+ title: 'Error',+ render: (_, run) => run.error ?? '—',+ },+ ]+ return <LemonTable dataSource={runs} columns={columns} loading={loading} emptyState="No track rules runs yet" />+}diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.test.tsnew file mode 100644index 000000000000..16af6c334eeb--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.test.ts@@ -0,0 +1,198 @@+import { expectLogic } from 'kea-test-utils'++import { ApiError } from 'lib/api'++import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'+import { initKeaTests } from '~/test/init'++import {+ accountTrackRulesList,+ accountTrackRulesPreviewCreate,+ accountTrackRulesRunCreate,+ accountTrackRulesRunsList,+ accountTrackRulesUpdate,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountTrackRulePreviewApi,+ AccountTrackRuleRunViewApi,+ AccountTrackRulesConfigApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountTrackRulesLogic } from './accountTrackRulesLogic'++jest.mock('products/customer_analytics/frontend/generated/api', () => ({+ ...jest.requireActual('products/customer_analytics/frontend/generated/api'),+ accountTrackRulesList: jest.fn(),+ accountTrackRulesPreviewCreate: jest.fn(),+ accountTrackRulesRunCreate: jest.fn(),+ accountTrackRulesRunsList: jest.fn(),+ accountTrackRulesUpdate: jest.fn(),+}))++const mockList = accountTrackRulesList as jest.MockedFunction<typeof accountTrackRulesList>+const mockPreview = accountTrackRulesPreviewCreate as jest.MockedFunction<typeof accountTrackRulesPreviewCreate>+const mockRun = accountTrackRulesRunCreate as jest.MockedFunction<typeof accountTrackRulesRunCreate>+const mockRuns = accountTrackRulesRunsList as jest.MockedFunction<typeof accountTrackRulesRunsList>+const mockUpdate = accountTrackRulesUpdate as jest.MockedFunction<typeof accountTrackRulesUpdate>++const CONFIG: AccountTrackRulesConfigApi = {+ schema_version: 1,+ version: 3,+ enabled: true,+ groups: [+ {+ conditions: [+ {+ field: { kind: 'account_field', field: 'name' },+ operator: 'icontains',+ values: ['PostHog'],+ },+ ],+ },+ ],+}++const PREVIEW: AccountTrackRulePreviewApi = {+ config_version: 3,+ eligible_active: 10,+ skipped_churned: 1,+ tracked: 8,+ ignored: 2,+ newly_ignored: 1,+ restored: 1,+ tracked_samples: [],+ ignored_samples: [],+ validation_errors: [],+}++const RUN: AccountTrackRuleRunViewApi = {+ id: '01980d7c-0000-7000-8000-000000000010',+ config_version: 4,+ trigger: 'manual',+ status: 'pending',+ eligible_active: 0,+ skipped_churned: 0,+ tracked: 0,+ ignored: 0,+ newly_ignored: 0,+ restored: 0,+ started_at: null,+ finished_at: null,+ error: null,+ created_by: 1,+ created_at: '2026-08-20T12:00:00Z',+}++describe('accountTrackRulesLogic', () => {+ let logic: ReturnType<typeof accountTrackRulesLogic.build>++ beforeEach(async () => {+ initKeaTests()+ jest.resetAllMocks()+ mockList.mockResolvedValue(CONFIG)+ mockRuns.mockResolvedValue({ count: 0, results: [] })+ logic = accountTrackRulesLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ })++ afterEach(() => {+ logic.unmount()+ resumeKeaLoadersErrors()+ })++ it('runs saved enabled rules without requiring a preview', () => {+ expect(logic.values.hasUnsavedChanges).toBe(false)+ expect(logic.values.canSave).toBe(false)+ expect(logic.values.canRun).toBe(true)+ })++ it('marks a preview stale only when its rule content changes', async () => {+ mockPreview.mockResolvedValue(PREVIEW)++ await expectLogic(logic, () => logic.actions.previewDraft()).toFinishAllListeners()+ expect(mockPreview).toHaveBeenCalledWith(String(logic.values.currentTeamId), CONFIG)+ expect(logic.values.previewMatchesDraft).toBe(true)++ logic.actions.setEnabled(false)++ expect(logic.values.hasUnsavedChanges).toBe(true)+ expect(logic.values.previewMatchesDraft).toBe(false)+ expect(logic.values.canRun).toBe(false)+ })++ it('keeps the previous preview stale when a new preview fails', async () => {+ mockPreview.mockResolvedValueOnce(PREVIEW)+ await expectLogic(logic, () => logic.actions.previewDraft()).toFinishAllListeners()++ logic.actions.setEnabled(false)+ silenceKeaLoadersErrors()+ mockPreview.mockRejectedValueOnce(new ApiError('Invalid rule', 400))+ await expectLogic(logic, () => logic.actions.previewDraft()).toFinishAllListeners()++ expect(logic.values.previewedDraft).toEqual(CONFIG)+ expect(logic.values.previewResponse).toEqual(PREVIEW)+ expect(logic.values.previewMatchesDraft).toBe(false)+ })++ it('previews a valid unsaved configuration without saving it', async () => {+ mockPreview.mockResolvedValue(PREVIEW)+ logic.actions.setEnabled(false)++ await expectLogic(logic, () => logic.actions.previewDraft()).toFinishAllListeners()++ expect(mockPreview).toHaveBeenCalledWith(String(logic.values.currentTeamId), {+ ...CONFIG,+ enabled: false,+ })+ expect(logic.values.canPreview).toBe(true)+ expect(logic.values.previewMatchesDraft).toBe(true)+ expect(mockUpdate).not.toHaveBeenCalled()+ })++ it('saves and runs automatically when Track Rules are enabled', async () => {+ const disabled = { ...CONFIG, enabled: false }+ const enabled = { ...CONFIG, version: 4, enabled: true }+ mockUpdate.mockResolvedValue(enabled)+ mockRun.mockResolvedValue(RUN)+ logic.actions.loadConfigSuccess(disabled)++ await expectLogic(logic, () => logic.actions.toggleEnabled(true)).toFinishAllListeners()++ expect(mockUpdate).toHaveBeenCalledWith(String(logic.values.currentTeamId), {+ ...disabled,+ enabled: true,+ })+ expect(mockRun).toHaveBeenCalledWith(String(logic.values.currentTeamId), {+ idempotency_key: expect.any(String),+ confirmed: true,+ })+ expect(mockUpdate.mock.invocationCallOrder[0]).toBeLessThan(mockRun.mock.invocationCallOrder[0])+ expect(logic.values.draft).toEqual(enabled)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ })++ it('saves rule changes without applying them', async () => {+ const saved = { ...CONFIG, version: 4, enabled: false }+ mockUpdate.mockResolvedValue(saved)+ logic.actions.setEnabled(false)++ await expectLogic(logic, () => logic.actions.saveConfig()).toFinishAllListeners()++ expect(mockUpdate).toHaveBeenCalledWith(String(logic.values.currentTeamId), {+ ...CONFIG,+ enabled: false,+ })+ expect(mockRun).not.toHaveBeenCalled()+ expect(logic.values.draft).toEqual(saved)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ })++ it('does not allow saving or previewing an empty group', () => {+ logic.actions.addGroup()++ expect(logic.values.hasUnsavedChanges).toBe(true)+ expect(logic.values.canSave).toBe(false)+ expect(logic.values.canPreview).toBe(false)+ })+})diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.tsnew file mode 100644index 000000000000..6ff188d4dcfb--- /dev/null+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/accountTrackRulesLogic.ts@@ -0,0 +1,369 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'+import { v4 as uuidv4 } from 'uuid'++import { ApiError } from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import {+ accountTrackRulesList,+ accountTrackRulesPreviewCreate,+ accountTrackRulesRunCreate,+ accountTrackRulesRunsList,+ accountTrackRulesUpdate,+} from 'products/customer_analytics/frontend/generated/api'+import type {+ AccountTrackRuleGroupApi,+ AccountTrackRulePreviewApi,+ AccountTrackRuleRunViewApi,+ AccountTrackRulesConfigApi,+} from 'products/customer_analytics/frontend/generated/api.schemas'++const RUN_POLL_INTERVAL_MS = 5_000+const RUN_POLL_MAX_ATTEMPTS = 360+const TERMINAL_RUN_STATUSES = new Set(['completed', 'failed', 'stale'])++function captureUnexpectedApiError(error: unknown, scope: string): void {+ if (!(error instanceof ApiError) || (error.status ?? 500) >= 500) {+ posthog.captureException(error, { scope })+ }+}++const EMPTY_CONFIG: AccountTrackRulesConfigApi = {+ schema_version: 1,+ version: 0,+ enabled: false,+ groups: [],+}++export interface accountTrackRulesLogicValues {+ currentTeamId: number | null // teamLogic+ config: AccountTrackRulesConfigApi | null+ configLoading: boolean+ draft: AccountTrackRulesConfigApi+ hasUnsavedChanges: boolean+ canSave: boolean+ canPreview: boolean+ previewResponse: AccountTrackRulePreviewApi | null+ previewResponseLoading: boolean+ previewedDraft: AccountTrackRulesConfigApi | null+ previewMatchesDraft: boolean+ runs: AccountTrackRuleRunViewApi[]+ runsLoading: boolean+ currentRun: AccountTrackRuleRunViewApi | null+ currentRunLoading: boolean+ canRun: boolean+ saveResponse: AccountTrackRulesConfigApi | null+ saveResponseLoading: boolean+}++export interface accountTrackRulesLogicActions {+ loadConfig: () => { value: true }+ loadConfigSuccess: (config: AccountTrackRulesConfigApi | null) => { config: AccountTrackRulesConfigApi | null }+ loadConfigFailure: (error: unknown) => { error: unknown }+ saveConfig: () => { value: true }+ saveConfigSuccess: (saveResponse: AccountTrackRulesConfigApi) => { saveResponse: AccountTrackRulesConfigApi }+ saveConfigFailure: (error: unknown) => { error: unknown }+ previewDraft: () => { value: true }+ loadPreview: () => { value: true }+ loadPreviewSuccess: (previewResponse: AccountTrackRulePreviewApi) => {+ previewResponse: AccountTrackRulePreviewApi+ }+ loadPreviewFailure: (error: unknown) => { error: unknown }+ setPreviewedDraft: (config: AccountTrackRulesConfigApi) => { config: AccountTrackRulesConfigApi }+ loadRuns: () => { value: true }+ loadRunsSuccess: (runs: AccountTrackRuleRunViewApi[]) => { runs: AccountTrackRuleRunViewApi[] }+ loadRunsFailure: (error: unknown) => { error: unknown }+ startRun: () => { value: true }+ startRunSuccess: (currentRun: AccountTrackRuleRunViewApi) => { currentRun: AccountTrackRuleRunViewApi }+ startRunFailure: (error: unknown) => { error: unknown }+ setDraft: (config: AccountTrackRulesConfigApi) => { config: AccountTrackRulesConfigApi }+ setEnabled: (enabled: boolean) => { enabled: boolean }+ toggleEnabled: (enabled: boolean) => { enabled: boolean }+ addGroup: () => { value: true }+ updateGroup: (index: number, group: AccountTrackRuleGroupApi) => { index: number; group: AccountTrackRuleGroupApi }+ removeGroup: (index: number) => { index: number }+}++export type accountTrackRulesLogicType = MakeLogicType<accountTrackRulesLogicValues, accountTrackRulesLogicActions>++export const accountTrackRulesLogic = kea<accountTrackRulesLogicType>([+ path(['products', 'customerAnalytics', 'configuration', 'accountTrackRulesLogic']),++ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),++ actions({+ setDraft: (config: AccountTrackRulesConfigApi) => ({ config }),+ setPreviewedDraft: (config: AccountTrackRulesConfigApi) => ({ config }),+ previewDraft: true,+ setEnabled: (enabled: boolean) => ({ enabled }),+ toggleEnabled: (enabled: boolean) => ({ enabled }),+ addGroup: true,+ updateGroup: (index: number, group: AccountTrackRuleGroupApi) => ({ index, group }),+ removeGroup: (index: number) => ({ index }),+ }),++ reducers({+ draft: [+ EMPTY_CONFIG,+ {+ setDraft: (_, { config }) => config,+ setEnabled: (state, { enabled }) => ({ ...state, enabled }),+ addGroup: (state) => ({ ...state, groups: [...state.groups, { conditions: [] }] }),+ updateGroup: (state, { index, group }) => ({+ ...state,+ groups: state.groups.map((existing, groupIndex) => (groupIndex === index ? group : existing)),+ }),+ removeGroup: (state, { index }) => ({+ ...state,+ groups: state.groups.filter((_, groupIndex) => groupIndex !== index),+ }),+ },+ ],+ previewedDraft: [+ null as AccountTrackRulesConfigApi | null,+ {+ setPreviewedDraft: (_, { config }) => config,+ },+ ],+ }),++ loaders(({ values }) => ({+ config: [+ null as AccountTrackRulesConfigApi | null,+ {+ loadConfig: async () => {+ if (values.currentTeamId === null) {+ return null+ }+ try {+ return await accountTrackRulesList(String(values.currentTeamId))+ } catch (error) {+ captureUnexpectedApiError(error, 'accountTrackRulesLogic.loadConfig')+ throw error+ }+ },+ },+ ],+ saveResponse: [+ null as AccountTrackRulesConfigApi | null,+ {+ saveConfig: async () => {+ if (values.currentTeamId === null) {+ throw new Error('No project selected')+ }+ try {+ return await accountTrackRulesUpdate(String(values.currentTeamId), values.draft)+ } catch (error) {+ captureUnexpectedApiError(error, 'accountTrackRulesLogic.saveConfig')+ throw error+ }+ },+ },+ ],+ previewResponse: [+ null as AccountTrackRulePreviewApi | null,+ {+ loadPreview: async () => {+ if (values.currentTeamId === null) {+ throw new Error('No project selected')+ }+ try {+ return await accountTrackRulesPreviewCreate(String(values.currentTeamId), values.draft)+ } catch (error) {+ captureUnexpectedApiError(error, 'accountTrackRulesLogic.loadPreview')+ throw error+ }+ },+ },+ ],+ runs: [+ [] as AccountTrackRuleRunViewApi[],+ {+ loadRuns: async () => {+ if (values.currentTeamId === null) {+ return []+ }+ try {+ return (await accountTrackRulesRunsList(String(values.currentTeamId), { limit: 10 })).results+ } catch (error) {+ captureUnexpectedApiError(error, 'accountTrackRulesLogic.loadRuns')+ throw error+ }+ },+ },+ ],+ currentRun: [+ null as AccountTrackRuleRunViewApi | null,+ {+ startRun: async () => {+ if (values.currentTeamId === null) {+ throw new Error('No project selected')+ }+ try {+ return await accountTrackRulesRunCreate(String(values.currentTeamId), {+ idempotency_key: uuidv4(),+ confirmed: true,+ })+ } catch (error) {+ captureUnexpectedApiError(error, 'accountTrackRulesLogic.startRun')+ throw error+ }+ },+ },+ ],+ })),++ selectors({+ hasUnsavedChanges: [+ (s) => [s.config, s.draft],+ (config: AccountTrackRulesConfigApi | null, draft: AccountTrackRulesConfigApi): boolean =>+ config !== null && JSON.stringify(config) !== JSON.stringify(draft),+ ],+ canSave: [+ (s) => [s.draft, s.hasUnsavedChanges],+ (draft: AccountTrackRulesConfigApi, hasUnsavedChanges: boolean): boolean =>+ hasUnsavedChanges &&+ (!draft.enabled || draft.groups.length > 0) &&+ draft.groups.every((group) => group.conditions.length > 0),+ ],+ canPreview: [+ (s) => [s.draft],+ (draft: AccountTrackRulesConfigApi): boolean =>+ draft.groups.length > 0 && draft.groups.every((group) => group.conditions.length > 0),+ ],+ previewMatchesDraft: [+ (s) => [s.previewResponse, s.previewedDraft, s.draft],+ (+ previewResponse: AccountTrackRulePreviewApi | null,+ previewedDraft: AccountTrackRulesConfigApi | null,+ draft: AccountTrackRulesConfigApi+ ): boolean => {+ if (!previewResponse || !previewedDraft) {+ return false+ }+ return JSON.stringify({ ...previewedDraft, version: 0 }) === JSON.stringify({ ...draft, version: 0 })+ },+ ],+ canRun: [+ (s) => [s.config, s.hasUnsavedChanges, s.currentRunLoading, s.currentRun, s.runs],+ (+ config: AccountTrackRulesConfigApi | null,+ hasUnsavedChanges: boolean,+ currentRunLoading: boolean,+ currentRun: AccountTrackRuleRunViewApi | null,+ runs: AccountTrackRuleRunViewApi[]+ ): boolean => {+ const currentRunStillPending =+ !!currentRun &&+ !TERMINAL_RUN_STATUSES.has(currentRun.status) &&+ !runs.some((run) => run.id === currentRun.id && TERMINAL_RUN_STATUSES.has(run.status))+ return (+ !!config?.enabled &&+ !hasUnsavedChanges &&+ !currentRunLoading &&+ !currentRunStillPending &&+ !runs.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))+ )+ },+ ],+ }),++ listeners(({ actions, cache, values }) => ({+ loadConfigSuccess: ({ config }) => {+ if (config) {+ actions.setDraft(config)+ }+ },+ loadConfigFailure: () => {+ lemonToast.error('Could not load account track rules')+ },+ saveConfigSuccess: ({ saveResponse }) => {+ const runAfterSave = cache.runAfterSave === true+ cache.runAfterSave = false+ cache.toggleSaveInProgress = false+ actions.setDraft(saveResponse)+ lemonToast.success('Track rules saved')+ actions.loadConfigSuccess(saveResponse)+ if (runAfterSave) {+ actions.startRun()+ }+ },+ saveConfigFailure: ({ error }) => {+ cache.runAfterSave = false+ if (cache.toggleSaveInProgress && values.config) {+ actions.setDraft(values.config)+ }+ cache.toggleSaveInProgress = false+ lemonToast.error(+ error instanceof ApiError && error.status === 409+ ? 'Track rules changed since this page loaded. Reload and try again.'+ : 'Could not save track rules. Check every condition and try again.'+ )+ },+ toggleEnabled: ({ enabled }) => {+ cache.runAfterSave = enabled+ cache.toggleSaveInProgress = true+ actions.setEnabled(enabled)+ actions.saveConfig()+ },+ previewDraft: () => {+ cache.pendingPreviewDraft = structuredClone(values.draft)+ actions.loadPreview()+ },+ loadPreviewSuccess: () => {+ if (cache.pendingPreviewDraft) {+ actions.setPreviewedDraft(cache.pendingPreviewDraft)+ }+ cache.pendingPreviewDraft = null+ },+ loadPreviewFailure: ({ error }) => {+ cache.pendingPreviewDraft = null+ lemonToast.error(+ error instanceof ApiError && error.status === 400+ ? 'Track rules reference an invalid or deleted field.'+ : 'Could not preview track rules'+ )+ },+ startRunSuccess: () => {+ cache.trackRulesRunPollAttempts = 0+ lemonToast.success('Track rules run started')+ actions.loadRuns()+ },+ startRunFailure: ({ error }) => {+ lemonToast.error(+ error instanceof ApiError && error.status === 409+ ? 'Another track rules run is already in progress.'+ : error instanceof ApiError && error.status === 400+ ? 'Enable and save track rules before running them.'+ : 'Could not start the track rules run'+ )+ },+ loadRunsSuccess: () => {+ cache.disposables.dispose('trackRulesRunPoll')+ const hasActiveRun = values.runs.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))+ const attempts = (cache.trackRulesRunPollAttempts ?? 0) + 1+ cache.trackRulesRunPollAttempts = attempts+ if (hasActiveRun && attempts < RUN_POLL_MAX_ATTEMPTS) {+ cache.disposables.add(() => {+ const timeoutId = setTimeout(() => actions.loadRuns(), RUN_POLL_INTERVAL_MS)+ return () => clearTimeout(timeoutId)+ }, 'trackRulesRunPoll')+ } else if (!hasActiveRun) {+ cache.trackRulesRunPollAttempts = 0+ }+ },+ loadRunsFailure: () => {+ lemonToast.error('Could not load track rules run history')+ },+ })),++ afterMount(({ actions }) => {+ actions.loadConfig()+ actions.loadRuns()+ }),+])diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.tsindex 48f3525c932a..ea1831d57e1e 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/customerAnalyticsConfigurationSceneLogic.ts@@ -15,6 +15,7 @@ export type ConfigurationSceneTabType =| 'customer-analytics-usage-metrics'| 'customer-analytics-dashboard-events'| 'customer-analytics-accounts'+ | 'customer-analytics-track-rules'| 'customer-analytics-event-stream'export interface CustomerAnalyticsConfigurationSceneLogicProps {@@ -86,7 +87,7 @@ export const customerAnalyticsConfigurationSceneLogic = kea<customerAnalyticsCon{key: Scene.CustomerAnalytics,path:- tab === 'customer-analytics-accounts'+ tab === 'customer-analytics-accounts' || tab === 'customer-analytics-track-rules'? urls.customerAnalyticsAccounts(): urls.customerAnalytics(),name: 'Customer analytics',diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 9189570c7367..f5d4d3a3314c 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -99,6 +99,21 @@ tools:account-relationship-definitions-update:operation: account_relationship_definitions_updateenabled: false+ account-track-rules-list:+ operation: account_track_rules_list+ enabled: false+ account-track-rules-preview-create:+ operation: account_track_rules_preview_create+ enabled: false+ account-track-rules-run-create:+ operation: account_track_rules_run_create+ enabled: false+ account-track-rules-runs-list:+ operation: account_track_rules_runs_list+ enabled: false+ account-track-rules-update:+ operation: account_track_rules_update+ enabled: falseaccounts-create:operation: accounts_createenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f23a3a73341a..d987b74a7459 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -634,6 +634,130 @@ export namespace Schemas {readonly created_at: string;}+ /**+ * * `account_field` - account_field+ * * `custom_property` - custom_property+ */+ export type AccountTrackRuleFieldKindEnum = typeof AccountTrackRuleFieldKindEnum[keyof typeof AccountTrackRuleFieldKindEnum];+++ export const AccountTrackRuleFieldKindEnum = {+ AccountField: 'account_field',+ CustomProperty: 'custom_property',+ } as const;++ /**+ * * `name` - name+ * * `external_id` - external_id+ * * `created_at` - created_at+ * * `updated_at` - updated_at+ * * `churned_at` - churned_at+ * * `ignored_at` - ignored_at+ * * `stripe_customer_id` - stripe_customer_id+ * * `hubspot_deal_id` - hubspot_deal_id+ * * `billing_id` - billing_id+ * * `sfdc_id` - sfdc_id+ * * `zendesk_id` - zendesk_id+ */+ export type AccountTrackRuleFieldFieldEnum = typeof AccountTrackRuleFieldFieldEnum[keyof typeof AccountTrackRuleFieldFieldEnum];+++ export const AccountTrackRuleFieldFieldEnum = {+ Name: 'name',+ ExternalId: 'external_id',+ CreatedAt: 'created_at',+ UpdatedAt: 'updated_at',+ ChurnedAt: 'churned_at',+ IgnoredAt: 'ignored_at',+ StripeCustomerId: 'stripe_customer_id',+ HubspotDealId: 'hubspot_deal_id',+ BillingId: 'billing_id',+ SfdcId: 'sfdc_id',+ ZendeskId: 'zendesk_id',+ } as const;++ export interface AccountTrackRuleField {+ kind: AccountTrackRuleFieldKindEnum;+ field?: AccountTrackRuleFieldFieldEnum | null;+ /** @nullable */+ definition_id?: string | null;+ }++ export interface AccountTrackRuleCondition {+ field: AccountTrackRuleField;+ operator: string;+ values?: unknown[];+ }++ export interface AccountTrackRuleGroup {+ conditions: AccountTrackRuleCondition[];+ }++ export type AccountTrackRuleSampleRuleValues = { [key: string]: unknown };++ export interface AccountTrackRuleSample {+ readonly id: string;+ readonly name: string;+ /** @nullable */+ readonly external_id: string | null;+ readonly rule_values: AccountTrackRuleSampleRuleValues;+ }++ export interface AccountTrackRulePreview {+ config_version: number;+ eligible_active: number;+ skipped_churned: number;+ tracked: number;+ ignored: number;+ newly_ignored: number;+ restored: number;+ readonly tracked_samples: readonly AccountTrackRuleSample[];+ readonly ignored_samples: readonly AccountTrackRuleSample[];+ validation_errors?: string[];+ }++ export interface AccountTrackRuleRunRequest {+ idempotency_key: string;+ confirmed: boolean;+ }++ export interface AccountTrackRuleRunView {+ readonly id: string;+ /** @minimum 0 */+ readonly config_version: number;+ readonly trigger: string;+ readonly status: string;+ /** @minimum 0 */+ readonly eligible_active: number;+ /** @minimum 0 */+ readonly skipped_churned: number;+ /** @minimum 0 */+ readonly tracked: number;+ /** @minimum 0 */+ readonly ignored: number;+ /** @minimum 0 */+ readonly newly_ignored: number;+ /** @minimum 0 */+ readonly restored: number;+ /** @nullable */+ readonly started_at: string | null;+ /** @nullable */+ readonly finished_at: string | null;+ /** @nullable */+ readonly error: string | null;+ /** @nullable */+ readonly created_by: number | null;+ readonly created_at: string;+ }++ export interface AccountTrackRulesConfig {+ schema_version: number;+ /** @minimum 0 */+ version: number;+ enabled: boolean;+ groups: AccountTrackRuleGroup[];+ }+export type BounceRatePageViewMode = typeof BounceRatePageViewMode[keyof typeof BounceRatePageViewMode];@@ -38264,10 +38388,10 @@ export namespace Schemas {* * `evidence` - Evidence* * `product_areas` - Product areas*/- export type FieldEnum = typeof FieldEnum[keyof typeof FieldEnum];+ export type FeatureRequestHistoryChangeFieldEnum = typeof FeatureRequestHistoryChangeFieldEnum[keyof typeof FeatureRequestHistoryChangeFieldEnum];- export const FieldEnum = {+ export const FeatureRequestHistoryChangeFieldEnum = {Status: 'status',Priority: 'priority',Account: 'account',@@ -38335,7 +38459,7 @@ export namespace Schemas {* * `accounts` - Accounts* * `evidence` - Evidence* * `product_areas` - Product areas */- readonly field: FieldEnum;+ readonly field: FeatureRequestHistoryChangeFieldEnum;/** Value before the update, including relation snapshots. */readonly before: FeatureRequestHistoryChangeBefore;/** Value after the update, including relation snapshots. */@@ -51057,6 +51181,15 @@ export namespace Schemas {results: AccountSupportTicketMessage[];}+ export interface PaginatedAccountTrackRuleRunViewList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: AccountTrackRuleRunView[];+ }+export interface PaginatedActionList {count: number;/** @nullable */@@ -86291,6 +86424,17 @@ export namespace Schemas {offset?: number;};+ export type AccountTrackRulesRunsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type AccountsListParams = {/*** When true, returns only accounts where no user actively holds any relationship.