: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): filter tickets by tags with AND and NOT (#62469)
Christiaan Hendriksenb8e8e802e2c3
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex f6647b3754f8..d78653760a28 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -1,3 +1,4 @@+import jsonfrom datetime import timedeltafrom posthog.test.base import (@@ -23,7 +24,7 @@ from posthog.schema import HogQLQueryModifiers, MaterializationModefrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query-from posthog.models import ActivityLog, Comment, Organization, User+from posthog.models import ActivityLog, Comment, Organization, Tag, Userfrom posthog.models.person import Personfrom posthog.personhog_client.test_helpers import PersonhogTestMixin@@ -58,6 +59,50 @@ class TestTicketAPI(APIBaseTest):self.assertEqual(response.json()["count"], 1)self.assertEqual(response.json()["results"][0]["id"], str(self.ticket.id))+ def _ticket_with_tags(self, *tag_names):+ ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source=Channel.WIDGET,+ widget_session_id="-".join(tag_names) or "untagged",+ distinct_id="user-123",+ status=Status.NEW,+ )+ for name in tag_names:+ tag, _ = Tag.objects.get_or_create(name=name, team_id=self.team.id)+ ticket.tagged_items.create(tag=tag)+ return ticket++ def _list_ids(self, **params):+ response = self.client.get(f"/api/projects/{self.team.id}/conversations/tickets/", data=params)+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ return {r["id"] for r in response.json()["results"]}++ @parameterized.expand(+ [+ ("tags_matches_any", {"tags": '["alpha", "beta"]'}, {"alpha_beta", "alpha", "beta_gamma"}),+ ("tags_all_matches_every", {"tags_all": '["alpha", "beta"]'}, {"alpha_beta"}),+ ("tags_exclude_drops_tagged", {"tags_exclude": '["gamma"]'}, {"alpha_beta", "alpha"}),+ (+ "tags_all_composes_with_tags_exclude",+ {"tags_all": '["alpha"]', "tags_exclude": '["beta"]'},+ {"alpha"},+ ),+ ("malformed_json_ignored", {"tags_all": "not-json"}, {"alpha_beta", "alpha", "beta_gamma"}),+ ("oversized_list_capped_not_500", {"tags_all": json.dumps([f"t{i}" for i in range(200)])}, set()),+ ]+ )+ def test_filter_tags(self, mock_on_commit, _name, params, expected_keys):+ # Expectations are fixture keys rather than ids (tickets don't exist at decorator+ # time); the response is projected onto the fixture, which also keeps the untagged+ # setUp ticket out of the comparison.+ fixture = {+ "alpha_beta": self._ticket_with_tags("alpha", "beta"),+ "alpha": self._ticket_with_tags("alpha"),+ "beta_gamma": self._ticket_with_tags("beta", "gamma"),+ }+ ids = self._list_ids(**params)+ self.assertEqual({key for key, ticket in fixture.items() if str(ticket.id) in ids}, expected_keys)+def test_list_tickets_only_returns_team_tickets(self, mock_on_commit):other_ticket = Ticket.objects.create_with_number(team=self.team,diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex e014d69593e9..96680be9bb66 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -146,6 +146,9 @@ class TicketPagination(pagination.LimitOffsetPagination):max_limit = 1000+MAX_TAG_FILTER_VALUES = 50++class TicketPersonSerializer(serializers.Serializer):"""Minimal person serializer for embedding in ticket responses."""@@ -372,7 +375,28 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Modtry:tags_list = json.loads(tags_param)if isinstance(tags_list, list) and tags_list:- queryset = queryset.filter(tagged_items__tag__name__in=tags_list).distinct()+ queryset = queryset.filter(tagged_items__tag__name__in=tags_list[:MAX_TAG_FILTER_VALUES]).distinct()+ except json.JSONDecodeError:+ pass++ tags_all_param = self.request.query_params.get("tags_all")+ if tags_all_param:+ try:+ tags_all_list = json.loads(tags_all_param)+ if isinstance(tags_all_list, list) and tags_all_list:+ # One filter per tag (not __in) so this is AND: the ticket must carry every tag.+ for tag_name in tags_all_list[:MAX_TAG_FILTER_VALUES]:+ queryset = queryset.filter(tagged_items__tag__name=tag_name)+ queryset = queryset.distinct()+ except json.JSONDecodeError:+ pass++ tags_exclude_param = self.request.query_params.get("tags_exclude")+ if tags_exclude_param:+ try:+ tags_exclude_list = json.loads(tags_exclude_param)+ if isinstance(tags_exclude_list, list) and tags_exclude_list:+ queryset = queryset.exclude(tagged_items__tag__name__in=tags_exclude_list[:MAX_TAG_FILTER_VALUES])except json.JSONDecodeError:pass@@ -553,7 +577,19 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod"tags",OpenApiTypes.STR,location=OpenApiParameter.QUERY,- description='JSON-encoded array of tag names to filter by, e.g. `["billing","urgent"]`.',+ description='JSON-encoded array of tag names; returns tickets with ANY of them (OR), e.g. `["billing","urgent"]`.',+ ),+ OpenApiParameter(+ "tags_all",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ description='JSON-encoded array of tag names; returns tickets that have ALL of them (AND), e.g. `["billing","urgent"]`.',+ ),+ OpenApiParameter(+ "tags_exclude",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ description='JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `["escalated"]`.',),OpenApiParameter("order_by",diff --git a/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx b/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsxindex 04a6a3425b5d..bc7a6058a5da 100644--- a/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx+++ b/products/conversations/frontend/components/SavedViews/SavedViewsModal.tsx@@ -25,7 +25,13 @@ function FiltersSummary({ filters }: { filters: TicketViewFilters }): JSX.Elemenlines.push({ label: 'SLA', value: filters.sla })}if (filters.tags?.length) {- lines.push({ label: 'Tags', value: filters.tags.join(', ') })+ lines.push({+ label: filters.tagsMatch === 'all' ? 'Tags (all)' : 'Tags (any)',+ value: filters.tags.join(', '),+ })+ }+ if (filters.tagsExclude?.length) {+ lines.push({ label: 'Exclude tags', value: filters.tagsExclude.join(', ') })}if (filters.assignee && filters.assignee !== 'all') {const val =diff --git a/products/conversations/frontend/generated/api.schemas.ts b/products/conversations/frontend/generated/api.schemas.tsindex b7a739b918a7..cd2da6867c08 100644--- a/products/conversations/frontend/generated/api.schemas.ts+++ b/products/conversations/frontend/generated/api.schemas.ts@@ -734,9 +734,17 @@ export type ConversationsTicketsListParams = {*/status?: string/**- * JSON-encoded array of tag names to filter by, e.g. `["billing","urgent"]`.+ * JSON-encoded array of tag names; returns tickets with ANY of them (OR), e.g. `["billing","urgent"]`.*/tags?: string+ /**+ * JSON-encoded array of tag names; returns tickets that have ALL of them (AND), e.g. `["billing","urgent"]`.+ */+ tags_all?: string+ /**+ * JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `["escalated"]`.+ */+ tags_exclude?: string}export type ConversationsTicketsListChannelDetail =diff --git a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsxindex 2198e05a7cc7..4b559c4e92f8 100644--- a/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx+++ b/products/conversations/frontend/scenes/tickets/SupportTicketsScene.tsx@@ -11,6 +11,7 @@ import {LemonDropdown,LemonInput,LemonInputSelect,+ LemonSegmentedButton,LemonSelect,LemonTable,LemonTableColumns,@@ -50,6 +51,7 @@ import {type Ticket,type TicketSlaState,type TicketStatus,+ type TicketTagsMatch,channelOptions,priorityMultiselectOptions,slaOptions,@@ -367,6 +369,8 @@ export function SupportTicketsTableFilters(): JSX.Element {slaFilter,assigneeFilter,tagsFilter,+ tagsMatch,+ tagsExcludeFilter,dateFrom,dateTo,ticketsLoading,@@ -379,10 +383,13 @@ export function SupportTicketsTableFilters(): JSX.Element {setSlaFilter,setAssigneeFilter,setTagsFilter,+ setTagsMatch,+ setTagsExcludeFilter,setDateRange,loadTickets,} = useActions(logic)const { tags: tagsAvailable } = useValues(tagsModel)+ const tagOptions = tagsAvailable?.map((t: string) => ({ key: t, label: t })) || []return (<div className="flex flex-wrap gap-3 items-center justify-between">@@ -523,33 +530,68 @@ export function SupportTicketsTableFilters(): JSX.Element {<LemonDropdowncloseOnClickInside={false}overlay={- <div className="p-2 min-w-64">- <LemonInputSelect- mode="multiple"- allowCustomValues- value={tagsFilter}- options={tagsAvailable?.map((t: string) => ({ key: t, label: t })) || []}- onChange={setTagsFilter}- placeholder="Select or type tags..."- data-attr="tags-filter-input"- />+ <div className="p-2 min-w-64 flex flex-col gap-2">+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between gap-2">+ <span className="text-muted text-xs">Include tags</span>+ <LemonSegmentedButton+ size="small"+ value={tagsMatch}+ onChange={(value) => setTagsMatch(value as TicketTagsMatch)}+ options={[+ { value: 'any', label: 'Match any' },+ { value: 'all', label: 'Match all' },+ ]}+ />+ </div>+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={tagsFilter}+ options={tagOptions}+ onChange={setTagsFilter}+ placeholder="Select or type tags..."+ data-attr="tags-filter-input"+ />+ </div>+ <div className="flex flex-col gap-1">+ <span className="text-muted text-xs">Exclude tags</span>+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={tagsExcludeFilter}+ options={tagOptions}+ onChange={setTagsExcludeFilter}+ placeholder="Exclude tags..."+ data-attr="tags-exclude-filter-input"+ />+ </div></div>}><LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>- {tagsFilter.length === 0+ {tagsFilter.length === 0 && tagsExcludeFilter.length === 0? 'All tags'- : tagsFilter.length === 1- ? tagsFilter[0]- : `${tagsFilter.length} tags`}+ : [+ tagsFilter.length > 0 &&+ (tagsFilter.length === 1+ ? tagsFilter[0]+ : `${tagsMatch === 'all' ? 'all' : 'any'} of ${tagsFilter.length} tags`),+ tagsExcludeFilter.length > 0 && `excl. ${tagsExcludeFilter.length}`,+ ]+ .filter(Boolean)+ .join(', ')}</LemonButton></LemonDropdown>- {tagsFilter.length > 0 && (+ {(tagsFilter.length > 0 || tagsExcludeFilter.length > 0) && (<LemonButtontype="secondary"size="small"icon={<IconX />}- onClick={() => setTagsFilter([])}+ onClick={() => {+ setTagsFilter([])+ setTagsExcludeFilter([])+ }}tooltip="Clear tag filter"/>)}diff --git a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.tsindex 842b53d6bae5..32e9145d16fb 100644--- a/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts+++ b/products/conversations/frontend/scenes/tickets/supportTicketsSceneLogic.ts@@ -15,6 +15,7 @@ import type {TicketPriority,TicketSlaState,TicketStatus,+ TicketTagsMatch,TicketViewFilters,} from '../../types'import type { supportTicketsSceneLogicType } from './supportTicketsSceneLogicType'@@ -37,6 +38,8 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([setPriorityFilter: (priorities: TicketPriority[]) => ({ priorities }),setAssigneeFilter: (assignee: AssigneeFilterValue) => ({ assignee }),setTagsFilter: (tags: string[]) => ({ tags }),+ setTagsMatch: (match: TicketTagsMatch) => ({ match }),+ setTagsExcludeFilter: (tags: string[]) => ({ tags }),setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setSorting: (sorting: Sorting | null) => ({ sorting }),setSearchQuery: (query: string) => ({ query }),@@ -126,6 +129,22 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([applyViewFilters: (state, { filters }) => filters.tags ?? state,},],+ tagsMatch: [+ 'any' as TicketTagsMatch,+ { persist: true },+ {+ setTagsMatch: (_, { match }) => match,+ applyViewFilters: (state, { filters }) => filters.tagsMatch ?? state,+ },+ ],+ tagsExcludeFilter: [+ [] as string[],+ { persist: true },+ {+ setTagsExcludeFilter: (_, { tags }) => tags,+ applyViewFilters: (state, { filters }) => filters.tagsExclude ?? state,+ },+ ],searchQuery: ['' as string,{@@ -204,6 +223,8 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([s.slaFilter,s.assigneeFilter,s.tagsFilter,+ s.tagsMatch,+ s.tagsExcludeFilter,s.dateFrom,s.dateTo,s.sorting,@@ -216,6 +237,8 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([sla: TicketSlaState | 'all',assignee: AssigneeFilterValue,tags: string[],+ tagsMatch: TicketTagsMatch,+ tagsExclude: string[],dateFrom: string | null,dateTo: string | null,sorting: Sorting | null,@@ -227,6 +250,8 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([sla,assignee,tags,+ tagsMatch,+ tagsExclude,dateFrom,dateTo,sorting,@@ -263,7 +288,10 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([}}if (values.tagsFilter.length > 0) {- params.tags = JSON.stringify(values.tagsFilter)+ params[values.tagsMatch === 'all' ? 'tags_all' : 'tags'] = JSON.stringify(values.tagsFilter)+ }+ if (values.tagsExcludeFilter.length > 0) {+ params.tags_exclude = JSON.stringify(values.tagsExcludeFilter)}if (values.searchQuery) {params.search = values.searchQuery@@ -321,6 +349,14 @@ export const supportTicketsSceneLogic = kea<supportTicketsSceneLogicType>([actions.clearActiveView()actions.setCurrentPage(1)},+ setTagsMatch: () => {+ actions.clearActiveView()+ actions.setCurrentPage(1)+ },+ setTagsExcludeFilter: () => {+ actions.clearActiveView()+ actions.setCurrentPage(1)+ },setDateRange: () => {actions.clearActiveView()actions.setCurrentPage(1)diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex ed4ea00d236f..ff85a50b042e 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -23,6 +23,8 @@ export type SidePanelViewState = 'list' | 'ticket' | 'new' | 'restore'export type RestoreFlowState = 'idle' | 'sending' | 'sent' | 'error'export type AssigneeFilterValue = 'all' | 'unassigned' | TicketAssignee+export type TicketTagsMatch = 'any' | 'all'+export interface TicketViewFilters {status?: TicketStatus[]priority?: TicketPriority[]@@ -30,6 +32,8 @@ export interface TicketViewFilters {sla?: TicketSlaState | 'all'assignee?: AssigneeFilterValuetags?: string[]+ tagsMatch?: TicketTagsMatch+ tagsExclude?: string[]dateFrom?: string | nulldateTo?: string | nullsorting?: Sorting | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 96ffb55cbf1a..f11843bab992 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -47842,9 +47842,17 @@ export namespace Schemas {*/status?: string;/**- * JSON-encoded array of tag names to filter by, e.g. `["billing","urgent"]`.+ * JSON-encoded array of tag names; returns tickets with ANY of them (OR), e.g. `["billing","urgent"]`.*/tags?: string;+ /**+ * JSON-encoded array of tag names; returns tickets that have ALL of them (AND), e.g. `["billing","urgent"]`.+ */+ tags_all?: string;+ /**+ * JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `["escalated"]`.+ */+ tags_exclude?: string;};export type ConversationsTicketsListChannelDetail = typeof ConversationsTicketsListChannelDetail[keyof typeof ConversationsTicketsListChannelDetail];diff --git a/services/mcp/src/generated/conversations/api.ts b/services/mcp/src/generated/conversations/api.tsindex 2d88b06efb77..034b15f04d6e 100644--- a/services/mcp/src/generated/conversations/api.ts+++ b/services/mcp/src/generated/conversations/api.ts@@ -90,7 +90,21 @@ export const ConversationsTicketsListQueryParams = /* @__PURE__ */ zod.object({tags: zod.string().optional()- .describe('JSON-encoded array of tag names to filter by, e.g. `["billing","urgent"]`.'),+ .describe(+ 'JSON-encoded array of tag names; returns tickets with ANY of them (OR), e.g. `["billing","urgent"]`.'+ ),+ tags_all: zod+ .string()+ .optional()+ .describe(+ 'JSON-encoded array of tag names; returns tickets that have ALL of them (AND), e.g. `["billing","urgent"]`.'+ ),+ tags_exclude: zod+ .string()+ .optional()+ .describe(+ 'JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `["escalated"]`.'+ ),})/**diff --git a/services/mcp/src/tools/generated/conversations.ts b/services/mcp/src/tools/generated/conversations.tsindex 7ac5cda9db41..1b548a23626f 100644--- a/services/mcp/src/tools/generated/conversations.ts+++ b/services/mcp/src/tools/generated/conversations.ts@@ -39,6 +39,8 @@ const conversationsTicketsList = (): ToolBase<sla: params.sla,status: params.status,tags: params.tags,+ tags_all: params.tags_all,+ tags_exclude: params.tags_exclude,},})const filtered = {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 14c48ba15ce2..e8b9cb1d1016 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@@ -66,7 +66,15 @@"type": "string"},"tags": {- "description": "JSON-encoded array of tag names to filter by, e.g. `[\"billing\",\"urgent\"]`.",+ "description": "JSON-encoded array of tag names; returns tickets with ANY of them (OR), e.g. `[\"billing\",\"urgent\"]`.",+ "type": "string"+ },+ "tags_all": {+ "description": "JSON-encoded array of tag names; returns tickets that have ALL of them (AND), e.g. `[\"billing\",\"urgent\"]`.",+ "type": "string"+ },+ "tags_exclude": {+ "description": "JSON-encoded array of tag names; returns tickets that have NONE of them (NOT), e.g. `[\"escalated\"]`.","type": "string"}},