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.

chore(messaging): move the recipient preferences page behind the facade (#114009)

Harley Alexander0387bd76cfcc
diff --git a/products/messaging/backend/facade/preferences.py b/products/messaging/backend/facade/preferences.py
index a8292d777a69..8162858c7e62 100644
--- a/products/messaging/backend/facade/preferences.py
+++ b/products/messaging/backend/facade/preferences.py
@@ -2,16 +2,32 @@
from collections.abc import Iterator, Sequence
from datetime import datetime
+from enum import StrEnum
from typing import Any
from uuid import UUID
from posthog.dataclasses import frozen
+from products.messaging.backend.models import message_preferences as preference_model
from products.messaging.backend.models.message_preferences import MessageRecipientPreference
-from products.messaging.backend.services import preferences as preferences_service
+from products.messaging.backend.services import (
+ customerio_sync_service,
+ preferences as preferences_service,
+)
from products.messaging.backend.services.lazy_list import LazyList
from products.messaging.backend.services.opt_out_service import BulkOptOutEntry, UnknownCategoryError
+ALL_MESSAGE_PREFERENCE_CATEGORY_ID: str = preference_model.ALL_MESSAGE_PREFERENCE_CATEGORY_ID
+EMAIL_TRACKING_PREFERENCE_ID: str = preference_model.EMAIL_TRACKING_PREFERENCE_ID
+
+
+class PreferenceStatus(StrEnum):
+ """The stored value of one preference. Mirrors the model's choices."""
+
+ OPTED_IN = "OPTED_IN"
+ OPTED_OUT = "OPTED_OUT"
+ NO_PREFERENCE = "NO_PREFERENCE"
+
class MessageCategoryNotFound(Exception):
"""No category with the requested key exists for the team. The message names the key when known."""
@@ -106,3 +122,58 @@ def bulk_opt_out(
return BulkOptOutOutcome(
total=result.total, opted_out=result.opted_out, skipped=result.skipped, errors=result.errors
)
+
+
+@frozen
+class CategoryOption:
+ id: UUID
+ name: str
+ public_description: str
+
+
+def preference_status(preferences: dict[str, Any], category_id: str) -> PreferenceStatus:
+ """The status stored for one category. Raises ValueError for a value that is not a status."""
+ return PreferenceStatus(preferences.get(str(category_id), PreferenceStatus.NO_PREFERENCE.value))
+
+
+def all_preference_statuses(preferences: dict[str, Any]) -> dict[str, PreferenceStatus]:
+ """Every stored status by category id. Raises ValueError for a value that is not a status."""
+ return {str(category_id): PreferenceStatus(status) for category_id, status in preferences.items()}
+
+
+def category_ids(team_id: int) -> set[str]:
+ """Ids of the team's categories that are not deleted, of every type."""
+ return preferences_service.category_ids(team_id)
+
+
+def marketing_categories(team_id: int) -> list[CategoryOption]:
+ """The team's marketing categories that are not deleted, by name."""
+ return [
+ CategoryOption(id=c.id, name=c.name, public_description=c.public_description)
+ for c in preferences_service.marketing_categories(team_id)
+ ]
+
+
+def get_or_create_recipient(team_id: int, identifier: str) -> RecipientPreferences:
+ return _to_contract(preferences_service.get_or_create_recipient(team_id, identifier))
+
+
+def recipient_preferences(team_id: int, identifier: str) -> dict[str, Any] | None:
+ """The recipient's stored preferences, or None when the team has no row for them."""
+ row = preferences_service.recipient_or_none(team_id, identifier)
+ return None if row is None else row.preferences
+
+
+def set_preferences_column(team_id: int, identifier: str, preferences: dict[str, Any]) -> None:
+ """Overwrite an existing recipient's preferences. Writes only that column, so updated_at stays."""
+ preferences_service.set_preferences_column(team_id, identifier, preferences)
+
+
+def replace_preferences(team_id: int, identifier: str, preferences: dict[str, Any]) -> None:
+ """Overwrite the recipient's preferences with one full save, creating the row when it is missing."""
+ preferences_service.replace_preferences(team_id, identifier, preferences)
+
+
+def sync_to_customerio(team_id: int, identifier: str, preferences: dict[str, Any]) -> None:
+ """Push the preferences to Customer.io now, when the team has track sync enabled."""
+ customerio_sync_service.sync_preferences_to_customerio(team_id, identifier, preferences)
diff --git a/products/messaging/backend/presentation/views/recipient_preferences.py b/products/messaging/backend/presentation/views/recipient_preferences.py
index d686149325a1..9801c4bfac08 100644
--- a/products/messaging/backend/presentation/views/recipient_preferences.py
+++ b/products/messaging/backend/presentation/views/recipient_preferences.py
@@ -12,14 +12,20 @@ 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 (
+from products.messaging.backend.facade.preferences import (
ALL_MESSAGE_PREFERENCE_CATEGORY_ID,
EMAIL_TRACKING_PREFERENCE_ID,
- MessageRecipientPreference,
PreferenceStatus,
+ all_preference_statuses,
+ category_ids as team_category_ids,
+ get_or_create_recipient,
+ marketing_categories,
+ preference_status,
+ recipient_preferences,
+ replace_preferences,
+ set_preferences_column,
+ sync_to_customerio,
)
-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__)
@@ -43,12 +49,7 @@ def report_workflows_email_unsubscribed(team_id: int, identifier: str, category_
# 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
- )
- }
+ known_category_ids = team_category_ids(team_id)
except Exception as e:
capture_exception(e)
return
@@ -127,14 +128,17 @@ def preferences_page(request: HttpRequest, token: str) -> HttpResponse:
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")
+ recipient = get_or_create_recipient(team_id, identifier)
+ current_preferences = recipient.preferences
+ categories = marketing_categories(team_id)
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
+ was_fully_opted_out = (
+ preference_status(recipient.preferences, 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}
@@ -148,10 +152,10 @@ def preferences_page(request: HttpRequest, token: str) -> HttpResponse:
if tracking_pref is not None:
preferences_dict[EMAIL_TRACKING_PREFERENCE_ID] = tracking_pref
- recipient.preferences = preferences_dict
- recipient.save(update_fields=["preferences"])
+ set_preferences_column(team_id, identifier, preferences_dict)
+ current_preferences = preferences_dict
- sync_preferences_to_customerio(team_id, identifier, preferences_dict)
+ sync_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:
@@ -161,7 +165,7 @@ def preferences_page(request: HttpRequest, token: str) -> HttpResponse:
return HttpResponse(status=200)
# Only fetch active categories and their preferences
- preferences = recipient.get_all_preferences() if recipient else {}
+ preferences = all_preference_statuses(current_preferences)
categories_templating = [
{
@@ -229,15 +233,10 @@ def update_preferences(request: HttpRequest) -> JsonResponse:
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)
+ stored_preferences = recipient_preferences(team_id, identifier)
try:
- prior_preferences = dict(recipient.preferences or {})
+ prior_preferences = dict(stored_preferences or {})
preferences = request.POST.getlist("preferences[]")
# Convert to dict of category_id: status
preferences_dict = {}
@@ -269,11 +268,9 @@ def update_preferences(request: HttpRequest) -> JsonResponse:
if not subscription_prefs:
preferences_dict = {**prior_preferences, **preferences_dict}
- # Update all preferences with a single DB write
- recipient.preferences = preferences_dict
- recipient.save()
+ replace_preferences(team_id, identifier, preferences_dict)
- sync_preferences_to_customerio(team_id, identifier, preferences_dict)
+ sync_to_customerio(team_id, identifier, preferences_dict)
# Only genuine opt-out transitions count, so repeated saves don't double-emit
newly_opted_out = [
diff --git a/products/messaging/backend/services/preferences.py b/products/messaging/backend/services/preferences.py
index b45860dd6e7e..900299b36056 100644
--- a/products/messaging/backend/services/preferences.py
+++ b/products/messaging/backend/services/preferences.py
@@ -123,3 +123,39 @@ def bulk_opt_out(
team_id: int, entries: list[BulkOptOutEntry], default_category_key: str | None, created_by_id: int | None
) -> BulkOptOutResult:
return OptOutService(team_id=team_id, created_by_id=created_by_id).opt_out_recipients(entries, default_category_key)
+
+
+def category_ids(team_id: int) -> set[str]:
+ return {
+ str(category_id)
+ for category_id in MessageCategory.objects.filter(team_id=team_id, deleted=False).values_list("id", flat=True)
+ }
+
+
+def marketing_categories(team_id: int) -> QuerySet[MessageCategory]:
+ return MessageCategory.objects.filter(deleted=False, team=team_id, category_type="marketing").order_by("name")
+
+
+def get_or_create_recipient(team_id: int, identifier: str) -> MessageRecipientPreference:
+ recipient, _ = MessageRecipientPreference.objects.get_or_create(team_id=team_id, identifier=identifier)
+ return recipient
+
+
+def recipient_or_none(team_id: int, identifier: str) -> MessageRecipientPreference | None:
+ return MessageRecipientPreference.objects.filter(team_id=team_id, identifier=identifier).first()
+
+
+def set_preferences_column(team_id: int, identifier: str, preferences: dict[str, Any]) -> None:
+ recipient = MessageRecipientPreference.objects.get(team_id=team_id, identifier=identifier)
+ recipient.preferences = preferences
+ recipient.save(update_fields=["preferences"])
+
+
+def replace_preferences(team_id: int, identifier: str, preferences: dict[str, Any]) -> None:
+ try:
+ recipient = MessageRecipientPreference.objects.get(team_id=team_id, identifier=identifier)
+ except MessageRecipientPreference.DoesNotExist:
+ recipient = MessageRecipientPreference(team_id=team_id, identifier=identifier)
+ # Update all preferences with a single DB write
+ recipient.preferences = preferences
+ recipient.save()
diff --git a/products/messaging/backend/tests/api/test_message_preferences.py b/products/messaging/backend/tests/api/test_message_preferences.py
index b7587018cb62..0e0bd5a7dc42 100644
--- a/products/messaging/backend/tests/api/test_message_preferences.py
+++ b/products/messaging/backend/tests/api/test_message_preferences.py
@@ -68,7 +68,7 @@ class TestMessagePreferencesViews(BaseTest):
self.assertTemplateUsed(response, "message_preferences/preferences.html")
# Check context
- self.assertEqual(response.context["recipient"], self.recipient)
+ self.assertEqual(response.context["recipient"].identifier, self.recipient.identifier)
self.assertEqual(len(response.context["categories"]), 3)
self.assertEqual(response.context["token"], self.token)
diff --git a/pyproject.toml b/pyproject.toml
index 68adca17d9f3..ef6d4dd80dcc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -753,9 +753,6 @@ ignore_imports = [
"products.messaging.backend.presentation.views.message_suppression -> products.messaging.backend.models.message_suppression",
# Lane B: categories, Customer.io config and the Customer.io webhook
# Lane C: preferences and the recipient preferences page
- "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",
# Lane D: templates
"products.messaging.backend.presentation.views.message_templates -> products.messaging.backend.models.message_category",
"products.messaging.backend.presentation.views.message_templates -> products.messaging.backend.models.message_template",