: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 Customer.io sync setup behind the facade (#114021)
Harley Alexander3bf714d001d9
diff --git a/products/messaging/backend/facade/customerio.py b/products/messaging/backend/facade/customerio.pynew file mode 100644index 000000000000..0ea5c0a28eb2--- /dev/null+++ b/products/messaging/backend/facade/customerio.py@@ -0,0 +1,99 @@+"""Customer.io sync setup: the App API import, the inbound webhook, the outbound Track API, and the CSV import."""++from typing import IO, Any++from posthog.dataclasses import frozen++from products.messaging.backend.services import customerio_config+++class CustomerIOConfigConflict(Exception):+ """An integration of that kind already exists. The message tells the caller to delete it first."""+++class CustomerIOConfigIncomplete(Exception):+ """The request lacks a credential the change needs. The message names it."""+++@frozen+class SyncConfigState:+ app_integration_id: int | None+ app_import_result: dict[str, Any] | None+ csv_import_result: dict[str, Any] | None+ webhook_enabled: bool+ has_webhook_secret: bool+ track_enabled: bool+ has_track_credentials: bool+++@frozen+class WebhookConfigState:+ webhook_enabled: bool+ has_webhook_secret: bool+++@frozen+class TrackConfigState:+ track_enabled: bool+ has_track_credentials: bool+++def import_from_customerio(team_id: int, app_api_key: str | None, created_by_id: int | None) -> dict[str, Any]:+ """Import topics and global unsubscribes from the App API. Stores the key on first use.++ Returns the import result as the API serves it. Raises CustomerIOConfigIncomplete without a key,+ and CustomerIOConfigConflict when a stored key exists and a new one is sent.+ """+ try:+ return customerio_config.import_from_customerio(team_id, app_api_key, created_by_id)+ except customerio_config.ConfigIncomplete as e:+ raise CustomerIOConfigIncomplete(str(e)) from e+ except customerio_config.ConfigConflict as e:+ raise CustomerIOConfigConflict(str(e)) from e+++def get_sync_config_state(team_id: int) -> SyncConfigState:+ return SyncConfigState(**customerio_config.sync_config_state(team_id))+++def remove_app_config(team_id: int) -> None:+ customerio_config.remove_app_config(team_id)+++def save_webhook_config(+ team_id: int, signing_secret: str | None, enabled: bool, created_by_id: int | None+) -> WebhookConfigState:+ """Store the signing secret on first use, and turn the inbound webhook on or off."""+ try:+ saved = customerio_config.save_webhook_config(team_id, signing_secret, enabled, created_by_id)+ except customerio_config.ConfigIncomplete as e:+ raise CustomerIOConfigIncomplete(str(e)) from e+ except customerio_config.ConfigConflict as e:+ raise CustomerIOConfigConflict(str(e)) from e+ return WebhookConfigState(webhook_enabled=saved.enabled, has_webhook_secret=saved.has_credentials)+++def remove_webhook_config(team_id: int) -> None:+ customerio_config.remove_webhook_config(team_id)+++def save_track_config(+ team_id: int, site_id: str | None, api_key: str | None, region: str, enabled: bool, created_by_id: int | None+) -> TrackConfigState:+ """Store the Track API credentials on first use, and turn outbound sync on or off."""+ try:+ saved = customerio_config.save_track_config(team_id, site_id, api_key, region, enabled, created_by_id)+ except customerio_config.ConfigIncomplete as e:+ raise CustomerIOConfigIncomplete(str(e)) from e+ except customerio_config.ConfigConflict as e:+ raise CustomerIOConfigConflict(str(e)) from e+ return TrackConfigState(track_enabled=saved.enabled, has_track_credentials=saved.has_credentials)+++def remove_track_config(team_id: int) -> None:+ customerio_config.remove_track_config(team_id)+++def import_preferences_csv(team_id: int, csv_file: IO[bytes], created_by_id: int | None) -> dict[str, Any]:+ """Import recipient preferences from a Customer.io CSV export. Returns the result as the API serves it."""+ return customerio_config.import_preferences_csv(team_id, csv_file, created_by_id)diff --git a/products/messaging/backend/presentation/views/message_categories.py b/products/messaging/backend/presentation/views/message_categories.pyindex 3138dcdd075e..1e3253746c16 100644--- a/products/messaging/backend/presentation/views/message_categories.py+++ b/products/messaging/backend/presentation/views/message_categories.py@@ -1,17 +1,28 @@-from django.utils import timezone-from rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.parsers import FormParser, MultiPartParserfrom rest_framework.response import Response+from rest_framework_dataclasses.serializers import DataclassSerializerfrom posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.models.integration import Integration+from products.messaging.backend.facade.customerio import (+ CustomerIOConfigConflict,+ CustomerIOConfigIncomplete,+ SyncConfigState,+ TrackConfigState,+ WebhookConfigState,+ get_sync_config_state,+ import_from_customerio,+ import_preferences_csv,+ remove_app_config,+ remove_track_config,+ remove_webhook_config,+ save_track_config,+ save_webhook_config,+)from products.messaging.backend.models.message_category import MessageCategory-from products.messaging.backend.models.optout_sync_config import OptOutSyncConfig-from products.messaging.backend.services.customerio_import_service import CustomerIOImportServiceclass MessageCategorySerializer(serializers.ModelSerializer):@@ -58,6 +69,21 @@ class CustomerIOImportSerializer(serializers.Serializer):app_api_key = serializers.CharField(required=True, help_text="Customer.io App API Key")+class SyncConfigStateSerializer(DataclassSerializer):+ class Meta:+ dataclass = SyncConfigState+++class WebhookConfigStateSerializer(DataclassSerializer):+ class Meta:+ dataclass = WebhookConfigState+++class TrackConfigStateSerializer(DataclassSerializer):+ class Meta:+ dataclass = TrackConfigState++class MessageCategoryViewSet(TeamAndOrgViewSetMixin,ForbidDestroyModel,@@ -80,57 +106,12 @@ class MessageCategoryViewSet(Persists the App API key in Integration(kind="customerio-app").If no app_api_key is provided, reuses the stored Integration key."""- integration = Integration.objects.filter(team_id=self.team_id, kind="customerio-app").first()- api_key = request.data.get("app_api_key") or (- integration.sensitive_config.get("app_api_key") if integration else None- )-- if not api_key:- return Response(- {"error": "No API key provided and no stored key found."}, status=status.HTTP_400_BAD_REQUEST- )-- if integration and request.data.get("app_api_key"):- return Response(- {"error": "Integration already exists. Delete it first to use a different key."},- status=status.HTTP_409_CONFLICT,- )-- if not integration:- integration = Integration.objects.create(- team_id=self.team_id,- kind="customerio-app",- sensitive_config={"app_api_key": api_key},- created_by=request.user,- errors="",- )-- config, _ = OptOutSyncConfig.objects.get_or_create(team_id=self.team_id)- config.app_integration = integration- config.save(update_fields=["app_integration"])-- # Create import service- import_service = CustomerIOImportService(team=self.team, api_key=api_key, user=request.user)-- # Run import synchronously- result = import_service.import_api_data()-- # Persist import result (success or failure)- if result.get("status") == "completed":- config.app_import_result = {- "status": "completed",- "imported_at": timezone.now().isoformat(),- "categories_created": result.get("categories_created", 0),- "globally_unsubscribed_count": result.get("globally_unsubscribed_count", 0),- }- else:- errors = result.get("errors", [])- config.app_import_result = {- "status": "failed",- "imported_at": timezone.now().isoformat(),- "error": ", ".join(errors) if errors else "Import failed",- }- config.save(update_fields=["app_import_result"])+ try:+ result = import_from_customerio(self.team_id, request.data.get("app_api_key"), request.user.id)+ except CustomerIOConfigIncomplete as e:+ return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)+ except CustomerIOConfigConflict as e:+ return Response({"error": str(e)}, status=status.HTTP_409_CONFLICT)# Return the result directlyreturn Response(result, status=status.HTTP_200_OK)@@ -141,57 +122,13 @@ class MessageCategoryViewSet(Get the Customer.io sync configuration state for this team.Used by the frontend to derive step completion."""- try:- config = OptOutSyncConfig.objects.select_related(- "app_integration",- "webhook_integration",- "track_integration",- ).get(team_id=self.team_id)- except OptOutSyncConfig.DoesNotExist:- return Response(- {- "app_integration_id": None,- "app_import_result": None,- "csv_import_result": None,- "webhook_enabled": False,- "has_webhook_secret": False,- "track_enabled": False,- "has_track_credentials": False,- },- status=status.HTTP_200_OK,- )-- return Response(- {- "app_integration_id": config.app_integration.id if config.app_integration else None,- "app_import_result": config.app_import_result,- "csv_import_result": config.csv_import_result,- "webhook_enabled": config.webhook_enabled,- "has_webhook_secret": bool(- config.webhook_integration- and config.webhook_integration.sensitive_config.get("webhook_signing_secret")- ),- "track_enabled": config.track_enabled,- "has_track_credentials": bool(- config.track_integration- and config.track_integration.sensitive_config.get("site_id")- and config.track_integration.sensitive_config.get("api_key")- ),- },- status=status.HTTP_200_OK,- )+ state = get_sync_config_state(self.team_id)+ return Response(SyncConfigStateSerializer(state).data, status=status.HTTP_200_OK)@action(detail=False, methods=["delete"])def remove_customerio_app_config(self, request, **kwargs):"""Remove the Customer.io App API integration and reset import state."""- Integration.objects.filter(team_id=self.team_id, kind="customerio-app").delete()- try:- config = OptOutSyncConfig.objects.get(team_id=self.team_id)- config.app_integration = None- config.app_import_result = None- config.save(update_fields=["app_integration", "app_import_result"])- except OptOutSyncConfig.DoesNotExist:- pass+ remove_app_config(self.team_id)return Response(status=status.HTTP_204_NO_CONTENT)@action(detail=False, methods=["post"])@@ -206,54 +143,19 @@ class MessageCategoryViewSet(signing_secret = request.data.get("webhook_signing_secret")enabled = bool(request.data.get("webhook_enabled", False))- integration = Integration.objects.filter(team_id=self.team_id, kind="customerio-webhook").first()-- if integration and signing_secret:- return Response(- {"error": "Integration already exists. Delete it first to use a different secret."},- status=status.HTTP_409_CONFLICT,- )-- if enabled and not integration and not signing_secret:- return Response(- {"error": "Webhook signing secret is required to enable sync."},- status=status.HTTP_400_BAD_REQUEST,- )+ try:+ state = save_webhook_config(self.team_id, signing_secret, enabled, request.user.id)+ except CustomerIOConfigConflict as e:+ return Response({"error": str(e)}, status=status.HTTP_409_CONFLICT)+ except CustomerIOConfigIncomplete as e:+ return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)- if not integration and signing_secret:- integration = Integration.objects.create(- team_id=self.team_id,- kind="customerio-webhook",- sensitive_config={"webhook_signing_secret": signing_secret},- created_by=request.user,- errors="",- )-- config, _ = OptOutSyncConfig.objects.get_or_create(team_id=self.team_id)- config.webhook_integration = integration- config.webhook_enabled = enabled- config.save(update_fields=["webhook_integration", "webhook_enabled"])-- has_webhook_secret = bool(integration and integration.sensitive_config.get("webhook_signing_secret"))- return Response(- {- "webhook_enabled": enabled,- "has_webhook_secret": has_webhook_secret,- },- status=status.HTTP_200_OK,- )+ return Response(WebhookConfigStateSerializer(state).data, status=status.HTTP_200_OK)@action(detail=False, methods=["delete"])def remove_webhook_config(self, request, **kwargs):"""Remove the Customer.io webhook integration and reset inbound sync state."""- Integration.objects.filter(team_id=self.team_id, kind="customerio-webhook").delete()- try:- config = OptOutSyncConfig.objects.get(team_id=self.team_id)- config.webhook_integration = None- config.webhook_enabled = False- config.save(update_fields=["webhook_integration", "webhook_enabled"])- except OptOutSyncConfig.DoesNotExist:- pass+ remove_webhook_config(self.team_id)return Response(status=status.HTTP_204_NO_CONTENT)@action(detail=False, methods=["post"])@@ -271,59 +173,20 @@ class MessageCategoryViewSet(api_key = request.data.get("api_key")region = request.data.get("region", "us")enabled = bool(request.data.get("track_enabled", False))- has_new_creds = bool(site_id and api_key)-- integration = Integration.objects.filter(team_id=self.team_id, kind="customerio-track").first()- if integration and has_new_creds:- return Response(- {"error": "Integration already exists. Delete it first to use different credentials."},- status=status.HTTP_409_CONFLICT,- )-- if enabled and not integration and not has_new_creds:- return Response(- {"error": "Site ID and API key are required to enable outbound sync."},- status=status.HTTP_400_BAD_REQUEST,- )-- if not integration and has_new_creds:- integration = Integration.objects.create(- team_id=self.team_id,- kind="customerio-track",- sensitive_config={"site_id": site_id, "api_key": api_key},- config={"region": region},- created_by=request.user,- errors="",- )+ try:+ state = save_track_config(self.team_id, site_id, api_key, region, enabled, request.user.id)+ except CustomerIOConfigConflict as e:+ return Response({"error": str(e)}, status=status.HTTP_409_CONFLICT)+ except CustomerIOConfigIncomplete as e:+ return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)- config, _ = OptOutSyncConfig.objects.get_or_create(team_id=self.team_id)- config.track_integration = integration- config.track_enabled = enabled- config.save(update_fields=["track_integration", "track_enabled"])-- has_track_credentials = bool(- integration and integration.sensitive_config.get("site_id") and integration.sensitive_config.get("api_key")- )- return Response(- {- "track_enabled": enabled,- "has_track_credentials": has_track_credentials,- },- status=status.HTTP_200_OK,- )+ return Response(TrackConfigStateSerializer(state).data, status=status.HTTP_200_OK)@action(detail=False, methods=["delete"])def remove_track_config(self, request, **kwargs):"""Remove the Customer.io Track API integration and reset outbound sync state."""- Integration.objects.filter(team_id=self.team_id, kind="customerio-track").delete()- try:- config = OptOutSyncConfig.objects.get(team_id=self.team_id)- config.track_integration = None- config.track_enabled = False- config.save(update_fields=["track_integration", "track_enabled"])- except OptOutSyncConfig.DoesNotExist:- pass+ remove_track_config(self.team_id)return Response(status=status.HTTP_204_NO_CONTENT)@action(detail=False, methods=["post"], parser_classes=[MultiPartParser, FormParser])@@ -349,27 +212,6 @@ class MessageCategoryViewSet(status=status.HTTP_400_BAD_REQUEST,)- import_service = CustomerIOImportService(team=self.team, api_key=None, user=request.user)-- # Process CSV synchronously (should be fast enough for reasonable file sizes)- result = import_service.process_preferences_csv(csv_file)-- config, _ = OptOutSyncConfig.objects.get_or_create(team_id=self.team_id)- if result.get("status") == "completed":- config.csv_import_result = {- "status": "completed",- "imported_at": timezone.now().isoformat(),- "total_rows": result.get("total_rows", 0),- "users_with_optouts": result.get("users_with_optouts", 0),- "users_skipped": result.get("users_skipped", 0),- "parse_errors": result.get("parse_errors", 0),- }- else:- config.csv_import_result = {- "status": "failed",- "imported_at": timezone.now().isoformat(),- "error": result.get("details", "CSV import failed"),- }- config.save(update_fields=["csv_import_result"])+ result = import_preferences_csv(self.team_id, csv_file, request.user.id)return Response(result, status=status.HTTP_200_OK)diff --git a/products/messaging/backend/services/customerio_config.py b/products/messaging/backend/services/customerio_config.pynew file mode 100644index 000000000000..8bacd5780d8d--- /dev/null+++ b/products/messaging/backend/services/customerio_config.py@@ -0,0 +1,228 @@+from typing import IO, Any++from django.utils import timezone++from posthog.dataclasses import frozen+from posthog.models.integration import Integration++from products.messaging.backend.models.optout_sync_config import OptOutSyncConfig+from products.messaging.backend.services.customerio_import_service import CustomerIOImportService+++@frozen+class SavedConfig:+ enabled: bool+ has_credentials: bool+++class ConfigConflict(Exception):+ pass+++class ConfigIncomplete(Exception):+ pass+++def import_from_customerio(team_id: int, app_api_key: str | None, created_by_id: int | None) -> dict[str, Any]:+ integration = Integration.objects.filter(team_id=team_id, kind="customerio-app").first()+ api_key = app_api_key or (integration.sensitive_config.get("app_api_key") if integration else None)++ if not api_key:+ raise ConfigIncomplete("No API key provided and no stored key found.")++ if integration and app_api_key:+ raise ConfigConflict("Integration already exists. Delete it first to use a different key.")++ if not integration:+ integration = Integration.objects.create(+ team_id=team_id,+ kind="customerio-app",+ sensitive_config={"app_api_key": api_key},+ created_by_id=created_by_id,+ errors="",+ )++ config, _ = OptOutSyncConfig.objects.get_or_create(team_id=team_id)+ config.app_integration = integration+ config.save(update_fields=["app_integration"])++ # Run import synchronously+ result = CustomerIOImportService(team_id=team_id, api_key=api_key, created_by_id=created_by_id).import_api_data()++ # Persist import result (success or failure)+ if result.get("status") == "completed":+ config.app_import_result = {+ "status": "completed",+ "imported_at": timezone.now().isoformat(),+ "categories_created": result.get("categories_created", 0),+ "globally_unsubscribed_count": result.get("globally_unsubscribed_count", 0),+ }+ else:+ errors = result.get("errors", [])+ config.app_import_result = {+ "status": "failed",+ "imported_at": timezone.now().isoformat(),+ "error": ", ".join(errors) if errors else "Import failed",+ }+ config.save(update_fields=["app_import_result"])+ return result+++def sync_config_state(team_id: int) -> dict[str, Any]:+ try:+ config = OptOutSyncConfig.objects.select_related(+ "app_integration",+ "webhook_integration",+ "track_integration",+ ).get(team_id=team_id)+ except OptOutSyncConfig.DoesNotExist:+ return {+ "app_integration_id": None,+ "app_import_result": None,+ "csv_import_result": None,+ "webhook_enabled": False,+ "has_webhook_secret": False,+ "track_enabled": False,+ "has_track_credentials": False,+ }++ return {+ "app_integration_id": config.app_integration.id if config.app_integration else None,+ "app_import_result": config.app_import_result,+ "csv_import_result": config.csv_import_result,+ "webhook_enabled": config.webhook_enabled,+ "has_webhook_secret": bool(+ config.webhook_integration and config.webhook_integration.sensitive_config.get("webhook_signing_secret")+ ),+ "track_enabled": config.track_enabled,+ "has_track_credentials": bool(+ config.track_integration+ and config.track_integration.sensitive_config.get("site_id")+ and config.track_integration.sensitive_config.get("api_key")+ ),+ }+++def remove_app_config(team_id: int) -> None:+ Integration.objects.filter(team_id=team_id, kind="customerio-app").delete()+ try:+ config = OptOutSyncConfig.objects.get(team_id=team_id)+ config.app_integration = None+ config.app_import_result = None+ config.save(update_fields=["app_integration", "app_import_result"])+ except OptOutSyncConfig.DoesNotExist:+ pass+++def save_webhook_config(+ team_id: int, signing_secret: str | None, enabled: bool, created_by_id: int | None+) -> SavedConfig:+ integration = Integration.objects.filter(team_id=team_id, kind="customerio-webhook").first()++ if integration and signing_secret:+ raise ConfigConflict("Integration already exists. Delete it first to use a different secret.")++ if enabled and not integration and not signing_secret:+ raise ConfigIncomplete("Webhook signing secret is required to enable sync.")++ if not integration and signing_secret:+ integration = Integration.objects.create(+ team_id=team_id,+ kind="customerio-webhook",+ sensitive_config={"webhook_signing_secret": signing_secret},+ created_by_id=created_by_id,+ errors="",+ )++ config, _ = OptOutSyncConfig.objects.get_or_create(team_id=team_id)+ config.webhook_integration = integration+ config.webhook_enabled = enabled+ config.save(update_fields=["webhook_integration", "webhook_enabled"])++ return SavedConfig(+ enabled=enabled,+ has_credentials=bool(integration and integration.sensitive_config.get("webhook_signing_secret")),+ )+++def remove_webhook_config(team_id: int) -> None:+ Integration.objects.filter(team_id=team_id, kind="customerio-webhook").delete()+ try:+ config = OptOutSyncConfig.objects.get(team_id=team_id)+ config.webhook_integration = None+ config.webhook_enabled = False+ config.save(update_fields=["webhook_integration", "webhook_enabled"])+ except OptOutSyncConfig.DoesNotExist:+ pass+++def save_track_config(+ team_id: int, site_id: str | None, api_key: str | None, region: str, enabled: bool, created_by_id: int | None+) -> SavedConfig:+ has_new_creds = bool(site_id and api_key)+ integration = Integration.objects.filter(team_id=team_id, kind="customerio-track").first()++ if integration and has_new_creds:+ raise ConfigConflict("Integration already exists. Delete it first to use different credentials.")++ if enabled and not integration and not has_new_creds:+ raise ConfigIncomplete("Site ID and API key are required to enable outbound sync.")++ if not integration and has_new_creds:+ integration = Integration.objects.create(+ team_id=team_id,+ kind="customerio-track",+ sensitive_config={"site_id": site_id, "api_key": api_key},+ config={"region": region},+ created_by_id=created_by_id,+ errors="",+ )++ config, _ = OptOutSyncConfig.objects.get_or_create(team_id=team_id)+ config.track_integration = integration+ config.track_enabled = enabled+ config.save(update_fields=["track_integration", "track_enabled"])++ return SavedConfig(+ enabled=enabled,+ has_credentials=bool(+ integration and integration.sensitive_config.get("site_id") and integration.sensitive_config.get("api_key")+ ),+ )+++def remove_track_config(team_id: int) -> None:+ Integration.objects.filter(team_id=team_id, kind="customerio-track").delete()+ try:+ config = OptOutSyncConfig.objects.get(team_id=team_id)+ config.track_integration = None+ config.track_enabled = False+ config.save(update_fields=["track_integration", "track_enabled"])+ except OptOutSyncConfig.DoesNotExist:+ pass+++def import_preferences_csv(team_id: int, csv_file: IO[bytes], created_by_id: int | None) -> dict[str, Any]:+ # Process CSV synchronously (should be fast enough for reasonable file sizes)+ result = CustomerIOImportService(+ team_id=team_id, api_key=None, created_by_id=created_by_id+ ).process_preferences_csv(csv_file)++ config, _ = OptOutSyncConfig.objects.get_or_create(team_id=team_id)+ if result.get("status") == "completed":+ config.csv_import_result = {+ "status": "completed",+ "imported_at": timezone.now().isoformat(),+ "total_rows": result.get("total_rows", 0),+ "users_with_optouts": result.get("users_with_optouts", 0),+ "users_skipped": result.get("users_skipped", 0),+ "parse_errors": result.get("parse_errors", 0),+ }+ else:+ config.csv_import_result = {+ "status": "failed",+ "imported_at": timezone.now().isoformat(),+ "error": result.get("details", "CSV import failed"),+ }+ config.save(update_fields=["csv_import_result"])+ return resultdiff --git a/products/messaging/backend/services/customerio_import_service.py b/products/messaging/backend/services/customerio_import_service.pyindex b590f3894d0a..14c9cb165564 100644--- a/products/messaging/backend/services/customerio_import_service.py+++ b/products/messaging/backend/services/customerio_import_service.py@@ -6,8 +6,6 @@ from typing import Any, Optionalfrom django.db import transaction-from posthog.models import Team-from products.messaging.backend.models.message_category import MessageCategory, MessageCategoryTypefrom products.messaging.backend.models.message_preferences import MessageRecipientPreference, PreferenceStatus@@ -17,9 +15,9 @@ logger = logging.getLogger(__name__)class CustomerIOImportService:- def __init__(self, team: Team, api_key: Optional[str], user):- self.team = team- self.user = user+ def __init__(self, team_id: int, api_key: Optional[str], created_by_id: Optional[int]):+ self.team_id = team_id+ self.created_by_id = created_by_idself.client: Optional[CustomerIOClient] = Noneself.api_key = api_keyself.topic_mapping: dict[str, str] = {} # Maps Customer.io topic IDs to PostHog MessageCategory IDs@@ -230,7 +228,7 @@ class CustomerIOImportService:emails = list(email_to_categories.keys())existing_prefs = {pref.identifier: pref- for pref in MessageRecipientPreference.objects.filter(team_id=self.team.id, identifier__in=emails)+ for pref in MessageRecipientPreference.objects.filter(team_id=self.team_id, identifier__in=emails)}to_create = []@@ -253,7 +251,7 @@ class CustomerIOImportService:}to_create.append(MessageRecipientPreference(- team_id=self.team.id,+ team_id=self.team_id,identifier=email,preferences=preferences_dict,)@@ -295,14 +293,14 @@ class CustomerIOImportService:# Create or update the MessageCategorywith transaction.atomic():category, _ = MessageCategory.objects.update_or_create(- team=self.team,+ team_id=self.team_id,key=topic_key,defaults={"name": topic_name,"description": description,"public_description": public_description,"category_type": category_type,- "created_by": self.user,+ "created_by_id": self.created_by_id,"deleted": False,},)@@ -385,7 +383,7 @@ class CustomerIOImportService:# Fetch existing preferencesexisting_prefs = {pref.identifier: pref- for pref in MessageRecipientPreference.objects.filter(team_id=self.team.id, identifier__in=emails)+ for pref in MessageRecipientPreference.objects.filter(team_id=self.team_id, identifier__in=emails)}to_create = []@@ -405,7 +403,7 @@ class CustomerIOImportService:}to_create.append(MessageRecipientPreference(- team_id=self.team.id,+ team_id=self.team_id,identifier=email,preferences=preferences_dict,)@@ -428,7 +426,7 @@ class CustomerIOImportService:def _load_topic_mapping(self) -> None:"""Load topic mapping from existing categories"""- categories = MessageCategory.objects.filter(team=self.team, key__startswith="customerio_", deleted=False)+ categories = MessageCategory.objects.filter(team_id=self.team_id, key__startswith="customerio_", deleted=False)for category in categories:# Extract topic identifier from key (e.g., "customerio_topic_1" -> "topic_1")diff --git a/products/messaging/backend/services/test_customerio_import_service.py b/products/messaging/backend/services/test_customerio_import_service.pyindex ff5a89758c00..b106e3b699a4 100644--- a/products/messaging/backend/services/test_customerio_import_service.py+++ b/products/messaging/backend/services/test_customerio_import_service.py@@ -13,7 +13,7 @@ class TestCustomerIOImportService(BaseTest):def setUp(self):super().setUp()self.api_key = "test-api-key"- self.service = CustomerIOImportService(self.team, self.api_key, self.user)+ self.service = CustomerIOImportService(self.team.id, self.api_key, self.user.id)def test_process_preferences_csv_complete_flow(self):"""Test complete CSV processing flow with batching"""@@ -186,7 +186,7 @@ [email protected],cio_6,"{""topics"": {""topic_1"": true, ""topic_2"": true}}"[email protected],cio_1,"{""topics"": {""topic_1"": false}}""""# Create service with None API key since CSV doesn't need it- service = CustomerIOImportService(self.team, api_key=None, user=self.user)+ service = CustomerIOImportService(self.team.id, api_key=None, created_by_id=self.user.id)# Process CSV without creating categories firstresult = service.process_preferences_csv(StringIO(csv_content))diff --git a/products/messaging/backend/services/test_customerio_import_service_unit.py b/products/messaging/backend/services/test_customerio_import_service_unit.pyindex c7421f07d2c3..8d0b47d92531 100644--- a/products/messaging/backend/services/test_customerio_import_service_unit.py+++ b/products/messaging/backend/services/test_customerio_import_service_unit.py@@ -13,7 +13,7 @@ class TestCustomerIOImportServiceUnit(SimpleTestCase):self.team = MagicMock()self.user = MagicMock()self.api_key = "test-api-key"- self.service = CustomerIOImportService(self.team, self.api_key, self.user)+ self.service = CustomerIOImportService(self.team.id, self.api_key, self.user.id)@parameterized.expand([@@ -113,7 +113,7 @@ class TestCustomerIOImportServiceUnit(SimpleTestCase):def test_api_import_without_api_key(self):"""Test API import fails when API key is None"""- service = CustomerIOImportService(self.team, api_key=None, user=self.user)+ service = CustomerIOImportService(self.team.id, api_key=None, created_by_id=self.user.id)# Run import without API keyresult = service.import_api_data()diff --git a/products/messaging/backend/tests/api/test_message_categories.py b/products/messaging/backend/tests/api/test_message_categories.pyindex b858d2d40259..e158f6596598 100644--- a/products/messaging/backend/tests/api/test_message_categories.py+++ b/products/messaging/backend/tests/api/test_message_categories.py@@ -209,7 +209,7 @@ class TestMessageCategoryAPI(APIBaseTest):def test_import_preferences_csv_without_categories(self):"""Test CSV import when no categories exist"""with patch(- "products.messaging.backend.presentation.views.message_categories.CustomerIOImportService"+ "products.messaging.backend.services.customerio_config.CustomerIOImportService") as mock_service_class:mock_service = MagicMock()mock_service_class.return_value = mock_service@@ -311,7 +311,7 @@ class TestOptOutSyncConfigAPI(APIBaseTest):self.assertEqual(data["app_import_result"]["categories_created"], 6)self.assertIsNone(data["csv_import_result"])- @patch("products.messaging.backend.presentation.views.message_categories.CustomerIOImportService")+ @patch("products.messaging.backend.services.customerio_config.CustomerIOImportService")def test_import_from_customerio_stores_integration_and_result(self, mock_service_class):mock_service = MagicMock()mock_service_class.return_value = mock_service@@ -340,7 +340,7 @@ class TestOptOutSyncConfigAPI(APIBaseTest):self.assertEqual(config.app_import_result["status"], "completed")self.assertEqual(config.app_import_result["categories_created"], 3)- @patch("products.messaging.backend.presentation.views.message_categories.CustomerIOImportService")+ @patch("products.messaging.backend.services.customerio_config.CustomerIOImportService")def test_import_from_customerio_stores_failure_result(self, mock_service_class):mock_service = MagicMock()mock_service_class.return_value = mock_service@@ -362,7 +362,7 @@ class TestOptOutSyncConfigAPI(APIBaseTest):self.assertEqual(config.app_import_result["status"], "failed")self.assertIn("Invalid API key", config.app_import_result["error"])- @patch("products.messaging.backend.presentation.views.message_categories.CustomerIOImportService")+ @patch("products.messaging.backend.services.customerio_config.CustomerIOImportService")def test_import_from_customerio_reuses_stored_key(self, mock_service_class):Integration.objects.create(team=self.team,@@ -381,7 +381,9 @@ class TestOptOutSyncConfigAPI(APIBaseTest):format="json",)self.assertEqual(response.status_code, status.HTTP_200_OK)- mock_service_class.assert_called_once_with(team=self.team, api_key="stored_key", user=self.user)+ mock_service_class.assert_called_once_with(+ team_id=self.team.id, api_key="stored_key", created_by_id=self.user.id+ )def test_import_from_customerio_fails_without_key(self):response = self.client.post(@@ -528,7 +530,7 @@ class TestOptOutSyncConfigAPI(APIBaseTest):integration = Integration.objects.get(team=self.team, kind="customerio-webhook")self.assertEqual(integration.sensitive_config["webhook_signing_secret"], "secret")- @patch("products.messaging.backend.presentation.views.message_categories.CustomerIOImportService")+ @patch("products.messaging.backend.services.customerio_config.CustomerIOImportService")def test_csv_import_stores_success_result(self, mock_service_class):mock_service = MagicMock()mock_service_class.return_value = mock_service@@ -554,7 +556,7 @@ class TestOptOutSyncConfigAPI(APIBaseTest):self.assertEqual(config.csv_import_result["total_rows"], 100)self.assertEqual(config.csv_import_result["users_with_optouts"], 60)- @patch("products.messaging.backend.presentation.views.message_categories.CustomerIOImportService")+ @patch("products.messaging.backend.services.customerio_config.CustomerIOImportService")def test_csv_import_stores_failure_result(self, mock_service_class):mock_service = MagicMock()mock_service_class.return_value = mock_servicediff --git a/pyproject.toml b/pyproject.tomlindex 9a09a52ce669..e2d57dc3831e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -756,8 +756,6 @@ ignore_imports = ["products.messaging.backend.presentation.views.customerio_webhook -> products.messaging.backend.models.message_preferences","products.messaging.backend.presentation.views.customerio_webhook -> products.messaging.backend.models.optout_sync_config","products.messaging.backend.presentation.views.message_categories -> products.messaging.backend.models.message_category",- "products.messaging.backend.presentation.views.message_categories -> products.messaging.backend.models.optout_sync_config",- "products.messaging.backend.presentation.views.message_categories -> products.messaging.backend.services.customerio_import_service",# 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",