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 templates behind the facade and seal the product (#114069)

Harley Alexander3170fb9df3c9
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index 4d7204644de8..33d17c284443 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -227,6 +227,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {
"products.stamphog.backend.presentation.views.PullRequestViewSet",
"products.stamphog.backend.presentation.views.ReviewRunViewSet",
"products.stamphog.backend.presentation.views.StamphogRepoConfigViewSet",
+ "products.messaging.backend.presentation.views.message_templates.MessageTemplatesViewSet",
"products.streamlit_apps.backend.presentation.views.StreamlitAppViewSet",
"products.surveys.backend.api.survey.SurveyViewSet",
"products.tasks.backend.presentation.views.api.SandboxCustomImageViewSet",
diff --git a/products/isolation_baseline.txt b/products/isolation_baseline.txt
index bce2298a8e57..eb654a741656 100644
--- a/products/isolation_baseline.txt
+++ b/products/isolation_baseline.txt
@@ -54,7 +54,6 @@ managed_migrations
marketing_analytics
mcp_analytics
mcp_store
-messaging
notebooks
notifications
platform_features
diff --git a/products/messaging/backend/facade/templates.py b/products/messaging/backend/facade/templates.py
new file mode 100644
index 000000000000..ce207f3b3b50
--- /dev/null
+++ b/products/messaging/backend/facade/templates.py
@@ -0,0 +1,95 @@
+"""The email template library: saved templates a workflow email step can start from."""
+
+from collections.abc import Callable, Sequence
+from datetime import datetime
+from typing import Any
+from uuid import UUID
+
+from django.core.exceptions import ObjectDoesNotExist, ValidationError
+
+from posthog.dataclasses import frozen
+
+from products.messaging.backend.models.message_template import MessageTemplate
+from products.messaging.backend.services import message_templates as templates_service
+from products.messaging.backend.services.lazy_list import LazyList
+
+
+class MessageTemplateMissing(Exception):
+ """The team has no template with that id that is not deleted, or the id is not a UUID."""
+
+
+class MessageCategoryNotInTeam(Exception):
+ """The team has no category with that id."""
+
+
+@frozen
+class MessageTemplateRow:
+ id: UUID
+ name: str
+ description: str
+ created_at: datetime
+ updated_at: datetime
+ content: dict[str, Any]
+ created_by_id: int | None
+ type: str
+ message_category_id: UUID | None
+ deleted: bool
+
+
+def _to_contract(row: MessageTemplate) -> MessageTemplateRow:
+ return MessageTemplateRow(
+ id=row.id,
+ name=row.name,
+ description=row.description,
+ created_at=row.created_at,
+ updated_at=row.updated_at,
+ content=row.content,
+ created_by_id=row.created_by_id,
+ type=row.type,
+ message_category_id=row.message_category_id,
+ deleted=row.deleted,
+ )
+
+
+def list_templates(team_id: int) -> Sequence[MessageTemplateRow]:
+ """The team's templates that are not deleted, newest first. Sizing is a COUNT, and a slice reads one page."""
+ return LazyList(templates_service.team_templates(team_id), _to_contract)
+
+
+def get_template(team_id: int, template_id: UUID | str) -> MessageTemplateRow:
+ try:
+ return _to_contract(templates_service.team_template(team_id, template_id))
+ except (MessageTemplate.DoesNotExist, ValidationError, ValueError, TypeError) as e:
+ raise MessageTemplateMissing() from e
+
+
+def team_category_id(team_id: int, category_id: Any) -> UUID:
+ """The id of the team's category with that pk, deleted or not.
+
+ Raises MessageCategoryNotInTeam when there is none. A value that is not a UUID raises Django's
+ ValidationError, and a value of the wrong type raises TypeError or ValueError.
+ """
+ try:
+ return templates_service.category_id_for_team(team_id, category_id)
+ except ObjectDoesNotExist as e:
+ raise MessageCategoryNotInTeam() from e
+
+
+def create_template(team_id: int, created_by_id: int | None, fields: dict[str, Any]) -> MessageTemplateRow:
+ """Create a template from validated fields. `message_category` holds a category id or None."""
+ return _to_contract(templates_service.create_template(team_id, created_by_id, fields))
+
+
+def update_template(team_id: int, template_id: UUID, fields: dict[str, Any]) -> MessageTemplateRow:
+ """Set the given fields and save the whole row. `message_category` holds a category id or None."""
+ return _to_contract(templates_service.update_template(team_id, template_id, fields))
+
+
+def edit_template_content(
+ team_id: int, template_id: UUID, edit: Callable[[dict[str, Any]], dict[str, Any]]
+) -> MessageTemplateRow:
+ """Lock the template, replace its content with `edit(content)` and save, in one transaction.
+
+ `edit` gets a copy of the stored content. An exception from it rolls the change back.
+ """
+ return _to_contract(templates_service.edit_content_locked(team_id, template_id, edit))
diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.py
index e53dc5de5f94..672aa2b74064 100644
--- a/products/messaging/backend/presentation/views/message_templates.py
+++ b/products/messaging/backend/presentation/views/message_templates.py
@@ -1,22 +1,24 @@
-from copy import deepcopy
+from collections.abc import Sequence
+from dataclasses import fields as dataclass_fields
+from types import SimpleNamespace
from typing import Any
-from django.db import transaction
-
import structlog
-from drf_spectacular.utils import extend_schema, extend_schema_field
-from rest_framework import serializers, viewsets
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
+from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
from posthog.cdp.validation import build_html_wrap_design
from posthog.event_usage import report_user_action
+from posthog.models import User
from products.messaging.backend.facade.api import (
UnlayerNotConfiguredError,
@@ -25,8 +27,17 @@ from products.messaging.backend.facade.api import (
render_design_html,
validate_design,
)
-from products.messaging.backend.models.message_category import MessageCategory
-from products.messaging.backend.models.message_template import MessageTemplate
+from products.messaging.backend.facade.templates import (
+ MessageCategoryNotInTeam,
+ MessageTemplateMissing,
+ MessageTemplateRow,
+ create_template,
+ edit_template_content,
+ get_template,
+ list_templates,
+ team_category_id,
+ update_template,
+)
from products.messaging.backend.presentation.views.serializers import DesignOperationSerializer
from products.notifications.backend.facade.api import publish_resource_edited
@@ -108,40 +119,62 @@ class MessageTemplateContentSerializer(serializers.Serializer):
)
-class MessageTemplateSerializer(serializers.ModelSerializer):
- created_by = UserBasicSerializer(read_only=True)
+@extend_schema_field(OpenApiTypes.UUID)
+class MessageTemplateCategoryField(serializers.Field):
+ """A category id that must belong to the template's team. Errors match a primary key related field."""
+
+ default_error_messages = serializers.PrimaryKeyRelatedField.default_error_messages
+
+ def run_validation(self, data: Any = serializers.empty) -> Any:
+ # A DRF related field reads an empty string as null, and clients send "" to clear the category.
+ if data == "":
+ data = None
+ return super().run_validation(data)
+
+ def to_internal_value(self, data: Any) -> Any:
+ if isinstance(data, bool):
+ self.fail("incorrect_type", data_type=type(data).__name__)
+ try:
+ return team_category_id(self.context["team_id"], data)
+ except MessageCategoryNotInTeam:
+ self.fail("does_not_exist", pk_value=data)
+ except (TypeError, ValueError):
+ self.fail("incorrect_type", data_type=type(data).__name__)
+
+ def to_representation(self, value: Any) -> Any:
+ return value
+
+
+class MessageTemplateSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True)
+ name = serializers.CharField(max_length=400, help_text="Human-readable template name shown in the library.")
+ description = serializers.CharField(
+ allow_blank=True,
+ required=False,
+ style={"base_template": "textarea.html"},
+ help_text="What the template is for and when to use it.",
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+ updated_at = serializers.DateTimeField(read_only=True)
content = MessageTemplateContentSerializer(
required=False,
help_text="Template content keyed by channel. Replaced as a whole on update, not merged.",
)
- message_category = TeamScopedPrimaryKeyRelatedField(
- queryset=MessageCategory.objects.all(),
+ created_by = UserBasicSerializer(read_only=True)
+ type = serializers.CharField(
+ max_length=24,
+ allow_blank=True,
+ required=False,
+ help_text="Message channel of the template. Currently 'email'.",
+ )
+ message_category = MessageTemplateCategoryField(
required=False,
allow_null=True,
help_text="Message category ID to file the template under. Must belong to the same project.",
)
-
- class Meta:
- model = MessageTemplate
- fields = [
- "id",
- "name",
- "description",
- "created_at",
- "updated_at",
- "content",
- "created_by",
- "type",
- "message_category",
- "deleted",
- ]
- read_only_fields = ["id", "created_at", "created_by", "updated_at"]
- extra_kwargs = {
- "name": {"help_text": "Human-readable template name shown in the library."},
- "description": {"help_text": "What the template is for and when to use it."},
- "type": {"help_text": "Message channel of the template. Currently 'email'."},
- "deleted": {"help_text": "Soft-delete flag. Set true to remove the template from the library."},
- }
+ deleted = serializers.BooleanField(
+ required=False, help_text="Soft-delete flag. Set true to remove the template from the library."
+ )
def validate(self, data: Any) -> Any:
template_type = data.get("type")
@@ -177,13 +210,6 @@ class MessageTemplateSerializer(serializers.ModelSerializer):
)
return data
- def create(self, validated_data: Any) -> Any:
- request = self.context["request"]
- team_id = self.context["team_id"]
-
- instance = MessageTemplate.objects.create(**validated_data, team_id=team_id, created_by=request.user)
- return instance
-
class DesignPatchSerializer(serializers.Serializer):
operations = serializers.ListField(
@@ -197,6 +223,20 @@ class DesignPatchSerializer(serializers.Serializer):
)
+TEMPLATE_ID_PARAMETER = OpenApiParameter(
+ name="id",
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.PATH,
+ description="A UUID string identifying this message template.",
+)
+
+
+@extend_schema_view(
+ retrieve=extend_schema(parameters=[TEMPLATE_ID_PARAMETER]),
+ update=extend_schema(parameters=[TEMPLATE_ID_PARAMETER]),
+ partial_update=extend_schema(parameters=[TEMPLATE_ID_PARAMETER]),
+ destroy=extend_schema(parameters=[TEMPLATE_ID_PARAMETER]),
+)
class MessageTemplatesViewSet(
TeamAndOrgViewSetMixin,
ForbidDestroyModel,
@@ -209,20 +249,46 @@ class MessageTemplatesViewSet(
scope_object_write_actions = ["create", "update", "partial_update", "patch", "destroy", "design"]
serializer_class = MessageTemplateSerializer
- queryset = MessageTemplate.objects.all()
- def safely_get_queryset(self, queryset):
- return (
- queryset.filter(
- team_id=self.team_id,
- deleted=False,
+ def dangerously_get_object(self) -> MessageTemplateRow:
+ # Team scoping happens in the facade lookup, because the view has no queryset to filter.
+ # DRF's detail OPTIONS metadata also calls get_object(), so the lookup must live here.
+ try:
+ template = get_template(self.team_id, self.kwargs["pk"])
+ except MessageTemplateMissing:
+ raise NotFound()
+ self.check_object_permissions(self.request, template)
+ return template
+
+ def _with_creators(self, templates: Sequence[MessageTemplateRow]) -> list[SimpleNamespace]:
+ creator_ids = {template.created_by_id for template in templates if template.created_by_id}
+ creators = {user.id: user for user in User.objects.filter(id__in=creator_ids)} if creator_ids else {}
+ return [
+ SimpleNamespace(
+ **{field.name: getattr(template, field.name) for field in dataclass_fields(template)},
+ created_by=creators.get(template.created_by_id) if template.created_by_id else None,
+ message_category=template.message_category_id,
)
- .select_related("created_by")
- .order_by("-created_at")
- )
+ for template in templates
+ ]
- def perform_create(self, serializer: serializers.BaseSerializer) -> None:
- instance: MessageTemplate = serializer.save()
+ def _serialize(self, template: MessageTemplateRow) -> Any:
+ return self.get_serializer(self._with_creators([template])[0]).data
+
+ def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ templates = list_templates(self.team_id)
+ page = self.paginate_queryset(templates)
+ if page is not None:
+ return self.get_paginated_response(self.get_serializer(self._with_creators(page), many=True).data)
+ return Response(self.get_serializer(self._with_creators(list(templates)), many=True).data)
+
+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return Response(self._serialize(self.get_object()))
+
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ template = create_template(self.team_id, request.user.id, serializer.validated_data)
# report_user_action injects source and MCP-client properties from the request, so a create from the
# visual editor and one from the agent count in the same metric. Capture must never break the request.
try:
@@ -230,7 +296,7 @@ class MessageTemplatesViewSet(
self.request.user,
"message_template_created",
{
- "template_id": str(instance.id),
+ "template_id": str(template.id),
"team_id": str(self.team_id),
"organization_id": str(self.organization_id),
},
@@ -242,12 +308,19 @@ class MessageTemplatesViewSet(
)
except Exception as e:
logger.warning("Failed to capture message template usage event", error=str(e))
-
- def perform_update(self, serializer: serializers.BaseSerializer) -> None:
- instance: MessageTemplate = serializer.save()
- self._emit_resource_edited(instance)
-
- def _emit_resource_edited(self, instance: MessageTemplate) -> None:
+ data = self._serialize(template)
+ 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)
+ template = self.get_object()
+ serializer = self.get_serializer(self._with_creators([template])[0], data=request.data, partial=partial)
+ serializer.is_valid(raise_exception=True)
+ updated = update_template(self.team_id, template.id, serializer.validated_data)
+ self._emit_resource_edited(updated)
+ return Response(self._serialize(updated))
+
+ def _emit_resource_edited(self, instance: MessageTemplateRow) -> None:
# Realtime "edited elsewhere" signal so an open editor can refresh instead of overwriting a write
# from another channel (UI/MCP/API). Fires for every channel; the frontend drops its own echo by
# comparing updated_at. Transient, so no inbox notification. The write is already committed when
@@ -264,7 +337,9 @@ class MessageTemplatesViewSet(
except Exception as e:
logger.warning("Failed to publish message template edited event", error=str(e))
- @extend_schema(request=DesignPatchSerializer, responses={200: MessageTemplateSerializer})
+ @extend_schema(
+ request=DesignPatchSerializer, responses={200: MessageTemplateSerializer}, parameters=[TEMPLATE_ID_PARAMETER]
+ )
@action(detail=True, methods=["PATCH"])
def design(self, request: Request, *args: Any, **kwargs: Any) -> Response:
# Surgical design editing: apply a small, id-addressed op list to the stored Unlayer design instead
@@ -276,13 +351,9 @@ class MessageTemplatesViewSet(
operations = op_serializer.validated_data["operations"]
# Authorize + team-scope via the normal lookup, then re-read FOR UPDATE inside the transaction.
- instance = self.get_object()
-
- with transaction.atomic():
- # nosemgrep: idor-lookup-without-team (re-fetch of already-authorized instance, locked for update)
- locked = MessageTemplate.objects.select_for_update().get(pk=instance.pk)
+ template = self.get_object()
- content = deepcopy(locked.content or {})
+ def apply_operations(content: dict[str, Any]) -> dict[str, Any]:
email = content.get("email") or {}
design = email.get("design")
if not isinstance(design, dict):
@@ -295,16 +366,20 @@ class MessageTemplatesViewSet(
new_design = apply_design_operations(design, operations)
for warning in validate_design(new_design):
- logger.info("email_template_design_warning", warning=warning, template_id=str(locked.id))
+ logger.info("email_template_design_warning", warning=warning, template_id=str(template.id))
email["design"] = new_design
# Drop html so the serializer re-renders it from the patched design (its design->html path).
email.pop("html", None)
content["email"] = email
- serializer = self.get_serializer(locked, data={"content": content}, partial=True)
+ serializer = self.get_serializer(
+ self._with_creators([template])[0], data={"content": content}, partial=True
+ )
serializer.is_valid(raise_exception=True)
- serializer.save()
+ return serializer.validated_data["content"]
+
+ locked = edit_template_content(self.team_id, template.id, apply_operations)
self._emit_resource_edited(locked)
- return Response(self.get_serializer(locked).data)
+ return Response(self._serialize(locked))
diff --git a/products/messaging/backend/services/message_templates.py b/products/messaging/backend/services/message_templates.py
index b2e9e8fdc0d9..696000e0fe39 100644
--- a/products/messaging/backend/services/message_templates.py
+++ b/products/messaging/backend/services/message_templates.py
@@ -1,11 +1,12 @@
from collections.abc import Callable
+from copy import deepcopy
from typing import Any
from uuid import UUID
from django.db import models, transaction
from django.db.models.functions import Cast
-from products.messaging.backend.models import MessageTemplate
+from products.messaging.backend.models import MessageCategory, MessageTemplate
def get_email_content(team_id: int, template_id: UUID) -> dict | None:
@@ -48,3 +49,47 @@ def rewrite_content(
# updated_at is auto_now, so listing it bumps it. The editor's stale-write check reads it.
template.save(update_fields=["content", "updated_at"])
return occurrences
+
+
+def team_templates(team_id: int) -> models.QuerySet[MessageTemplate]:
+ # The pk tiebreak keeps pages stable, as the mixin ordering did for the queryset view.
+ return MessageTemplate.objects.filter(team_id=team_id, deleted=False).order_by("-created_at", "-pk")
+
+
+def team_template(team_id: int, template_id: UUID | str) -> MessageTemplate:
+ return MessageTemplate.objects.get(team_id=team_id, deleted=False, pk=template_id)
+
+
+def category_id_for_team(team_id: int, category_id: Any) -> UUID:
+ # Not filtered on deleted, as the related field this serves never was.
+ return MessageCategory.objects.get(team_id=team_id, pk=category_id).pk
+
+
+def _apply_fields(template: MessageTemplate, fields: dict[str, Any]) -> None:
+ for attr, value in fields.items():
+ setattr(template, "message_category_id" if attr == "message_category" else attr, value)
+
+
+def create_template(team_id: int, created_by_id: int | None, fields: dict[str, Any]) -> MessageTemplate:
+ template = MessageTemplate(team_id=team_id, created_by_id=created_by_id)
+ _apply_fields(template, fields)
+ template.save(force_insert=True)
+ return template
+
+
+def update_template(team_id: int, template_id: UUID | str, fields: dict[str, Any]) -> MessageTemplate:
+ template = team_template(team_id, template_id)
+ _apply_fields(template, fields)
+ template.save()
+ return template
+
+
+def edit_content_locked(
+ team_id: int, template_id: UUID | str, edit: Callable[[dict[str, Any]], dict[str, Any]]
+) -> MessageTemplate:
+ with transaction.atomic():
+ # nosemgrep: idor-lookup-without-team (re-fetch of an already team-scoped template, locked for update)
+ locked = MessageTemplate.objects.select_for_update().get(pk=team_template(team_id, template_id).pk)
+ locked.content = edit(deepcopy(locked.content or {}))
+ locked.save()
+ return locked
diff --git a/products/messaging/backend/tests/api/test_message_templates.py b/products/messaging/backend/tests/api/test_message_templates.py
index 660b83732158..33be978ef09d 100644
--- a/products/messaging/backend/tests/api/test_message_templates.py
+++ b/products/messaging/backend/tests/api/test_message_templates.py
@@ -1,3 +1,6 @@
+from datetime import UTC, datetime
+from uuid import UUID
+
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -57,6 +60,24 @@ class TestMessageTemplatesAPI(APIBaseTest):
}
assert template["type"] == "email"
+ def test_list_pages_templates_with_equal_created_at_by_descending_id(self):
+ ids = [UUID(int=n) for n in (1, 2, 3)]
+ for template_id in ids:
+ MessageTemplate.objects.create(id=template_id, team=self.team, name=str(template_id), type="email")
+ MessageTemplate.objects.filter(id__in=ids).update(created_at=datetime(2100, 1, 1, tzinfo=UTC))
+
+ pages = [
+ [
+ row["id"]
+ for row in self.client.get(
+ f"/api/environments/{self.team.id}/messaging_templates/?limit=2&offset={offset}"
+ ).json()["results"]
+ ]
+ for offset in (0, 2)
+ ]
+
+ assert pages == [[str(ids[2]), str(ids[1])], [str(ids[0]), str(self.message_template.id)]]
+
def test_retrieve_message_template(self):
response = self.client.get(f"/api/environments/{self.team.id}/messaging_templates/{self.message_template.id}/")
assert response.status_code == status.HTTP_200_OK
@@ -343,18 +364,34 @@ class TestMessageTemplatesAPI(APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/messaging_templates/{self.other_team_template.id}/")
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_can_bind_template_to_own_teams_message_category(self):
- own_category = MessageCategory.objects.create(team=self.team, key="own-key", name="Own")
+ @parameterized.expand([("other_own_category",), ("empty_string",), ("null",)])
+ def test_patch_sets_or_clears_own_teams_message_category(self, sent: str):
+ current = MessageCategory.objects.create(team=self.team, key="current-key", name="Current")
+ other = MessageCategory.objects.create(team=self.team, key="own-key", name="Own")
+ self.message_template.message_category = current
+ self.message_template.save()
+ value, expected = {
+ "other_own_category": (str(other.id), other.id),
+ "empty_string": ("", None),
+ "null": (None, None),
+ }[sent]
response = self.client.patch(
f"/api/environments/{self.team.id}/messaging_templates/{self.message_template.id}/",
- data={"message_category": str(own_category.id)},
+ data={"message_category": value},
format="json",
)
- assert response.status_code == status.HTTP_200_OK
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["message_category"] == (str(expected) if expected else None)
self.message_template.refresh_from_db()
- assert self.message_template.message_category_id == own_category.id
+ assert self.message_template.message_category_id == expected
+
+ def test_detail_options_describes_writable_fields(self):
+ response = self.client.options(f"/api/projects/{self.team.id}/messaging_templates/{self.message_template.id}/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert "message_category" in response.json()["actions"]["PUT"]
def _design_with_text(self) -> dict:
return {
diff --git a/products/messaging/package.json b/products/messaging/package.json
index 7bcdcc1cb6df..784b1caa225e 100644
--- a/products/messaging/package.json
+++ b/products/messaging/package.json
@@ -1,6 +1,7 @@
{
"name": "@posthog/products-messaging",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
}
}
diff --git a/products/messaging/turbo.json b/products/messaging/turbo.json
new file mode 100644
index 000000000000..5a1fb406a1b9
--- /dev/null
+++ b/products/messaging/turbo.json
@@ -0,0 +1,17 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/routes.py",
+ "backend/tasks/**",
+ "backend/models/**",
+ "backend/migrations/**"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/pyproject.toml b/pyproject.toml
index a8acd5b6803a..073cd8798288 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -745,16 +745,6 @@ 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 moved views still read messaging models and services
- # directly. Each lane thins its own modules to parse -> facade -> serialize and deletes only its
- # own entries, keeping its header. backend:contract-check stays off until this list is empty.
- # Only delete entries here: a new import from these views goes through the facade.
- # Lane A: suppression
- # Lane B: categories, Customer.io config and the Customer.io webhook
- # Lane C: preferences and the recipient preferences page
- # 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",
]
# routes.py is the one module core reads to assemble a product's API router, so it is the