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(conversations): add inbound and bot join timestamps to Salesforce (#71862)

Abhischek8d5344305caa
diff --git a/ee/billing/salesforce_enrichment/constants.py b/ee/billing/salesforce_enrichment/constants.py
index c594459b8e70..ef295616d600 100644
--- a/ee/billing/salesforce_enrichment/constants.py
+++ b/ee/billing/salesforce_enrichment/constants.py
@@ -156,6 +156,8 @@ CONVERSATIONS_SLACK_FIELD_MAPPINGS: dict[str, str] = {
"slack_user_count": "slack_user_count__c",
"last_slack_activity": "last_slack_activity__c",
"most_recent_support_ticket_url": "Most_Recent_Support_Ticket__c",
+ "last_customer_message_at": "last_customer_message_at__c",
+ "slack_bot_joined_at": "slack_bot_joined_at__c",
}
PERSONAL_EMAIL_DOMAINS = {
diff --git a/ee/billing/salesforce_enrichment/conversations_signals.py b/ee/billing/salesforce_enrichment/conversations_signals.py
index 72fbc5661162..e87fd572b093 100644
--- a/ee/billing/salesforce_enrichment/conversations_signals.py
+++ b/ee/billing/salesforce_enrichment/conversations_signals.py
@@ -2,6 +2,7 @@
import datetime as dt
from dataclasses import dataclass
+from itertools import batched
from django.conf import settings
from django.contrib.postgres.aggregates import ArrayAgg
@@ -11,6 +12,10 @@ from django.db.models.functions import Cast, Coalesce
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.client.execute import query_with_columns
+from posthog.clickhouse.query_tagging import tags_context
+from posthog.models.comment import Comment
from posthog.models.organization import OrganizationMembership
from posthog.temporal.common.logger import get_logger
@@ -32,6 +37,8 @@ class ConversationsSlackSignals:
slack_user_count: int | None
last_slack_activity: dt.datetime | None
most_recent_support_ticket_url: str | None
+ last_customer_message_at: dt.datetime | None = None
+ slack_bot_joined_at: dt.datetime | None = None
def build_slack_channel_url(slack_channel_id: str, slack_team_id: str | None = None) -> str:
@@ -245,6 +252,133 @@ def _fetch_latest_support_ticket_rows(org_ids: list[str]) -> list[dict[str, obje
)
+# PostHog's own analytics project on US cloud; every region's internal analytics
+# (posthoganalytics.capture) reports into it.
+INTERNAL_ANALYTICS_TEAM_ID = 2
+_BOT_JOINED_CHANNEL_EVENT = "support slack bot joined channel"
+# Channel joins are only tracked since the event's introduction in July 2026; the bound
+# also lets ClickHouse prune partitions.
+_BOT_JOINED_TRACKING_SINCE = dt.datetime(2026, 7, 1, tzinfo=dt.UTC)
+
+
+def _fetch_slack_bot_joined_at_by_channel(
+ slack_channel_ids: list[str],
+) -> dict[tuple[str, str], dt.datetime]:
+ """First time the support Slack bot joined each (workspace, channel) pair.
+
+ ``_track_bot_joined_channel`` (products/conversations/backend/slack.py) reports
+ the join as an internal analytics event carrying the Slack workspace and channel
+ ids but no customer org, so callers match the timestamps to an org through the
+ org's selected channel.
+ """
+ if not slack_channel_ids:
+ return {}
+
+ query = """
+ SELECT
+ JSONExtractString(properties, 'slack_team_id') AS slack_team_id,
+ JSONExtractString(properties, 'slack_channel_id') AS slack_channel_id,
+ min(timestamp) AS bot_joined_at
+ FROM events
+ WHERE team_id = %(team_id)s
+ AND event = %(event)s
+ AND timestamp >= %(since)s
+ AND JSONExtractString(properties, 'slack_channel_id') IN %(channel_ids)s
+ GROUP BY slack_team_id, slack_channel_id
+ """
+ with tags_context(usage_report="salesforce_conversations_slack_signals"):
+ rows = query_with_columns(
+ query,
+ {
+ "team_id": INTERNAL_ANALYTICS_TEAM_ID,
+ "event": _BOT_JOINED_CHANNEL_EVENT,
+ "since": _BOT_JOINED_TRACKING_SINCE,
+ "channel_ids": slack_channel_ids,
+ },
+ workload=Workload.OFFLINE,
+ )
+
+ joined_at_by_channel: dict[tuple[str, str], dt.datetime] = {}
+ for row in rows:
+ value = row["bot_joined_at"]
+ if not isinstance(value, dt.datetime):
+ continue
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=dt.UTC)
+ joined_at_by_channel[(str(row["slack_team_id"]), str(row["slack_channel_id"]))] = value
+ return joined_at_by_channel
+
+
+def _lookup_slack_bot_joined_at(
+ joined_at_by_channel: dict[tuple[str, str], dt.datetime],
+ slack_team_id: str | None,
+ slack_channel_id: str | None,
+) -> dt.datetime | None:
+ """Resolve the bot-joined timestamp for a selected channel row.
+
+ Channel ids are only unique per workspace, so rows without a workspace id are
+ never matched — a channel-only match could return another workspace's join.
+ """
+ if slack_team_id is None or slack_channel_id is None:
+ return None
+ return joined_at_by_channel.get((slack_team_id, slack_channel_id))
+
+
+_COMMENT_ITEM_ID_CHUNK_SIZE = 1000
+
+
+def _fetch_last_customer_message_at_by_org(org_ids: list[str]) -> dict[str, dt.datetime]:
+ """Per org, ``created_at`` of the most recent customer-authored (non-staff) support message.
+
+ Messages live in ``Comment`` rows keyed by ``item_id`` (the ticket id as text,
+ with no FK), so this resolves the batch's verified tickets first and then takes
+ the max over their customer comments. Staff (``support``/``human``) and ``AI``
+ replies don't count, and neither do comments on tickets without verified org
+ attribution.
+ """
+ if not org_ids:
+ return {}
+
+ ticket_rows = (
+ _tickets_with_verified_org().filter(organization_id__in=org_ids).values_list("organization_id", "team_id", "id")
+ )
+ # Attribution keys on the exact (team_id, item_id) pair: the generic comments API
+ # lets any team write arbitrary item_id/item_context values, so a comment counts
+ # only when it lives on the ticket's own team.
+ org_by_ticket = {(team_id, str(ticket_id)): str(org_id) for org_id, team_id, ticket_id in ticket_rows}
+ team_ids = {team_id for team_id, _item_id in org_by_ticket}
+ item_ids = [item_id for _team_id, item_id in org_by_ticket]
+ if not org_by_ticket:
+ return {}
+
+ last_by_org: dict[str, dt.datetime] = {}
+ # Chunk item_id__in so one org with pathologically many tickets can't blow up a
+ # single SQL statement; each chunk stays on the (team_id, scope, item_id, deleted)
+ # comment index.
+ for chunk in batched(item_ids, _COMMENT_ITEM_ID_CHUNK_SIZE, strict=False):
+ comment_rows = (
+ Comment.objects.filter(
+ team_id__in=team_ids,
+ scope="conversations_ticket",
+ item_id__in=chunk,
+ item_context__author_type="customer",
+ deleted=False,
+ )
+ .values("team_id", "item_id")
+ .annotate(last_customer_message_at=Max("created_at"))
+ )
+ for row in comment_rows:
+ org_id = org_by_ticket.get((row["team_id"], str(row["item_id"])))
+ value = row["last_customer_message_at"]
+ if (
+ org_id is not None
+ and isinstance(value, dt.datetime)
+ and (org_id not in last_by_org or value > last_by_org[org_id])
+ ):
+ last_by_org[org_id] = value
+ return last_by_org
+
+
def aggregate_conversations_slack_signals_for_orgs(
org_ids: list[str],
*,
@@ -268,6 +402,7 @@ def aggregate_conversations_slack_signals_for_orgs(
rows = _fetch_slack_channel_aggregate_rows(org_ids)
channel_activity_rows = _fetch_trusted_slack_channel_activity_rows(rows)
latest_ticket_rows = _fetch_latest_support_ticket_rows(org_ids)
+ last_customer_message_at_by_org = _fetch_last_customer_message_at_by_org(org_ids)
channel_activity_by_key = {
(row.get("team_id"), row.get("slack_team_id"), row.get("slack_channel_id")): row.get("last_slack_activity")
@@ -310,6 +445,16 @@ def aggregate_conversations_slack_signals_for_orgs(
if org_id not in selected_latest_ticket_rows:
selected_latest_ticket_rows[org_id] = row
+ selected_channel_ids: set[str] = set()
+ for row in selected_rows.values():
+ channel_id = row.get("slack_channel_id")
+ workspace_id = row.get("slack_team_id")
+ # Workspace-less rows can never be matched (see _lookup_slack_bot_joined_at),
+ # so don't fetch their channels.
+ if isinstance(channel_id, str) and channel_id and isinstance(workspace_id, str) and workspace_id:
+ selected_channel_ids.add(channel_id)
+ bot_joined_at_by_channel = _fetch_slack_bot_joined_at_by_channel(sorted(selected_channel_ids))
+
result: dict[str, ConversationsSlackSignals] = {}
for org_id in sorted(set(selected_rows) | set(selected_latest_ticket_rows)):
row = selected_rows.get(org_id, {})
@@ -354,6 +499,8 @@ def aggregate_conversations_slack_signals_for_orgs(
slack_user_count=slack_user_count,
last_slack_activity=last_slack_activity,
most_recent_support_ticket_url=most_recent_support_ticket_url,
+ last_customer_message_at=last_customer_message_at_by_org.get(org_id),
+ slack_bot_joined_at=_lookup_slack_bot_joined_at(bot_joined_at_by_channel, slack_team_id, slack_channel_id),
)
LOGGER.info("fetched_conversations_slack_signals", org_count=len(org_ids), signals_found=len(result))
diff --git a/ee/billing/test/test_conversations_signals.py b/ee/billing/test/test_conversations_signals.py
index 73efd456bf10..cd4d68a30d34 100644
--- a/ee/billing/test/test_conversations_signals.py
+++ b/ee/billing/test/test_conversations_signals.py
@@ -10,13 +10,17 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.clickhouse.client.connection import Workload
from posthog.models import Organization, Team, User
+from posthog.models.comment import Comment
from products.conversations.backend.models import TeamConversationsSlackConfig, Ticket
from products.conversations.backend.models.constants import Channel
from ee.billing.salesforce_enrichment.conversations_signals import (
+ _fetch_slack_bot_joined_at_by_channel,
_get_slack_bot_token,
+ _lookup_slack_bot_joined_at,
aggregate_conversations_slack_signals_for_orgs,
build_slack_channel_url,
build_support_ticket_url,
@@ -33,11 +37,18 @@ class TestConversationsSlackSignals(SimpleTestCase):
with self.settings(SITE_URL="https://us.posthog.com"):
assert build_support_ticket_url(2, 1234) == "https://us.posthog.com/project/2/support/tickets/1234"
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_bot_joined_at_by_channel")
+ @patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_last_customer_message_at_by_org")
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_latest_support_ticket_rows")
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_trusted_slack_channel_activity_rows")
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_channel_aggregate_rows")
def test_aggregates_latest_channel_for_org(
- self, mock_fetch_rows, mock_fetch_channel_activity, mock_fetch_latest_tickets
+ self,
+ mock_fetch_rows,
+ mock_fetch_channel_activity,
+ mock_fetch_latest_tickets,
+ mock_fetch_last_customer,
+ mock_fetch_bot_joined,
):
org_id = "org-1"
mock_fetch_rows.return_value = [
@@ -67,6 +78,8 @@ class TestConversationsSlackSignals(SimpleTestCase):
"activity_at": dt.datetime(2026, 6, 30, 8, 0, tzinfo=dt.UTC),
}
]
+ mock_fetch_last_customer.return_value = {org_id: dt.datetime(2026, 6, 28, 14, 30, tzinfo=dt.UTC)}
+ mock_fetch_bot_joined.return_value = {("T123", "C_NEW"): dt.datetime(2026, 7, 5, 9, 0, tzinfo=dt.UTC)}
with self.settings(SITE_URL="https://us.posthog.com"):
result = aggregate_conversations_slack_signals_for_orgs([org_id], include_slack_user_count=False)
@@ -79,12 +92,27 @@ class TestConversationsSlackSignals(SimpleTestCase):
assert signals.slack_user_count is None
assert signals.last_slack_activity == dt.datetime(2026, 6, 29, 9, 0, tzinfo=dt.UTC)
assert signals.most_recent_support_ticket_url == "https://us.posthog.com/project/2/support/tickets/1234"
+ assert signals.last_customer_message_at == dt.datetime(2026, 6, 28, 14, 30, tzinfo=dt.UTC)
+ assert signals.slack_bot_joined_at == dt.datetime(2026, 7, 5, 9, 0, tzinfo=dt.UTC)
+ @patch(
+ "ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_bot_joined_at_by_channel",
+ return_value={},
+ )
+ @patch(
+ "ee.billing.salesforce_enrichment.conversations_signals._fetch_last_customer_message_at_by_org",
+ return_value={},
+ )
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_latest_support_ticket_rows")
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_trusted_slack_channel_activity_rows")
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_channel_aggregate_rows")
def test_returns_latest_support_ticket_without_slack_rows(
- self, mock_fetch_rows, mock_fetch_channel_activity, mock_fetch_latest_tickets
+ self,
+ mock_fetch_rows,
+ mock_fetch_channel_activity,
+ mock_fetch_latest_tickets,
+ _mock_fetch_last_customer,
+ _mock_fetch_bot_joined,
):
org_id = "org-1"
mock_fetch_rows.return_value = []
@@ -109,10 +137,25 @@ class TestConversationsSlackSignals(SimpleTestCase):
assert signals.last_slack_activity is None
assert signals.most_recent_support_ticket_url == "https://us.posthog.com/project/2/support/tickets/5678"
+ @patch(
+ "ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_bot_joined_at_by_channel",
+ return_value={},
+ )
+ @patch(
+ "ee.billing.salesforce_enrichment.conversations_signals._fetch_last_customer_message_at_by_org",
+ return_value={},
+ )
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_latest_support_ticket_rows")
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_trusted_slack_channel_activity_rows")
@patch("ee.billing.salesforce_enrichment.conversations_signals._fetch_slack_channel_aggregate_rows")
- def test_returns_empty_when_no_rows(self, mock_fetch_rows, mock_fetch_channel_activity, mock_fetch_latest_tickets):
+ def test_returns_empty_when_no_rows(
+ self,
+ mock_fetch_rows,
+ mock_fetch_channel_activity,
+ mock_fetch_latest_tickets,
+ _mock_fetch_last_customer,
+ _mock_fetch_bot_joined,
+ ):
mock_fetch_rows.return_value = []
mock_fetch_channel_activity.return_value = []
mock_fetch_latest_tickets.return_value = []
@@ -121,6 +164,75 @@ class TestConversationsSlackSignals(SimpleTestCase):
assert result == {}
+ @patch("ee.billing.salesforce_enrichment.conversations_signals.query_with_columns")
+ def test_fetch_slack_bot_joined_at_keys_rows_by_workspace_and_channel(self, mock_query):
+ # The ClickHouse driver can return naive datetimes; they must come back UTC-aware.
+ # A row without a datetime value must be skipped, not crash or store None.
+ mock_query.return_value = [
+ {"slack_team_id": "T123", "slack_channel_id": "C1", "bot_joined_at": dt.datetime(2026, 7, 5, 9, 0)},
+ {
+ "slack_team_id": "T999",
+ "slack_channel_id": "C2",
+ "bot_joined_at": dt.datetime(2026, 7, 6, 10, 0, tzinfo=dt.UTC),
+ },
+ {"slack_team_id": "T000", "slack_channel_id": "C3", "bot_joined_at": None},
+ ]
+
+ result = _fetch_slack_bot_joined_at_by_channel(["C1", "C2"])
+
+ assert result == {
+ ("T123", "C1"): dt.datetime(2026, 7, 5, 9, 0, tzinfo=dt.UTC),
+ ("T999", "C2"): dt.datetime(2026, 7, 6, 10, 0, tzinfo=dt.UTC),
+ }
+
+ # Pin the ClickHouse contract with the emitter (_track_bot_joined_channel) as
+ # literal values: if the event name, internal analytics team, or tracking-since
+ # bound drifts, this fails instead of Salesforce silently going empty.
+ query, params = mock_query.call_args.args
+ assert params == {
+ "team_id": 2,
+ "event": "support slack bot joined channel",
+ "since": dt.datetime(2026, 7, 1, tzinfo=dt.UTC),
+ "channel_ids": ["C1", "C2"],
+ }
+ assert mock_query.call_args.kwargs == {"workload": Workload.OFFLINE}
+ for fragment in (
+ "team_id = %(team_id)s",
+ "event = %(event)s",
+ "timestamp >= %(since)s",
+ "min(timestamp) AS bot_joined_at",
+ "JSONExtractString(properties, 'slack_team_id')",
+ "JSONExtractString(properties, 'slack_channel_id') IN %(channel_ids)s",
+ "GROUP BY slack_team_id, slack_channel_id",
+ ):
+ assert fragment in query
+
+ @patch("ee.billing.salesforce_enrichment.conversations_signals.query_with_columns")
+ def test_fetch_slack_bot_joined_at_skips_query_without_channels(self, mock_query):
+ # An empty IN () clause is a ClickHouse syntax error, so the guard is load-bearing.
+ assert _fetch_slack_bot_joined_at_by_channel([]) == {}
+ mock_query.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("workspace_match", "T123", "C1", dt.datetime(2026, 7, 5, 9, 0, tzinfo=dt.UTC)),
+ ("workspace_mismatch", "T999", "C1", None),
+ # Channel ids are only unique per workspace, so a workspace-less row is
+ # never matched even when a channel id lines up.
+ ("no_workspace", None, "C1", None),
+ ("no_channel", "T123", None, None),
+ ]
+ )
+ def test_lookup_slack_bot_joined_at(
+ self, _name: str, slack_team_id: str | None, slack_channel_id: str | None, expected: dt.datetime | None
+ ) -> None:
+ joined_at_by_channel = {
+ ("T123", "C1"): dt.datetime(2026, 7, 5, 9, 0, tzinfo=dt.UTC),
+ ("T456", "C1"): dt.datetime(2026, 7, 4, 8, 0, tzinfo=dt.UTC),
+ }
+
+ assert _lookup_slack_bot_joined_at(joined_at_by_channel, slack_team_id, slack_channel_id) == expected
+
@patch("ee.billing.salesforce_enrichment.conversations_signals.WebClient")
@patch("ee.billing.salesforce_enrichment.conversations_signals._get_slack_bot_token")
def test_fetch_slack_channel_user_count_paginates(self, mock_get_token, mock_web_client):
@@ -172,6 +284,21 @@ class TestConversationsSlackSignalsDatabase(BaseTest):
user = User.objects.create_and_join(organization, email, None)
return organization, user
+ def _create_ticket_comment(
+ self, ticket: Ticket, author_type: str, created_at: dt.datetime, deleted: bool = False
+ ) -> Comment:
+ comment = Comment.objects.create(
+ team=ticket.team,
+ scope="conversations_ticket",
+ item_id=str(ticket.id),
+ content="message",
+ item_context={"author_type": author_type, "is_private": False},
+ deleted=deleted,
+ )
+ # created_at is auto_now_add, so backdate it after the fact.
+ Comment.objects.filter(id=comment.id).update(created_at=created_at)
+ return comment
+
def test_aggregate_query_applies_recency_and_tie_break_ordering(self):
selected_activity = dt.datetime(2026, 6, 30, 11, 0, tzinfo=dt.UTC)
most_recent_ticket = self._create_slack_ticket(channel_id="C_NEW", activity_at=selected_activity)
@@ -423,6 +550,93 @@ class TestConversationsSlackSignalsDatabase(BaseTest):
assert together[self.org_id].slack_channel_url == "https://app.slack.com/archives/C_OWN"
assert together[self.org_id].last_slack_activity == own_activity
+ def test_last_customer_message_at_counts_only_customer_comments_on_verified_tickets(self):
+ slack_ticket = self._create_slack_ticket(
+ channel_id="C123", activity_at=dt.datetime(2026, 6, 28, 10, 0, tzinfo=dt.UTC)
+ )
+ expected = dt.datetime(2026, 6, 29, 11, 0, tzinfo=dt.UTC)
+ self._create_ticket_comment(slack_ticket, "customer", dt.datetime(2026, 6, 28, 10, 0, tzinfo=dt.UTC))
+ # Staff, AI, and deleted-customer messages are all newer but must not count.
+ self._create_ticket_comment(slack_ticket, "support", dt.datetime(2026, 6, 30, 9, 0, tzinfo=dt.UTC))
+ self._create_ticket_comment(slack_ticket, "AI", dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC))
+ self._create_ticket_comment(
+ slack_ticket, "customer", dt.datetime(2026, 6, 30, 11, 0, tzinfo=dt.UTC), deleted=True
+ )
+
+ # The org-wide max spans channels: a newer customer message on an email ticket wins.
+ email_ticket = Ticket.objects.create_with_number(
+ team=self.team,
+ widget_session_id=f"session-{uuid.uuid4()}",
+ distinct_id="",
+ channel_source=Channel.EMAIL,
+ email_from=self.user.email,
+ organization_id=self.org_id,
+ last_message_at=expected,
+ identity_verified=True,
+ )
+ self._create_ticket_comment(email_ticket, "customer", expected)
+
+ # Customer messages on unverified tickets must not count.
+ unverified_ticket = self._create_slack_ticket(
+ channel_id="C_UNVERIFIED",
+ activity_at=dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC),
+ identity_verified=False,
+ )
+ self._create_ticket_comment(unverified_ticket, "customer", dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC))
+
+ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)
+
+ assert result[self.org_id].last_customer_message_at == expected
+
+ def test_last_customer_message_at_stays_scoped_per_org_within_a_batch(self):
+ # Both orgs' teams land in the same batch-wide comment query, so attribution
+ # must key on the ticket (item_id), not the team set — a regression here would
+ # hand one org the other's newer timestamp.
+ own_time = dt.datetime(2026, 6, 29, 10, 0, tzinfo=dt.UTC)
+ own_ticket = self._create_slack_ticket(channel_id="C_OWN", activity_at=own_time)
+ self._create_ticket_comment(own_ticket, "customer", own_time)
+
+ other_org, other_user = self._create_member_of_other_org(f"other-{uuid.uuid4()}@posthog.com")
+ other_team = Team.objects.create(organization=other_org, name="other")
+ other_time = dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC)
+ other_ticket = self._create_slack_ticket(
+ org_id=str(other_org.id),
+ channel_id="C_OTHER",
+ activity_at=other_time,
+ distinct_id=other_user.distinct_id,
+ team=other_team,
+ )
+ self._create_ticket_comment(other_ticket, "customer", other_time)
+
+ # A comment forged through the generic comments API — created under the other
+ # org's team but pointing at this org's ticket — must not count either.
+ forged = Comment.objects.create(
+ team=other_team,
+ scope="conversations_ticket",
+ item_id=str(own_ticket.id),
+ content="forged",
+ item_context={"author_type": "customer", "is_private": False},
+ deleted=False,
+ )
+ Comment.objects.filter(id=forged.id).update(created_at=dt.datetime(2026, 7, 1, 9, 0, tzinfo=dt.UTC))
+
+ result = aggregate_conversations_slack_signals_for_orgs(
+ [self.org_id, str(other_org.id)], include_slack_user_count=False
+ )
+
+ assert result[self.org_id].last_customer_message_at == own_time
+ assert result[str(other_org.id)].last_customer_message_at == other_time
+
+ def test_last_customer_message_at_is_none_without_customer_comments(self):
+ ticket = self._create_slack_ticket(
+ channel_id="C123", activity_at=dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC)
+ )
+ self._create_ticket_comment(ticket, "support", dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC))
+
+ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)
+
+ assert result[self.org_id].last_customer_message_at is None
+
def test_get_slack_bot_token_resolves_by_workspace_then_team(self):
TeamConversationsSlackConfig.objects.update_or_create(
team=self.team, defaults={"slack_team_id": "TWORK", "slack_bot_token": "xoxb-test"}
diff --git a/posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py b/posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py
index e1abfd7ec5f0..f006051166fb 100644
--- a/posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py
+++ b/posthog/temporal/salesforce_enrichment/conversations_slack_workflow.py
@@ -88,8 +88,10 @@ def prepare_conversations_slack_update_record(
if value is None:
continue
- if attr == "last_slack_activity" and isinstance(value, dt.datetime):
- record[sf_field] = value.date().isoformat()
+ if isinstance(value, dt.datetime):
+ # last_slack_activity__c is a Date field in Salesforce; the newer
+ # datetime signals map to DateTime fields and keep full precision.
+ record[sf_field] = value.date().isoformat() if attr == "last_slack_activity" else value.isoformat()
continue
record[sf_field] = value
@@ -99,8 +101,9 @@ def prepare_conversations_slack_update_record(
def _serialize_signals(signals: ConversationsSlackSignals) -> dict[str, Any]:
serialized = dataclasses.asdict(signals)
- if signals.last_slack_activity is not None:
- serialized["last_slack_activity"] = signals.last_slack_activity.isoformat()
+ for attr, value in serialized.items():
+ if isinstance(value, dt.datetime):
+ serialized[attr] = value.isoformat()
return serialized
diff --git a/posthog/temporal/tests/salesforce_enrichment/test_conversations_slack_workflow.py b/posthog/temporal/tests/salesforce_enrichment/test_conversations_slack_workflow.py
index 394b7db315b7..8d7430a84cc2 100644
--- a/posthog/temporal/tests/salesforce_enrichment/test_conversations_slack_workflow.py
+++ b/posthog/temporal/tests/salesforce_enrichment/test_conversations_slack_workflow.py
@@ -62,11 +62,13 @@ def _signals(
slack_user_count=12,
last_slack_activity=last_slack_activity or dt.datetime(2026, 6, 29, 15, 30, tzinfo=dt.UTC),
most_recent_support_ticket_url=f"https://us.posthog.com/project/2/support/tickets/{1000 if org_id == 'org-1' else 1001}",
+ last_customer_message_at=dt.datetime(2026, 6, 28, 14, 30, tzinfo=dt.UTC),
+ slack_bot_joined_at=dt.datetime(2026, 7, 5, 9, 0, tzinfo=dt.UTC),
)
class TestPrepareConversationsSlackUpdateRecord(SimpleTestCase):
- def test_formats_last_slack_activity_as_salesforce_date(self):
+ def test_formats_datetime_fields_per_salesforce_field_type(self):
record = prepare_conversations_slack_update_record("001ABC", _signals())
assert record == {
@@ -74,8 +76,11 @@ class TestPrepareConversationsSlackUpdateRecord(SimpleTestCase):
"Slack_Channel__c": "https://app.slack.com/client/T123/C123",
"slack_issue_count__c": 3,
"slack_user_count__c": 12,
+ # last_slack_activity__c is a Date field; the newer timestamp fields are DateTime.
"last_slack_activity__c": "2026-06-29",
"Most_Recent_Support_Ticket__c": "https://us.posthog.com/project/2/support/tickets/1000",
+ "last_customer_message_at__c": "2026-06-28T14:30:00+00:00",
+ "slack_bot_joined_at__c": "2026-07-05T09:00:00+00:00",
}
def test_omits_none_fields(self):
@@ -86,6 +91,8 @@ class TestPrepareConversationsSlackUpdateRecord(SimpleTestCase):
slack_user_count=None,
last_slack_activity=None,
most_recent_support_ticket_url=None,
+ last_customer_message_at=None,
+ slack_bot_joined_at=None,
)
record = prepare_conversations_slack_update_record("001ABC", signals)