: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): match previous tickets by email too (#73119)
Eleftheria Trivyzaki2d26ddc21381
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 448df28bef70..8c030ce05167 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -7057,6 +7057,7 @@ const api = {assignee?: stringtags?: stringdistinct_ids?: string+ emails?: stringsearch?: stringdate_from?: stringdate_to?: stringdiff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex a55de0b4fe1b..0dea1b06c3ee 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -1626,6 +1626,52 @@ class TestTicketEmailFallbackPersonLookup(ClickhouseTestMixin, APIBaseTest):assert index_info is not None, f"Expected skip index {index_name} to be used:\n{subquery}"[email protected](transaction, "on_commit", side_effect=immediate_on_commit)+class TestTicketEmailFilter(APIBaseTest):+ """Tests the `emails` query param used by the previous-tickets panel to match related tickets."""++ def _create_ticket(self, distinct_id, email_from=None):+ return Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.EMAIL,+ distinct_id=distinct_id,+ email_from=email_from,+ status=Status.NEW,+ )++ def _numbers(self, response):+ return {r["ticket_number"] for r in response.json()["results"]}++ def test_filter_by_email_matches_email_from_case_insensitively(self, mock_on_commit):+ match = self._create_ticket(distinct_id="did-1", email_from="[email protected]")+ self._create_ticket(distinct_id="did-2", email_from="[email protected]")++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/[email protected]")++ assert response.status_code == status.HTTP_200_OK+ assert self._numbers(response) == {match.ticket_number}++ def test_filter_by_distinct_ids_or_emails_returns_union(self, mock_on_commit):+ by_did = self._create_ticket(distinct_id="did-1", email_from="[email protected]")+ by_email = self._create_ticket(distinct_id="did-2", email_from="[email protected]")+ self._create_ticket(distinct_id="did-3", email_from="[email protected]")++ response = self.client.get(+ f"/api/projects/{self.team.id}/conversations/tickets/?distinct_ids=did-1&[email protected]"+ )++ assert response.status_code == status.HTTP_200_OK+ assert self._numbers(response) == {by_did.ticket_number, by_email.ticket_number}++ def test_filter_by_email_no_match_returns_empty(self, mock_on_commit):+ self._create_ticket(distinct_id="did-1", email_from="[email protected]")++ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/[email protected]")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["count"] == 0++@patch.object(transaction, "on_commit", side_effect=immediate_on_commit)class TestComposeTicketAPI(APIBaseTest):def setUp(self):diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex c7faea5c03e8..47c9ab026c67 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -440,11 +440,29 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modif parsed:queryset = queryset.filter(updated_at__lte=parsed)+ # Related-ticket matching: a ticket belongs to the same customer if it shares one of the+ # person's merged distinct_ids OR the same email address. Email widens the match to tickets+ # whose distinct_id was never merged into the person (a separate anonymous session, or an+ # email-only ticket). The two params OR together when both are supplied.+ match_q = Q()+distinct_ids_param = self.request.query_params.get("distinct_ids")if distinct_ids_param:ids = [id.strip() for id in distinct_ids_param.split(",") if id.strip()][:100]if ids:- queryset = queryset.filter(distinct_id__in=ids)+ match_q |= Q(distinct_id__in=ids)++ emails_param = self.request.query_params.get("emails")+ if emails_param:+ emails = [e.strip() for e in emails_param.split(",") if e.strip()][:100]+ email_q = Q()+ for email in emails:+ email_q |= Q(email_from__iexact=email)+ if email_q:+ match_q |= email_q++ if match_q:+ queryset = queryset.filter(match_q)search = self.request.query_params.get("search")if search and len(search) <= 200:@@ -714,6 +732,16 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modlocation=OpenApiParameter.QUERY,description="Comma-separated list of person `distinct_id`s to filter by (max 100).",),+ OpenApiParameter(+ "emails",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ description=(+ "Comma-separated list of email addresses to filter by, matched case-insensitively "+ "against `email_from` (max 100). When combined with `distinct_ids`, tickets matching "+ "either the distinct_ids or the emails are returned (OR)."+ ),+ ),OpenApiParameter("search",OpenApiTypes.STR,diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex 15f5d9c93aa2..8ee101992670 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -1216,6 +1216,10 @@ export type ConversationsTicketsListParams = {* Comma-separated list of person `distinct_id`s to filter by (max 100).*/distinct_ids?: string+ /**+ * Comma-separated list of email addresses to filter by, matched case-insensitively against `email_from` (max 100). When combined with `distinct_ids`, tickets matching either the distinct_ids or the emails are returned (OR).+ */+ emails?: string/*** Number of results to return per page.*/diff --git a/products/conversations/frontend/scenes/ticket/PreviousTicketsPanel.tsx b/products/conversations/frontend/scenes/ticket/PreviousTicketsPanel.tsxindex a449a1e9e655..79fb0dcb07d8 100644--- a/products/conversations/frontend/scenes/ticket/PreviousTicketsPanel.tsx+++ b/products/conversations/frontend/scenes/ticket/PreviousTicketsPanel.tsx@@ -1,4 +1,5 @@-import { LemonCollapse, LemonTag, Link } from '@posthog/lemon-ui'+import { IconWarning } from '@posthog/icons'+import { LemonCollapse, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { stripMarkdown } from 'lib/utils/markdown'@@ -9,11 +10,15 @@ import { Ticket } from '../../types'interface PreviousTicketsPanelProps {previousTickets: Ticket[]previousTicketsLoading?: boolean+ // Merged distinct_ids of the current ticket's person. Tickets whose distinct_id+ // is not in this set were matched by email alone, so they may be a different person.+ personDistinctIds?: string[]}export function PreviousTicketsPanel({previousTickets,previousTicketsLoading,+ personDistinctIds,}: PreviousTicketsPanelProps): JSX.Element {return (<LemonCollapse@@ -37,38 +42,54 @@ export function PreviousTicketsPanel({<div className="text-muted-alt text-xs">No previous tickets found</div>) : (<div className="space-y-2 max-h-96 overflow-auto">- {previousTickets.map((ticket) => (- <Link- key={ticket.id}- to={urls.supportTicketDetail(ticket.ticket_number)}- className="block p-2 mb-2 rounded border border-primary hover:bg-accent-3000 transition-colors hover:border-secondary"- >- <div className="flex items-center justify-between mb-1">- <span className="font-mono text-xs text-muted-alt">- #{ticket.ticket_number}- </span>- <LemonTag- type={- ticket.status === 'resolved'- ? 'success'- : ticket.status === 'new'- ? 'primary'- : 'default'- }- >- {ticket.status === 'on_hold' ? 'On hold' : ticket.status}- </LemonTag>- </div>- {ticket.last_message_text && (- <div className="text-xs text-muted truncate mb-1">- {stripMarkdown(ticket.last_message_text)}+ {previousTickets.map((ticket) => {+ const matchedByEmailOnly =+ !!ticket.distinct_id &&+ !!personDistinctIds?.length &&+ !personDistinctIds.includes(ticket.distinct_id)+ return (+ <Link+ key={ticket.id}+ to={urls.supportTicketDetail(ticket.ticket_number)}+ className="block p-2 mb-2 rounded border border-primary hover:bg-accent-3000 transition-colors hover:border-secondary"+ >+ <div className="flex items-center justify-between mb-1">+ <div className="flex items-center gap-1">+ <span className="font-mono text-xs text-muted-alt">+ #{ticket.ticket_number}+ </span>+ {matchedByEmailOnly && (+ <Tooltip title="Matched by email address, so this may not be the same person profile.">+ <LemonTag type="warning" size="small" className="gap-1">+ <IconWarning />+ Email match+ </LemonTag>+ </Tooltip>+ )}+ </div>+ <LemonTag+ type={+ ticket.status === 'resolved'+ ? 'success'+ : ticket.status === 'new'+ ? 'primary'+ : 'default'+ }+ >+ {ticket.status === 'on_hold' ? 'On hold' : ticket.status}+ </LemonTag></div>- )}- <div className="text-xs text-muted-alt">- Created <TZLabel time={ticket.created_at} />- </div>- </Link>- ))}+ {ticket.last_message_text && (+ <div className="text-xs text-muted truncate mb-1">+ {stripMarkdown(ticket.last_message_text)}+ </div>+ )}+ <div className="text-xs text-muted-alt">+ Created <TZLabel time={ticket.created_at} />+ </div>+ </Link>+ )+ })}</div>)}</div>diff --git a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsxindex 5c991f8d28fa..062667b1a85d 100644--- a/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx+++ b/products/conversations/frontend/scenes/ticket/SupportTicketScene.tsx@@ -512,6 +512,7 @@ export function SupportTicketScene({ ticketId }: { ticketId: string }): JSX.Elem<PreviousTicketsPanelpreviousTickets={previousTickets}previousTicketsLoading={previousTicketsLoading}+ personDistinctIds={person?.distinct_ids}/></>)}diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.tsindex bf6548a62dbc..eac0dfbee45b 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.test.ts@@ -375,3 +375,52 @@ describe('supportTicketSceneLogic sendMessage with statusAfterSend', () => {expect(logic.values.ticketUpdating).toBe(false)})})++describe('supportTicketSceneLogic loadPreviousTickets email gating', () => {+ let logic: ReturnType<typeof supportTicketSceneLogic.build>++ const personsListMock = api.persons.list as jest.Mock+ const ticketsListMock = api.conversationsTickets.list as jest.Mock+ const ticketGetMock = api.conversationsTickets.get as jest.Mock++ beforeEach(() => {+ initKeaTests()+ // Person carries a customer-controlled properties.email distinct from the ticket's email_from,+ // so the assertions prove the match uses email_from (when verified) and never properties.email.+ personsListMock.mockReset().mockResolvedValue({+ results: [{ id: 'p1', distinct_ids: ['user-1'], properties: { email: '[email protected]' } }],+ })+ ticketsListMock.mockReset().mockResolvedValue({ results: [] })+ ticketGetMock.mockReset()+ })++ // email_from is attacker-spoofable unless the ticket's identity is positively attested, and+ // person.properties.email is customer-controlled analytics with no trusted mapping. Only a+ // verified ticket may widen the match by email — otherwise a spoofed sender pulls another+ // customer's ticket history into their own view.+ test.each<[string, boolean | null, Record<string, string>]>([+ [+ 'verified email ticket matches by email_from',+ true,+ { distinct_ids: 'user-1', emails: '[email protected]' },+ ],+ ['unverified ticket omits emails', false, { distinct_ids: 'user-1' }],+ ['unknown identity omits emails', null, { distinct_ids: 'user-1' }],+ ])('%s', async (_name, identity_verified, expectedParams) => {+ ticketGetMock.mockResolvedValue({+ ...makeTicket(),+ distinct_id: 'user-1',+ channel_source: 'email',+ email_from: '[email protected]',+ identity_verified,+ })++ logic = supportTicketSceneLogic({ id: 42 })++ await expectLogic(logic, () => {+ logic.mount()+ }).toDispatchActions(['loadPreviousTicketsSuccess'])++ expect(ticketsListMock).toHaveBeenLastCalledWith(expectedParams)+ })+})diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 4bb0c22b53ac..c53e222573e9 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -536,9 +536,20 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([return []}+ // Widen the match to email only when the current ticket's identity was positively+ // attested (e.g. SPF-authenticated email). email_from is attacker-controllable on+ // unverified tickets, and person.properties.email is customer-controlled analytics+ // data with no trusted mapping — trusting either would let a spoofed sender pull a+ // real customer's ticket history into their own ticket view.+ const emails = new Set<string>()+ if (values.ticket?.identity_verified === true && values.ticket.email_from) {+ emails.add(values.ticket.email_from)+ }+try {const response = await api.conversationsTickets.list({distinct_ids: person.distinct_ids.join(','),+ ...(emails.size > 0 ? { emails: Array.from(emails).join(',') } : {}),})const allTickets = response.results || []diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f29ced522399..f35ebf631282 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -72731,6 +72731,10 @@ export namespace Schemas {* Comma-separated list of person `distinct_id`s to filter by (max 100).*/distinct_ids?: string;+ /**+ * Comma-separated list of email addresses to filter by, matched case-insensitively against `email_from` (max 100). When combined with `distinct_ids`, tickets matching either the distinct_ids or the emails are returned (OR).+ */+ emails?: string;/*** Number of results to return per page.*/diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex 3f852b9531ac..072e6cf9cf49 100644--- a/services/mcp/src/generated/conversations/api.ts+++ b/services/mcp/src/generated/conversations/api.ts@@ -57,6 +57,12 @@ export const ConversationsTicketsListQueryParams = /* @__PURE__ */ zod.object({.string().optional().describe('Comma-separated list of person `distinct_id`s to filter by (max 100).'),+ emails: zod+ .string()+ .optional()+ .describe(+ 'Comma-separated list of email addresses to filter by, matched case-insensitively against `email_from` (max 100). When combined with `distinct_ids`, tickets matching either the distinct_ids or the emails are returned (OR).'+ ),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),order_by: zoddiff --git a/services/mcp/src/tools/generated/conversations.ts b/services/mcp/src/tools/generated/conversations.tsindex 66945a46b415..08c797b59830 100644--- a/services/mcp/src/tools/generated/conversations.ts+++ b/services/mcp/src/tools/generated/conversations.ts@@ -36,6 +36,7 @@ const conversationsTicketsList = (): ToolBase<date_from: params.date_from,date_to: params.date_to,distinct_ids: params.distinct_ids,+ emails: params.emails,limit: params.limit,offset: params.offset,order_by: params.order_by,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.jsonindex d715885474a2..17fba8781570 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/conversations-tickets-list.json@@ -36,6 +36,10 @@"description": "Comma-separated list of person `distinct_id`s to filter by (max 100).","type": "string"},+ "emails": {+ "description": "Comma-separated list of email addresses to filter by, matched case-insensitively against `email_from` (max 100). When combined with `distinct_ids`, tickets matching either the distinct_ids or the emails are returned (OR).",+ "type": "string"+ },"limit": {"description": "Number of results to return per page.","type": "number"