: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(conversations): attribute slack tickets to accounts via channel fallback (#72571)
Abigailce548ae11ff8
diff --git a/frontend/src/scenes/groups/RelatedGroups.tsx b/frontend/src/scenes/groups/RelatedGroups.tsxindex f0e7fe2f53f4..a43ebf166ce9 100644--- a/frontend/src/scenes/groups/RelatedGroups.tsx+++ b/frontend/src/scenes/groups/RelatedGroups.tsx@@ -23,6 +23,8 @@ export interface RelatedGroupsProps {highlightGroupKey?: string | null/** Label for the tag on the highlighted row. Required for the tag to render. */highlightLabel?: string+ /** Tooltip shown on the highlight label tag (caller supplies the context-specific wording). */+ highlightLabelTooltip?: string/** Also show a "Stale" tag on the highlighted row. */highlightStale?: boolean/** Tooltip shown on the "Stale" tag (caller supplies the context-specific wording). */@@ -39,6 +41,7 @@ export function RelatedGroups({embedded = false,highlightGroupKey,highlightLabel,+ highlightLabelTooltip,highlightStale = false,highlightStaleTooltip,extraActors,@@ -80,9 +83,11 @@ export function RelatedGroups({<div className="flex items-center gap-2"><GroupActorDisplay actor={actor} />{isHighlighted && highlightLabel && (- <LemonTag type="muted" size="small">- {highlightLabel}- </LemonTag>+ <Tooltip title={highlightLabelTooltip}>+ <LemonTag type="muted" size="small">+ {highlightLabel}+ </LemonTag>+ </Tooltip>)}{isHighlighted && highlightStale && (<Tooltip title={highlightStaleTooltip}>@@ -98,7 +103,14 @@ export function RelatedGroups({},},],- [aggregationLabel, highlightGroupKey, highlightLabel, highlightStale, highlightStaleTooltip]+ [+ aggregationLabel,+ highlightGroupKey,+ highlightLabel,+ highlightLabelTooltip,+ highlightStale,+ highlightStaleTooltip,+ ])const nouns: [string, string] =diff --git a/products/conversations/backend/api/tests/test_events.py b/products/conversations/backend/api/tests/test_events.pyindex f136ae4d7a27..2f51556f6819 100644--- a/products/conversations/backend/api/tests/test_events.py+++ b/products/conversations/backend/api/tests/test_events.py@@ -24,6 +24,8 @@ from products.conversations.backend.events import (capture_ticket_status_changed,)from products.conversations.backend.models import Ticket, TicketAssignment+from products.conversations.backend.models.constants import OrganizationIdSource+from products.customer_analytics.backend.facade import contracts as ca_contractsfrom ee.models.rbac.role import Role@@ -1023,8 +1025,12 @@ class TestConversationEvents(BaseTest):assert self.ticket.organization_id is Nonecapture_ticket_created(self.ticket)- self.ticket.refresh_from_db()- assert self.ticket.organization_id == str(person_org.id)+ # Fetch a fresh instance: refresh_from_db() on self.ticket would leave mypy's+ # None-narrowing from the precondition assert in place, making the equality+ # assert "unreachable".+ stored = Ticket.objects.get(id=self.ticket.id)+ assert stored.organization_id == str(person_org.id)+ assert stored.organization_id_source == OrganizationIdSource.PERSON@patch("products.conversations.backend.events.capture_internal")@patch("products.conversations.backend.events._resolve_org_groups")@@ -1042,6 +1048,169 @@ class TestConversationEvents(BaseTest):assert groups["project"] == str(self.team.uuid)assert groups["instance"] == SITE_URL+ def _configure_account_group_type(self, index: int | None) -> None:+ config = self.team.customer_analytics_config+ config.account_group_type_index = index+ config.save()++ def _create_slack_ticket(self, distinct_id: str = "", slack_channel_id: str | None = "C123") -> Ticket:+ return Ticket.objects.create_with_number(+ team=self.team,+ widget_session_id="",+ distinct_id=distinct_id,+ channel_source="slack",+ slack_channel_id=slack_channel_id,+ slack_thread_ts="1234.5678",+ anonymous_traits={"name": "Unknown"},+ )++ @patch("products.customer_analytics.backend.facade.api.get_account_ref_by_slack_channel_id")+ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events.get_group_types_for_project")+ def test_capture_ticket_created_slack_channel_account_fallback(+ self, mock_group_types, mock_capture, mock_get_account+ ):+ """Unidentified Slack requester: the ticket is attributed to the customer analytics+ account bound to its channel, and the provenance is persisted for the UI."""+ self._configure_account_group_type(1)+ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 1}]+ mock_get_account.return_value = ca_contracts.AccountRef(+ id=str(uuid.uuid4()), name="Acme Corp", external_id="acme-org-1"+ )++ ticket = self._create_slack_ticket()+ capture_ticket_created(ticket)++ mock_get_account.assert_called_once_with(self.team.id, "C123")+ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is False+ assert call_kwargs["properties"]["$groups"] == {+ "instance": SITE_URL,+ "project": str(self.team.uuid),+ "organization": "acme-org-1",+ }+ ticket.refresh_from_db()+ assert ticket.organization_id == "acme-org-1"+ assert ticket.organization_id_source == OrganizationIdSource.SLACK_CHANNEL_ACCOUNT++ @parameterized.expand(+ [+ # name, config_index, account_ref_kwargs (None -> facade returns None), ticket_channel, expect_lookup+ ("config_index_unset", None, {"external_id": "acme-org-1"}, "C123", False),+ ("config_index_not_in_group_types", 3, {"external_id": "acme-org-1"}, "C123", False),+ ("no_matching_account", 1, None, "C123", True),+ ("account_without_external_id", 1, {"external_id": None}, "C123", True),+ ("ticket_without_slack_channel", 1, {"external_id": "acme-org-1"}, None, False),+ ]+ )+ @patch("products.customer_analytics.backend.facade.api.get_account_ref_by_slack_channel_id")+ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events.get_group_types_for_project")+ def test_capture_ticket_created_slack_channel_fallback_not_applied_when(+ self,+ _name,+ config_index,+ account_ref_kwargs,+ ticket_channel,+ expect_lookup,+ mock_group_types,+ mock_capture,+ mock_get_account,+ ):+ self._configure_account_group_type(config_index)+ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 1}]+ mock_get_account.return_value = (+ ca_contracts.AccountRef(id=str(uuid.uuid4()), name="Acme Corp", **account_ref_kwargs)+ if account_ref_kwargs is not None+ else None+ )++ ticket = self._create_slack_ticket(slack_channel_id=ticket_channel)+ capture_ticket_created(ticket)++ assert mock_get_account.called is expect_lookup+ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is False+ assert "$groups" not in call_kwargs["properties"]+ ticket.refresh_from_db()+ assert ticket.organization_id is None+ assert ticket.organization_id_source is None++ @patch("products.customer_analytics.backend.facade.api.get_account_ref_by_slack_channel_id")+ @patch("products.conversations.backend.events.capture_internal")+ @patch("posthog.hogql.query.execute_hogql_query")+ @patch("products.conversations.backend.events.get_group_types_for_project")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_identified_person_without_org_falls_back_to_slack_channel(+ self, mock_get_persons, mock_group_types, mock_hogql, mock_capture, mock_get_account+ ):+ """Identified requester with no resolvable org (no membership, no analytics groups):+ the channel association is still better evidence than nothing."""+ from posthog.models.person.person import Person++ self._configure_account_group_type(1)+ mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]+ mock_group_types.return_value = [{"group_type": "organization", "group_type_index": 1}]+ mock_hogql.return_value.results = []+ mock_get_account.return_value = ca_contracts.AccountRef(+ id=str(uuid.uuid4()), name="Acme Corp", external_id="acme-org-1"+ )++ ticket = self._create_slack_ticket(distinct_id="[email protected]")+ capture_ticket_created(ticket)++ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is False+ assert call_kwargs["properties"]["$groups"]["organization"] == "acme-org-1"+ ticket.refresh_from_db()+ assert ticket.organization_id_source == OrganizationIdSource.SLACK_CHANNEL_ACCOUNT++ @patch("products.customer_analytics.backend.facade.api.get_account_ref_by_slack_channel_id")+ @patch("products.conversations.backend.events.capture_internal")+ @patch("products.conversations.backend.events.get_persons_by_distinct_ids")+ def test_capture_ticket_created_person_resolution_wins_over_slack_channel_fallback(+ self, mock_get_persons, mock_capture, mock_get_account+ ):+ from posthog.models.person.person import Person++ self._configure_account_group_type(1)+ person_org = Organization.objects.create(name="Member Org")+ person_user = User.objects.create(email="[email protected]", distinct_id="[email protected]")+ OrganizationMembership.objects.create(user=person_user, organization=person_org)+ mock_get_persons.return_value = [Person(team_id=self.team.id, is_identified=True)]++ ticket = self._create_slack_ticket(distinct_id="[email protected]")+ capture_ticket_created(ticket)++ mock_get_account.assert_not_called()+ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["properties"]["$groups"]["organization"] == str(person_org.id)+ ticket.refresh_from_db()+ assert ticket.organization_id_source == OrganizationIdSource.PERSON++ @parameterized.expand(+ [+ ("channel_derived", OrganizationIdSource.SLACK_CHANNEL_ACCOUNT.value, False),+ ("person_derived", OrganizationIdSource.PERSON.value, True),+ ("legacy_no_source", None, True),+ ]+ )+ @patch("products.conversations.backend.events.capture_internal")+ def test_capture_message_received_stored_org_source_controls_person_processing(+ self, _name, source, expected_process_person, mock_capture+ ):+ """A channel-inferred org says nothing about the sender: reusing it on follow-up+ messages must not create a person profile for the empty/synthetic distinct_id."""+ self.ticket.organization_id = "stored-org-123"+ self.ticket.organization_id_source = source+ self.ticket.save(update_fields=["organization_id", "organization_id_source"])++ capture_message_received(self.ticket, "msg-456", "Hello support")++ call_kwargs = mock_capture.call_args.kwargs+ assert call_kwargs["process_person_profile"] is expected_process_person+ assert call_kwargs["properties"]["$groups"]["organization"] == "stored-org-123"+@patch("products.conversations.backend.events.capture_internal")@patch("products.conversations.backend.events._resolve_org_groups")def test_capture_message_received_persists_resolved_organization_id(self, mock_resolve, mock_capture):@@ -1050,6 +1219,7 @@ class TestConversationEvents(BaseTest):mock_resolve.return_value = (True,{"instance": SITE_URL, "project": str(self.team.uuid), "organization": "late-org-1"},+ OrganizationIdSource.PERSON,)assert self.ticket.organization_id is None@@ -1072,6 +1242,7 @@ class TestConversationEvents(BaseTest):mock_resolve.return_value = (True,{"instance": SITE_URL, "project": str(self.team.uuid), "organization": "late-org-2"},+ OrganizationIdSource.PERSON,)Ticket.objects.filter(id=self.ticket.id).update(organization_id="first-org-1")diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex 2d23d07b0bd3..bf98ca44189d 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -274,6 +274,7 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):"github_issue_number","zendesk_ticket_id","organization_id",+ "organization_id_source","person","tags",]@@ -303,6 +304,7 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):"github_issue_number","zendesk_ticket_id","organization_id",+ "organization_id_source","person","ai_triage","identity_verified",@@ -323,6 +325,11 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):"organization_id": {"help_text": "Customer's PostHog organization group key, resolved at ticket creation. Null when unknown."},+ "organization_id_source": {+ "help_text": "How organization_id was resolved: 'person' (from the requester's identity) or "+ "'slack_channel_account' (inferred from the customer analytics account linked to the ticket's Slack channel). "+ "Null when organization_id is unset."+ },"ai_triage": {"help_text": "AI support pipeline triage and outcome (status, result, ticket_type, confidence, attempts, etc.)."},diff --git a/products/conversations/backend/events.py b/products/conversations/backend/events.pyindex 8eb2a2a43d94..4e60b65dba9d 100644--- a/products/conversations/backend/events.py+++ b/products/conversations/backend/events.py@@ -28,7 +28,7 @@ from posthog.settings import SITE_URLfrom products.conversations.backend.cache import get_cached_resolved_groups, set_cached_resolved_groupsfrom products.conversations.backend.models import Ticket, TicketAssignment-from products.conversations.backend.models.constants import Channel+from products.conversations.backend.models.constants import Channel, OrganizationIdSourcefrom ee.models.rbac.role import Role@@ -186,8 +186,8 @@ def _resolve_groups_from_person_properties(team: Team, person: Person) -> dict |return {"instance": SITE_URL, "project": str(team.uuid), "organization": org_id}-def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:- """Resolve the customer organization's ``$groups`` for a ticket.+def _resolve_person_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:+ """Resolve the customer organization's ``$groups`` from the requester's identity.Returns ``(process_person, groups)``. ``groups`` is ``None`` when thecustomer can't be tied to a PostHog organization.@@ -264,6 +264,61 @@ def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None]:return False, None+def _resolve_groups_from_slack_channel(team: Team, slack_channel_id: str) -> dict | None:+ """Attribute the ticket to the customer analytics account bound to its Slack channel.++ Last-resort fallback when the requester can't be tied to an organization: a+ dedicated support channel maps to one account, and that account's ``external_id``+ is the group key at the team's configured account group type. Channel-level+ evidence only — it says which account the ticket belongs to, not who sent it.+ """+ group_type_index = team.customer_analytics_config.account_group_type_index+ if group_type_index is None:+ return None++ group_type_name = next(+ (+ gtm["group_type"]+ for gtm in get_group_types_for_project(team.project_id)+ if gtm["group_type_index"] == group_type_index+ ),+ None,+ )+ if group_type_name is None:+ return None++ # The facade pulls the workflows/notebooks facades with it; keep that off the+ # django.setup() path this module loads on via the conversations signal wiring.+ from products.customer_analytics.backend.facade import api as customer_analytics # noqa: PLC0415++ account = customer_analytics.get_account_ref_by_slack_channel_id(team.id, slack_channel_id)+ if account is None or not account.external_id:+ return None++ return {"instance": SITE_URL, "project": str(team.uuid), group_type_name: account.external_id}+++def _resolve_org_groups(ticket: Ticket, team: Team) -> tuple[bool, dict | None, str | None]:+ """Resolve a ticket's ``$groups``, preferring the requester's identity.++ Returns ``(process_person, groups, source)`` where ``source`` is an+ ``OrganizationIdSource`` value recording how ``groups`` was resolved, or+ ``None`` when nothing resolved. Slack tickets that can't be attributed+ through the person fall back to the customer analytics account associated+ with the ticket's Slack channel.+ """+ process_person, groups = _resolve_person_org_groups(ticket, team)+ if groups is not None:+ return process_person, groups, OrganizationIdSource.PERSON++ if ticket.channel_source == Channel.SLACK.value and ticket.slack_channel_id:+ groups = _resolve_groups_from_slack_channel(team, ticket.slack_channel_id)+ if groups is not None:+ return process_person, groups, OrganizationIdSource.SLACK_CHANNEL_ACCOUNT++ return process_person, None, None++def _groups_from_org_id(team: Team, organization_id: str) -> dict:"""Rebuild minimal $groups from a stored org id, skipping the expensive resolver."""return {"instance": SITE_URL, "project": str(team.uuid), "organization": organization_id}@@ -349,13 +404,14 @@ def capture_ticket_created(ticket: Ticket) -> None:team_id = team.idprocess_person = Falsetry:- process_person, groups = _resolve_org_groups(ticket, team)+ process_person, groups, groups_source = _resolve_org_groups(ticket, team)if groups is not None:properties["$groups"] = groupsorg_id = groups.get("organization")if org_id and not ticket.organization_id:- Ticket.objects.filter(id=ticket.id).update(organization_id=org_id)+ Ticket.objects.filter(id=ticket.id).update(organization_id=org_id, organization_id_source=groups_source)ticket.organization_id = org_id+ ticket.organization_id_source = groups_sourceexcept Exception:logger.exception("ticket_created_person_lookup_failed", team_id=team_id, ticket_id=str(ticket.id))@@ -480,9 +536,11 @@ def capture_message_received(ticket: Ticket, message_id: str, message_content: stry:if ticket.organization_id:properties["$groups"] = _groups_from_org_id(team, ticket.organization_id)- process_person = True+ # A channel-inferred org says nothing about the sender, so don't create a+ # person profile for it (legacy rows without a source were person-resolved).+ process_person = ticket.organization_id_source != OrganizationIdSource.SLACK_CHANNEL_ACCOUNTelse:- process_person, groups = _resolve_org_groups(ticket, team)+ process_person, groups, groups_source = _resolve_org_groups(ticket, team)if groups is not None:properties["$groups"] = groupsorg_id = groups.get("organization")@@ -492,10 +550,11 @@ def capture_message_received(ticket: Ticket, message_id: str, message_content: s# wins: only mirror to the in-memory ticket when this update landed,# so a concurrent handler's value isn't shadowed.rows_updated = Ticket.objects.filter(id=ticket.id, organization_id__isnull=True).update(- organization_id=org_id+ organization_id=org_id, organization_id_source=groups_source)if rows_updated:ticket.organization_id = org_id+ ticket.organization_id_source = groups_sourceexcept Exception:logger.exception("message_received_person_lookup_failed", team_id=team.id, ticket_id=str(ticket.id))diff --git a/products/conversations/backend/migrations/0052_ticket_organization_id_source.py b/products/conversations/backend/migrations/0052_ticket_organization_id_source.pynew file mode 100644index 000000000000..2d4a9827752a--- /dev/null+++ b/products/conversations/backend/migrations/0052_ticket_organization_id_source.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-02 16:05++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0051_ticketviewfavorite"),+ ]++ operations = [+ migrations.AddField(+ model_name="ticket",+ name="organization_id_source",+ field=models.CharField(blank=True, max_length=32, null=True),+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex bbc9a1c655d3..5d3b541940ca 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0051_ticketviewfavorite+0052_ticket_organization_id_sourcediff --git a/products/conversations/backend/models/constants.py b/products/conversations/backend/models/constants.pyindex 35810fe88c16..5a62df7bf70c 100644--- a/products/conversations/backend/models/constants.py+++ b/products/conversations/backend/models/constants.py@@ -39,6 +39,11 @@ class Priority(models.TextChoices):CRITICAL = "critical", "Critical"+class OrganizationIdSource(models.TextChoices):+ PERSON = "person", "Requester identity"+ SLACK_CHANNEL_ACCOUNT = "slack_channel_account", "Slack channel account"++class RuleType(models.TextChoices):TONE = "tone", "Tone"ESCALATION = "escalation", "Escalation"diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.pyindex 9a2adb6aa900..305d252e950b 100644--- a/products/conversations/backend/models/ticket.py+++ b/products/conversations/backend/models/ticket.py@@ -108,6 +108,9 @@ class Ticket(UUIDTModel):# Customer's PostHog org group key, resolved once at creation or on a later message# (local org pk, cross-region analytics key, or the person's organization_id property).organization_id = models.CharField(max_length=400, null=True, blank=True)+ # How organization_id was resolved: "person" (the requester's identity) or+ # "slack_channel_account" (inferred from the customer analytics account linked to the Slack channel).+ organization_id_source = models.CharField(max_length=32, null=True, blank=True)# Zendesk import dedup — set when a ticket is imported from Zendesk Support.# No standalone index: the partial unique constraint below covers the dedup lookupdiff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex ce87fce75622..15f5d9c93aa2 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -761,6 +761,11 @@ export interface TicketApi {* @nullable*/readonly organization_id: string | null+ /**+ * How organization_id was resolved: 'person' (from the requester's identity) or 'slack_channel_account' (inferred from the customer analytics account linked to the ticket's Slack channel). Null when organization_id is unset.+ * @nullable+ */+ readonly organization_id_source: string | nullreadonly person: TicketPersonApi | nulltags?: unknown[]}@@ -854,6 +859,11 @@ export interface PatchedTicketApi {* @nullable*/readonly organization_id?: string | null+ /**+ * How organization_id was resolved: 'person' (from the requester's identity) or 'slack_channel_account' (inferred from the customer analytics account linked to the ticket's Slack channel). Null when organization_id is unset.+ * @nullable+ */+ readonly organization_id_source?: string | nullreadonly person?: TicketPersonApi | nulltags?: unknown[]}diff --git a/products/conversations/frontend/scenes/ticket/RelatedGroupsPanel.tsx b/products/conversations/frontend/scenes/ticket/RelatedGroupsPanel.tsxindex e5deb16ec0fd..486cd9a63d62 100644--- a/products/conversations/frontend/scenes/ticket/RelatedGroupsPanel.tsx+++ b/products/conversations/frontend/scenes/ticket/RelatedGroupsPanel.tsx@@ -1,23 +1,31 @@import { useValues } from 'kea'-import { LemonCollapse } from '@posthog/lemon-ui'+import { LemonCollapse, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'import { RelatedGroups } from 'scenes/groups/RelatedGroups'import { relatedGroupsLogic } from 'scenes/groups/relatedGroupsLogic'+import { GroupActorDisplay } from 'scenes/persons/GroupActorDisplay'import { groupsModel } from '~/models/groupsModel'-import { ActorType, GroupActorType } from '~/types'+import { ActorType, Group, GroupActorType } from '~/types'import { creationGroupLogic } from './creationGroupLogic'-const HIGHLIGHT_LABEL = 'Ticket origin'+const ORIGIN_LABEL = 'Ticket origin'const STALE_TOOLTIP ="This group was active when the ticket was created, but it's no longer in the person's recent related groups."+const CHANNEL_ACCOUNT_LABEL = 'Customer analytics'+const CHANNEL_ACCOUNT_TOOLTIP =+ "This group was inferred from the customer analytics account associated with the ticket's Slack channel, not from the requester's identity."++export const SLACK_CHANNEL_ACCOUNT_SOURCE = 'slack_channel_account'interface RelatedGroupsPanelProps {- personUuid: string+ personUuid?: string | null// The group the ticket was created with (organization group key), snapshotted at creation.organizationId?: string | null+ // How organization_id was resolved ("person" or "slack_channel_account").+ organizationIdSource?: string | null}// Append the creation group as its own row only when it exists but isn't already in the person's live@@ -35,16 +43,41 @@ export function shouldShowCreationFallback(return !relatedActors.some((actor) => actor.type === 'group' && actor.group_key === organizationId)}-export function RelatedGroupsPanel({ personUuid, organizationId }: RelatedGroupsPanelProps): JSX.Element {+// `organization_id` is always a key of the "organization" group type (set that way at creation),+// so we can resolve its index by name when the group isn't in a live related list.+function useOrgGroupTypeIndex(): { orgGroupTypeIndex: number | null; groupTypesLoading: boolean } {+ const { groupTypes, groupTypesLoading } = useValues(groupsModel)+ return {+ orgGroupTypeIndex:+ Array.from(groupTypes.values()).find((gt) => gt.group_type === 'organization')?.group_type_index ?? null,+ groupTypesLoading,+ }+}++function toGroupActor(group: Group): GroupActorType {+ return {+ type: 'group',+ id: group.group_key,+ group_key: group.group_key,+ group_type_index: group.group_type_index,+ properties: group.group_properties,+ created_at: group.created_at,+ } as GroupActorType+}++function PersonRelatedGroups({+ personUuid,+ organizationId,+ fromChannelAccount,+}: {+ personUuid: string+ organizationId?: string | null+ fromChannelAccount: boolean+}): JSX.Element {const { relatedActors, relatedActorsLoading } = useValues(relatedGroupsLogic({ groupTypeIndex: null, id: personUuid }))- const { groupTypes } = useValues(groupsModel)-- // `organization_id` is always a key of the "organization" group type (set that way at creation),- // so we can resolve its index by name when the group has dropped out of the live related list.- const orgGroupTypeIndex =- Array.from(groupTypes.values()).find((gt) => gt.group_type === 'organization')?.group_type_index ?? null+ const { orgGroupTypeIndex } = useOrgGroupTypeIndex()const { group: creationGroup } = useValues(creationGroupLogic({ groupTypeIndex: orgGroupTypeIndex, groupKey: organizationId ?? null })@@ -59,19 +92,81 @@ export function RelatedGroupsPanel({ personUuid, organizationId }: RelatedGroups// When the snapshot group isn't in the live related list, fetch it and append it as a real row// (type + name + link) rather than a bare key, tagged via highlightGroupKey below.- const extraActors: ActorType[] =- showFallback && creationGroup- ? [- {- type: 'group',- id: creationGroup.group_key,- group_key: creationGroup.group_key,- group_type_index: creationGroup.group_type_index,- properties: creationGroup.group_properties,- created_at: creationGroup.created_at,- } as GroupActorType,- ]- : []+ const extraActors: ActorType[] = showFallback && creationGroup ? [toGroupActor(creationGroup)] : []++ return (+ <RelatedGroups+ id={personUuid}+ groupTypeIndex={null}+ embedded+ highlightGroupKey={organizationId}+ highlightLabel={fromChannelAccount ? CHANNEL_ACCOUNT_LABEL : ORIGIN_LABEL}+ highlightLabelTooltip={fromChannelAccount ? CHANNEL_ACCOUNT_TOOLTIP : undefined}+ // A channel-inferred group was never tied to the person, so "stale" (dropped out of the+ // person's recent groups) doesn't apply to it.+ highlightStale={!fromChannelAccount && showFallback}+ highlightStaleTooltip={STALE_TOOLTIP}+ extraActors={extraActors}+ />+ )+}++// No person to query related groups for — show just the creation-snapshot group.+function CreationGroupOnly({+ organizationId,+ fromChannelAccount,+}: {+ organizationId: string+ fromChannelAccount: boolean+}): JSX.Element {+ const { orgGroupTypeIndex, groupTypesLoading } = useOrgGroupTypeIndex()+ const { group: creationGroup, groupLoading } = useValues(+ creationGroupLogic({ groupTypeIndex: orgGroupTypeIndex, groupKey: organizationId })+ )++ // While group types are loading, the index is transiently null and the group lookup+ // no-ops — hold the loading state rather than flashing the empty state.+ if (groupTypesLoading || groupLoading) {+ return <Spinner />+ }+ if (!creationGroup) {+ return <div className="text-secondary">No related groups found</div>+ }++ return (+ <div className="flex items-center gap-2">+ <GroupActorDisplay actor={toGroupActor(creationGroup)} />+ <Tooltip title={fromChannelAccount ? CHANNEL_ACCOUNT_TOOLTIP : undefined}>+ <LemonTag type="muted" size="small">+ {fromChannelAccount ? CHANNEL_ACCOUNT_LABEL : ORIGIN_LABEL}+ </LemonTag>+ </Tooltip>+ </div>+ )+}++export function RelatedGroupsPanel({+ personUuid,+ organizationId,+ organizationIdSource,+}: RelatedGroupsPanelProps): JSX.Element | null {+ const fromChannelAccount = organizationIdSource === SLACK_CHANNEL_ACCOUNT_SOURCE++ let content: JSX.Element | null = null+ if (personUuid) {+ content = (+ <PersonRelatedGroups+ personUuid={personUuid}+ organizationId={organizationId}+ fromChannelAccount={fromChannelAccount}+ />+ )+ } else if (organizationId) {+ content = <CreationGroupOnly organizationId={organizationId} fromChannelAccount={fromChannelAccount} />+ }+ if (!content) {+ return null+ }return (<LemonCollapse@@ -81,18 +176,7 @@ export function RelatedGroupsPanel({ personUuid, organizationId }: RelatedGroups{key: 'related-groups',header: 'Related groups',- content: (- <RelatedGroups- id={personUuid}- groupTypeIndex={null}- embedded- highlightGroupKey={organizationId}- highlightLabel={HIGHLIGHT_LABEL}- highlightStale={showFallback}- highlightStaleTooltip={STALE_TOOLTIP}- extraActors={extraActors}- />- ),+ content,},]}/>diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex ed4be686803f..6c2e3aff8164 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -464,8 +464,12 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem</LemonCard>{/* Related Groups Panel */}- {person?.uuid && (- <RelatedGroupsPanel personUuid={person.uuid} organizationId={ticket?.organization_id} />+ {(person?.uuid || ticket?.organization_id) && (+ <RelatedGroupsPanel+ personUuid={person?.uuid}+ organizationId={ticket?.organization_id}+ organizationIdSource={ticket?.organization_id_source}+ />)}{/* Staff Actions Panel */}diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex 93858a63e66f..85e9072c27ef 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -176,6 +176,7 @@ export interface Ticket {github_issue_number?: number | nullzendesk_ticket_id?: number | nullorganization_id?: string | null+ organization_id_source?: string | nullperson?: TicketPerson | nulltags?: string[]ai_triage?: AITriagediff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 0cb0515fc192..b44fbf782609 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -25,6 +25,7 @@ from django.core.exceptions import ValidationErrorfrom django.db import IntegrityError, transactionfrom django.db.models import Exists, OuterRef, Prefetch, Q+import structlogfrom celery import current_appfrom pydantic import ValidationError as PydanticValidationError@@ -82,6 +83,8 @@ from . import contracts# The "Update account property" workflow action (Hog template) stores the custom property values it# sets keyed by definition id under its ``properties`` input — the link we resolve into references.+logger = structlog.get_logger(__name__)+_ACCOUNT_PROPERTY_TEMPLATE_ID = "template-posthog-update-account-property"_ACCOUNT_PROPERTY_INPUT_KEY = "properties"@@ -249,6 +252,34 @@ def get_account()+def get_account_ref_by_slack_channel_id(team_id: int, slack_channel_id: str) -> contracts.AccountRef | None:+ """Fetch the team's account whose ``slack_channel_id`` property matches the given channel.++ The channel → account mapping is expected to be one-to-one; the property has no+ uniqueness constraint, so if several accounts claim the same channel the mapping is+ ambiguous (an import or config mistake) and attributing to any one of them risks+ tagging tickets with the wrong customer — return None instead.+ """+ if not slack_channel_id:+ return None+ rows = list(+ Account.objects.for_team(team_id)+ .filter(_properties__slack_channel_id=slack_channel_id)+ .values("id", "name", "external_id")[:2]+ )+ if not rows:+ return None+ if len(rows) > 1:+ logger.warning(+ "multiple_accounts_claim_slack_channel",+ team_id=team_id,+ slack_channel_id=slack_channel_id,+ )+ return None+ row = rows[0]+ return contracts.AccountRef(id=str(row["id"]), name=row["name"], external_id=row["external_id"])++# --- External (CDP worker) account API ---## The data access, transactional write, org-membership resolution, tagdiff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.pyindex f64f96c7787d..2e8b4ac7eeb2 100644--- a/products/customer_analytics/backend/test/test_facade.py+++ b/products/customer_analytics/backend/test/test_facade.py@@ -68,6 +68,26 @@ class TestCustomerAnalyticsFacade(BaseTest):assert facade.get_account(self.team.id, account_id="not-a-uuid") is Noneassert facade.get_account(self.team.id) is None+ def test_get_account_ref_by_slack_channel_id(self):+ account = create_account(+ team_id=self.team.id,+ name="Acme Corp",+ external_id="acme-123",+ _properties={"slack_channel_id": "C123"},+ )+ create_account(team_id=self.team.id, name="No Channel", external_id="other-1")+ other_team = Team.objects.create(organization=self.organization, name="Other")+ create_account(team_id=other_team.id, name="Other Team Corp", _properties={"slack_channel_id": "C123"})++ ref = facade.get_account_ref_by_slack_channel_id(self.team.id, "C123")+ assert ref == contracts.AccountRef(id=str(account.id), name="Acme Corp", external_id="acme-123")+ assert facade.get_account_ref_by_slack_channel_id(self.team.id, "C999") is None+ assert facade.get_account_ref_by_slack_channel_id(self.team.id, "") is None++ # Two accounts claiming the same channel is a config error: attribution is ambiguous, so bail.+ create_account(team_id=self.team.id, name="Acme Duplicate", _properties={"slack_channel_id": "C123"})+ assert facade.get_account_ref_by_slack_channel_id(self.team.id, "C123") is None+def test_get_account_context_data_bundles_tags_and_notes(self):account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123")tag = Tag.objects.create(name="enterprise", team_id=self.team.id)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex e8ec870871d0..24c1f349bfbf 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -44941,6 +44941,11 @@ export namespace Schemas {* @nullable*/readonly organization_id: string | null;+ /**+ * How organization_id was resolved: 'person' (from the requester's identity) or 'slack_channel_account' (inferred from the customer analytics account linked to the ticket's Slack channel). Null when organization_id is unset.+ * @nullable+ */+ readonly organization_id_source: string | null;readonly person: TicketPerson | null;tags?: unknown[];}@@ -52836,6 +52841,11 @@ export namespace Schemas {* @nullable*/readonly organization_id?: string | null;+ /**+ * How organization_id was resolved: 'person' (from the requester's identity) or 'slack_channel_account' (inferred from the customer analytics account linked to the ticket's Slack channel). Null when organization_id is unset.+ * @nullable+ */+ readonly organization_id_source?: string | null;readonly person?: TicketPerson | null;tags?: unknown[];}diff --git a/tach.toml b/tach.tomlindex 5c724e63bf14..9c69f700d4d0 100644--- a/tach.toml+++ b/tach.toml@@ -223,7 +223,7 @@ layer = "modules"path = "products.conversations"depends_on = ["ee",- "posthog", "products.tasks", "products.business_knowledge", "products.warehouse_sources",+ "posthog", "products.tasks", "products.business_knowledge", "products.warehouse_sources", "products.customer_analytics",]layer = "modules"