: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: support multiple channels / teams in ms teams (#64330)
Alex V7cdadee1d00c
diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex e05f6292ecb9..449159ad3c13 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -737,6 +737,14 @@ export interface ConversationsSettings {teams_team_name?: string | nullteams_channel_id?: string | nullteams_channel_name?: string | null+ teams_channels?:+ | {+ team_id: string+ team_name?: string | null+ channel_id: string+ channel_name?: string | null+ }[]+ | nullgithub_enabled?: booleangithub_integration_id?: number | nullgithub_repos?: string[] | nulldiff --git a/posthog/api/team.py b/posthog/api/team.pyindex 90319cb7e98d..e087f59972ff 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -1241,6 +1241,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin"teams_team_name","teams_channel_id","teams_channel_name",+ "teams_channels",):value.pop(managed_key, None)# Normalize multi-channel list: must be a list of non-empty strings, deduped, capped at 50diff --git a/products/conversations/backend/api/teams_channels.py b/products/conversations/backend/api/teams_channels.pyindex 8e252a4d63d2..95e8190adaf5 100644--- a/products/conversations/backend/api/teams_channels.py+++ b/products/conversations/backend/api/teams_channels.py@@ -222,19 +222,63 @@ class TeamsSelectChannelRequestSerializer(serializers.Serializer):teams_channel_id = serializers.CharField(required=False, allow_null=True, allow_blank=True, max_length=500)+class TeamsChannelActionSerializer(serializers.Serializer):+ action = serializers.ChoiceField(choices=["add", "remove"], required=True)+ team_id = serializers.UUIDField(required=False)+ channel_id = serializers.CharField(required=True, max_length=500)+++MAX_TEAMS_CHANNELS = 25+++def _seed_teams_channels_from_legacy(settings_blob: dict) -> list[dict]:+ """Seed teams_channels from legacy scalar fields if not yet present."""+ if "teams_channels" in settings_blob and isinstance(settings_blob.get("teams_channels"), list):+ return list(settings_blob["teams_channels"])+ legacy_team_id = settings_blob.get("teams_team_id")+ legacy_channel_id = settings_blob.get("teams_channel_id")+ if legacy_team_id and legacy_channel_id:+ return [+ {+ "team_id": legacy_team_id,+ "team_name": settings_blob.get("teams_team_name"),+ "channel_id": legacy_channel_id,+ "channel_name": settings_blob.get("teams_channel_name"),+ }+ ]+ return []+++def _update_legacy_scalars_from_list(settings_blob: dict, channels: list[dict]) -> None:+ """Keep legacy scalar fields in sync with the first entry of teams_channels."""+ if channels:+ first = channels[0]+ settings_blob["teams_team_id"] = first.get("team_id")+ settings_blob["teams_team_name"] = first.get("team_name")+ settings_blob["teams_channel_id"] = first.get("channel_id")+ settings_blob["teams_channel_name"] = first.get("channel_name")+ else:+ settings_blob["teams_team_id"] = None+ settings_blob["teams_team_name"] = None+ settings_blob["teams_channel_id"] = None+ settings_blob["teams_channel_name"] = None++class TeamsSelectChannelView(APIView):"""Persist the admin's MS Teams group/channel selection for this project.- Replaces writing ``teams_team_id`` / ``teams_channel_id`` (and their display- names) through the generic ``PATCH /api/projects/:id`` path. Those fields- are on ``managed_key``, so the only way to set them is via this endpoint,- which re-validates the IDs against Graph under the current OAuth grant. The- display names are always re-derived from Graph and never trusted from the- client to avoid spoofed audit-log values like "channel X was configured".+ Supports two request formats:++ 1. **New format (add/remove)**: Incremental updates with ``action`` and ``channel_id``.+ - ``action: "add"``: Requires ``team_id``. Validates the pair against Graph, upserts into ``teams_channels`` (keyed by channel_id).+ - ``action: "remove"``: Removes the entry by ``channel_id``, no Graph call needed.- Passing ``teams_team_id: null`` (or omitting it) clears the whole selection.- Passing a valid ``teams_team_id`` without ``teams_channel_id`` clears just- the channel.+ 2. **Legacy format**: Single ``teams_team_id`` / ``teams_channel_id`` pair.+ - Passing ``teams_team_id: null`` clears the whole selection.+ - Passing a valid ``teams_team_id`` without ``teams_channel_id`` clears just the channel.++ Both formats re-derive display names from Graph (not trusted from client) and keep+ the legacy scalar fields (``teams_team_id``, etc.) in sync from the first list entry."""permission_classes = [IsAuthenticated, IsConversationsAdmin]@@ -245,6 +289,208 @@ class TeamsSelectChannelView(APIView):if not isinstance(user, User) or user.current_team is None:return Response({"error": "No current team selected"}, status=400)+ # Check if this is a new-format (action-based) request+ if "action" in request.data:+ return self._handle_action_request(request, user)++ # Legacy format+ return self._handle_legacy_request(request, user)++ def _handle_action_request(self, request: Request, user: User) -> Response:+ """Handle new action-based add/remove requests."""+ serializer = TeamsChannelActionSerializer(data=request.data)+ if not serializer.is_valid():+ return Response({"error": "invalid_payload", "details": serializer.errors}, status=400)++ action = serializer.validated_data["action"]+ teams_channel_id = serializer.validated_data["channel_id"].strip()++ if not teams_channel_id:+ return Response({"error": "channel_id_required"}, status=400)++ team = user.current_team+ assert team is not None++ if action == "remove":+ return self._handle_remove(team, user, teams_channel_id)++ teams_team_id = serializer.validated_data.get("team_id")+ if not teams_team_id:+ return Response({"error": "team_id_required"}, status=400)++ return self._handle_add(team, user, str(teams_team_id), teams_channel_id)++ def _handle_add(self, team: Team, user: User, teams_team_id: str, teams_channel_id: str) -> Response:+ """Validate and add a team/channel pair."""+ try:+ token = get_graph_token(team)+ except ValueError:+ logger.exception("teams_select_channel_token_error")+ return Response({"error": "Failed to get Teams access token"}, status=400)++ # Validate team access+ try:+ resp = requests.get(+ f"{GRAPH_API_BASE}/me/joinedTeams",+ headers={"Authorization": f"Bearer {token}"},+ timeout=15,+ )+ except Exception:+ logger.exception("teams_select_channel_joined_teams_error")+ return Response({"error": "graph_network_error"}, status=502)+ if resp.status_code != 200:+ logger.warning("teams_select_channel_joined_teams_failed", status=resp.status_code)+ return Response({"error": "graph_error"}, status=502)++ joined = resp.json().get("value", []) or []+ team_match = next((t for t in joined if str(t.get("id", "")) == teams_team_id), None)+ if not team_match:+ return Response({"error": "team_not_accessible"}, status=400)+ teams_team_name = team_match.get("displayName") or None++ # Validate channel access+ try:+ resp = requests.get(+ f"{GRAPH_API_BASE}/teams/{teams_team_id}/channels",+ headers={"Authorization": f"Bearer {token}"},+ timeout=15,+ )+ except Exception:+ logger.exception("teams_select_channel_channels_error")+ return Response({"error": "graph_network_error"}, status=502)+ if resp.status_code != 200:+ logger.warning("teams_select_channel_channels_failed", status=resp.status_code)+ return Response({"error": "graph_error"}, status=502)++ channels = resp.json().get("value", []) or []+ channel_match = next((c for c in channels if str(c.get("id", "")) == teams_channel_id), None)+ if not channel_match:+ return Response({"error": "channel_not_accessible"}, status=400)+ teams_channel_name = channel_match.get("displayName") or None++ # Persist: read-modify-write under lock+ with transaction.atomic():+ locked_team = Team.objects.select_for_update().only("conversations_settings").get(pk=team.pk)+ settings_blob = dict(locked_team.conversations_settings or {})++ # Seed from legacy if teams_channels not yet present+ teams_channels = _seed_teams_channels_from_legacy(settings_blob)++ existing_entry = next((c for c in teams_channels if c.get("channel_id") == teams_channel_id), None)++ # Upsert by channel_id (channel_id is unique across teams)+ new_entry = {+ "team_id": teams_team_id,+ "team_name": teams_team_name,+ "channel_id": teams_channel_id,+ "channel_name": teams_channel_name,+ }+ # Remove existing entry with same channel_id (if any)+ teams_channels = [c for c in teams_channels if c.get("channel_id") != teams_channel_id]+ # Add new entry+ teams_channels.append(new_entry)++ # Cap at max+ if len(teams_channels) > MAX_TEAMS_CHANNELS:+ return Response(+ {"error": "max_channels_exceeded", "max": MAX_TEAMS_CHANNELS},+ status=400,+ )++ settings_blob["teams_channels"] = teams_channels+ _update_legacy_scalars_from_list(settings_blob, teams_channels)++ locked_team.conversations_settings = settings_blob+ locked_team.save(update_fields=["conversations_settings"])+ team.conversations_settings = settings_blob++ new_label = f"{teams_team_name} / {teams_channel_name}"+ if existing_entry:+ change = Change(+ type="Team",+ action="changed",+ field="teams_channels",+ before=f"{existing_entry.get('team_name')} / {existing_entry.get('channel_name')}",+ after=new_label,+ )+ else:+ change = Change(+ type="Team",+ action="created",+ field="teams_channels",+ after=new_label,+ )++ log_activity(+ organization_id=team.organization_id,+ team_id=team.pk,+ user=user,+ was_impersonated=is_impersonated_session(self.request),+ scope="Team",+ item_id=team.pk,+ activity="updated",+ detail=Detail(+ name=str(team.name),+ changes=[change],+ ),+ )++ return Response({"ok": True, "teams_channels": settings_blob.get("teams_channels")})++ def _handle_remove(self, team: Team, user: User, teams_channel_id: str) -> Response:+ """Remove a channel from the configured list."""+ removed_entry: dict | None = None++ with transaction.atomic():+ locked_team = Team.objects.select_for_update().only("conversations_settings").get(pk=team.pk)+ settings_blob = dict(locked_team.conversations_settings or {})++ # Seed from legacy if teams_channels not yet present+ teams_channels = _seed_teams_channels_from_legacy(settings_blob)++ # Find and remove entry+ new_channels = []+ for c in teams_channels:+ if c.get("channel_id") == teams_channel_id:+ removed_entry = c+ else:+ new_channels.append(c)++ if removed_entry is None:+ return Response({"error": "channel_not_found"}, status=404)++ settings_blob["teams_channels"] = new_channels+ _update_legacy_scalars_from_list(settings_blob, new_channels)++ locked_team.conversations_settings = settings_blob+ locked_team.save(update_fields=["conversations_settings"])+ team.conversations_settings = settings_blob++ log_activity(+ organization_id=team.organization_id,+ team_id=team.pk,+ user=user,+ was_impersonated=is_impersonated_session(self.request),+ scope="Team",+ item_id=team.pk,+ activity="updated",+ detail=Detail(+ name=str(team.name),+ changes=[+ Change(+ type="Team",+ action="deleted",+ field="teams_channels",+ before=f"{removed_entry.get('team_name')} / {removed_entry.get('channel_name')}",+ ),+ ],+ ),+ )++ return Response({"ok": True, "teams_channels": settings_blob.get("teams_channels")})++ def _handle_legacy_request(self, request: Request, user: User) -> Response:+ """Handle legacy single team/channel pair request for backwards compatibility."""serializer = TeamsSelectChannelRequestSerializer(data=request.data)if not serializer.is_valid():return Response({"error": "invalid_payload", "details": serializer.errors}, status=400)@@ -256,8 +502,11 @@ class TeamsSelectChannelView(APIView):if teams_channel_id and not teams_team_id:return Response({"error": "channel_id_requires_team_id"}, status=400)+ team = user.current_team+ assert team is not None+try:- token = get_graph_token(user.current_team)+ token = get_graph_token(team)except ValueError:logger.exception("teams_select_channel_token_error")return Response({"error": "Failed to get Teams access token"}, status=400)@@ -305,12 +554,24 @@ class TeamsSelectChannelView(APIView):return Response({"error": "channel_not_accessible"}, status=400)teams_channel_name = match.get("displayName") or None- team = user.current_teamwith transaction.atomic():- # Re-read under row lock, as in save_teams_token, so we don't- # clobber a concurrent conversations_settings write.locked_team = Team.objects.select_for_update().only("conversations_settings").get(pk=team.pk)settings_blob = dict(locked_team.conversations_settings or {})++ # For legacy requests, we replace the single-entry list (backwards-compatible behavior)+ if teams_team_id and teams_channel_id:+ settings_blob["teams_channels"] = [+ {+ "team_id": teams_team_id,+ "team_name": teams_team_name,+ "channel_id": teams_channel_id,+ "channel_name": teams_channel_name,+ }+ ]+ else:+ # Clearing — remove the list too+ settings_blob.pop("teams_channels", None)+settings_blob["teams_team_id"] = teams_team_idsettings_blob["teams_team_name"] = teams_team_namesettings_blob["teams_channel_id"] = teams_channel_iddiff --git a/products/conversations/backend/api/tests/test_teams_endpoints.py b/products/conversations/backend/api/tests/test_teams_endpoints.pyindex 0794902de69c..a2c65fb83893 100644--- a/products/conversations/backend/api/tests/test_teams_endpoints.py+++ b/products/conversations/backend/api/tests/test_teams_endpoints.py@@ -393,3 +393,323 @@ class TestTeamsOAuthEndpoints(APIBaseTest):self.client.logout()response = self.client.post("/api/conversations/v1/teams/disconnect")assert response.status_code in (401, 403)+++class TestTeamsSelectChannelMultiChannel(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.team.conversations_enabled = True+ self.team.conversations_settings = {"teams_enabled": True}+ self.team.save()+ TeamConversationsTeamsConfig.objects.update_or_create(+ team=self.team,+ defaults={+ "teams_tenant_id": "tenant-abc",+ "teams_graph_access_token": "graph-tok",+ "teams_graph_refresh_token": "graph-ref",+ },+ )++ def _mock_graph_responses(self, mock_get, teams_list, channels_list):+ def side_effect(url, **kwargs):+ resp = MagicMock()+ resp.status_code = 200+ if "joinedTeams" in url:+ resp.json.return_value = {"value": teams_list}+ elif "channels" in url:+ resp.json.return_value = {"value": channels_list}+ return resp++ mock_get.side_effect = side_effect++ @patch("products.conversations.backend.api.teams_channels.requests.get")+ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_add_channel_pair_success(self, _mock_refresh, mock_get):+ team_uuid = "00000000-0000-0000-0000-000000000001"+ self._mock_graph_responses(+ mock_get,+ [{"id": team_uuid, "displayName": "Engineering"}],+ [{"id": "ch-1", "displayName": "General"}],+ )++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "add",+ "team_id": team_uuid,+ "channel_id": "ch-1",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.json()+ assert data["ok"] is True+ assert len(data["teams_channels"]) == 1+ assert data["teams_channels"][0]["channel_id"] == "ch-1"+ assert data["teams_channels"][0]["team_name"] == "Engineering"+ assert data["teams_channels"][0]["channel_name"] == "General"++ # Verify legacy scalars are also updated+ self.team.refresh_from_db()+ assert self.team.conversations_settings["teams_channel_id"] == "ch-1"+ assert self.team.conversations_settings["teams_team_id"] == team_uuid++ @patch("products.conversations.backend.api.teams_channels.requests.get")+ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_add_multiple_channels_preserves_existing(self, _mock_refresh, mock_get):+ team_uuid = "00000000-0000-0000-0000-000000000001"+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channels": [+ {"team_id": "t-existing", "team_name": "Existing", "channel_id": "ch-existing", "channel_name": "Old"}+ ],+ }+ self.team.save()++ self._mock_graph_responses(+ mock_get,+ [{"id": team_uuid, "displayName": "Engineering"}],+ [{"id": "ch-new", "displayName": "New Channel"}],+ )++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "add",+ "team_id": team_uuid,+ "channel_id": "ch-new",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.json()+ assert len(data["teams_channels"]) == 2+ channel_ids = {c["channel_id"] for c in data["teams_channels"]}+ assert channel_ids == {"ch-existing", "ch-new"}++ @patch("products.conversations.backend.api.teams_channels.requests.get")+ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_add_channel_seeds_from_legacy(self, _mock_refresh, mock_get):+ """First add should seed teams_channels from legacy scalar fields."""+ team_uuid = "00000000-0000-0000-0000-000000000001"+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_team_id": "legacy-team",+ "teams_team_name": "Legacy Team",+ "teams_channel_id": "legacy-ch",+ "teams_channel_name": "Legacy Channel",+ }+ self.team.save()++ self._mock_graph_responses(+ mock_get,+ [{"id": team_uuid, "displayName": "New Team"}],+ [{"id": "new-ch", "displayName": "New Channel"}],+ )++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "add",+ "team_id": team_uuid,+ "channel_id": "new-ch",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.json()+ assert len(data["teams_channels"]) == 2+ channel_ids = {c["channel_id"] for c in data["teams_channels"]}+ assert channel_ids == {"legacy-ch", "new-ch"}++ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_remove_channel_pair_success(self, _mock_refresh):+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channels": [+ {"team_id": "t1", "team_name": "Team 1", "channel_id": "ch-1", "channel_name": "Ch 1"},+ {"team_id": "t2", "team_name": "Team 2", "channel_id": "ch-2", "channel_name": "Ch 2"},+ ],+ }+ self.team.save()++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "remove",+ "channel_id": "ch-1",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.json()+ assert data["ok"] is True+ assert len(data["teams_channels"]) == 1+ assert data["teams_channels"][0]["channel_id"] == "ch-2"++ # Legacy scalars should now point to remaining channel+ self.team.refresh_from_db()+ assert self.team.conversations_settings["teams_channel_id"] == "ch-2"++ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_remove_last_channel_clears_legacy(self, _mock_refresh):+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channels": [+ {"team_id": "t1", "team_name": "Team 1", "channel_id": "ch-1", "channel_name": "Ch 1"},+ ],+ "teams_channel_id": "ch-1",+ }+ self.team.save()++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "remove",+ "channel_id": "ch-1",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.json()+ assert len(data["teams_channels"]) == 0++ self.team.refresh_from_db()+ assert self.team.conversations_settings.get("teams_channel_id") is None+ assert self.team.conversations_settings.get("teams_team_id") is None++ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_remove_nonexistent_channel_returns_404(self, _mock_refresh):+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channels": [+ {"team_id": "t1", "channel_id": "ch-1"},+ ],+ }+ self.team.save()++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "remove",+ "channel_id": "ch-nonexistent",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 404++ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_add_without_team_id_returns_400(self, _mock_refresh):+ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "add",+ "channel_id": "ch-1",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 400+ assert response.json()["error"] == "team_id_required"++ @patch("products.conversations.backend.api.teams_channels.requests.get")+ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_add_inaccessible_team_returns_400(self, _mock_refresh, mock_get):+ team_uuid = "00000000-0000-0000-0000-000000000001"+ self._mock_graph_responses(+ mock_get,+ [{"id": "other-team", "displayName": "Other"}], # Different team+ [],+ )++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "add",+ "team_id": team_uuid,+ "channel_id": "ch-1",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 400+ assert response.json()["error"] == "team_not_accessible"++ @patch("products.conversations.backend.api.teams_channels.requests.get")+ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_add_inaccessible_channel_returns_400(self, _mock_refresh, mock_get):+ team_uuid = "00000000-0000-0000-0000-000000000001"+ self._mock_graph_responses(+ mock_get,+ [{"id": team_uuid, "displayName": "Engineering"}],+ [{"id": "other-ch", "displayName": "Other Channel"}], # Different channel+ )++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "action": "add",+ "team_id": team_uuid,+ "channel_id": "ch-1",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 400+ assert response.json()["error"] == "channel_not_accessible"++ @patch("products.conversations.backend.api.teams_channels.requests.get")+ @patch("products.conversations.backend.support_teams.refresh_graph_token", return_value="fresh-token")+ def test_legacy_request_format_still_works(self, _mock_refresh, mock_get):+ """Legacy single team_id/channel_id format should still work."""+ team_uuid = "00000000-0000-0000-0000-000000000001"+ self._mock_graph_responses(+ mock_get,+ [{"id": team_uuid, "displayName": "Engineering"}],+ [{"id": "ch-1", "displayName": "General"}],+ )++ response = self.client.post(+ "/api/conversations/v1/teams/select-channel",+ data=json.dumps(+ {+ "teams_team_id": team_uuid,+ "teams_channel_id": "ch-1",+ }+ ),+ content_type="application/json",+ )++ assert response.status_code == 200+ data = response.json()+ assert data["teams_channel_id"] == "ch-1"+ assert data["teams_team_name"] == "Engineering"++ self.team.refresh_from_db()+ assert len(self.team.conversations_settings.get("teams_channels", [])) == 1diff --git a/products/conversations/backend/api/tests/test_teams_multi_channel.py b/products/conversations/backend/api/tests/test_teams_multi_channel.pynew file mode 100644index 000000000000..ec39fd83d1fa--- /dev/null+++ b/products/conversations/backend/api/tests/test_teams_multi_channel.py@@ -0,0 +1,244 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from products.conversations.backend.models import Ticket+from products.conversations.backend.models.constants import Channel, ChannelDetail+from products.conversations.backend.teams import _configured_support_channel_ids, handle_teams_message+++class TestConfiguredSupportChannelIds(BaseTest):+ @parameterized.expand(+ [+ ("empty_settings", {}, set()),+ ("legacy_only", {"teams_channel_id": "19:[email protected]"}, {"19:[email protected]"}),+ (+ "new_only",+ {+ "teams_channels": [+ {"team_id": "t1", "channel_id": "19:[email protected]"},+ {"team_id": "t2", "channel_id": "19:[email protected]"},+ ]+ },+ {"19:[email protected]", "19:[email protected]"},+ ),+ (+ "both_overlapping",+ {+ "teams_channel_id": "19:[email protected]",+ "teams_channels": [+ {"team_id": "t1", "channel_id": "19:[email protected]"},+ {"team_id": "t2", "channel_id": "19:[email protected]"},+ ],+ },+ {"19:[email protected]", "19:[email protected]"},+ ),+ (+ "both_disjoint",+ {+ "teams_channel_id": "19:[email protected]",+ "teams_channels": [+ {"team_id": "t1", "channel_id": "19:[email protected]"},+ {"team_id": "t2", "channel_id": "19:[email protected]"},+ ],+ },+ ),+ (+ "empty_list_with_legacy",+ {"teams_channel_id": "19:[email protected]", "teams_channels": []},+ {"19:[email protected]"},+ ),+ ("none_list", {"teams_channels": None}, set()),+ (+ "malformed_entry_skipped",+ {+ "teams_channels": [+ {"team_id": "t1", "channel_id": "19:[email protected]"},+ {"team_id": "t2"}, # missing channel_id+ "invalid", # not a dict+ ]+ },+ {"19:[email protected]"},+ ),+ ],+ )+ def test_configured_support_channel_ids(self, _name, settings, expected):+ assert _configured_support_channel_ids(settings) == expected+++def _make_activity(+ *,+ channel_id: str = "19:[email protected]",+ conversation_id: str = "19:[email protected]",+ text: str = "Hello",+ reply_to_id: str | None = None,+ service_url: str = "https://smba.trafficmanager.net/teams/",+) -> dict:+ activity_id = "msg-123"+ activity: dict = {+ "type": "message",+ "id": activity_id,+ "text": text,+ "serviceUrl": service_url,+ "from": {"id": "29:user", "aadObjectId": "aad-user-1", "role": "user"},+ "conversation": {"id": f"{conversation_id};messageid={activity_id}"},+ "channelData": {+ "channel": {"id": channel_id},+ "tenant": {"id": "tenant-abc"},+ },+ }+ if reply_to_id:+ activity["replyToId"] = reply_to_id+ activity["conversation"]["id"] = f"{conversation_id};messageid={reply_to_id}"+ return activity+++class TestTeamsMultiChannel(BaseTest):+ @parameterized.expand(+ [+ ("first_configured_creates", "19:[email protected]", True),+ ("second_configured_creates", "19:[email protected]", True),+ ("unknown_channel_ignored", "19:[email protected]", False),+ ],+ )+ @patch("products.conversations.backend.teams.create_or_update_teams_ticket")+ @patch("products.conversations.backend.teams.resolve_teams_user", return_value={"name": "U", "email": None})+ def test_top_level_message_routing(self, _name, channel, expect_create, _mock_user, mock_create):+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channels": [+ {"team_id": "t1", "channel_id": "19:[email protected]"},+ {"team_id": "t2", "channel_id": "19:[email protected]"},+ ],+ }+ self.team.save()++ handle_teams_message(_make_activity(channel_id=channel), self.team, "tenant-abc")++ if expect_create:+ mock_create.assert_called_once()+ assert mock_create.call_args.kwargs["channel_detail"] == ChannelDetail.TEAMS_CHANNEL_MESSAGE+ else:+ mock_create.assert_not_called()++ @parameterized.expand(+ [+ ("configured_channel_accepted", "19:[email protected]", True),+ ("non_configured_channel_ignored", "19:[email protected]", False),+ ],+ )+ @patch("products.conversations.backend.teams.create_or_update_teams_ticket")+ @patch("products.conversations.backend.teams.resolve_teams_user", return_value={"name": "U", "email": None})+ def test_thread_reply_without_ticket_routing(self, _name, channel, expect_create, _mock_user, mock_create):+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channels": [+ {"team_id": "t1", "channel_id": "19:[email protected]"},+ {"team_id": "t2", "channel_id": "19:[email protected]"},+ ],+ }+ self.team.save()++ handle_teams_message(+ _make_activity(channel_id=channel, reply_to_id="parent-msg"),+ self.team,+ "tenant-abc",+ )++ if expect_create:+ mock_create.assert_called_once()+ assert mock_create.call_args.kwargs["is_thread_reply"] is True+ else:+ mock_create.assert_not_called()++ @patch("products.conversations.backend.teams.create_or_update_teams_ticket")+ @patch("products.conversations.backend.teams.resolve_teams_user", return_value={"name": "U", "email": None})+ def test_thread_reply_with_existing_ticket_syncs_regardless_of_config(self, _mock_user, mock_create):+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channels": [{"team_id": "t1", "channel_id": "19:[email protected]"}],+ }+ self.team.save()++ Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.TEAMS,+ widget_session_id="",+ distinct_id="",+ teams_channel_id="19:[email protected]",+ teams_conversation_id="19:[email protected];messageid=parent-msg",+ )++ handle_teams_message(+ _make_activity(channel_id="19:[email protected]", reply_to_id="parent-msg"),+ self.team,+ "tenant-abc",+ )++ mock_create.assert_called_once()+ assert mock_create.call_args.kwargs["is_thread_reply"] is True++ @patch("products.conversations.backend.teams.create_or_update_teams_ticket")+ @patch("products.conversations.backend.teams.resolve_teams_user", return_value={"name": "U", "email": None})+ def test_legacy_teams_channel_id_still_works(self, _mock_user, mock_create):+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channel_id": "19:[email protected]",+ }+ self.team.save()++ handle_teams_message(_make_activity(channel_id="19:[email protected]"), self.team, "tenant-abc")++ mock_create.assert_called_once()+ assert mock_create.call_args.kwargs["channel_detail"] == ChannelDetail.TEAMS_CHANNEL_MESSAGE++ @patch("products.conversations.backend.teams.create_or_update_teams_ticket")+ @patch("products.conversations.backend.teams.resolve_teams_user", return_value={"name": "U", "email": None})+ def test_legacy_and_new_union(self, _mock_user, mock_create):+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channel_id": "19:[email protected]",+ "teams_channels": [{"team_id": "t1", "channel_id": "19:[email protected]"}],+ }+ self.team.save()++ handle_teams_message(_make_activity(channel_id="19:[email protected]"), self.team, "tenant-abc")+ assert mock_create.call_count == 1++ mock_create.reset_mock()+ handle_teams_message(+ _make_activity(channel_id="19:[email protected]", conversation_id="19:[email protected]"),+ self.team,+ "tenant-abc",+ )+ assert mock_create.call_count == 1++ @patch("products.conversations.backend.teams.create_or_update_teams_ticket")+ def test_no_channels_configured_ignores_all(self, mock_create):+ self.team.conversations_settings = {"teams_enabled": True}+ self.team.save()++ handle_teams_message(_make_activity(channel_id="19:[email protected]"), self.team, "tenant-abc")++ mock_create.assert_not_called()++ @patch("products.conversations.backend.teams.create_or_update_teams_ticket")+ @patch("products.conversations.backend.teams.resolve_teams_user", return_value={"name": "U", "email": None})+ def test_shared_channel_in_multiple_teams_dedupe(self, _mock_user, mock_create):+ """Shared channel configured under two different MS Teams groups should only create one ticket."""+ shared_channel = "19:[email protected]"+ self.team.conversations_settings = {+ "teams_enabled": True,+ "teams_channels": [+ {"team_id": "team-a", "channel_id": shared_channel},+ {"team_id": "team-b", "channel_id": shared_channel},+ ],+ }+ self.team.save()++ handle_teams_message(_make_activity(channel_id=shared_channel), self.team, "tenant-abc")++ # Should create exactly one ticket, not two+ mock_create.assert_called_once()diff --git a/products/conversations/backend/support_teams.py b/products/conversations/backend/support_teams.pyindex 3ca4cffbc9f0..3b4386d3c954 100644--- a/products/conversations/backend/support_teams.py+++ b/products/conversations/backend/support_teams.py@@ -511,6 +511,7 @@ def clear_teams_token(settings_blob.pop("teams_team_name", None)settings_blob.pop("teams_channel_id", None)settings_blob.pop("teams_channel_name", None)+ settings_blob.pop("teams_channels", None)locked_team.conversations_settings = settings_blobconfig.teams_tenant_id = Nonediff --git a/products/conversations/backend/teams.py b/products/conversations/backend/teams.pyindex b226647840c5..46cb0b2b18d6 100644--- a/products/conversations/backend/teams.py+++ b/products/conversations/backend/teams.py@@ -585,6 +585,27 @@ def create_or_update_teams_ticket(return ticket+def _configured_support_channel_ids(settings: dict) -> set[str]:+ """Return the set of Teams channel IDs configured for auto-ticket creation.++ Merges the new ``teams_channels`` list with the legacy scalar+ ``teams_channel_id`` so that teams that haven't re-saved settings after+ the multi-channel migration still work.+ """+ ids: set[str] = set()+ teams_channels = settings.get("teams_channels")+ if isinstance(teams_channels, list):+ for entry in teams_channels:+ if isinstance(entry, dict):+ channel_id = entry.get("channel_id")+ if channel_id:+ ids.add(channel_id)+ legacy = settings.get("teams_channel_id")+ if legacy:+ ids.add(legacy)+ return ids++def handle_teams_message(activity: dict, team: Team, tenant_id: str) -> None:"""Handle a Teams message activity for the dedicated support channel.@@ -606,7 +627,7 @@ def handle_teams_message(activity: dict, team: Team, tenant_id: str) -> None:returnsettings_dict = team.conversations_settings or {}- configured_channel = settings_dict.get("teams_channel_id")+ configured_channels = _configured_support_channel_ids(settings_dict)conversation_id = _extract_conversation_id(activity)is_reply = _is_reply(activity)@@ -616,7 +637,7 @@ def handle_teams_message(activity: dict, team: Team, tenant_id: str) -> None:if not Ticket.objects.filter(team=team, teams_channel_id=channel_id, teams_conversation_id=conversation_id).exists():- if not configured_channel or configured_channel != channel_id:+ if channel_id not in configured_channels:returncreate_or_update_teams_ticket(@@ -627,7 +648,7 @@ def handle_teams_message(activity: dict, team: Team, tenant_id: str) -> None:)return- if not configured_channel or configured_channel != channel_id:+ if channel_id not in configured_channels:return# Top-level message -> create new ticketdiff --git a/products/conversations/frontend/scenes/settings/TeamsSection.tsx b/products/conversations/frontend/scenes/settings/TeamsSection.tsxindex 19861130d1dd..606dfc1dc15c 100644--- a/products/conversations/frontend/scenes/settings/TeamsSection.tsx+++ b/products/conversations/frontend/scenes/settings/TeamsSection.tsx@@ -1,5 +1,7 @@import { useActions, useValues } from 'kea'+import { useState } from 'react'+import { IconTrash } from '@posthog/icons'import { LemonBanner, LemonButton, LemonCard, LemonDivider, LemonSelect, LemonTag, Link } from '@posthog/lemon-ui'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'@@ -31,31 +33,187 @@ export function TeamsSection(): JSX.Element {)}-function TeamsChannelSection(): JSX.Element {+interface TeamsChannelRowProps {+ pair: { team_id: string; team_name?: string | null; channel_id: string; channel_name?: string | null }+ onRemove: () => void+ isLoading: boolean+ adminRestrictionReason: string | null+}++function TeamsChannelRow({ pair, onRemove, isLoading, adminRestrictionReason }: TeamsChannelRowProps): JSX.Element {+ return (+ <div className="flex items-center justify-between gap-2 py-2 px-3 bg-muted rounded">+ <div className="flex-1 min-w-0">+ <div className="font-medium truncate">{pair.team_name || pair.team_id}</div>+ <div className="text-xs text-muted-alt truncate">#{pair.channel_name || pair.channel_id}</div>+ </div>+ <LemonButton+ icon={<IconTrash />}+ size="small"+ status="danger"+ onClick={onRemove}+ loading={isLoading}+ disabledReason={adminRestrictionReason || (isLoading ? 'Removing...' : undefined)}+ />+ </div>+ )+}++interface AddTeamsChannelRowProps {+ adminRestrictionReason: string | null+}++function AddTeamsChannelRow({ adminRestrictionReason }: AddTeamsChannelRowProps): JSX.Element {const {- teamsConnected,- teamsTeamId,teamsTeams,teamsTeamsLoading,- teamsChannelId,- teamsChannels,teamsChannelsLoading,teamsInstallStatus,+ teamsInstallingForTeamId,+ teamsChannelsCache,+ teamsChannelPairLoading,+ teamsChannelPairs,} = useValues(supportSettingsLogic)- const {- connectTeams,- disconnectTeams,- setTeamsTeam,- setTeamsChannel,- loadTeamsTeamsWithToken,- loadTeamsChannelsForTeam,- installTeamsApp,- } = useActions(supportSettingsLogic)+ const { loadTeamsTeamsWithToken, loadTeamsChannelsForTeam, installTeamsApp, addTeamsChannelPair } =+ useActions(supportSettingsLogic)++ const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null)++ // One channel per Teams group: don't offer groups that already have a configured channel.+ const configuredTeamIds = new Set(teamsChannelPairs.map((p) => p.team_id))+ const availableTeams = teamsTeams.filter((t: { id: string }) => !configuredTeamIds.has(t.id))++ // Install status is a single global value; only apply it to the row when it refers to the selected team.+ const statusForSelected =+ selectedTeamId && teamsInstallingForTeamId === selectedTeamId ? teamsInstallStatus : 'idle'+ const isInstalling = statusForSelected === 'installing'+ const needsOrgCatalog = statusForSelected === 'needs_org_catalog'+ const installError = statusForSelected === 'error'+ const appInstalled = statusForSelected === 'installed'++ const selectedTeamChannels = selectedTeamId ? teamsChannelsCache[selectedTeamId] || [] : []++ const handleTeamSelect = (teamId: string | null): void => {+ setSelectedTeamId(teamId)+ // installTeamsApp loads the team's channels on success (and is idempotent server-side).+ if (teamId) {+ installTeamsApp(teamId)+ }+ }++ const handleChannelSelect = (channelId: string | null): void => {+ if (channelId && selectedTeamId) {+ addTeamsChannelPair(selectedTeamId, channelId)+ setSelectedTeamId(null)+ }+ }++ return (+ <div className="flex flex-col gap-2 py-2 px-3 border border-dashed border-muted rounded">+ <div className="flex gap-2 items-center">+ <div className="flex-1">+ <LemonSelect+ value={selectedTeamId}+ options={[+ { value: null, label: 'Select team group...' },+ ...availableTeams.map((t: { id: string; name: string }) => ({+ value: t.id,+ label: t.name,+ })),+ ]}+ onChange={handleTeamSelect}+ loading={teamsTeamsLoading}+ placeholder="Select team group"+ fullWidth+ disabledReason={adminRestrictionReason || undefined}+ />+ </div>+ <LemonButton+ type="secondary"+ size="small"+ onClick={loadTeamsTeamsWithToken}+ disabledReason={teamsTeamsLoading ? 'Loading...' : undefined}+ >+ Refresh+ </LemonButton>+ </div>++ {selectedTeamId && isInstalling && (+ <LemonBanner type="info">Installing SupportHog in the Teams group…</LemonBanner>+ )}++ {selectedTeamId && needsOrgCatalog && (+ <LemonBanner type="warning" className="flex flex-col gap-2">+ <div>+ <strong>SupportHog isn't available in your Microsoft tenant's app catalog.</strong> Your+ organisation's Teams admin needs to upload the SupportHog app package to your{' '}+ <Link to="https://posthog.com/docs/support/teams#org-catalog" target="_blank">+ org catalog+ </Link>{' '}+ (one-time). Once uploaded, click Retry.+ </div>+ <div>+ <LemonButton type="primary" size="small" onClick={() => installTeamsApp(selectedTeamId)}>+ Retry install+ </LemonButton>+ </div>+ </LemonBanner>+ )}++ {selectedTeamId && installError && (+ <LemonBanner type="error" className="flex flex-col gap-2">+ <div>Failed to install SupportHog into the selected Teams group.</div>+ <div>+ <LemonButton type="primary" size="small" onClick={() => installTeamsApp(selectedTeamId)}>+ Retry+ </LemonButton>+ </div>+ </LemonBanner>+ )}++ {selectedTeamId && appInstalled && (+ <div className="flex gap-2 items-center">+ <div className="flex-1">+ <LemonSelect+ value={null}+ options={[+ { value: null, label: 'Select channel...' },+ ...selectedTeamChannels.map((c: { id: string; name: string }) => ({+ value: c.id,+ label: `#${c.name}`,+ })),+ ]}+ onChange={handleChannelSelect}+ loading={teamsChannelsLoading || !!teamsChannelPairLoading}+ placeholder="Select channel"+ fullWidth+ disabledReason={adminRestrictionReason || undefined}+ />+ </div>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => loadTeamsChannelsForTeam(selectedTeamId)}+ disabledReason={teamsChannelsLoading ? 'Loading...' : undefined}+ >+ Refresh+ </LemonButton>+ </div>+ )}+ </div>+ )+}++function TeamsChannelSection(): JSX.Element {+ const { teamsConnected, teamsChannelPairs, teamsChannelPairLoading } = useValues(supportSettingsLogic)+ const { connectTeams, disconnectTeams, removeTeamsChannelPair } = useActions(supportSettingsLogic)const adminRestrictionReason = useRestrictedArea({scope: RestrictionScope.Organization,minimumAccessLevel: OrganizationMembershipLevel.Admin,})+ const [showAddRow, setShowAddRow] = useState(false)+return (<div className="flex flex-col gap-y-2"><div>@@ -79,131 +237,42 @@ function TeamsChannelSection(): JSX.Element {{teamsConnected && (<><LemonDivider />- <div className="gap-4">+ <div className="flex flex-col gap-2"><div>- <label className="font-medium">Teams group</label>+ <label className="font-medium">Support channels</label><p className="text-xs text-muted-alt">- Select the Microsoft Teams group that contains your support channel.+ Messages posted in these channels will automatically create support tickets. Thread+ replies become ticket messages. You can add one channel per Teams group.</p></div>- <div className="flex gap-2 items-center">- <LemonSelect- value={teamsTeamId}- options={[- { value: null, label: 'None' },- ...teamsTeams.map((t: { id: string; name: string }) => ({- value: t.id,- label: t.name,- })),- ]}- onChange={(value) => {- const team = teamsTeams.find((t: { id: string }) => t.id === value)- setTeamsTeam(value, team?.name ?? null)- }}- loading={teamsTeamsLoading}- placeholder="Select team"- />++ {teamsChannelPairs.length > 0 && (+ <div className="flex flex-col gap-2">+ {teamsChannelPairs.map((pair) => (+ <TeamsChannelRow+ key={pair.channel_id}+ pair={pair}+ onRemove={() => removeTeamsChannelPair(pair.channel_id)}+ isLoading={teamsChannelPairLoading === pair.channel_id}+ adminRestrictionReason={adminRestrictionReason}+ />+ ))}+ </div>+ )}++ {showAddRow ? (+ <AddTeamsChannelRow adminRestrictionReason={adminRestrictionReason} />+ ) : (<LemonButtontype="secondary"size="small"- onClick={loadTeamsTeamsWithToken}- disabledReason={teamsTeamsLoading ? 'Loading teams...' : undefined}+ onClick={() => setShowAddRow(true)}+ disabledReason={adminRestrictionReason || undefined}>- Refresh+ Add Teams channel</LemonButton>- </div>+ )}</div>- {teamsTeamId && teamsInstallStatus === 'installing' && (- <>- <LemonDivider />- <LemonBanner type="info">Installing SupportHog in your Teams group…</LemonBanner>- </>- )}- {teamsTeamId && teamsInstallStatus === 'needs_org_catalog' && (- <>- <LemonDivider />- <LemonBanner type="warning" className="flex flex-col gap-2">- <div>- <strong>SupportHog isn't available in your Microsoft tenant's app catalog.</strong>{' '}- Your organisation's Teams admin needs to upload the SupportHog app package to your{' '}- <Link to="https://posthog.com/docs/support/teams#org-catalog" target="_blank">- org catalog- </Link>{' '}- (one-time). Once uploaded, click Retry.- </div>- <div>- <LemonButton- type="primary"- size="small"- onClick={() => installTeamsApp(teamsTeamId)}- >- Retry install- </LemonButton>- </div>- </LemonBanner>- </>- )}- {teamsTeamId && teamsInstallStatus === 'error' && (- <>- <LemonDivider />- <LemonBanner type="error" className="flex flex-col gap-2">- <div>Failed to install SupportHog into the selected Teams group.</div>- <div>- <LemonButton- type="primary"- size="small"- onClick={() => installTeamsApp(teamsTeamId)}- >- Retry- </LemonButton>- </div>- </LemonBanner>- </>- )}- {teamsTeamId && teamsInstallStatus === 'installed' && (- <>- <LemonDivider />- <div className="gap-4">- <div>- <label className="font-medium">Support channel</label>- <p className="text-xs text-muted-alt">- Messages posted in this channel will automatically create support tickets.- Thread replies become ticket messages.- </p>- </div>- <div className="flex gap-2 items-center">- <LemonSelect- value={teamsChannelId}- options={[- { value: null, label: 'None' },- ...teamsChannels.map((c: { id: string; name: string }) => ({- value: c.id,- label: c.name,- })),- ]}- onChange={(value) => {- const channel = teamsChannels.find((c: { id: string }) => c.id === value)- setTeamsChannel(value, channel?.name ?? null)- }}- loading={teamsChannelsLoading}- placeholder="Select channel"- />- <LemonButton- type="secondary"- size="small"- onClick={() => {- if (teamsTeamId) {- loadTeamsChannelsForTeam(teamsTeamId)- }- }}- disabledReason={teamsChannelsLoading ? 'Loading channels...' : undefined}- >- Refresh- </LemonButton>- </div>- </div>- </>- )}<LemonDivider /><div className="flex items-center gap-4 justify-between"><div>diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.tsindex c23e464ded65..fcfea6faaed7 100644--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts@@ -16,6 +16,9 @@ describe('supportSettingsLogic', () => {},post: {'api/environments/:team_id/': async ({ request }) => [200, await request.json()],+ 'api/conversations/v1/teams/select-channel': { ok: true, teams_channels: [] },+ 'api/conversations/v1/teams/install': { ok: true, status: 'installed' },+ 'api/conversations/v1/teams/channels': { channels: [] },},})initKeaTests()@@ -74,4 +77,79 @@ describe('supportSettingsLogic', () => {expect(logic.values.aiSuggestionsLoading).toBe(false)})})++ describe('teamsChannelPairs selector', () => {+ it('reads the teams_channels list when present', async () => {+ initKeaTests(true, {+ conversations_settings: {+ teams_channels: [+ { team_id: 't1', team_name: 'Team 1', channel_id: 'ch-1', channel_name: 'Ch 1' },+ { team_id: 't2', team_name: 'Team 2', channel_id: 'ch-2', channel_name: 'Ch 2' },+ ],+ },+ } as unknown as TeamType)+ logic = supportSettingsLogic()+ logic.mount()+ await expectLogic(logic).toMatchValues({+ teamsChannelPairs: [+ { team_id: 't1', team_name: 'Team 1', channel_id: 'ch-1', channel_name: 'Ch 1' },+ { team_id: 't2', team_name: 'Team 2', channel_id: 'ch-2', channel_name: 'Ch 2' },+ ],+ })+ })++ it('falls back to legacy scalar fields when teams_channels is absent', async () => {+ initKeaTests(true, {+ conversations_settings: {+ teams_team_id: 'legacy-team',+ teams_team_name: 'Legacy Team',+ teams_channel_id: 'legacy-ch',+ teams_channel_name: 'Legacy Channel',+ },+ } as unknown as TeamType)+ logic = supportSettingsLogic()+ logic.mount()+ await expectLogic(logic).toMatchValues({+ teamsChannelPairs: [+ {+ team_id: 'legacy-team',+ team_name: 'Legacy Team',+ channel_id: 'legacy-ch',+ channel_name: 'Legacy Channel',+ },+ ],+ })+ })++ it('returns an empty list when nothing is configured', async () => {+ initKeaTests(true, { conversations_settings: { teams_enabled: true } } as unknown as TeamType)+ logic = supportSettingsLogic()+ logic.mount()+ await expectLogic(logic).toMatchValues({ teamsChannelPairs: [] })+ })+ })++ describe('teams channel pair actions', () => {+ it('addTeamsChannelPair posts an add action and refreshes the team', async () => {+ logic = supportSettingsLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.addTeamsChannelPair('t1', 'ch-1')+ })+ .toDispatchActions(['addTeamsChannelPair', 'loadCurrentTeam', 'installTeamsApp'])+ .toMatchValues({ teamsChannelPairLoading: null })+ })++ it('removeTeamsChannelPair posts a remove action and refreshes the team', async () => {+ logic = supportSettingsLogic()+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.removeTeamsChannelPair('ch-1')+ })+ .toDispatchActions(['removeTeamsChannelPair', 'loadCurrentTeam', 'setTeamsChannelPairLoading'])+ .toMatchValues({ teamsChannelPairLoading: null })+ })+ })})diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.tsindex b68fab8f62ea..a5335287bdf9 100644--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts@@ -67,8 +67,6 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([// Teams channel settingsconnectTeams: (nextPath: string) => ({ nextPath }),disconnectTeams: true,- setTeamsTeam: (teamId: string | null, teamName: string | null) => ({ teamId, teamName }),- setTeamsChannel: (channelId: string | null, channelName: string | null) => ({ channelId, channelName }),loadTeamsTeamsWithToken: true,loadTeamsChannelsForTeam: (teamId: string) => ({ teamId }),installTeamsApp: (teamId: string) => ({ teamId }),@@ -76,6 +74,11 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([status: 'idle' | 'installing' | 'installed' | 'needs_org_catalog' | 'error',teamId: string | null = null) => ({ status, teamId }),+ // Multi-channel Teams actions+ addTeamsChannelPair: (teamId: string, channelId: string) => ({ teamId, channelId }),+ removeTeamsChannelPair: (channelId: string) => ({ channelId }),+ setTeamsChannelPairLoading: (channelId: string | null) => ({ channelId }),+ cacheTeamsChannelsForTeam: (teamId: string, channels: { id: string; name: string }[]) => ({ teamId, channels }),// Email channel settings (multi-config)loadEmailConfigs: true,loadEmailConfigsDone: (configs: EmailConfigStatus[]) => ({ configs }),@@ -247,6 +250,21 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([disconnectTeams: () => null,},],+ teamsChannelsCache: [+ {} as Record<string, { id: string; name: string }[]>,+ {+ cacheTeamsChannelsForTeam: (state, { teamId, channels }) => ({ ...state, [teamId]: channels }),+ disconnectTeams: () => ({}),+ },+ ],+ teamsChannelPairLoading: [+ null as string | null,+ {+ setTeamsChannelPairLoading: (_, { channelId }) => channelId,+ addTeamsChannelPair: (_, { channelId }) => channelId,+ removeTeamsChannelPair: (_, { channelId }) => channelId,+ },+ ],aiSuggestionsLoading: [false,{@@ -274,7 +292,7 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([},],}),- loaders(({ values }) => ({+ loaders(({ actions, values }) => ({githubIntegrations: [[] as { id: number; name: string }[],{@@ -341,13 +359,16 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([teamsChannels: [[] as { id: string; name: string }[],{- loadTeamsChannelsForTeam: async ({ teamId }) => {+ loadTeamsChannelsForTeam: async ({ teamId }: { teamId: string }) => {try {// nosemgrep: prefer-codegen-apiconst response = await api.create('api/conversations/v1/teams/channels', {team_id: teamId,})- return response.channels || []+ const channels = response.channels || []+ // Also cache for multi-channel UI+ actions.cacheTeamsChannelsForTeam(teamId, channels)+ return channels} catch {lemonToast.error('Failed to load Teams channels')return values.teamsChannels@@ -428,6 +449,29 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([(s) => [s.currentTeam],(currentTeam): string | null => currentTeam?.conversations_settings?.teams_channel_name ?? null,],+ teamsChannelPairs: [+ (s) => [s.currentTeam],+ (+ currentTeam+ ): { team_id: string; team_name?: string | null; channel_id: string; channel_name?: string | null }[] => {+ const cs = currentTeam?.conversations_settings+ if (Array.isArray(cs?.teams_channels) && cs.teams_channels.length > 0) {+ return cs.teams_channels+ }+ // Fallback to legacy scalar fields+ if (cs?.teams_team_id && cs?.teams_channel_id) {+ return [+ {+ team_id: cs.teams_team_id,+ team_name: cs.teams_team_name,+ channel_id: cs.teams_channel_id,+ channel_name: cs.teams_channel_name,+ },+ ]+ }+ return []+ },+ ],githubConnected: [(s) => [s.currentTeam],(currentTeam): boolean => !!currentTeam?.conversations_settings?.github_enabled,@@ -744,23 +788,6 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([actions.loadCurrentTeam()lemonToast.success('Microsoft Teams disconnected')},- setTeamsTeam: async ({ teamId }) => {- try {- // nosemgrep: prefer-codegen-api- await api.create('api/conversations/v1/teams/select-channel', {- teams_team_id: teamId,- })- } catch {- lemonToast.error('Failed to save the selected Teams group')- return- }- actions.loadCurrentTeam()- if (teamId) {- actions.installTeamsApp(teamId)- } else {- actions.setTeamsInstallStatus('idle')- }- },installTeamsApp: async ({ teamId }) => {try {// nosemgrep: prefer-codegen-api@@ -791,23 +818,43 @@ export const supportSettingsLogic = kea<supportSettingsLogicType>([lemonToast.error('Failed to install SupportHog in the selected Teams group')}},- setTeamsChannel: async ({ channelId }) => {- const teamsTeamId = values.currentTeam?.conversations_settings?.teams_team_id- if (!teamsTeamId) {- lemonToast.error('Select a Microsoft Teams group before choosing a channel')+ addTeamsChannelPair: async ({ teamId, channelId }) => {+ try {+ // nosemgrep: prefer-codegen-api+ await api.create('api/conversations/v1/teams/select-channel', {+ action: 'add',+ team_id: teamId,+ channel_id: channelId,+ })+ } catch (err: any) {+ const detail = err?.data?.error ?? ''+ if (detail === 'max_channels_exceeded') {+ lemonToast.error('Maximum number of Teams channels reached')+ } else {+ lemonToast.error('Failed to add Teams channel')+ }+ actions.setTeamsChannelPairLoading(null)return}+ actions.loadCurrentTeam()+ actions.setTeamsChannelPairLoading(null)+ // Install app in the team group if not already installed+ actions.installTeamsApp(teamId)+ },+ removeTeamsChannelPair: async ({ channelId }) => {try {// nosemgrep: prefer-codegen-apiawait api.create('api/conversations/v1/teams/select-channel', {- teams_team_id: teamsTeamId,- teams_channel_id: channelId,+ action: 'remove',+ channel_id: channelId,})} catch {- lemonToast.error('Failed to save the selected Teams channel')+ lemonToast.error('Failed to remove Teams channel')+ actions.setTeamsChannelPairLoading(null)return}actions.loadCurrentTeam()+ actions.setTeamsChannelPairLoading(null)},setAiSuggestionsEnabled: ({ enabled }) => {actions.setAiSuggestionsLoading(true)