:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(messaging): move the recipient preferences page into messaging (#113926)
Harley Alexander981b309dcc8e
diff --git a/posthog/urls.py b/posthog/urls.pyindex b860b06813b9..fd7020d63d43 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -50,6 +50,7 @@ from products.customer_analytics.backend.presentation.views.internal import (from products.early_access_features.backend.api import early_access_featuresfrom products.messaging.backend.api.customerio_webhook import CustomerIOWebhookViewfrom products.messaging.backend.api.push_subscriptions import push_subscriptions+from products.messaging.backend.presentation.views.recipient_preferences import preferences_page, update_preferencesfrom products.notebooks.backend.facade.sql_v2 import (notebook_sql_v2_callback,notebook_sql_v2_data_plane,@@ -82,14 +83,12 @@ from .views import (health,login_required,metrics_view,- preferences_page,preflight_check,render_query,replay_player_frame,robots_txt,security_txt,stats,- update_preferences,)# One view for both paths, so the provider is built once per process rather than once per route.diff --git a/posthog/views.py b/posthog/views.pyindex 655c91ff64e2..06a12318036d 100644--- a/posthog/views.py+++ b/posthog/views.py@@ -3,7 +3,7 @@ from dataclasses import dataclassfrom datetime import timedeltafrom functools import wrapsfrom html import escape-from typing import Any, Union+from typing import Unionfrom urllib.parse import parse_qs, urlencode, urlparse, urlunparsefrom django.apps import apps@@ -20,14 +20,12 @@ from django.shortcuts import redirect, renderfrom django.template import loaderfrom django.views.decorators.cache import never_cachefrom django.views.decorators.clickjacking import xframe_options_exempt-from django.views.decorators.csrf import csrf_exempt, csrf_protect, requires_csrf_token-from django.views.decorators.http import require_http_methods+from django.views.decorators.csrf import csrf_protect, requires_csrf_tokenimport structlogfrom opentelemetry import tracefrom prometheus_client import REGISTRY, CollectorRegistry, generate_latest, multiprocess-from posthog.api.capture import capture_internalfrom posthog.api.secret_revocation import NON_PERSONAL_SECRET_PREFIXESfrom posthog.auth import AUTH_BRAND_COOKIE, apply_auth_brand_cookie, normalize_auth_brandfrom posthog.cloud_utils import is_cloud@@ -35,7 +33,7 @@ from posthog.email import is_email_availablefrom posthog.exceptions_capture import capture_exceptionfrom posthog.health import is_clickhouse_connected, is_kafka_connectedfrom posthog.helpers.dev_login import is_dev_login_allowed-from posthog.models import Organization, Team, User+from posthog.models import Organization, Userfrom posthog.models.activity_logging.activity_log import Detail, log_activityfrom posthog.models.integration import SlackIntegrationfrom posthog.models.oauth import find_oauth_access_token, find_oauth_refresh_token@@ -47,7 +45,6 @@ from posthog.models.utils import (PROJECT_API_TOKEN_PREFIX,SECRET_API_TOKEN_PREFIX,)-from posthog.plugins.plugin_server_api import validate_messaging_preferences_tokenfrom posthog.redis import get_clientfrom posthog.utils import (get_available_timezones_with_offsets,@@ -64,16 +61,6 @@ from posthog.utils import (render_template,)-from products.messaging.backend.models.message_category import MessageCategory-from products.messaging.backend.models.message_preferences import (- ALL_MESSAGE_PREFERENCE_CATEGORY_ID,- EMAIL_TRACKING_PREFERENCE_ID,- MessageRecipientPreference,- PreferenceStatus,-)-from products.messaging.backend.services.customerio_sync_service import sync_preferences_to_customerio-from products.workflows.backend.facade.enums import EmailTrackingConsentMode-logger = structlog.get_logger(__name__)tracer = trace.get_tracer(__name__)@@ -522,280 +509,6 @@ def api_key_search_view(request: HttpRequest):return render(request, template_name="api_key_search/values.html", context=context, status=200)-def report_workflows_email_unsubscribed(team_id: int, identifier: str, category_ids: list[str], source: str) -> None:- """- Emit $workflows_email_unsubscribed engagement events into the customer's project.-- Mirrors the plugin-server's $workflows_email_* engagement events (email-tracking.service.ts),- gated on the same capture_workflows_engagement_events team flag. The unsubscribe token only- carries team_id + identifier, so this event is email-level: distinct_id is the recipient's- email, and no workflow/action id is available. Best-effort — never fails the unsubscribe flow.- """- try:- team = Team.objects.get(id=team_id)- if not team.workflows_config.capture_workflows_engagement_events:- return-- # The form POST accepts arbitrary category id strings; only emit for the team's real- # categories (or "$all") so a token bearer can't inject junk property values- known_category_ids: set[str] = set()- if any(category_id != ALL_MESSAGE_PREFERENCE_CATEGORY_ID for category_id in category_ids):- known_category_ids = {- str(category_id)- for category_id in MessageCategory.objects.filter(team_id=team_id, deleted=False).values_list(- "id", flat=True- )- }- except Exception as e:- capture_exception(e)- return-- # Each category is independently best-effort: one failed capture must not skip the rest- for category_id in category_ids:- if category_id != ALL_MESSAGE_PREFERENCE_CATEGORY_ID and category_id not in known_category_ids:- continue- properties: dict[str, Any] = {- "$email": identifier,- "category": category_id,- "source": source,- }- try:- result = capture_internal(- token=team.api_token,- event_name="$workflows_email_unsubscribed",- event_source="workflows_unsubscribe",- distinct_id=identifier,- properties=properties,- )- if not result.succeeded():- logger.error(- "workflows_email_unsubscribed_capture_failed",- team_id=team_id,- category=category_id,- error=result.error,- )- except Exception as e:- capture_exception(e)---def report_workflows_email_tracking_consent_updated(team_id: int, identifier: str, status: str) -> None:- """- Emit a $workflows_email_tracking_consent_updated engagement event when a recipient- changes their open/click tracking consent on the preferences page. Gated on the same- capture_workflows_engagement_events flag as the other $workflows_email_* events.- Best-effort — never fails the preferences flow.- """- try:- team = Team.objects.get(id=team_id)- if not team.workflows_config.capture_workflows_engagement_events:- return- result = capture_internal(- token=team.api_token,- event_name="$workflows_email_tracking_consent_updated",- event_source="workflows_preferences",- distinct_id=identifier,- properties={"$email": identifier, "status": status, "source": "preferences_page"},- )- if not result.succeeded():- logger.error(- "workflows_email_tracking_consent_capture_failed",- team_id=team_id,- error=result.error,- )- except Exception as e:- capture_exception(e)---@csrf_exempt-@require_http_methods(["GET", "POST"])-def preferences_page(request: HttpRequest, token: str) -> HttpResponse:- """Render the preferences page for a given recipient token"""- response = validate_messaging_preferences_token(token)- if response.status_code != 200:- error_msg = response.json().get("error", "Invalid recipient token")- return render(request, "message_preferences/error.html", {"error": error_msg}, status=400)-- data = response.json()- if not data.get("valid"):- return render(request, "message_preferences/error.html", {"error": "Invalid recipient token"}, status=400)-- team_id = data.get("team_id")- identifier = data.get("identifier")- if not team_id or not identifier:- return render(request, "message_preferences/error.html", {"error": "Invalid recipient"}, status=400)-- recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=identifier)- categories = MessageCategory.objects.filter(deleted=False, team=team_id, category_type="marketing").order_by("name")-- is_one_click_unsubscribe = (- request.GET.get("one_click_unsubscribe") == "1" or request.POST.get("one_click_unsubscribe") == "1"- )- if is_one_click_unsubscribe:- was_fully_opted_out = recipient.get_preference(ALL_MESSAGE_PREFERENCE_CATEGORY_ID) == PreferenceStatus.OPTED_OUT-- # If one-click unsubscribe, set all preferences to opted out- preferences_dict = {str(cat.id): PreferenceStatus.OPTED_OUT.value for cat in categories}-- # Also set the "$all" preference- preferences_dict[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_OUT.value-- # Unsubscribing is about which emails arrive, not how they're measured — a stored- # tracking-consent answer must survive the wholesale rebuild- tracking_pref = (recipient.preferences or {}).get(EMAIL_TRACKING_PREFERENCE_ID)- if tracking_pref is not None:- preferences_dict[EMAIL_TRACKING_PREFERENCE_ID] = tracking_pref-- recipient.preferences = preferences_dict- recipient.save(update_fields=["preferences"])-- sync_preferences_to_customerio(team_id, identifier, preferences_dict)-- # Only a genuine transition emits, so token replays and scanner prefetches don't inflate events- if not was_fully_opted_out:- report_workflows_email_unsubscribed(team_id, identifier, [ALL_MESSAGE_PREFERENCE_CATEGORY_ID], "one_click")-- if request.method == "POST":- return HttpResponse(status=200)-- # Only fetch active categories and their preferences- preferences = recipient.get_all_preferences() if recipient else {}-- categories_templating = [- {- "id": cat.id,- "name": cat.name,- "description": cat.public_description,- "status": preferences.get(str(cat.id), PreferenceStatus.NO_PREFERENCE),- }- for cat in categories- ]-- # Only surface the tracking-consent toggle when the team actually enforces consent —- # in "off" mode a stored preference would have no effect on sends- tracking_consent_mode = Team.objects.get(id=team_id).workflows_config.email_tracking_consent_mode- tracking_status = preferences.get(EMAIL_TRACKING_PREFERENCE_ID, PreferenceStatus.NO_PREFERENCE)-- context = {- "recipient": recipient,- "categories": [- *categories_templating,- {- "id": ALL_MESSAGE_PREFERENCE_CATEGORY_ID,- "name": "All marketing communications",- "description": "Unsubscribing here overrides individual preferences.",- "status": preferences.get(ALL_MESSAGE_PREFERENCE_CATEGORY_ID, PreferenceStatus.NO_PREFERENCE),- },- ],- "token": token,- "email_tracking_consent_enabled": tracking_consent_mode != EmailTrackingConsentMode.OFF,- # No stored answer falls back to the mode's default: tracked under opt-out, untracked under opt-in- "email_tracking_allowed": (- tracking_status == PreferenceStatus.OPTED_IN- if tracking_consent_mode == EmailTrackingConsentMode.OPT_IN- else tracking_status != PreferenceStatus.OPTED_OUT- ),- }-- return render(- request,- "message_preferences/one_click_unsubscribe_success.html"- if is_one_click_unsubscribe- else "message_preferences/preferences.html",- context,- )---@csrf_protect-@require_http_methods(["POST"])-def update_preferences(request: HttpRequest) -> JsonResponse:- """Update preferences for a recipient"""- token = request.POST.get("token")- if not token:- return JsonResponse({"error": "Missing token"}, status=400)-- response = validate_messaging_preferences_token(token)- if response.status_code != 200:- error_msg = response.json().get("error", "Invalid recipient token")- return JsonResponse({"error": error_msg}, status=400)-- data = response.json()- if not data.get("valid"):- return JsonResponse({"error": "Invalid recipient token"}, status=400)- team_id = data.get("team_id")- identifier = data.get("identifier")- if not team_id or not identifier:- return JsonResponse({"error": "Invalid recipient"}, status=400)-- recipient = None-- try:- recipient = MessageRecipientPreference.objects.get(team_id=team_id, identifier=identifier)- except MessageRecipientPreference.DoesNotExist:- recipient = MessageRecipientPreference(team_id=team_id, identifier=identifier)-- try:- prior_preferences = dict(recipient.preferences or {})- preferences = request.POST.getlist("preferences[]")- # Convert to dict of category_id: status- preferences_dict = {}-- for pref in preferences:- category_id, opted_in = pref.split(":")-- if opted_in not in ["true", "false"]:- return JsonResponse({"error": "Preference values must be 'true' or 'false'"}, status=400)-- status = PreferenceStatus.OPTED_IN if opted_in == "true" else PreferenceStatus.OPTED_OUT- preferences_dict[category_id] = status.value-- # $email_tracking is a measurement consent, not a subscription — it must neither- # block nor trigger the "unsubscribed from everything" $all computation- subscription_prefs = {k: v for k, v in preferences_dict.items() if k != EMAIL_TRACKING_PREFERENCE_ID}-- # If all preferences are opted out, add the "$all" preference- if subscription_prefs and all(v == PreferenceStatus.OPTED_OUT.value for v in subscription_prefs.values()):- preferences_dict[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_OUT.value-- # A save that doesn't include the tracking toggle (e.g. consent mode is off) must- # not erase a stored consent answer in the wholesale rebuild- if EMAIL_TRACKING_PREFERENCE_ID not in preferences_dict and EMAIL_TRACKING_PREFERENCE_ID in prior_preferences:- preferences_dict[EMAIL_TRACKING_PREFERENCE_ID] = prior_preferences[EMAIL_TRACKING_PREFERENCE_ID]-- # A tracking-only save (no category toggles rendered, e.g. a team without marketing- # categories) must not rebuild subscription state - it would drop a stored $all opt-out- if not subscription_prefs:- preferences_dict = {**prior_preferences, **preferences_dict}-- # Update all preferences with a single DB write- recipient.preferences = preferences_dict- recipient.save()-- sync_preferences_to_customerio(team_id, identifier, preferences_dict)-- # Only genuine opt-out transitions count, so repeated saves don't double-emit- newly_opted_out = [- category_id- for category_id, status in preferences_dict.items()- if category_id != EMAIL_TRACKING_PREFERENCE_ID- and status == PreferenceStatus.OPTED_OUT.value- and prior_preferences.get(category_id) != PreferenceStatus.OPTED_OUT.value- ]- if newly_opted_out:- report_workflows_email_unsubscribed(team_id, identifier, newly_opted_out, "preferences_page")-- new_tracking_consent = preferences_dict.get(EMAIL_TRACKING_PREFERENCE_ID)- if new_tracking_consent is not None and new_tracking_consent != prior_preferences.get(- EMAIL_TRACKING_PREFERENCE_ID- ):- report_workflows_email_tracking_consent_updated(team_id, identifier, new_tracking_consent)-- return JsonResponse({"success": True})-- except Exception as e:- capture_exception(e)- return JsonResponse({"error": "Failed to update preferences"}, status=400)--@xframe_options_exempt@never_cachedef replay_player_frame(request: HttpRequest) -> HttpResponse:diff --git a/products/messaging/backend/api/test/test_message_preferences.py b/products/messaging/backend/api/test/test_message_preferences.pyindex 4a8517be8204..b7587018cb62 100644--- a/products/messaging/backend/api/test/test_message_preferences.py+++ b/products/messaging/backend/api/test/test_message_preferences.py@@ -57,7 +57,7 @@ class TestMessagePreferencesViews(BaseTest):self._token_patch.stop()super().tearDown()- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_preferences_page_valid_token(self, mock_validate_messaging_preferences_token):mock_validate_messaging_preferences_token.return_value = mock_response(200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}@@ -79,7 +79,7 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(categories[2]["name"], "All marketing communications")self.assertEqual(categories[2]["id"], ALL_MESSAGE_PREFERENCE_CATEGORY_ID)- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_preferences_page_one_click_unsubscribe_get(self, mock_validate_messaging_preferences_token):mock_validate_messaging_preferences_token.return_value = mock_response(200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}@@ -99,7 +99,7 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(prefs[str(self.category2.id)], PreferenceStatus.OPTED_OUT)self.assertEqual(prefs[ALL_MESSAGE_PREFERENCE_CATEGORY_ID], PreferenceStatus.OPTED_OUT)- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_preferences_page_one_click_unsubscribe_post(self, mock_validate_messaging_preferences_token):mock_validate_messaging_preferences_token.return_value = mock_response(200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}@@ -118,14 +118,14 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(prefs[str(self.category2.id)], PreferenceStatus.OPTED_OUT)self.assertEqual(prefs[ALL_MESSAGE_PREFERENCE_CATEGORY_ID], PreferenceStatus.OPTED_OUT)- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_preferences_page_invalid_token(self, mock_validate_messaging_preferences_token):mock_validate_messaging_preferences_token.return_value = mock_response(400, {"error": "Invalid token"})response = self.client.get(reverse("message_preferences", kwargs={"token": "invalid-token"}))self.assertEqual(response.status_code, 400)self.assertTemplateUsed(response, "message_preferences/error.html")- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_update_preferences_valid(self, mock_validate_messaging_preferences_token):data = {"token": self.token, "preferences[]": [f"{self.category.id}:true", f"{self.category2.id}:false"]}mock_validate_messaging_preferences_token.return_value = mock_response(@@ -141,7 +141,7 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(prefs[str(self.category.id)], PreferenceStatus.OPTED_IN)self.assertEqual(prefs[str(self.category2.id)], PreferenceStatus.OPTED_OUT)- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_update_preferences_all_opted_out_adds_all(self, mock_validate_messaging_preferences_token):data = {"token": self.token, "preferences[]": [f"{self.category.id}:false", f"{self.category2.id}:false"]}mock_validate_messaging_preferences_token.return_value = mock_response(@@ -171,7 +171,7 @@ class TestMessagePreferencesViews(BaseTest):("invalid-token", mock_response(200, {"valid": False})),])- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_update_preferences_invalid_token(self, token, mock_response_value, mock_validate_messaging_preferences_token):@@ -182,7 +182,7 @@ class TestMessagePreferencesViews(BaseTest):self.assertIn("error", json.loads(response.content))@parameterized.expand(["invalid", "TRUE", "", "1"])- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_update_preferences_invalid_preference_format(self, invalid_value, mock_validate_messaging_preferences_token):@@ -199,8 +199,8 @@ class TestMessagePreferencesViews(BaseTest):config.capture_workflows_engagement_events = Trueconfig.save()- @patch("posthog.views.capture_internal")- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.capture_internal")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_one_click_unsubscribe_emits_unsubscribed_event(self, mock_validate_messaging_preferences_token, mock_capture_internal):@@ -236,8 +236,8 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(response.status_code, 200)mock_capture_internal.assert_not_called()- @patch("posthog.views.capture_internal")- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.capture_internal")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_update_preferences_emits_only_for_newly_opted_out(self, mock_validate_messaging_preferences_token, mock_capture_internal):@@ -272,8 +272,8 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(call.kwargs["properties"]["source"], "preferences_page")@parameterized.expand(["one_click", "preferences_form"])- @patch("posthog.views.capture_internal")- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.capture_internal")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_no_unsubscribed_event_when_flag_off(self, code_path, mock_validate_messaging_preferences_token, mock_capture_internal):@@ -310,7 +310,7 @@ class TestMessagePreferencesViews(BaseTest):("opt_in", PreferenceStatus.OPTED_IN, True, True),])- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_preferences_page_tracking_section_per_mode(self, mode, stored_preference, section_shown, toggle_checked, mock_validate_messaging_preferences_token):@@ -332,7 +332,7 @@ class TestMessagePreferencesViews(BaseTest):else:self.assertNotContains(response, "Open and click tracking")- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_tracking_opt_out_alone_does_not_unsubscribe(self, mock_validate_messaging_preferences_token):mock_validate_messaging_preferences_token.return_value = mock_response(200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}@@ -349,7 +349,7 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(prefs[EMAIL_TRACKING_PREFERENCE_ID], PreferenceStatus.OPTED_OUT)self.assertNotIn(ALL_MESSAGE_PREFERENCE_CATEGORY_ID, prefs)- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_tracking_only_save_preserves_stored_all_opt_out(self, mock_validate_messaging_preferences_token):# A tracking-only payload (no category toggles rendered) must not rebuild# subscription state and silently resubscribe a one-click-unsubscribed recipient@@ -370,7 +370,7 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(prefs[ALL_MESSAGE_PREFERENCE_CATEGORY_ID], PreferenceStatus.OPTED_OUT)self.assertEqual(prefs[EMAIL_TRACKING_PREFERENCE_ID], PreferenceStatus.OPTED_OUT)- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_tracking_opt_in_does_not_block_all_unsubscribe(self, mock_validate_messaging_preferences_token):mock_validate_messaging_preferences_token.return_value = mock_response(200, {"valid": True, "team_id": self.team.id, "identifier": self.recipient.identifier}@@ -395,7 +395,7 @@ class TestMessagePreferencesViews(BaseTest):self.assertEqual(prefs[EMAIL_TRACKING_PREFERENCE_ID], PreferenceStatus.OPTED_IN)@parameterized.expand(["one_click", "preferences_form"])- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_stored_tracking_consent_survives_writes_that_omit_it(self, code_path, mock_validate_messaging_preferences_token):@@ -422,8 +422,8 @@ class TestMessagePreferencesViews(BaseTest):self.recipient.refresh_from_db()self.assertEqual(self.recipient.get_all_preferences()[EMAIL_TRACKING_PREFERENCE_ID], PreferenceStatus.OPTED_OUT)- @patch("posthog.views.capture_internal")- @patch("posthog.views.validate_messaging_preferences_token")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.capture_internal")+ @patch("products.messaging.backend.presentation.views.recipient_preferences.validate_messaging_preferences_token")def test_tracking_consent_change_emits_event_only_on_transition(self, mock_validate_messaging_preferences_token, mock_capture_internal):diff --git a/products/messaging/backend/presentation/views/__init__.py b/products/messaging/backend/presentation/views/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/messaging/backend/presentation/views/recipient_preferences.py b/products/messaging/backend/presentation/views/recipient_preferences.pynew file mode 100644index 000000000000..d686149325a1--- /dev/null+++ b/products/messaging/backend/presentation/views/recipient_preferences.py@@ -0,0 +1,299 @@+from typing import Any++from django.http import HttpRequest, HttpResponse, JsonResponse+from django.shortcuts import render+from django.views.decorators.csrf import csrf_exempt, csrf_protect+from django.views.decorators.http import require_http_methods++import structlog++from posthog.api.capture import capture_internal+from posthog.exceptions_capture import capture_exception+from posthog.models import Team+from posthog.plugins.plugin_server_api import validate_messaging_preferences_token++from products.messaging.backend.models.message_category import MessageCategory+from products.messaging.backend.models.message_preferences import (+ ALL_MESSAGE_PREFERENCE_CATEGORY_ID,+ EMAIL_TRACKING_PREFERENCE_ID,+ MessageRecipientPreference,+ PreferenceStatus,+)+from products.messaging.backend.services.customerio_sync_service import sync_preferences_to_customerio+from products.workflows.backend.facade.enums import EmailTrackingConsentMode++logger = structlog.get_logger(__name__)+++def report_workflows_email_unsubscribed(team_id: int, identifier: str, category_ids: list[str], source: str) -> None:+ """+ Emit $workflows_email_unsubscribed engagement events into the customer's project.++ Mirrors the plugin-server's $workflows_email_* engagement events (email-tracking.service.ts),+ gated on the same capture_workflows_engagement_events team flag. The unsubscribe token only+ carries team_id + identifier, so this event is email-level: distinct_id is the recipient's+ email, and no workflow/action id is available. Best-effort — never fails the unsubscribe flow.+ """+ try:+ team = Team.objects.get(id=team_id)+ if not team.workflows_config.capture_workflows_engagement_events:+ return++ # The form POST accepts arbitrary category id strings; only emit for the team's real+ # categories (or "$all") so a token bearer can't inject junk property values+ known_category_ids: set[str] = set()+ if any(category_id != ALL_MESSAGE_PREFERENCE_CATEGORY_ID for category_id in category_ids):+ known_category_ids = {+ str(category_id)+ for category_id in MessageCategory.objects.filter(team_id=team_id, deleted=False).values_list(+ "id", flat=True+ )+ }+ except Exception as e:+ capture_exception(e)+ return++ # Each category is independently best-effort: one failed capture must not skip the rest+ for category_id in category_ids:+ if category_id != ALL_MESSAGE_PREFERENCE_CATEGORY_ID and category_id not in known_category_ids:+ continue+ properties: dict[str, Any] = {+ "$email": identifier,+ "category": category_id,+ "source": source,+ }+ try:+ result = capture_internal(+ token=team.api_token,+ event_name="$workflows_email_unsubscribed",+ event_source="workflows_unsubscribe",+ distinct_id=identifier,+ properties=properties,+ )+ if not result.succeeded():+ logger.error(+ "workflows_email_unsubscribed_capture_failed",+ team_id=team_id,+ category=category_id,+ error=result.error,+ )+ except Exception as e:+ capture_exception(e)+++def report_workflows_email_tracking_consent_updated(team_id: int, identifier: str, status: str) -> None:+ """+ Emit a $workflows_email_tracking_consent_updated engagement event when a recipient+ changes their open/click tracking consent on the preferences page. Gated on the same+ capture_workflows_engagement_events flag as the other $workflows_email_* events.+ Best-effort — never fails the preferences flow.+ """+ try:+ team = Team.objects.get(id=team_id)+ if not team.workflows_config.capture_workflows_engagement_events:+ return+ result = capture_internal(+ token=team.api_token,+ event_name="$workflows_email_tracking_consent_updated",+ event_source="workflows_preferences",+ distinct_id=identifier,+ properties={"$email": identifier, "status": status, "source": "preferences_page"},+ )+ if not result.succeeded():+ logger.error(+ "workflows_email_tracking_consent_capture_failed",+ team_id=team_id,+ error=result.error,+ )+ except Exception as e:+ capture_exception(e)+++@csrf_exempt+@require_http_methods(["GET", "POST"])+def preferences_page(request: HttpRequest, token: str) -> HttpResponse:+ """Render the preferences page for a given recipient token"""+ response = validate_messaging_preferences_token(token)+ if response.status_code != 200:+ error_msg = response.json().get("error", "Invalid recipient token")+ return render(request, "message_preferences/error.html", {"error": error_msg}, status=400)++ data = response.json()+ if not data.get("valid"):+ return render(request, "message_preferences/error.html", {"error": "Invalid recipient token"}, status=400)++ team_id = data.get("team_id")+ identifier = data.get("identifier")+ if not team_id or not identifier:+ return render(request, "message_preferences/error.html", {"error": "Invalid recipient"}, status=400)++ recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=identifier)+ categories = MessageCategory.objects.filter(deleted=False, team=team_id, category_type="marketing").order_by("name")++ is_one_click_unsubscribe = (+ request.GET.get("one_click_unsubscribe") == "1" or request.POST.get("one_click_unsubscribe") == "1"+ )+ if is_one_click_unsubscribe:+ was_fully_opted_out = recipient.get_preference(ALL_MESSAGE_PREFERENCE_CATEGORY_ID) == PreferenceStatus.OPTED_OUT++ # If one-click unsubscribe, set all preferences to opted out+ preferences_dict = {str(cat.id): PreferenceStatus.OPTED_OUT.value for cat in categories}++ # Also set the "$all" preference+ preferences_dict[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_OUT.value++ # Unsubscribing is about which emails arrive, not how they're measured — a stored+ # tracking-consent answer must survive the wholesale rebuild+ tracking_pref = (recipient.preferences or {}).get(EMAIL_TRACKING_PREFERENCE_ID)+ if tracking_pref is not None:+ preferences_dict[EMAIL_TRACKING_PREFERENCE_ID] = tracking_pref++ recipient.preferences = preferences_dict+ recipient.save(update_fields=["preferences"])++ sync_preferences_to_customerio(team_id, identifier, preferences_dict)++ # Only a genuine transition emits, so token replays and scanner prefetches don't inflate events+ if not was_fully_opted_out:+ report_workflows_email_unsubscribed(team_id, identifier, [ALL_MESSAGE_PREFERENCE_CATEGORY_ID], "one_click")++ if request.method == "POST":+ return HttpResponse(status=200)++ # Only fetch active categories and their preferences+ preferences = recipient.get_all_preferences() if recipient else {}++ categories_templating = [+ {+ "id": cat.id,+ "name": cat.name,+ "description": cat.public_description,+ "status": preferences.get(str(cat.id), PreferenceStatus.NO_PREFERENCE),+ }+ for cat in categories+ ]++ # Only surface the tracking-consent toggle when the team actually enforces consent —+ # in "off" mode a stored preference would have no effect on sends+ tracking_consent_mode = Team.objects.get(id=team_id).workflows_config.email_tracking_consent_mode+ tracking_status = preferences.get(EMAIL_TRACKING_PREFERENCE_ID, PreferenceStatus.NO_PREFERENCE)++ context = {+ "recipient": recipient,+ "categories": [+ *categories_templating,+ {+ "id": ALL_MESSAGE_PREFERENCE_CATEGORY_ID,+ "name": "All marketing communications",+ "description": "Unsubscribing here overrides individual preferences.",+ "status": preferences.get(ALL_MESSAGE_PREFERENCE_CATEGORY_ID, PreferenceStatus.NO_PREFERENCE),+ },+ ],+ "token": token,+ "email_tracking_consent_enabled": tracking_consent_mode != EmailTrackingConsentMode.OFF,+ # No stored answer falls back to the mode's default: tracked under opt-out, untracked under opt-in+ "email_tracking_allowed": (+ tracking_status == PreferenceStatus.OPTED_IN+ if tracking_consent_mode == EmailTrackingConsentMode.OPT_IN+ else tracking_status != PreferenceStatus.OPTED_OUT+ ),+ }++ return render(+ request,+ "message_preferences/one_click_unsubscribe_success.html"+ if is_one_click_unsubscribe+ else "message_preferences/preferences.html",+ context,+ )+++@csrf_protect+@require_http_methods(["POST"])+def update_preferences(request: HttpRequest) -> JsonResponse:+ """Update preferences for a recipient"""+ token = request.POST.get("token")+ if not token:+ return JsonResponse({"error": "Missing token"}, status=400)++ response = validate_messaging_preferences_token(token)+ if response.status_code != 200:+ error_msg = response.json().get("error", "Invalid recipient token")+ return JsonResponse({"error": error_msg}, status=400)++ data = response.json()+ if not data.get("valid"):+ return JsonResponse({"error": "Invalid recipient token"}, status=400)+ team_id = data.get("team_id")+ identifier = data.get("identifier")+ if not team_id or not identifier:+ return JsonResponse({"error": "Invalid recipient"}, status=400)++ recipient = None++ try:+ recipient = MessageRecipientPreference.objects.get(team_id=team_id, identifier=identifier)+ except MessageRecipientPreference.DoesNotExist:+ recipient = MessageRecipientPreference(team_id=team_id, identifier=identifier)++ try:+ prior_preferences = dict(recipient.preferences or {})+ preferences = request.POST.getlist("preferences[]")+ # Convert to dict of category_id: status+ preferences_dict = {}++ for pref in preferences:+ category_id, opted_in = pref.split(":")++ if opted_in not in ["true", "false"]:+ return JsonResponse({"error": "Preference values must be 'true' or 'false'"}, status=400)++ status = PreferenceStatus.OPTED_IN if opted_in == "true" else PreferenceStatus.OPTED_OUT+ preferences_dict[category_id] = status.value++ # $email_tracking is a measurement consent, not a subscription — it must neither+ # block nor trigger the "unsubscribed from everything" $all computation+ subscription_prefs = {k: v for k, v in preferences_dict.items() if k != EMAIL_TRACKING_PREFERENCE_ID}++ # If all preferences are opted out, add the "$all" preference+ if subscription_prefs and all(v == PreferenceStatus.OPTED_OUT.value for v in subscription_prefs.values()):+ preferences_dict[ALL_MESSAGE_PREFERENCE_CATEGORY_ID] = PreferenceStatus.OPTED_OUT.value++ # A save that doesn't include the tracking toggle (e.g. consent mode is off) must+ # not erase a stored consent answer in the wholesale rebuild+ if EMAIL_TRACKING_PREFERENCE_ID not in preferences_dict and EMAIL_TRACKING_PREFERENCE_ID in prior_preferences:+ preferences_dict[EMAIL_TRACKING_PREFERENCE_ID] = prior_preferences[EMAIL_TRACKING_PREFERENCE_ID]++ # A tracking-only save (no category toggles rendered, e.g. a team without marketing+ # categories) must not rebuild subscription state - it would drop a stored $all opt-out+ if not subscription_prefs:+ preferences_dict = {**prior_preferences, **preferences_dict}++ # Update all preferences with a single DB write+ recipient.preferences = preferences_dict+ recipient.save()++ sync_preferences_to_customerio(team_id, identifier, preferences_dict)++ # Only genuine opt-out transitions count, so repeated saves don't double-emit+ newly_opted_out = [+ category_id+ for category_id, status in preferences_dict.items()+ if category_id != EMAIL_TRACKING_PREFERENCE_ID+ and status == PreferenceStatus.OPTED_OUT.value+ and prior_preferences.get(category_id) != PreferenceStatus.OPTED_OUT.value+ ]+ if newly_opted_out:+ report_workflows_email_unsubscribed(team_id, identifier, newly_opted_out, "preferences_page")++ new_tracking_consent = preferences_dict.get(EMAIL_TRACKING_PREFERENCE_ID)+ if new_tracking_consent is not None and new_tracking_consent != prior_preferences.get(+ EMAIL_TRACKING_PREFERENCE_ID+ ):+ report_workflows_email_tracking_consent_updated(team_id, identifier, new_tracking_consent)++ return JsonResponse({"success": True})++ except Exception as e:+ capture_exception(e)+ return JsonResponse({"error": "Failed to update preferences"}, status=400)diff --git a/posthog/templates/message_preferences/error.html b/products/messaging/backend/templates/message_preferences/error.htmlsimilarity index 100%rename from posthog/templates/message_preferences/error.htmlrename to products/messaging/backend/templates/message_preferences/error.htmldiff --git a/posthog/templates/message_preferences/one_click_unsubscribe_success.html b/products/messaging/backend/templates/message_preferences/one_click_unsubscribe_success.htmlsimilarity index 100%rename from posthog/templates/message_preferences/one_click_unsubscribe_success.htmlrename to products/messaging/backend/templates/message_preferences/one_click_unsubscribe_success.htmldiff --git a/posthog/templates/message_preferences/preferences.html b/products/messaging/backend/templates/message_preferences/preferences.htmlsimilarity index 100%rename from posthog/templates/message_preferences/preferences.htmlrename to products/messaging/backend/templates/message_preferences/preferences.htmldiff --git a/pyproject.toml b/pyproject.tomlindex 9cc9caf66687..2bf11a0397ec 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -745,6 +745,12 @@ ignore_imports = ["products.batch_exports.backend.presentation.views.file_download -> products.batch_exports.backend.service","products.batch_exports.backend.presentation.views.file_download -> products.batch_exports.backend.temporal.record_batch_model","products.batch_exports.backend.presentation.views.file_download -> products.batch_exports.backend.temporal.sql.common",+ # TODO: messaging presentation wave — the recipient preferences page moved out of posthog/views.py+ # unchanged, so it still reads messaging models and services directly. Route each read through+ # the facade and delete each entry. Only delete entries here: a new import goes through the facade.+ "products.messaging.backend.presentation.views.recipient_preferences -> products.messaging.backend.models.message_category",+ "products.messaging.backend.presentation.views.recipient_preferences -> products.messaging.backend.models.message_preferences",+ "products.messaging.backend.presentation.views.recipient_preferences -> products.messaging.backend.services.customerio_sync_service",]# routes.py is the one module core reads to assemble a product's API router, so it is thediff --git a/tach.toml b/tach.tomlindex 42803691002e..6c736c84e66c 100644--- a/tach.toml+++ b/tach.toml@@ -633,6 +633,9 @@ depends_on = [# Facade-only: template writes publish the realtime edited-elsewhere event through# products.notifications.backend.facade.api."products.notifications",+ # Facade-only: the recipient preferences page reads EmailTrackingConsentMode through+ # products.workflows.backend.facade.enums.+ "products.workflows",]layer = "modules"