:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): backfill default email channel on zendesk re-import (#69701)
Abigailee3aa74d0195
diff --git a/products/conversations/backend/temporal/zendesk_import/activities.py b/products/conversations/backend/temporal/zendesk_import/activities.pyindex 56748b44504e..270aaff91cd5 100644--- a/products/conversations/backend/temporal/zendesk_import/activities.py+++ b/products/conversations/backend/temporal/zendesk_import/activities.py@@ -202,6 +202,16 @@ def _import_ticket_batch_sync(input: ImportBatchInput) -> ImportBatchOutput:credentials = _credentials_from_job(job)client = ZendeskImportClient(credentials)+ # 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)+existing_ids = set(Ticket.objects.filter(team_id=input.team_id).filter(zendesk_ticket_id__in=input.ticket_ids)@@ -209,6 +219,21 @@ def _import_ticket_batch_sync(input: ImportBatchInput) -> ImportBatchOutput:)to_import = [tid for tid in input.ticket_ids if tid not in existing_ids]skipped = len(input.ticket_ids) - len(to_import)++ # Re-import backfill: tickets a previous run imported without an email channel (no default+ # was provided at the time) adopt this run's default. Tickets that already resolved a+ # channel — their own recipient match or an earlier default — keep it. QuerySet.update()+ # bypasses the signal receivers (see the Phase 3 comment below) and doesn't bump the+ # historical updated_at.+ if existing_ids and default_email_channel is not None and not input.dry_run:+ backfilled = Ticket.objects.filter(+ team_id=input.team_id,+ zendesk_ticket_id__in=existing_ids,+ email_config__isnull=True,+ ).update(email_config=default_email_channel)+ if backfilled:+ logger.info("zendesk_import_backfilled_email_channel", team_id=team.id, backfilled=backfilled)+if not to_import:return ImportBatchOutput(imported=0, skipped=skipped, failed=0)@@ -223,16 +248,6 @@ def _import_ticket_batch_sync(input: ImportBatchInput) -> ImportBatchOutput:imported = 0failed = 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()diff --git a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.pyindex 6e61bb28ff72..438a914bb7c7 100644--- a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py+++ b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py@@ -97,6 +97,7 @@ class TestZendeskImportBatchActivity(BaseTest):download_raises: bool = False,save_return: str | None = "https://media.posthog.test/file",default_email_channel_id: str | None = None,+ dry_run: bool = False,) -> tuple[Any, MagicMock]:client = MagicMock()client.fetch_tickets.return_value = tickets@@ -117,6 +118,7 @@ class TestZendeskImportBatchActivity(BaseTest):team_id=self.team.id,ticket_ids=ticket_ids,default_email_channel_id=default_email_channel_id,+ dry_run=dry_run,))return result, client@@ -263,6 +265,74 @@ class TestZendeskImportBatchActivity(BaseTest):expected_id = {"matched": matched.id, "default": default.id, None: None}[expected]self.assertEqual(ticket.email_config_id, expected_id)+ @parameterized.expand(+ [+ # null channel (first import ran without a default) → adopt this run's default.+ ("null_channel_adopts_default", False, True, False, "default"),+ # a channel resolved by an earlier run must never be overwritten by a new default.+ ("existing_channel_kept", True, True, False, "existing"),+ # no default on this run either → stays null.+ ("no_default_stays_null", False, False, False, None),+ # dry run must not mutate previously imported tickets.+ ("dry_run_does_not_backfill", False, True, True, None),+ ]+ )+ def test_reimport_backfills_default_email_channel(+ self, _name: str, has_channel: bool, use_default: bool, dry_run: bool, expected: str | None+ ) -> None:+ existing_channel = self._make_channel("[email protected]", "tok-original")+ default = self._make_channel("[email protected]", "tok-default")+ ticket = Ticket.objects.create(+ team=self.team,+ ticket_number=1,+ widget_session_id="existing",+ distinct_id="d",+ zendesk_ticket_id=301,+ email_config=existing_channel if has_channel else None,+ )++ result, client = self._run_batch(+ [301],+ tickets=[],+ users={},+ comments_by_ticket={},+ default_email_channel_id=str(default.id) if use_default else None,+ dry_run=dry_run,+ )++ # The ticket is still skipped (never re-imported) and never re-fetched from Zendesk.+ self.assertEqual((result.imported, result.skipped, result.failed), (0, 1, 0))+ client.fetch_tickets.assert_not_called()+ ticket.refresh_from_db()+ expected_id = {"default": default.id, "existing": existing_channel.id, None: None}[expected]+ self.assertEqual(ticket.email_config_id, expected_id)++ def test_reimport_backfills_existing_and_imports_new_in_same_batch(self) -> None:+ # Guards the channel resolution feeding both paths: the previously imported null-channel+ # ticket is backfilled while the new ticket in the same batch imports with the default.+ default = self._make_channel("[email protected]", "tok-default")+ existing = Ticket.objects.create(+ team=self.team,+ ticket_number=1,+ widget_session_id="existing",+ distinct_id="d",+ zendesk_ticket_id=401,+ )++ result, _ = self._run_batch(+ [401, 402],+ tickets=[_zd_ticket(402, 10)],+ users={10: _zd_user(10, "[email protected]")},+ comments_by_ticket={402: []},+ default_email_channel_id=str(default.id),+ )++ self.assertEqual((result.imported, result.skipped, result.failed), (1, 1, 0))+ existing.refresh_from_db()+ self.assertEqual(existing.email_config_id, default.id)+ new_ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=402)+ self.assertEqual(new_ticket.email_config_id, default.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.