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 announcement data model (#70358)

Christophe Eynius Tranberg3f064e2241cc
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 0361c521a495..a9a9c5a890a5 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -73,6 +73,8 @@ rules:
|Alert
|AlertConfiguration
|Annotation
+ |Announcement
+ |AnnouncementDelivery
|ApprovalPolicy
|BatchExport
|BatchExportBackfill
@@ -387,6 +389,8 @@ rules:
|Alert
|AlertConfiguration
|Annotation
+ |Announcement
+ |AnnouncementDelivery
|ApprovalPolicy
|BatchExport
|BatchExportBackfill
diff --git a/posthog/test/base.py b/posthog/test/base.py
index a3e421dc7db4..d33ccc3bc47a 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -1577,6 +1577,7 @@ class BaseTestMigrations(QueryMatchingTest):
old_apps = executor.loader.project_state(migrate_from).apps
# Reverse to the original migration
+ self._flush_deferred_constraint_triggers()
executor.migrate(migrate_from)
self.setUpBeforeMigration(old_apps)
@@ -1585,6 +1586,7 @@ class BaseTestMigrations(QueryMatchingTest):
executor = MigrationExecutor(connection)
executor.loader.build_graph() # reload.
+ self._flush_deferred_constraint_triggers()
if self.assert_snapshots:
self._execute_migration_with_snapshots(executor)
else:
@@ -1592,6 +1594,15 @@ class BaseTestMigrations(QueryMatchingTest):
self.apps = executor.loader.project_state(migrate_to).apps
+ @staticmethod
+ def _flush_deferred_constraint_triggers() -> None:
+ # Fixture inserts (e.g. BaseTest teams) queue deferred FK checks in the open test
+ # transaction; (un)applying a migration that adds or drops an FK on those tables then
+ # fails with "cannot ALTER TABLE ... because it has pending trigger events". Firing
+ # the checks now clears the queue.
+ with connection.cursor() as cursor:
+ cursor.execute("SET CONSTRAINTS ALL IMMEDIATE")
+
@snapshot_postgres_queries
def _execute_migration_with_snapshots(self, executor):
migrate_to = [(self.app, self.migrate_to)]
diff --git a/products/conversations/backend/api/slack_channels.py b/products/conversations/backend/api/slack_channels.py
index a11374d5721f..a3161eb043cd 100644
--- a/products/conversations/backend/api/slack_channels.py
+++ b/products/conversations/backend/api/slack_channels.py
@@ -1,6 +1,6 @@
-"""API endpoint for fetching Slack channels using a bot token."""
+"""API endpoint for fetching Slack channels using the SupportHog bot token."""
-from typing import Any, cast
+from typing import Any
import structlog
from rest_framework import status
@@ -8,13 +8,15 @@ from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
-from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
-from products.conversations.backend.support_slack import get_support_slack_bot_token
+from products.conversations.backend.support_slack_channels import (
+ SupportSlackChannelsUnavailable,
+ SupportSlackNotConfigured,
+ list_support_bot_channels,
+)
logger = structlog.get_logger(__name__)
-MAX_CHANNEL_PAGES = 100
class SlackChannelsView(APIView):
@@ -24,43 +26,22 @@ class SlackChannelsView(APIView):
def post(self, request: Request, *args: Any, **kwargs: Any) -> Response:
team = request.user.current_team # type: ignore[union-attr]
- bot_token = get_support_slack_bot_token(team) # type: ignore[arg-type]
- if not bot_token:
+ # members_only restricts to channels the bot belongs to (chat.postMessage returns
+ # not_in_channel otherwise); callers that only route replies can omit it.
+ members_only = bool(request.data.get("members_only"))
+
+ try:
+ resolved = list_support_bot_channels(team, members_only=members_only) # type: ignore[arg-type]
+ except SupportSlackNotConfigured:
return Response(
{"error": "Support Slack bot token is not configured"},
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)
-
- try:
- client = WebClient(token=bot_token)
- channels = []
- cursor = None
-
- # Paginate through all channels
- for _ in range(MAX_CHANNEL_PAGES):
- result = client.conversations_list(
- types="public_channel,private_channel",
- exclude_archived=True,
- limit=1000,
- cursor=cursor,
- )
- for c in cast(list[dict[str, Any]], result.get("channels") or []):
- channels.append({"id": c["id"], "name": c["name"]})
-
- response_metadata = result.get("response_metadata") or {}
- cursor = response_metadata.get("next_cursor", "")
- if not cursor:
- break
- else:
- logger.warning("slack_channels_fetch_too_many_pages", max_pages=MAX_CHANNEL_PAGES)
- return Response(
- {"error": "Too many channel pages returned by Slack"},
- status=status.HTTP_400_BAD_REQUEST,
- )
-
- # Sort by name for easier selection
- channels.sort(key=lambda c: c["name"].lower())
- return Response({"channels": channels})
+ except SupportSlackChannelsUnavailable:
+ return Response(
+ {"error": "Too many channel pages returned by Slack"},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
except SlackApiError as e:
logger.warning("slack_channels_fetch_failed", error=str(e))
return Response(
@@ -73,3 +54,7 @@ class SlackChannelsView(APIView):
{"error": "Failed to fetch channels"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
)
+
+ # Keep this endpoint's response shape ({id, name}); is_member is an internal detail the
+ # announcements picker consumes via its own action, not part of this contract.
+ return Response({"channels": [{"id": c["id"], "name": c["name"]} for c in resolved]})
diff --git a/products/conversations/backend/api/tests/test_slack_endpoints.py b/products/conversations/backend/api/tests/test_slack_endpoints.py
index 15f4b03d7ebe..c59a4108b25c 100644
--- a/products/conversations/backend/api/tests/test_slack_endpoints.py
+++ b/products/conversations/backend/api/tests/test_slack_endpoints.py
@@ -290,7 +290,7 @@ class TestSlackChannelsAPI(APIBaseTest):
response = APIClient().post("/api/conversations/v1/slack/channels", {})
assert response.status_code == 401
- @patch("products.conversations.backend.api.slack_channels.get_support_slack_bot_token")
+ @patch("products.conversations.backend.support_slack_channels.get_support_slack_bot_token")
def test_returns_503_when_support_bot_token_missing(self, mock_get_token: MagicMock):
mock_get_token.return_value = ""
@@ -298,8 +298,8 @@ class TestSlackChannelsAPI(APIBaseTest):
assert response.status_code == 503
- @patch("products.conversations.backend.api.slack_channels.WebClient")
- @patch("products.conversations.backend.api.slack_channels.get_support_slack_bot_token")
+ @patch("products.conversations.backend.support_slack_channels.WebClient")
+ @patch("products.conversations.backend.support_slack_channels.get_support_slack_bot_token")
def test_handles_slack_api_error(self, mock_get_token: MagicMock, mock_web_client: MagicMock):
mock_get_token.return_value = "xoxb-support-token"
client = MagicMock()
@@ -311,8 +311,8 @@ class TestSlackChannelsAPI(APIBaseTest):
assert response.status_code == 400
assert "Slack API error" in response.json()["error"]
- @patch("products.conversations.backend.api.slack_channels.WebClient")
- @patch("products.conversations.backend.api.slack_channels.get_support_slack_bot_token")
+ @patch("products.conversations.backend.support_slack_channels.WebClient")
+ @patch("products.conversations.backend.support_slack_channels.get_support_slack_bot_token")
def test_paginates_and_sorts_channels(self, mock_get_token: MagicMock, mock_web_client: MagicMock):
mock_get_token.return_value = "xoxb-support-token"
client = MagicMock()
@@ -336,9 +336,9 @@ class TestSlackChannelsAPI(APIBaseTest):
{"id": "C2", "name": "beta"},
]
- @patch("products.conversations.backend.api.slack_channels.MAX_CHANNEL_PAGES", 2)
- @patch("products.conversations.backend.api.slack_channels.WebClient")
- @patch("products.conversations.backend.api.slack_channels.get_support_slack_bot_token")
+ @patch("products.conversations.backend.support_slack_channels.MAX_CHANNEL_PAGES", 2)
+ @patch("products.conversations.backend.support_slack_channels.WebClient")
+ @patch("products.conversations.backend.support_slack_channels.get_support_slack_bot_token")
def test_returns_error_when_page_cap_exceeded(self, mock_support_config: MagicMock, mock_web_client: MagicMock):
mock_support_config.return_value = "xoxb-support-token"
client = MagicMock()
diff --git a/products/conversations/backend/facade/__init__.py b/products/conversations/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.py
new file mode 100644
index 000000000000..eccc8a7db9b0
--- /dev/null
+++ b/products/conversations/backend/facade/api.py
@@ -0,0 +1,108 @@
+"""
+Facade API for conversations.
+
+The only conversations surface other products may import. Wraps the SupportHog
+Slack integration behind contract types so callers never touch slack_sdk or the
+team's Slack credentials directly.
+"""
+
+from typing import Any
+
+from pydantic.dataclasses import dataclass
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.team import Team
+
+from products.conversations.backend.slack import get_slack_client
+from products.conversations.backend.support_slack_channels import (
+ SupportSlackChannelsUnavailable as SupportSlackChannelsUnavailable,
+ SupportSlackNotConfigured as SupportSlackNotConfigured,
+ list_support_bot_channels as _list_support_bot_channels,
+)
+
+
+class SupportMessageSendError(Exception):
+ """Slack rejected a SupportHog bot message.
+
+ ``code`` is the Slack error code (e.g. ``not_in_channel``); ``retry_after`` carries
+ the requested wait in seconds when Slack rate-limited the post, else None.
+ """
+
+ def __init__(self, code: str, retry_after: float | None = None) -> None:
+ super().__init__(code)
+ self.code = code
+ self.retry_after = retry_after
+
+
+@dataclass(frozen=True)
+class SupportChannel:
+ """A Slack channel visible to the SupportHog bot."""
+
+ id: str
+ name: str
+ is_member: bool
+
+
+def list_support_bot_channels(team_id: int, *, members_only: bool = False) -> list[SupportChannel]:
+ """Slack channels the SupportHog bot can see for this team, sorted by name.
+
+ With ``members_only=True``, only channels the bot belongs to (the ones it can
+ post to). Raises :class:`SupportSlackNotConfigured` when the bot isn't connected
+ and :class:`SupportSlackChannelsUnavailable` when the list can't be resolved.
+ """
+ try:
+ team = Team.objects.get(id=team_id)
+ except Team.DoesNotExist:
+ raise SupportSlackNotConfigured()
+ try:
+ channels = _list_support_bot_channels(team, members_only=members_only)
+ except (SupportSlackNotConfigured, SupportSlackChannelsUnavailable):
+ raise
+ except Exception:
+ # slack_sdk errors must not cross the boundary as slack_sdk types.
+ raise SupportSlackChannelsUnavailable()
+ return [SupportChannel(id=c["id"], name=c["name"], is_member=c["is_member"]) for c in channels]
+
+
+def post_support_message(team_id: int, channel_id: str, text: str) -> str:
+ """Post ``text`` to a Slack channel as the SupportHog bot, applying the team's
+ configured bot display name and icon. Returns the posted message's Slack ts.
+
+ Raises :class:`SupportSlackNotConfigured` when the bot isn't connected and
+ :class:`SupportMessageSendError` when the post fails.
+ """
+ try:
+ team = Team.objects.get(id=team_id)
+ client = get_slack_client(team)
+ except (Team.DoesNotExist, ValueError):
+ raise SupportSlackNotConfigured()
+
+ message_kwargs: dict[str, Any] = {}
+ support_settings = team.conversations_settings or {}
+ if bot_display_name := support_settings.get("slack_bot_display_name"):
+ message_kwargs["username"] = bot_display_name
+ if bot_icon_url := support_settings.get("slack_bot_icon_url"):
+ message_kwargs["icon_url"] = bot_icon_url
+
+ try:
+ response = client.chat_postMessage(channel=channel_id, text=text, **message_kwargs)
+ except SlackApiError as e:
+ slack_response = getattr(e, "response", None)
+ error_code = str((slack_response or {}).get("error", "unknown"))
+ retry_after = None
+ # Slack's error code is "ratelimited"; Retry-After is an HTTP header on
+ # SlackResponse.headers, not in the JSON body that .get() reads.
+ if error_code == "ratelimited":
+ raw_retry_after = (getattr(slack_response, "headers", None) or {}).get("Retry-After")
+ try:
+ retry_after = float(raw_retry_after) if raw_retry_after is not None else None
+ except (TypeError, ValueError):
+ retry_after = None
+ raise SupportMessageSendError(error_code, retry_after=retry_after)
+ except Exception:
+ # Transport failures (connection/timeout) must not cross the boundary as slack_sdk types.
+ raise SupportMessageSendError("transport_error")
+ ts = str(response.get("ts") or "")
+ if not ts:
+ raise SupportMessageSendError("missing_ts")
+ return ts
diff --git a/products/conversations/backend/support_slack_channels.py b/products/conversations/backend/support_slack_channels.py
new file mode 100644
index 000000000000..13c82210e620
--- /dev/null
+++ b/products/conversations/backend/support_slack_channels.py
@@ -0,0 +1,72 @@
+"""Shared listing of the SupportHog bot's Slack channels.
+
+Single source of truth for paginating ``conversations_list`` so both the support
+ticket-routing picker and the customer-analytics announcements picker (plus its
+server-side channel validation) share identical bot-membership semantics instead
+of duplicating WebClient logic.
+"""
+
+from typing import TYPE_CHECKING, Any, cast
+
+import structlog
+from slack_sdk import WebClient
+
+from products.conversations.backend.support_slack import get_support_slack_bot_token
+
+if TYPE_CHECKING:
+ from posthog.models.team.team import Team
+
+logger = structlog.get_logger(__name__)
+
+MAX_CHANNEL_PAGES = 100
+
+
+class SupportSlackNotConfigured(Exception):
+ """The team has no SupportHog bot token configured."""
+
+
+class SupportSlackChannelsUnavailable(Exception):
+ """The bot's channel list could not be resolved (Slack error or too many pages)."""
+
+
+def list_support_bot_channels(team: "Team", *, members_only: bool = False) -> list[dict[str, Any]]:
+ """Return the SupportHog bot's Slack channels as ``{id, name, is_member}`` dicts.
+
+ With ``members_only=True`` only channels the bot belongs to are returned — the bot
+ can only post to those (``chat.postMessage`` returns ``not_in_channel`` otherwise).
+ Raises ``SupportSlackNotConfigured`` when no bot token is set; ``slack_sdk``'s
+ ``SlackApiError`` propagates to the caller.
+ """
+ bot_token = get_support_slack_bot_token(team)
+ if not bot_token:
+ raise SupportSlackNotConfigured()
+
+ client = WebClient(token=bot_token)
+ channels: list[dict[str, Any]] = []
+ cursor = None
+
+ for _ in range(MAX_CHANNEL_PAGES):
+ result = client.conversations_list(
+ types="public_channel,private_channel",
+ exclude_archived=True,
+ limit=1000,
+ cursor=cursor,
+ )
+ for c in cast(list[dict[str, Any]], result.get("channels") or []):
+ # conversations_list reports is_member for public channels; private channels are
+ # only returned when the bot is already in them, so treat a returned private
+ # channel as a member channel when the flag is absent.
+ is_member = bool(c.get("is_member", c.get("is_private", False)))
+ if members_only and not is_member:
+ continue
+ channels.append({"id": c["id"], "name": c["name"], "is_member": is_member})
+
+ cursor = (result.get("response_metadata") or {}).get("next_cursor", "")
+ if not cursor:
+ break
+ else:
+ logger.warning("support_bot_channels_too_many_pages", max_pages=MAX_CHANNEL_PAGES, team_id=team.pk)
+ raise SupportSlackChannelsUnavailable()
+
+ channels.sort(key=lambda c: c["name"].lower())
+ return channels
diff --git a/products/conversations/backend/tests/__init__.py b/products/conversations/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/conversations/backend/tests/test_facade.py b/products/conversations/backend/tests/test_facade.py
new file mode 100644
index 000000000000..274b06ab138b
--- /dev/null
+++ b/products/conversations/backend/tests/test_facade.py
@@ -0,0 +1,76 @@
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from slack_sdk.errors import SlackApiError
+
+from products.conversations.backend.facade.api import SupportMessageSendError, post_support_message
+
+CLIENT = "products.conversations.backend.facade.api.get_slack_client"
+
+
+class FakeSlackResponse(dict):
+ # Mimics slack_sdk's SlackResponse: .get() reads the JSON body, HTTP headers are an attribute.
+ def __init__(self, data: dict, headers: dict | None = None) -> None:
+ super().__init__(data)
+ self.headers = headers or {}
+
+
+class TestPostSupportMessage(BaseTest):
+ @patch(CLIENT)
+ def test_applies_configured_bot_identity(self, mock_get_client: MagicMock):
+ self.team.conversations_settings = {
+ "slack_bot_display_name": "SupportBot",
+ "slack_bot_icon_url": "https://example.com/icon.png",
+ }
+ self.team.save()
+ client = MagicMock()
+ client.chat_postMessage.return_value = {"ts": "111.222"}
+ mock_get_client.return_value = client
+
+ ts = post_support_message(self.team.pk, "C1", "hello team")
+
+ assert ts == "111.222"
+ kwargs = client.chat_postMessage.call_args.kwargs
+ assert kwargs["channel"] == "C1"
+ assert kwargs["text"] == "hello team"
+ assert kwargs["username"] == "SupportBot"
+ assert kwargs["icon_url"] == "https://example.com/icon.png"
+
+ @parameterized.expand(
+ [
+ (
+ "slack_rate_limited",
+ SlackApiError(
+ message="x",
+ response=FakeSlackResponse({"error": "ratelimited"}, headers={"Retry-After": "7"}),
+ ),
+ None,
+ "ratelimited",
+ 7.0,
+ ),
+ ("transport_error", ConnectionError("boom"), None, "transport_error", None),
+ ("missing_ts", None, {"ok": True}, "missing_ts", None),
+ ]
+ )
+ @patch(CLIENT)
+ def test_translates_send_failures(
+ self,
+ _name: str,
+ side_effect: Exception | None,
+ return_value: dict | None,
+ expected_code: str,
+ expected_retry_after: float | None,
+ mock_get_client: MagicMock,
+ ):
+ client = MagicMock()
+ if side_effect is not None:
+ client.chat_postMessage.side_effect = side_effect
+ else:
+ client.chat_postMessage.return_value = return_value
+ mock_get_client.return_value = client
+
+ with self.assertRaises(SupportMessageSendError) as ctx:
+ post_support_message(self.team.pk, "C1", "hi")
+ assert ctx.exception.code == expected_code
+ assert ctx.exception.retry_after == expected_retry_after
diff --git a/products/customer_analytics/backend/migrations/0016_announcement.py b/products/customer_analytics/backend/migrations/0016_announcement.py
new file mode 100644
index 000000000000..49db2074a9ce
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0016_announcement.py
@@ -0,0 +1,187 @@
+# Generated by Django 5.2.14 on 2026-07-13 08:41
+
+import django.db.models.manager
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.utils
+import posthog.models.utils
+from posthog.migration_helpers import AddForeignKeyNotValid
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0015_person_target_custom_properties"),
+ ("posthog", "1251_alter_integration_kind"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="Announcement",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "short_id",
+ models.CharField(
+ blank=True,
+ default=posthog.utils.generate_short_id,
+ max_length=12,
+ ),
+ ),
+ ("message", models.TextField()),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("sending", "Sending"),
+ ("sent", "Sent"),
+ ("partially_failed", "Partially failed"),
+ ("failed", "Failed"),
+ ],
+ default="pending",
+ max_length=20,
+ ),
+ ),
+ ("total_channels", models.PositiveIntegerField(default=0)),
+ ("sent_count", models.PositiveIntegerField(default=0)),
+ ("failed_count", models.PositiveIntegerField(default=0)),
+ ("sent_at", models.DateTimeField(blank=True, null=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "abstract": False,
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.CreateModel(
+ name="AnnouncementDelivery",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("slack_channel_id", models.CharField(max_length=64)),
+ (
+ "slack_channel_name",
+ models.CharField(blank=True, default="", max_length=255),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("sent", "Sent"),
+ ("failed", "Failed"),
+ ],
+ default="pending",
+ max_length=20,
+ ),
+ ),
+ ("error", models.TextField(blank=True, default="")),
+ (
+ "slack_message_ts",
+ models.CharField(blank=True, default="", max_length=64),
+ ),
+ ("sent_at", models.DateTimeField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "announcement",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="deliveries",
+ to="customer_analytics.announcement",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "abstract": False,
+ "default_manager_name": "all_teams",
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.AddIndex(
+ model_name="announcement",
+ index=models.Index(fields=["team_id", "-created_at"], name="ca_announcement_team_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="announcementdelivery",
+ index=models.Index(fields=["announcement_id", "status"], name="ca_ann_deliv_status_idx"),
+ ),
+ migrations.AddConstraint(
+ model_name="announcementdelivery",
+ constraint=models.UniqueConstraint(
+ fields=("announcement", "slack_channel_id"),
+ name="ca_announcement_delivery_uniq",
+ ),
+ ),
+ AddForeignKeyNotValid(
+ model_name="announcement",
+ name="ca_announcement_team_id_fk",
+ column="team_id",
+ to_table="posthog_team",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="announcement",
+ name="ca_announcement_created_by_id_fk",
+ column="created_by_id",
+ to_table="posthog_user",
+ to_column="id",
+ ),
+ AddForeignKeyNotValid(
+ model_name="announcementdelivery",
+ name="ca_announcement_delivery_team_id_fk",
+ column="team_id",
+ to_table="posthog_team",
+ to_column="id",
+ ),
+ ]
diff --git a/products/customer_analytics/backend/migrations/0017_announcement_validate_fks.py b/products/customer_analytics/backend/migrations/0017_announcement_validate_fks.py
new file mode 100644
index 000000000000..1d35e8b97540
--- /dev/null
+++ b/products/customer_analytics/backend/migrations/0017_announcement_validate_fks.py
@@ -0,0 +1,15 @@
+from django.db import migrations
+
+from posthog.migration_helpers import ValidateForeignKey
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("customer_analytics", "0016_announcement"),
+ ]
+
+ operations = [
+ ValidateForeignKey(model_name="announcement", name="ca_announcement_team_id_fk"),
+ ValidateForeignKey(model_name="announcement", name="ca_announcement_created_by_id_fk"),
+ ValidateForeignKey(model_name="announcementdelivery", name="ca_announcement_delivery_team_id_fk"),
+ ]
diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txt
index ece1e7773f3e..f307d45e3f3d 100644
--- a/products/customer_analytics/backend/migrations/max_migration.txt
+++ b/products/customer_analytics/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0015_person_target_custom_properties
+0017_announcement_validate_fks
diff --git a/products/customer_analytics/backend/models/__init__.py b/products/customer_analytics/backend/models/__init__.py
index 5e2d07643131..981ce7238b38 100644
--- a/products/customer_analytics/backend/models/__init__.py
+++ b/products/customer_analytics/backend/models/__init__.py
@@ -1,4 +1,6 @@
from .account import Account
+from .announcement import Announcement
+from .announcement_delivery import AnnouncementDelivery
from .custom_property_definition import (
DATA_TYPE_BY_DISPLAY_TYPE,
CustomPropertyDefinition,
@@ -18,6 +20,8 @@ __all__ = [
"Account",
"AccountRelationship",
"AccountRelationshipDefinition",
+ "Announcement",
+ "AnnouncementDelivery",
"CustomPropertyDefinition",
"CustomPropertySource",
"CustomPropertyValue",
diff --git a/products/customer_analytics/backend/models/announcement.py b/products/customer_analytics/backend/models/announcement.py
new file mode 100644
index 000000000000..303cc0de8bab
--- /dev/null
+++ b/products/customer_analytics/backend/models/announcement.py
@@ -0,0 +1,40 @@
+from __future__ import annotations
+
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+from posthog.utils import generate_short_id
+
+
+class Announcement(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetaFields):
+ class Status(models.TextChoices):
+ PENDING = "pending", "Pending"
+ SENDING = "sending", "Sending"
+ SENT = "sent", "Sent"
+ PARTIALLY_FAILED = "partially_failed", "Partially failed"
+ FAILED = "failed", "Failed"
+
+ all_teams = models.Manager() # noqa: DJ012
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False
+ )
+
+ short_id = models.CharField(max_length=12, blank=True, default=generate_short_id)
+ message = models.TextField()
+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
+ total_channels = models.PositiveIntegerField(default=0)
+ sent_count = models.PositiveIntegerField(default=0)
+ failed_count = models.PositiveIntegerField(default=0)
+ sent_at = models.DateTimeField(null=True, blank=True)
+
+ class Meta(TeamScopedRootMixin.Meta):
+ default_manager_name = "all_teams"
+ indexes = [
+ models.Index(fields=["team_id", "-created_at"], name="ca_announcement_team_idx"),
+ ]
+
+ def __str__(self) -> str:
+ return f"Announcement({self.short_id}, status={self.status})"
diff --git a/products/customer_analytics/backend/models/announcement_delivery.py b/products/customer_analytics/backend/models/announcement_delivery.py
new file mode 100644
index 000000000000..0a0a27dee481
--- /dev/null
+++ b/products/customer_analytics/backend/models/announcement_delivery.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+from .announcement import Announcement
+
+
+class AnnouncementDelivery(TeamScopedRootMixin, UUIDModel):
+ class Status(models.TextChoices):
+ PENDING = "pending", "Pending"
+ SENT = "sent", "Sent"
+ FAILED = "failed", "Failed"
+
+ all_teams = models.Manager() # noqa: DJ012
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ announcement = models.ForeignKey(Announcement, on_delete=models.CASCADE, related_name="deliveries")
+ slack_channel_id = models.CharField(max_length=64)
+ slack_channel_name = models.CharField(max_length=255, blank=True, default="")
+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)
+ error = models.TextField(blank=True, default="")
+ slack_message_ts = models.CharField(max_length=64, blank=True, default="")
+ sent_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta(TeamScopedRootMixin.Meta):
+ default_manager_name = "all_teams"
+ constraints = [
+ models.UniqueConstraint(
+ fields=["announcement", "slack_channel_id"],
+ name="ca_announcement_delivery_uniq",
+ ),
+ ]
+ indexes = [
+ models.Index(fields=["announcement_id", "status"], name="ca_ann_deliv_status_idx"),
+ ]
+
+ def __str__(self) -> str:
+ return f"AnnouncementDelivery({self.slack_channel_id}, status={self.status})"
diff --git a/products/customer_analytics/backend/test/test_announcement.py b/products/customer_analytics/backend/test/test_announcement.py
new file mode 100644
index 000000000000..1c5de84fe045
--- /dev/null
+++ b/products/customer_analytics/backend/test/test_announcement.py
@@ -0,0 +1,52 @@
+import pytest
+from posthog.test.base import BaseTest
+
+from django.db.utils import IntegrityError
+
+from posthog.models import Team
+from posthog.models.scoping import team_scope
+from posthog.models.scoping.manager import TeamScopeError
+
+from products.customer_analytics.backend.models import Announcement, AnnouncementDelivery
+
+
+class TestAnnouncementModels(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.other_team = Team.objects.create(organization=self.organization, name="Other")
+
+ def test_objects_manager_is_fail_closed_and_team_scoped(self):
+ # Set up one announcement per team through the unscoped sibling.
+ Announcement.all_teams.create(team=self.team, message="ours")
+ Announcement.all_teams.create(team=self.other_team, message="theirs")
+
+ # `objects` (TeamScopedManager) refuses to read without a team context — this is the
+ # tenant-isolation guarantee that would silently break if the manager were swapped.
+ with pytest.raises(TeamScopeError):
+ list(Announcement.objects.all())
+
+ # Within a team context it returns only that team's rows...
+ with team_scope(self.team.id, canonical=True):
+ assert [a.message for a in Announcement.objects.all()] == ["ours"]
+
+ # ...while `all_teams` is the deliberate cross-team escape hatch.
+ assert Announcement.all_teams.count() == 2
+
+ def test_delivery_channel_is_unique_per_announcement(self):
+ announcement = Announcement.all_teams.create(team=self.team, message="hi", total_channels=1)
+ AnnouncementDelivery.all_teams.create(team=self.team, announcement=announcement, slack_channel_id="C1")
+
+ # Re-posting the same channel to the same announcement is rejected — this constraint is
+ # what makes the async send task idempotent (no double-post on retry).
+ with pytest.raises(IntegrityError):
+ AnnouncementDelivery.all_teams.create(team=self.team, announcement=announcement, slack_channel_id="C1")
+
+ def test_same_channel_allowed_across_announcements(self):
+ # The uniqueness is scoped to (announcement, channel), not the channel alone — the same
+ # channel must be reachable by later announcements.
+ first = Announcement.all_teams.create(team=self.team, message="a")
+ second = Announcement.all_teams.create(team=self.team, message="b")
+ AnnouncementDelivery.all_teams.create(team=self.team, announcement=first, slack_channel_id="C1")
+ AnnouncementDelivery.all_teams.create(team=self.team, announcement=second, slack_channel_id="C1")
+
+ assert AnnouncementDelivery.all_teams.filter(slack_channel_id="C1").count() == 2