: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 message category CRUD behind the facade (#114034)
Harley Alexander5cd7de6f8a4d
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex 1ca161359ab6..4d7204644de8 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -266,6 +266,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.workflows.backend.presentation.views.hog_flow.HogFlowViewSet","products.workflows.backend.presentation.views.hog_flow_template.HogFlowTemplateViewSet","products.workflows.backend.presentation.views.hog_flow_template.PublicHogFlowTemplateViewSet",+ "products.messaging.backend.presentation.views.message_categories.MessageCategoryViewSet",}diff --git a/products/messaging/backend/facade/categories.py b/products/messaging/backend/facade/categories.pynew file mode 100644index 000000000000..a0163724495a--- /dev/null+++ b/products/messaging/backend/facade/categories.py@@ -0,0 +1,79 @@+"""Message categories: the per-team topics a recipient can opt out of."""++from collections.abc import Sequence+from datetime import datetime+from typing import Any+from uuid import UUID++from django.core.exceptions import ValidationError++from posthog.dataclasses import frozen++from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryType+from products.messaging.backend.services import categories as categories_service+from products.messaging.backend.services.lazy_list import LazyList++MESSAGE_CATEGORY_TYPE_CHOICES: list[tuple[str, str]] = [+ (value, str(label)) for value, label in MessageCategoryType.choices+]+DEFAULT_MESSAGE_CATEGORY_TYPE: str = MessageCategoryType.MARKETING.value+++class MessageCategoryMissing(Exception):+ """The team has no category with that id that is not deleted, or the id is not a UUID."""+++@frozen+class MessageCategoryRow:+ id: UUID+ key: str+ name: str+ description: str+ public_description: str+ category_type: str+ created_at: datetime+ updated_at: datetime+ created_by_id: int | None+ deleted: bool+++def _to_contract(row: MessageCategory) -> MessageCategoryRow:+ return MessageCategoryRow(+ id=row.id,+ key=row.key,+ name=row.name,+ description=row.description,+ public_description=row.public_description,+ category_type=row.category_type,+ created_at=row.created_at,+ updated_at=row.updated_at,+ created_by_id=row.created_by_id,+ deleted=row.deleted,+ )+++def list_categories(team_id: int) -> Sequence[MessageCategoryRow]:+ """The team's categories that are not deleted. Sizing is a COUNT, and a slice reads one page."""+ # The mixin only adds its stable pk ordering to a QuerySet, so pages need it set here.+ return LazyList(categories_service.team_categories(team_id).order_by("pk"), _to_contract)+++def get_category(team_id: int, category_id: UUID | str) -> MessageCategoryRow:+ try:+ return _to_contract(categories_service.team_category(team_id, category_id))+ except (MessageCategory.DoesNotExist, ValidationError, ValueError, TypeError) as e:+ raise MessageCategoryMissing() from e+++def category_key_in_use(team_id: int, key: str) -> bool:+ """True when a category that is not deleted already uses the key."""+ return categories_service.key_in_use(team_id, key)+++def create_category(team_id: int, created_by_id: int | None, fields: dict[str, Any]) -> MessageCategoryRow:+ return _to_contract(categories_service.create_category(team_id, created_by_id, fields))+++def update_category(team_id: int, category_id: UUID, fields: dict[str, Any]) -> MessageCategoryRow:+ """Set the given fields and save the whole row, as the serializer's update did."""+ return _to_contract(categories_service.update_category(team_id, category_id, fields))diff --git a/products/messaging/backend/presentation/views/message_categories.py b/products/messaging/backend/presentation/views/message_categories.pyindex 1e3253746c16..a0d1e54e6c9c 100644--- a/products/messaging/backend/presentation/views/message_categories.py+++ b/products/messaging/backend/presentation/views/message_categories.py@@ -1,12 +1,28 @@+from typing import Any++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_viewfrom rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import action+from rest_framework.exceptions import NotFoundfrom rest_framework.parsers import FormParser, MultiPartParser+from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixin+from products.messaging.backend.facade.categories import (+ MESSAGE_CATEGORY_TYPE_CHOICES,+ MessageCategoryMissing,+ MessageCategoryRow,+ category_key_in_use,+ create_category,+ get_category,+ list_categories,+ update_category,+)from products.messaging.backend.facade.customerio import (CustomerIOConfigConflict,CustomerIOConfigIncomplete,@@ -22,46 +38,32 @@ from products.messaging.backend.facade.customerio import (save_track_config,save_webhook_config,)-from products.messaging.backend.models.message_category import MessageCategory-class MessageCategorySerializer(serializers.ModelSerializer):+class MessageCategorySerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True)+ key = serializers.CharField(max_length=64)+ name = serializers.CharField(max_length=128)+ description = serializers.CharField(allow_blank=True, required=False, style={"base_template": "textarea.html"})+ public_description = serializers.CharField(+ allow_blank=True, required=False, style={"base_template": "textarea.html"}+ )+ category_type = serializers.ChoiceField(choices=MESSAGE_CATEGORY_TYPE_CHOICES, required=False)+ created_at = serializers.DateTimeField(read_only=True)+ updated_at = serializers.DateTimeField(read_only=True)+ created_by = serializers.IntegerField(source="created_by_id", read_only=True, allow_null=True)+ deleted = serializers.BooleanField(required=False)+def validate(self, data):if self.instance is None:# Ensure key is unique per team for new instances- if MessageCategory.objects.filter(team_id=self.context["team_id"], key=data["key"], deleted=False).exists():+ if category_key_in_use(self.context["team_id"], data["key"]):raise serializers.ValidationError({"key": "A message category with this key already exists."})else:if "key" in data and hasattr(self.instance, "key") and data["key"] != self.instance.key:raise serializers.ValidationError({"key": "The key field cannot be updated after creation."})return data- class Meta:- model = MessageCategory- fields = (- "id",- "key",- "name",- "description",- "public_description",- "category_type",- "created_at",- "updated_at",- "created_by",- "deleted",- )- read_only_fields = (- "id",- "created_at",- "updated_at",- "created_by",- )-- def create(self, validated_data):- validated_data["team_id"] = self.context["team_id"]- validated_data["created_by"] = self.context["request"].user- return super().create(validated_data)-class CustomerIOImportSerializer(serializers.Serializer):"""Serializer for Customer.io import request"""@@ -84,6 +86,20 @@ class TrackConfigStateSerializer(DataclassSerializer):dataclass = TrackConfigState+CATEGORY_ID_PARAMETER = OpenApiParameter(+ name="id",+ type=OpenApiTypes.UUID,+ location=OpenApiParameter.PATH,+ description="A UUID string identifying this message category.",+)+++@extend_schema_view(+ retrieve=extend_schema(parameters=[CATEGORY_ID_PARAMETER]),+ update=extend_schema(parameters=[CATEGORY_ID_PARAMETER]),+ partial_update=extend_schema(parameters=[CATEGORY_ID_PARAMETER]),+ destroy=extend_schema(parameters=[CATEGORY_ID_PARAMETER]),+)class MessageCategoryViewSet(TeamAndOrgViewSetMixin,ForbidDestroyModel,@@ -92,12 +108,39 @@ class MessageCategoryViewSet(scope_object = "INTERNAL"serializer_class = MessageCategorySerializer- queryset = MessageCategory.objects.all()- def safely_get_queryset(self, queryset):- return queryset.filter(- deleted=False,- )+ def _category(self) -> MessageCategoryRow:+ # INTERNAL scope has no object-level access rules, so a team-scoped lookup is the whole check.+ try:+ return get_category(self.team_id, self.kwargs["pk"])+ except MessageCategoryMissing:+ raise NotFound()++ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ categories = list_categories(self.team_id)+ # The paginator only needs len() and slicing, which the facade's sequence provides.+ page = self.paginate_queryset(categories)+ if page is not None:+ return self.get_paginated_response(self.get_serializer(page, many=True).data)+ return Response(self.get_serializer(categories, many=True).data)++ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ return Response(self.get_serializer(self._category()).data)++ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ category = create_category(self.team_id, request.user.id, serializer.validated_data)+ data = self.get_serializer(category).data+ return Response(data, status=status.HTTP_201_CREATED, headers=self.get_success_headers(data))++ def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ partial = kwargs.pop("partial", False)+ category = self._category()+ serializer = self.get_serializer(category, data=request.data, partial=partial)+ serializer.is_valid(raise_exception=True)+ updated = update_category(self.team_id, category.id, serializer.validated_data)+ return Response(self.get_serializer(updated).data)@action(detail=False, methods=["post"])def import_from_customerio(self, request, **kwargs):diff --git a/products/messaging/backend/services/categories.py b/products/messaging/backend/services/categories.pynew file mode 100644index 000000000000..9f298d05a186--- /dev/null+++ b/products/messaging/backend/services/categories.py@@ -0,0 +1,30 @@+from typing import Any+from uuid import UUID++from django.db.models import QuerySet++from products.messaging.backend.models.message_category import MessageCategory+++def team_categories(team_id: int) -> QuerySet[MessageCategory]:+ return MessageCategory.objects.filter(team_id=team_id, deleted=False)+++def team_category(team_id: int, category_id: UUID | str) -> MessageCategory:+ return team_categories(team_id).get(pk=category_id)+++def key_in_use(team_id: int, key: str) -> bool:+ return MessageCategory.objects.filter(team_id=team_id, key=key, deleted=False).exists()+++def create_category(team_id: int, created_by_id: int | None, fields: dict[str, Any]) -> MessageCategory:+ return MessageCategory.objects.create(**fields, team_id=team_id, created_by_id=created_by_id)+++def update_category(team_id: int, category_id: UUID | str, fields: dict[str, Any]) -> MessageCategory:+ category = team_category(team_id, category_id)+ for attr, value in fields.items():+ setattr(category, attr, value)+ category.save()+ return categorydiff --git a/products/messaging/backend/services/lazy_list.py b/products/messaging/backend/services/lazy_list.pynew file mode 100644index 000000000000..42d2c1a87301--- /dev/null+++ b/products/messaging/backend/services/lazy_list.py@@ -0,0 +1,37 @@+from collections.abc import Callable, Iterator, Sequence+from typing import Any, TypeVar, overload++from django.db.models import QuerySet++_Contract = TypeVar("_Contract")+++class LazyList(Sequence[_Contract]):+ """Contracts backed by a queryset, converted only for the rows a caller slices.++ A paginating view sizes the list and then slices one page, so the database returns one page+ and the size is a COUNT. Nothing but contracts leaves the facade.+ """++ def __init__(self, queryset: QuerySet, to_contract: Callable[[Any], _Contract]) -> None:+ self._queryset = queryset+ self._to_contract = to_contract++ def __len__(self) -> int:+ return self._queryset.count()++ def __iter__(self) -> Iterator[_Contract]:+ # Explicit: the Sequence mixin would iterate by index, one query per row.+ return (self._to_contract(row) for row in self._queryset)++ @overload+ def __getitem__(self, index: int) -> _Contract: ...++ @overload+ def __getitem__(self, index: slice) -> list[_Contract]: ...++ def __getitem__(self, index: int | slice) -> _Contract | list[_Contract]:+ rows = self._queryset[index]+ if isinstance(index, slice):+ return [self._to_contract(row) for row in rows]+ return self._to_contract(rows)diff --git a/products/messaging/backend/tests/api/test_message_categories.py b/products/messaging/backend/tests/api/test_message_categories.pyindex e158f6596598..6252bd06a72b 100644--- a/products/messaging/backend/tests/api/test_message_categories.py+++ b/products/messaging/backend/tests/api/test_message_categories.py@@ -1,3 +1,5 @@+from uuid import UUID+from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -30,6 +32,23 @@ class TestMessageCategoryAPI(APIBaseTest):self.assertEqual(len(response_data["results"]), 1)self.assertEqual(response_data["results"][0]["name"], "Team 1 Category")+ def test_list_pages_categories_by_ascending_id(self):+ ids = [UUID(int=n) for n in (3, 2, 1)]+ for category_id in ids:+ MessageCategory.objects.create(id=category_id, team=self.team, name=str(category_id), key=str(category_id))++ pages = [+ [+ row["id"]+ for row in self.client.get(+ f"/api/environments/{self.team.id}/messaging_categories/?limit=2&offset={offset}"+ ).json()["results"]+ ]+ for offset in (0, 2)+ ]++ assert pages == [[str(ids[2]), str(ids[1])], [str(ids[0])]]+def test_get_message_category(self):"""Tests GET /messaging_categories/:id works as expected.diff --git a/pyproject.toml b/pyproject.tomlindex f54540001314..e6b3f44b5a93 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -752,7 +752,6 @@ ignore_imports = [# Lane A: suppression"products.messaging.backend.presentation.views.message_suppression -> products.messaging.backend.models.message_suppression",# Lane B: categories, Customer.io config and the Customer.io webhook- "products.messaging.backend.presentation.views.message_categories -> products.messaging.backend.models.message_category",# Lane C: preferences and the recipient preferences page"products.messaging.backend.presentation.views.message_preferences -> products.messaging.backend.models.message_category","products.messaging.backend.presentation.views.message_preferences -> products.messaging.backend.models.message_preferences",