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(customer-analytics): filter tasks by role (#113631)

Arthur Moreira de Deus42ed4211bfcc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3de63af81abb..0f53bf04d729 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9251,9 +9251,13 @@ snapshots:
scenes-app-customer-analytics-dashboard--b-2-c-mode--light:
hash: v1.k794b7964.ff25e11868464e00df352180254dbe0a1017cd1d8c7c4f4c7d6995068e80e2dc.m0XFOZVPCdSaCLaPQ6XTePvkZJ1I11QI2KARZi9QpWs
scenes-app-customer-analytics-dashboard--customer-tasks--dark:
- hash: v1.k794b7964.bf4411a8550fe620b82da8dbf7db11efbe3915634ecdcf3baa8b2bffc0aad593.frezJ_q91GKzahZb8GfRbUeRbERSv-ReB2HIBNJN6Ow
+ hash: v1.k794b7964.08e8cd42e255347bc8144b25b3592a4103483ebd5587cb14e9013786f000023b.duE7w5P1SNIj600LVcMaVEe9UWEqi-oGOprjEEeJaIE
scenes-app-customer-analytics-dashboard--customer-tasks--light:
- hash: v1.k794b7964.acedcb03c7c39d27c2b9f0ed3f1b1ac44fe3fdc58f68a0ed0d0b9e475e70ca96.nKLpWDvqLrHFG2HwFEAexR8rc63-OmxYQogH_Utdg9I
+ hash: v1.k794b7964.d936025c0bd0ec7e3886085746a8160e92c0f5e36b64ca46eea3dbf44839ea4a.9Lx5kC0EJ_EHO-lvAOH6xGgv_BkbefqSM-HpKmuzusM
+ scenes-app-customer-analytics-dashboard--customer-tasks-assignee-roles--dark:
+ hash: v1.k794b7964.ff1e2d80d015ed8d85aa11b81e21fbe6651f3f10f08184c5dacdbf297db0ffd2.EfU11y8W9FRIQhKcqwM67uop3eSNdNwPsp5Uv6Z09yU
+ scenes-app-customer-analytics-dashboard--customer-tasks-assignee-roles--light:
+ hash: v1.k794b7964.1eed6cafb7b3199131a277eba2e0afa88d1ef9359d122bc7c509d97300399c22.IHVs3nKi8DZlyCOFHz1f1kw9BXUnYdpBWK3Q4pgY4LA
scenes-app-customer-analytics-dashboard--feature-request-details--dark:
hash: v1.k794b7964.d87f1abf2d12f5814dd652ba1c760a15d00f6fa2f6927f9aaa662dacbd91a83c.8qn3xLm6N1ZugTMoofH8kEhupFhydr4UcG0Wlko4SLY
scenes-app-customer-analytics-dashboard--feature-request-details--light:
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 8aeb90023847..f5ab08a597f6 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -1394,6 +1394,10 @@ class CustomerTaskAssigneeCannotViewAccount(Exception):
pass
+class CustomerTaskRoleNotFound(Exception):
+ pass
+
+
class CustomerTaskInvalidTransition(Exception):
def __init__(self, current: str, requested: str) -> None:
self.current = current
@@ -1463,6 +1467,7 @@ class CustomerTaskListFilters:
search: str | None = None
account_id: UUID | None = None
assigned_to: str | None = None
+ assigned_role_id: UUID | None = None
statuses: tuple[str, ...] = ()
archive_state: str = "active"
due_after: datetime | None = None
diff --git a/products/customer_analytics/backend/logic/customer_tasks.py b/products/customer_analytics/backend/logic/customer_tasks.py
index fb4e12cd7c43..d0e4a898f09d 100644
--- a/products/customer_analytics/backend/logic/customer_tasks.py
+++ b/products/customer_analytics/backend/logic/customer_tasks.py
@@ -27,6 +27,7 @@ from products.customer_analytics.backend.facade.contracts import (
CustomerTaskAssigneeCannotViewAccount,
CustomerTaskAssigneeInvalid,
CustomerTaskInvalidTransition,
+ CustomerTaskRoleNotFound,
)
from products.customer_analytics.backend.models import Account, CustomerTask, CustomerTaskActivity
from products.customer_analytics.backend.models.customer_task import CustomerTaskActivityType, CustomerTaskStatus
@@ -273,6 +274,15 @@ def remove_customer_task_assignee_access_for_account(*, team: Team, account_id:
)
+def _list_role_member_user_ids(team_id: int, user_access_control: UserAccessControl, role_id: UUID) -> list[int]:
+ team = user_access_control.team
+ if team is None or team.id != team_id:
+ team = Team.objects.only("organization_id").get(id=team_id)
+ if not access_control_api.role_belongs_to_organization(role_id=role_id, organization_id=team.organization_id):
+ raise CustomerTaskRoleNotFound()
+ return access_control_api.valid_role_member_user_ids(role_id=role_id)
+
+
def list_customer_tasks(
*,
team_id: int,
@@ -292,6 +302,10 @@ def list_customer_tasks(
queryset = queryset.filter(assigned_to_id__isnull=True)
elif filters.assigned_to:
queryset = queryset.filter(assigned_to_id=int(filters.assigned_to))
+ if filters.assigned_role_id is not None:
+ queryset = queryset.filter(
+ assigned_to_id__in=_list_role_member_user_ids(team_id, user_access_control, filters.assigned_role_id)
+ )
if filters.statuses:
queryset = queryset.filter(status__in=filters.statuses)
if filters.archive_state == "active":
diff --git a/products/customer_analytics/backend/presentation/views/customer_tasks.py b/products/customer_analytics/backend/presentation/views/customer_tasks.py
index f991f2fc21b8..024b723486e0 100644
--- a/products/customer_analytics/backend/presentation/views/customer_tasks.py
+++ b/products/customer_analytics/backend/presentation/views/customer_tasks.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from functools import cached_property
from typing import Any, cast
+from uuid import UUID
from drf_spectacular.helpers import forced_singular_serializer
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
@@ -23,7 +24,9 @@ from products.access_control.backend.facade.user_access_control import UserAcces
from products.customer_analytics.backend.facade import api, contracts
from products.customer_analytics.backend.facade.constants import CUSTOMER_ANALYTICS_CUSTOMER_TASKS_FLAG
-_ASSIGNED_TO_ERROR = "assigned_to must be me, unassigned, or a project member ID."
+_ASSIGNED_TO_ERROR = "assigned_to must be me, unassigned, a project member ID, or role:<role UUID>."
+# pinned: the frontend writes the same prefix into links and API calls
+_ROLE_ASSIGNEE_PREFIX = "role:"
# posthog_user.id is an int4 column, and DRF never runs full_clean, so an ID past this bound would
# fail in Postgres with a 500 rather than being rejected here.
_MAX_MEMBER_ID = 2147483647
@@ -90,6 +93,10 @@ class CustomerTaskAssigneeErrorSerializer(serializers.Serializer):
assigned_to_id = serializers.CharField(read_only=True, help_text="Why the selected assignee is not allowed.")
+class CustomerTaskAssigneeFilterErrorSerializer(serializers.Serializer):
+ assigned_to = serializers.CharField(read_only=True, help_text="Why the selected assignee filter is not allowed.")
+
+
class CustomerTaskCreateSerializer(serializers.Serializer):
account_id = serializers.UUIDField(
required=False, allow_null=True, help_text="UUID of a visible account, or null for an accountless task."
@@ -188,7 +195,10 @@ class CustomerTaskActivitySerializer(serializers.Serializer):
class CustomerTaskListQuerySerializer(serializers.Serializer):
search = serializers.CharField(required=False, allow_blank=True, help_text="Search task name and description.")
account_id = serializers.UUIDField(required=False, help_text="Filter by account UUID.")
- assigned_to = serializers.CharField(required=False, help_text="Filter by me, unassigned, or one user ID.")
+ assigned_to = serializers.CharField(
+ required=False,
+ help_text="Filter by me, unassigned, one user ID, or role:<role UUID>. A role returns tasks assigned to any current member of that organization role.",
+ )
statuses = serializers.CharField(required=False, help_text="Comma-separated task statuses.")
archive_state = serializers.ChoiceField(
required=False,
@@ -212,6 +222,12 @@ class CustomerTaskListQuerySerializer(serializers.Serializer):
def validate_assigned_to(self, value: str) -> str:
if value in {"me", "unassigned"}:
return value
+ if value.startswith(_ROLE_ASSIGNEE_PREFIX):
+ try:
+ role_id = UUID(value.removeprefix(_ROLE_ASSIGNEE_PREFIX))
+ except ValueError:
+ raise serializers.ValidationError(_ASSIGNED_TO_ERROR) from None
+ return f"{_ROLE_ASSIGNEE_PREFIX}{role_id}"
# str.isdigit() accepts characters such as "²" that int() rejects.
try:
member_id = int(value)
@@ -228,6 +244,12 @@ class CustomerTaskListQuerySerializer(serializers.Serializer):
return values
+def _parse_assigned_role_id(assigned_to: str | None) -> UUID | None:
+ if assigned_to is None or not assigned_to.startswith(_ROLE_ASSIGNEE_PREFIX):
+ return None
+ return UUID(assigned_to.removeprefix(_ROLE_ASSIGNEE_PREFIX))
+
+
class CustomerTaskActivityQuerySerializer(serializers.Serializer):
limit = serializers.IntegerField(
required=False, default=50, min_value=1, max_value=100, help_text="Page size, from 1 to 100."
@@ -323,13 +345,16 @@ class CustomerTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
def list(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
data = request.validated_query_data
+ assigned_to = data.get("assigned_to")
+ assigned_role_id = _parse_assigned_role_id(assigned_to)
page, count = api.list_customer_tasks(
team_id=self.canonical_team_id,
user_access_control=self.user_access_control,
filters=contracts.CustomerTaskListFilters(
search=data.get("search", "").strip() or None,
account_id=data.get("account_id"),
- assigned_to=data.get("assigned_to"),
+ assigned_to=None if assigned_role_id else assigned_to,
+ assigned_role_id=assigned_role_id,
statuses=data.get("statuses", ()),
archive_state=data["archive_state"],
due_after=data.get("due_after"),
@@ -460,6 +485,11 @@ class CustomerTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
}
)
return Response(error.data, status=status.HTTP_400_BAD_REQUEST)
+ if isinstance(exc, contracts.CustomerTaskRoleNotFound):
+ role_error = CustomerTaskAssigneeFilterErrorSerializer(
+ instance={"assigned_to": "Select a role in this organization."}
+ )
+ return Response(role_error.data, status=status.HTTP_400_BAD_REQUEST)
if isinstance(exc, contracts.CustomerTaskInvalidTransition):
return Response(
{"status": "This task can" + chr(39) + f"t move from {exc.current} to {exc.requested}."},
diff --git a/products/customer_analytics/backend/test/test_customer_tasks.py b/products/customer_analytics/backend/test/test_customer_tasks.py
index 7236ad654def..4c4c62de9bba 100644
--- a/products/customer_analytics/backend/test/test_customer_tasks.py
+++ b/products/customer_analytics/backend/test/test_customer_tasks.py
@@ -10,11 +10,12 @@ from parameterized import parameterized
from rest_framework import serializers, status
from posthog.constants import AvailableFeature
-from posthog.models import OrganizationMembership, PersonalAPIKey, Team, User
+from posthog.models import Organization, OrganizationMembership, PersonalAPIKey, Team, User
from posthog.models.personal_api_key import hash_key_value
from posthog.models.utils import generate_random_token_personal
from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.role import Role, RoleMembership
from products.customer_analytics.backend.logic import customer_tasks
from products.customer_analytics.backend.models import Account, CustomerTask, CustomerTaskActivity
from products.customer_analytics.backend.presentation.views.customer_tasks import (
@@ -49,9 +50,11 @@ class CustomerTaskSerializerTest(SimpleTestCase):
("a member id", "7", "7"),
("a non-decimal digit", "٢", "2"),
("the me shorthand", "me", "me"),
+ ("a role", "role:00000000-0000-4000-8000-000000000001", "role:00000000-0000-4000-8000-000000000001"),
+ ("a role without a UUID", "role:onboarding", None),
]
)
- def test_assigned_to_filter_only_accepts_a_usable_member_id(
+ def test_assigned_to_filter_only_accepts_a_usable_member_or_role(
self, _name: str, value: str, expected: str | None
) -> None:
serializer = CustomerTaskListQuerySerializer(data={"assigned_to": value})
@@ -579,6 +582,33 @@ class CustomerTaskAPI(APIBaseTest):
assert response.json()["count"] == len(expected_names)
assert {task["name"] for task in response.json()["results"]} == set(expected_names)
+ def test_list_role_filter_matches_current_role_members(self) -> None:
+ _, other_assignee = self._create_filtering_dataset()
+ role = Role.objects.create(name="Onboarding", organization=self.organization)
+ RoleMembership.objects.create(role=role, user=other_assignee)
+
+ response = self.client.get(self.url, {"assigned_to": f"role:{role.id}"})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert {task["name"] for task in response.json()["results"]} == {"Bravo", "Delta"}
+
+ RoleMembership.objects.create(role=role, user=self.user)
+
+ response = self.client.get(self.url, {"assigned_to": f"role:{role.id}"})
+
+ assert response.status_code == status.HTTP_200_OK
+ assert {task["name"] for task in response.json()["results"]} == {"Alpha", "Bravo", "Delta"}
+
+ def test_list_role_filter_rejects_a_role_from_another_organization(self) -> None:
+ self._create_filtering_dataset()
+ other_organization = Organization.objects.create(name="Other organization")
+ foreign_role = Role.objects.create(name="Onboarding", organization=other_organization)
+
+ response = self.client.get(self.url, {"assigned_to": f"role:{foreign_role.id}"})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "assigned_to" in response.json()
+
@parameterized.expand(
[
("due_after", "due_after", "2026-01-02T00:00:00Z", ("Alpha", "Delta")),
diff --git a/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx b/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx
index a3fcfa880ae2..1ba9533af971 100644
--- a/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx
+++ b/products/customer_analytics/frontend/CustomerAnalyticsScene.stories.tsx
@@ -1,4 +1,8 @@
+import { MOCK_DEFAULT_BASIC_USER } from 'lib/api.mock'
+
import { Meta, StoryObj } from '@storybook/react'
+import { waitFor, within } from '@testing-library/dom'
+import userEvent from '@testing-library/user-event'
import posthog from 'posthog-js'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -188,6 +192,75 @@ export const CustomerTasks: Story = {
},
}
+const roleStoryItems = [
+ {
+ id: '018f47de-7e12-7000-8000-000000000061',
+ name: 'Team Onboarding',
+ created_at: '2024-01-01T10:00:00Z',
+ created_by: null,
+ members: [
+ {
+ id: '018f47de-7e12-7000-8000-000000000071',
+ role_id: '018f47de-7e12-7000-8000-000000000061',
+ user: MOCK_DEFAULT_BASIC_USER,
+ user_uuid: MOCK_DEFAULT_BASIC_USER.uuid,
+ joined_at: '2024-01-01T10:00:00Z',
+ updated_at: '2024-01-01T10:00:00Z',
+ },
+ ],
+ },
+ {
+ id: '018f47de-7e12-7000-8000-000000000062',
+ name: 'Team Customer Success',
+ created_at: '2024-01-01T10:00:00Z',
+ created_by: null,
+ members: [],
+ },
+]
+
+export const CustomerTasksAssigneeRoles: Story = {
+ render: () => {
+ useStorybookMocks({
+ get: {
+ 'api/projects/:team_id/customer_tasks/': {
+ count: customerTaskStoryItems.length,
+ next: null,
+ previous: null,
+ results: customerTaskStoryItems,
+ },
+ '/api/organizations/:organization_id/roles/': {
+ count: roleStoryItems.length,
+ next: null,
+ previous: null,
+ results: roleStoryItems,
+ },
+ },
+ })
+ return <App />
+ },
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.CUSTOMER_ANALYTICS, FEATURE_FLAGS.CUSTOMER_ANALYTICS_CUSTOMER_TASKS],
+ pageUrl: urls.customerAnalyticsTasks(),
+ testOptions: {
+ waitForSelector: '[data-attr="customer-task-name"]',
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const trigger = await waitFor(
+ () => {
+ const element = canvasElement.querySelector<HTMLElement>('[data-attr="customer-tasks-assignee-filter"]')
+ if (!element) {
+ throw new Error('Assignee filter not rendered yet')
+ }
+ return element
+ },
+ { timeout: 15000 }
+ )
+ await userEvent.click(trigger)
+ await within(canvasElement.ownerDocument.body).findByText('Team Customer Success', {}, { timeout: 15000 })
+ },
+}
+
const featureRequestStoryItem = {
id: '018f47de-7e12-7000-8000-000000000001',
title: 'Export account-level retention data',
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksAssigneeDropdown.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksAssigneeDropdown.tsx
new file mode 100644
index 000000000000..f7df13a88654
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksAssigneeDropdown.tsx
@@ -0,0 +1,147 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconChevronDown } from '@posthog/icons'
+import { LemonButton, LemonDropdown, LemonInput, ProfilePicture } from '@posthog/lemon-ui'
+
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
+import { fullName } from 'lib/utils/strings'
+
+import type { RoleType } from '~/types'
+
+import { isRoleAssigneeFilter, type CustomerTaskAssigneeFilter } from './customerTaskFilters'
+import { customerTasksAssigneeDropdownLogic } from './customerTasksAssigneeDropdownLogic'
+
+export interface CustomerTasksAssigneeDropdownProps {
+ value: CustomerTaskAssigneeFilter
+ onChange: (value: CustomerTaskAssigneeFilter) => void
+}
+
+export function CustomerTasksAssigneeDropdown({ value, onChange }: CustomerTasksAssigneeDropdownProps): JSX.Element {
+ const {
+ search,
+ rolesLoading,
+ quickOptions,
+ myRoles,
+ otherRoles,
+ filteredMembers,
+ membersLoading,
+ nothingMatches,
+ assigneeLabel,
+ } = useValues(customerTasksAssigneeDropdownLogic)
+ const { setSearch, ensureAllMembersLoaded } = useActions(customerTasksAssigneeDropdownLogic)
+ const [open, setOpen] = useState(false)
+ // The trigger label names the selected member, so the member list has to load before the dropdown opens.
+ useOnMountEffect(ensureAllMembersLoaded)
+
+ const select = (next: CustomerTaskAssigneeFilter): void => {
+ setOpen(false)
+ setSearch('')
+ onChange(next)
+ }
+
+ const selectedRoleId = isRoleAssigneeFilter(value) ? value.roleId : null
+
+ const renderRole = (role: RoleType): JSX.Element => (
+ <LemonButton
+ key={role.id}
+ fullWidth
+ role="menuitem"
+ size="small"
+ active={selectedRoleId === role.id}
+ icon={<ProfilePicture user={{ first_name: role.name }} size="sm" />}
+ onClick={() => select({ roleId: role.id })}
+ data-attr="customer-tasks-assignee-filter-role"
+ >
+ <span className="truncate">{role.name}</span>
+ </LemonButton>
+ )
+
+ return (
+ <LemonDropdown
+ visible={open}
+ onVisibilityChange={(visible) => {
+ setOpen(visible)
+ if (!visible) {
+ setSearch('')
+ }
+ }}
+ closeOnClickInside={false}
+ placement="bottom-start"
+ overlay={
+ <div className="flex flex-col gap-1 p-1 w-72 max-h-120 overflow-y-auto">
+ <LemonInput
+ type="search"
+ placeholder="Search roles and members"
+ autoFocus
+ size="small"
+ value={search}
+ onChange={setSearch}
+ fullWidth
+ />
+ {quickOptions.map((option) => (
+ <LemonButton
+ key={option.value}
+ fullWidth
+ role="menuitem"
+ size="small"
+ active={value === option.value}
+ onClick={() => select(option.value)}
+ >
+ {option.label}
+ </LemonButton>
+ ))}
+ {myRoles.length > 0 && (
+ <section className="flex flex-col">
+ <h5 className="mx-2 my-1">My roles</h5>
+ {myRoles.map(renderRole)}
+ </section>
+ )}
+ {rolesLoading ? (
+ <div className="px-2 py-1 text-secondary">Loading roles…</div>
+ ) : (
+ otherRoles.length > 0 && (
+ <section className="flex flex-col">
+ <h5 className="mx-2 my-1">{myRoles.length > 0 ? 'Other roles' : 'Roles'}</h5>
+ {otherRoles.map(renderRole)}
+ </section>
+ )
+ )}
+ {membersLoading ? (
+ <div className="px-2 py-1 text-secondary">Loading members…</div>
+ ) : (
+ filteredMembers.length > 0 && (
+ <section className="flex flex-col">
+ <h5 className="mx-2 my-1">Members</h5>
+ {filteredMembers.map((member) => (
+ <LemonButton
+ key={member.user.id}
+ fullWidth
+ role="menuitem"
+ size="small"
+ active={value === member.user.id}
+ icon={<ProfilePicture user={member.user} size="sm" />}
+ onClick={() => select(member.user.id)}
+ data-attr="customer-tasks-assignee-filter-member"
+ >
+ <span className="truncate">{fullName(member.user) || member.user.email}</span>
+ </LemonButton>
+ ))}
+ </section>
+ )
+ )}
+ {nothingMatches && <div className="px-2 py-1 text-secondary">No roles or members match.</div>}
+ </div>
+ }
+ >
+ <LemonButton
+ type="secondary"
+ size="small"
+ sideIcon={<IconChevronDown />}
+ data-attr="customer-tasks-assignee-filter"
+ >
+ {assigneeLabel(value)}
+ </LemonButton>
+ </LemonDropdown>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx
index 610237cf7f70..0eb9efc79405 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksFilters.tsx
@@ -10,14 +10,13 @@ import {
type LemonMenuItems,
} from '@posthog/lemon-ui'
-import { MemberSelect } from 'lib/components/MemberSelect'
-
-import type { CustomerTaskAssigneeFilter, CustomerTasksContext } from './customerTaskFilters'
+import type { CustomerTasksContext } from './customerTaskFilters'
import {
CUSTOMER_TASK_ARCHIVE_OPTIONS,
CUSTOMER_TASK_DUE_OPTIONS,
CUSTOMER_TASK_STATUS_OPTIONS,
} from './customerTaskFilters'
+import { CustomerTasksAssigneeDropdown } from './CustomerTasksAssigneeDropdown'
import type { customerTasksLogicType } from './customerTasksLogic'
export interface CustomerTasksFiltersProps {
logic: import('kea').BuiltLogic<customerTasksLogicType>
@@ -27,8 +26,15 @@ export interface CustomerTasksFiltersProps {
export function CustomerTasksFilters({ logic, context, canViewAll = false }: CustomerTasksFiltersProps): JSX.Element {
const { filters, hasActiveFilters, accountOptions, accountOptionsResponseLoading, accountFilterOpen } =
useValues(logic)
- const { setFilters, setSearch, setAccountFilter, setAccountFilterOpen, loadAccountOptions, resetFilters } =
- useActions(logic)
+ const {
+ setAssignee,
+ setFilters,
+ setSearch,
+ setAccountFilter,
+ setAccountFilterOpen,
+ loadAccountOptions,
+ resetFilters,
+ } = useActions(logic)
const status: LemonMenuItems = [
{
items: CUSTOMER_TASK_STATUS_OPTIONS.map((o) => ({
@@ -56,23 +62,6 @@ export function CustomerTasksFilters({ logic, context, canViewAll = false }: Cus
})),
},
]
- const assignee: LemonMenuItems = [
- {
- items: [
- { label: 'Anyone', active: filters.assignee === 'any', onClick: () => setFilters({ assignee: 'any' }) },
- { label: 'Me', active: filters.assignee === 'me', onClick: () => setFilters({ assignee: 'me' }) },
- ...(canViewAll
- ? [
- {
- label: 'Unassigned',
- active: filters.assignee === 'unassigned',
- onClick: () => setFilters({ assignee: 'unassigned' }),
- },
- ]
- : []),
- ],
- },
- ]
// The account tab always lists every visible task for the account, so the query drops
// assigned_to there — offering the control would do nothing.
const showAssigneeFilters = canViewAll && context === 'inbox'
@@ -96,22 +85,7 @@ export function CustomerTasksFilters({ logic, context, canViewAll = false }: Cus
{CUSTOMER_TASK_STATUS_OPTIONS.find((o) => o.value === filters.status)?.label}
</LemonButton>
</LemonMenu>
- {showAssigneeFilters && (
- <LemonMenu items={assignee}>
- <LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>
- {assigneeLabel(filters.assignee)}
- </LemonButton>
- </LemonMenu>
- )}
- {showAssigneeFilters && (
- <MemberSelect
- value={typeof filters.assignee === 'number' ? filters.assignee : null}
- defaultLabel="Choose member"
- type="secondary"
- size="small"
- onChange={(u) => setFilters({ assignee: u?.id ?? 'any' })}
- />
- )}{' '}
+ {showAssigneeFilters && <CustomerTasksAssigneeDropdown value={filters.assignee} onChange={setAssignee} />}
{context === 'inbox' && (
<LemonMenu items={due}>
<LemonButton type="secondary" size="small" sideIcon={<IconChevronDown />}>
@@ -162,6 +136,3 @@ export function CustomerTasksFilters({ logic, context, canViewAll = false }: Cus
</div>
)
}
-function assigneeLabel(value: CustomerTaskAssigneeFilter): string {
- return value === 'any' ? 'Anyone' : value === 'me' ? 'Me' : value === 'unassigned' ? 'Unassigned' : 'Member'
-}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx
index 5ff9197ea4bf..d4462be56214 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx
+++ b/products/customer_analytics/frontend/components/CustomerTasks/CustomerTasksTable.test.tsx
@@ -181,7 +181,7 @@ describe('CustomerTasksTable', () => {
</Provider>
)
expect(findTableHeader(screen.getByRole('table'), 'Account')).not.toBeUndefined()
- expect(within(filterBar(inbox.container)).queryByText('Choose member')).not.toBeNull()
+ expect(filterBar(inbox.container).querySelector('[data-attr="customer-tasks-assignee-filter"]')).not.toBeNull()
cleanup()
logic.unmount()
@@ -195,7 +195,9 @@ describe('CustomerTasksTable', () => {
)
expect(findTableHeader(accountTable.getByRole('table'), 'Account')).toBeUndefined()
- expect(within(filterBar(accountTable.container)).queryByText('Choose member')).toBeNull()
+ expect(
+ filterBar(accountTable.container).querySelector('[data-attr="customer-tasks-assignee-filter"]')
+ ).toBeNull()
})
test('shows the due window a link asked for', async () => {
cleanup()
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts
index fd98a67e44b0..6b5e16a85f98 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.test.ts
@@ -9,7 +9,9 @@ import {
hasCustomerTaskFilters,
parseCustomerTaskSearchParams,
} from './customerTaskFilters'
-import type { CustomerTaskDueFilter, CustomerTasksContext } from './customerTaskFilters'
+import type { CustomerTaskAssigneeFilter, CustomerTaskDueFilter, CustomerTasksContext } from './customerTaskFilters'
+
+const ROLE_ID = '0199ed4a-5c03-0000-3220-df21df612e95'
describe('customer task filter helpers', () => {
test.each([
@@ -102,12 +104,14 @@ describe('customer task filter helpers', () => {
})
test.each([
- ['a resource viewer', true, 'unassigned'],
- ['an assignment-only user', false, 'me'],
- ])('keeps %s within their allowed assignee scope', (_, canViewAll, assignedTo) => {
+ ['a resource viewer', true, 'unassigned', { assigned_to: 'unassigned' }],
+ ['an assignment-only user', false, 'unassigned', { assigned_to: 'me' }],
+ ['a resource viewer filtering by role', true, { roleId: ROLE_ID }, { assigned_to: `role:${ROLE_ID}` }],
+ ['an assignment-only user filtering by role', false, { roleId: ROLE_ID }, { assigned_to: 'me' }],
+ ])('keeps %s within their allowed assignee scope', (_, canViewAll, assignee, expected) => {
expect(
customerTasksQuery(
- { ...defaultCustomerTaskFilters('inbox'), assignee: 'unassigned' },
+ { ...defaultCustomerTaskFilters('inbox'), assignee: assignee as CustomerTaskAssigneeFilter },
'inbox',
undefined,
1,
@@ -115,7 +119,7 @@ describe('customer task filter helpers', () => {
'UTC',
canViewAll
)
- ).toMatchObject({ assigned_to: assignedTo })
+ ).toMatchObject(expected)
})
test.each([
['the inbox defaults', {}],
@@ -124,6 +128,7 @@ describe('customer task filter helpers', () => {
'a named member and an account',
{ assignee: '42', account: '0199ed4a-5c03-0000-3220-df21df612e95', sort: '-updated_at' },
],
+ ['a role', { assignee: `role:${ROLE_ID}` }],
['a search', { search: 'renewal' }],
['a whitespace search the query still sends', { search: ' ' }],
])('round-trips %s through the search params', (_, params) => {
@@ -137,6 +142,7 @@ describe('customer task filter helpers', () => {
['a non-member assignee', { assignee: 'someone' }, { assignee: 'me' }],
['a negative member id', { assignee: '-1' }, { assignee: 'me' }],
['an out-of-range member id', { assignee: '2147483648' }, { assignee: 'me' }],
+ ['a malformed role id', { assignee: 'role:../x' }, { assignee: 'me' }],
['an empty account', { account: '' }, { account: null }],
['a path-shaped account', { account: '../../x' }, { account: null }],
])('falls back to the inbox default for %s', (_, params, expected) => {
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
index ae8d4cfe2f45..451b3657c12b 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTaskFilters.ts
@@ -12,11 +12,36 @@ import type {
export type CustomerTasksContext = 'account' | 'inbox'
export type CustomerTaskStatusFilter = 'open' | 'completed' | 'canceled' | 'all'
-export type CustomerTaskAssigneeFilter = 'any' | 'me' | 'unassigned' | number
+export type CustomerTaskRoleAssigneeFilter = { roleId: string }
+export type CustomerTaskAssigneeFilter = 'any' | 'me' | 'unassigned' | number | CustomerTaskRoleAssigneeFilter
+export type CustomerTaskAssigneeMode = 'any' | 'me' | 'unassigned' | 'member' | 'role'
export type CustomerTaskDueFilter = 'any' | 'overdue' | 'today' | 'upcoming' | 'no_due_date'
export type CustomerTaskAccountFilter = { id: string; name: string }
const MAX_CUSTOMER_TASK_ASSIGNEE_ID = 2_147_483_647
+// pinned: links and the assigned_to API parameter both use this prefix, so shared links keep working
+const ROLE_ASSIGNEE_PREFIX = 'role:'
+
+export function isRoleAssigneeFilter(value: CustomerTaskAssigneeFilter): value is CustomerTaskRoleAssigneeFilter {
+ return typeof value === 'object'
+}
+
+export function customerTaskAssigneeMode(value: CustomerTaskAssigneeFilter): CustomerTaskAssigneeMode {
+ if (isRoleAssigneeFilter(value)) {
+ return 'role'
+ }
+ return typeof value === 'number' ? 'member' : value
+}
+
+function assignedToParam(value: CustomerTaskAssigneeFilter): CustomerTasksListParams['assigned_to'] {
+ if (value === 'any') {
+ return undefined
+ }
+ if (isRoleAssigneeFilter(value)) {
+ return ROLE_ASSIGNEE_PREFIX + value.roleId
+ }
+ return String(value)
+}
export const CUSTOMER_TASK_ORDERINGS = [
'name',
'-name',
@@ -174,19 +199,11 @@ export function customerTasksQuery(
canViewAll = true,
ordering: CustomerTaskOrdering = DEFAULT_CUSTOMER_TASK_ORDERING
): CustomerTasksListParams {
+ const assignee: CustomerTaskAssigneeFilter = !canViewAll && context === 'inbox' ? 'me' : filters.assignee
const query: CustomerTasksListParams = {
search: filters.search || undefined,
account_id: accountId ?? filters.account?.id,
- assigned_to:
- !canViewAll && context === 'inbox'
- ? 'me'
- : filters.assignee === 'any'
- ? undefined
- : filters.assignee === 'me'
- ? 'me'
- : filters.assignee === 'unassigned'
- ? 'unassigned'
- : String(filters.assignee),
+ assigned_to: assignedToParam(assignee),
statuses:
filters.status === 'all' ? undefined : filters.status === 'open' ? 'open,in_progress' : filters.status,
archive_state: filters.archiveState,
@@ -210,6 +227,7 @@ export const CUSTOMER_TASK_URL_KEYS = [...CUSTOMER_TASK_FILTER_URL_KEYS, 'sort',
// Event names are consumed by product analytics, so changing one splits its historical data.
export const CustomerTaskEvents = {
InboxViewed: 'customer analytics tasks inbox viewed',
+ AssigneeFilterChanged: 'customer analytics tasks assignee filter changed',
} as const
export type CustomerTaskUrlState = {
@@ -229,7 +247,9 @@ export function customerTaskSearchParams(state: CustomerTaskUrlState): Record<st
if (state.filters.status !== defaults.status) {
params.status = state.filters.status
}
- if (state.filters.assignee !== defaults.assignee) {
+ if (isRoleAssigneeFilter(state.filters.assignee)) {
+ params.assignee = ROLE_ASSIGNEE_PREFIX + state.filters.assignee.roleId
+ } else if (state.filters.assignee !== defaults.assignee) {
params.assignee = String(state.filters.assignee)
}
if (state.filters.archiveState !== defaults.archiveState) {
@@ -254,6 +274,10 @@ function parseAssignee(value: unknown): CustomerTaskAssigneeFilter | null {
if (value === 'any' || value === 'me' || value === 'unassigned') {
return value
}
+ if (typeof value === 'string' && value.startsWith(ROLE_ASSIGNEE_PREFIX)) {
+ const roleId = value.slice(ROLE_ASSIGNEE_PREFIX.length)
+ return isUUIDLike(roleId) ? { roleId } : null
+ }
const memberId = Number(value)
return Number.isInteger(memberId) && memberId > 0 && memberId <= MAX_CUSTOMER_TASK_ASSIGNEE_ID ? memberId : null
}
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksAssigneeDropdownLogic.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksAssigneeDropdownLogic.ts
new file mode 100644
index 000000000000..d0822c41b8ed
--- /dev/null
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksAssigneeDropdownLogic.ts
@@ -0,0 +1,140 @@
+import { MakeLogicType, LogicWrapper, actions, connect, kea, path, reducers, selectors } from 'kea'
+
+import { fullName } from 'lib/utils/strings'
+import { membersLogic } from 'scenes/organization/membersLogic'
+import { rolesLogic } from 'scenes/settings/organization/Permissions/Roles/rolesLogic'
+
+import type { OrganizationMemberType, RoleType } from '~/types'
+
+import { isRoleAssigneeFilter, type CustomerTaskAssigneeFilter } from './customerTaskFilters'
+
+export type CustomerTaskQuickAssigneeOption = { value: 'any' | 'me' | 'unassigned'; label: string }
+
+const CUSTOMER_TASK_QUICK_ASSIGNEE_OPTIONS: readonly CustomerTaskQuickAssigneeOption[] = [
+ { value: 'any', label: 'Anyone' },
+ { value: 'me', label: 'Me' },
+ { value: 'unassigned', label: 'Unassigned' },
+]
+
+export interface customerTasksAssigneeDropdownLogicValues {
+ search: string
+ roles: RoleType[]
+ rolesLoading: boolean
+ me: OrganizationMemberType | null
+ meFirstMembers: OrganizationMemberType[]
+ membersLoading: boolean
+ quickOptions: CustomerTaskQuickAssigneeOption[]
+ myRoles: RoleType[]
+ otherRoles: RoleType[]
+ filteredMembers: OrganizationMemberType[]
+ nothingMatches: boolean
+ assigneeLabel: (assignee: CustomerTaskAssigneeFilter) => string
+}
+
+export interface customerTasksAssigneeDropdownLogicActions {
+ setSearch: (search: string) => { search: string }
+ ensureAllMembersLoaded: () => { value: true }
+}
+
+export type customerTasksAssigneeDropdownLogicType = MakeLogicType<
+ customerTasksAssigneeDropdownLogicValues,
+ customerTasksAssigneeDropdownLogicActions
+>
+
+function matchesSearch(text: string, search: string): boolean {
+ return text.toLowerCase().includes(search.trim().toLowerCase())
+}
+
+function memberName(member: OrganizationMemberType): string {
+ return fullName(member.user) || member.user.email
+}
+
+function filterRolesBySearch(roles: RoleType[], search: string): RoleType[] {
+ return roles
+ .filter((role) => matchesSearch(role.name, search))
+ .sort((left, right) => left.name.localeCompare(right.name))
+}
+
+export const customerTasksAssigneeDropdownLogic: LogicWrapper<customerTasksAssigneeDropdownLogicType> =
+ kea<customerTasksAssigneeDropdownLogicType>([
+ path([
+ 'products',
+ 'customer_analytics',
+ 'frontend',
+ 'components',
+ 'CustomerTasks',
+ 'customerTasksAssigneeDropdownLogic',
+ ]),
+ connect(() => ({
+ values: [rolesLogic, ['roles', 'rolesLoading'], membersLogic, ['me', 'meFirstMembers', 'membersLoading']],
+ actions: [membersLogic, ['ensureAllMembersLoaded']],
+ })),
+ actions({
+ setSearch: (search: string) => ({ search }),
+ }),
+ reducers({
+ search: ['', { setSearch: (_, { search }) => search }],
+ }),
+ selectors({
+ quickOptions: [
+ (s) => [s.search],
+ (search: string): CustomerTaskQuickAssigneeOption[] =>
+ CUSTOMER_TASK_QUICK_ASSIGNEE_OPTIONS.filter((option) => matchesSearch(option.label, search)),
+ ],
+ myRoles: [
+ (s) => [s.roles, s.me, s.search],
+ (roles: RoleType[], me: OrganizationMemberType | null, search: string): RoleType[] =>
+ me
+ ? filterRolesBySearch(roles ?? [], search).filter((role) =>
+ (role.members ?? []).some((member) => member.user.uuid === me.user.uuid)
+ )
+ : [],
+ ],
+ otherRoles: [
+ (s) => [s.roles, s.myRoles, s.search],
+ (roles: RoleType[], myRoles: RoleType[], search: string): RoleType[] => {
+ const myRoleIds = new Set(myRoles.map((role) => role.id))
+ return filterRolesBySearch(roles ?? [], search).filter((role) => !myRoleIds.has(role.id))
+ },
+ ],
+ filteredMembers: [
+ (s) => [s.meFirstMembers, s.search],
+ (members: OrganizationMemberType[], search: string): OrganizationMemberType[] =>
+ members.filter(
+ (member) =>
+ matchesSearch(memberName(member), search) || matchesSearch(member.user.email, search)
+ ),
+ ],
+ nothingMatches: [
+ (s) => [s.quickOptions, s.myRoles, s.otherRoles, s.filteredMembers, s.rolesLoading, s.membersLoading],
+ (
+ quickOptions: CustomerTaskQuickAssigneeOption[],
+ myRoles: RoleType[],
+ otherRoles: RoleType[],
+ filteredMembers: OrganizationMemberType[],
+ rolesLoading: boolean,
+ membersLoading: boolean
+ ): boolean =>
+ !rolesLoading &&
+ !membersLoading &&
+ quickOptions.length + myRoles.length + otherRoles.length + filteredMembers.length === 0,
+ ],
+ assigneeLabel: [
+ (s) => [s.roles, s.meFirstMembers],
+ (roles: RoleType[], members: OrganizationMemberType[]) =>
+ (assignee: CustomerTaskAssigneeFilter): string => {
+ if (isRoleAssigneeFilter(assignee)) {
+ return (roles ?? []).find((role) => role.id === assignee.roleId)?.name ?? 'Role'
+ }
+ if (typeof assignee === 'number') {
+ const member = members.find((candidate) => candidate.user.id === assignee)
+ return member ? memberName(member) : 'Member'
+ }
+ return (
+ CUSTOMER_TASK_QUICK_ASSIGNEE_OPTIONS.find((option) => option.value === assignee)?.label ??
+ 'Anyone'
+ )
+ },
+ ],
+ }),
+ ])
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts
index 50ab7a4d539a..97321e3be1e1 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.test.ts
@@ -1,5 +1,6 @@
import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { waitFor } from '@testing-library/react'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
@@ -44,6 +45,8 @@ const mockAccount = accountsRetrieve as jest.MockedFunction<typeof accountsRetri
const URL_ACCOUNT_ID = '0199ed4a-5c03-0000-3220-df21df612e95'
const SECOND_URL_ACCOUNT_ID = '0199ed4a-5c03-0000-3220-df21df612e96'
+const DELETED_ROLE_ID = '0199ed4a-5c03-0000-3220-df21df612e97'
+const NEWER_ROLE_ID = '0199ed4a-5c03-0000-3220-df21df612e98'
function task(canEdit = true): CustomerTaskApi {
return {
@@ -310,6 +313,50 @@ describe('customerTasksLogic', () => {
)
})
+ test('falls back to the default assignee when a linked role no longer exists', async () => {
+ mockList.mockRejectedValueOnce(
+ new ApiError(undefined, 400, undefined, { assigned_to: 'Select a role in this organization.' })
+ )
+ router.actions.push(urls.customerAnalyticsTasks(), { assignee: `role:${DELETED_ROLE_ID}` })
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(mockList).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ assigned_to: `role:${DELETED_ROLE_ID}` })
+ )
+ expect(logic.values.filters.assignee).toBe('me')
+ expect(router.values.searchParams.assignee).toBeUndefined()
+ expect(mockList).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ assigned_to: 'me' }))
+ })
+
+ test('keeps a newer role when a superseded role request fails', async () => {
+ let rejectStaleRequest: (error: unknown) => void = () => {}
+ mockList.mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ rejectStaleRequest = reject
+ })
+ )
+ router.actions.push(urls.customerAnalyticsTasks(), { assignee: `role:${DELETED_ROLE_ID}` })
+ logic = customerTasksLogic({ context: 'inbox', canViewAll: true })
+ logic.mount()
+ await waitFor(() => expect(mockList).toHaveBeenCalledTimes(1))
+
+ logic.actions.setAssignee({ roleId: NEWER_ROLE_ID })
+ rejectStaleRequest(
+ new ApiError(undefined, 400, undefined, { assigned_to: 'Select a role in this organization.' })
+ )
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters.assignee).toEqual({ roleId: NEWER_ROLE_ID })
+ expect(mockList).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ assigned_to: `role:${NEWER_ROLE_ID}` })
+ )
+ })
+
test('keeps the persisted filters when the link carries none', async () => {
const prefix = customerTasksPersistencePrefix(1, 42)
logic = customerTasksLogic({ context: 'inbox', canViewAll: true, persistPrefix: prefix })
diff --git a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
index 19fc7b094bb5..487848ccb8c5 100644
--- a/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
+++ b/products/customer_analytics/frontend/components/CustomerTasks/customerTasksLogic.ts
@@ -52,14 +52,17 @@ import {
CUSTOMER_TASK_FILTER_URL_KEYS,
CUSTOMER_TASK_ORDERINGS,
CUSTOMER_TASK_URL_KEYS,
+ customerTaskAssigneeMode,
customerTaskSearchParams,
CustomerTaskEvents,
+ isRoleAssigneeFilter,
customerTasksQuery,
DEFAULT_CUSTOMER_TASK_ORDERING,
defaultCustomerTaskFilters,
hasCustomerTaskFilters,
parseCustomerTaskSearchParams,
type CustomerTaskAccountFilter,
+ type CustomerTaskAssigneeFilter,
type CustomerTaskFilters,
type CustomerTaskOrdering,
type CustomerTasksContext,
@@ -112,6 +115,7 @@ export interface customerTasksLogicActions {
createTask: (task: CustomerTaskCreateApi) => { task: CustomerTaskCreateApi }
loadAccountOptions: (payload: { query: string }) => { query: string }
loadTaskPage: () => { value: true }
+ loadTaskPageFailure: (error: string, errorObject?: any) => { error: string; errorObject?: any }
mutationFinished: (key: string) => { key: string }
mutationStarted: (key: string) => { key: string }
openCreateModal: () => void
@@ -121,6 +125,7 @@ export interface customerTasksLogicActions {
archiveTask: (taskId: string) => { taskId: string }
setAccountFilter: (account: CustomerTaskAccountFilter | null) => { account: CustomerTaskAccountFilter | null }
setAccountFilterOpen: (open: boolean) => { open: boolean }
+ setAssignee: (assignee: CustomerTaskAssigneeFilter) => { assignee: CustomerTaskAssigneeFilter }
setFilters: (filters: Partial<CustomerTaskFilters>) => { filters: Partial<CustomerTaskFilters> }
setFiltersFromUrl: (state: CustomerTaskUrlState) => { state: CustomerTaskUrlState }
setAccountFilterName: (name: string) => { name: string }
@@ -195,6 +200,7 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
openTaskFromUrl: (taskId: string) => ({ taskId }),
loadTaskPage: true,
loadAccountOptions: (payload: { query: string }) => payload,
+ setAssignee: (assignee: CustomerTaskAssigneeFilter) => ({ assignee }),
setFilters: (filters: Partial<CustomerTaskFilters>) => ({ filters }),
setFiltersFromUrl: (state: CustomerTaskUrlState) => ({ state }),
setAccountFilterName: (name: string) => ({ name }),
@@ -230,21 +236,27 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
if (values.currentTeamId === null) {
return null
}
- const result = await customerTasksList(
- String(values.currentTeamId),
- customerTasksQuery(
- values.filters,
- props.context,
- props.accountId,
- values.page,
- values.pageSize,
- values.timezone,
- props.canViewAll,
- values.ordering
+ try {
+ const result = await customerTasksList(
+ String(values.currentTeamId),
+ customerTasksQuery(
+ values.filters,
+ props.context,
+ props.accountId,
+ values.page,
+ values.pageSize,
+ values.timezone,
+ props.canViewAll,
+ values.ordering
+ )
)
- )
- breakpoint()
- return result
+ breakpoint()
+ return result
+ } catch (error) {
+ // A superseded request must not reach loadTaskPageFailure, which would act on newer filters.
+ breakpoint()
+ throw error
+ }
},
},
],
@@ -434,10 +446,22 @@ export const customerTasksLogic: LogicWrapper<customerTasksLogicType> = kea<cust
)
}
},
+ setAssignee: ({ assignee }) => {
+ posthog.capture(CustomerTaskEvents.AssigneeFilterChanged, { mode: customerTaskAssigneeMode(assignee) })
+ actions.setFilters({ assignee })
+ },
setFilters: () => {
props.onConfigChange?.(taskConfig(values))
actions.loadTaskPage()
},
+ loadTaskPageFailure: ({ errorObject }) => {
+ // A role deleted after someone saved or shared the filter makes every request fail,
+ // so fall back to the default view instead of an error that never clears.
+ const body = errorObject instanceof ApiError ? (errorObject.data as Record<string, unknown> | null) : null
+ if (body?.assigned_to && isRoleAssigneeFilter(values.filters.assignee)) {
+ actions.setFilters({ assignee: defaultCustomerTaskFilters(props.context).assignee })
+ }
+ },
setFiltersFromUrl: async () => {
actions.loadTaskPage()
const account = values.filters.account
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index e479ada3f571..67226a4be624 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -4989,7 +4989,7 @@ export type CustomerTasksListParams = {
*/
archive_state?: CustomerTasksListArchiveState
/**
- * Filter by me, unassigned, or one user ID.
+ * Filter by me, unassigned, one user ID, or role:<role UUID>. A role returns tasks assigned to any current member of that organization role.
* @minLength 1
*/
assigned_to?: string
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 2c3858720774..e13b5d3927ff 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -806,8 +806,9 @@ tools:
list: true
title: List customer tasks
description: >
- List accessible Customer analytics tasks. Filter by search, account UUID, assignee (me, unassigned, or user
- ID), comma-separated statuses, deadline, or archive state. Active tasks are returned by default.
+ List accessible Customer analytics tasks. Filter by search, account UUID, assignee (me, unassigned, a user
+ ID, or role:<role UUID> for tasks assigned to any current member of that role), comma-separated statuses,
+ deadline, or archive state. Active tasks are returned by default. Use roles-list to find role UUIDs.
feature_flag: customer-analytics-customer-tasks
customer-tasks-partial-update:
operation: customer_tasks_partial_update
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index e39dbd2b235a..eb60d9f3b122 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3289,7 +3289,7 @@
"feature_flag": "customer-analytics-customer-tasks"
},
"customer-tasks-list": {
- "description": "List accessible Customer analytics tasks. Filter by search, account UUID, assignee (me, unassigned, or user ID), comma-separated statuses, deadline, or archive state. Active tasks are returned by default.",
+ "description": "List accessible Customer analytics tasks. Filter by search, account UUID, assignee (me, unassigned, a user ID, or role:<role UUID> for tasks assigned to any current member of that role), comma-separated statuses, deadline, or archive state. Active tasks are returned by default. Use roles-list to find role UUIDs.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "List customer tasks",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 2de0bcf66716..591cf275dbd4 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -3304,7 +3304,7 @@
"feature_flag": "customer-analytics-customer-tasks"
},
"customer-tasks-list": {
- "description": "List accessible Customer analytics tasks. Filter by search, account UUID, assignee (me, unassigned, or user ID), comma-separated statuses, deadline, or archive state. Active tasks are returned by default.",
+ "description": "List accessible Customer analytics tasks. Filter by search, account UUID, assignee (me, unassigned, a user ID, or role:<role UUID> for tasks assigned to any current member of that role), comma-separated statuses, deadline, or archive state. Active tasks are returned by default. Use roles-list to find role UUIDs.",
"category": "Customer analytics",
"feature": "customer_analytics",
"summary": "List customer tasks",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ef3c8b5793a0..5ba80fd36800 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -116843,7 +116843,7 @@ export namespace Schemas {
*/
archive_state?: CustomerTasksListArchiveState;
/**
- * Filter by me, unassigned, or one user ID.
+ * Filter by me, unassigned, one user ID, or role:<role UUID>. A role returns tasks assigned to any current member of that organization role.
* @minLength 1
*/
assigned_to?: string;
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index d1d84895718f..e31e2666cc5f 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -971,7 +971,13 @@ export const CustomerTasksListQueryParams = () => zod.object({
.enum(['active', 'archived', 'all'])
.default(customerTasksListQueryArchiveStateDefault)
.describe('Which archive state to include.\n\n\* `active` - active\n\* `archived` - archived\n\* `all` - all'),
- assigned_to: zod.string().min(1).optional().describe('Filter by me, unassigned, or one user ID.'),
+ assigned_to: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ 'Filter by me, unassigned, one user ID, or role:<role UUID>. A role returns tasks assigned to any current member of that organization role.'
+ ),
due_after: zod.iso.datetime({ offset: true }).optional().describe('Inclusive lower deadline bound.'),
due_before: zod.iso.datetime({ offset: true }).optional().describe('Exclusive upper deadline bound.'),
has_due_at: zod.boolean().optional().describe('Filter tasks by whether a deadline exists.'),