: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
fix(billing): attribute employee slack activity (#70419)
Abhischek116439c100e4
diff --git a/ee/billing/salesforce_enrichment/conversations_signals.py b/ee/billing/salesforce_enrichment/conversations_signals.pyindex 9ee584095ae8..72fbc5661162 100644--- a/ee/billing/salesforce_enrichment/conversations_signals.py+++ b/ee/billing/salesforce_enrichment/conversations_signals.py@@ -4,6 +4,7 @@ import datetime as dtfrom dataclasses import dataclassfrom django.conf import settings+from django.contrib.postgres.aggregates import ArrayAggfrom django.db.models import Case, Count, DateTimeField, Exists, Max, Min, OuterRef, Q, QuerySet, UUIDField, Whenfrom django.db.models.functions import Cast, Coalesce@@ -169,16 +170,64 @@ def _fetch_slack_channel_aggregate_rows(org_ids: list[str]) -> list[dict[str, ob.values("organization_id", "slack_team_id", "slack_channel_id").annotate(representative_team_id=Min("team_id"),+ team_ids=ArrayAgg("team_id", distinct=True),slack_issue_count=Count("id"),last_slack_activity=Max("activity_at"),)- .order_by(- "organization_id",- "-last_slack_activity",- "-slack_issue_count",- "slack_channel_id",- "slack_team_id",+ )+++def _fetch_trusted_slack_channel_activity_rows(+ channel_rows: list[dict[str, object]],+) -> list[dict[str, object]]:+ channel_filters = Q()+ for row in channel_rows:+ team_ids = row.get("team_ids")+ slack_channel_id = row.get("slack_channel_id")+ if (+ not isinstance(team_ids, list)+ or not team_ids+ or not isinstance(slack_channel_id, str)+ or not slack_channel_id+ ):+ continue++ # Filter by the group's full team set (a channel group can span teams, and the+ # team-led indexes anchor the query), and match slack_team_id by raw value+ # (None compiles to IS NULL) so the filter stays aligned with the lookup keys+ # built from these same rows.+ channel_filters |= Q(+ team_id__in=team_ids, slack_channel_id=slack_channel_id, slack_team_id=row.get("slack_team_id"))++ if not channel_filters:+ return []++ return list(+ Ticket.objects.filter(channel_filters, channel_source=Channel.SLACK, identity_verified=True)+ .annotate(activity_at=_activity_at())+ # Group by team as well as (workspace, channel): a team's Slack connection+ # pins the workspace, so the key stays unambiguous even when slack_team_id+ # is null — otherwise same-ID channels from unrelated orgs in the batch+ # would merge into one group.+ .values("team_id", "slack_team_id", "slack_channel_id")+ .annotate(last_slack_activity=Max("activity_at"))+ )+++def _trusted_channel_sort_key(row: dict[str, object]) -> tuple[str, float, int, str, bool, str]:+ last_slack_activity = row.get("last_slack_activity")+ activity_timestamp = last_slack_activity.timestamp() if isinstance(last_slack_activity, dt.datetime) else 0+ slack_issue_count = row.get("slack_issue_count")++ return (+ str(row["organization_id"]),+ -activity_timestamp,+ -(slack_issue_count if isinstance(slack_issue_count, int) else 0),+ str(row.get("slack_channel_id") or ""),+ # Rows with a known workspace win ties over workspace-less rows.+ row.get("slack_team_id") is None,+ str(row.get("slack_team_id") or ""),)@@ -203,11 +252,13 @@ def aggregate_conversations_slack_signals_for_orgs() -> dict[str, ConversationsSlackSignals]:"""Aggregate Conversations Slack signals for organizations.- Only tickets with verified org attribution count (see- ``_tickets_with_verified_org``). If an organization has multiple Slack- channels, choose the most recently active workspace-scoped channel, then- tie-break by ticket count and channel ID. Salesforce exposes a single- Slack channel field, so the issue/user/activity stats are for that+ Channels and issue counts come from tickets with verified org attribution+ (see ``_tickets_with_verified_org``). Once a channel is trusted that way,+ ``last_slack_activity`` reflects every identity-verified ticket in it, so+ replies attributed to another org (e.g. PostHog employees) still count as+ recency. If an organization has multiple Slack channels, choose the most+ recently active one, then tie-break by ticket count and channel ID.+ Salesforce exposes a single Slack channel field, so the stats are for thatrepresentative channel."""if not org_ids:@@ -215,8 +266,38 @@ def aggregate_conversations_slack_signals_for_orgs(LOGGER.info("fetching_conversations_slack_signals", org_count=len(org_ids))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)+ channel_activity_by_key = {+ (row.get("team_id"), row.get("slack_team_id"), row.get("slack_channel_id")): row.get("last_slack_activity")+ for row in channel_activity_rows+ }++ for row in rows:+ team_ids = row.get("team_ids")+ if not isinstance(team_ids, list):+ continue+ # Take the trusted max over the row's own team set, so activity stays scoped+ # to the channel group that established it even when slack_team_id is null.+ trusted_channel_activity: dt.datetime | None = None+ for team_id in team_ids:+ activity = channel_activity_by_key.get((team_id, row.get("slack_team_id"), row.get("slack_channel_id")))+ if isinstance(activity, dt.datetime) and (+ trusted_channel_activity is None or activity > trusted_channel_activity+ ):+ trusted_channel_activity = activity+ org_channel_activity = row.get("last_slack_activity")+ # The trusted set should cover every ticket behind the row's own max, so this+ # guard is insurance against the two queries drifting: never move activity+ # backwards.+ if trusted_channel_activity is not None and (+ not isinstance(org_channel_activity, dt.datetime) or trusted_channel_activity > org_channel_activity+ ):+ row["last_slack_activity"] = trusted_channel_activity++ rows.sort(key=_trusted_channel_sort_key)+selected_rows: dict[str, dict[str, object]] = {}for row in rows:org_id = str(row["organization_id"])diff --git a/ee/billing/test/test_conversations_signals.py b/ee/billing/test/test_conversations_signals.pyindex 4be0a6f3523b..73efd456bf10 100644--- a/ee/billing/test/test_conversations_signals.py+++ b/ee/billing/test/test_conversations_signals.py@@ -10,7 +10,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.models import Organization, User+from posthog.models import Organization, Team, Userfrom products.conversations.backend.models import TeamConversationsSlackConfig, Ticketfrom products.conversations.backend.models.constants import Channel@@ -34,8 +34,11 @@ class TestConversationsSlackSignals(SimpleTestCase):assert build_support_ticket_url(2, 1234) == "https://us.posthog.com/project/2/support/tickets/1234"@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_latest_tickets):+ def test_aggregates_latest_channel_for_org(+ self, mock_fetch_rows, mock_fetch_channel_activity, mock_fetch_latest_tickets+ ):org_id = "org-1"mock_fetch_rows.return_value = [{@@ -55,6 +58,7 @@ class TestConversationsSlackSignals(SimpleTestCase):"last_slack_activity": dt.datetime(2026, 6, 1, 12, 0, tzinfo=dt.UTC),},]+ mock_fetch_channel_activity.return_value = []mock_fetch_latest_tickets.return_value = [{"organization_id": org_id,@@ -77,10 +81,14 @@ class TestConversationsSlackSignals(SimpleTestCase):assert signals.most_recent_support_ticket_url == "https://us.posthog.com/project/2/support/tickets/1234"@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_latest_tickets):+ def test_returns_latest_support_ticket_without_slack_rows(+ self, mock_fetch_rows, mock_fetch_channel_activity, mock_fetch_latest_tickets+ ):org_id = "org-1"mock_fetch_rows.return_value = []+ mock_fetch_channel_activity.return_value = []mock_fetch_latest_tickets.return_value = [{"organization_id": org_id,@@ -102,9 +110,11 @@ class TestConversationsSlackSignals(SimpleTestCase):assert signals.most_recent_support_ticket_url == "https://us.posthog.com/project/2/support/tickets/5678"@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_latest_tickets):+ def test_returns_empty_when_no_rows(self, mock_fetch_rows, mock_fetch_channel_activity, mock_fetch_latest_tickets):mock_fetch_rows.return_value = []+ mock_fetch_channel_activity.return_value = []mock_fetch_latest_tickets.return_value = []result = aggregate_conversations_slack_signals_for_orgs(["org-1"], include_slack_user_count=False)@@ -143,9 +153,10 @@ class TestConversationsSlackSignalsDatabase(BaseTest):slack_team_id: str | None = "T123",distinct_id: str | None = None,identity_verified: bool | None = True,+ team: Team | None = None,) -> Ticket:return Ticket.objects.create_with_number(- team=self.team,+ team=team or self.team,widget_session_id=f"session-{uuid.uuid4()}",distinct_id=self.user.distinct_id if distinct_id is None else distinct_id,channel_source=Channel.SLACK,@@ -277,6 +288,69 @@ class TestConversationsSlackSignalsDatabase(BaseTest):== f"https://us.posthog.com/project/{self.team.id}/support/tickets/{legit_ticket.ticket_number}")+ def test_employee_activity_updates_a_trusted_customer_channel(self):+ customer_activity = dt.datetime(2026, 6, 29, 10, 0, tzinfo=dt.UTC)+ other_channel_activity = dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC)+ employee_activity = dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC)+ self._create_slack_ticket(channel_id="C_CUSTOMER", activity_at=customer_activity)+ most_recent_customer_ticket = self._create_slack_ticket(+ channel_id="C_OTHER", activity_at=other_channel_activity+ )++ employee_org, employee = self._create_member_of_other_org(f"employee-{uuid.uuid4()}@posthog.com")+ self._create_slack_ticket(+ org_id=str(employee_org.id),+ channel_id="C_CUSTOMER",+ activity_at=employee_activity,+ distinct_id=employee.distinct_id,+ )++ with self.settings(SITE_URL="https://us.posthog.com"):+ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)++ signals = result[self.org_id]+ assert signals.slack_channel_url == "https://app.slack.com/client/T123/C_CUSTOMER"+ assert signals.last_slack_activity == employee_activity+ assert signals.slack_issue_count == 1+ assert (+ signals.most_recent_support_ticket_url+ == f"https://us.posthog.com/project/{self.team.id}/support/tickets/{most_recent_customer_ticket.ticket_number}"+ )++ def test_unverified_ticket_does_not_bump_trusted_channel_activity(self):+ verified_activity = dt.datetime(2026, 6, 29, 10, 0, tzinfo=dt.UTC)+ self._create_slack_ticket(channel_id="C_CUSTOMER", activity_at=verified_activity)+ self._create_slack_ticket(+ channel_id="C_CUSTOMER",+ activity_at=dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC),+ distinct_id=f"stranger-{uuid.uuid4()}",+ identity_verified=False,+ )++ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)++ assert result[self.org_id].last_slack_activity == verified_activity++ def test_trusted_activity_covers_all_teams_in_a_channel_group(self):+ second_team = Team.objects.create(organization=self.organization, name="second")+ newest_customer_activity = dt.datetime(2026, 6, 29, 10, 0, tzinfo=dt.UTC)+ employee_activity = dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC)+ self._create_slack_ticket(channel_id="C_MULTI", activity_at=dt.datetime(2026, 6, 28, 10, 0, tzinfo=dt.UTC))+ self._create_slack_ticket(channel_id="C_MULTI", activity_at=newest_customer_activity, team=second_team)++ employee_org, employee = self._create_member_of_other_org(f"employee-{uuid.uuid4()}@posthog.com")+ self._create_slack_ticket(+ org_id=str(employee_org.id),+ channel_id="C_MULTI",+ activity_at=employee_activity,+ distinct_id=employee.distinct_id,+ team=second_team,+ )++ result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)++ assert result[self.org_id].last_slack_activity == employee_activity+def test_email_channel_ticket_verified_by_email_from(self):ticket = Ticket.objects.create_with_number(team=self.team,@@ -306,11 +380,10 @@ class TestConversationsSlackSignalsDatabase(BaseTest):activity_at=dt.datetime(2026, 6, 30, 10, 0, tzinfo=dt.UTC),slack_team_id="T_ONE",)- self._create_slack_ticket(- channel_id="C_SHARED",- activity_at=dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC),- slack_team_id="T_TWO",- )+ latest_activity = dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC)+ self._create_slack_ticket(channel_id="C_SHARED", activity_at=latest_activity, slack_team_id="T_TWO")+ # A workspace-less row tied on recency must lose to the known-workspace row.+ self._create_slack_ticket(channel_id="C_SHARED", activity_at=latest_activity, slack_team_id=None)result = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)@@ -318,6 +391,38 @@ class TestConversationsSlackSignalsDatabase(BaseTest):assert signals.slack_channel_url == "https://app.slack.com/client/T_TWO/C_SHARED"assert signals.slack_issue_count == 1+ def test_null_workspace_channel_activity_stays_scoped_to_its_org(self):+ own_activity = dt.datetime(2026, 6, 29, 12, 0, tzinfo=dt.UTC)+ self._create_slack_ticket(channel_id="C_OWN", activity_at=own_activity, slack_team_id=None)+ self._create_slack_ticket(+ channel_id="C_SHARED_ID",+ activity_at=dt.datetime(2026, 6, 29, 10, 0, tzinfo=dt.UTC),+ slack_team_id=None,+ )++ # Another org in the batch has a newer ticket in a different team whose+ # channel happens to reuse the same ID (channel IDs are only unique per+ # workspace, and here the workspace is unknown).+ 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")+ self._create_slack_ticket(+ org_id=str(other_org.id),+ channel_id="C_SHARED_ID",+ activity_at=dt.datetime(2026, 6, 30, 12, 0, tzinfo=dt.UTC),+ slack_team_id=None,+ distinct_id=other_user.distinct_id,+ team=other_team,+ )++ alone = aggregate_conversations_slack_signals_for_orgs([self.org_id], include_slack_user_count=False)+ together = aggregate_conversations_slack_signals_for_orgs(+ [self.org_id, str(other_org.id)], include_slack_user_count=False+ )++ assert together[self.org_id] == alone[self.org_id]+ 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_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"}