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): add a facade and move outside callers onto it (#113876)

Harley Alexander88b920df153c
diff --git a/posthog/cdp/test/test_validation.py b/posthog/cdp/test/test_validation.py
index 15057b5a6422..3e8c3e229ffb 100644
--- a/posthog/cdp/test/test_validation.py
+++ b/posthog/cdp/test/test_validation.py
@@ -22,7 +22,7 @@ from posthog.cdp.validation import (
)
from posthog.models.integration import Integration
-from products.messaging.backend.api.design_validation import validate_design
+from products.messaging.backend.facade.api import validate_design
from common.hogvm.python.operation import HOGQL_BYTECODE_VERSION
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index d399dfb7afb4..15b86ccf8744 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -94,6 +94,10 @@ from products.experiments.backend.models.experiment import Experiment
from products.exports.backend.models.exported_asset import ExportedAsset
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.logs.backend.models import LogsAlertConfiguration, LogsView
+from products.messaging.backend.facade.testing import (
+ create_message_category_for_test,
+ create_recipient_preference_for_test,
+)
from products.notebooks.backend.models import Notebook, ResourceNotebook
from products.product_analytics.backend.facade.models import Insight, InsightVariable
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerOrigin, ScannerType
@@ -547,17 +551,13 @@ def _create_hog_flow(team: Team, label: str) -> str:
return create_workflow_for_test(team_id=team.id, name=f"flow_{label}").id
-def _create_message_category(team: Team, label: str):
- from products.messaging.backend.models.message_category import MessageCategory
-
- return MessageCategory.objects.create(team=team, key=f"category_{label}", name=f"Category {label}")
-
+def _create_message_category(team: Team, label: str) -> uuid.UUID:
+ return create_message_category_for_test(team_id=team.pk, key=f"category_{label}", name=f"Category {label}")
-def _create_message_recipient_preference(team: Team, label: str):
- from products.messaging.backend.models.message_preferences import MessageRecipientPreference
- return MessageRecipientPreference.objects.create(
- team=team, identifier=f"{label}@example.com", preferences={"$all": "OPTED_OUT"}
+def _create_message_recipient_preference(team: Team, label: str) -> uuid.UUID:
+ return create_recipient_preference_for_test(
+ team_id=team.pk, identifier=f"{label}@example.com", preferences={"$all": "OPTED_OUT"}
)
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.py
index 96735b68878d..e63889bea66e 100644
--- a/posthog/models/remote_config.py
+++ b/posthog/models/remote_config.py
@@ -213,7 +213,7 @@ class RemoteConfig(UUIDTModel):
from products.error_tracking.backend.facade import build_error_tracking_config
from products.feature_flags.backend.models.feature_flag import FeatureFlag
- from products.messaging.backend.remote_config import build_push_config
+ from products.messaging.backend.facade.api import build_push_config
from products.surveys.backend.api.survey import get_surveys_opt_in, get_surveys_response
from products.web_analytics.backend.remote_config import build_heatmaps_config
@@ -251,7 +251,7 @@ class RemoteConfig(UUIDTModel):
config["errorTracking"] = build_error_tracking_config(team)
# MARK: Push notifications
- config["push"] = build_push_config(team)
+ config["push"] = build_push_config(team.id)
# MARK: Logs
logs_settings = team.logs_settings or {}
@@ -619,12 +619,12 @@ def organization_subscription_saved(sender, instance, created, **kwargs):
@receiver(post_save, sender="posthog.Integration")
@receiver(post_delete, sender="posthog.Integration")
def push_integration_changed(sender, instance, **kwargs):
- from products.messaging.backend.remote_config import PUSH_APP_ID_CONFIG_KEYS
+ from products.messaging.backend.facade.api import is_push_integration_kind
# Integrations cover every kind we support, and most of them have nothing to do with the SDK
# payload. Only refresh for the two push kinds, so an OAuth token refresh on an unrelated
# integration doesn't enqueue a rebuild for every team that has one.
- if instance.kind not in PUSH_APP_ID_CONFIG_KEYS:
+ if not is_push_integration_kind(instance.kind):
return
# The app_ids live in config, and integration code saves errors and created_by on their own —
# apns_integration alone does three saves per creation. Only config can change the payload.
diff --git a/products/messaging/backend/api/test/test_message_preferences.py b/products/messaging/backend/api/test/test_message_preferences.py
index 76d891447cac..4a8517be8204 100644
--- a/products/messaging/backend/api/test/test_message_preferences.py
+++ b/products/messaging/backend/api/test/test_message_preferences.py
@@ -829,7 +829,7 @@ class TestMessagePreferencesAPIViewSet(APIBaseTest):
("remove_opt_out", PreferenceStatus.OPTED_IN),
]
)
- @patch("products.messaging.backend.tasks.sync_preferences_to_customerio")
+ @patch("products.messaging.backend.tasks.tasks.sync_preferences_to_customerio")
def test_opt_out_writes_are_synced_to_customerio(self, endpoint, expected_status, mock_sync):
# Exercises the whole dispatch chain: the view enqueues the task on commit, and the
# task (eager in tests) reads the row back and calls the sync service.
diff --git a/products/messaging/backend/facade/__init__.py b/products/messaging/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/messaging/backend/facade/api.py b/products/messaging/backend/facade/api.py
new file mode 100644
index 000000000000..d92fd9b17289
--- /dev/null
+++ b/products/messaging/backend/facade/api.py
@@ -0,0 +1,66 @@
+from collections.abc import Callable
+from typing import Any
+from uuid import UUID
+
+from products.messaging.backend.api import design_operations, design_validation
+from products.messaging.backend.remote_config import (
+ PUSH_APP_ID_CONFIG_KEYS,
+ build_push_config as build_push_app_ids,
+)
+from products.messaging.backend.services import message_templates
+from products.messaging.backend.unlayer import (
+ UnlayerNotConfiguredError,
+ UnlayerRenderError,
+ render_design_html as render_unlayer_design,
+)
+
+__all__ = [
+ "UnlayerNotConfiguredError",
+ "UnlayerRenderError",
+ "apply_design_operations",
+ "build_push_config",
+ "find_template_ids_containing",
+ "get_template_email_content",
+ "is_push_integration_kind",
+ "render_design_html",
+ "rewrite_template_content",
+ "validate_design",
+]
+
+
+def build_push_config(team_id: int) -> dict[str, list[str]]:
+ """The `push` key of the SDK remote config: the app ids the team accepts device registrations for."""
+ return build_push_app_ids(team_id)
+
+
+def is_push_integration_kind(kind: str) -> bool:
+ return kind in PUSH_APP_ID_CONFIG_KEYS
+
+
+def apply_design_operations(design: dict, operations: list[dict]) -> dict:
+ """Raises a DRF ValidationError keyed on `operations` when an operation does not apply."""
+ return design_operations.apply_design_operations(design, operations)
+
+
+def validate_design(design: dict) -> list[str]:
+ return design_validation.validate_design(design)
+
+
+def render_design_html(design: dict[str, Any]) -> str:
+ """Raises UnlayerNotConfiguredError or UnlayerRenderError."""
+ return render_unlayer_design(design)
+
+
+def get_template_email_content(team_id: int, template_id: UUID) -> dict | None:
+ return message_templates.get_email_content(team_id, template_id)
+
+
+def find_template_ids_containing(text: str, *, team_ids: list[int] | None, template_id: str | None) -> list[UUID]:
+ return message_templates.find_ids_containing(text, team_ids=team_ids, template_id=template_id)
+
+
+def rewrite_template_content(
+ template_id: UUID, rewrite: Callable[[Any], tuple[Any, int]], *, team_ids: list[int] | None, dry_run: bool
+) -> int:
+ """Apply `rewrite` to a template's content under a row lock. Returns the number of occurrences it replaced."""
+ return message_templates.rewrite_content(template_id, rewrite, team_ids=team_ids, dry_run=dry_run)
diff --git a/products/messaging/backend/facade/testing.py b/products/messaging/backend/facade/testing.py
new file mode 100644
index 000000000000..8ead0ad4f24d
--- /dev/null
+++ b/products/messaging/backend/facade/testing.py
@@ -0,0 +1,18 @@
+from typing import Any
+from uuid import UUID
+
+from products.messaging.backend.models import MessageCategory, MessageRecipientPreference, MessageTemplate
+
+
+def create_message_category_for_test(*, team_id: int, key: str, name: str) -> UUID:
+ return MessageCategory.objects.create(team_id=team_id, key=key, name=name).id
+
+
+def create_recipient_preference_for_test(*, team_id: int, identifier: str, preferences: dict[str, str]) -> UUID:
+ return MessageRecipientPreference.objects.create(team_id=team_id, identifier=identifier, preferences=preferences).id
+
+
+def create_message_template_for_test(
+ *, team_id: int, name: str, content: dict[str, Any], deleted: bool = False
+) -> UUID:
+ return MessageTemplate.objects.create(team_id=team_id, name=name, content=content, deleted=deleted).id
diff --git a/products/messaging/backend/remote_config.py b/products/messaging/backend/remote_config.py
index f923da38eb66..838639a5ecae 100644
--- a/products/messaging/backend/remote_config.py
+++ b/products/messaging/backend/remote_config.py
@@ -1,5 +1,4 @@
from posthog.models.integration import Integration
-from posthog.models.team.team import Team
# Firebase identifies an app by its project_id, APNs by its bundle_id. Kept in step with
# _find_integrations in products/messaging/backend/api/push_subscriptions.py, which resolves the same
@@ -7,7 +6,7 @@ from posthog.models.team.team import Team
PUSH_APP_ID_CONFIG_KEYS = {"firebase": "project_id", "apns": "bundle_id"}
-def build_push_config(team: Team) -> dict:
+def build_push_config(team_id: int) -> dict[str, list[str]]:
"""The app_ids this team can accept device registrations for.
Mobile SDKs register a device token on launch whenever push capture is on, and the registration
@@ -17,7 +16,9 @@ def build_push_config(team: Team) -> dict:
Always present, including as an empty list. An SDK cannot tell an unconfigured project from an
older server that never sends the key, so absent has to keep meaning "attempt the registration".
"""
- integrations = Integration.objects.filter(team=team, kind__in=list(PUSH_APP_ID_CONFIG_KEYS)).only("kind", "config")
+ integrations = Integration.objects.filter(team_id=team_id, kind__in=list(PUSH_APP_ID_CONFIG_KEYS)).only(
+ "kind", "config"
+ )
# config is a JSONField, so an identifier can be any JSON value. Anything but a non-empty string is
# unusable as an app_id, and letting one through would raise inside the set or the sort — which
# aborts build_config and leaves the team's whole remote config stale, not just its push key.
diff --git a/products/messaging/backend/services/message_templates.py b/products/messaging/backend/services/message_templates.py
new file mode 100644
index 000000000000..b2e9e8fdc0d9
--- /dev/null
+++ b/products/messaging/backend/services/message_templates.py
@@ -0,0 +1,50 @@
+from collections.abc import Callable
+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
+
+
+def get_email_content(team_id: int, template_id: UUID) -> dict | None:
+ template = MessageTemplate.objects.filter(team_id=team_id, id=template_id, deleted=False).first()
+ email_content = (template.content or {}).get("email") if template else None
+ return email_content if isinstance(email_content, dict) else None
+
+
+def _templates(team_ids: list[int] | None) -> models.QuerySet[MessageTemplate]:
+ queryset = MessageTemplate.objects.all()
+ return queryset.filter(team_id__in=team_ids) if team_ids else queryset
+
+
+def find_ids_containing(text: str, *, team_ids: list[int] | None, template_id: str | None) -> list[UUID]:
+ queryset = _templates(team_ids)
+ if template_id:
+ queryset = queryset.filter(id=template_id)
+ # The text cast stays in the WHERE clause, so the scan never returns a full copy of each content blob.
+ return list(
+ queryset.annotate(_text_content=Cast("content", models.TextField()))
+ .filter(_text_content__contains=text)
+ .order_by("id")
+ .values_list("id", flat=True)
+ )
+
+
+def rewrite_content(
+ template_id: UUID, rewrite: Callable[[Any], tuple[Any, int]], *, team_ids: list[int] | None, dry_run: bool
+) -> int:
+ if dry_run:
+ return rewrite(_templates(team_ids).get(pk=template_id).content)[1]
+
+ # Read the row again under a row lock, so a concurrent save is not overwritten with a stale blob.
+ with transaction.atomic():
+ template = _templates(team_ids).select_for_update().get(pk=template_id)
+ new_content, occurrences = rewrite(template.content)
+ if not occurrences:
+ return 0
+ template.content = new_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
diff --git a/products/messaging/backend/tasks/__init__.py b/products/messaging/backend/tasks/__init__.py
new file mode 100644
index 000000000000..f300c640b0a2
--- /dev/null
+++ b/products/messaging/backend/tasks/__init__.py
@@ -0,0 +1,2 @@
+from products.messaging.backend.tasks.tasks import * # noqa: F401,F403
+from products.messaging.backend.tasks.tasks import sync_preferences_to_customerio_task # noqa: F401
diff --git a/products/messaging/backend/tasks.py b/products/messaging/backend/tasks/tasks.py
similarity index 89%
rename from products/messaging/backend/tasks.py
rename to products/messaging/backend/tasks/tasks.py
index 5e9e082695d9..f6e63fe224a6 100644
--- a/products/messaging/backend/tasks.py
+++ b/products/messaging/backend/tasks/tasks.py
@@ -6,7 +6,7 @@ from products.messaging.backend.models.message_preferences import MessageRecipie
from products.messaging.backend.services.customerio_sync_service import sync_preferences_to_customerio
-@shared_task(ignore_result=True)
+@shared_task(ignore_result=True, name="products.messaging.backend.tasks.sync_preferences_to_customerio_task")
@skip_team_scope_audit # MessageRecipientPreference is still on the default manager
def sync_preferences_to_customerio_task(team_id: int, identifier: str) -> None:
"""Push a recipient's current preference state to Customer.io off the request path.
diff --git a/products/messaging/backend/tests/test_remote_config.py b/products/messaging/backend/tests/test_remote_config.py
index d4c608460c72..66e24aae6f24 100644
--- a/products/messaging/backend/tests/test_remote_config.py
+++ b/products/messaging/backend/tests/test_remote_config.py
@@ -4,7 +4,7 @@ from parameterized import parameterized
from posthog.models.integration import Integration
-from products.messaging.backend.remote_config import build_push_config
+from products.messaging.backend.facade.api import build_push_config
class TestBuildPushConfig(BaseTest):
@@ -30,4 +30,4 @@ class TestBuildPushConfig(BaseTest):
for kind, config in integrations:
Integration.objects.create(team=self.team, kind=kind, config=config)
- assert build_push_config(self.team) == {"appIds": expected_app_ids}
+ assert build_push_config(self.team.id) == {"appIds": expected_app_ids}
diff --git a/products/workflows/backend/management/commands/rewrite_email_asset_url.py b/products/workflows/backend/management/commands/rewrite_email_asset_url.py
index 31bf92448556..d2ea0c5c30c1 100644
--- a/products/workflows/backend/management/commands/rewrite_email_asset_url.py
+++ b/products/workflows/backend/management/commands/rewrite_email_asset_url.py
@@ -12,13 +12,14 @@ from django.utils import timezone
from posthog.plugins.plugin_server_api import reload_hog_flows_on_workers, reload_hog_functions_on_workers
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
-from products.messaging.backend.models.message_template import MessageTemplate
+from products.messaging.backend.facade.api import find_template_ids_containing, rewrite_template_content
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.hog_flow.hog_flow_template import HogFlowTemplate
logger = logging.getLogger(__name__)
WorkerReload = Callable[[int, str], None]
+RowRewrite = Callable[[Any], int]
# Only executed config has a worker-side cache to invalidate; templates are copied at creation time
# and never read by a worker, so they need no reload.
@@ -33,12 +34,14 @@ WORKER_RELOADS: Final[dict[str, WorkerReload]] = {
# `actions`/`inputs` carry both the editable value (html, design) and the compiled hog bytecode the
# executor renders from when an input isn't liquid, so a rewrite has to cover the whole blob -
# fixing only value.html would leave those sends unchanged.
-TARGETS: Final[dict[str, tuple[type[models.Model], dict[str, str]]]] = {
+MODEL_TARGETS: Final[dict[str, tuple[type[models.Model], dict[str, str]]]] = {
"hog_flows": (HogFlow, {"actions": "updated_at", "draft": "draft_updated_at"}),
"hog_flow_templates": (HogFlowTemplate, {"actions": "updated_at"}),
- "message_templates": (MessageTemplate, {"content": "updated_at"}),
"hog_functions": (HogFunction, {"inputs": "updated_at", "draft": "draft_updated_at"}),
}
+# Message templates belong to messaging, which finds and rewrites its own rows (content, updated_at).
+MESSAGE_TEMPLATES: Final = "message_templates"
+TARGETS: Final[tuple[str, ...]] = ("hog_flows", "hog_flow_templates", MESSAGE_TEMPLATES, "hog_functions")
@dataclass(frozen=False)
@@ -146,30 +149,12 @@ class Command(BaseCommand):
raise CommandError(f"{totals.errors} row(s) failed to rewrite - see the errors above and re-run")
def _process_target(self, target: str, from_url: str, to_url: str, options: dict[str, Any]) -> RewriteCounts:
- model, field_timestamps = TARGETS[target]
- fields = tuple(field_timestamps)
counts = RewriteCounts()
+ if target == MESSAGE_TEMPLATES:
+ row_ids, rewrite_row = self._message_template_rows(from_url, to_url, options)
+ else:
+ row_ids, rewrite_row = self._model_rows(target, from_url, to_url, options)
- # _default_manager, not .objects: the loop is generic over four models, and Model itself
- # doesn't declare a manager. unscoped() where it exists - a fix like this is deliberately
- # cross-team, so a fail-closed manager would otherwise raise TeamScopeError.
- manager = model._default_manager
- base_queryset = manager.unscoped() if hasattr(manager, "unscoped") else manager.all()
- if options.get("team_id"):
- base_queryset = base_queryset.filter(team_id__in=options["team_id"])
- if options.get("row_id"):
- base_queryset = base_queryset.filter(id=options["row_id"])
-
- # The text casts belong only on the id-matching query, where they stay in the WHERE clause.
- # Loading rows off the un-annotated base queryset avoids the database returning a full text
- # copy of every large JSON column alongside the value we actually rewrite.
- matcher = base_queryset
- match = models.Q()
- for field in fields:
- matcher = matcher.annotate(**{f"_text_{field}": Cast(field, models.TextField())})
- match |= models.Q(**{f"_text_{field}__contains": from_url})
-
- row_ids = list(matcher.filter(match).order_by("id").values_list("id", flat=True))
self.stdout.write(f"{target}: {len(row_ids)} row(s) matched")
if not row_ids:
return counts
@@ -180,15 +165,7 @@ class Command(BaseCommand):
for row_id in batch:
counts.rows_scanned += 1
try:
- occurrences = self._rewrite_row(
- base_queryset,
- row_id,
- field_timestamps,
- WORKER_RELOADS.get(target),
- from_url,
- to_url,
- dry_run=options["dry_run"],
- )
+ occurrences = rewrite_row(row_id)
except Exception as e:
counts.errors += 1
logger.exception("Failed to rewrite %s %s: %s", target, row_id, e)
@@ -202,6 +179,62 @@ class Command(BaseCommand):
return counts
+ def _message_template_rows(
+ self, from_url: str, to_url: str, options: dict[str, Any]
+ ) -> tuple[list[Any], RowRewrite]:
+ team_ids: list[int] | None = options.get("team_id")
+ row_ids = find_template_ids_containing(from_url, team_ids=team_ids, template_id=options.get("row_id"))
+
+ def rewrite_row(row_id: Any) -> int:
+ return rewrite_template_content(
+ row_id,
+ lambda blob: rewrite_blob(blob, from_url, to_url),
+ team_ids=team_ids,
+ dry_run=options["dry_run"],
+ )
+
+ return row_ids, rewrite_row
+
+ def _model_rows(
+ self, target: str, from_url: str, to_url: str, options: dict[str, Any]
+ ) -> tuple[list[Any], RowRewrite]:
+ model, field_timestamps = MODEL_TARGETS[target]
+ fields = tuple(field_timestamps)
+
+ # _default_manager, not .objects: the loop is generic over the model targets, and Model itself
+ # doesn't declare a manager. unscoped() where it exists - a fix like this is deliberately
+ # cross-team, so a fail-closed manager would otherwise raise TeamScopeError.
+ manager = model._default_manager
+ base_queryset = manager.unscoped() if hasattr(manager, "unscoped") else manager.all()
+ if options.get("team_id"):
+ base_queryset = base_queryset.filter(team_id__in=options["team_id"])
+ if options.get("row_id"):
+ base_queryset = base_queryset.filter(id=options["row_id"])
+
+ # The text casts belong only on the id-matching query, where they stay in the WHERE clause.
+ # Loading rows off the un-annotated base queryset avoids the database returning a full text
+ # copy of every large JSON column alongside the value we actually rewrite.
+ matcher = base_queryset
+ match = models.Q()
+ for field in fields:
+ matcher = matcher.annotate(**{f"_text_{field}": Cast(field, models.TextField())})
+ match |= models.Q(**{f"_text_{field}__contains": from_url})
+
+ row_ids = list(matcher.filter(match).order_by("id").values_list("id", flat=True))
+
+ def rewrite_row(row_id: Any) -> int:
+ return self._rewrite_row(
+ base_queryset,
+ row_id,
+ field_timestamps,
+ WORKER_RELOADS.get(target),
+ from_url,
+ to_url,
+ dry_run=options["dry_run"],
+ )
+
+ return row_ids, rewrite_row
+
def _rewrite_row(
self,
base_queryset: models.QuerySet,
diff --git a/products/workflows/backend/services/hog_flow_email_design.py b/products/workflows/backend/services/hog_flow_email_design.py
index cd2f2ed6b59b..9f806c91ba64 100644
--- a/products/workflows/backend/services/hog_flow_email_design.py
+++ b/products/workflows/backend/services/hog_flow_email_design.py
@@ -1,9 +1,13 @@
from uuid import UUID
-from products.messaging.backend.api.design_operations import apply_design_operations
-from products.messaging.backend.api.design_validation import validate_design
-from products.messaging.backend.models import MessageTemplate
-from products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_html
+from products.messaging.backend.facade.api import (
+ UnlayerNotConfiguredError,
+ UnlayerRenderError,
+ apply_design_operations,
+ get_template_email_content,
+ render_design_html,
+ validate_design,
+)
from products.workflows.backend.facade.contracts import (
EditedEmailDesign,
EmailDesignRenderFailed,
@@ -12,9 +16,7 @@ from products.workflows.backend.facade.contracts import (
def get_email_template_content(team_id: int, template_id: UUID) -> dict | None:
- template = MessageTemplate.objects.filter(team_id=team_id, id=template_id, deleted=False).first()
- email_content = (template.content or {}).get("email") if template else None
- return email_content if isinstance(email_content, dict) else None
+ return get_template_email_content(team_id, template_id)
def apply_email_design_operations(design: dict, operations: list[dict]) -> EditedEmailDesign:
diff --git a/products/workflows/backend/test/test_rewrite_email_asset_url.py b/products/workflows/backend/test/test_rewrite_email_asset_url.py
index acdae9979512..a154f7eb3a14 100644
--- a/products/workflows/backend/test/test_rewrite_email_asset_url.py
+++ b/products/workflows/backend/test/test_rewrite_email_asset_url.py
@@ -10,6 +10,8 @@ from parameterized import parameterized
from posthog.models import Team
+from products.messaging.backend.facade.api import get_template_email_content
+from products.messaging.backend.facade.testing import create_message_template_for_test
from products.workflows.backend.management.commands import rewrite_email_asset_url
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
@@ -103,6 +105,9 @@ class TestRewriteEmailAssetUrl(BaseTest):
def test_rewrites_only_the_named_team(self) -> None:
mine = self._flow(self.team, "mine")
theirs = self._flow(self.other_team, "theirs")
+ content = {"email": {"html": f'<img src="{OLD}?w=960px" />'}}
+ my_template = create_message_template_for_test(team_id=self.team.id, name="mine", content=content)
+ their_template = create_message_template_for_test(team_id=self.other_team.id, name="theirs", content=content)
call_command("rewrite_email_asset_url", "--from-url", OLD, "--to-url", NEW, "--team-id", str(self.team.id))
@@ -111,6 +116,8 @@ class TestRewriteEmailAssetUrl(BaseTest):
assert NEW in json.dumps(mine.actions)
assert OLD not in json.dumps(mine.actions)
assert OLD in json.dumps(theirs.actions)
+ assert get_template_email_content(self.team.id, my_template) == {"html": f'<img src="{NEW}?w=960px" />'}
+ assert get_template_email_content(self.other_team.id, their_template) == content["email"]
def test_preserves_query_suffixes_and_is_idempotent(self) -> None:
flow = self._flow(self.team, "mine")
diff --git a/products/workflows/backend/tests/api/test_hog_flow_action_email.py b/products/workflows/backend/tests/api/test_hog_flow_action_email.py
index 89d9a0d695b8..6e22be068786 100644
--- a/products/workflows/backend/tests/api/test_hog_flow_action_email.py
+++ b/products/workflows/backend/tests/api/test_hog_flow_action_email.py
@@ -1,4 +1,5 @@
from copy import deepcopy
+from uuid import UUID
from posthog.test.base import APIBaseTest
from unittest.mock import patch
@@ -8,8 +9,8 @@ from parameterized import parameterized
from posthog.cdp.templates.hog_function_template import sync_template_to_db
from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
-from products.messaging.backend.models import MessageTemplate
-from products.messaging.backend.unlayer import UnlayerRenderError
+from products.messaging.backend.facade.api import UnlayerRenderError
+from products.messaging.backend.facade.testing import create_message_template_for_test
from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
@@ -382,17 +383,17 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
super().setUp()
sync_template_to_db(_email_function_template())
- def _create_library_template(self, **overrides) -> MessageTemplate:
+ def _create_library_template(self, html: str = "<p>Library html</p>", deleted: bool = False) -> UUID:
content = {
"templating": "liquid",
"email": {
"subject": "Library subject",
"text": "Library text",
- "html": "<p>Library html</p>",
+ "html": html,
"design": _design(),
},
}
- return MessageTemplate.objects.create(team=self.team, name="Welcome", content=content, **overrides)
+ return create_message_template_for_test(team_id=self.team.id, name="Welcome", content=content, deleted=deleted)
def _post_flow(self, email_config: dict, mcp: bool = True):
flow = {
@@ -413,11 +414,11 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
# The incremental authoring path: reference a saved template plus the two step-level
# keys, get a complete email step, then iterate with the surgical patch endpoint —
# previously the whole email object had to be authored in a single graph operation.
- template = self._create_library_template()
+ template_id = self._create_library_template()
response = self._post_flow(
{
"template_id": "template-email",
- "template_uuid": str(template.id),
+ "template_uuid": str(template_id),
"inputs": {"email": {"value": {"from": "[email protected]", "to": "{{ person.properties.email }}"}}},
}
)
@@ -430,7 +431,7 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
assert stored["design"] == _design()
assert stored["from"] == "[email protected]"
config = next(a for a in flow.actions if a["id"] == "email_1")["config"]
- assert config["template_uuid"] == str(template.id)
+ assert config["template_uuid"] == str(template_id)
patch_response = self.client.patch(
f"/api/projects/{self.team.id}/hog_flows/{flow.pk}/actions/email_1/email",
@@ -443,10 +444,10 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
# The dominant authoring mistake puts the library UUID in template_id. The fixed-id
# coercion moves it into template_uuid; materialization must run after that move so
# the mistaken-but-resolvable reference still produces a complete step in one save.
- template = self._create_library_template()
+ template_id = self._create_library_template()
response = self._post_flow(
{
- "template_id": str(template.id),
+ "template_id": str(template_id),
"inputs": {"email": {"value": {"from": "[email protected]", "to": "{{ person.properties.email }}"}}},
}
)
@@ -456,18 +457,18 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
"config"
]
assert config["template_id"] == "template-email"
- assert config["template_uuid"] == str(template.id)
+ assert config["template_uuid"] == str(template_id)
assert config["inputs"]["email"]["value"]["subject"] == "Library subject"
def test_falsy_body_placeholders_do_not_clobber_template_content(self):
# Agents emit explicit null/empty placeholders for fields they aren't setting. The
# materialization decision ignores falsy body keys, so the merge must too - otherwise
# a subject: null placeholder erases the template's subject it just resolved.
- template = self._create_library_template()
+ template_id = self._create_library_template()
response = self._post_flow(
{
"template_id": "template-email",
- "template_uuid": str(template.id),
+ "template_uuid": str(template_id),
"inputs": {
"email": {
"value": {
@@ -489,11 +490,11 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
def test_caller_authored_body_wins_over_template_reference(self):
# Any caller-supplied body key means the caller owns the whole body; merging template
# content underneath it would mix two different emails.
- template = self._create_library_template()
+ template_id = self._create_library_template()
response = self._post_flow(
{
"template_id": "template-email",
- "template_uuid": str(template.id),
+ "template_uuid": str(template_id),
"inputs": {
"email": {
"value": {
@@ -518,7 +519,7 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
deleted = self._create_library_template(deleted=True)
for _name, template_uuid in [
("unknown", "0199aabb-ccdd-0000-1122-334455667788"),
- ("deleted", str(deleted.id)),
+ ("deleted", str(deleted)),
("malformed", "not-a-uuid"),
]:
response = self._post_flow(
@@ -534,8 +535,8 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
def test_template_reference_still_requires_from_and_to(self):
# The template supplies only the body; the step-level keys stay the caller's job and
# the validator names exactly what's left to add.
- template = self._create_library_template()
- response = self._post_flow({"template_id": "template-email", "template_uuid": str(template.id)})
+ template_id = self._create_library_template()
+ response = self._post_flow({"template_id": "template-email", "template_uuid": str(template_id)})
assert response.status_code == 400, response.json()
assert "'from'" in response.json()["detail"], response.json()
@@ -553,12 +554,10 @@ class TestHogFlowEmailTemplateReference(APIBaseTest):
# Each body-less reference expands server-side, so without a cumulative cap a small
# request with many steps referencing one large template amplifies into an oversized
# write. Each step here is under the cap on its own; only the running total crosses it.
- template = self._create_library_template()
- template.content["email"]["html"] = "<p>" + "x" * 5000 + "</p>"
- template.save()
+ template_id = self._create_library_template(html="<p>" + "x" * 5000 + "</p>")
email_config = {
"template_id": "template-email",
- "template_uuid": str(template.id),
+ "template_uuid": str(template_id),
"inputs": {"email": {"value": {"from": "[email protected]", "to": "[email protected]"}}},
}
flow = {