Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(customer-analytics): track when a customer last messaged in the bound Slack channel (#75553)

Arthur Moreira de Deusd7c02eda4e48
diff --git a/products/conversations/backend/api/tests/test_slack_message_routing.py b/products/conversations/backend/api/tests/test_slack_message_routing.py
index 53dd7b617ad0..48564175b779 100644
--- a/products/conversations/backend/api/tests/test_slack_message_routing.py
+++ b/products/conversations/backend/api/tests/test_slack_message_routing.py
@@ -1,4 +1,5 @@
import json
+from datetime import UTC, datetime
from posthog.test.base import BaseTest
from unittest.mock import Mock, patch
@@ -25,9 +26,14 @@ from products.conversations.backend.slack import (
handle_support_reaction,
)
from products.conversations.backend.tasks import process_supporthog_interactivity
+from products.customer_analytics.backend.facade import api as customer_analytics
+from products.customer_analytics.backend.test.factories import create_account
MODULE = "products.conversations.backend.slack"
TASKS_MODULE = "products.conversations.backend.tasks"
+MESSAGE_TS = "1700000000.000100"
+MESSAGE_SENT_AT = datetime(2023, 11, 14, 22, 13, 20, 100, tzinfo=UTC)
+USE_TEAMMATE_EMAIL = "use-the-org-members-own-email"
class TestSlackMessageRouting(BaseTest):
@@ -449,6 +455,66 @@ class TestSlackMessageRouting(BaseTest):
mock_create_or_update.assert_not_called()
+class TestSlackLastCustomerMessage(BaseTest):
+ def setUp(self):
+ super().setUp()
+ cache.clear()
+ self.team.conversations_settings = {"slack_enabled": True, "slack_channel_id": "C_CONFIG"}
+ self.team.save()
+ self.account = create_account(team_id=self.team.id, _properties={"slack_channel_id": "C_CONFIG"})
+ for target in ("create_or_update_slack_ticket", "get_slack_client", "post_ticket_confirmation_prompt"):
+ patcher = patch(f"{MODULE}.{target}")
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _handle(self, **overrides) -> None:
+ event = {
+ "type": "message",
+ "channel": "C_CONFIG",
+ "ts": MESSAGE_TS,
+ "user": "U123",
+ "text": "Our exports are failing again",
+ **overrides,
+ }
+ handle_support_message(event, self.team, "T123")
+
+ def _recorded_values(self, account=None) -> list:
+ account_id = (account or self.account).id
+ return [
+ value.value for value in customer_analytics.list_active_custom_property_values(self.team.id, account_id)
+ ]
+
+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Customer", "email": "[email protected]"})
+ def test_customer_message_is_recorded_on_the_bound_account(self, _mock_resolve):
+ self._handle()
+
+ assert self._recorded_values() == [MESSAGE_SENT_AT]
+
+ @patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Customer", "email": "[email protected]"})
+ def test_a_bound_channel_outside_the_support_channels_is_still_recorded(self, _mock_resolve):
+ other = create_account(team_id=self.team.id, name="Beta Corp", _properties={"slack_channel_id": "C_OTHER"})
+
+ self._handle(channel="C_OTHER")
+
+ assert self._recorded_values(other) == [MESSAGE_SENT_AT]
+
+ @parameterized.expand(
+ [
+ ("bot", {"bot_id": "B1"}, "[email protected]"),
+ ("system subtype", {"subtype": "channel_join"}, "[email protected]"),
+ ("unbound channel", {"channel": "C_UNBOUND"}, "[email protected]"),
+ ("posthog teammate", {}, USE_TEAMMATE_EMAIL),
+ ("unresolved author", {}, None),
+ ]
+ )
+ def test_non_customer_messages_are_not_recorded(self, _name, overrides, email):
+ resolved = self.user.email if email == USE_TEAMMATE_EMAIL else email
+ with patch(f"{MODULE}.resolve_slack_user", return_value={"name": "X", "email": resolved}):
+ self._handle(**overrides)
+
+ assert self._recorded_values() == []
+
+
class TestSlackNudge(BaseTest):
def setUp(self):
super().setUp()
diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.py
index a2fcc9b429e3..93998a2156cb 100644
--- a/products/conversations/backend/slack.py
+++ b/products/conversations/backend/slack.py
@@ -11,6 +11,7 @@ All three converge to create_or_update_slack_ticket().
import re
import json
+from datetime import UTC, datetime
from types import MappingProxyType
from typing import Any, Literal, NamedTuple
from urllib.parse import urljoin, urlparse
@@ -24,6 +25,7 @@ import posthoganalytics
from slack_sdk import WebClient
from posthog.event_usage import groups, report_team_action
+from posthog.exceptions_capture import capture_exception
from posthog.models.comment import Comment
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
@@ -697,12 +699,48 @@ def _configured_support_channels(settings: dict) -> set[str]:
return ids
+def _record_last_slack_message(
+ team: Team, *, channel: str, slack_user_id: str, message_ts: str | None, is_bot: bool
+) -> None:
+ """Record the message time on the customer analytics account bound to `channel`.
+
+ Bound means the account carries the channel in its ``slack_channel_id`` property, which is
+ independent of ticketing — so this covers every channel the bot can see, not only the
+ configured support channels. Bots and PostHog teammates aren't customers, so their messages
+ don't count. Failures are captured and swallowed: this must not stop the ticket path.
+ """
+ if is_bot or not message_ts:
+ return
+
+ from products.customer_analytics.backend.facade import api as customer_analytics # noqa: PLC0415
+
+ try:
+ team_id = _get_team_id(team)
+ account = customer_analytics.get_account_ref_by_slack_channel_id(team_id, channel)
+ if account is None:
+ return
+ slack_user = resolve_slack_user(get_slack_client(team), slack_user_id)
+ # An unresolved email may belong to a teammate, so treat it as one.
+ email = slack_user.get("email")
+ if not email or resolve_posthog_user_for_slack(email, team):
+ return
+ customer_analytics.record_last_slack_message_at(
+ team_id=team_id,
+ account_id=account.id,
+ timestamp=datetime.fromtimestamp(float(message_ts), tz=UTC),
+ )
+ except Exception as e:
+ capture_exception(e, {"team_id": getattr(team, "id", None), "slack_channel_id": channel})
+
+
def handle_support_message(event: dict, team: Team, slack_team_id: str) -> None:
"""
Handle a Slack 'message' event for configured support channels.
Top-level messages create new tickets.
Thread replies add messages to existing tickets.
+ Any message from a customer also records the time on the account bound to the channel,
+ whether or not the channel is a support channel.
"""
channel = event.get("channel")
if not channel:
@@ -728,6 +766,8 @@ def handle_support_message(event: dict, team: Team, slack_team_id: str) -> None:
thread_ts = event.get("thread_ts")
message_ts = event.get("ts")
+ _record_last_slack_message(team, channel=channel, slack_user_id=slack_user_id, message_ts=message_ts, is_bot=is_bot)
+
if thread_ts:
if is_bot:
# Allow other bots' thread replies but skip our own bot to prevent loops
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 8c986d0bfbeb..89a157063232 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -75,6 +75,7 @@ from products.customer_analytics.backend.logic.usage_spike_notifications import
notify_managers_of_usage_spike as notify_managers_of_usage_spike,
)
from products.customer_analytics.backend.models import (
+ CANONICAL_DISPLAY_TYPE_BY_NAME,
Account,
AccountChannelSummary,
AccountRelationship,
@@ -695,6 +696,12 @@ class CustomPropertyDefinitionConflictError(Exception):
"""Raised when a custom property definition violates the per-team unique name constraint."""
+class CanonicalCustomPropertyReadOnlyError(Exception):
+ """Raised when an update would change a field PostHog owns on a canonical custom property —
+ its name or display type. Both are what the write path matches on, so a user editing them
+ would silently stop the values from being recorded (→ 400)."""
+
+
class ResourceForbiddenError(Exception):
"""Raised when the caller passes resource/object access checks at the team level but
lacks the object-level access required for the action — the view maps this to 403,
@@ -958,6 +965,7 @@ def _to_custom_property_definition_view(
target_type=definition.target_type,
group_type_index=definition.group_type_index,
is_big_number=definition.is_big_number,
+ is_canonical=definition.name in CANONICAL_DISPLAY_TYPE_BY_NAME,
created_at=definition.created_at,
created_by=definition.created_by_id,
updated_at=definition.updated_at,
@@ -1124,6 +1132,21 @@ def create_custom_property_definition(
return _to_custom_property_definition_view(definition)
+def _assert_canonical_fields_unchanged(definition: CustomPropertyDefinition, fields: dict[str, Any]) -> None:
+ """Refuse a rename or a type change on a canonical property — PostHog owns both.
+
+ Everything else on the definition (description, position in a view) stays editable. Deleting
+ it is allowed: the next recorded value recreates it.
+ """
+ if definition.name not in CANONICAL_DISPLAY_TYPE_BY_NAME:
+ return
+ for attr in ("name", "display_type"):
+ if attr in fields and fields[attr] != getattr(definition, attr):
+ raise CanonicalCustomPropertyReadOnlyError(
+ f"'{definition.name}' is set by PostHog, so its {attr.replace('_', ' ')} can't be changed."
+ )
+
+
def update_custom_property_definition(
*,
team_id: int,
@@ -1139,6 +1162,7 @@ def update_custom_property_definition(
definition = _get_team_scoped(CustomPropertyDefinition, team_id, definition_id)
if definition is None:
return None
+ _assert_canonical_fields_unchanged(definition, fields)
previous = CustomPropertyDefinition.objects.get(pk=definition.pk)
for attr, value in fields.items():
setattr(definition, attr, value)
@@ -2697,6 +2721,17 @@ def set_custom_property_value(
return _to_custom_property_value(row)
+def record_last_slack_message_at(*, team_id: int, account_id: str | UUID, timestamp: datetime) -> bool:
+ """Record when a customer last messaged in the Slack channel bound to `account_id`.
+
+ For conversations, which sees the messages. Throttled and self-creating — see the logic
+ function. Returns whether the stored value moved.
+ """
+ return _custom_property_values_logic.record_last_slack_message_at(
+ team_id=team_id, account_id=account_id, timestamp=timestamp
+ )
+
+
def list_active_custom_property_values(team_id: int, account_id: str | UUID) -> list[contracts.CustomPropertyValue]:
"""The account's current (non-deleted) custom property values as contracts, newest first."""
rows = _custom_property_values_logic.list_active_custom_property_values(team_id=team_id, account_id=account_id)
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index e03cdf312cc4..346b4eb35e39 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -394,6 +394,7 @@ class CustomPropertyDefinitionView:
# Only set for group targets: which group type (0-4) the property attaches to. Null otherwise.
group_type_index: int | None = None
is_big_number: bool = False
+ is_canonical: bool = False
created_at: datetime | None = None
created_by: int | None = None
updated_at: datetime | None = None
diff --git a/products/customer_analytics/backend/logic/custom_property_values.py b/products/customer_analytics/backend/logic/custom_property_values.py
index c3a82da61ceb..87066f50074b 100644
--- a/products/customer_analytics/backend/logic/custom_property_values.py
+++ b/products/customer_analytics/backend/logic/custom_property_values.py
@@ -7,7 +7,7 @@ Called by facade/api.py. Do not call from outside this module.
import math
from collections.abc import Callable
-from datetime import UTC, date, datetime
+from datetime import UTC, date, datetime, timedelta
from typing import Any
from uuid import UUID
@@ -20,6 +20,7 @@ from posthog.models.user import User
from products.customer_analytics.backend.events import emit_account_custom_property_changed
from products.customer_analytics.backend.models import (
+ CANONICAL_LAST_SLACK_MESSAGE_AT,
Account,
CustomPropertyDefinition,
CustomPropertyValue,
@@ -141,6 +142,49 @@ def set_account_custom_properties_by_id(
return rows
+MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES = timedelta(hours=1)
+_LAST_SLACK_MESSAGE_WRITE_ATTEMPTS = 3
+
+
+def record_last_slack_message_at(*, team_id: int, account_id: str | UUID, timestamp: datetime) -> bool:
+ """Record when a customer last messaged in the Slack channel bound to `account_id`.
+
+ Creates the canonical definition on first write for the team — no user owns it, so
+ `created_by` stays null and no activity-log entry is written. Skips the write when the stored
+ value is newer than `timestamp` (Slack events can arrive out of order) or less than
+ `MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES` behind it. Returns whether it wrote.
+
+ Raises `InvalidCustomPropertyValue` when the team already has a property under the canonical
+ name with a non-datetime type.
+ """
+ definition, _ = CustomPropertyDefinition.objects.for_team(team_id).get_or_create(
+ team_id=team_id,
+ name=CANONICAL_LAST_SLACK_MESSAGE_AT,
+ defaults={"display_type": DisplayType.DATETIME},
+ )
+ for _attempt in range(_LAST_SLACK_MESSAGE_WRITE_ATTEMPTS):
+ current = (
+ CustomPropertyValue.objects.for_team(team_id)
+ .filter(account_id=account_id, definition_id=definition.id, is_deleted=False)
+ .values_list("value_datetime", flat=True)
+ .first()
+ )
+ if current is not None and timestamp - current < MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES:
+ return False
+ try:
+ _set_value(
+ team_id=team_id,
+ account_id=account_id,
+ definition=definition,
+ value=timestamp,
+ created_by_id=None,
+ )
+ except CustomPropertyValueConflict:
+ continue
+ return True
+ return False
+
+
def _set_value(
*,
team_id: int,
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index b8e4f2712198..2b68225c5dce 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -3,6 +3,8 @@ from .account_channel_summary import AccountChannelSummary, SlackSummaryCadence
from .announcement import Announcement
from .announcement_delivery import AnnouncementDelivery
from .custom_property_definition import (
+ CANONICAL_DISPLAY_TYPE_BY_NAME,
+ CANONICAL_LAST_SLACK_MESSAGE_AT,
DATA_TYPE_BY_DISPLAY_TYPE,
CustomPropertyDefinition,
DataType,
@@ -19,6 +21,8 @@ from .relationship import AccountRelationship, AccountRelationshipDefinition
from .team_customer_analytics_config import TeamCustomerAnalyticsConfig
__all__ = [
+ "CANONICAL_DISPLAY_TYPE_BY_NAME",
+ "CANONICAL_LAST_SLACK_MESSAGE_AT",
"DATA_TYPE_BY_DISPLAY_TYPE",
"Account",
"AccountChannelSummary",
diff --git a/products/customer_analytics/backend/models/custom_property_definition.py b/products/customer_analytics/backend/models/custom_property_definition.py
index 4943433c7bed..b5b8dd50fa6d 100644
--- a/products/customer_analytics/backend/models/custom_property_definition.py
+++ b/products/customer_analytics/backend/models/custom_property_definition.py
@@ -46,6 +46,13 @@ NUMERIC_DISPLAY_TYPES = [
]
+CANONICAL_LAST_SLACK_MESSAGE_AT = "Last Slack message at"
+
+CANONICAL_DISPLAY_TYPE_BY_NAME: dict[str, DisplayType] = {
+ CANONICAL_LAST_SLACK_MESSAGE_AT: DisplayType.DATETIME,
+}
+
+
class CustomPropertyDefinition(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index 93a7ae303da7..cd2efb3a970a 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -658,6 +658,13 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
allow_null=True,
help_text="The data-warehouse view-sync binding feeding this property, or null when values are set manually.",
)
+ is_canonical = serializers.BooleanField(
+ read_only=True,
+ help_text=(
+ "True when PostHog writes this property itself. Its name and display type are fixed — "
+ "an update changing either is rejected."
+ ),
+ )
created_at = serializers.DateTimeField(read_only=True)
created_by = serializers.IntegerField(read_only=True, allow_null=True)
updated_at = serializers.DateTimeField(read_only=True, allow_null=True)
@@ -692,6 +699,7 @@ class CustomPropertyDefinitionSerializer(DataclassSerializer):
"target_type",
"group_type_index",
"is_big_number",
+ "is_canonical",
"options",
"source",
"created_at",
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index b6af7e32bd06..5add3022761a 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -404,6 +404,8 @@ class CustomPropertyDefinitionViewSet(
)
except api.CustomPropertyDefinitionConflictError as e:
raise Conflict(str(e))
+ except api.CanonicalCustomPropertyReadOnlyError as e:
+ raise ValidationError(str(e))
except api.InvalidCustomPropertyOptions as e:
raise ValidationError({"options": str(e)})
if definition is None:
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
index 3f66314e4e13..8a64d1771da4 100644
--- a/products/customer_analytics/backend/test/test_custom_property_values.py
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -1,4 +1,4 @@
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from uuid import UUID, uuid4
import pytest
@@ -18,16 +18,19 @@ from products.customer_analytics.backend.facade import (
contracts,
)
from products.customer_analytics.backend.logic.custom_property_values import (
+ MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES,
VALUE_SUGGESTIONS_LIMIT,
CustomPropertyDefinitionNotFound,
CustomPropertyValueConflict,
InvalidCustomPropertyValue,
list_active_custom_property_values,
list_custom_property_value_suggestions,
+ record_last_slack_message_at,
set_account_custom_properties_by_id,
set_custom_property_value,
)
from products.customer_analytics.backend.models import (
+ CANONICAL_LAST_SLACK_MESSAGE_AT,
Account,
CustomPropertyDefinition,
CustomPropertyValue,
@@ -400,6 +403,175 @@ class TestCustomPropertyValueFacade(BaseTest):
assert result[0].definition_id == plan.id
+class TestRecordLastSlackMessageAt(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.account = create_account(team_id=self.team.id, _properties={"slack_channel_id": "C_ACME"})
+ self.at = datetime(2026, 7, 29, 12, tzinfo=UTC)
+
+ def _record(self, timestamp: datetime) -> bool:
+ return record_last_slack_message_at(team_id=self.team.id, account_id=self.account.id, timestamp=timestamp)
+
+ def _active_values(self) -> list[datetime | None]:
+ return list(
+ CustomPropertyValue.objects.for_team(self.team.id)
+ .filter(is_deleted=False)
+ .values_list("value_datetime", flat=True)
+ )
+
+ def _row_count(self) -> int:
+ return CustomPropertyValue.objects.for_team(self.team.id).count()
+
+ def test_first_message_creates_the_canonical_definition(self):
+ assert self._record(self.at) is True
+
+ definition = CustomPropertyDefinition.objects.for_team(self.team.id).get(name=CANONICAL_LAST_SLACK_MESSAGE_AT)
+ assert definition.display_type == DisplayType.DATETIME
+ assert definition.created_by_id is None
+ assert self._active_values() == [self.at]
+
+ def test_message_within_the_interval_does_not_write(self):
+ self._record(self.at)
+
+ assert self._record(self.at + MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES - timedelta(minutes=1)) is False
+ assert self._active_values() == [self.at]
+ assert self._row_count() == 1
+
+ def test_message_after_the_interval_supersedes_the_value(self):
+ self._record(self.at)
+ later = self.at + MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES
+
+ assert self._record(later) is True
+ assert self._active_values() == [later]
+ # The superseded row stays for history.
+ assert self._row_count() == 2
+
+ def test_out_of_order_message_does_not_move_the_value_backwards(self):
+ self._record(self.at)
+
+ assert self._record(self.at - timedelta(days=1)) is False
+ assert self._active_values() == [self.at]
+
+ @patch(f"{LOGIC_MODULE}._set_value")
+ def test_losing_the_active_row_race_retries_instead_of_dropping_the_timestamp(self, mock_set_value):
+ later = self.at + MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES
+ mock_set_value.side_effect = [CustomPropertyValueConflict("rival won the active row"), None]
+
+ assert self._record(later) is True
+ assert mock_set_value.call_count == 2
+
+ @patch(f"{LOGIC_MODULE}._set_value")
+ def test_a_rival_storing_a_newer_value_stops_the_retry(self, mock_set_value):
+ # The rival's value lands before the retry re-reads, so the retry must skip rather than
+ # drag the stored value back to this older message.
+ newer = self.at + 2 * MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES
+
+ def store_newer_then_conflict(**kwargs):
+ self._set_active_value(newer)
+ raise CustomPropertyValueConflict("rival won the active row")
+
+ mock_set_value.side_effect = store_newer_then_conflict
+
+ assert self._record(self.at + MIN_INTERVAL_BETWEEN_LAST_SLACK_MESSAGE_WRITES) is False
+ assert self._active_values() == [newer]
+ # The retry re-read the rival's value and skipped, rather than writing again.
+ assert mock_set_value.call_count == 1
+
+ def _set_active_value(self, timestamp: datetime) -> None:
+ """Store a value the way a rival task would. Writes through the ORM, not the logic's own
+ write path — this test doubles that path, so going through it would store nothing."""
+ definition = CustomPropertyDefinition.objects.for_team(self.team.id).get(name=CANONICAL_LAST_SLACK_MESSAGE_AT)
+ rows = CustomPropertyValue.objects.for_team(self.team.id)
+ rows.filter(account_id=self.account.id, definition_id=definition.id, is_deleted=False).update(is_deleted=True)
+ rows.create(
+ team_id=self.team.id,
+ account_id=self.account.id,
+ definition_id=definition.id,
+ value_datetime=timestamp,
+ )
+
+ def test_a_conflicting_definition_type_rejects_the_write(self):
+ create_custom_property_definition(
+ team_id=self.team.id, name=CANONICAL_LAST_SLACK_MESSAGE_AT, display_type=DisplayType.TEXT
+ )
+
+ with pytest.raises(InvalidCustomPropertyValue):
+ self._record(self.at)
+
+ def test_facade_records_the_value(self):
+ assert (
+ facade.record_last_slack_message_at(team_id=self.team.id, account_id=self.account.id, timestamp=self.at)
+ is True
+ )
+ assert self._active_values() == [self.at]
+
+
+class TestCanonicalCustomPropertyDefinition(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.definition = create_custom_property_definition(
+ team_id=self.team.id, name=CANONICAL_LAST_SLACK_MESSAGE_AT, display_type=DisplayType.DATETIME
+ )
+
+ def _update(self, fields: dict) -> None:
+ with team_scope(self.team.id):
+ facade.update_custom_property_definition(
+ team_id=self.team.id,
+ definition_id=str(self.definition.id),
+ fields=fields,
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ @parameterized.expand([("name", "Something else"), ("display_type", DisplayType.TEXT.value)])
+ def test_posthog_owned_fields_cannot_be_changed(self, field, value):
+ with pytest.raises(facade.CanonicalCustomPropertyReadOnlyError):
+ self._update({field: value})
+
+ self.definition.refresh_from_db()
+ assert self.definition.name == CANONICAL_LAST_SLACK_MESSAGE_AT
+ assert self.definition.display_type == DisplayType.DATETIME
+
+ def test_the_rest_of_the_definition_stays_editable(self):
+ self._update({"description": "When the customer last posted in Slack"})
+
+ self.definition.refresh_from_db()
+ assert self.definition.description == "When the customer last posted in Slack"
+
+ @parameterized.expand([(CANONICAL_LAST_SLACK_MESSAGE_AT, True), ("Plan", False)])
+ def test_the_view_marks_canonical_definitions(self, name, expected):
+ definition = self.definition if expected else create_custom_property_definition(team_id=self.team.id, name=name)
+
+ with team_scope(self.team.id):
+ view = facade.get_custom_property_definition(
+ self.team.id, str(definition.id), user_access_control=self._uac()
+ )
+
+ assert view is not None
+ assert view.is_canonical is expected
+
+ def _uac(self):
+ uac = MagicMock()
+ uac.check_access_level_for_resource.return_value = True
+ return uac
+
+ def test_a_non_canonical_definition_can_be_renamed(self):
+ plan = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ with team_scope(self.team.id):
+ facade.update_custom_property_definition(
+ team_id=self.team.id,
+ definition_id=str(plan.id),
+ fields={"name": "Tier"},
+ organization_id=self.organization.id,
+ user=self.user,
+ was_impersonated=False,
+ )
+
+ plan.refresh_from_db()
+ assert plan.name == "Tier"
+
+
class TestSetExternalAccountCustomProperties(BaseTest):
def setUp(self):
super().setUp()
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts
index 807ceb5507d8..8ba7bf143710 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.test.ts
@@ -1,4 +1,6 @@
-import { buildHistoryDisplay } from './AccountsHogQLTable'
+import type { CustomPropertyDefinitionApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+import { buildHistoryDisplay, getCanonicalPropertyTab } from './AccountsHogQLTable'
const DAY = 24 * 60 * 60
const NOW_MS = 1_800_000_000_000
@@ -42,3 +44,20 @@ describe('buildHistoryDisplay', () => {
expect(buildHistoryDisplay([], 7, NOW_MS)).toEqual({ latest: null, baseline: null, chartPoints: [] })
})
})
+
+describe('getCanonicalPropertyTab', () => {
+ const definition = (name: string, isCanonical: boolean): CustomPropertyDefinitionApi =>
+ ({ name, is_canonical: isCanonical }) as CustomPropertyDefinitionApi
+
+ it('routes the last Slack message to the channel summaries', () => {
+ expect(getCanonicalPropertyTab(definition('Last Slack message at', true))).toBe('summaries')
+ })
+
+ it('does not link an ordinary property a user happened to name the same', () => {
+ expect(getCanonicalPropertyTab(definition('Last Slack message at', false))).toBeUndefined()
+ })
+
+ it('does not link a canonical property with no tab of its own', () => {
+ expect(getCanonicalPropertyTab(definition('Some future canonical property', true))).toBeUndefined()
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
index 34ad90738fd6..1db72eb03de3 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsHogQLTable.tsx
@@ -39,7 +39,7 @@ import {
LEGACY_ROLE_COLUMNS,
accountsColumnConfigLogic,
} from './accountsColumnConfigLogic'
-import { accountsExpansionLogic } from './accountsExpansionLogic'
+import { AccountExpansionTab, accountsExpansionLogic } from './accountsExpansionLogic'
import { accountsLogic, savingRoleKey } from './accountsLogic'
import { AccountsEvents } from './constants'
@@ -323,6 +323,51 @@ function CustomPropertyHistoryCell({
)
}
+const CANONICAL_PROPERTY_TAB: Record<string, AccountExpansionTab> = {
+ 'Last Slack message at': 'summaries',
+}
+
+export function getCanonicalPropertyTab(definition: CustomPropertyDefinitionApi): AccountExpansionTab | undefined {
+ return definition.is_canonical ? CANONICAL_PROPERTY_TAB[definition.name] : undefined
+}
+
+function CanonicalTimestampCell({
+ record,
+ definition,
+ value,
+ tab,
+}: {
+ record: unknown
+ definition: CustomPropertyDefinitionApi
+ value: string
+ tab: AccountExpansionTab
+}): JSX.Element {
+ const { visibleColumnNames } = useValues(accountsColumnConfigLogic)
+ const { openAccountTab } = useActions(accountsExpansionLogic)
+ const accountId = getNameCell(record, visibleColumnNames)?.id
+ const label = <TZLabel time={value} showSeconds={definition.display_type === 'datetime'} />
+
+ if (!accountId) {
+ return label
+ }
+ return (
+ <Link
+ to={urls.customerAnalyticsAccount(accountId, tab)}
+ onClick={(event) => {
+ // Modifier-click keeps the href's new-tab behavior, matching the account name cell.
+ if (event.metaKey || event.ctrlKey || event.shiftKey) {
+ return
+ }
+ event.preventDefault()
+ event.stopPropagation()
+ openAccountTab(accountId, tab)
+ }}
+ >
+ {label}
+ </Link>
+ )
+}
+
function CustomPropertyCell({
record,
column,
@@ -345,6 +390,10 @@ function CustomPropertyCell({
return <span className="text-muted">—</span>
}
if (definition.display_type === 'date' || definition.display_type === 'datetime') {
+ const tab = getCanonicalPropertyTab(definition)
+ if (tab) {
+ return <CanonicalTimestampCell record={record} definition={definition} value={value} tab={tab} />
+ }
return <TZLabel time={value} showSeconds={definition.display_type === 'datetime'} />
}
if (definition.display_type === 'boolean') {
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
index bf92ae934ba0..f456498c173c 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsColumnConfigLogic.test.ts
@@ -26,6 +26,7 @@ function definition(
name,
display_type: 'text',
is_big_number: false,
+ is_canonical: false,
description: null,
created_at: '2024-01-01T00:00:00Z',
created_by: null,
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 5d0cb4f66100..a5b3b97625a3 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -891,6 +891,8 @@ export interface CustomPropertyDefinitionApi {
group_type_index?: number | null
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean
+ /** True when PostHog writes this property itself. Its name and display type are fixed — an update changing either is rejected. */
+ readonly is_canonical: boolean
/**
* For select properties: the allowed options. Required (non-empty) when display_type is 'select'; cleared server-side for other types.
* @nullable
@@ -960,6 +962,8 @@ export interface PatchedCustomPropertyDefinitionApi {
group_type_index?: number | null
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean
+ /** True when PostHog writes this property itself. Its name and display type are fixed — an update changing either is rejected. */
+ readonly is_canonical?: boolean
/**
* For select properties: the allowed options. Required (non-empty) when display_type is 'select'; cleared server-side for other types.
* @nullable
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
index 86c134e22aaa..253be8057c57 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomPropertyModal.tsx
@@ -383,6 +383,8 @@ export function CustomPropertyModal(): JSX.Element {
const profileTargetAvailable = !!featureFlags[FEATURE_FLAGS.WAREHOUSE_PERSON_PROPERTIES] || isProfileTarget
const hasExistingSource = !!editingDefinition?.source
const noViews = !savedQueriesLoading && materializedViews.length === 0
+ const isCanonical = !!editingDefinition?.is_canonical
+ const canonicalReason = 'PostHog sets this property automatically, so its name and type are fixed.'
// While a workflow references the property it stays workflow-sourced no matter what is picked
// here, so the other options are locked until it's removed from the workflow(s).
@@ -446,8 +448,8 @@ export function CustomPropertyModal(): JSX.Element {
enableFormOnSubmit
className="flex flex-col gap-4"
>
- <LemonField name="name" label="Name">
- <LemonInput placeholder="e.g. ARR" autoFocus />
+ <LemonField name="name" label="Name" help={isCanonical ? canonicalReason : undefined}>
+ <LemonInput placeholder="e.g. ARR" autoFocus={!isCanonical} disabled={isCanonical} />
</LemonField>
<LemonField name="description" label="Description">
<LemonTextArea placeholder="Optional description" minRows={2} />
@@ -477,8 +479,12 @@ export function CustomPropertyModal(): JSX.Element {
person property is a raw $set value, so these are account-only. */}
{targetType === 'account' && (
<>
- <LemonField name="displayType" label="Type">
- <LemonSelect options={DISPLAY_TYPE_OPTIONS} fullWidth />
+ <LemonField name="displayType" label="Type" help={isCanonical ? canonicalReason : undefined}>
+ <LemonSelect
+ options={DISPLAY_TYPE_OPTIONS}
+ fullWidth
+ disabledReason={isCanonical ? canonicalReason : undefined}
+ />
</LemonField>
{showBigNumberSwitch && (
<LemonField name="isBigNumber">
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0d1970328379..8f0be1ac8b9d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15670,6 +15670,8 @@ export namespace Schemas {
group_type_index?: number | null;
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean;
+ /** True when PostHog writes this property itself. Its name and display type are fixed — an update changing either is rejected. */
+ readonly is_canonical: boolean;
/**
* For select properties: the allowed options. Required (non-empty) when display_type is 'select'; cleared server-side for other types.
* @nullable
@@ -48257,6 +48259,8 @@ export namespace Schemas {
group_type_index?: number | null;
/** Abbreviate large numbers (e.g. 10,000 → 10K). Only applies to numeric properties. */
is_big_number?: boolean;
+ /** True when PostHog writes this property itself. Its name and display type are fixed — an update changing either is rejected. */
+ readonly is_canonical?: boolean;
/**
* For select properties: the allowed options. Required (non-empty) when display_type is 'select'; cleared server-side for other types.
* @nullable