Skip to content

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

feat(customer-analytics): add announcements API with channel validation (#70366)

Christophe Eynius Tranberg3107eace13a0
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 2d2a6b4b378e..5f23f7eae50c 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -572,6 +572,8 @@ SPECTACULAR_SETTINGS = {
"MetricsRecalculationStatusEnum": (
"products.experiments.backend.models.experiment.ExperimentMetricsRecalculation.Status"
),
+ "AnnouncementStatusEnum": "products.customer_analytics.backend.models.announcement.Announcement.Status",
+ "AnnouncementDeliveryStatusEnum": "products.customer_analytics.backend.models.announcement_delivery.AnnouncementDelivery.Status",
"HealthIssueStatusEnum": "posthog.models.health_issue.HealthIssue.Status",
"HealthIssueSeverityEnum": "posthog.models.health_issue.HealthIssue.Severity",
"IngestionWarningSeverityEnum": "posthog.api.ingestion_warnings_v2.INGESTION_WARNING_SEVERITIES",
diff --git a/products/customer_analytics/backend/constants.py b/products/customer_analytics/backend/constants.py
index c1526e4d11de..803d83240644 100644
--- a/products/customer_analytics/backend/constants.py
+++ b/products/customer_analytics/backend/constants.py
@@ -32,3 +32,6 @@ CUSTOM_PROPERTY_DISPLAY_TYPE_CHOICES = [
# Mirrors OPTION_COLOR_TOKENS in the frontend's customPropertyTypes.ts (DataColorToken presets).
CUSTOM_PROPERTY_OPTION_COLORS = [f"preset-{i}" for i in range(1, 11)]
+
+# Bounds the fan-out so one create can't enqueue an unbounded Slack send loop.
+MAX_ANNOUNCEMENT_CHANNELS = 200
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index b44fbf782609..c855af589381 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -34,7 +34,9 @@ from posthog.models import OrganizationMembership, Tag
from posthog.models.activity_logging.activity_log import AuditableScope, Detail, changes_between, log_activity
from posthog.models.tag import tagify
from posthog.models.tagged_item import TaggedItem
+from posthog.models.team import Team
+from products.conversations.backend.facade.api import SupportSlackChannelsUnavailable, SupportSlackNotConfigured
from products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplink
from products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDS
from products.customer_analytics.backend.events import emit_account_tags_added
@@ -42,6 +44,7 @@ from products.customer_analytics.backend.facade.contracts import (
InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,
)
from products.customer_analytics.backend.logic import (
+ announcements as _announcements_logic,
custom_property_values as _custom_property_values_logic,
relationships as _relationships_logic,
)
@@ -60,6 +63,7 @@ from products.customer_analytics.backend.models import (
Account,
AccountRelationship,
AccountRelationshipDefinition,
+ Announcement,
CustomerJourney,
CustomerProfileConfig,
CustomPropertyDefinition,
@@ -88,6 +92,8 @@ logger = structlog.get_logger(__name__)
_ACCOUNT_PROPERTY_TEMPLATE_ID = "template-posthog-update-account-property"
_ACCOUNT_PROPERTY_INPUT_KEY = "properties"
+logger = structlog.get_logger(__name__)
+
if TYPE_CHECKING:
from posthog.models.user import User
from posthog.rbac.user_access_control import UserAccessControl
@@ -2098,3 +2104,71 @@ def end_account_relationship(
except _relationships_logic.AccountRelationshipNotFound:
return None
return _to_account_relationship(relationship)
+
+
+# --- Announcements ---
+
+
+def _to_announcement_delivery_view(delivery) -> contracts.AnnouncementDeliveryView:
+ return contracts.AnnouncementDeliveryView(
+ id=delivery.id,
+ slack_channel_id=delivery.slack_channel_id,
+ slack_channel_name=delivery.slack_channel_name,
+ status=delivery.status,
+ error=delivery.error,
+ slack_message_ts=delivery.slack_message_ts,
+ sent_at=delivery.sent_at,
+ )
+
+
+def _to_announcement_view(announcement) -> contracts.AnnouncementView:
+ return contracts.AnnouncementView(
+ id=announcement.id,
+ short_id=announcement.short_id,
+ message=announcement.message,
+ status=announcement.status,
+ total_channels=announcement.total_channels,
+ sent_count=announcement.sent_count,
+ failed_count=announcement.failed_count,
+ sent_at=announcement.sent_at,
+ created_at=announcement.created_at,
+ created_by=_to_user_basic_info(announcement.created_by),
+ deliveries=[_to_announcement_delivery_view(d) for d in announcement.deliveries.all()],
+ )
+
+
+def _announcements_queryset(team_id: int):
+ return (
+ Announcement.objects.for_team(team_id)
+ .select_related("created_by")
+ .prefetch_related("deliveries")
+ .order_by("-created_at")
+ )
+
+
+def list_announcements(team_id: int, offset: int, limit: int) -> tuple[list[contracts.AnnouncementView], int]:
+ queryset = _announcements_queryset(team_id)
+ total_count = queryset.count()
+ page = queryset[offset : offset + limit]
+ return [_to_announcement_view(a) for a in page], total_count
+
+
+def get_announcement(team_id: int, short_id: str) -> contracts.AnnouncementView | None:
+ announcement = _announcements_queryset(team_id).filter(short_id=short_id).first()
+ return _to_announcement_view(announcement) if announcement is not None else None
+
+
+def create_announcement(*, team_id: int, user: "User", message: str, channels: list[str]) -> contracts.AnnouncementView:
+ team = Team.objects.get(id=team_id)
+ announcement = _announcements_logic.create_announcement(team, user, message, channels)
+ return _to_announcement_view(announcement)
+
+
+def list_announcement_channels(team_id: int) -> list[contracts.AnnouncementChannelView]:
+ try:
+ return _announcements_logic.list_channels(team_id)
+ except SupportSlackNotConfigured:
+ return []
+ except SupportSlackChannelsUnavailable:
+ logger.warning("announcement_channels_unavailable", team_id=team_id)
+ return []
diff --git a/products/customer_analytics/backend/facade/constants.py b/products/customer_analytics/backend/facade/constants.py
index 91233596f361..68b94c75d056 100644
--- a/products/customer_analytics/backend/facade/constants.py
+++ b/products/customer_analytics/backend/facade/constants.py
@@ -13,6 +13,7 @@ from products.customer_analytics.backend.constants import (
CUSTOM_PROPERTY_OPTION_COLORS,
CUSTOMER_ANALYTICS_CSP_FLAG,
DEFAULT_ACTIVITY_EVENT,
+ MAX_ANNOUNCEMENT_CHANNELS,
)
__all__ = [
@@ -23,4 +24,5 @@ __all__ = [
"CUSTOM_PROPERTY_OPTION_COLORS",
"CUSTOMER_ANALYTICS_CSP_FLAG",
"DEFAULT_ACTIVITY_EVENT",
+ "MAX_ANNOUNCEMENT_CHANNELS",
]
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 3c5167b396d6..7739ae6f0284 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -507,3 +507,46 @@ class ExternalAccountCustomPropertiesResult:
values: list[CustomPropertyValue] | None = None
error: ExternalAccountCustomPropertiesError | None = None
error_field: str | None = None
+
+
+class AnnouncementValidationError(ValueError):
+ def __init__(self, detail: str | dict[str, str]) -> None:
+ super().__init__(str(detail))
+ self.detail = detail
+
+
+@stdlib_dataclass(frozen=True)
+class AnnouncementChannelView:
+ id: str
+ name: str
+ is_member: bool
+ customer_name: str | None
+
+
+@stdlib_dataclass(frozen=True)
+class AnnouncementDeliveryView:
+ id: UUID | None = None
+ slack_channel_id: str = ""
+ slack_channel_name: str = ""
+ status: str = ""
+ error: str = ""
+ slack_message_ts: str = ""
+ sent_at: datetime | None = None
+
+
+@stdlib_dataclass(frozen=True)
+class AnnouncementView:
+ # Defaults let the wrapping DataclassSerializer parse create requests, which carry only
+ # message + channels; channels is write-only and always returned empty.
+ id: UUID | None = None
+ short_id: str = ""
+ message: str = ""
+ status: str = ""
+ total_channels: int = 0
+ sent_count: int = 0
+ failed_count: int = 0
+ sent_at: datetime | None = None
+ created_at: datetime | None = None
+ created_by: UserBasicInfo | None = None
+ deliveries: list[AnnouncementDeliveryView] = field(default_factory=list)
+ channels: list[str] = field(default_factory=list)
diff --git a/products/customer_analytics/backend/logic/announcements.py b/products/customer_analytics/backend/logic/announcements.py
new file mode 100644
index 000000000000..a6bde3ef6f6e
--- /dev/null
+++ b/products/customer_analytics/backend/logic/announcements.py
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from django.db import transaction
+
+from products.conversations.backend.facade.api import (
+ SupportSlackChannelsUnavailable,
+ SupportSlackNotConfigured,
+ list_support_bot_channels,
+)
+from products.customer_analytics.backend.facade.contracts import AnnouncementChannelView, AnnouncementValidationError
+from products.customer_analytics.backend.models import Account, Announcement, AnnouncementDelivery
+
+if TYPE_CHECKING:
+ from posthog.models.team import Team
+ from posthog.models.user import User
+
+
+def create_announcement(team: Team, created_by: User, message: str, channel_ids: list[str]) -> Announcement:
+ try:
+ allowed = {c.id: c for c in list_support_bot_channels(team.pk, members_only=True)}
+ except SupportSlackNotConfigured:
+ raise AnnouncementValidationError("The SupportHog Slack bot is not connected.")
+ except SupportSlackChannelsUnavailable:
+ raise AnnouncementValidationError("Could not verify Slack channels right now. Please try again.")
+
+ # Only member channels get a pending row (the only state the send task posts), so a
+ # crafted channel ID can never make the bot post to an arbitrary Slack destination;
+ # non-member channels are born failed, same as a channel lost between create and send.
+ with transaction.atomic():
+ announcement = Announcement.objects.create(
+ team=team,
+ message=message,
+ created_by=created_by,
+ total_channels=len(channel_ids),
+ status=Announcement.Status.PENDING,
+ )
+ AnnouncementDelivery.objects.bulk_create(
+ [
+ AnnouncementDelivery(
+ team=team,
+ announcement=announcement,
+ slack_channel_id=cid,
+ slack_channel_name=allowed[cid].name if cid in allowed else "",
+ status=(
+ AnnouncementDelivery.Status.PENDING if cid in allowed else AnnouncementDelivery.Status.FAILED
+ ),
+ error="" if cid in allowed else "not_in_channel",
+ )
+ for cid in channel_ids
+ ]
+ )
+ return announcement
+
+
+def list_channels(team_id: int) -> list[AnnouncementChannelView]:
+ member_channels = list_support_bot_channels(team_id, members_only=True)
+ name_by_channel = _customer_names_by_channel(team_id)
+ enriched = [
+ AnnouncementChannelView(
+ id=c.id,
+ name=c.name,
+ is_member=c.is_member,
+ customer_name=name_by_channel.get(c.id),
+ )
+ for c in member_channels
+ ]
+ enriched.sort(key=lambda c: (c.customer_name is None, (c.customer_name or c.name).lower()))
+ return enriched
+
+
+def _customer_names_by_channel(team_id: int) -> dict[str, str]:
+ result: dict[str, str] = {}
+ rows = Account.objects.for_team(team_id).filter(_properties__has_key="slack_channel_id")
+ for channel_id, name in rows.values_list("_properties__slack_channel_id", "name"):
+ if channel_id:
+ result.setdefault(channel_id, name)
+ return result
diff --git a/products/customer_analytics/backend/presentation/views/announcements.py b/products/customer_analytics/backend/presentation/views/announcements.py
new file mode 100644
index 000000000000..29abd52ebfa9
--- /dev/null
+++ b/products/customer_analytics/backend/presentation/views/announcements.py
@@ -0,0 +1,197 @@
+from __future__ import annotations
+
+from typing import Any, cast
+
+from drf_spectacular.utils import extend_schema
+from rest_framework import mixins, serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import UserBasicSerializer
+from posthog.event_usage import report_user_action
+from posthog.models.user import User
+
+from products.customer_analytics.backend.facade import api
+from products.customer_analytics.backend.facade.constants import MAX_ANNOUNCEMENT_CHANNELS
+from products.customer_analytics.backend.facade.contracts import (
+ AnnouncementDeliveryView,
+ AnnouncementValidationError,
+ AnnouncementView,
+)
+from products.customer_analytics.backend.presentation.views.views import _FacadePaginationMixin
+
+# Duplicated from the model TextChoices so this module imports no product models;
+# ENUM_NAME_OVERRIDES matches the generated enums against these by value.
+_ANNOUNCEMENT_STATUS_CHOICES = [
+ ("pending", "Pending"),
+ ("sending", "Sending"),
+ ("sent", "Sent"),
+ ("partially_failed", "Partially failed"),
+ ("failed", "Failed"),
+]
+
+_DELIVERY_STATUS_CHOICES = [
+ ("pending", "Pending"),
+ ("sent", "Sent"),
+ ("failed", "Failed"),
+]
+
+
+class AnnouncementDeliverySerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True)
+ slack_channel_id = serializers.CharField(
+ read_only=True, help_text="Slack channel ID the message was sent to (e.g. C0123ABCD)."
+ )
+ slack_channel_name = serializers.CharField(
+ read_only=True, help_text="Slack channel display name at send time (without the leading #)."
+ )
+ status = serializers.ChoiceField(
+ read_only=True,
+ choices=_DELIVERY_STATUS_CHOICES,
+ help_text="Per-channel delivery status: pending, sent, or failed.",
+ )
+ error = serializers.CharField(
+ read_only=True, help_text="Slack error code when delivery to this channel failed; empty otherwise."
+ )
+ slack_message_ts = serializers.CharField(
+ read_only=True, help_text="Timestamp ID of the posted Slack message, when delivery succeeded."
+ )
+ sent_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="When the message was delivered to this channel. Null until sent."
+ )
+
+ class Meta:
+ dataclass = AnnouncementDeliveryView
+ ref_name = "AnnouncementDelivery"
+ fields = ["id", "slack_channel_id", "slack_channel_name", "status", "error", "slack_message_ts", "sent_at"]
+
+
+class AnnouncementChannelSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Slack channel ID (e.g. C0123ABCD).")
+ name = serializers.CharField(help_text="Slack channel display name (without the leading #).")
+ is_member = serializers.BooleanField(help_text="Whether the SupportHog bot is a member of this channel.")
+ customer_name = serializers.CharField(
+ allow_null=True,
+ help_text="Name of the customer account whose slack_channel_id points at this channel, or null if unmapped.",
+ )
+
+
+class AnnouncementSerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True)
+ short_id = serializers.CharField(read_only=True, help_text="Short human-friendly identifier for the announcement.")
+ message = serializers.CharField(help_text="Message body to send, rendered as Slack mrkdwn.")
+ status = serializers.ChoiceField(
+ read_only=True,
+ choices=_ANNOUNCEMENT_STATUS_CHOICES,
+ help_text="Overall status: pending, sending, sent, partially_failed, or failed.",
+ )
+ total_channels = serializers.IntegerField(read_only=True, help_text="Number of channels this announcement targets.")
+ sent_count = serializers.IntegerField(
+ read_only=True, help_text="Number of channels the message was successfully delivered to."
+ )
+ failed_count = serializers.IntegerField(read_only=True, help_text="Number of channels delivery failed for.")
+ sent_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="When delivery finished (all channels resolved). Null while pending/sending.",
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the announcement was created.")
+ created_by = UserBasicSerializer(read_only=True)
+ deliveries = AnnouncementDeliverySerializer(
+ many=True, read_only=True, help_text="Per-channel delivery rows, one per selected Slack channel."
+ )
+ channels = serializers.ListField(
+ child=serializers.CharField(),
+ write_only=True,
+ help_text="Slack channel IDs to send to. Each must be a channel the SupportHog bot is a member of; "
+ "names are resolved server-side.",
+ )
+
+ class Meta:
+ dataclass = AnnouncementView
+ ref_name = "Announcement"
+ fields = [
+ "id",
+ "short_id",
+ "message",
+ "status",
+ "total_channels",
+ "sent_count",
+ "failed_count",
+ "sent_at",
+ "created_at",
+ "created_by",
+ "deliveries",
+ "channels",
+ ]
+
+ def validate_message(self, value: str) -> str:
+ if not value.strip():
+ raise serializers.ValidationError("Message cannot be empty.")
+ return value
+
+ def validate_channels(self, value: list[str]) -> list[str]:
+ deduped = list(dict.fromkeys(value))
+ if not deduped:
+ raise serializers.ValidationError("Select at least one channel.")
+ if len(deduped) > MAX_ANNOUNCEMENT_CHANNELS:
+ raise serializers.ValidationError(
+ f"An announcement can target at most {MAX_ANNOUNCEMENT_CHANNELS} channels."
+ )
+ return deduped
+
+
+class AnnouncementViewSet(
+ TeamAndOrgViewSetMixin,
+ _FacadePaginationMixin,
+ mixins.CreateModelMixin,
+ viewsets.ReadOnlyModelViewSet,
+):
+ scope_object = "customer_analytics"
+ serializer_class = AnnouncementSerializer
+ queryset = None # data is reached through the facade; declared for router/schema only
+ lookup_field = "short_id"
+
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return self._paginate_via_facade(
+ request,
+ lambda offset, limit: api.list_announcements(self.team_id, offset=offset, limit=limit),
+ AnnouncementSerializer,
+ )
+
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ announcement = api.get_announcement(self.team_id, self.kwargs["short_id"])
+ if announcement is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(AnnouncementSerializer(instance=announcement).data)
+
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = AnnouncementSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+ try:
+ announcement = api.create_announcement(
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ message=data.message,
+ channels=data.channels,
+ )
+ except AnnouncementValidationError as e:
+ raise serializers.ValidationError(e.detail)
+ report_user_action(
+ request.user,
+ "customer analytics announcement created",
+ {"id": str(announcement.id), "channel_count": announcement.total_channels},
+ team=self.team,
+ )
+ return Response(AnnouncementSerializer(instance=announcement).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(responses=AnnouncementChannelSerializer(many=True))
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def channels(self, request: Request, **kwargs: Any) -> Response:
+ """Slack channels the SupportHog bot can post to, labeled by customer account name."""
+ member_channels = api.list_announcement_channels(self.team_id)
+ return Response(AnnouncementChannelSerializer(member_channels, many=True).data)
diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.py
index 2ff80a910611..44f83163a5a5 100644
--- a/products/customer_analytics/backend/routes.py
+++ b/products/customer_analytics/backend/routes.py
@@ -1,5 +1,6 @@
from posthog.api.routing import RouterRegistry
+from products.customer_analytics.backend.presentation.views.announcements import AnnouncementViewSet
from products.customer_analytics.backend.presentation.views.organization_members import (
OrganizationMembersForAccountViewSet,
)
@@ -18,6 +19,12 @@ from products.customer_analytics.backend.presentation.views.views import (
def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(
+ r"announcements",
+ AnnouncementViewSet,
+ "project_announcements",
+ ["team_id"],
+ )
routers.projects.register(
r"organization_members",
OrganizationMembersForAccountViewSet,
diff --git a/products/customer_analytics/backend/test/test_announcements.py b/products/customer_analytics/backend/test/test_announcements.py
new file mode 100644
index 000000000000..dd7c02e4909b
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_announcements.py
@@ -0,0 +1,159 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
+
+from rest_framework import status
+
+from posthog.models.team import Team
+
+from products.conversations.backend.facade.api import SupportChannel, SupportSlackNotConfigured
+from products.customer_analytics.backend.models import Account, Announcement, AnnouncementDelivery
+
+HELPER = "products.customer_analytics.backend.logic.announcements.list_support_bot_channels"
+
+
+class TestAnnouncementAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.base_url = f"/api/projects/{self.team.pk}/announcements/"
+
+ def _member_channels(self):
+ return [
+ SupportChannel(id="C1", name="acme-corp", is_member=True),
+ SupportChannel(id="C2", name="globex", is_member=True),
+ ]
+
+ @patch("products.customer_analytics.backend.presentation.views.announcements.report_user_action")
+ @patch(HELPER)
+ def test_create_persists_announcement_and_resolves_channel_names(self, mock_channels, _mock_report):
+ mock_channels.return_value = self._member_channels()
+
+ response = self.client.post(
+ self.base_url, {"message": "Offsite this week, slower replies.", "channels": ["C1", "C2"]}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ data = response.json()
+ assert data["status"] == "pending"
+ assert data["total_channels"] == 2
+ assert data["created_by"]["id"] == self.user.pk
+ assert {(d["slack_channel_id"], d["slack_channel_name"]) for d in data["deliveries"]} == {
+ ("C1", "acme-corp"),
+ ("C2", "globex"),
+ }
+ announcement = Announcement.all_teams.get(id=data["id"])
+ assert AnnouncementDelivery.all_teams.filter(announcement=announcement).count() == 2
+
+ @patch(HELPER)
+ def test_create_isolates_non_member_channel(self, mock_channels):
+ mock_channels.return_value = self._member_channels()
+
+ response = self.client.post(self.base_url, {"message": "hi", "channels": ["C1", "D_secret_dm"]}, format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED
+ announcement = Announcement.all_teams.get(id=response.json()["id"])
+ by_channel = {d.slack_channel_id: d for d in AnnouncementDelivery.all_teams.filter(announcement=announcement)}
+ assert by_channel["D_secret_dm"].status == AnnouncementDelivery.Status.FAILED
+ assert by_channel["D_secret_dm"].error == "not_in_channel"
+ assert by_channel["C1"].status == AnnouncementDelivery.Status.PENDING
+
+ @patch(HELPER)
+ def test_create_rejects_when_slack_not_connected(self, mock_channels):
+ mock_channels.side_effect = SupportSlackNotConfigured()
+
+ response = self.client.post(self.base_url, {"message": "hi", "channels": ["C1"]}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert Announcement.all_teams.count() == 0
+
+ @patch(HELPER)
+ def test_create_validates_message_and_channels(self, mock_channels):
+ mock_channels.return_value = self._member_channels()
+
+ assert (
+ self.client.post(self.base_url, {"message": " ", "channels": ["C1"]}, format="json").status_code
+ == status.HTTP_400_BAD_REQUEST
+ )
+ assert (
+ self.client.post(self.base_url, {"message": "hi", "channels": []}, format="json").status_code
+ == status.HTTP_400_BAD_REQUEST
+ )
+ assert Announcement.all_teams.count() == 0
+
+ @patch(HELPER)
+ def test_create_dedupes_channels(self, mock_channels):
+ mock_channels.return_value = self._member_channels()
+
+ response = self.client.post(self.base_url, {"message": "hi", "channels": ["C1", "C1"]}, format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json()["total_channels"] == 1
+
+ @patch(HELPER)
+ def test_list_and_retrieve_scoped_to_team(self, mock_channels):
+ mock_channels.return_value = self._member_channels()
+ created = self.client.post(self.base_url, {"message": "A", "channels": ["C1"]}, format="json").json()
+
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other = Announcement.all_teams.create(team=other_team, message="secret", total_channels=0)
+
+ list_resp = self.client.get(self.base_url)
+ assert list_resp.status_code == status.HTTP_200_OK
+ assert {r["message"] for r in list_resp.json()["results"]} == {"A"}
+
+ assert self.client.get(f"{self.base_url}{created['short_id']}/").status_code == status.HTTP_200_OK
+ assert self.client.get(f"{self.base_url}{other.short_id}/").status_code == status.HTTP_404_NOT_FOUND
+
+ def test_list_query_count_does_not_grow_with_announcements(self):
+ def create_announcement_with_deliveries(index: int) -> None:
+ announcement = Announcement.all_teams.create(
+ team=self.team, message=f"msg {index}", created_by=self.user, total_channels=2
+ )
+ AnnouncementDelivery.all_teams.bulk_create(
+ AnnouncementDelivery(
+ team=self.team, announcement=announcement, slack_channel_id=f"C{index}-{n}", slack_channel_name="ch"
+ )
+ for n in range(2)
+ )
+
+ create_announcement_with_deliveries(0)
+ self.client.get(self.base_url) # warm request-scoped caches so both captures compare equal work
+ with CaptureQueriesContext(connection) as small_list:
+ assert self.client.get(self.base_url).status_code == status.HTTP_200_OK
+
+ for index in range(1, 5):
+ create_announcement_with_deliveries(index)
+ with CaptureQueriesContext(connection) as large_list:
+ response = self.client.get(self.base_url)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["results"]) == 5
+ assert len(large_list) == len(small_list)
+
+ @patch(HELPER)
+ def test_channels_action_labels_by_customer_and_sorts_mapped_first(self, mock_channels):
+ mock_channels.return_value = [
+ SupportChannel(id="C1", name="zzz-internal", is_member=True),
+ SupportChannel(id="C2", name="acme-shared", is_member=True),
+ ]
+ Account.objects.create_account(team=self.team, name="Acme", properties={"slack_channel_id": "C2"})
+
+ response = self.client.get(f"{self.base_url}channels/")
+
+ assert response.status_code == status.HTTP_200_OK
+ channels = response.json()
+ assert channels[0]["id"] == "C2"
+ assert channels[0]["customer_name"] == "Acme"
+ assert channels[1]["id"] == "C1"
+ assert channels[1]["customer_name"] is None
+
+ @patch(HELPER)
+ def test_channels_action_returns_empty_when_slack_not_connected(self, mock_channels):
+ mock_channels.side_effect = SupportSlackNotConfigured()
+
+ response = self.client.get(f"{self.base_url}channels/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == []
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 79b722053b95..8ef6acee23f0 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -437,6 +437,117 @@ export interface PatchedAccountApi {
readonly updated_at?: string | null
}
+/**
+ * * `pending` - Pending
+ * * `sending` - Sending
+ * * `sent` - Sent
+ * * `partially_failed` - Partially failed
+ * * `failed` - Failed
+ */
+export type AnnouncementStatusEnumApi = (typeof AnnouncementStatusEnumApi)[keyof typeof AnnouncementStatusEnumApi]
+
+export const AnnouncementStatusEnumApi = {
+ Pending: 'pending',
+ Sending: 'sending',
+ Sent: 'sent',
+ PartiallyFailed: 'partially_failed',
+ Failed: 'failed',
+} as const
+
+/**
+ * * `pending` - Pending
+ * * `sent` - Sent
+ * * `failed` - Failed
+ */
+export type AnnouncementDeliveryStatusEnumApi =
+ (typeof AnnouncementDeliveryStatusEnumApi)[keyof typeof AnnouncementDeliveryStatusEnumApi]
+
+export const AnnouncementDeliveryStatusEnumApi = {
+ Pending: 'pending',
+ Sent: 'sent',
+ Failed: 'failed',
+} as const
+
+export interface AnnouncementDeliveryApi {
+ readonly id: string
+ /** Slack channel ID the message was sent to (e.g. C0123ABCD). */
+ readonly slack_channel_id: string
+ /** Slack channel display name at send time (without the leading #). */
+ readonly slack_channel_name: string
+ /** Per-channel delivery status: pending, sent, or failed.
+ *
+ * * `pending` - Pending
+ * * `sent` - Sent
+ * * `failed` - Failed */
+ readonly status: AnnouncementDeliveryStatusEnumApi
+ /** Slack error code when delivery to this channel failed; empty otherwise. */
+ readonly error: string
+ /** Timestamp ID of the posted Slack message, when delivery succeeded. */
+ readonly slack_message_ts: string
+ /**
+ * When the message was delivered to this channel. Null until sent.
+ * @nullable
+ */
+ readonly sent_at: string | null
+}
+
+export interface AnnouncementApi {
+ readonly id: string
+ /** Short human-friendly identifier for the announcement. */
+ readonly short_id: string
+ /** Message body to send, rendered as Slack mrkdwn. */
+ message: string
+ /** Overall status: pending, sending, sent, partially_failed, or failed.
+ *
+ * * `pending` - Pending
+ * * `sending` - Sending
+ * * `sent` - Sent
+ * * `partially_failed` - Partially failed
+ * * `failed` - Failed */
+ readonly status: AnnouncementStatusEnumApi
+ /** Number of channels this announcement targets. */
+ readonly total_channels: number
+ /** Number of channels the message was successfully delivered to. */
+ readonly sent_count: number
+ /** Number of channels delivery failed for. */
+ readonly failed_count: number
+ /**
+ * When delivery finished (all channels resolved). Null while pending/sending.
+ * @nullable
+ */
+ readonly sent_at: string | null
+ /** When the announcement was created. */
+ readonly created_at: string
+ readonly created_by: UserBasicApi
+ /** Per-channel delivery rows, one per selected Slack channel. */
+ readonly deliveries: readonly AnnouncementDeliveryApi[]
+ /** Slack channel IDs to send to. Each must be a channel the SupportHog bot is a member of; names are resolved server-side. */
+ channels: string[]
+}
+
+export interface PaginatedAnnouncementListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: AnnouncementApi[]
+}
+
+export interface AnnouncementChannelApi {
+ /** Slack channel ID (e.g. C0123ABCD). */
+ id: string
+ /** Slack channel display name (without the leading #). */
+ name: string
+ /** Whether the SupportHog bot is a member of this channel. */
+ is_member: boolean
+ /**
+ * Name of the customer account whose slack_channel_id points at this channel, or null if unmapped.
+ * @nullable
+ */
+ customer_name: string | null
+}
+
/**
* * `text` - text
* * `number` - number
@@ -1119,6 +1230,17 @@ export type AccountsRelationshipsListParams = {
include_history?: boolean
}
+export type AnnouncementsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type CustomPropertyDefinitionsListParams = {
/**
* Number of results to return per page.
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index 46f6fc0498e2..abdd10a085fe 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -19,6 +19,9 @@ import type {
AccountsListParams,
AccountsNotebooksListParams,
AccountsRelationshipsListParams,
+ AnnouncementApi,
+ AnnouncementChannelApi,
+ AnnouncementsListParams,
CustomPropertyDefinitionApi,
CustomPropertyDefinitionsListParams,
CustomPropertyDefinitionsValuesRetrieveParams,
@@ -40,6 +43,7 @@ import type {
PaginatedAccountNoteListApi,
PaginatedAccountNotebookListApi,
PaginatedAccountRelationshipDefinitionListApi,
+ PaginatedAnnouncementListApi,
PaginatedCustomPropertyDefinitionListApi,
PaginatedCustomPropertySourceListApi,
PaginatedCustomerJourneyListApi,
@@ -532,6 +536,82 @@ export const accountsDestroy = async (projectId: string, id: string, options?: R
})
}
+export const getAnnouncementsListUrl = (projectId: string, params?: AnnouncementsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/announcements/?${stringifiedParams}`
+ : `/api/projects/${projectId}/announcements/`
+}
+
+export const announcementsList = async (
+ projectId: string,
+ params?: AnnouncementsListParams,
+ options?: RequestInit
+): Promise<PaginatedAnnouncementListApi> => {
+ return apiMutator<PaginatedAnnouncementListApi>(getAnnouncementsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAnnouncementsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/announcements/`
+}
+
+export const announcementsCreate = async (
+ projectId: string,
+ announcementApi: NonReadonly<AnnouncementApi>,
+ options?: RequestInit
+): Promise<AnnouncementApi> => {
+ return apiMutator<AnnouncementApi>(getAnnouncementsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(announcementApi),
+ })
+}
+
+export const getAnnouncementsRetrieveUrl = (projectId: string, shortId: string) => {
+ return `/api/projects/${projectId}/announcements/${shortId}/`
+}
+
+export const announcementsRetrieve = async (
+ projectId: string,
+ shortId: string,
+ options?: RequestInit
+): Promise<AnnouncementApi> => {
+ return apiMutator<AnnouncementApi>(getAnnouncementsRetrieveUrl(projectId, shortId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getAnnouncementsChannelsListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/announcements/channels/`
+}
+
+/**
+ * Slack channels the SupportHog bot can post to, labeled by customer account name.
+ */
+export const announcementsChannelsList = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<AnnouncementChannelApi[]> => {
+ return apiMutator<AnnouncementChannelApi[]>(getAnnouncementsChannelsListUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getCustomPropertyDefinitionsListUrl = (
projectId: string,
params?: CustomPropertyDefinitionsListParams
diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.ts
index f56904498282..5cec5bd74a62 100644
--- a/products/customer_analytics/frontend/generated/api.zod.ts
+++ b/products/customer_analytics/frontend/generated/api.zod.ts
@@ -276,6 +276,15 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod
})
.describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')
+export const AnnouncementsCreateBody = /* @__PURE__ */ zod.object({
+ message: zod.string().describe('Message body to send, rendered as Slack mrkdwn.'),
+ channels: zod
+ .array(zod.string())
+ .describe(
+ 'Slack channel IDs to send to. Each must be a channel the SupportHog bot is a member of; names are resolved server-side.'
+ ),
+})
+
export const customPropertyDefinitionsCreateBodyNameMax = 400
export const customPropertyDefinitionsCreateBodyTargetTypeDefault = `account`
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 3c8062b6f9ce..d879d1777f1d 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -362,6 +362,18 @@ tools:
accounts-update:
operation: accounts_update
enabled: false
+ announcements-channels-list:
+ operation: announcements_channels_list
+ enabled: false
+ announcements-create:
+ operation: announcements_create
+ enabled: false
+ announcements-list:
+ operation: announcements_list
+ enabled: false
+ announcements-retrieve:
+ operation: announcements_retrieve
+ enabled: false
custom-property-definitions-create:
operation: custom_property_definitions_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5b59e104780c..cb08580f9462 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10134,6 +10134,109 @@ export namespace Schemas {
hidden_in_user_interface?: boolean | null;
}
+ /**
+ * * `pending` - Pending
+ * * `sending` - Sending
+ * * `sent` - Sent
+ * * `partially_failed` - Partially failed
+ * * `failed` - Failed
+ */
+ export type AnnouncementStatusEnum = typeof AnnouncementStatusEnum[keyof typeof AnnouncementStatusEnum];
+
+
+ export const AnnouncementStatusEnum = {
+ Pending: 'pending',
+ Sending: 'sending',
+ Sent: 'sent',
+ PartiallyFailed: 'partially_failed',
+ Failed: 'failed',
+ } as const;
+
+ /**
+ * * `pending` - Pending
+ * * `sent` - Sent
+ * * `failed` - Failed
+ */
+ export type AnnouncementDeliveryStatusEnum = typeof AnnouncementDeliveryStatusEnum[keyof typeof AnnouncementDeliveryStatusEnum];
+
+
+ export const AnnouncementDeliveryStatusEnum = {
+ Pending: 'pending',
+ Sent: 'sent',
+ Failed: 'failed',
+ } as const;
+
+ export interface AnnouncementDelivery {
+ readonly id: string;
+ /** Slack channel ID the message was sent to (e.g. C0123ABCD). */
+ readonly slack_channel_id: string;
+ /** Slack channel display name at send time (without the leading #). */
+ readonly slack_channel_name: string;
+ /** Per-channel delivery status: pending, sent, or failed.
+ *
+ * * `pending` - Pending
+ * * `sent` - Sent
+ * * `failed` - Failed */
+ readonly status: AnnouncementDeliveryStatusEnum;
+ /** Slack error code when delivery to this channel failed; empty otherwise. */
+ readonly error: string;
+ /** Timestamp ID of the posted Slack message, when delivery succeeded. */
+ readonly slack_message_ts: string;
+ /**
+ * When the message was delivered to this channel. Null until sent.
+ * @nullable
+ */
+ readonly sent_at: string | null;
+ }
+
+ export interface Announcement {
+ readonly id: string;
+ /** Short human-friendly identifier for the announcement. */
+ readonly short_id: string;
+ /** Message body to send, rendered as Slack mrkdwn. */
+ message: string;
+ /** Overall status: pending, sending, sent, partially_failed, or failed.
+ *
+ * * `pending` - Pending
+ * * `sending` - Sending
+ * * `sent` - Sent
+ * * `partially_failed` - Partially failed
+ * * `failed` - Failed */
+ readonly status: AnnouncementStatusEnum;
+ /** Number of channels this announcement targets. */
+ readonly total_channels: number;
+ /** Number of channels the message was successfully delivered to. */
+ readonly sent_count: number;
+ /** Number of channels delivery failed for. */
+ readonly failed_count: number;
+ /**
+ * When delivery finished (all channels resolved). Null while pending/sending.
+ * @nullable
+ */
+ readonly sent_at: string | null;
+ /** When the announcement was created. */
+ readonly created_at: string;
+ readonly created_by: UserBasic;
+ /** Per-channel delivery rows, one per selected Slack channel. */
+ readonly deliveries: readonly AnnouncementDelivery[];
+ /** Slack channel IDs to send to. Each must be a channel the SupportHog bot is a member of; names are resolved server-side. */
+ channels: string[];
+ }
+
+ export interface AnnouncementChannel {
+ /** Slack channel ID (e.g. C0123ABCD). */
+ id: string;
+ /** Slack channel display name (without the leading #). */
+ name: string;
+ /** Whether the SupportHog bot is a member of this channel. */
+ is_member: boolean;
+ /**
+ * Name of the customer account whose slack_channel_id points at this channel, or null if unmapped.
+ * @nullable
+ */
+ customer_name: string | null;
+ }
+
export interface AppContract {
/** User who created this app. */
created_by?: StreamlitAppUserInfo | null;
@@ -40634,6 +40737,15 @@ export namespace Schemas {
results: Annotation[];
}
+ export interface PaginatedAnnouncementList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: Announcement[];
+ }
+
export interface PaginatedAppContractList {
count: number;
/** @nullable */
@@ -72503,6 +72615,17 @@ export namespace Schemas {
search?: string;
};
+ export type AnnouncementsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type ApprovalPoliciesListParams = {
/**
* Number of results to return per page.
diff --git a/tach.toml b/tach.toml
index 3e9094901acd..6fc866c81bfc 100644
--- a/tach.toml
+++ b/tach.toml
@@ -693,6 +693,7 @@ path = "products.customer_analytics"
depends_on = [
"ee",
"posthog",
+ "products.conversations",
"products.notebooks",
"products.notifications",
"products.product_analytics",