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.

feat(conversations): add zendesk historical ticket import (#67419)

Alex V920e38169b4b
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 721e7e637fce..6a119bbd20c3 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -261,6 +261,7 @@ rules:
|TeamConversationsTeamsConfig
|Ticket
|TicketView
+ |ZendeskImportJob
|ReviewQueue
|ReviewQueueItem
|TraceReview
@@ -537,6 +538,7 @@ rules:
|TeamConversationsTeamsConfig
|Ticket
|TicketView
+ |ZendeskImportJob
|ReviewQueue
|ReviewQueueItem
|TraceReview
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 17335a09ad80..b52ca111175d 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -434,6 +434,7 @@ export const FEATURE_FLAGS = {
PRODUCT_SUPPORT_AI_SUGGESTION: 'product-support-ai-suggestion', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_CREATE_TICKET: 'product-support-create-ticket', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_GITHUB_CHANNEL: 'product-support-github-channel', // owner: @veryayskiy #team-conversations
+ PRODUCT_SUPPORT_IMPORT_TICKETS: 'product-support-import-tickets', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_SIDE_PANEL: 'product-support-side-panel', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_SLACK_NOTIFY_ON_MEMBERS: 'product-support-slack-notify-on-members', // owner: @veryayskiy #team-conversations
PRODUCT_SUPPORT_TEAMS_ENABLED: 'product-support-teams-enabled', // owner: @veryayskiy #team-conversations
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index e10c8fab60cc..bad421b7d967 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -46,6 +46,7 @@ import { AccessControlLevel, AccessControlResourceType, Realm } from '~/types'
import { AISection } from 'products/conversations/frontend/scenes/settings/AISection'
import { GeneralSection } from 'products/conversations/frontend/scenes/settings/GeneralSection'
import { NotificationsSection } from 'products/conversations/frontend/scenes/settings/NotificationsSection'
+import { ZendeskImportSection } from 'products/conversations/frontend/scenes/settings/ZendeskImportSection'
import { CustomerAnalyticsAccountConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/CustomerAnalyticsAccountConfig'
import { CustomerAnalyticsDashboardEvents } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/CustomerAnalyticsDashboardEvents'
import { ExceptionAutocaptureToggle } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings'
@@ -1147,6 +1148,15 @@ export const SETTINGS_MAP: SettingSection[] = [
allowForTeam: (t) => !!t?.conversations_enabled,
keywords: ['ai', 'suggestion', 'auto', 'reply', 'support', 'conversation'],
},
+ {
+ id: 'conversations-imports',
+ title: 'Imports',
+ description: 'Import historical support data from external tools into Conversations.',
+ component: <ZendeskImportSection />,
+ flag: 'PRODUCT_SUPPORT_IMPORT_TICKETS',
+ allowForTeam: (t) => !!t?.conversations_enabled,
+ keywords: ['import', 'zendesk', 'migrate', 'ticket', 'support', 'conversation'],
+ },
],
},
{
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 2f747df67edb..9923f9116d95 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -111,6 +111,7 @@ export type SettingId =
| 'conversations-ai'
| 'conversations-channels'
| 'conversations-general'
+ | 'conversations-imports'
| 'conversations-notifications'
| 'cookieless-server-hash-mode'
| 'core-memory'
diff --git a/products/conversations/backend/api/__init__.py b/products/conversations/backend/api/__init__.py
index 18631be42880..8174f4dfad41 100644
--- a/products/conversations/backend/api/__init__.py
+++ b/products/conversations/backend/api/__init__.py
@@ -1,6 +1,7 @@
from .ticket_views import TicketViewViewSet
from .tickets import TicketViewSet
from .widget import WidgetMessagesView, WidgetMessageView, WidgetTicketsView
+from .zendesk_import import ZendeskImportViewSet
__all__ = [
"TicketViewSet",
@@ -8,4 +9,5 @@ __all__ = [
"WidgetMessageView",
"WidgetMessagesView",
"WidgetTicketsView",
+ "ZendeskImportViewSet",
]
diff --git a/products/conversations/backend/api/tests/test_zendesk_import.py b/products/conversations/backend/api/tests/test_zendesk_import.py
new file mode 100644
index 000000000000..903da4eea545
--- /dev/null
+++ b/products/conversations/backend/api/tests/test_zendesk_import.py
@@ -0,0 +1,104 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import AsyncMock, patch
+
+from rest_framework import status
+
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team import Team
+from posthog.models.utils import generate_random_token_secret
+
+from products.conversations.backend.models import ZendeskImportJob
+
+
+class TestZendeskImportAPI(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.team.conversations_enabled = True
+ self.team.save(update_fields=["conversations_enabled"])
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.client.force_login(self.user)
+
+ def test_status_returns_404_when_no_job(self):
+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/zendesk_imports/status/")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ @patch(
+ "products.conversations.backend.api.zendesk_import.validate_zendesk_credentials",
+ return_value=True,
+ )
+ @patch(
+ "products.conversations.backend.api.zendesk_import.start_zendesk_import_workflow",
+ new_callable=AsyncMock,
+ return_value=("workflow-id", "run-id"),
+ )
+ def test_start_import_creates_job(self, _mock_start, _mock_validate):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/conversations/zendesk_imports/",
+ {
+ "subdomain": "acme",
+ "email_address": "[email protected]",
+ "api_token": generate_random_token_secret(),
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["status"], "running")
+ self.assertTrue(ZendeskImportJob.objects.unscoped().filter(team_id=self.team.id).exists())
+
+ @patch(
+ "products.conversations.backend.api.zendesk_import.validate_zendesk_credentials",
+ return_value=True,
+ )
+ @patch(
+ "products.conversations.backend.api.zendesk_import.start_zendesk_import_workflow",
+ new_callable=AsyncMock,
+ return_value=("workflow-id", "run-id"),
+ )
+ def test_start_import_rejects_duplicate_running_job(self, _mock_start, _mock_validate):
+ ZendeskImportJob.objects.unscoped().create(
+ team_id=self.team.id,
+ status=ZendeskImportJob.Status.RUNNING,
+ job_inputs={"subdomain": "acme", "email_address": "[email protected]", "api_token": "x"},
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/conversations/zendesk_imports/",
+ {
+ "subdomain": "acme",
+ "email_address": "[email protected]",
+ "api_token": generate_random_token_secret(),
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_non_admin_member_cannot_start_or_poll(self):
+ # A plain member of the routed team must not be able to start an import or read status —
+ # the endpoint requires org-admin, not just team membership.
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ post = self.client.post(
+ f"/api/projects/{self.team.id}/conversations/zendesk_imports/",
+ {"subdomain": "acme", "email_address": "[email protected]", "api_token": generate_random_token_secret()},
+ format="json",
+ )
+ self.assertEqual(post.status_code, status.HTTP_403_FORBIDDEN)
+ self.assertFalse(ZendeskImportJob.objects.unscoped().filter(team_id=self.team.id).exists())
+
+ get = self.client.get(f"/api/projects/{self.team.id}/conversations/zendesk_imports/status/")
+ self.assertEqual(get.status_code, status.HTTP_403_FORBIDDEN)
+
+ def test_admin_cannot_target_project_in_another_organization(self):
+ # Being an admin of one org must not authorize importing into a project the user
+ # has no membership in — the gate is scoped to the routed team, not org-wide.
+ other_org = Organization.objects.create(name="other")
+ other_team = Team.objects.create(organization=other_org, name="other", conversations_enabled=True)
+
+ response = self.client.post(
+ f"/api/projects/{other_team.id}/conversations/zendesk_imports/",
+ {"subdomain": "acme", "email_address": "[email protected]", "api_token": generate_random_token_secret()},
+ format="json",
+ )
+ self.assertIn(response.status_code, (status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND))
+ self.assertFalse(ZendeskImportJob.objects.unscoped().filter(team_id=other_team.id).exists())
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index 83febd533872..054dedd5bca8 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -260,6 +260,7 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
"cc_participants",
"github_repo",
"github_issue_number",
+ "zendesk_ticket_id",
"organization_id",
"person",
"tags",
@@ -288,6 +289,7 @@ class TicketSerializer(TaggedItemSerializerMixin, serializers.ModelSerializer):
"cc_participants",
"github_repo",
"github_issue_number",
+ "zendesk_ticket_id",
"organization_id",
"person",
"ai_triage",
diff --git a/products/conversations/backend/api/zendesk_import.py b/products/conversations/backend/api/zendesk_import.py
new file mode 100644
index 000000000000..fe6d0fe3bc90
--- /dev/null
+++ b/products/conversations/backend/api/zendesk_import.py
@@ -0,0 +1,227 @@
+"""Zendesk historical import API for Conversations settings."""
+
+from __future__ import annotations
+
+import asyncio
+
+from django.utils import timezone
+
+import structlog
+from drf_spectacular.utils import extend_schema
+from rest_framework import (
+ serializers,
+ status as drf_status,
+ viewsets,
+)
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+
+from products.conversations.backend.models import EmailChannel, ZendeskImportJob
+from products.conversations.backend.permissions import IsConversationsAdmin
+from products.conversations.backend.temporal.zendesk_import.client import (
+ ZendeskCredentials,
+ validate_zendesk_credentials,
+)
+from products.conversations.backend.temporal.zendesk_import.starter import start_zendesk_import_workflow
+
+logger = structlog.get_logger(__name__)
+
+# Generic, user-safe message stored in `latest_error` and returned to admins. Raw
+# exception strings can carry internal hostnames, query details, or secrets from
+# failing requests, so the real error is logged server-side instead.
+WORKFLOW_START_FAILED_MESSAGE = "Failed to start the import. Please try again or contact support if it persists."
+
+
+class ZendeskImportStartSerializer(serializers.Serializer):
+ subdomain = serializers.CharField(
+ help_text="Zendesk subdomain (e.g. 'acme' from acme.zendesk.com).",
+ max_length=255,
+ )
+ email_address = serializers.EmailField(help_text="Zendesk agent email tied to the API token.")
+ api_token = serializers.CharField(
+ help_text="Zendesk API token with ticket read access.",
+ write_only=True,
+ max_length=500,
+ )
+ default_email_channel_id = serializers.UUIDField(
+ help_text=(
+ "Optional fallback email channel for tickets whose original Zendesk recipient doesn't "
+ "match a configured support address (or isn't an email). Omit or null to leave those "
+ "tickets without an email channel."
+ ),
+ required=False,
+ allow_null=True,
+ )
+
+
+class ZendeskImportErrorSerializer(serializers.Serializer):
+ detail = serializers.CharField(help_text="Human-readable error message.")
+
+
+class ZendeskImportJobSerializer(serializers.ModelSerializer):
+ # Surface only the account-level subdomain so the settings form can show which Zendesk account
+ # was last used. The agent email and API token live in the same encrypted blob but are NEVER
+ # serialized: the email is a personal login that must not leak to other admins. `has_credentials`
+ # lets the UI show "configured" without disclosing the operator's identity.
+ subdomain = serializers.SerializerMethodField(help_text="Zendesk subdomain used for this import job.")
+ has_credentials = serializers.SerializerMethodField(
+ help_text="Whether stored Zendesk credentials exist for this job (the token/email are never returned)."
+ )
+
+ class Meta:
+ model = ZendeskImportJob
+ fields = [
+ "id",
+ "status",
+ "subdomain",
+ "has_credentials",
+ "total_tickets",
+ "processed_tickets",
+ "imported_tickets",
+ "skipped_tickets",
+ "failed_tickets",
+ "started_at",
+ "finished_at",
+ "latest_error",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = fields
+ extra_kwargs = {
+ "id": {"help_text": "Unique identifier for the import job."},
+ "status": {"help_text": "Current job state: pending, running, completed, or failed."},
+ "total_tickets": {"help_text": "Total number of tickets discovered for import."},
+ "processed_tickets": {"help_text": "Number of tickets processed so far."},
+ "imported_tickets": {"help_text": "Number of tickets successfully imported."},
+ "skipped_tickets": {"help_text": "Number of tickets skipped because they were already imported."},
+ "failed_tickets": {"help_text": "Number of tickets that failed to import."},
+ "started_at": {"help_text": "When the import started running."},
+ "finished_at": {"help_text": "When the import reached a terminal state."},
+ "latest_error": {"help_text": "Generic, user-safe error message when the job failed."},
+ "created_at": {"help_text": "When the import job was created."},
+ "updated_at": {"help_text": "When the import job was last updated."},
+ }
+
+ def get_subdomain(self, obj: ZendeskImportJob) -> str | None:
+ return (obj.job_inputs or {}).get("subdomain")
+
+ def get_has_credentials(self, obj: ZendeskImportJob) -> bool:
+ return bool((obj.job_inputs or {}).get("api_token"))
+
+
+class ZendeskImportViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ # Settings-only, admin-gated, session-auth endpoint — not exposed as a public API scope.
+ # IsConversationsAdmin gates on the *routed* team's org admin; the mixin's
+ # TeamMemberAccessPermission additionally enforces membership of the routed project,
+ # so an org admin can't import into a project they can't access.
+ scope_object = "INTERNAL"
+ serializer_class = ZendeskImportJobSerializer
+ permission_classes = [IsConversationsAdmin]
+ # Class-level attr must be unscoped: the fail-closed manager's .all() reads team context
+ # eagerly and there is none at import time. Every per-request read below goes through the
+ # scoped manager instead (the mixin sets canonical team context in initial()), so they filter
+ # by the canonical team id rather than the raw routed id.
+ queryset = ZendeskImportJob.objects.unscoped()
+
+ def safely_get_queryset(self, queryset):
+ return ZendeskImportJob.objects.all().order_by("-created_at")
+
+ @extend_schema(
+ request=ZendeskImportStartSerializer,
+ responses={
+ 201: ZendeskImportJobSerializer,
+ 400: ZendeskImportErrorSerializer,
+ 500: ZendeskImportErrorSerializer,
+ },
+ )
+ def create(self, request: Request, *args, **kwargs) -> Response:
+ team_id = self.team_id
+ if not self.team.conversations_enabled:
+ return Response(
+ {"detail": "Conversations is not enabled for this team"}, status=drf_status.HTTP_400_BAD_REQUEST
+ )
+
+ serializer = ZendeskImportStartSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ data = serializer.validated_data
+
+ # Cheap local checks first — don't probe Zendesk with the submitted credentials when the
+ # request would be rejected anyway.
+ running = ZendeskImportJob.objects.filter(
+ status__in=[ZendeskImportJob.Status.PENDING, ZendeskImportJob.Status.RUNNING],
+ ).exists()
+ if running:
+ return Response(
+ {"detail": "A Zendesk import is already running for this team"},
+ status=drf_status.HTTP_400_BAD_REQUEST,
+ )
+
+ default_email_channel_id = data.get("default_email_channel_id")
+ if (
+ default_email_channel_id is not None
+ and not EmailChannel.objects.filter(team_id=team_id, id=default_email_channel_id).exists()
+ ):
+ return Response(
+ {"detail": "The selected default email channel does not belong to this team"},
+ status=drf_status.HTTP_400_BAD_REQUEST,
+ )
+
+ credentials = ZendeskCredentials(
+ subdomain=data["subdomain"],
+ email_address=data["email_address"],
+ api_token=data["api_token"],
+ )
+ if not validate_zendesk_credentials(credentials):
+ return Response({"detail": "Zendesk rejected the credentials"}, status=drf_status.HTTP_400_BAD_REQUEST)
+
+ job = ZendeskImportJob.objects.create(
+ team_id=team_id,
+ status=ZendeskImportJob.Status.PENDING,
+ job_inputs={
+ "subdomain": credentials.subdomain,
+ "email_address": credentials.email_address,
+ "api_token": credentials.api_token,
+ },
+ )
+
+ try:
+ workflow_id, workflow_run_id = asyncio.run(
+ start_zendesk_import_workflow(
+ job_id=str(job.id),
+ team_id=team_id,
+ default_email_channel_id=(
+ str(default_email_channel_id) if default_email_channel_id is not None else None
+ ),
+ )
+ )
+ job.workflow_id = workflow_id
+ job.workflow_run_id = workflow_run_id
+ job.status = ZendeskImportJob.Status.RUNNING
+ job.started_at = timezone.now()
+ job.save(update_fields=["workflow_id", "workflow_run_id", "status", "started_at", "updated_at"])
+ except Exception:
+ logger.exception("zendesk_import_workflow_start_failed", job_id=str(job.id), team_id=team_id)
+ job.status = ZendeskImportJob.Status.FAILED
+ job.latest_error = WORKFLOW_START_FAILED_MESSAGE
+ job.finished_at = timezone.now()
+ job.save(update_fields=["status", "latest_error", "finished_at", "updated_at"])
+ return Response({"detail": WORKFLOW_START_FAILED_MESSAGE}, status=drf_status.HTTP_500_INTERNAL_SERVER_ERROR)
+
+ return Response(ZendeskImportJobSerializer(job).data, status=drf_status.HTTP_201_CREATED)
+
+ @extend_schema(
+ responses={
+ 200: ZendeskImportJobSerializer,
+ 404: ZendeskImportErrorSerializer,
+ },
+ )
+ @action(detail=False, methods=["get"])
+ def status(self, request: Request, *args, **kwargs) -> Response:
+ job = ZendeskImportJob.objects.order_by("-created_at").first()
+ if job is None:
+ return Response({"detail": "No Zendesk import job found"}, status=drf_status.HTTP_404_NOT_FOUND)
+
+ return Response(ZendeskImportJobSerializer(job).data)
diff --git a/products/conversations/backend/management/commands/migrate_zendesk_tickets.py b/products/conversations/backend/management/commands/migrate_zendesk_tickets.py
new file mode 100644
index 000000000000..59a20e291768
--- /dev/null
+++ b/products/conversations/backend/management/commands/migrate_zendesk_tickets.py
@@ -0,0 +1,128 @@
+"""Start a Zendesk historical import for a team (internal/ops)."""
+
+from __future__ import annotations
+
+import asyncio
+
+from django.core.management.base import BaseCommand, CommandError
+from django.utils import timezone
+
+import structlog
+
+from posthog.models import Team
+
+from products.conversations.backend.api.zendesk_import import WORKFLOW_START_FAILED_MESSAGE
+from products.conversations.backend.models import ZendeskImportJob
+from products.conversations.backend.temporal.zendesk_import.client import (
+ ZendeskCredentials,
+ validate_zendesk_credentials,
+)
+from products.conversations.backend.temporal.zendesk_import.starter import start_zendesk_import_workflow
+
+logger = structlog.get_logger(__name__)
+
+
+class Command(BaseCommand):
+ help = "Import historical Zendesk tickets into Conversations for a team."
+
+ def add_arguments(self, parser) -> None:
+ parser.add_argument("--team-id", type=int, required=True)
+ parser.add_argument("--subdomain", type=str, required=True)
+ parser.add_argument("--email", type=str, required=True)
+ parser.add_argument("--api-token", type=str, required=True)
+ parser.add_argument("--dry-run", action="store_true", default=False)
+ parser.add_argument(
+ "--limit",
+ type=int,
+ default=None,
+ help="Cap total tickets imported (for testing, e.g. 10/100/1000). Omit for a full import.",
+ )
+ parser.add_argument(
+ "--default-email-channel-id",
+ type=str,
+ default=None,
+ help="Fallback EmailChannel id for tickets whose Zendesk recipient doesn't match a "
+ "configured support address. Omit to leave those tickets without an email channel.",
+ )
+ parser.add_argument(
+ "--force",
+ action="store_true",
+ default=False,
+ help="Mark any existing pending/running job for this team as failed before starting. "
+ "Use to recover after a workflow was terminated out-of-band (e.g. killed in the "
+ "Temporal UI), which leaves the DB row stuck 'running'.",
+ )
+
+ def handle(self, *args, **options) -> None:
+ team_id: int = options["team_id"]
+ team = Team.objects.filter(id=team_id).first()
+ if team is None:
+ raise CommandError(f"Team {team_id} not found")
+ if not team.conversations_enabled:
+ raise CommandError(f"Conversations is not enabled for team {team_id}")
+
+ credentials = ZendeskCredentials(
+ subdomain=options["subdomain"],
+ email_address=options["email"],
+ api_token=options["api_token"],
+ )
+ if not validate_zendesk_credentials(credentials):
+ raise CommandError("Zendesk rejected the credentials")
+
+ active_jobs = ZendeskImportJob.objects.unscoped().filter(
+ team_id=team_id,
+ status__in=[ZendeskImportJob.Status.PENDING, ZendeskImportJob.Status.RUNNING],
+ )
+ if active_jobs.exists():
+ if not options["force"]:
+ raise CommandError(
+ "A Zendesk import is already running for this team. "
+ "If it was terminated out-of-band (e.g. in the Temporal UI), re-run with --force."
+ )
+ reset = active_jobs.update(
+ status=ZendeskImportJob.Status.FAILED,
+ latest_error="Superseded by a --force re-import (previous job was no longer running).",
+ finished_at=timezone.now(),
+ updated_at=timezone.now(),
+ )
+ self.stdout.write(self.style.WARNING(f"--force: marked {reset} stale job(s) as failed"))
+
+ job = ZendeskImportJob.objects.unscoped().create(
+ team_id=team_id,
+ status=ZendeskImportJob.Status.PENDING,
+ job_inputs={
+ "subdomain": credentials.subdomain,
+ "email_address": credentials.email_address,
+ "api_token": credentials.api_token,
+ },
+ )
+
+ try:
+ workflow_id, workflow_run_id = asyncio.run(
+ start_zendesk_import_workflow(
+ job_id=str(job.id),
+ team_id=team_id,
+ dry_run=options["dry_run"],
+ max_tickets=options["limit"],
+ default_email_channel_id=options["default_email_channel_id"],
+ )
+ )
+ job.workflow_id = workflow_id
+ job.workflow_run_id = workflow_run_id
+ job.status = ZendeskImportJob.Status.RUNNING
+ job.started_at = timezone.now()
+ job.save(update_fields=["workflow_id", "workflow_run_id", "status", "started_at", "updated_at"])
+ except Exception as exc:
+ logger.exception("zendesk_import_workflow_start_failed", job_id=str(job.id), team_id=team_id)
+ job.status = ZendeskImportJob.Status.FAILED
+ job.latest_error = WORKFLOW_START_FAILED_MESSAGE
+ job.finished_at = timezone.now()
+ job.save(update_fields=["status", "latest_error", "finished_at", "updated_at"])
+ raise CommandError(f"Failed to start workflow: {exc}")
+
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Started Zendesk import job {job.id} (workflow {workflow_id}, "
+ f"dry_run={options['dry_run']}, limit={options['limit']})"
+ )
+ )
diff --git a/products/conversations/backend/migrations/0044_zendesk_import.py b/products/conversations/backend/migrations/0044_zendesk_import.py
new file mode 100644
index 000000000000..574683ac2fd9
--- /dev/null
+++ b/products/conversations/backend/migrations/0044_zendesk_import.py
@@ -0,0 +1,67 @@
+from django.db import migrations, models
+
+import posthog.models.utils
+from posthog.helpers.encrypted_fields import EncryptedJSONField
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("conversations", "0043_backfill_identity_verified"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="ticket",
+ name="zendesk_ticket_id",
+ field=models.BigIntegerField(blank=True, null=True),
+ ),
+ migrations.CreateModel(
+ name="ZendeskImportJob",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7, editable=False, primary_key=True, serialize=False
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("running", "Running"),
+ ("completed", "Completed"),
+ ("failed", "Failed"),
+ ],
+ default="pending",
+ max_length=32,
+ ),
+ ),
+ ("total_tickets", models.BigIntegerField(default=0)),
+ ("processed_tickets", models.BigIntegerField(default=0)),
+ ("imported_tickets", models.BigIntegerField(default=0)),
+ ("skipped_tickets", models.BigIntegerField(default=0)),
+ ("failed_tickets", models.BigIntegerField(default=0)),
+ ("export_cursor", models.TextField(blank=True, null=True)),
+ ("started_at", models.DateTimeField(blank=True, null=True)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ ("workflow_id", models.CharField(blank=True, max_length=400, null=True)),
+ ("workflow_run_id", models.CharField(blank=True, max_length=400, null=True)),
+ ("latest_error", models.TextField(blank=True, null=True)),
+ ("job_inputs", EncryptedJSONField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "team",
+ models.ForeignKey(db_constraint=False, on_delete=models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_conversations_zendesk_import_job",
+ "indexes": [
+ models.Index(fields=["team", "-created_at"], name="posthog_con_zd_import_team_idx"),
+ models.Index(fields=["team", "status"], name="posthog_con_zd_import_stat_idx"),
+ ],
+ },
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/0045_zendesk_ticket_uniq.py b/products/conversations/backend/migrations/0045_zendesk_ticket_uniq.py
new file mode 100644
index 000000000000..7155c3eacae4
--- /dev/null
+++ b/products/conversations/backend/migrations/0045_zendesk_ticket_uniq.py
@@ -0,0 +1,40 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Required for CREATE INDEX CONCURRENTLY (the partial unique index backing the constraint).
+ atomic = False
+
+ dependencies = [
+ ("conversations", "0044_zendesk_import"),
+ ]
+
+ operations = [
+ # posthog_conversations_ticket is an existing, populated table, so the partial unique
+ # index must be built concurrently to avoid an ACCESS EXCLUSIVE lock on writes.
+ # SeparateDatabaseAndState keeps Django's state as a UniqueConstraint while the DB
+ # gets the equivalent partial unique index under the same name.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="ticket",
+ constraint=models.UniqueConstraint(
+ fields=("team", "zendesk_ticket_id"),
+ condition=models.Q(("zendesk_ticket_id__isnull", False)),
+ name="posthog_con_zendesk_ticket_uniq",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="posthog_con_zendesk_ticket_uniq",
+ table_name="posthog_conversations_ticket",
+ columns="(team_id, zendesk_ticket_id)",
+ unique=True,
+ where="WHERE zendesk_ticket_id IS NOT NULL",
+ ),
+ ],
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txt
index d3331da1ad1d..34c0a68a10e9 100644
--- a/products/conversations/backend/migrations/max_migration.txt
+++ b/products/conversations/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0043_backfill_identity_verified
+0045_zendesk_ticket_uniq
diff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.py
index 5dba61014c8a..7a3d7b3b13ba 100644
--- a/products/conversations/backend/models/__init__.py
+++ b/products/conversations/backend/models/__init__.py
@@ -10,6 +10,7 @@ from .team_conversations_teams_channel_sync import TeamConversationsTeamsChannel
from .team_conversations_teams_config import TeamConversationsTeamsConfig
from .ticket import Ticket
from .ticket_view import TicketView
+from .zendesk_import_job import ZendeskImportJob
__all__ = [
"Channel",
@@ -28,4 +29,5 @@ __all__ = [
"Ticket",
"TicketAssignment",
"TicketView",
+ "ZendeskImportJob",
]
diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.py
index 2d09b602a321..bea1c8d7a682 100644
--- a/products/conversations/backend/models/ticket.py
+++ b/products/conversations/backend/models/ticket.py
@@ -108,6 +108,11 @@ class Ticket(UUIDTModel):
# Customer's PostHog org group key, resolved once at creation (local org pk or cross-region analytics key).
organization_id = models.CharField(max_length=400, null=True, blank=True)
+ # Zendesk import dedup — set when a ticket is imported from Zendesk Support.
+ # No standalone index: the partial unique constraint below covers the dedup lookup
+ # (team + zendesk_ticket_id), mirroring the GitHub issue-number pattern.
+ zendesk_ticket_id = models.BigIntegerField(null=True, blank=True)
+
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -151,6 +156,11 @@ class Ticket(UUIDTModel):
condition=models.Q(github_repo__isnull=False, github_issue_number__isnull=False),
name="posthog_con_github_issue_uniq",
),
+ models.UniqueConstraint(
+ fields=["team", "zendesk_ticket_id"],
+ condition=models.Q(zendesk_ticket_id__isnull=False),
+ name="posthog_con_zendesk_ticket_uniq",
+ ),
]
def __str__(self):
diff --git a/products/conversations/backend/models/zendesk_import_job.py b/products/conversations/backend/models/zendesk_import_job.py
new file mode 100644
index 000000000000..05dc3401aebb
--- /dev/null
+++ b/products/conversations/backend/models/zendesk_import_job.py
@@ -0,0 +1,47 @@
+from django.db import models
+
+from posthog.helpers.encrypted_fields import EncryptedJSONField
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class ZendeskImportJob(TeamScopedRootMixin, UUIDModel):
+ class Status(models.TextChoices):
+ PENDING = "pending", "Pending"
+ RUNNING = "running", "Running"
+ COMPLETED = "completed", "Completed"
+ FAILED = "failed", "Failed"
+
+ # db_constraint=False: a real FK constraint would take SHARE ROW EXCLUSIVE on the
+ # hot posthog_team table on CreateModel. App-level enforcement is enough here.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ status = models.CharField(max_length=32, choices=Status, default=Status.PENDING)
+
+ total_tickets = models.BigIntegerField(default=0)
+ processed_tickets = models.BigIntegerField(default=0)
+ imported_tickets = models.BigIntegerField(default=0)
+ skipped_tickets = models.BigIntegerField(default=0)
+ failed_tickets = models.BigIntegerField(default=0)
+
+ export_cursor = models.TextField(null=True, blank=True)
+
+ started_at = models.DateTimeField(null=True, blank=True)
+ finished_at = models.DateTimeField(null=True, blank=True)
+
+ workflow_id = models.CharField(max_length=400, null=True, blank=True)
+ workflow_run_id = models.CharField(max_length=400, null=True, blank=True)
+ latest_error = models.TextField(null=True, blank=True)
+
+ # Encrypted: subdomain, email_address, api_token
+ job_inputs = EncryptedJSONField(null=True, blank=True)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ app_label = "conversations"
+ db_table = "posthog_conversations_zendesk_import_job"
+ indexes = [
+ models.Index(fields=["team", "-created_at"], name="posthog_con_zd_import_team_idx"),
+ models.Index(fields=["team", "status"], name="posthog_con_zd_import_stat_idx"),
+ ]
diff --git a/products/conversations/backend/permissions.py b/products/conversations/backend/permissions.py
index a19c4120f30d..2b615742b832 100644
--- a/products/conversations/backend/permissions.py
+++ b/products/conversations/backend/permissions.py
@@ -10,12 +10,28 @@ class IsConversationsAdmin(BasePermission):
def has_permission(self, request: Request, view) -> bool:
user = request.user
- if not isinstance(user, User) or user.current_team is None:
+ if not isinstance(user, User):
+ return False
+
+ # On project-nested viewsets (TeamAndOrgViewSetMixin) gate on the *routed* team's
+ # organization so an org admin can't target another project by ID. Plain APIViews
+ # have no routed team, so fall back to the user's current team.
+ organization_id = None
+ try:
+ routed_team = view.team
+ except Exception:
+ routed_team = None
+ if routed_team is not None:
+ organization_id = routed_team.organization_id
+ elif user.current_team is not None:
+ organization_id = user.current_team.organization_id
+
+ if organization_id is None:
return False
try:
membership = OrganizationMembership.objects.get(
user=user,
- organization_id=user.current_team.organization_id,
+ organization_id=organization_id,
)
except OrganizationMembership.DoesNotExist:
return False
diff --git a/products/conversations/backend/routes.py b/products/conversations/backend/routes.py
index 95bd4c29462f..bf7036c38cb2 100644
--- a/products/conversations/backend/routes.py
+++ b/products/conversations/backend/routes.py
@@ -1,6 +1,6 @@
from posthog.api.routing import RouterRegistry
-from products.conversations.backend.api import TicketViewSet, TicketViewViewSet
+from products.conversations.backend.api import TicketViewSet, TicketViewViewSet, ZendeskImportViewSet
def register_routes(routers: RouterRegistry) -> None:
@@ -10,6 +10,12 @@ def register_routes(routers: RouterRegistry) -> None:
"environment_conversations_tickets",
["team_id"],
)
+ routers.projects.register(
+ r"conversations/zendesk_imports",
+ ZendeskImportViewSet,
+ "project_conversations_zendesk_imports",
+ ["team_id"],
+ )
# Dual-route surface preserved for existing clients (project + environment).
routers.register_legacy_dual_route(
r"conversations/views",
diff --git a/products/conversations/backend/temporal/__init__.py b/products/conversations/backend/temporal/__init__.py
index 07b4436552dc..0fa572935c84 100644
--- a/products/conversations/backend/temporal/__init__.py
+++ b/products/conversations/backend/temporal/__init__.py
@@ -18,10 +18,22 @@ from products.conversations.backend.temporal.pipeline import (
support_safety_filter_activity,
support_validate_activity,
)
+from products.conversations.backend.temporal.zendesk_import.activities import (
+ zendesk_import_batch_activity,
+ zendesk_import_enumerate_tickets_activity,
+ zendesk_import_update_job_progress_activity,
+ zendesk_import_update_job_status_activity,
+)
+from products.conversations.backend.temporal.zendesk_import.workflows import (
+ ZendeskImportBatchWorkflow,
+ ZendeskImportCoordinatorWorkflow,
+)
WORKFLOWS = [
SupportReplyWorkflow,
SupportReplyCoordinatorWorkflow,
+ ZendeskImportCoordinatorWorkflow,
+ ZendeskImportBatchWorkflow,
]
ACTIVITIES = [
@@ -37,4 +49,8 @@ ACTIVITIES = [
support_persist_knowledge_gap_activity,
support_record_triage_activity,
support_collect_eligible_tickets_activity,
+ zendesk_import_enumerate_tickets_activity,
+ zendesk_import_batch_activity,
+ zendesk_import_update_job_status_activity,
+ zendesk_import_update_job_progress_activity,
]
diff --git a/products/conversations/backend/temporal/zendesk_import/activities.py b/products/conversations/backend/temporal/zendesk_import/activities.py
new file mode 100644
index 000000000000..56748b44504e
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/activities.py
@@ -0,0 +1,561 @@
+"""Temporal activities for Zendesk historical ticket import."""
+
+from __future__ import annotations
+
+import uuid
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+import structlog
+from temporalio import activity, workflow
+
+# The package __init__ imports this module inside the Temporal workflow sandbox, but these
+# Django/HogQL/model imports are non-deterministic and trip sandbox restrictions (e.g. the
+# ORM query-expression names walk django.core.checks.translation -> gettext). Only the
+# activity sync helpers touch them at runtime, so pass them through the sandbox unmodified.
+with workflow.unsafe.imports_passed_through():
+ from django.db import transaction
+ from django.db.models import F, Max
+ from django.utils import timezone
+ from django.utils.dateparse import parse_datetime
+ from django.utils.html import strip_tags
+
+ from posthog.models import Team
+ from posthog.models.comment import Comment
+ from posthog.sync import database_sync_to_async
+ from posthog.temporal.common.heartbeat import Heartbeater
+
+ from products.conversations.backend.models import EmailChannel, Ticket, ZendeskImportJob
+ from products.conversations.backend.models.constants import Status
+ from products.conversations.backend.services.attachments import (
+ CONVERSATIONS_MAX_IMAGE_BYTES,
+ build_content_with_images,
+ save_file_to_uploaded_media,
+ )
+ from products.conversations.backend.temporal.zendesk_import.client import (
+ ZendeskAttachmentTooLargeError,
+ ZendeskCredentials,
+ ZendeskImportClient,
+ )
+ from products.conversations.backend.temporal.zendesk_import.mappers import (
+ default_channel_source,
+ map_zendesk_author_type,
+ map_zendesk_priority,
+ map_zendesk_status,
+ )
+
+logger = structlog.get_logger(__name__)
+
+
+@dataclass
+class EnumerateTicketsInput:
+ job_id: str
+ cursor: str | None = None
+
+
+@dataclass
+class EnumerateTicketsOutput:
+ ticket_ids: list[int]
+ next_cursor: str | None
+ end_of_stream: bool
+
+
+@dataclass
+class ImportBatchInput:
+ job_id: str
+ team_id: int
+ ticket_ids: list[int]
+ dry_run: bool = False
+ # Fallback EmailChannel (UUID str) for tickets whose Zendesk `recipient` doesn't match a
+ # configured support address (e.g. a *.zendesk.com recipient) or is absent. None = leave the
+ # ticket's email_config null in those cases.
+ default_email_channel_id: str | None = None
+
+
+@dataclass
+class ImportBatchOutput:
+ imported: int
+ skipped: int
+ failed: int
+
+
+@dataclass
+class UpdateJobStatusInput:
+ job_id: str
+ status: str
+ latest_error: str | None = None
+
+
+@dataclass
+class UpdateJobProgressInput:
+ job_id: str
+ processed_delta: int = 0
+ imported_delta: int = 0
+ skipped_delta: int = 0
+ failed_delta: int = 0
+ total_delta: int = 0
+ export_cursor: str | None = None
+
+
+def _parse_zendesk_datetime(value: str | None) -> datetime | None:
+ if not value:
+ return None
+ parsed = parse_datetime(value)
+ if parsed is None:
+ return None
+ if timezone.is_naive(parsed):
+ return timezone.make_aware(parsed, timezone=UTC)
+ return parsed
+
+
+def _credentials_from_job(job: ZendeskImportJob) -> ZendeskCredentials:
+ inputs = job.job_inputs or {}
+ subdomain = str(inputs.get("subdomain") or "")
+ email_address = str(inputs.get("email_address") or "")
+ api_token = str(inputs.get("api_token") or "")
+ if not subdomain or not email_address or not api_token:
+ raise ValueError("Zendesk import job is missing credentials")
+ return ZendeskCredentials(subdomain=subdomain, email_address=email_address, api_token=api_token)
+
+
+def _strip_nul(value: str) -> str:
+ """Remove NUL (0x00) bytes, which Postgres text/jsonb columns reject outright.
+
+ Zendesk ticket bodies occasionally carry stray NULs (bad email encodings, copy-paste
+ artifacts). One such byte anywhere in a batch aborts the entire bulk_create with a
+ DataError and exhausts the activity's retries, so scrub it from every stored string.
+ """
+ return value.replace("\x00", "") if "\x00" in value else value
+
+
+def _comment_body(comment: dict[str, Any]) -> str:
+ body = (comment.get("body") or "").strip()
+ if body:
+ return _strip_nul(body)
+ html_body = comment.get("html_body") or ""
+ return _strip_nul(strip_tags(html_body).strip())
+
+
+def _comment_is_private(comment: Comment) -> bool:
+ """True for internal notes, which must never surface in customer-facing denormalized stats."""
+ ctx = comment.item_context
+ return isinstance(ctx, dict) and ctx.get("is_private") is True
+
+
+def _process_attachments(
+ client: ZendeskImportClient,
+ team: Team,
+ comment: dict[str, Any],
+ content: str,
+ rich_content: dict[str, Any] | None,
+) -> tuple[str, dict[str, Any] | None]:
+ images: list[dict[str, Any]] = []
+ file_links: list[str] = []
+ for attachment in comment.get("attachments") or []:
+ content_url = attachment.get("content_url")
+ file_name = attachment.get("file_name") or "attachment"
+ content_type = attachment.get("content_type") or "application/octet-stream"
+ if not content_url:
+ continue
+ try:
+ raw = client.download_attachment(content_url, max_bytes=CONVERSATIONS_MAX_IMAGE_BYTES)
+ except ZendeskAttachmentTooLargeError:
+ logger.warning(
+ "zendesk_import_attachment_too_large",
+ team_id=team.id,
+ file_name=file_name,
+ max_bytes=CONVERSATIONS_MAX_IMAGE_BYTES,
+ )
+ continue
+ except Exception as exc:
+ logger.warning(
+ "zendesk_import_attachment_download_failed",
+ team_id=team.id,
+ file_name=file_name,
+ error=str(exc),
+ )
+ continue
+ is_image = content_type.startswith("image/")
+ media_url = save_file_to_uploaded_media(
+ team,
+ file_name,
+ content_type,
+ raw,
+ validate_images=is_image,
+ )
+ if not media_url:
+ continue
+ if is_image:
+ images.append({"url": media_url, "name": file_name})
+ else:
+ file_links.append(f"[{file_name}]({media_url})")
+ if file_links:
+ suffix = "\n".join(file_links)
+ content = f"{content}\n\n{suffix}" if content else suffix
+ return build_content_with_images(content, rich_content, images)
+
+
+def _import_ticket_batch_sync(input: ImportBatchInput) -> ImportBatchOutput:
+ job = ZendeskImportJob.objects.for_team(input.team_id).get(id=input.job_id)
+ team = Team.objects.get(id=input.team_id)
+ credentials = _credentials_from_job(job)
+ client = ZendeskImportClient(credentials)
+
+ existing_ids = set(
+ Ticket.objects.filter(team_id=input.team_id)
+ .filter(zendesk_ticket_id__in=input.ticket_ids)
+ .values_list("zendesk_ticket_id", flat=True)
+ )
+ to_import = [tid for tid in input.ticket_ids if tid not in existing_ids]
+ skipped = len(input.ticket_ids) - len(to_import)
+ if not to_import:
+ return ImportBatchOutput(imported=0, skipped=skipped, failed=0)
+
+ if input.dry_run:
+ logger.info("zendesk_import_dry_run_batch", team_id=team.id, would_import=len(to_import), skipped=skipped)
+ return ImportBatchOutput(imported=len(to_import), skipped=skipped, failed=0)
+
+ zendesk_tickets = client.fetch_tickets(to_import)
+ requester_ids = [int(t["requester_id"]) for t in zendesk_tickets if t.get("requester_id") is not None]
+ users_by_id = client.fetch_users(requester_ids)
+
+ imported = 0
+ failed = 0
+
+ # Map the team's support addresses so each ticket's Zendesk `recipient` (the address the
+ # customer originally emailed) resolves to the matching EmailChannel. Unmatched/absent
+ # recipients fall back to the caller-selected default channel, if any. Bounded to
+ # MAX_EMAIL_CONFIGS_PER_TEAM rows, so a single query up front is cheap.
+ email_channels = list(EmailChannel.objects.filter(team_id=team.id))
+ email_channels_by_addr = {(c.from_email or "").strip().lower(): c for c in email_channels}
+ default_email_channel = None
+ if input.default_email_channel_id:
+ default_email_channel = next((c for c in email_channels if str(c.id) == input.default_email_channel_id), None)
+
+ # Phase 1: Fetch all comments + attachments OUTSIDE the transaction (network I/O).
+ ticket_data: list[tuple[dict[str, Any], list[dict[str, Any]]]] = []
+ comment_author_ids: set[int] = set()
+ for zendesk_ticket in zendesk_tickets:
+ zendesk_id = int(zendesk_ticket["id"])
+ try:
+ comments = client.fetch_comments(zendesk_id)
+ for zd_comment in comments:
+ author_id = zd_comment.get("author_id")
+ if author_id is not None:
+ comment_author_ids.add(int(author_id))
+ ticket_data.append((zendesk_ticket, comments))
+ except Exception as exc:
+ failed += 1
+ logger.exception(
+ "zendesk_import_ticket_fetch_failed",
+ team_id=team.id,
+ zendesk_ticket_id=zendesk_id,
+ error=str(exc),
+ )
+
+ if not ticket_data:
+ return ImportBatchOutput(imported=0, skipped=skipped, failed=failed)
+
+ # Batch-resolve every comment author's role in one shot (so classification uses the real
+ # role for each participant, not a per-thread heuristic). Deactivated agents still resolve;
+ # only hard-deleted users won't, and those fall back to the customer-side id check below.
+ missing_author_ids = [aid for aid in comment_author_ids if aid not in users_by_id]
+ if missing_author_ids:
+ users_by_id.update(client.fetch_users(missing_author_ids))
+
+ # Phase 2: Process each ticket (attachments involve network I/O, so outside atomic).
+ tickets_to_create: list[Ticket] = []
+ ticket_comments_map: list[tuple[int, list[Comment], int, int]] = []
+ # Maps index in tickets_to_create → index in ticket_data
+ ticket_create_to_data_idx: list[int] = []
+
+ for idx, (zendesk_ticket, comments) in enumerate(ticket_data):
+ zendesk_id = int(zendesk_ticket["id"])
+ try:
+ requester = users_by_id.get(int(zendesk_ticket.get("requester_id") or 0), {})
+ requester_email = _strip_nul(
+ (requester.get("email") or f"zendesk-user-{zendesk_ticket.get('requester_id')}").strip()
+ )
+ requester_name = _strip_nul((requester.get("name") or "").strip())
+ # Access identity: use the Zendesk requester email verbatim. This gates verified-widget
+ # ticket history (widget.py checks ticket.distinct_id ∈ the caller's person distinct_ids),
+ # and person distinct_ids are set only by the app's own identify()/alias() calls. We must
+ # NOT resolve this via a person lookup on `properties.email`: that field is attacker-
+ # settable analytics data, so seeding a profile with a victim's email would rebind the
+ # victim's imported tickets to the attacker's distinct_id (identity poisoning).
+ distinct_id = requester_email
+
+ # Populate anonymous_traits so the customer renders as their name/email instead of
+ # "Anonymous user" when no PostHog person matched — same shape as the other import
+ # paths (Slack/email/GitHub). The email is from the authenticated Zendesk API, not
+ # public widget input, so it's trustworthy for restore-by-email.
+ anonymous_traits: dict[str, str] = {}
+ if requester_name:
+ anonymous_traits["name"] = requester_name
+ if "@" in requester_email:
+ anonymous_traits["email"] = requester_email
+
+ # Zendesk `recipient` is the original support address the customer emailed. Match it to
+ # a configured EmailChannel; otherwise fall back to the caller-selected default (or null).
+ recipient = (zendesk_ticket.get("recipient") or "").strip().lower()
+ email_config = email_channels_by_addr.get(recipient) or default_email_channel
+
+ ticket = Ticket(
+ team=team,
+ channel_source=default_channel_source(),
+ widget_session_id=str(uuid.uuid4()),
+ distinct_id=distinct_id,
+ status=map_zendesk_status(zendesk_ticket.get("status")),
+ priority=map_zendesk_priority(zendesk_ticket.get("priority")),
+ email_subject=_strip_nul(zendesk_ticket.get("subject") or "")[:500] or None,
+ email_from=requester_email if "@" in requester_email else None,
+ email_config=email_config,
+ anonymous_traits=anonymous_traits,
+ zendesk_ticket_id=zendesk_id,
+ )
+ create_idx = len(tickets_to_create)
+ tickets_to_create.append(ticket)
+ ticket_create_to_data_idx.append(idx)
+
+ comments_to_create: list[Comment] = []
+ customer_message_count = 0
+ agent_reply_count = 0
+
+ # Customer-side participants: the requester plus any CCs/collaborators. Used only as a
+ # fallback when an author's role can't be resolved (hard-deleted users) so a deleted
+ # end-user still counts as a customer and a deleted agent counts as staff.
+ customer_side_ids: set[int] = set()
+ if zendesk_ticket.get("requester_id") is not None:
+ customer_side_ids.add(int(zendesk_ticket["requester_id"]))
+ for cc_id in (zendesk_ticket.get("collaborator_ids") or []) + (zendesk_ticket.get("email_cc_ids") or []):
+ if cc_id is not None:
+ customer_side_ids.add(int(cc_id))
+
+ for zd_comment in comments:
+ author_id = zd_comment.get("author_id")
+ author = users_by_id.get(int(author_id), {}) if author_id is not None else {}
+
+ is_public = bool(zd_comment.get("public", True))
+ is_customer_side = author_id is not None and int(author_id) in customer_side_ids
+ author_type, is_private = map_zendesk_author_type(
+ role=author.get("role"), is_public=is_public, is_customer_side=is_customer_side
+ )
+ body = _comment_body(zd_comment)
+ rich_content: dict[str, Any] | None = None
+ body, rich_content = _process_attachments(client, team, zd_comment, body, rich_content)
+ if not body and not rich_content:
+ continue
+
+ # Mirror signals.update_ticket_on_message: private/internal notes are dropped from
+ # every denormalized widget stat (message_count, last_message_*, unread counts).
+ # Counting them here would leak note text into last_message_text and inflate the
+ # customer's unread badge on the verified widget.
+ if is_private:
+ pass
+ elif author_type == "customer":
+ customer_message_count += 1
+ else:
+ agent_reply_count += 1
+
+ # Persist each comment's own author identity so the thread shows the actual
+ # commenter (a second requester, an agent, etc.) instead of every message
+ # inheriting the ticket-level requester from anonymous_traits.
+ author_name = _strip_nul((author.get("name") or "").strip())
+ author_email = _strip_nul((author.get("email") or "").strip())
+ # A staff author whose Zendesk user no longer resolves (deleted ex-agent) has no
+ # name/email — recover it from the comment's own sender (`via.source.from`), which
+ # survives user deletion, so the reply doesn't render as "Anonymous user".
+ if author_type == "support" and not author_name and not author_email:
+ via_from = ((zd_comment.get("via") or {}).get("source") or {}).get("from") or {}
+ author_name = _strip_nul((via_from.get("name") or "").strip())
+ author_email = _strip_nul((via_from.get("address") or "").strip())
+ item_context: dict[str, Any] = {
+ "author_type": author_type,
+ "is_private": is_private,
+ "from_zendesk": True,
+ "zendesk_comment_id": zd_comment.get("id"),
+ }
+ if author_name:
+ item_context["author_name"] = author_name
+ if author_email:
+ item_context["author_email"] = author_email
+
+ comment_created_at = _parse_zendesk_datetime(zd_comment.get("created_at"))
+ comment_obj = Comment(
+ team=team,
+ scope="conversations_ticket",
+ item_id="", # placeholder — set after ticket gets an ID
+ content=_strip_nul(body),
+ rich_content=rich_content,
+ item_context=item_context,
+ )
+ # auto_now_add clobbers created_at during bulk_create, so stash the
+ # historical value on a shadow attr and re-apply it via bulk_update.
+ comment_obj._zendesk_created_at = comment_created_at # type: ignore[attr-defined]
+ comments_to_create.append(comment_obj)
+
+ ticket_comments_map.append((create_idx, comments_to_create, customer_message_count, agent_reply_count))
+ except Exception as exc:
+ failed += 1
+ logger.exception(
+ "zendesk_import_ticket_failed",
+ team_id=team.id,
+ zendesk_ticket_id=zendesk_id,
+ error=str(exc),
+ )
+
+ if not tickets_to_create:
+ return ImportBatchOutput(imported=0, skipped=skipped, failed=failed)
+
+ # Phase 3: Persist tickets + comments in a single transaction (no network I/O).
+ # Ticket numbers are assigned under the same lock that guards bulk_create, so
+ # concurrent batch activities can't collide on unique_ticket_number_per_team.
+ #
+ # IMPORTANT: persist historical rows with bulk_create/bulk_update ONLY. These bypass the
+ # post_save/pre_save receivers in products/conversations/backend/signals.py, which is what
+ # keeps a backfill silent: those receivers emit the $conversation_* analytics events that
+ # power hogflow triggers (New ticket created, Ticket message sent/received, ...) AND enqueue
+ # outbound Slack/email/Teams/GitHub replies. Switching any write here to create_with_number(),
+ # Comment.objects.create(), or .save() would fire those signals for every imported row —
+ # triggering workflows and re-sending replies to real customers for years-old tickets. Don't.
+ with transaction.atomic():
+ Team.objects.select_for_update().get(id=team.id)
+ max_num = Ticket.objects.filter(team_id=team.id).aggregate(Max("ticket_number"))["ticket_number__max"] or 0
+ for offset, ticket_to_number in enumerate(tickets_to_create):
+ ticket_to_number.ticket_number = max_num + 1 + offset
+ created_tickets = Ticket.objects.bulk_create(tickets_to_create)
+
+ # Apply historical timestamps
+ ticket_ts_updates: list[Ticket] = []
+ for i, ticket_obj in enumerate(created_tickets):
+ data_idx = ticket_create_to_data_idx[i]
+ zendesk_ticket = ticket_data[data_idx][0]
+ created_at = _parse_zendesk_datetime(zendesk_ticket.get("created_at"))
+ updated_at_ts = _parse_zendesk_datetime(zendesk_ticket.get("updated_at"))
+ if created_at or updated_at_ts:
+ ticket_obj.created_at = created_at or timezone.now()
+ ticket_obj.updated_at = updated_at_ts or timezone.now()
+ ticket_ts_updates.append(ticket_obj)
+ if ticket_ts_updates:
+ Ticket.objects.bulk_update(ticket_ts_updates, ["created_at", "updated_at"])
+
+ # Set item_id on comments now that tickets have IDs, then bulk_create
+ all_comments: list[Comment] = []
+ # (ticket, public customer messages, public agent replies) — private notes are excluded
+ # from every denormalized counter to match the live signal path.
+ ticket_counter_updates: list[tuple[Ticket, int, int]] = []
+ for idx, comments_list, cust_count, agent_count in ticket_comments_map:
+ if idx >= len(created_tickets):
+ continue
+ ticket_obj = created_tickets[idx]
+ for c in comments_list:
+ c.item_id = str(ticket_obj.id)
+ all_comments.extend(comments_list)
+ if comments_list:
+ ticket_counter_updates.append((ticket_obj, cust_count, agent_count))
+
+ if all_comments:
+ created_comments = Comment.objects.bulk_create(all_comments)
+ # bulk_create's auto_now_add overwrote created_at, so re-apply the stashed
+ # historical timestamps for comments that had one.
+ comment_ts_updates: list[Comment] = []
+ for c in created_comments:
+ historical = getattr(c, "_zendesk_created_at", None)
+ if historical is not None:
+ c.created_at = historical
+ comment_ts_updates.append(c)
+ if comment_ts_updates:
+ Comment.objects.bulk_update(comment_ts_updates, ["created_at"])
+
+ # Update denormalized counters per ticket. All of these back the customer-facing widget
+ # (message_count, last_message_*, unread badge), so they must exclude private notes — see
+ # the counting loop above and signals.update_ticket_on_message.
+ for ticket_obj, cust_count, agent_count in ticket_counter_updates:
+ update_fields_dict: dict[str, Any] = {
+ "message_count": F("message_count") + cust_count + agent_count,
+ }
+ # last_message_* is shown to the customer, so use the latest non-private comment.
+ # Comments are appended in Zendesk chronological order, so reverse-scan for the
+ # newest visible one.
+ ticket_comments = [c for c in all_comments if c.item_id == str(ticket_obj.id)]
+ last_visible = next((c for c in reversed(ticket_comments) if not _comment_is_private(c)), None)
+ if last_visible is not None:
+ update_fields_dict["last_message_at"] = last_visible.created_at
+ update_fields_dict["last_message_text"] = (last_visible.content or "")[:500]
+ # Only still-active imported tickets should surface unread badges. Pending/on-hold/
+ # resolved (Zendesk solved+closed) tickets are done or parked, so lighting up the agent
+ # inbox (unread_team_count) or the customer widget (unread_customer_count) with years-old
+ # activity is pure alert fatigue — import them read.
+ is_active = ticket_obj.status in (Status.NEW, Status.OPEN)
+ if is_active and cust_count:
+ update_fields_dict["unread_team_count"] = F("unread_team_count") + cust_count
+ if is_active and agent_count:
+ update_fields_dict["unread_customer_count"] = F("unread_customer_count") + agent_count
+ Ticket.objects.filter(team_id=team.id, id=ticket_obj.id).update(**update_fields_dict)
+
+ imported = len(created_tickets)
+
+ return ImportBatchOutput(imported=imported, skipped=skipped, failed=failed)
+
+
+async def zendesk_import_enumerate_tickets_activity(input: EnumerateTicketsInput) -> EnumerateTicketsOutput:
+ async with Heartbeater():
+ return await database_sync_to_async(_enumerate_tickets_sync, thread_sensitive=False)(input)
+
+
+def _enumerate_tickets_sync(input: EnumerateTicketsInput) -> EnumerateTicketsOutput:
+ job = ZendeskImportJob.objects.unscoped().get(id=input.job_id)
+ client = ZendeskImportClient(_credentials_from_job(job))
+ ticket_ids, next_cursor, end_of_stream = client.list_ticket_ids_page(cursor=input.cursor)
+ return EnumerateTicketsOutput(ticket_ids=ticket_ids, next_cursor=next_cursor, end_of_stream=end_of_stream)
+
+
+async def zendesk_import_batch_activity(input: ImportBatchInput) -> ImportBatchOutput:
+ async with Heartbeater():
+ return await database_sync_to_async(_import_ticket_batch_sync, thread_sensitive=False)(input)
+
+
+def _update_job_status_sync(input: UpdateJobStatusInput) -> None:
+ job = ZendeskImportJob.objects.unscoped().get(id=input.job_id)
+ update_fields = ["status", "updated_at"]
+ job.status = input.status
+ if input.latest_error is not None:
+ job.latest_error = input.latest_error
+ update_fields.append("latest_error")
+ if input.status == ZendeskImportJob.Status.RUNNING and job.started_at is None:
+ job.started_at = timezone.now()
+ update_fields.append("started_at")
+ if input.status in (ZendeskImportJob.Status.COMPLETED, ZendeskImportJob.Status.FAILED):
+ job.finished_at = timezone.now()
+ update_fields.append("finished_at")
+ # Narrow update_fields so this write can't clobber counters / cursor
+ # that in-flight batch children may update concurrently (e.g. on FAILED).
+ job.save(update_fields=update_fields)
+
+
+def _update_job_progress_sync(input: UpdateJobProgressInput) -> None:
+ updates: dict[str, Any] = {
+ "processed_tickets": F("processed_tickets") + input.processed_delta,
+ "imported_tickets": F("imported_tickets") + input.imported_delta,
+ "skipped_tickets": F("skipped_tickets") + input.skipped_delta,
+ "failed_tickets": F("failed_tickets") + input.failed_delta,
+ "total_tickets": F("total_tickets") + input.total_delta,
+ }
+ if input.export_cursor is not None:
+ updates["export_cursor"] = input.export_cursor
+ ZendeskImportJob.objects.unscoped().filter(id=input.job_id).update(**updates)
+
+
+async def zendesk_import_update_job_status_activity(input: UpdateJobStatusInput) -> None:
+ async with Heartbeater():
+ await database_sync_to_async(_update_job_status_sync, thread_sensitive=False)(input)
+
+
+async def zendesk_import_update_job_progress_activity(input: UpdateJobProgressInput) -> None:
+ async with Heartbeater():
+ await database_sync_to_async(_update_job_progress_sync, thread_sensitive=False)(input)
diff --git a/products/conversations/backend/temporal/zendesk_import/client.py b/products/conversations/backend/temporal/zendesk_import/client.py
new file mode 100644
index 000000000000..485646a0b4b4
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/client.py
@@ -0,0 +1,282 @@
+"""Zendesk Support API client for historical ticket import."""
+
+from __future__ import annotations
+
+import re
+import time
+import base64
+from dataclasses import dataclass
+from typing import Any
+from urllib.parse import urlsplit
+
+import structlog
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+
+logger = structlog.get_logger(__name__)
+
+TICKETS_PER_PAGE = 1000
+COMMENTS_PER_PAGE = 100
+USERS_SHOW_MANY_BATCH = 100
+TICKETS_SHOW_MANY_BATCH = 100
+
+# Rate-limit handling: this client runs inside a Temporal activity thread
+# (database_sync_to_async, thread_sensitive=False). Sleeping the full Retry-After
+# in-thread ties up a thread-pool slot, so bound both how many times and how long
+# we wait before handing the backoff to Temporal's RetryPolicy (which waits between
+# activity attempts without holding a thread).
+MAX_RATE_LIMIT_RETRIES = 3
+MAX_RATE_LIMIT_SLEEP_SECONDS = 30
+
+# Stream attachment bodies in bounded chunks so an oversized file is aborted mid-download
+# instead of being fully buffered in the worker's memory before the size check.
+ATTACHMENT_CHUNK_BYTES = 64 * 1024
+
+# A Zendesk subdomain is a single DNS label: alphanumerics + hyphens, no leading/trailing
+# hyphen, <= 63 chars. Pinning to this stops a crafted subdomain (e.g. "attacker.example#")
+# from resolving the base host to something other than "<label>.zendesk.com" (SSRF).
+_SUBDOMAIN_LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$", re.IGNORECASE)
+
+
+def normalize_subdomain(subdomain: str) -> str:
+ """Reduce whatever the user entered to the bare Zendesk subdomain label.
+
+ Users frequently paste the full host ("nibbles.zendesk.com") or a URL
+ ("https://nibbles.zendesk.com/"). Collapse those to the bare label so the base
+ URL doesn't become "https://nibbles.zendesk.com.zendesk.com/". Callers still
+ validate the result against ``_SUBDOMAIN_LABEL_RE`` before issuing any request.
+
+ Owned here (copied from the warehouse Zendesk source rather than imported) so the
+ import's SSRF-sensitive host handling doesn't depend on another product's internals.
+ """
+ subdomain = subdomain.strip()
+ if "://" in subdomain:
+ subdomain = subdomain.split("://", 1)[1]
+ subdomain = subdomain.split("/", 1)[0]
+ return re.sub(r"\.zendesk\.com$", "", subdomain, flags=re.IGNORECASE)
+
+
+class ZendeskRateLimitError(Exception):
+ """Raised when Zendesk keeps rate-limiting beyond the in-thread retry budget.
+
+ Retryable by default, so Temporal's RetryPolicy reschedules the activity and
+ absorbs the longer wait out-of-thread.
+ """
+
+
+class ZendeskAttachmentTooLargeError(Exception):
+ """Raised when an attachment exceeds the caller's byte cap.
+
+ Distinct from a transport failure so the caller can skip the attachment (count it
+ as oversized) without treating it as a retryable download error.
+ """
+
+
+@dataclass(frozen=True)
+class ZendeskCredentials:
+ subdomain: str
+ email_address: str
+ api_token: str
+
+
+class ZendeskImportClient:
+ def __init__(self, credentials: ZendeskCredentials) -> None:
+ subdomain = normalize_subdomain(credentials.subdomain)
+ if not _SUBDOMAIN_LABEL_RE.match(subdomain):
+ raise ValueError(f"Invalid Zendesk subdomain: {credentials.subdomain!r}")
+ # Pin every request (including absolute next_page / attachment URLs echoed back by
+ # the API) to this host so a malicious/compromised API response can't redirect us at
+ # internal services.
+ self._host = f"{subdomain}.zendesk.com".lower()
+ self._base_url = f"https://{self._host}"
+ token = base64.b64encode(f"{credentials.email_address}/token:{credentials.api_token}".encode("ascii")).decode(
+ "ascii"
+ )
+ # The Basic auth header carries a reusable Zendesk API token. Mask the token,
+ # api_token, and email everywhere they might surface in logged URLs/samples, and
+ # disable sample capture entirely since the name-based scrubbers can't guarantee
+ # the Authorization header is stripped from captured request samples.
+ self._session = make_tracked_session(
+ redact_values=(token, credentials.api_token, credentials.email_address),
+ capture=False,
+ )
+ self._headers = {"Authorization": f"Basic {token}"}
+
+ def _handle_rate_limit(self, response: Response, path: str, attempt: int) -> None:
+ """Sleep for a bounded Retry-After, or raise once the budget is spent.
+
+ Raising (instead of sleeping indefinitely) hands the backoff to Temporal so a
+ long Retry-After can't pin a thread-pool slot for minutes.
+ """
+ try:
+ # Retry-After may be an HTTP-date (or garbage) rather than delta-seconds; fall back to a
+ # short default instead of letting a ValueError escape mid-backoff.
+ retry_after = int(response.headers.get("Retry-After", "5"))
+ except ValueError:
+ retry_after = 5
+ if attempt >= MAX_RATE_LIMIT_RETRIES or retry_after > MAX_RATE_LIMIT_SLEEP_SECONDS:
+ logger.warning("zendesk_import_rate_limited_giving_up", retry_after=retry_after, path=path, attempt=attempt)
+ raise ZendeskRateLimitError(
+ f"Zendesk rate limit exceeded in-thread retry budget (Retry-After={retry_after}s, attempt={attempt})"
+ )
+ logger.warning("zendesk_import_rate_limited", retry_after=retry_after, path=path, attempt=attempt)
+ time.sleep(retry_after)
+
+ def _assert_expected_host(self, url: str) -> None:
+ """Reject absolute URLs that aren't https on the pinned Zendesk host (SSRF guard).
+
+ Scheme is enforced alongside host: a host-only check lets a malicious/compromised API
+ response hand back an http:// URL on the right host, which passes but sends the reusable
+ Basic auth token in cleartext over the wire. Zendesk only ever returns https URLs, so
+ anything else is rejected.
+ """
+ parts = urlsplit(url)
+ host = parts.hostname
+ if parts.scheme.lower() != "https" or host is None or host.lower() != self._host:
+ raise ValueError(f"Refusing to fetch non-https or off-host URL (expected https://{self._host}): {url!r}")
+
+ def _request(self, method: str, path: str, *, params: dict[str, Any] | None = None) -> dict[str, Any]:
+ if path.startswith("http"):
+ self._assert_expected_host(path)
+ url = path
+ else:
+ url = f"{self._base_url}{path}"
+ attempt = 0
+ while True:
+ response = self._session.request(method, url, headers=self._headers, params=params, timeout=60)
+ if response.status_code == 429:
+ self._handle_rate_limit(response, path, attempt)
+ attempt += 1
+ continue
+ response.raise_for_status()
+ return response.json()
+
+ def list_ticket_ids_page(
+ self, *, cursor: str | None = None, start_time: int = 0
+ ) -> tuple[list[int], str | None, bool]:
+ params: dict[str, Any] = {"per_page": TICKETS_PER_PAGE}
+ if cursor:
+ params["cursor"] = cursor
+ else:
+ params["start_time"] = start_time
+
+ data = self._request("GET", "/api/v2/incremental/tickets/cursor", params=params)
+ tickets = data.get("tickets") or []
+ ticket_ids = [int(t["id"]) for t in tickets if t.get("id") is not None]
+ end_of_stream = bool(data.get("end_of_stream"))
+ after_cursor = data.get("after_cursor")
+ if end_of_stream:
+ return ticket_ids, None, True
+ if not after_cursor:
+ raise ValueError("Zendesk cursor export missing after_cursor before end_of_stream")
+ return ticket_ids, str(after_cursor), False
+
+ def fetch_tickets(self, ticket_ids: list[int]) -> list[dict[str, Any]]:
+ if not ticket_ids:
+ return []
+ results: list[dict[str, Any]] = []
+ for i in range(0, len(ticket_ids), TICKETS_SHOW_MANY_BATCH):
+ batch = ticket_ids[i : i + TICKETS_SHOW_MANY_BATCH]
+ data = self._request(
+ "GET",
+ "/api/v2/tickets/show_many.json",
+ params={"ids": ",".join(str(tid) for tid in batch)},
+ )
+ results.extend(data.get("tickets") or [])
+ return results
+
+ def fetch_users(self, user_ids: list[int]) -> dict[int, dict[str, Any]]:
+ if not user_ids:
+ return {}
+ users_by_id: dict[int, dict[str, Any]] = {}
+ unique_ids = sorted(set(user_ids))
+ for i in range(0, len(unique_ids), USERS_SHOW_MANY_BATCH):
+ batch = unique_ids[i : i + USERS_SHOW_MANY_BATCH]
+ data = self._request(
+ "GET",
+ "/api/v2/users/show_many.json",
+ params={"ids": ",".join(str(uid) for uid in batch)},
+ )
+ for user in data.get("users") or []:
+ if user.get("id") is not None:
+ users_by_id[int(user["id"])] = user
+ return users_by_id
+
+ def fetch_comments(self, ticket_id: int) -> list[dict[str, Any]]:
+ comments: list[dict[str, Any]] = []
+ url: str | None = f"/api/v2/tickets/{ticket_id}/comments.json"
+ params: dict[str, Any] | None = {"per_page": COMMENTS_PER_PAGE}
+ while url:
+ data = self._request("GET", url, params=params)
+ comments.extend(data.get("comments") or [])
+ url = data.get("next_page")
+ params = None
+ return comments
+
+ def download_attachment(self, content_url: str, *, max_bytes: int) -> bytes:
+ self._assert_expected_host(content_url)
+ attempt = 0
+ while True:
+ with self._session.get(content_url, headers=self._headers, timeout=120, stream=True) as response:
+ if response.status_code == 429:
+ self._handle_rate_limit(response, content_url, attempt)
+ attempt += 1
+ continue
+ response.raise_for_status()
+ # Precheck the declared size so a server-advertised oversized body is rejected
+ # before we read any of it.
+ declared = response.headers.get("Content-Length")
+ if declared is not None:
+ try:
+ if int(declared) > max_bytes:
+ raise ZendeskAttachmentTooLargeError(
+ f"Attachment exceeds {max_bytes} bytes (Content-Length={declared})"
+ )
+ except ValueError:
+ pass
+ # A lying/absent Content-Length can't sneak past: abort once streamed bytes
+ # cross the cap instead of buffering the whole response.
+ buffer = bytearray()
+ for chunk in response.iter_content(chunk_size=ATTACHMENT_CHUNK_BYTES):
+ if not chunk:
+ continue
+ buffer.extend(chunk)
+ if len(buffer) > max_bytes:
+ raise ZendeskAttachmentTooLargeError(f"Attachment exceeds {max_bytes} bytes while streaming")
+ return bytes(buffer)
+
+
+def validate_zendesk_credentials(credentials: ZendeskCredentials) -> bool:
+ """Probe the tickets count endpoint to confirm the credentials work.
+
+ Validates the subdomain to a single DNS label here (same guard as
+ `ZendeskImportClient.__init__`) so a crafted subdomain like "attacker.example#"
+ can't retarget the probe — and the Basic auth token with it — at another host (SSRF).
+ """
+ subdomain = normalize_subdomain(credentials.subdomain)
+ if not _SUBDOMAIN_LABEL_RE.match(subdomain):
+ return False
+ token = base64.b64encode(f"{credentials.email_address}/token:{credentials.api_token}".encode("ascii")).decode(
+ "ascii"
+ )
+ # The Basic auth header carries a reusable Zendesk API token. Mask the token, api_token,
+ # and email in logged URLs/samples, and disable sample capture so the Authorization header
+ # can't leak into HTTP telemetry.
+ session = make_tracked_session(
+ redact_values=(token, credentials.api_token, credentials.email_address),
+ capture=False,
+ )
+ # Runs synchronously inside the settings-page create() request handler. Without a timeout a
+ # slow/unresponsive host would pin the Django worker indefinitely; without the try/except a
+ # transport-level error (DNS/connection/SSL) would escape as a 500 instead of the intended
+ # "credentials rejected" 400. Any failure to reach + authenticate == invalid credentials.
+ try:
+ res = session.get(
+ f"https://{subdomain}.zendesk.com/api/v2/tickets/count",
+ headers={"Authorization": f"Basic {token}"},
+ timeout=10,
+ )
+ return res.status_code == 200
+ except Exception:
+ return False
diff --git a/products/conversations/backend/temporal/zendesk_import/constants.py b/products/conversations/backend/temporal/zendesk_import/constants.py
new file mode 100644
index 000000000000..966fa0dbb3d0
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/constants.py
@@ -0,0 +1,10 @@
+"""Constants for Zendesk historical import."""
+
+from __future__ import annotations
+
+BATCH_SIZE = 100
+MAX_CONCURRENT_BATCH_WORKFLOWS = 5
+CONTINUE_AS_NEW_AFTER_PAGES = 50
+
+WORKFLOW_ID_PREFIX = "zendesk-import"
+BATCH_WORKFLOW_ID_PREFIX = "zendesk-import-batch"
diff --git a/products/conversations/backend/temporal/zendesk_import/mappers.py b/products/conversations/backend/temporal/zendesk_import/mappers.py
new file mode 100644
index 000000000000..70e7d1071565
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/mappers.py
@@ -0,0 +1,57 @@
+"""Field mapping from Zendesk Support API payloads to Conversations models."""
+
+from __future__ import annotations
+
+from products.conversations.backend.models.constants import Channel, Priority, Status
+
+ZENDESK_STATUS_MAP: dict[str, str] = {
+ "new": Status.NEW,
+ "open": Status.OPEN,
+ "pending": Status.PENDING,
+ "hold": Status.ON_HOLD,
+ "solved": Status.RESOLVED,
+ "closed": Status.RESOLVED,
+}
+
+ZENDESK_PRIORITY_MAP: dict[str, str | None] = {
+ "low": Priority.LOW,
+ "normal": Priority.MEDIUM,
+ "high": Priority.HIGH,
+ "urgent": Priority.HIGH,
+}
+
+
+def map_zendesk_status(status: str | None) -> str:
+ if not status:
+ return Status.NEW
+ return ZENDESK_STATUS_MAP.get(status.lower(), Status.OPEN)
+
+
+def map_zendesk_priority(priority: str | None) -> str | None:
+ if not priority:
+ return None
+ return ZENDESK_PRIORITY_MAP.get(priority.lower())
+
+
+def map_zendesk_author_type(*, role: str | None, is_public: bool, is_customer_side: bool) -> tuple[str, bool]:
+ """Return (author_type, is_private) for Comment.item_context.
+
+ Role is the primary signal (`agent`/`admin` → staff, `end-user` → customer). Every
+ active participant resolves to a role, so a multi-party thread (requester + another
+ end-user + agent) classifies each correctly. `is_customer_side` — author is the
+ requester or a CC/collaborator — is only the fallback when `role` can't be resolved
+ (hard-deleted users): a deleted end-user stays a customer, while a deleted agent (staff
+ who was let go) is not customer-side and so is treated as staff. Prevents a staff reply
+ from being attributed to the customer.
+ """
+ if not is_public:
+ return "support", True
+ if role in ("agent", "admin"):
+ return "support", False
+ if role == "end-user":
+ return "customer", False
+ return ("customer", False) if is_customer_side else ("support", False)
+
+
+def default_channel_source() -> str:
+ return Channel.EMAIL
diff --git a/products/conversations/backend/temporal/zendesk_import/starter.py b/products/conversations/backend/temporal/zendesk_import/starter.py
new file mode 100644
index 000000000000..26549b60dc43
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/starter.py
@@ -0,0 +1,43 @@
+"""Helpers to start Zendesk import Temporal workflows."""
+
+from __future__ import annotations
+
+from django.conf import settings
+
+from temporalio.common import WorkflowIDReusePolicy
+
+from posthog.temporal.common.client import async_connect
+
+from products.conversations.backend.temporal.zendesk_import.constants import WORKFLOW_ID_PREFIX
+from products.conversations.backend.temporal.zendesk_import.workflows import (
+ ZendeskImportCoordinatorInput,
+ ZendeskImportCoordinatorWorkflow,
+)
+
+
+async def start_zendesk_import_workflow(
+ *,
+ job_id: str,
+ team_id: int,
+ dry_run: bool = False,
+ max_tickets: int | None = None,
+ default_email_channel_id: str | None = None,
+) -> tuple[str, str | None]:
+ client = await async_connect()
+ workflow_id = f"{WORKFLOW_ID_PREFIX}-{team_id}-{job_id}"
+ task_queue = settings.VIDEO_EXPORT_TASK_QUEUE
+ handle = await client.start_workflow(
+ ZendeskImportCoordinatorWorkflow.run,
+ ZendeskImportCoordinatorInput(
+ job_id=job_id,
+ team_id=team_id,
+ dry_run=dry_run,
+ max_tickets=max_tickets,
+ default_email_channel_id=default_email_channel_id,
+ task_queue=task_queue,
+ ),
+ id=workflow_id,
+ task_queue=task_queue,
+ id_reuse_policy=WorkflowIDReusePolicy.REJECT_DUPLICATE,
+ )
+ return workflow_id, handle.run_id
diff --git a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py
new file mode 100644
index 000000000000..6e61bb28ff72
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py
@@ -0,0 +1,518 @@
+from __future__ import annotations
+
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.models.comment import Comment
+
+from products.conversations.backend.models import EmailChannel, Ticket, ZendeskImportJob
+from products.conversations.backend.models.constants import Channel, Priority, Status
+from products.conversations.backend.temporal.zendesk_import.activities import (
+ ImportBatchInput,
+ UpdateJobProgressInput,
+ UpdateJobStatusInput,
+ _import_ticket_batch_sync,
+ _parse_zendesk_datetime,
+ _update_job_progress_sync,
+ _update_job_status_sync,
+)
+
+M = "products.conversations.backend.temporal.zendesk_import.activities"
+
+
+def _zd_ticket(
+ tid: int,
+ requester_id: int,
+ *,
+ status: str = "open",
+ priority: str = "normal",
+ subject: str = "Help",
+ created_at: str = "2020-01-02T03:04:05Z",
+ updated_at: str = "2020-01-03T04:05:06Z",
+ recipient: str | None = None,
+) -> dict[str, Any]:
+ ticket: dict[str, Any] = {
+ "id": tid,
+ "requester_id": requester_id,
+ "status": status,
+ "priority": priority,
+ "subject": subject,
+ "created_at": created_at,
+ "updated_at": updated_at,
+ }
+ if recipient is not None:
+ ticket["recipient"] = recipient
+ return ticket
+
+
+def _zd_user(uid: int, email: str, role: str | None = "end-user", name: str | None = None) -> dict[str, Any]:
+ return {"id": uid, "email": email, "role": role, "name": name}
+
+
+def _zd_comment(
+ cid: int,
+ author_id: int,
+ *,
+ public: bool = True,
+ body: str = "hello",
+ created_at: str = "2020-01-02T03:04:05Z",
+ attachments: list[dict[str, Any]] | None = None,
+ via_from: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ comment: dict[str, Any] = {
+ "id": cid,
+ "author_id": author_id,
+ "public": public,
+ "body": body,
+ "html_body": "",
+ "created_at": created_at,
+ "attachments": attachments or [],
+ }
+ if via_from is not None:
+ comment["via"] = {"source": {"from": via_from}}
+ return comment
+
+
+class TestZendeskImportBatchActivity(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.job = ZendeskImportJob.objects.unscoped().create(
+ team_id=self.team.id,
+ status=ZendeskImportJob.Status.RUNNING,
+ job_inputs={"subdomain": "acme", "email_address": "[email protected]", "api_token": "tok"},
+ )
+
+ def _run_batch(
+ self,
+ ticket_ids: list[int],
+ *,
+ tickets: list[dict[str, Any]],
+ users: dict[int, dict[str, Any]],
+ comments_by_ticket: dict[int, list[dict[str, Any]]],
+ download: bytes = b"filebytes",
+ download_raises: bool = False,
+ save_return: str | None = "https://media.posthog.test/file",
+ default_email_channel_id: str | None = None,
+ ) -> tuple[Any, MagicMock]:
+ client = MagicMock()
+ client.fetch_tickets.return_value = tickets
+ client.fetch_users.side_effect = lambda ids: {uid: users[uid] for uid in ids if uid in users}
+ client.fetch_comments.side_effect = lambda tid: comments_by_ticket.get(tid, [])
+ if download_raises:
+ client.download_attachment.side_effect = RuntimeError("boom")
+ else:
+ client.download_attachment.return_value = download
+
+ with (
+ patch(f"{M}.ZendeskImportClient", return_value=client),
+ patch(f"{M}.save_file_to_uploaded_media", return_value=save_return),
+ ):
+ result = _import_ticket_batch_sync(
+ ImportBatchInput(
+ job_id=str(self.job.id),
+ team_id=self.team.id,
+ ticket_ids=ticket_ids,
+ default_email_channel_id=default_email_channel_id,
+ )
+ )
+ return result, client
+
+ def test_idempotency_skips_already_imported_tickets(self) -> None:
+ # A ticket already synced (same zendesk_ticket_id) must not be re-fetched or re-inserted;
+ # this guards the pre-filter that makes "run it again later" safe.
+ Ticket.objects.create(
+ team=self.team,
+ ticket_number=1,
+ widget_session_id="existing",
+ distinct_id="d",
+ zendesk_ticket_id=111,
+ )
+
+ result, client = self._run_batch(
+ [111],
+ tickets=[],
+ users={},
+ comments_by_ticket={},
+ )
+
+ self.assertEqual((result.imported, result.skipped, result.failed), (0, 1, 0))
+ self.assertEqual(Ticket.objects.filter(team=self.team, zendesk_ticket_id=111).count(), 1)
+ client.fetch_tickets.assert_not_called()
+
+ def test_import_sets_counters_fields_and_historical_timestamps(self) -> None:
+ # customer message, public agent reply, internal note. The private note is dropped from
+ # every customer-facing denormalized stat (matching the live signal path): message_count
+ # counts the 2 public comments, unread_team_count the 1 customer message,
+ # unread_customer_count the 1 public agent reply, and last_message_* skips the note.
+ comments = [
+ _zd_comment(1, 10, public=True, body="customer msg"),
+ _zd_comment(2, 20, public=True, body="agent reply"),
+ _zd_comment(3, 20, public=False, body="internal note"),
+ ]
+ result, _ = self._run_batch(
+ [201],
+ tickets=[_zd_ticket(201, 10)],
+ users={10: _zd_user(10, "[email protected]"), 20: _zd_user(20, "[email protected]", role="agent")},
+ comments_by_ticket={201: comments},
+ )
+
+ self.assertEqual((result.imported, result.skipped, result.failed), (1, 0, 0))
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=201)
+ self.assertEqual(ticket.message_count, 2)
+ self.assertEqual(ticket.unread_team_count, 1)
+ self.assertEqual(ticket.unread_customer_count, 1)
+ self.assertEqual(ticket.status, Status.OPEN)
+ self.assertEqual(ticket.priority, Priority.MEDIUM)
+ self.assertEqual(ticket.channel_source, Channel.EMAIL)
+ self.assertEqual(ticket.email_subject, "Help")
+ self.assertEqual(ticket.email_from, "[email protected]")
+ # The newest comment is a private note; the customer-facing summary must show the
+ # latest *public* comment instead so internal note text never leaks to the widget.
+ self.assertEqual(ticket.last_message_text, "agent reply")
+ # auto_now_add / auto_now must not clobber the historical Zendesk timestamps.
+ self.assertEqual(ticket.created_at, _parse_zendesk_datetime("2020-01-02T03:04:05Z"))
+ self.assertEqual(ticket.updated_at, _parse_zendesk_datetime("2020-01-03T04:05:06Z"))
+ self.assertEqual(ticket.last_message_at, _parse_zendesk_datetime("2020-01-02T03:04:05Z"))
+
+ stored = Comment.objects.filter(team=self.team, scope="conversations_ticket", item_id=str(ticket.id))
+ self.assertEqual(stored.count(), 3)
+ self.assertEqual(stored.order_by("created_at").first().created_at.year, 2020)
+
+ @parameterized.expand(
+ [
+ ("solved", "solved"),
+ ("closed", "closed"),
+ ("pending", "pending"),
+ ("hold", "hold"),
+ ]
+ )
+ def test_inactive_imported_tickets_have_no_unread_counts(self, _name: str, zendesk_status: str) -> None:
+ # Alert-fatigue guard: a done/parked ticket (resolved/pending/on-hold) must import read —
+ # no unread badge on the agent inbox or customer widget for years-old activity. Message
+ # metadata still populates; only the unread counters are suppressed for non-active statuses.
+ comments = [
+ _zd_comment(1, 10, public=True, body="customer msg"),
+ _zd_comment(2, 20, public=True, body="agent reply"),
+ ]
+ self._run_batch(
+ [211],
+ tickets=[_zd_ticket(211, 10, status=zendesk_status)],
+ users={10: _zd_user(10, "[email protected]"), 20: _zd_user(20, "[email protected]", role="agent")},
+ comments_by_ticket={211: comments},
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=211)
+ self.assertEqual(ticket.message_count, 2)
+ self.assertEqual(ticket.unread_team_count, 0)
+ self.assertEqual(ticket.unread_customer_count, 0)
+
+ def test_unmatched_requester_sets_anonymous_traits_for_display(self) -> None:
+ # The customer must render as their Zendesk name/email (via anonymous_traits) instead of
+ # "Anonymous user".
+ self._run_batch(
+ [205],
+ tickets=[_zd_ticket(205, 10)],
+ users={10: _zd_user(10, "[email protected]", name="Ada Lovelace")},
+ comments_by_ticket={205: []},
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=205)
+ self.assertEqual(ticket.anonymous_traits, {"name": "Ada Lovelace", "email": "[email protected]"})
+
+ def _make_channel(self, from_email: str, token: str) -> EmailChannel:
+ return EmailChannel.objects.create(
+ team=self.team,
+ inbound_token=token,
+ from_email=from_email,
+ from_name="Support",
+ domain="acme.com",
+ )
+
+ @parameterized.expand(
+ [
+ # recipient matches a configured channel (case-insensitively) → that channel wins,
+ # even when a different default is set.
+ ("matched_wins_over_default", "[email protected]", True, "matched"),
+ # recipient is a *.zendesk.com / non-configured address → fall back to the default.
+ ("unmatched_uses_default", "[email protected]", True, "default"),
+ # recipient absent → fall back to the default.
+ ("null_uses_default", None, True, "default"),
+ # no default configured and no match → leave email_config null (don't fabricate one).
+ ("unmatched_no_default_stays_null", "[email protected]", False, None),
+ ]
+ )
+ def test_recipient_maps_to_email_channel(
+ self, _name: str, recipient: str | None, use_default: bool, expected: str | None
+ ) -> None:
+ matched = self._make_channel("[email protected]", "tok-matched")
+ default = self._make_channel("[email protected]", "tok-default")
+
+ self._run_batch(
+ [210],
+ tickets=[_zd_ticket(210, 10, recipient=recipient)],
+ users={10: _zd_user(10, "[email protected]", name="Ada")},
+ comments_by_ticket={210: []},
+ default_email_channel_id=str(default.id) if use_default else None,
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=210)
+ expected_id = {"matched": matched.id, "default": default.id, None: None}[expected]
+ self.assertEqual(ticket.email_config_id, expected_id)
+
+ def test_staff_reply_with_unresolved_role_is_not_attributed_to_customer(self) -> None:
+ # Reported bug: a public agent reply whose author role can't be resolved (role=None) was
+ # typed "customer" and rendered as the ticket's customer identity. It must map to support.
+ comments = [
+ _zd_comment(1, 10, public=True, body="customer question"),
+ _zd_comment(2, 99, public=True, body="staff answer"),
+ ]
+ self._run_batch(
+ [206],
+ tickets=[_zd_ticket(206, 10)],
+ users={
+ 10: _zd_user(10, "[email protected]", name="Person"),
+ 99: _zd_user(99, "[email protected]", role=None), # role unresolved
+ },
+ comments_by_ticket={206: comments},
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=206)
+ by_body = {c.content: c for c in Comment.objects.filter(team=self.team, item_id=str(ticket.id))}
+ self.assertEqual(by_body["customer question"].item_context["author_type"], "customer")
+ self.assertEqual(by_body["staff answer"].item_context["author_type"], "support")
+ # One customer message, one team message.
+ self.assertEqual(ticket.unread_team_count, 1)
+ self.assertEqual(ticket.unread_customer_count, 1)
+
+ def test_second_end_user_reply_is_customer_not_staff(self) -> None:
+ # [email protected] (requester) + [email protected] (another end-user, not a CC) + staff.
+ # person2 must classify as customer by role, not fall to the staff fallback.
+ comments = [
+ _zd_comment(1, 10, public=True, body="from requester"),
+ _zd_comment(2, 11, public=True, body="from second end user"),
+ _zd_comment(3, 20, public=True, body="from staff"),
+ ]
+ self._run_batch(
+ [207],
+ tickets=[_zd_ticket(207, 10)],
+ users={
+ 10: _zd_user(10, "[email protected]", name="Person"),
+ 11: _zd_user(11, "[email protected]", role="end-user"),
+ 20: _zd_user(20, "[email protected]", role="agent"),
+ },
+ comments_by_ticket={207: comments},
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=207)
+ by_body = {c.content: c for c in Comment.objects.filter(team=self.team, item_id=str(ticket.id))}
+ self.assertEqual(by_body["from requester"].item_context["author_type"], "customer")
+ self.assertEqual(by_body["from second end user"].item_context["author_type"], "customer")
+ self.assertEqual(by_body["from staff"].item_context["author_type"], "support")
+ # Each comment carries its own author identity so the thread doesn't show the ticket
+ # requester on every message.
+ self.assertEqual(by_body["from second end user"].item_context["author_email"], "[email protected]")
+ self.assertEqual(by_body["from staff"].item_context["author_email"], "[email protected]")
+
+ def test_deleted_staff_author_recovered_from_comment_via_sender(self) -> None:
+ # Staff author id 88 doesn't resolve (deleted ex-agent, absent from `users`), so name/email
+ # must come from the comment's own via.source.from sender rather than being dropped.
+ comments = [
+ _zd_comment(1, 10, public=True, body="customer"),
+ _zd_comment(
+ 2,
+ 88,
+ public=True,
+ body="staff reply",
+ via_from={"name": "Marcus", "address": "[email protected]"},
+ ),
+ ]
+ self._run_batch(
+ [208],
+ tickets=[_zd_ticket(208, 10)],
+ users={10: _zd_user(10, "[email protected]", name="Person")}, # 88 intentionally missing
+ comments_by_ticket={208: comments},
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=208)
+ staff = Comment.objects.get(team=self.team, item_id=str(ticket.id), content="staff reply")
+ assert staff.item_context is not None
+ self.assertEqual(staff.item_context["author_type"], "support")
+ self.assertEqual(staff.item_context["author_name"], "Marcus")
+ self.assertEqual(staff.item_context["author_email"], "[email protected]")
+
+ def test_nul_bytes_are_stripped_from_persisted_fields(self) -> None:
+ # A single NUL byte anywhere in the batch aborts the whole bulk_create with a Postgres
+ # DataError (which then exhausts the activity's retries), so every Zendesk-sourced string
+ # must be scrubbed. Cover the subject, requester name/email, comment body, and per-comment
+ # author identity in one go.
+ result, _ = self._run_batch(
+ [209],
+ tickets=[_zd_ticket(209, 10, subject="sub\x00ject")],
+ users={10: _zd_user(10, "person\[email protected]", name="Per\x00son")},
+ comments_by_ticket={209: [_zd_comment(1, 10, public=True, body="hell\x00o")]},
+ )
+
+ self.assertEqual(result.imported, 1)
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=209)
+ self.assertEqual(ticket.email_subject, "subject")
+ self.assertEqual(ticket.anonymous_traits, {"name": "Person", "email": "[email protected]"})
+ comment = Comment.objects.get(team=self.team, item_id=str(ticket.id))
+ self.assertEqual(comment.content, "hello")
+ assert comment.item_context is not None
+ self.assertEqual(comment.item_context["author_email"], "[email protected]")
+
+ def test_distinct_id_is_the_zendesk_requester_email(self) -> None:
+ # Access-control invariant: the imported ticket's distinct_id must be the Zendesk requester
+ # email verbatim, never a distinct_id resolved from a PostHog person's `properties.email`.
+ # That analytics field is attacker-settable, so resolving through it would let an attacker
+ # seed a profile with a victim's email and inherit the victim's imported ticket history
+ # (identity poisoning). The email comes from the authenticated Zendesk API, so it's trusted.
+ self._run_batch(
+ [202],
+ tickets=[_zd_ticket(202, 10)],
+ users={10: _zd_user(10, "[email protected]")},
+ comments_by_ticket={202: []},
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=202)
+ self.assertEqual(ticket.distinct_id, "[email protected]")
+
+ def test_ticket_numbers_are_unique_and_gap_free_within_batch(self) -> None:
+ # Pre-existing ticket sets MAX(ticket_number)=5; the batch must assign 6,7,8 under one lock
+ # without colliding on unique_ticket_number_per_team.
+ Ticket.objects.create(team=self.team, ticket_number=5, widget_session_id="s", distinct_id="d")
+
+ self._run_batch(
+ [301, 302, 303],
+ tickets=[_zd_ticket(301, 10), _zd_ticket(302, 10), _zd_ticket(303, 10)],
+ users={10: _zd_user(10, "[email protected]")},
+ comments_by_ticket={},
+ )
+
+ numbers = sorted(
+ Ticket.objects.filter(team=self.team, zendesk_ticket_id__in=[301, 302, 303]).values_list(
+ "ticket_number", flat=True
+ )
+ )
+ self.assertEqual(numbers, [6, 7, 8])
+
+ def test_image_attachment_embedded_in_rich_content(self) -> None:
+ comment = _zd_comment(
+ 1,
+ 10,
+ body="see image",
+ attachments=[{"content_url": "http://zd/a", "file_name": "shot.png", "content_type": "image/png"}],
+ )
+ self._run_batch(
+ [401],
+ tickets=[_zd_ticket(401, 10)],
+ users={10: _zd_user(10, "[email protected]")},
+ comments_by_ticket={401: [comment]},
+ save_return="https://media.posthog.test/shot.png",
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=401)
+ stored = Comment.objects.get(team=self.team, scope="conversations_ticket", item_id=str(ticket.id))
+ rich_content = stored.rich_content
+ assert rich_content is not None
+ image_nodes = [n for n in rich_content["content"] if n.get("type") == "image"]
+ self.assertEqual(image_nodes[0]["attrs"]["src"], "https://media.posthog.test/shot.png")
+ content = stored.content
+ assert content is not None
+ self.assertIn("https://media.posthog.test/shot.png", content)
+
+ def test_non_image_attachment_linked(self) -> None:
+ comment = _zd_comment(
+ 1,
+ 10,
+ body="report",
+ attachments=[{"content_url": "http://zd/b", "file_name": "doc.pdf", "content_type": "application/pdf"}],
+ )
+ self._run_batch(
+ [402],
+ tickets=[_zd_ticket(402, 10)],
+ users={10: _zd_user(10, "[email protected]")},
+ comments_by_ticket={402: [comment]},
+ save_return="https://media.posthog.test/doc.pdf",
+ )
+
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=402)
+ stored = Comment.objects.get(team=self.team, scope="conversations_ticket", item_id=str(ticket.id))
+ content = stored.content
+ assert content is not None
+ self.assertIn("[doc.pdf](https://media.posthog.test/doc.pdf)", content)
+ self.assertIsNone(stored.rich_content)
+
+ def test_failed_attachment_download_does_not_fail_the_ticket(self) -> None:
+ comment = _zd_comment(
+ 1,
+ 10,
+ body="body survives",
+ attachments=[{"content_url": "http://zd/c", "file_name": "x.png", "content_type": "image/png"}],
+ )
+ result, _ = self._run_batch(
+ [403],
+ tickets=[_zd_ticket(403, 10)],
+ users={10: _zd_user(10, "[email protected]")},
+ comments_by_ticket={403: [comment]},
+ download_raises=True,
+ )
+
+ self.assertEqual((result.imported, result.failed), (1, 0))
+ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=403)
+ stored = Comment.objects.get(team=self.team, scope="conversations_ticket", item_id=str(ticket.id))
+ self.assertEqual(stored.content, "body survives")
+
+
+class TestZendeskImportJobUpdates(BaseTest):
+ def _make_job(self, **kwargs: Any) -> ZendeskImportJob:
+ return ZendeskImportJob.objects.unscoped().create(
+ team_id=self.team.id,
+ status=ZendeskImportJob.Status.PENDING,
+ job_inputs={"subdomain": "acme", "email_address": "[email protected]", "api_token": "t"},
+ **kwargs,
+ )
+
+ @parameterized.expand(
+ [
+ (ZendeskImportJob.Status.RUNNING, True, False, None),
+ (ZendeskImportJob.Status.COMPLETED, False, True, None),
+ (ZendeskImportJob.Status.FAILED, False, True, "kaboom"),
+ ]
+ )
+ def test_status_update_persists_timestamps_and_error(
+ self, status: str, started_set: bool, finished_set: bool, latest_error: str | None
+ ) -> None:
+ # Guards the narrowed update_fields: started_at / finished_at / latest_error must actually
+ # be written, not silently dropped by an incomplete update_fields list.
+ job = self._make_job()
+
+ _update_job_status_sync(UpdateJobStatusInput(job_id=str(job.id), status=status, latest_error=latest_error))
+
+ job.refresh_from_db()
+ self.assertEqual(job.status, status)
+ self.assertEqual(job.started_at is not None, started_set)
+ self.assertEqual(job.finished_at is not None, finished_set)
+ self.assertEqual(job.latest_error, latest_error)
+
+ def test_progress_update_accumulates_counters_and_cursor(self) -> None:
+ # F()-based increments must accumulate across batches (not overwrite) and persist the cursor.
+ job = self._make_job()
+
+ _update_job_progress_sync(
+ UpdateJobProgressInput(job_id=str(job.id), total_delta=100, processed_delta=10, imported_delta=8)
+ )
+ _update_job_progress_sync(
+ UpdateJobProgressInput(job_id=str(job.id), processed_delta=5, skipped_delta=2, export_cursor="c2")
+ )
+
+ job.refresh_from_db()
+ self.assertEqual(job.total_tickets, 100)
+ self.assertEqual(job.processed_tickets, 15)
+ self.assertEqual(job.imported_tickets, 8)
+ self.assertEqual(job.skipped_tickets, 2)
+ self.assertEqual(job.export_cursor, "c2")
diff --git a/products/conversations/backend/temporal/zendesk_import/tests/test_client.py b/products/conversations/backend/temporal/zendesk_import/tests/test_client.py
new file mode 100644
index 000000000000..2c27d8ad4ac4
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/tests/test_client.py
@@ -0,0 +1,129 @@
+from collections.abc import Iterable
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.conversations.backend.temporal.zendesk_import.client import (
+ ZendeskAttachmentTooLargeError,
+ ZendeskCredentials,
+ ZendeskImportClient,
+ validate_zendesk_credentials,
+)
+
+M = "products.conversations.backend.temporal.zendesk_import.client"
+
+
+class _FakeStreamResponse:
+ def __init__(self, *, headers: dict[str, str] | None = None, chunks: Iterable[bytes] = ()) -> None:
+ self.status_code = 200
+ self.headers = headers or {}
+ self._chunks = list(chunks)
+ self.consumed_chunks = 0
+
+ def __enter__(self) -> "_FakeStreamResponse":
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ return None
+
+ def raise_for_status(self) -> None:
+ pass
+
+ def iter_content(self, chunk_size: int = 0) -> Iterable[bytes]:
+ for chunk in self._chunks:
+ self.consumed_chunks += 1
+ yield chunk
+
+
+class TestValidateZendeskCredentials:
+ @pytest.mark.parametrize(
+ "subdomain",
+ [
+ # A `#` turns the rest of the base URL into a fragment, so the real host would become
+ # the attacker value instead of "<label>.zendesk.com" — the Basic auth token must not
+ # be sent there.
+ pytest.param("attacker.example#", id="host_fragment"),
+ pytest.param("169.254.169.254#", id="metadata_ip_fragment"),
+ pytest.param("foo.bar", id="multi_label"),
+ pytest.param("foo@bar", id="userinfo"),
+ ],
+ )
+ def test_rejects_host_retargeting_subdomain_without_request(self, subdomain: str) -> None:
+ credentials = ZendeskCredentials(subdomain=subdomain, email_address="[email protected]", api_token="token")
+
+ with patch(f"{M}.make_tracked_session") as mock_session:
+ assert validate_zendesk_credentials(credentials) is False
+ mock_session.assert_not_called()
+
+
+class TestDownloadAttachmentSizeCap:
+ def _client(self) -> ZendeskImportClient:
+ return ZendeskImportClient(
+ ZendeskCredentials(subdomain="acme", email_address="[email protected]", api_token="tok")
+ )
+
+ def test_content_length_precheck_aborts_before_reading_body(self) -> None:
+ client = self._client()
+ resp = _FakeStreamResponse(headers={"Content-Length": "11"}, chunks=[b"x" * 11])
+ client._session = MagicMock()
+ client._session.get.return_value = resp
+
+ with pytest.raises(ZendeskAttachmentTooLargeError):
+ client.download_attachment("https://acme.zendesk.com/a", max_bytes=10)
+ # Declared oversize is rejected without streaming any chunk into memory.
+ assert resp.consumed_chunks == 0
+
+ def test_streaming_aborts_when_lying_content_length(self) -> None:
+ # No/undersized Content-Length must not let an oversized body through — the
+ # chunked read has to abort once the running total crosses the cap.
+ client = self._client()
+ resp = _FakeStreamResponse(headers={}, chunks=[b"x" * 8, b"x" * 8])
+ client._session = MagicMock()
+ client._session.get.return_value = resp
+
+ with pytest.raises(ZendeskAttachmentTooLargeError):
+ client.download_attachment("https://acme.zendesk.com/a", max_bytes=10)
+
+ def test_returns_bytes_within_cap(self) -> None:
+ client = self._client()
+ resp = _FakeStreamResponse(headers={"Content-Length": "6"}, chunks=[b"abc", b"def"])
+ client._session = MagicMock()
+ client._session.get.return_value = resp
+
+ assert client.download_attachment("https://acme.zendesk.com/a", max_bytes=10) == b"abcdef"
+
+
+class TestExpectedHostGuard:
+ def _client(self) -> ZendeskImportClient:
+ return ZendeskImportClient(
+ ZendeskCredentials(subdomain="acme", email_address="[email protected]", api_token="tok")
+ )
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ # Right host, wrong scheme: a host-only check would pass and send the Basic auth token
+ # over cleartext http. Both the plaintext downgrade and any off-host redirect must be
+ # refused before a request (and its Authorization header) goes out.
+ pytest.param("http://acme.zendesk.com/api/v2/tickets/1/comments.json", id="http_downgrade"),
+ pytest.param("https://evil.example.com/steal", id="off_host"),
+ pytest.param("https://acme.zendesk.com.evil.com/steal", id="suffix_host"),
+ ],
+ )
+ def test_download_attachment_refuses_and_sends_nothing(self, url: str) -> None:
+ client = self._client()
+ client._session = MagicMock()
+
+ with pytest.raises(ValueError):
+ client.download_attachment(url, max_bytes=10)
+ client._session.get.assert_not_called()
+
+ def test_request_refuses_http_absolute_url_and_sends_nothing(self) -> None:
+ # `next_page` in a comments response is an absolute URL echoed straight into _request; an
+ # http:// value must be rejected before the token-bearing request is issued.
+ client = self._client()
+ client._session = MagicMock()
+
+ with pytest.raises(ValueError):
+ client._request("GET", "http://acme.zendesk.com/api/v2/tickets/1/comments.json")
+ client._session.request.assert_not_called()
diff --git a/products/conversations/backend/temporal/zendesk_import/tests/test_mappers.py b/products/conversations/backend/temporal/zendesk_import/tests/test_mappers.py
new file mode 100644
index 000000000000..529ce6210fa8
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/tests/test_mappers.py
@@ -0,0 +1,67 @@
+from parameterized import parameterized
+
+from products.conversations.backend.models.constants import Priority, Status
+from products.conversations.backend.temporal.zendesk_import.mappers import (
+ map_zendesk_author_type,
+ map_zendesk_priority,
+ map_zendesk_status,
+)
+
+
+class TestZendeskMappers:
+ @parameterized.expand(
+ [
+ ("new", Status.NEW),
+ ("open", Status.OPEN),
+ ("pending", Status.PENDING),
+ ("hold", Status.ON_HOLD),
+ ("solved", Status.RESOLVED),
+ ("closed", Status.RESOLVED),
+ ("unknown", Status.OPEN),
+ (None, Status.NEW),
+ ]
+ )
+ def test_map_zendesk_status(self, raw: str | None, expected: str) -> None:
+ assert map_zendesk_status(raw) == expected
+
+ @parameterized.expand(
+ [
+ ("low", Priority.LOW),
+ ("normal", Priority.MEDIUM),
+ ("high", Priority.HIGH),
+ ("urgent", Priority.HIGH),
+ (None, None),
+ ]
+ )
+ def test_map_zendesk_priority(self, raw: str | None, expected: str | None) -> None:
+ assert map_zendesk_priority(raw) == expected
+
+ @parameterized.expand(
+ [
+ # role, is_public, is_customer_side, expected_author_type, expected_is_private
+ # Role is authoritative when resolved, regardless of customer-side membership.
+ ("end_user", "end-user", True, True, "customer", False),
+ ("end_user_non_customer_side", "end-user", True, False, "customer", False),
+ ("agent", "agent", True, False, "support", False),
+ ("admin", "admin", True, False, "support", False),
+ # A second end-user (person2) in a thread resolves by role → customer, not staff.
+ ("second_end_user", "end-user", True, False, "customer", False),
+ ("agent_private_note", "agent", False, False, "support", True),
+ # Role unresolved (hard-deleted): customer-side → customer, otherwise staff.
+ ("deleted_customer_side", None, True, True, "customer", False),
+ ("deleted_agent_not_customer_side", None, True, False, "support", False),
+ ]
+ )
+ def test_map_zendesk_author_type(
+ self,
+ _name: str,
+ role: str | None,
+ is_public: bool,
+ is_customer_side: bool,
+ author_type: str,
+ is_private: bool,
+ ) -> None:
+ assert map_zendesk_author_type(role=role, is_public=is_public, is_customer_side=is_customer_side) == (
+ author_type,
+ is_private,
+ )
diff --git a/products/conversations/backend/temporal/zendesk_import/tests/test_workflows.py b/products/conversations/backend/temporal/zendesk_import/tests/test_workflows.py
new file mode 100644
index 000000000000..e0cce67a29e1
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/tests/test_workflows.py
@@ -0,0 +1,95 @@
+from __future__ import annotations
+
+import pytest
+
+from django.conf import settings
+
+from temporalio import activity, workflow
+
+from products.conversations.backend.temporal.zendesk_import.activities import (
+ EnumerateTicketsInput,
+ EnumerateTicketsOutput,
+ UpdateJobProgressInput,
+ UpdateJobStatusInput,
+)
+from products.conversations.backend.temporal.zendesk_import.constants import CONTINUE_AS_NEW_AFTER_PAGES
+from products.conversations.backend.temporal.zendesk_import.workflows import (
+ ZendeskImportBatchWorkflowInput,
+ ZendeskImportCoordinatorInput,
+ ZendeskImportCoordinatorOutput,
+ ZendeskImportCoordinatorWorkflow,
+)
+
+# Enough pages to cross exactly one continue-as-new boundary: the first generation processes
+# CONTINUE_AS_NEW_AFTER_PAGES pages, the second processes the remainder. One unique ticket per
+# page, so a fully-successful import returns exactly TOTAL_PAGES imported.
+TOTAL_PAGES = CONTINUE_AS_NEW_AFTER_PAGES + 5
+
+
+def _page_from_cursor(cursor: str | None) -> int:
+ return 0 if cursor is None else int(cursor)
+
+
[email protected](name="zendesk_import_enumerate_tickets_activity")
+async def _fake_enumerate(input: EnumerateTicketsInput) -> EnumerateTicketsOutput:
+ page = _page_from_cursor(input.cursor)
+ return EnumerateTicketsOutput(
+ ticket_ids=[1000 + page],
+ next_cursor=str(page + 1),
+ end_of_stream=(page + 1 >= TOTAL_PAGES),
+ )
+
+
[email protected](name="zendesk_import_update_job_progress_activity")
+async def _fake_progress(input: UpdateJobProgressInput) -> None:
+ return None
+
+
[email protected](name="zendesk_import_update_job_status_activity")
+async def _fake_status(input: UpdateJobStatusInput) -> None:
+ return None
+
+
[email protected](name="zendesk-import-batch")
+class _StubBatchWorkflow:
+ """Stands in for ZendeskImportBatchWorkflow (same registered name). Reports one import per
+ ticket id it actually receives, so a batch that never runs (child-id collision -> the
+ coordinator swallows WorkflowAlreadyStartedError and returns zeros) contributes nothing to the
+ total — that's the signal this test keys on."""
+
+ @workflow.run
+ async def run(self, input: ZendeskImportBatchWorkflowInput) -> ZendeskImportCoordinatorOutput:
+ return ZendeskImportCoordinatorOutput(imported=len(input.ticket_ids), skipped=0, failed=0)
+
+
+class TestZendeskImportCoordinatorContinueAsNew:
+ @pytest.mark.asyncio
+ async def test_import_continues_past_continue_as_new_boundary(self) -> None:
+ # Regression: child workflow ids must stay globally unique across continue-as-new. If they
+ # revert to the per-generation pages_processed (which resets to 0 each generation), the
+ # second generation regenerates the first generation's completed child ids; with
+ # ALLOW_DUPLICATE_FAILED_ONLY every such start raises WorkflowAlreadyStartedError, the
+ # coordinator counts zero, and the import silently stalls at the boundary (~50k tickets).
+ from temporalio.testing import WorkflowEnvironment
+ from temporalio.worker import Worker
+
+ # Children are dispatched to this queue explicitly, so the worker must host it (single queue
+ # for coordinator + children keeps the test self-contained).
+ task_queue = settings.VIDEO_EXPORT_TASK_QUEUE
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[ZendeskImportCoordinatorWorkflow, _StubBatchWorkflow],
+ activities=[_fake_enumerate, _fake_progress, _fake_status],
+ ):
+ result = await env.client.execute_workflow(
+ ZendeskImportCoordinatorWorkflow.run,
+ ZendeskImportCoordinatorInput(job_id="job-1", team_id=1, task_queue=task_queue),
+ id="test-zendesk-import-can",
+ task_queue=task_queue,
+ )
+
+ # Every enumerated ticket imported — nothing lost at the continue-as-new boundary.
+ assert result.imported == TOTAL_PAGES
diff --git a/products/conversations/backend/temporal/zendesk_import/workflows.py b/products/conversations/backend/temporal/zendesk_import/workflows.py
new file mode 100644
index 000000000000..0c7ce860bef6
--- /dev/null
+++ b/products/conversations/backend/temporal/zendesk_import/workflows.py
@@ -0,0 +1,313 @@
+"""Temporal workflows for Zendesk historical ticket import."""
+
+from __future__ import annotations
+
+import json
+import asyncio
+from dataclasses import dataclass
+from datetime import timedelta
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from temporalio.exceptions import WorkflowAlreadyStartedError
+
+with workflow.unsafe.imports_passed_through():
+ from products.conversations.backend.models.zendesk_import_job import ZendeskImportJob
+ from products.conversations.backend.temporal.zendesk_import.activities import (
+ EnumerateTicketsInput,
+ ImportBatchInput,
+ UpdateJobProgressInput,
+ UpdateJobStatusInput,
+ zendesk_import_batch_activity,
+ zendesk_import_enumerate_tickets_activity,
+ zendesk_import_update_job_progress_activity,
+ zendesk_import_update_job_status_activity,
+ )
+ from products.conversations.backend.temporal.zendesk_import.constants import (
+ BATCH_SIZE,
+ BATCH_WORKFLOW_ID_PREFIX,
+ CONTINUE_AS_NEW_AFTER_PAGES,
+ MAX_CONCURRENT_BATCH_WORKFLOWS,
+ WORKFLOW_ID_PREFIX,
+ )
+
+
+IMPORT_FAILED_MESSAGE = "The import failed. Please try again or contact support if it persists."
+IMPORT_CANCELLED_MESSAGE = "The import was cancelled."
+
+
+@dataclass
+class ZendeskImportCoordinatorInput:
+ job_id: str
+ team_id: int
+ cursor: str | None = None
+ pages_processed: int = 0
+ # Cumulative pages completed in prior continue-as-new generations. Child workflow IDs are
+ # built from the *absolute* page index (pages_offset + pages_processed); without this the
+ # per-run pages_processed resets to 0 each generation, regenerating child IDs that collide
+ # with the previous generation's already-completed children (ALLOW_DUPLICATE_FAILED_ONLY ->
+ # WorkflowAlreadyStartedError -> zero imports past the first CAN boundary).
+ pages_offset: int = 0
+ dry_run: bool = False
+ # Cap total tickets enumerated for import (ops/testing). None = no cap. Carried across
+ # continue-as-new as the *remaining* budget so the cap holds over the whole run.
+ max_tickets: int | None = None
+ # Fallback EmailChannel (UUID str) for tickets whose Zendesk recipient doesn't match a
+ # configured support address. None = leave email_config null in those cases.
+ default_email_channel_id: str | None = None
+ # Worker queue for batch child workflows. Passed in at start time (starter.py) so the
+ # coordinator never reads django.conf.settings inside the sandbox.
+ task_queue: str = ""
+ # Cumulative batch totals from prior continue-as-new generations (the in-memory counters
+ # reset on each generation; job progress activities already persist to the DB).
+ imported_offset: int = 0
+ skipped_offset: int = 0
+ failed_offset: int = 0
+
+
+@dataclass
+class ZendeskImportCoordinatorOutput:
+ imported: int
+ skipped: int
+ failed: int
+
+
+@dataclass
+class ZendeskImportBatchWorkflowInput:
+ job_id: str
+ team_id: int
+ ticket_ids: list[int]
+ dry_run: bool = False
+ default_email_channel_id: str | None = None
+
+
+RETRY_POLICY = RetryPolicy(maximum_attempts=5, initial_interval=timedelta(seconds=5))
+
+
[email protected](name="zendesk-import-coordinator")
+class ZendeskImportCoordinatorWorkflow:
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> ZendeskImportCoordinatorInput:
+ if not inputs:
+ raise ValueError("ZendeskImportCoordinatorWorkflow requires input")
+ loaded = json.loads(inputs[0])
+ return ZendeskImportCoordinatorInput(**loaded)
+
+ async def _run_batch_child(
+ self, *, child_id: str, wf_input: ZendeskImportBatchWorkflowInput, task_queue: str
+ ) -> ZendeskImportCoordinatorOutput:
+ try:
+ return await workflow.execute_child_workflow(
+ ZendeskImportBatchWorkflow.run,
+ wf_input,
+ id=child_id,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
+ task_queue=task_queue,
+ )
+ except WorkflowAlreadyStartedError:
+ # workflow.logger is a stdlib LoggerAdapter — structlog-style kwargs raise TypeError.
+ workflow.logger.info("zendesk_import_batch_already_running", extra={"child_id": child_id})
+ return ZendeskImportCoordinatorOutput(imported=0, skipped=0, failed=0)
+
+ @workflow.run
+ async def run(self, input: ZendeskImportCoordinatorInput) -> ZendeskImportCoordinatorOutput:
+ if input.pages_processed == 0:
+ await workflow.execute_activity(
+ zendesk_import_update_job_status_activity,
+ UpdateJobStatusInput(job_id=input.job_id, status=ZendeskImportJob.Status.RUNNING),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RETRY_POLICY,
+ )
+
+ total_imported = input.imported_offset
+ total_skipped = input.skipped_offset
+ total_failed = input.failed_offset
+ cursor = input.cursor
+ pages_processed = input.pages_processed
+ selected = 0 # tickets picked for import this run (against max_tickets budget)
+
+ try:
+ while True:
+ page = await workflow.execute_activity(
+ zendesk_import_enumerate_tickets_activity,
+ EnumerateTicketsInput(job_id=input.job_id, cursor=cursor),
+ start_to_close_timeout=timedelta(minutes=10),
+ retry_policy=RETRY_POLICY,
+ )
+ cursor = page.next_cursor
+ pages_processed += 1
+
+ ticket_ids = page.ticket_ids
+ reached_cap = False
+ if input.max_tickets is not None:
+ remaining = input.max_tickets - selected
+ if remaining <= 0:
+ break
+ if len(ticket_ids) >= remaining:
+ ticket_ids = ticket_ids[:remaining]
+ reached_cap = True
+ selected += len(ticket_ids)
+ page.ticket_ids = ticket_ids
+
+ # Publish a running total as tickets are enumerated (cursor export has no
+ # upfront count) so the UI can render "processed / total".
+ if page.ticket_ids:
+ await workflow.execute_activity(
+ zendesk_import_update_job_progress_activity,
+ UpdateJobProgressInput(
+ job_id=input.job_id,
+ total_delta=len(page.ticket_ids),
+ export_cursor=cursor,
+ ),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RETRY_POLICY,
+ )
+
+ batches = [page.ticket_ids[i : i + BATCH_SIZE] for i in range(0, len(page.ticket_ids), BATCH_SIZE)]
+
+ # Fan out batches with bounded concurrency, checkpointing progress per window.
+ for window_start in range(0, len(batches), MAX_CONCURRENT_BATCH_WORKFLOWS):
+ window = batches[window_start : window_start + MAX_CONCURRENT_BATCH_WORKFLOWS]
+ results = await asyncio.gather(
+ *[
+ self._run_batch_child(
+ child_id=(
+ f"{BATCH_WORKFLOW_ID_PREFIX}-{input.job_id}"
+ f"-{input.pages_offset + pages_processed}-{window_start + offset}"
+ ),
+ wf_input=ZendeskImportBatchWorkflowInput(
+ job_id=input.job_id,
+ team_id=input.team_id,
+ ticket_ids=batch,
+ dry_run=input.dry_run,
+ default_email_channel_id=input.default_email_channel_id,
+ ),
+ task_queue=input.task_queue,
+ )
+ for offset, batch in enumerate(window)
+ ]
+ )
+
+ window_imported = sum(r.imported for r in results)
+ window_skipped = sum(r.skipped for r in results)
+ window_failed = sum(r.failed for r in results)
+ window_processed = sum(len(batch) for batch in window)
+ total_imported += window_imported
+ total_skipped += window_skipped
+ total_failed += window_failed
+
+ await workflow.execute_activity(
+ zendesk_import_update_job_progress_activity,
+ UpdateJobProgressInput(
+ job_id=input.job_id,
+ processed_delta=window_processed,
+ imported_delta=window_imported,
+ skipped_delta=window_skipped,
+ failed_delta=window_failed,
+ export_cursor=cursor,
+ ),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RETRY_POLICY,
+ )
+
+ if page.end_of_stream or reached_cap:
+ break
+
+ if pages_processed >= CONTINUE_AS_NEW_AFTER_PAGES:
+ workflow.continue_as_new(
+ ZendeskImportCoordinatorInput(
+ job_id=input.job_id,
+ team_id=input.team_id,
+ cursor=cursor,
+ pages_processed=0,
+ pages_offset=input.pages_offset + pages_processed,
+ dry_run=input.dry_run,
+ max_tickets=None if input.max_tickets is None else input.max_tickets - selected,
+ default_email_channel_id=input.default_email_channel_id,
+ task_queue=input.task_queue,
+ imported_offset=total_imported,
+ skipped_offset=total_skipped,
+ failed_offset=total_failed,
+ )
+ )
+
+ await workflow.execute_activity(
+ zendesk_import_update_job_status_activity,
+ UpdateJobStatusInput(job_id=input.job_id, status=ZendeskImportJob.Status.COMPLETED),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RETRY_POLICY,
+ )
+ return ZendeskImportCoordinatorOutput(
+ imported=total_imported,
+ skipped=total_skipped,
+ failed=total_failed,
+ )
+ except asyncio.CancelledError:
+ # Cancellation (admin cancels from the Temporal UI/CLI, handle.cancel(), a future
+ # "cancel import" action) is delivered as asyncio.CancelledError, which subclasses
+ # BaseException — the `except Exception` below can't see it. Without recording a
+ # terminal state here the ZendeskImportJob row stays stuck at RUNNING forever, and the
+ # settings UI polls "Syncing" indefinitely (the migrate_zendesk_tickets --force flag
+ # exists to clean up exactly this). Scheduling a cleanup activity after cancel is the
+ # supported Temporal pattern; the request is state-once so this await isn't re-cancelled.
+ workflow.logger.warning(
+ "zendesk_import_coordinator_cancelled",
+ extra={"job_id": input.job_id, "team_id": input.team_id},
+ )
+ await workflow.execute_activity(
+ zendesk_import_update_job_status_activity,
+ UpdateJobStatusInput(
+ job_id=input.job_id,
+ status=ZendeskImportJob.Status.FAILED,
+ latest_error=IMPORT_CANCELLED_MESSAGE,
+ ),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RETRY_POLICY,
+ )
+ raise
+ except Exception:
+ # Raw exception strings can carry internal hostnames, query details, or
+ # secrets from failing requests. Log the full error server-side and persist
+ # only a generic message for the admin-facing UI.
+ workflow.logger.exception(
+ "zendesk_import_coordinator_failed",
+ extra={"job_id": input.job_id, "team_id": input.team_id},
+ )
+ await workflow.execute_activity(
+ zendesk_import_update_job_status_activity,
+ UpdateJobStatusInput(
+ job_id=input.job_id,
+ status=ZendeskImportJob.Status.FAILED,
+ latest_error=IMPORT_FAILED_MESSAGE,
+ ),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RETRY_POLICY,
+ )
+ raise
+
+
[email protected](name="zendesk-import-batch")
+class ZendeskImportBatchWorkflow:
+ @workflow.run
+ async def run(self, input: ZendeskImportBatchWorkflowInput) -> ZendeskImportCoordinatorOutput:
+ result = await workflow.execute_activity(
+ zendesk_import_batch_activity,
+ ImportBatchInput(
+ job_id=input.job_id,
+ team_id=input.team_id,
+ ticket_ids=input.ticket_ids,
+ dry_run=input.dry_run,
+ default_email_channel_id=input.default_email_channel_id,
+ ),
+ start_to_close_timeout=timedelta(minutes=30),
+ retry_policy=RETRY_POLICY,
+ )
+ return ZendeskImportCoordinatorOutput(
+ imported=result.imported,
+ skipped=result.skipped,
+ failed=result.failed,
+ )
+
+
+def coordinator_workflow_id(team_id: int) -> str:
+ return f"{WORKFLOW_ID_PREFIX}-{team_id}"
diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsx
index 48532327dea9..8da2729f13d2 100644
--- a/products/conversations/frontend/components/Chat/Message.tsx
+++ b/products/conversations/frontend/components/Chat/Message.tsx
@@ -69,7 +69,9 @@ export function Message({ message, isCustomer, deliveryStatus }: MessageProps):
className="text-sm"
/>
) : (
- <SupportMarkdown className="text-sm">{message.content}</SupportMarkdown>
+ <SupportMarkdown className="text-sm" disableImages={message.fromZendesk}>
+ {message.content}
+ </SupportMarkdown>
)}
</div>
<div className="flex items-center justify-end gap-1">
diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.ts
index 51a847f6031c..58aba1b80053 100644
--- a/products/conversations/frontend/generated/api.schemas.ts
+++ b/products/conversations/frontend/generated/api.schemas.ts
@@ -731,6 +731,8 @@ export interface TicketApi {
readonly github_repo: string | null
/** @nullable */
readonly github_issue_number: number | null
+ /** @nullable */
+ readonly zendesk_ticket_id: number | null
/**
* Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.
* @nullable
@@ -821,6 +823,8 @@ export interface PatchedTicketApi {
readonly github_repo?: string | null
/** @nullable */
readonly github_issue_number?: number | null
+ /** @nullable */
+ readonly zendesk_ticket_id?: number | null
/**
* Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.
* @nullable
@@ -1002,6 +1006,95 @@ export interface PaginatedTicketViewListApi {
results: TicketViewApi[]
}
+export interface ZendeskImportStartApi {
+ /**
+ * Zendesk subdomain (e.g. 'acme' from acme.zendesk.com).
+ * @maxLength 255
+ */
+ subdomain: string
+ /** Zendesk agent email tied to the API token. */
+ email_address: string
+ /**
+ * Zendesk API token with ticket read access.
+ * @maxLength 500
+ */
+ api_token: string
+ /**
+ * Optional fallback email channel for tickets whose original Zendesk recipient doesn't match a configured support address (or isn't an email). Omit or null to leave those tickets without an email channel.
+ * @nullable
+ */
+ default_email_channel_id?: string | null
+}
+
+/**
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+export type ZendeskImportJobStatusEnumApi =
+ (typeof ZendeskImportJobStatusEnumApi)[keyof typeof ZendeskImportJobStatusEnumApi]
+
+export const ZendeskImportJobStatusEnumApi = {
+ Pending: 'pending',
+ Running: 'running',
+ Completed: 'completed',
+ Failed: 'failed',
+} as const
+
+export interface ZendeskImportJobApi {
+ /** Unique identifier for the import job. */
+ readonly id: string
+ /** Current job state: pending, running, completed, or failed.
+ *
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: ZendeskImportJobStatusEnumApi
+ /**
+ * Zendesk subdomain used for this import job.
+ * @nullable
+ */
+ readonly subdomain: string | null
+ /** Whether stored Zendesk credentials exist for this job (the token/email are never returned). */
+ readonly has_credentials: boolean
+ /** Total number of tickets discovered for import. */
+ readonly total_tickets: number
+ /** Number of tickets processed so far. */
+ readonly processed_tickets: number
+ /** Number of tickets successfully imported. */
+ readonly imported_tickets: number
+ /** Number of tickets skipped because they were already imported. */
+ readonly skipped_tickets: number
+ /** Number of tickets that failed to import. */
+ readonly failed_tickets: number
+ /**
+ * When the import started running.
+ * @nullable
+ */
+ readonly started_at: string | null
+ /**
+ * When the import reached a terminal state.
+ * @nullable
+ */
+ readonly finished_at: string | null
+ /**
+ * Generic, user-safe error message when the job failed.
+ * @nullable
+ */
+ readonly latest_error: string | null
+ /** When the import job was created. */
+ readonly created_at: string
+ /** When the import job was last updated. */
+ readonly updated_at: string
+}
+
+export interface ZendeskImportErrorApi {
+ /** Human-readable error message. */
+ detail: string
+}
+
export type ConversationsListParams = {
/**
* Number of results to return per page.
diff --git a/products/conversations/frontend/generated/api.ts b/products/conversations/frontend/generated/api.ts
index 9ea15fb00360..d0419d7db510 100644
--- a/products/conversations/frontend/generated/api.ts
+++ b/products/conversations/frontend/generated/api.ts
@@ -34,6 +34,8 @@ import type {
TicketMessageApi,
TicketReplyRequestApi,
TicketViewApi,
+ ZendeskImportJobApi,
+ ZendeskImportStartApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -638,3 +640,34 @@ export const conversationsViewsDestroy = async (
method: 'DELETE',
})
}
+
+export const getConversationsZendeskImportsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/conversations/zendesk_imports/`
+}
+
+export const conversationsZendeskImportsCreate = async (
+ projectId: string,
+ zendeskImportStartApi: ZendeskImportStartApi,
+ options?: RequestInit
+): Promise<ZendeskImportJobApi> => {
+ return apiMutator<ZendeskImportJobApi>(getConversationsZendeskImportsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(zendeskImportStartApi),
+ })
+}
+
+export const getConversationsZendeskImportsStatusRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/conversations/zendesk_imports/status/`
+}
+
+export const conversationsZendeskImportsStatusRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<ZendeskImportJobApi> => {
+ return apiMutator<ZendeskImportJobApi>(getConversationsZendeskImportsStatusRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/conversations/frontend/generated/api.zod.ts b/products/conversations/frontend/generated/api.zod.ts
index 7acc17ae7910..1cd612dbffb8 100644
--- a/products/conversations/frontend/generated/api.zod.ts
+++ b/products/conversations/frontend/generated/api.zod.ts
@@ -373,3 +373,25 @@ export const ConversationsViewsCreateBody = /* @__PURE__ */ zod.object({
'Saved ticket filter criteria. May contain status, priority, channel, sla, assignee, tags, dateFrom, dateTo, and sorting keys.'
),
})
+
+export const conversationsZendeskImportsCreateBodySubdomainMax = 255
+
+export const conversationsZendeskImportsCreateBodyApiTokenMax = 500
+
+export const ConversationsZendeskImportsCreateBody = /* @__PURE__ */ zod.object({
+ subdomain: zod
+ .string()
+ .max(conversationsZendeskImportsCreateBodySubdomainMax)
+ .describe("Zendesk subdomain (e.g. 'acme' from acme.zendesk.com)."),
+ email_address: zod.email().describe('Zendesk agent email tied to the API token.'),
+ api_token: zod
+ .string()
+ .max(conversationsZendeskImportsCreateBodyApiTokenMax)
+ .describe('Zendesk API token with ticket read access.'),
+ default_email_channel_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ "Optional fallback email channel for tickets whose original Zendesk recipient doesn't match a configured support address (or isn't an email). Omit or null to leave those tickets without an email channel."
+ ),
+})
diff --git a/products/conversations/frontend/scenes/settings/SupportSettingsScene.tsx b/products/conversations/frontend/scenes/settings/SupportSettingsScene.tsx
index d02c7c317fa5..ec570dd41906 100644
--- a/products/conversations/frontend/scenes/settings/SupportSettingsScene.tsx
+++ b/products/conversations/frontend/scenes/settings/SupportSettingsScene.tsx
@@ -16,6 +16,7 @@ const VALID_SETTING_IDS = new Set<SettingId>([
'conversations-general',
'conversations-notifications',
'conversations-ai',
+ 'conversations-imports',
])
const DEFAULT_SETTING_ID: SettingId = 'conversations-general'
diff --git a/products/conversations/frontend/scenes/settings/ZendeskImportSection.tsx b/products/conversations/frontend/scenes/settings/ZendeskImportSection.tsx
new file mode 100644
index 000000000000..894c4a9bdf67
--- /dev/null
+++ b/products/conversations/frontend/scenes/settings/ZendeskImportSection.tsx
@@ -0,0 +1,159 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonCard, LemonInput, LemonSelect, LemonTag } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { OrganizationMembershipLevel } from 'lib/constants'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { SceneSection } from '~/layout/scenes/components/SceneSection'
+
+import { zendeskImportLogic, ZendeskImportJobStatus } from './zendeskImportLogic'
+
+function statusTag(status: ZendeskImportJobStatus | undefined): JSX.Element | null {
+ if (!status) {
+ return null
+ }
+ if (status === 'running' || status === 'pending') {
+ return (
+ <LemonTag type="warning" size="small">
+ Syncing
+ </LemonTag>
+ )
+ }
+ if (status === 'completed') {
+ return (
+ <LemonTag type="success" size="small">
+ Done
+ </LemonTag>
+ )
+ }
+ return (
+ <LemonTag type="danger" size="small">
+ Failed
+ </LemonTag>
+ )
+}
+
+export function ZendeskImportSection(): JSX.Element {
+ return (
+ <SceneSection
+ title="Zendesk import"
+ description="Import historical Zendesk Support tickets and message threads into Conversations. Already-synced tickets are skipped on re-run."
+ >
+ <LemonCard hoverEffect={false} className="flex flex-col gap-y-3 max-w-[800px] px-4 py-3">
+ <ZendeskImportForm />
+ </LemonCard>
+ </SceneSection>
+ )
+}
+
+function ZendeskImportForm(): JSX.Element {
+ const {
+ subdomain,
+ emailAddress,
+ apiToken,
+ defaultEmailChannelId,
+ emailConfigs,
+ importJob,
+ importJobLoading,
+ isImportRunning,
+ importProgressLabel,
+ } = useValues(zendeskImportLogic)
+ const { setSubdomain, setEmailAddress, setApiToken, setDefaultEmailChannelId, submitImport } =
+ useActions(zendeskImportLogic)
+ const adminRestrictionReason = useRestrictedArea({
+ scope: RestrictionScope.Organization,
+ minimumAccessLevel: OrganizationMembershipLevel.Admin,
+ })
+
+ const canSubmit = !!subdomain.trim() && !!emailAddress.trim() && !!apiToken.trim()
+
+ return (
+ <div className="flex flex-col gap-y-3">
+ <div className="flex items-center gap-2">
+ <span className="font-medium">Import status</span>
+ {statusTag(importJob?.status)}
+ {importProgressLabel ? <span className="text-xs text-muted-alt">{importProgressLabel}</span> : null}
+ </div>
+
+ {importJob?.status === 'completed' ? (
+ <>
+ <p className="text-xs text-muted-alt m-0">
+ Imported {importJob.imported_tickets.toLocaleString()} tickets (
+ {importJob.skipped_tickets.toLocaleString()} skipped,{' '}
+ {importJob.failed_tickets.toLocaleString()} failed).
+ </p>
+ <p className="text-xs text-muted-alt m-0">
+ If the imported total is lower than the latest ticket number in Zendesk, that is usually
+ expected. Ticket numbers count every ticket ever created, including gaps from deleted tickets.
+ The export API only returns tickets Zendesk still exposes: permanently deleted tickets (after
+ retention), archived tickets, and AI agent tickets may be omitted.
+ </p>
+ </>
+ ) : null}
+
+ {importJob?.status === 'failed' && importJob.latest_error ? (
+ <p className="text-xs text-danger m-0">{importJob.latest_error}</p>
+ ) : null}
+
+ <LemonInput
+ type="text"
+ placeholder="Zendesk subdomain"
+ value={subdomain}
+ onChange={setSubdomain}
+ disabled={isImportRunning}
+ />
+ <LemonInput
+ type="email"
+ placeholder={
+ importJob?.has_credentials
+ ? 'Zendesk agent email (configured — re-enter to start a new import)'
+ : 'Zendesk agent email'
+ }
+ value={emailAddress}
+ onChange={setEmailAddress}
+ disabled={isImportRunning}
+ />
+ <LemonInput
+ type="password"
+ placeholder={
+ importJob?.has_credentials
+ ? 'Zendesk API token (configured — re-enter to start a new import)'
+ : 'Zendesk API token'
+ }
+ value={apiToken}
+ onChange={setApiToken}
+ disabled={isImportRunning}
+ />
+ <LemonField.Pure
+ label="Default inbox"
+ info="Fallback email channel for tickets whose original Zendesk recipient doesn't match one of your configured support addresses (e.g. a *.zendesk.com address, or a non-email ticket). Tickets that do match are assigned to the matching channel regardless of this setting."
+ >
+ <LemonSelect<string | null>
+ value={defaultEmailChannelId}
+ onChange={setDefaultEmailChannelId}
+ disabled={isImportRunning}
+ placeholder="No default (leave unmatched tickets without an inbox)"
+ options={[
+ { label: 'No default', value: null },
+ ...emailConfigs.map((config) => ({ label: config.from_email, value: config.id })),
+ ]}
+ />
+ </LemonField.Pure>
+ <div>
+ <LemonButton
+ type="primary"
+ onClick={submitImport}
+ loading={importJobLoading}
+ disabledReason={
+ adminRestrictionReason ||
+ (isImportRunning ? 'Import already running' : !canSubmit ? 'Fill in all fields' : undefined)
+ }
+ >
+ Start import
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/products/conversations/frontend/scenes/settings/zendeskImportLogic.test.ts b/products/conversations/frontend/scenes/settings/zendeskImportLogic.test.ts
new file mode 100644
index 000000000000..5873118c1ff2
--- /dev/null
+++ b/products/conversations/frontend/scenes/settings/zendeskImportLogic.test.ts
@@ -0,0 +1,98 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { ZendeskImportJobApi } from '../../generated/api.schemas'
+import { zendeskImportLogic, ZendeskImportJobStatus } from './zendeskImportLogic'
+
+function makeJob(status: ZendeskImportJobStatus, overrides: Partial<ZendeskImportJobApi> = {}): ZendeskImportJobApi {
+ return {
+ id: 'job-1',
+ status,
+ subdomain: null,
+ has_credentials: false,
+ total_tickets: 0,
+ processed_tickets: 0,
+ imported_tickets: 0,
+ skipped_tickets: 0,
+ failed_tickets: 0,
+ started_at: null,
+ finished_at: null,
+ latest_error: null,
+ created_at: '2020-01-01T00:00:00Z',
+ updated_at: '2020-01-01T00:00:00Z',
+ ...overrides,
+ }
+}
+
+describe('zendeskImportLogic', () => {
+ let logic: ReturnType<typeof zendeskImportLogic.build>
+
+ beforeEach(async () => {
+ // The afterMount/poll status fetches resolve asynchronously and can land during teardown;
+ // their errors are expected noise, not failures.
+ silenceKeaLoadersErrors()
+ jest.useFakeTimers()
+ useMocks({
+ get: {
+ '/api/projects/:team_id/conversations/zendesk_imports/status/': () => [404, {}],
+ },
+ post: {
+ '/api/projects/:team_id/conversations/zendesk_imports/': () => [201, makeJob('running')],
+ },
+ })
+ initKeaTests()
+ logic = zendeskImportLogic()
+ logic.mount()
+ // Settle the afterMount status fetch (404 → null) so its async resolution can't
+ // leak into teardown and log spurious errors.
+ await expectLogic(logic).toDispatchActions(['loadImportJobSuccess'])
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ jest.clearAllTimers()
+ jest.useRealTimers()
+ resumeKeaLoadersErrors()
+ })
+
+ it.each([
+ ['running', makeJob('running', { processed_tickets: 3, total_tickets: 40 }), true, '3 / 40'],
+ ['pending with no total', makeJob('pending', { processed_tickets: 5 }), true, '5 processed'],
+ ['completed', makeJob('completed'), false, null],
+ ['failed', makeJob('failed'), false, null],
+ ])('exposes progress + running state for %s', async (_label, job, running, label) => {
+ await expectLogic(logic, () => {
+ logic.actions.loadImportJobSuccess(job)
+ }).toMatchValues({
+ isImportRunning: running,
+ importProgressLabel: label,
+ })
+ })
+
+ it('starts polling and clears the token on a successful submit', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.submitImportSuccess(makeJob('running'))
+ })
+ .toDispatchActions(['setApiToken', 'startPolling'])
+ .toMatchValues({ apiToken: '' })
+ })
+
+ it('stops polling once the job reaches a terminal status', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.startPolling()
+ }).toDispatchActions(['startPolling'])
+
+ await expectLogic(logic, () => {
+ logic.actions.loadImportJobSuccess(makeJob('completed'))
+ }).toDispatchActions(['stopPolling'])
+ })
+
+ it('starts polling when a running job is observed and no timer is active', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.loadImportJobSuccess(makeJob('running'))
+ }).toDispatchActions(['startPolling'])
+ })
+})
diff --git a/products/conversations/frontend/scenes/settings/zendeskImportLogic.ts b/products/conversations/frontend/scenes/settings/zendeskImportLogic.ts
new file mode 100644
index 000000000000..577896e055d6
--- /dev/null
+++ b/products/conversations/frontend/scenes/settings/zendeskImportLogic.ts
@@ -0,0 +1,139 @@
+import { actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
+
+import { conversationsZendeskImportsCreate, conversationsZendeskImportsStatusRetrieve } from '../../generated/api'
+import type { ZendeskImportJobApi } from '../../generated/api.schemas'
+import { supportSettingsLogic } from './supportSettingsLogic'
+import type { zendeskImportLogicType } from './zendeskImportLogicType'
+
+export type ZendeskImportJobStatus = ZendeskImportJobApi['status']
+
+const TERMINAL_STATUSES: ZendeskImportJobStatus[] = ['completed', 'failed']
+const POLL_INTERVAL_MS = 3000
+
+export const zendeskImportLogic = kea<zendeskImportLogicType>([
+ path(['products', 'conversations', 'frontend', 'scenes', 'settings', 'zendeskImportLogic']),
+ connect(() => ({
+ values: [supportSettingsLogic, ['emailConfigs']],
+ actions: [supportSettingsLogic, ['loadEmailConfigs']],
+ })),
+ actions({
+ setSubdomain: (subdomain: string) => ({ subdomain }),
+ setEmailAddress: (emailAddress: string) => ({ emailAddress }),
+ setApiToken: (apiToken: string) => ({ apiToken }),
+ setDefaultEmailChannelId: (defaultEmailChannelId: string | null) => ({ defaultEmailChannelId }),
+ submitImport: true,
+ startPolling: true,
+ stopPolling: true,
+ }),
+ reducers({
+ subdomain: ['', { setSubdomain: (_, { subdomain }) => subdomain }],
+ emailAddress: ['', { setEmailAddress: (_, { emailAddress }) => emailAddress }],
+ apiToken: ['', { setApiToken: (_, { apiToken }) => apiToken }],
+ // Fallback email channel for tickets whose Zendesk recipient doesn't match a configured
+ // support address; null = leave those tickets without an email channel.
+ defaultEmailChannelId: [
+ null as string | null,
+ { setDefaultEmailChannelId: (_, { defaultEmailChannelId }) => defaultEmailChannelId },
+ ],
+ }),
+ loaders(({ values }) => ({
+ importJob: [
+ null as ZendeskImportJobApi | null,
+ {
+ loadImportJob: async () => {
+ try {
+ return await conversationsZendeskImportsStatusRetrieve(String(getCurrentTeamId()))
+ } catch (error: any) {
+ if (error?.status === 404) {
+ return null
+ }
+ throw error
+ }
+ },
+ submitImport: async () => {
+ return await conversationsZendeskImportsCreate(String(getCurrentTeamId()), {
+ subdomain: values.subdomain,
+ email_address: values.emailAddress,
+ api_token: values.apiToken,
+ default_email_channel_id: values.defaultEmailChannelId,
+ })
+ },
+ },
+ ],
+ })),
+ selectors({
+ isImportRunning: [
+ // Derive purely from job status — not the shared loaders flag, which is also true during
+ // the initial status GET (and the submit POST). Folding loading in here mislabels the
+ // pre-first-response window on a fresh page as "Import already running". The submit
+ // button uses importJobLoading directly for its loading/disabled state instead.
+ (s) => [s.importJob],
+ (importJob: ZendeskImportJobApi | null): boolean =>
+ importJob?.status === 'running' || importJob?.status === 'pending',
+ ],
+ importProgressLabel: [
+ (s) => [s.importJob],
+ (importJob: ZendeskImportJobApi | null): string | null => {
+ if (!importJob || (importJob.status !== 'running' && importJob.status !== 'pending')) {
+ return null
+ }
+ if (importJob.total_tickets > 0) {
+ return `${importJob.processed_tickets.toLocaleString()} / ${importJob.total_tickets.toLocaleString()}`
+ }
+ return `${importJob.processed_tickets.toLocaleString()} processed`
+ },
+ ],
+ }),
+ listeners(({ actions, values, cache }) => ({
+ submitImportSuccess: () => {
+ lemonToast.success('Zendesk import started')
+ actions.setApiToken('')
+ actions.startPolling()
+ },
+ submitImportFailure: ({ error }) => {
+ // kea-loaders passes error.message (the DRF `detail` string for ApiErrors); it can be ''.
+ lemonToast.error(error || 'Failed to start Zendesk import')
+ },
+ startPolling: () => {
+ actions.stopPolling()
+ actions.loadImportJob()
+ cache.pollTimerId = setInterval(() => {
+ actions.loadImportJob()
+ }, POLL_INTERVAL_MS)
+ },
+ loadImportJobSuccess: ({ importJob }) => {
+ // Prefill only the account-level subdomain so an admin can see which Zendesk account is
+ // configured. The agent email and API token are intentionally never returned (the email
+ // is a personal login — don't disclose the prior operator's identity to other admins), so
+ // both must be re-entered to start a new import. Only fill an empty input to avoid
+ // clobbering what the user is typing when poll refreshes re-fire this.
+ if (importJob?.subdomain && !values.subdomain) {
+ actions.setSubdomain(importJob.subdomain)
+ }
+ if (importJob && TERMINAL_STATUSES.includes(importJob.status)) {
+ actions.stopPolling()
+ } else if (importJob && (importJob.status === 'running' || importJob.status === 'pending')) {
+ if (!cache.pollTimerId) {
+ actions.startPolling()
+ }
+ }
+ },
+ stopPolling: () => {
+ if (cache.pollTimerId) {
+ clearInterval(cache.pollTimerId)
+ cache.pollTimerId = null
+ }
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadImportJob()
+ actions.loadEmailConfigs()
+ }),
+ beforeUnmount(({ actions }) => {
+ actions.stopPolling()
+ }),
+])
diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
index 45286bceaf43..6ed616c2952a 100644
--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx
@@ -320,6 +320,12 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem
</Link>
</div>
)}
+ {ticket?.zendesk_ticket_id && (
+ <div className="flex justify-between items-center">
+ <span className="text-muted-alt">Zendesk ID</span>
+ <LemonTag type="highlight">#{ticket.zendesk_ticket_id}</LemonTag>
+ </div>
+ )}
{ticket?.session_context?.current_url && (
<div className="flex justify-between items-start gap-2">
<span className="text-muted-alt shrink-0">Page URL</span>
diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
index 7e585844e6fb..34b878ec737e 100644
--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts
@@ -392,20 +392,27 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
'Support'
} else if (authorType === 'AI') {
displayName = 'PostHog Assistant'
- } else if (authorType === 'customer') {
- const slackAuthorName = message.item_context?.slack_author_name
- const emailAuthorName = message.item_context?.email_from_name
- if (slackAuthorName) {
- displayName = slackAuthorName
- } else if (emailAuthorName) {
- displayName = emailAuthorName
- } else {
+ } else {
+ // Per-message author identity (e.g. Zendesk import stores each comment's own
+ // author) takes precedence over the ticket-level requester, so a reply from a
+ // second requester or an agent shows the real name instead of the ticket owner.
+ const messageAuthorName =
+ message.item_context?.author_name ||
+ message.item_context?.author_email ||
+ message.item_context?.slack_author_name ||
+ message.item_context?.email_from_name
+ if (messageAuthorName) {
+ displayName = messageAuthorName
+ } else if (authorType === 'customer') {
displayName =
ticket?.person?.properties?.name ||
ticket?.person?.properties?.email ||
ticket?.anonymous_traits?.name ||
ticket?.anonymous_traits?.email ||
'Anonymous user'
+ } else {
+ // Staff message with no resolvable author (e.g. deleted ex-agent).
+ displayName = 'Support'
}
}
@@ -419,6 +426,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([
createdAt: message.created_at,
isPrivate: message.item_context?.is_private || false,
emailDeliveryStatus: message.item_context?.email_delivery_status,
+ fromZendesk: message.item_context?.from_zendesk === true,
}
}),
],
diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.ts
index c9ffc1102049..6a93cad49e0a 100644
--- a/products/conversations/frontend/types.ts
+++ b/products/conversations/frontend/types.ts
@@ -145,6 +145,7 @@ export interface Ticket {
cc_participants?: string[]
github_repo?: string | null
github_issue_number?: number | null
+ zendesk_ticket_id?: number | null
organization_id?: string | null
person?: TicketPerson | null
tags?: string[]
@@ -197,6 +198,9 @@ export interface ChatMessage {
createdAt: string
isPrivate?: boolean
emailDeliveryStatus?: EmailDeliveryStatus
+ /** Imported from an external tool (e.g. Zendesk). Such content is untrusted, so its Markdown
+ * is rendered with external image auto-loading disabled. */
+ fromZendesk?: boolean
}
export const statusOptions: { value: TicketStatus | 'all'; label: string }[] = [
diff --git a/products/conversations/mcp/tools.yaml b/products/conversations/mcp/tools.yaml
index 25dfa9095c03..7a75c297785f 100644
--- a/products/conversations/mcp/tools.yaml
+++ b/products/conversations/mcp/tools.yaml
@@ -158,3 +158,9 @@ tools:
conversations-views-retrieve:
operation: conversations_views_retrieve
enabled: false
+ conversations-zendesk-imports-create:
+ operation: conversations_zendesk_imports_create
+ enabled: false
+ conversations-zendesk-imports-status-retrieve:
+ operation: conversations_zendesk_imports_status_retrieve
+ enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ebe40c7c7e77..d1ca9f65f1f5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -35490,6 +35490,8 @@ export namespace Schemas {
readonly github_repo: string | null;
/** @nullable */
readonly github_issue_number: number | null;
+ /** @nullable */
+ readonly zendesk_ticket_id: number | null;
/**
* Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.
* @nullable
@@ -42912,6 +42914,8 @@ export namespace Schemas {
readonly github_repo?: string | null;
/** @nullable */
readonly github_issue_number?: number | null;
+ /** @nullable */
+ readonly zendesk_ticket_id?: number | null;
/**
* Customer's PostHog organization group key, resolved at ticket creation. Null when unknown.
* @nullable
@@ -55249,6 +55253,95 @@ export namespace Schemas {
spec: WriteTypedBundleRequestSpec;
}
+ export interface ZendeskImportError {
+ /** Human-readable error message. */
+ detail: string;
+ }
+
+ /**
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed
+ */
+ export type ZendeskImportJobStatusEnum = typeof ZendeskImportJobStatusEnum[keyof typeof ZendeskImportJobStatusEnum];
+
+
+ export const ZendeskImportJobStatusEnum = {
+ Pending: 'pending',
+ Running: 'running',
+ Completed: 'completed',
+ Failed: 'failed',
+ } as const;
+
+ export interface ZendeskImportJob {
+ /** Unique identifier for the import job. */
+ readonly id: string;
+ /** Current job state: pending, running, completed, or failed.
+ *
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `completed` - Completed
+ * * `failed` - Failed */
+ readonly status: ZendeskImportJobStatusEnum;
+ /**
+ * Zendesk subdomain used for this import job.
+ * @nullable
+ */
+ readonly subdomain: string | null;
+ /** Whether stored Zendesk credentials exist for this job (the token/email are never returned). */
+ readonly has_credentials: boolean;
+ /** Total number of tickets discovered for import. */
+ readonly total_tickets: number;
+ /** Number of tickets processed so far. */
+ readonly processed_tickets: number;
+ /** Number of tickets successfully imported. */
+ readonly imported_tickets: number;
+ /** Number of tickets skipped because they were already imported. */
+ readonly skipped_tickets: number;
+ /** Number of tickets that failed to import. */
+ readonly failed_tickets: number;
+ /**
+ * When the import started running.
+ * @nullable
+ */
+ readonly started_at: string | null;
+ /**
+ * When the import reached a terminal state.
+ * @nullable
+ */
+ readonly finished_at: string | null;
+ /**
+ * Generic, user-safe error message when the job failed.
+ * @nullable
+ */
+ readonly latest_error: string | null;
+ /** When the import job was created. */
+ readonly created_at: string;
+ /** When the import job was last updated. */
+ readonly updated_at: string;
+ }
+
+ export interface ZendeskImportStart {
+ /**
+ * Zendesk subdomain (e.g. 'acme' from acme.zendesk.com).
+ * @maxLength 255
+ */
+ subdomain: string;
+ /** Zendesk agent email tied to the API token. */
+ email_address: string;
+ /**
+ * Zendesk API token with ticket read access.
+ * @maxLength 500
+ */
+ api_token: string;
+ /**
+ * Optional fallback email channel for tickets whose original Zendesk recipient doesn't match a configured support address (or isn't an email). Omit or null to leave those tickets without an email channel.
+ * @nullable
+ */
+ default_email_channel_id?: string | null;
+ }
+
export interface _CompareFilter {
/** When true, also fetch results for a comparison window and return them under `compare`. */
compare?: boolean;
diff --git a/tach.toml b/tach.toml
index 026602b4b5c7..5934472bad17 100644
--- a/tach.toml
+++ b/tach.toml
@@ -205,7 +205,7 @@ layer = "modules"
path = "products.conversations"
depends_on = [
"ee",
- "posthog", "products.tasks", "products.business_knowledge",
+ "posthog", "products.tasks", "products.business_knowledge", "products.warehouse_sources",
]
layer = "modules"
@@ -337,7 +337,6 @@ depends_on = [
"products.ai_observability",
"products.analytics_platform",
"products.data_tools",
- "products.data_warehouse",
"products.event_definitions",
"products.feature_flags",
"products.notifications",
@@ -517,7 +516,6 @@ depends_on = [
"products.actions",
"products.alerts",
"products.dashboards",
- "products.data_warehouse",
"products.event_definitions",
"products.annotations",
"products.warehouse_sources",
@@ -571,8 +569,7 @@ layer = "modules"
path = "products.revenue_analytics"
depends_on = [
"ee",
- "posthog",
- "products.data_warehouse", "products.warehouse_sources", "products.data_modeling", "products.data_tools",
+ "posthog", "products.warehouse_sources", "products.data_modeling", "products.data_tools",
]
layer = "modules"
@@ -641,7 +638,6 @@ path = "products.customer_analytics"
depends_on = [
"ee",
"posthog",
- "products.data_warehouse",
"products.notebooks",
"products.notifications",
"products.product_analytics",
@@ -657,8 +653,7 @@ depends_on = [
"posthog",
"products.access_control",
"products.actions",
- "products.analytics_platform",
- "products.data_warehouse", "products.warehouse_sources",
+ "products.analytics_platform", "products.warehouse_sources",
]
layer = "modules"