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(messaging): set a recipient's topic preferences with a project secret key (#127204)

Michael Reichenbach3fb53f89e4c0
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 6a53ce15039c..44b600b22306 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -276,9 +276,9 @@ PROJECT_SECRET_API_KEY_ALLOWED_API_SCOPE_ACTION: list[tuple[APIScopeObject, APIS
# Both are needed together; every other replay_scanner and session_recording route stays PSAK-denied.
("replay_scanner", "write"),
("session_recording", "read"),
- # Lets a service send transactional email (`messaging_templates/:id/send/`, `messaging/send/email/`) and read a
- # send's status (`messaging/emails/:id/`). Every other hog_flow route stays PSAK-denied, because no other hog_flow
- # viewset lists PSAK actions.
+ # Lets a service send transactional email (`messaging_templates/:id/send/`, `messaging/send/email/`), read a
+ # send's status (`messaging/emails/:id/`) and set a recipient's topic preferences (`messaging/preferences/`).
+ # Every other hog_flow route stays PSAK-denied, because no other hog_flow viewset lists PSAK actions.
("hog_flow", "read"),
("hog_flow", "write"),
]
diff --git a/products/messaging/backend/facade/preferences.py b/products/messaging/backend/facade/preferences.py
index d0e179cfe11b..147a707d7846 100644
--- a/products/messaging/backend/facade/preferences.py
+++ b/products/messaging/backend/facade/preferences.py
@@ -103,6 +103,54 @@ def remove_opt_out(
return ChangedPreferences(preferences=_to_contract(row), created=created)
+class TopicsNotFound(Exception):
+ """The project has no live topic with these keys."""
+
+ def __init__(self, keys: list[str]) -> None:
+ super().__init__(", ".join(keys))
+ self.keys = keys
+
+
+@frozen
+class TopicPreferences:
+ identifier: str
+ # True when the recipient opted back in to all marketing, False when opted out, None when never set.
+ all_marketing: bool | None
+ # Topic key to True (opted in) or False (opted out), for every live topic with a stored choice.
+ topics: dict[str, bool]
+
+
+def set_preferences(
+ team_id: int, identifier: str, all_marketing: bool | None, topics: dict[str, bool]
+) -> TopicPreferences:
+ """Apply `all_marketing`, then each topic in order, as one write. Syncs to Customer.io after commit.
+
+ Raises TopicsNotFound, and changes nothing, when a key names no live topic of the project.
+ """
+ try:
+ stored = preferences_service.set_preferences(team_id, identifier, all_marketing, topics)
+ except preferences_service.TopicsNotFound as e:
+ raise TopicsNotFound(e.keys) from e
+ keys_by_id = preferences_service.topic_keys_by_id(team_id)
+ return TopicPreferences(
+ identifier=identifier,
+ all_marketing=_opted_in(stored.get(ALL_MESSAGE_PREFERENCE_CATEGORY_ID)),
+ topics={
+ keys_by_id[category_id]: opted_in
+ for category_id, value in stored.items()
+ if category_id in keys_by_id and (opted_in := _opted_in(value)) is not None
+ },
+ )
+
+
+def _opted_in(value: Any) -> bool | None:
+ if value == PreferenceStatus.OPTED_IN.value:
+ return True
+ if value == PreferenceStatus.OPTED_OUT.value:
+ return False
+ return None
+
+
def export_opt_outs_csv(team_id: int, category_key: str | None) -> Iterator[str]:
"""CSV rows of the opt-out list, in the format the CSV import reads back."""
try:
diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.py
index a3aa34b0cef0..448af4a0c235 100644
--- a/products/messaging/backend/presentation/views/message_templates.py
+++ b/products/messaging/backend/presentation/views/message_templates.py
@@ -642,7 +642,8 @@ class TransactionalEmailSendMixin:
def _require_workflow_editor(self, hog_flow_id: Any) -> None:
# The template's own access rules don't cover the workflow it sends through, which can carry its own.
- # A project secret API key has no user to check, and its scope already limits it to sending.
+ # A project secret API key has no user to check. Its scope limits it to sending and to setting recipient
+ # topic preferences.
if is_authenticated_via_project_secret_api_key(self.request):
return
try:
diff --git a/products/messaging/backend/presentation/views/topic_preferences.py b/products/messaging/backend/presentation/views/topic_preferences.py
new file mode 100644
index 000000000000..8d8e9e9e7c83
--- /dev/null
+++ b/products/messaging/backend/presentation/views/topic_preferences.py
@@ -0,0 +1,153 @@
+from typing import Any
+
+import structlog
+from drf_spectacular.utils import OpenApiResponse
+from rest_framework import exceptions, serializers, viewsets
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+from rest_framework.throttling import BaseThrottle
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import ProjectSecretAPIKeyAuthentication
+from posthog.event_usage import report_user_action
+from posthog.permissions import is_authenticated_via_project_secret_api_key
+from posthog.rate_limit import PersonalOrProjectSecretApiKeyRateThrottle, ProjectSecretApiKeyTeamRateThrottle
+
+from products.messaging.backend.facade.preferences import TopicsNotFound, set_preferences
+from products.messaging.backend.presentation.views.message_templates import require_transactional_email_api
+
+logger = structlog.get_logger(__name__)
+
+
+class SetPreferencesSerializer(serializers.Serializer):
+ # Workflows looks the recipient up by the untrimmed address, so a trimmed one would save consent elsewhere.
+ identifier = serializers.CharField(
+ max_length=512,
+ trim_whitespace=False,
+ help_text="The recipient's email address, exactly as Workflows sends to it. Matching is exact, so "
+ "`[email protected]` and `[email protected]` are two recipients.",
+ )
+ all_marketing = serializers.BooleanField(
+ required=False,
+ help_text="`false` opts the recipient out of every marketing topic. `true` lifts that opt-out. "
+ "Applied before `topics`.",
+ )
+ topics = serializers.DictField(
+ child=serializers.BooleanField(),
+ required=False,
+ help_text="Topic key to `false` to opt the recipient out of that topic, or `true` to opt them back in. "
+ "Opting back in to one marketing topic after an all-marketing opt-out lifts that opt-out, so `all_marketing` "
+ "becomes `true`, and keeps the other marketing topics opted out. "
+ "Topics you leave out keep their current choice.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ if "all_marketing" not in attrs and not attrs.get("topics"):
+ raise serializers.ValidationError("Set all_marketing, topics, or both.")
+ return attrs
+
+
+class TopicPreferencesSerializer(serializers.Serializer):
+ identifier = serializers.CharField(help_text="The recipient the preferences belong to.")
+ all_marketing = serializers.BooleanField(
+ allow_null=True,
+ help_text="`false` when the recipient opted out of all marketing, `true` when they opted back in, "
+ "`null` when they never chose.",
+ )
+ topics = serializers.DictField(
+ child=serializers.BooleanField(),
+ help_text="Topic key to `false` (opted out) or `true` (opted in), for every topic the recipient chose. "
+ "A topic without a choice is not listed.",
+ )
+
+
+class TopicPreferencesBurstThrottle(PersonalOrProjectSecretApiKeyRateThrottle):
+ scope = "messaging_preferences_burst"
+ rate = "600/minute"
+
+
+class TopicPreferencesSustainedThrottle(PersonalOrProjectSecretApiKeyRateThrottle):
+ scope = "messaging_preferences_sustained"
+ rate = "20000/hour"
+
+
+class TopicPreferencesTeamBurstThrottle(ProjectSecretApiKeyTeamRateThrottle):
+ scope = "messaging_preferences_psak_team_burst"
+ rate = "600/minute"
+
+
+class TopicPreferencesTeamSustainedThrottle(ProjectSecretApiKeyTeamRateThrottle):
+ scope = "messaging_preferences_psak_team_sustained"
+ rate = "20000/hour"
+
+
+class TopicPreferencesViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "hog_flow"
+ permission_classes = [IsAuthenticated]
+ authentication_classes = [ProjectSecretAPIKeyAuthentication]
+ psak_allowed_actions = ["create"]
+
+ def get_throttles(self) -> list[BaseThrottle]:
+ if not is_authenticated_via_project_secret_api_key(self.request):
+ return super().get_throttles()
+ return [
+ TopicPreferencesBurstThrottle(),
+ TopicPreferencesSustainedThrottle(),
+ TopicPreferencesTeamBurstThrottle(),
+ TopicPreferencesTeamSustainedThrottle(),
+ ]
+
+ @validated_request(
+ SetPreferencesSerializer,
+ responses={
+ 200: OpenApiResponse(response=TopicPreferencesSerializer),
+ 401: OpenApiResponse(description="The request has no project secret API key."),
+ 404: OpenApiResponse(
+ description="A topic key names no topic of this project, with the code `unknown_topic`. Nothing "
+ "changed."
+ ),
+ },
+ summary="Set a recipient's topic preferences",
+ description=(
+ "Opt one recipient out of topics, or back in, in one call. `all_marketing` applies first, then each "
+ "topic in order, and the whole change is saved at once. The same change twice ends the same, but a retry "
+ "that lands after a newer change undoes that change. Workflows sends skip a marketing topic the "
+ "recipient opted out of. Needs a project secret API key with the `hog_flow:write` scope, which can also "
+ "send transactional email."
+ ),
+ )
+ def create(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
+ # The routing mixin adds session and personal API key authentication to every route. Preferences change
+ # from the customer's server, so only its project secret API key can change them here.
+ if not is_authenticated_via_project_secret_api_key(request):
+ raise exceptions.NotAuthenticated()
+ require_transactional_email_api(self.team)
+ data = request.validated_data
+ topics: dict[str, bool] = data.get("topics") or {}
+ try:
+ result = set_preferences(self.team_id, data["identifier"], data.get("all_marketing"), topics)
+ except TopicsNotFound as e:
+ self._report(request, data, outcome="unknown_topic")
+ raise exceptions.NotFound(
+ f"This project has no topic with the key {', '.join(e.keys)}.", code="unknown_topic"
+ ) from None
+ self._report(request, data, outcome="applied")
+ return Response(TopicPreferencesSerializer(result).data)
+
+ def _report(self, request: ValidatedRequest, data: dict[str, Any], *, outcome: str) -> None:
+ try:
+ report_user_action(
+ request.user,
+ "messaging preferences api set",
+ {
+ "team_id": self.team_id,
+ "outcome": outcome,
+ "topic_count": len(data.get("topics") or {}),
+ "sets_all_marketing": "all_marketing" in data,
+ },
+ team=self.team,
+ organization=self.organization,
+ )
+ except Exception as e:
+ logger.warning("Failed to capture messaging preferences api event", error=str(e))
diff --git a/products/messaging/backend/routes.py b/products/messaging/backend/routes.py
index 4444f2e15305..97aa185f092e 100644
--- a/products/messaging/backend/routes.py
+++ b/products/messaging/backend/routes.py
@@ -14,6 +14,7 @@ from products.messaging.backend.presentation.views.supabase_auth_emails import (
SupabaseAuthEmailsViewSet,
SupabaseSendEmailHookView,
)
+from products.messaging.backend.presentation.views.topic_preferences import TopicPreferencesViewSet
from products.messaging.backend.presentation.views.transactional_email_status import MessagingEmailsViewSet
webhook_urlpatterns: list[URLPattern] = [
@@ -50,3 +51,6 @@ def register_routes(routers: RouterRegistry) -> None:
["team_id"],
)
routers.projects.register(r"messaging/emails", MessagingEmailsViewSet, "project_messaging_emails", ["team_id"])
+ routers.projects.register(
+ r"messaging/preferences", TopicPreferencesViewSet, "project_messaging_set_preferences", ["team_id"]
+ )
diff --git a/products/messaging/backend/services/preferences.py b/products/messaging/backend/services/preferences.py
index 0e4d1a06f49d..52891335e9a9 100644
--- a/products/messaging/backend/services/preferences.py
+++ b/products/messaging/backend/services/preferences.py
@@ -1,4 +1,4 @@
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Iterator, Mapping
from typing import Any
from django.db import transaction
@@ -86,6 +86,57 @@ def remove_opt_out(
return preference, created
+class TopicsNotFound(Exception):
+ def __init__(self, keys: list[str]) -> None:
+ super().__init__(", ".join(keys))
+ self.keys = keys
+
+
+def set_preferences(
+ team_id: int, identifier: str, all_marketing: bool | None, topics: Mapping[str, bool]
+) -> dict[str, Any]:
+ """Apply `all_marketing`, then each topic in order, in one locked write. Returns the stored preferences.
+
+ Raises TopicsNotFound before any write when a topic key names no live category of the team.
+ """
+ categories = {
+ category.key: category
+ for category in MessageCategory.objects.filter(team_id=team_id, key__in=list(topics), deleted=False)
+ }
+ unknown = [key for key in topics if key not in categories]
+ if unknown:
+ raise TopicsNotFound(unknown)
+
+ saved: dict[str, Any] = {}
+
+ def apply(stored: dict[str, Any]) -> dict[str, Any]:
+ preferences = dict(stored)
+ if all_marketing is not None:
+ preferences[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = _status(all_marketing)
+ for key, opted_in in topics.items():
+ if opted_in:
+ _lift_global_opt_out(team_id, preferences, categories[key])
+ preferences[str(categories[key].id)] = _status(opted_in)
+ saved.update(preferences)
+ return preferences
+
+ transition_preferences(team_id, identifier, apply, touch_updated_at=True)
+ _sync_after_commit(team_id, identifier)
+ # The written snapshot, not a reread that a lagging replica could answer with old preferences.
+ return saved
+
+
+def _status(opted_in: bool) -> str:
+ return (PreferenceStatus.OPTED_IN if opted_in else PreferenceStatus.OPTED_OUT).value
+
+
+def topic_keys_by_id(team_id: int) -> dict[str, str]:
+ return {
+ str(category_id): key
+ for category_id, key in MessageCategory.objects.filter(team_id=team_id, deleted=False).values_list("id", "key")
+ }
+
+
def _lift_global_opt_out(team_id: int, preferences: dict[str, Any], category: MessageCategory) -> None:
"""Clear a `$all` opt-out that would otherwise swallow a per-category resubscribe.
diff --git a/products/messaging/backend/tests/api/test_topic_preferences.py b/products/messaging/backend/tests/api/test_topic_preferences.py
new file mode 100644
index 000000000000..7b0bfd670eaf
--- /dev/null
+++ b/products/messaging/backend/tests/api/test_topic_preferences.py
@@ -0,0 +1,213 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.test import APIClient
+
+from posthog.models import ProjectSecretAPIKey
+from posthog.models.personal_api_key import hash_key_value
+from posthog.models.utils import generate_random_token_secret
+
+from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryType
+from products.messaging.backend.models.message_preferences import (
+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID,
+ MessageRecipientPreference,
+ PreferenceStatus,
+)
+
+OPTED_IN = PreferenceStatus.OPTED_IN.value
+OPTED_OUT = PreferenceStatus.OPTED_OUT.value
+
+
+@patch(
+ "products.messaging.backend.presentation.views.message_templates.posthoganalytics.feature_enabled",
+ return_value=True,
+)
+class TestTopicPreferences(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.newsletter = MessageCategory.objects.create(team=self.team, key="newsletter", name="Newsletter")
+ self.product_updates = MessageCategory.objects.create(
+ team=self.team, key="product-updates", name="Product updates"
+ )
+ self.psak = self._psak_client(["hog_flow:write"])
+
+ def _psak_client(self, scopes: list[str], team: Any = None) -> APIClient:
+ raw_token = generate_random_token_secret()
+ ProjectSecretAPIKey.objects.create(
+ team=team or self.team,
+ label=f"preferences {ProjectSecretAPIKey.objects.count()}",
+ secure_value=hash_key_value(raw_token),
+ scopes=scopes,
+ mask_value=f"{raw_token[:4]}...{raw_token[-4:]}",
+ )
+ client = APIClient()
+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw_token}")
+ return client
+
+ def _set(self, body: dict[str, Any], client: APIClient | None = None):
+ return (client or self.psak).post(f"/api/projects/{self.team.id}/messaging/preferences/", body, format="json")
+
+ def _stored(self, identifier: str = "[email protected]") -> dict[str, str]:
+ return MessageRecipientPreference.objects.get(team=self.team, identifier=identifier).preferences
+
+ def _seed(self, preferences: dict[str, str]) -> None:
+ MessageRecipientPreference.objects.create(
+ team=self.team, identifier="[email protected]", preferences=preferences
+ )
+
+ @parameterized.expand([("plain", "[email protected]"), ("surrounding_whitespace", " [email protected] ")])
+ def test_opts_a_recipient_out_of_one_topic(self, _flag: MagicMock, _name: str, identifier: str) -> None:
+ response = self._set({"identifier": identifier, "topics": {"newsletter": False}})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json() == {
+ "identifier": identifier,
+ "all_marketing": None,
+ "topics": {"newsletter": False},
+ }
+ assert self._stored(identifier) == {str(self.newsletter.id): OPTED_OUT}
+
+ def test_applies_all_marketing_before_the_topics(self, _flag: MagicMock) -> None:
+ response = self._set({"identifier": "[email protected]", "all_marketing": False, "topics": {"newsletter": True}})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["all_marketing"] is True
+ assert response.json()["topics"] == {"newsletter": True, "product-updates": False}
+
+ def test_opting_back_in_to_one_topic_keeps_the_others_out(self, _flag: MagicMock) -> None:
+ self._seed({ALL_MESSAGE_PREFERENCE_CATEGORY_ID: OPTED_OUT})
+
+ response = self._set({"identifier": "[email protected]", "topics": {"newsletter": True}})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert self._stored() == {
+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID: OPTED_IN,
+ str(self.newsletter.id): OPTED_IN,
+ str(self.product_updates.id): OPTED_OUT,
+ }
+
+ def test_keeps_choices_the_call_does_not_name(self, _flag: MagicMock) -> None:
+ self._seed({str(self.product_updates.id): OPTED_OUT})
+
+ response = self._set({"identifier": "[email protected]", "all_marketing": True})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["topics"] == {"product-updates": False}
+ assert self._stored() == {
+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID: OPTED_IN,
+ str(self.product_updates.id): OPTED_OUT,
+ }
+
+ @parameterized.expand(
+ [
+ ("unknown", lambda test: "does-not-exist"),
+ ("deleted", lambda test: test._deleted_topic().key),
+ ("other_team", lambda test: test._other_team_topic().key),
+ ]
+ )
+ def test_refuses_a_topic_the_project_does_not_have_and_changes_nothing(
+ self, _flag: MagicMock, _name: str, topic_key: Any
+ ) -> None:
+ self._seed({str(self.product_updates.id): OPTED_OUT})
+
+ response = self._set(
+ {
+ "identifier": "[email protected]",
+ "all_marketing": False,
+ "topics": {"product-updates": True, topic_key(self): False},
+ }
+ )
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()
+ assert response.json()["code"] == "unknown_topic"
+ assert topic_key(self) in response.json()["detail"]
+ assert self._stored() == {str(self.product_updates.id): OPTED_OUT}
+
+ def _deleted_topic(self) -> MessageCategory:
+ return MessageCategory.objects.get_or_create(
+ team=self.team, key="retired", defaults={"name": "Retired", "deleted": True}
+ )[0]
+
+ def _other_team_topic(self) -> MessageCategory:
+ other_team = self.organization.teams.create(name="Other")
+ return MessageCategory.objects.get_or_create(team=other_team, key="theirs", defaults={"name": "Theirs"})[0]
+
+ def test_refuses_a_call_that_changes_nothing(self, _flag: MagicMock) -> None:
+ response = self._set({"identifier": "[email protected]", "topics": {}})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert not MessageRecipientPreference.objects.filter(team=self.team).exists()
+
+ def test_opts_out_of_a_transactional_topic_like_any_other(self, _flag: MagicMock) -> None:
+ receipts = MessageCategory.objects.create(
+ team=self.team, key="receipts", name="Receipts", category_type=MessageCategoryType.TRANSACTIONAL
+ )
+
+ response = self._set({"identifier": "[email protected]", "topics": {"receipts": False}})
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert self._stored() == {str(receipts.id): OPTED_OUT}
+
+ @patch("products.messaging.backend.services.preferences.sync_preferences_to_customerio_task.delay")
+ def test_syncs_the_change_to_customerio_once_after_commit(self, sync: MagicMock, _flag: MagicMock) -> None:
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self._set(
+ {"identifier": "[email protected]", "all_marketing": False, "topics": {"newsletter": False}}
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ sync.assert_called_once_with(self.team.id, "[email protected]")
+
+ @parameterized.expand(
+ [
+ ("read_only_key", ["hog_flow:read"]),
+ ("unrelated_scope", ["feature_flag:read"]),
+ ]
+ )
+ def test_refuses_a_project_secret_key_without_hog_flow_write(
+ self, _flag: MagicMock, _name: str, scopes: list[str]
+ ) -> None:
+ response = self._set({"identifier": "[email protected]", "all_marketing": False}, self._psak_client(scopes))
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert not MessageRecipientPreference.objects.filter(team=self.team).exists()
+
+ def test_refuses_another_projects_key(self, _flag: MagicMock) -> None:
+ other_team = self.organization.teams.create(name="Other")
+
+ response = self._set(
+ {"identifier": "[email protected]", "all_marketing": False},
+ self._psak_client(["hog_flow:write"], team=other_team),
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()
+ assert not MessageRecipientPreference.objects.filter(team=self.team).exists()
+
+ def test_refuses_a_logged_in_user(self, _flag: MagicMock) -> None:
+ response = self._set({"identifier": "[email protected]", "all_marketing": False}, self.client)
+
+ assert response.status_code == status.HTTP_401_UNAUTHORIZED, response.json()
+
+ def test_is_not_found_while_the_email_api_flag_is_off(self, flag: MagicMock) -> None:
+ flag.return_value = False
+
+ response = self._set({"identifier": "[email protected]", "all_marketing": False})
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ assert not MessageRecipientPreference.objects.filter(team=self.team).exists()
+
+ @patch("posthog.event_usage.posthoganalytics.capture")
+ def test_reports_each_call_with_its_outcome(self, capture: MagicMock, _flag: MagicMock) -> None:
+ self._set({"identifier": "[email protected]", "topics": {"newsletter": False, "product-updates": True}})
+ self._set({"identifier": "[email protected]", "topics": {"nope": False}})
+
+ outcomes = [call.kwargs["properties"] for call in capture.call_args_list]
+ assert [call.kwargs["event"] for call in capture.call_args_list] == ["messaging preferences api set"] * 2
+ assert [(o["outcome"], o["topic_count"], o["sets_all_marketing"]) for o in outcomes] == [
+ ("applied", 2, False),
+ ("unknown_topic", 1, False),
+ ]
diff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.ts
index 398ca8486eed..f3b1b706ea79 100644
--- a/products/messaging/frontend/generated/api.schemas.ts
+++ b/products/messaging/frontend/generated/api.schemas.ts
@@ -49,6 +49,40 @@ export interface EmailStatusApi {
reason: string | null
}
+/**
+ * Topic key to `false` to opt the recipient out of that topic, or `true` to opt them back in. Opting back in to one marketing topic after an all-marketing opt-out lifts that opt-out, so `all_marketing` becomes `true`, and keeps the other marketing topics opted out. Topics you leave out keep their current choice.
+ */
+export type SetPreferencesApiTopics = { [key: string]: boolean }
+
+export interface SetPreferencesApi {
+ /**
+ * The recipient's email address, exactly as Workflows sends to it. Matching is exact, so `[email protected]` and `[email protected]` are two recipients.
+ * @maxLength 512
+ */
+ identifier: string
+ /** `false` opts the recipient out of every marketing topic. `true` lifts that opt-out. Applied before `topics`. */
+ all_marketing?: boolean
+ /** Topic key to `false` to opt the recipient out of that topic, or `true` to opt them back in. Opting back in to one marketing topic after an all-marketing opt-out lifts that opt-out, so `all_marketing` becomes `true`, and keeps the other marketing topics opted out. Topics you leave out keep their current choice. */
+ topics?: SetPreferencesApiTopics
+}
+
+/**
+ * Topic key to `false` (opted out) or `true` (opted in), for every topic the recipient chose. A topic without a choice is not listed.
+ */
+export type TopicPreferencesApiTopics = { [key: string]: boolean }
+
+export interface TopicPreferencesApi {
+ /** The recipient the preferences belong to. */
+ identifier: string
+ /**
+ * `false` when the recipient opted out of all marketing, `true` when they opted back in, `null` when they never chose.
+ * @nullable
+ */
+ all_marketing: boolean | null
+ /** Topic key to `false` (opted out) or `true` (opted in), for every topic the recipient chose. A topic without a choice is not listed. */
+ topics: TopicPreferencesApiTopics
+}
+
/**
* Data for the template's Liquid placeholders, available as `variables`. For example `{"reset_link": "https://..."}` fills `{{ variables.reset_link }}`.
*/
diff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.ts
index 6ba5296b4898..bc9ad372bd82 100644
--- a/products/messaging/frontend/generated/api.ts
+++ b/products/messaging/frontend/generated/api.ts
@@ -40,8 +40,10 @@ import type {
SendEmailApi,
SendTransactionalEmailApi,
SendTransactionalEmailResponseApi,
+ SetPreferencesApi,
StartProviderImportApi,
SupabaseAuthEmailSettingsApi,
+ TopicPreferencesApi,
WebhookUrlApi,
} from './api.schemas'
@@ -81,6 +83,27 @@ export const messagingEmailsRetrieve = async (
})
}
+export const getMessagingPreferencesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/messaging/preferences/`
+}
+
+/**
+ * Opt one recipient out of topics, or back in, in one call. `all_marketing` applies first, then each topic in order, and the whole change is saved at once. The same change twice ends the same, but a retry that lands after a newer change undoes that change. Workflows sends skip a marketing topic the recipient opted out of. Needs a project secret API key with the `hog_flow:write` scope, which can also send transactional email.
+ * @summary Set a recipient's topic preferences
+ */
+export const messagingPreferencesCreate = async (
+ projectId: string,
+ setPreferencesApi: SetPreferencesApi,
+ options?: RequestInit
+): Promise<TopicPreferencesApi> => {
+ return apiMutator<TopicPreferencesApi>(getMessagingPreferencesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(setPreferencesApi),
+ })
+}
+
export const getMessagingSendEmailCreateUrl = (projectId: string) => {
return `/api/projects/${projectId}/messaging/send/email/`
}
diff --git a/products/messaging/frontend/generated/api.zod.ts b/products/messaging/frontend/generated/api.zod.ts
index 96e55b0e08de..29d6189042c0 100644
--- a/products/messaging/frontend/generated/api.zod.ts
+++ b/products/messaging/frontend/generated/api.zod.ts
@@ -9,6 +9,33 @@
*/
import * as zod from 'zod'
+/**
+ * Opt one recipient out of topics, or back in, in one call. `all_marketing` applies first, then each topic in order, and the whole change is saved at once. The same change twice ends the same, but a retry that lands after a newer change undoes that change. Workflows sends skip a marketing topic the recipient opted out of. Needs a project secret API key with the `hog_flow:write` scope, which can also send transactional email.
+ * @summary Set a recipient's topic preferences
+ */
+export const messagingPreferencesCreateBodyIdentifierMax = 512
+
+export const MessagingPreferencesCreateBody = /* @__PURE__ */ zod.object({
+ identifier: zod
+ .string()
+ .max(messagingPreferencesCreateBodyIdentifierMax)
+ .describe(
+ "The recipient's email address, exactly as Workflows sends to it. Matching is exact, so `[email protected]` and `[email protected]` are two recipients."
+ ),
+ all_marketing: zod
+ .boolean()
+ .optional()
+ .describe(
+ '`false` opts the recipient out of every marketing topic. `true` lifts that opt-out. Applied before `topics`.'
+ ),
+ topics: zod
+ .record(zod.string(), zod.boolean())
+ .optional()
+ .describe(
+ 'Topic key to `false` to opt the recipient out of that topic, or `true` to opt them back in. Opting back in to one marketing topic after an all-marketing opt-out lifts that opt-out, so `all_marketing` becomes `true`, and keeps the other marketing topics opted out. Topics you leave out keep their current choice.'
+ ),
+})
+
/**
* Send one transactional email to one recipient from the template named in `template_id`. The template must be made transactional first. `message_data` fills the template's `{{ variables.* }}` placeholders. Transactional emails skip opt-outs and frequency caps. Send an `Idempotency-Key` header to retry safely without sending the email twice.
* @summary Send a transactional email
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 44eba663f0e9..4019e270b481 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -112141,6 +112141,23 @@ export namespace Schemas {
enabled: boolean;
}
+ /**
+ * Topic key to `false` to opt the recipient out of that topic, or `true` to opt them back in. Opting back in to one marketing topic after an all-marketing opt-out lifts that opt-out, so `all_marketing` becomes `true`, and keeps the other marketing topics opted out. Topics you leave out keep their current choice.
+ */
+ export type SetPreferencesTopics = {[key: string]: boolean};
+
+ export interface SetPreferences {
+ /**
+ * The recipient's email address, exactly as Workflows sends to it. Matching is exact, so `[email protected]` and `[email protected]` are two recipients.
+ * @maxLength 512
+ */
+ identifier: string;
+ /** `false` opts the recipient out of every marketing topic. `true` lifts that opt-out. Applied before `topics`. */
+ all_marketing?: boolean;
+ /** Topic key to `false` to opt the recipient out of that topic, or `true` to opt them back in. Opting back in to one marketing topic after an all-marketing opt-out lifts that opt-out, so `all_marketing` becomes `true`, and keeps the other marketing topics opted out. Topics you leave out keep their current choice. */
+ topics?: SetPreferencesTopics;
+ }
+
export interface SetTemplateEnabled {
/** Active catalog template to enable or disable for the team. */
template_id: string;
@@ -123532,6 +123549,23 @@ export namespace Schemas {
change: WoWChange | null;
}
+ /**
+ * Topic key to `false` (opted out) or `true` (opted in), for every topic the recipient chose. A topic without a choice is not listed.
+ */
+ export type TopicPreferencesTopics = {[key: string]: boolean};
+
+ export interface TopicPreferences {
+ /** The recipient the preferences belong to. */
+ identifier: string;
+ /**
+ * `false` when the recipient opted out of all marketing, `true` when they opted back in, `null` when they never chose.
+ * @nullable
+ */
+ all_marketing: boolean | null;
+ /** Topic key to `false` (opted out) or `true` (opted in), for every topic the recipient chose. A topic without a choice is not listed. */
+ topics: TopicPreferencesTopics;
+ }
+
export type TraceNodeIdsByAlias = {[key: string]: string};
export interface TracePerson {